@biconomy/abstractjs
Version:
SDK for Biconomy integration with support for account abstraction, smart accounts, ERC-4337.
439 lines • 17.7 kB
JavaScript
import { concatHex, createPublicClient, domainSeparator, encodeAbiParameters, encodeFunctionData, encodePacked, keccak256, parseAbi, parseAbiParameters, toBytes, toHex, validateTypedData, zeroAddress } from "viem";
import { entryPoint07Address, getUserOperationHash, toSmartAccount } from "viem/account-abstraction";
import { ENTRY_POINT_ADDRESS, NEXUS_ACCOUNT_FACTORY_ADDRESS, NEXUS_BOOTSTRAP_ADDRESS, NEXUS_IMPLEMENTATION_ADDRESS } from "../constants/index.js";
// Constants
import { EntrypointAbi } from "../constants/abi/index.js";
import { COMPOSABILITY_MODULE_ABI } from "../constants/abi/index.js";
import { toEmptyHook } from "../modules/toEmptyHook.js";
import { toDefaultModule } from "../modules/validators/default/toDefaultModule.js";
import { toLegacyK1Module } from "../modules/validators/legacyK1/toLegacyK1Module.js";
import { getFactoryData, getInitData, getK1FactoryData } from "./decorators/getFactoryData.js";
import { getK1NexusAddress, getNexusAddress } from "./decorators/getNexusAddress.js";
import { getDefaultNonceKey, getNonceWithKeyUtil } from "./decorators/getNonceWithKey.js";
import { EXECUTE_BATCH, EXECUTE_SINGLE, PARENT_TYPEHASH } from "./utils/Constants.js";
import { addressEquals, eip712WrapHash, getAccountDomainStructFields, getTypesForEIP712Domain, isNullOrUndefined, typeToString } from "./utils/Utils.js";
import { getConfigFromNexusVersion, isVersionOlder } from "./utils/getVersion.js";
import { toInitData } from "./utils/toInitData.js";
import { toSigner } from "./utils/toSigner.js";
import { toWalletClient } from "./utils/toWalletClient.js";
/**
* @description Create a Nexus Smart Account.
*
* @param parameters - {@link ToNexusSmartAccountParameters}
* @returns Nexus Smart Account. {@link NexusAccount}
*
* @example
* import { toNexusAccount } from '@biconomy/abstractjs'
* import { createWalletClient, http } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const account = await toNexusAccount({
* chain: mainnet,
* transport: http(),
* signer: '0x...',
* })
*/
export const toNexusAccount = async (parameters) => {
const { chain, transport: transportConfig, signer: _signer, index = 0n, validators: customValidators, executors: customExecutors, hook: customHook, fallbacks: customFallbacks, prevalidationHooks: customPrevalidationHooks, accountAddress: accountAddress_, nexusVersion, attesterThreshold = 1, useK1Config = false } = parameters;
let { initData,
// those params are 1.2.0 by default
factoryAddress = NEXUS_ACCOUNT_FACTORY_ADDRESS, bootStrapAddress = NEXUS_BOOTSTRAP_ADDRESS, implementationAddress = NEXUS_IMPLEMENTATION_ADDRESS,
// those params are undefined by default and are defined only if explicitly provided
// or if nexus version is provided
registryAddress, attesters, k1ValidatorAddress, k1FactoryAddress } = parameters;
// if nexus version earlier than 1.2.0 is provided, use the config from the constants
if (nexusVersion && isVersionOlder(nexusVersion, "1.2.0")) {
;
({
factoryAddress,
bootStrapAddress,
implementationAddress,
registryAddress,
attesters,
k1ValidatorAddress,
k1FactoryAddress
} = getConfigFromNexusVersion(nexusVersion));
if (useK1Config) {
factoryAddress = k1FactoryAddress;
}
}
const signer = await toSigner({ signer: _signer });
const walletClient = toWalletClient({
unresolvedSigner: _signer,
resolvedSigner: signer,
chain,
transport: transportConfig
});
const publicClient = createPublicClient({ chain, transport: transportConfig });
// Prepare default validator module
const defaultValidator = toDefaultModule({ signer });
// Prepare validator modules
const validators = customValidators || [];
let k1Validator = undefined;
if (useK1Config && k1ValidatorAddress) {
k1Validator = toLegacyK1Module({
signer,
module: k1ValidatorAddress
});
}
// The default validator should be the defaultValidator unless custom validators have been set or k1Validator is set
let module = k1Validator || customValidators?.[0] || defaultValidator;
// Prepare executor modules
const executors = customExecutors || [];
// Prepare hook module
const hook = customHook || toEmptyHook();
// Prepare fallback modules
const fallbacks = customFallbacks || [];
// Generate the initialization data for the account using the initNexus function
const prevalidationHooks = customPrevalidationHooks || [];
let factoryData = "0x";
if (useK1Config) {
factoryData = getK1FactoryData({
signerAddress: signer.address,
index,
attesters: attesters,
attesterThreshold
});
}
else {
if (!initData) {
initData = getInitData({
defaultValidator: toInitData(defaultValidator),
prevalidationHooks,
validators: validators.map(toInitData),
executors: executors.map(toInitData),
hook: toInitData(hook),
fallbacks: fallbacks.map(toInitData),
bootStrapAddress,
registryAddress,
attesters,
attesterThreshold,
nexusVersion
});
factoryData = getFactoryData({ initData, index });
}
}
/**
* @description Gets the init code for the account
* @returns The init code as a hexadecimal string
*/
const getInitCode = () => concatHex([useK1Config ? k1FactoryAddress : factoryAddress, factoryData]);
let _accountAddress = accountAddress_;
const accountId = (await publicClient.readContract({
address: implementationAddress,
abi: parseAbi(["function accountId() public view returns (string)"]),
functionName: "accountId",
args: []
}));
/**
* @description Gets the counterfactual address of the account
* @returns The counterfactual address
* @throws {Error} If unable to get the counterfactual address
*/
const getAddress = async () => {
if (!isNullOrUndefined(_accountAddress))
return _accountAddress;
const addressFromFactory = useK1Config
? await getK1NexusAddress({
k1FactoryAddress: k1FactoryAddress,
index,
ownerAddress: signer.address,
attesters: attesters,
attesterThreshold,
publicClient
})
: await getNexusAddress({
factoryAddress,
index,
initData: initData,
publicClient
});
if (!addressEquals(addressFromFactory, zeroAddress)) {
_accountAddress = addressFromFactory;
return addressFromFactory;
}
throw new Error("Failed to get account address");
};
/**
* @description Calculates the hash of a user operation
* @param userOp - The user operation
* @returns The hash of the user operation
*/
const getUserOpHash = (userOp) => getUserOperationHash({
chainId: chain.id,
entryPointAddress: entryPoint07Address,
entryPointVersion: "0.7",
userOperation: userOp
});
/**
* @description Encodes a batch of calls for execution
* @param calls - An array of calls to encode
* @param mode - The execution mode
* @returns The encoded calls
*/
const encodeExecuteBatch = async (calls, mode = EXECUTE_BATCH) => {
const executionAbiParams = {
type: "tuple[]",
components: [
{ name: "target", type: "address" },
{ name: "value", type: "uint256" },
{ name: "callData", type: "bytes" }
]
};
const executions = calls.map((tx) => ({
target: tx.to,
callData: tx.data ?? "0x",
value: BigInt(tx.value ?? 0n)
}));
const executionCalldataPrep = encodeAbiParameters([executionAbiParams], [executions]);
return encodeFunctionData({
abi: parseAbi([
"function execute(bytes32 mode, bytes calldata executionCalldata) external"
]),
functionName: "execute",
args: [mode, executionCalldataPrep]
});
};
/**
* @description Encodes a single call for execution
* @param call - The call to encode
* @param mode - The execution mode
* @returns The encoded call
*/
const encodeExecute = async (call, mode = EXECUTE_SINGLE) => {
const executionCalldata = encodePacked(["address", "uint256", "bytes"], [call.to, BigInt(call.value ?? 0n), (call.data ?? "0x")]);
return encodeFunctionData({
abi: parseAbi([
"function execute(bytes32 mode, bytes calldata executionCalldata) external"
]),
functionName: "execute",
args: [mode, executionCalldata]
});
};
/**
* @description Encodes a composable calls for execution
* @param call - The calls to encode
* @returns The encoded composable compatible call
*/
const encodeExecuteComposable = async (calls) => {
const composableCalls = calls.map((call) => {
return {
to: call.to,
value: call.value ?? 0n,
functionSig: call.functionSig,
inputParams: call.inputParams,
outputParams: call.outputParams
};
});
return encodeFunctionData({
abi: COMPOSABILITY_MODULE_ABI,
functionName: "executeComposable", // Function selector in Composability feature which executes the composable calls.
args: [composableCalls] // Multiple composable calls can be batched here.
});
};
/**
* @description Gets the nonce for the account along with modified key
* @param parameters - Optional parameters for getting the nonce
* @returns The nonce and the key
*/
const getNonceWithKey = async (accountAddress, parameters) => {
const defaultNonceKey = await getDefaultNonceKey(accountAddress, chain.id);
const { key = defaultNonceKey, validationMode = "0x00", moduleAddress = module.module } = parameters ?? {};
return getNonceWithKeyUtil(publicClient, accountAddress, {
key,
validationMode,
moduleAddress
});
};
/**
* @description Gets the nonce for the account
* @param parameters - Optional parameters for getting the nonce
* @returns The nonce
*/
const getNonce = async (parameters) => {
const accountAddress = await getAddress();
const { nonce } = await getNonceWithKey(accountAddress, parameters);
return nonce;
};
/**
* @description Signs typed data
* @param parameters - The typed data parameters
* @returns The signature
*/
async function signTypedData(parameters) {
const { message, primaryType, types: _types, domain } = parameters;
if (!domain)
throw new Error("Missing domain");
if (!message)
throw new Error("Missing message");
const types = {
EIP712Domain: getTypesForEIP712Domain({ domain }),
..._types
};
// @ts-ignore: Comes from nexus parent typehash
const messageStuff = message.stuff;
// @ts-ignore
validateTypedData({
domain,
message,
primaryType,
types
});
const appDomainSeparator = domainSeparator({ domain });
const accountDomainStructFields = await getAccountDomainStructFields(publicClient, await getAddress());
const parentStructHash = keccak256(encodePacked(["bytes", "bytes"], [
encodeAbiParameters(parseAbiParameters(["bytes32, bytes32"]), [
keccak256(toBytes(PARENT_TYPEHASH)),
messageStuff
]),
accountDomainStructFields
]));
const wrappedTypedHash = eip712WrapHash(parentStructHash, appDomainSeparator);
let signature = await module.signMessage({ raw: toBytes(wrappedTypedHash) });
const contentsType = toBytes(typeToString(types)[1]);
const signatureData = concatHex([
signature,
appDomainSeparator,
messageStuff,
toHex(contentsType),
toHex(contentsType.length, { size: 2 })
]);
signature = encodePacked(["address", "bytes"], [module.module, signatureData]);
return signature;
}
/**
* @description Changes the active module for the account
* @param module - The new module to set as active
* @returns void
*/
const setModule = (validationModule) => {
module = validationModule;
};
/**
* @description Get authorization data for the EOA to Nexus Account
* @param forMee - Whether to return the authorization data formatted for MEE. Defaults to false.
* @param delegatedContract - The contract address to delegate the authorization to. Defaults to the implementation address.
*
* @example
* const eip7702Auth = await nexusAccount.toDelegation() // Returns MeeAuthorization
*/
async function toDelegation(params) {
const { authorization: authorization_, multiChain, delegatedContract } = params || {};
const contractAddress = delegatedContract || implementationAddress;
const authorization = authorization_ ||
(await walletClient.signAuthorization({
contractAddress
}));
const eip7702Auth = {
chainId: `0x${(multiChain ? 0 : chain.id).toString(16)}`,
address: authorization.address,
nonce: `0x${authorization.nonce.toString(16)}`,
r: authorization.r,
s: authorization.s,
v: `0x${authorization.v.toString(16)}`,
yParity: `0x${authorization.yParity.toString(16)}`
};
return eip7702Auth;
}
async function isDelegated() {
const code = await publicClient.getCode({ address: signer.address });
return (!!code &&
code
?.toLowerCase()
.includes(NEXUS_IMPLEMENTATION_ADDRESS.substring(2).toLowerCase()));
}
/**
* @description Get authorization data to unauthorize the account
* @returns Hex of the transaction hash
*
* @example
* const eip7702Auth = await nexusAccount.unDelegate()
*/
async function unDelegate(params) {
const { authorization } = params || {};
const deAuthorization = authorization ||
(await walletClient.signAuthorization({
address: zeroAddress,
executor: "self"
}));
return await walletClient.sendTransaction({
to: signer.address,
data: "0xdeadbeef",
type: "eip7702",
authorizationList: [deAuthorization]
});
}
// ================================================
// Return the Nexus Account
// ================================================
return toSmartAccount({
client: publicClient,
entryPoint: {
abi: EntrypointAbi,
address: ENTRY_POINT_ADDRESS,
version: "0.7"
},
getAddress,
encodeCalls: (calls) => {
return calls.length === 1
? encodeExecute(calls[0])
: encodeExecuteBatch(calls);
},
getFactoryArgs: async () => ({
factory: factoryAddress,
factoryData
}),
getStubSignature: async () => module.getStubSignature(),
/**
* @description Signs a message
* @param params - The parameters for signing
* @param params.message - The message to sign
* @returns The signature
*/
async signMessage({ message }) {
const tempSignature = await module.signMessage(message);
return encodePacked(["address", "bytes"], [module.module, tempSignature]);
},
signTypedData,
signUserOperation: async (parameters) => {
const { chainId = publicClient.chain.id, ...userOpWithoutSender } = parameters;
const address = await getAddress();
const userOperation = {
...userOpWithoutSender,
sender: address
};
const hash = getUserOperationHash({
chainId,
entryPointAddress: entryPoint07Address,
entryPointVersion: "0.7",
userOperation
});
return await module.signUserOpHash(hash);
},
getNonce,
extend: {
isDelegated,
toDelegation,
unDelegate,
entryPointAddress: entryPoint07Address,
getAddress,
accountId,
getInitCode,
getNonceWithKey,
encodeExecute,
encodeExecuteBatch,
encodeExecuteComposable,
getUserOpHash,
factoryData,
factoryAddress,
registryAddress,
signer,
walletClient,
publicClient,
chain,
setModule,
getModule: () => module
}
});
};
//# sourceMappingURL=toNexusAccount.js.map