@biconomy/abstractjs
Version:
SDK for Biconomy integration with support for account abstraction, smart accounts, ERC-4337.
351 lines • 15.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.userOp = exports.getQuote = exports.DEFAULT_VERIFICATION_GAS_LIMIT = exports.DEFAULT_GAS_LIMIT = exports.CLEANUP_USEROP_EXTENDED_EXEC_WINDOW_DURATION = exports.USEROP_MIN_EXEC_WINDOW_DURATION = void 0;
const viem_1 = require("viem");
const decorators_1 = require("../../../account/decorators/index.js");
const Utils_1 = require("../../../account/utils/Utils.js");
const getMultichainContract_1 = require("../../../account/utils/getMultichainContract.js");
const resolveInstructions_1 = require("../../../account/utils/resolveInstructions.js");
const constants_1 = require("../../../constants/index.js");
const composabilityCalls_1 = require("../../../modules/utils/composabilityCalls.js");
const createHttpClient_1 = require("../../createHttpClient.js");
const createMeeClient_1 = require("../../createMeeClient.js");
exports.USEROP_MIN_EXEC_WINDOW_DURATION = 180;
exports.CLEANUP_USEROP_EXTENDED_EXEC_WINDOW_DURATION = exports.USEROP_MIN_EXEC_WINDOW_DURATION / 2;
exports.DEFAULT_GAS_LIMIT = 75000n;
exports.DEFAULT_VERIFICATION_GAS_LIMIT = 150000n;
const getQuote = async (client, parameters) => {
const { account: account_ = client.account, instructions, cleanUps, feePayer, path = "quote", lowerBoundTimestamp: lowerBoundTimestamp_ = Math.floor(Date.now() / 1000), upperBoundTimestamp: upperBoundTimestamp_ = lowerBoundTimestamp_ +
exports.USEROP_MIN_EXEC_WINDOW_DURATION, delegate = false, authorization, moduleAddress, shortEncodingSuperTxn = false, sponsorship = false, sponsorshipOptions } = parameters;
const resolvedInstructions = await (0, resolveInstructions_1.resolveInstructions)(instructions);
let pathToQuery = path;
if (feePayer) {
pathToQuery = "/quote-permit";
}
const validUserOps = resolvedInstructions.every((userOp) => account_.deploymentOn(userOp.chainId) &&
client.info.supportedChains
.map(({ chainId }) => +chainId)
.includes(userOp.chainId));
if (!validUserOps) {
throw Error(`User operation chain(s) not supported by the node: ${resolvedInstructions
.map((x) => x.chainId)
.join(", ")}`);
}
const hasProcessedInitData = [];
const paymentVerificationGasLimit = resolvePaymentUserOpVerificationGasLimit({
moduleAddress,
sponsorship
});
const { paymentInfo, isInitDataProcessed } = await preparePaymentInfo(client, {
...parameters,
paymentVerificationGasLimit
});
if (isInitDataProcessed)
hasProcessedInitData.push(paymentInfo.chainId);
const preparedUserOps = await prepareUserOps(account_, resolvedInstructions, false, moduleAddress);
if (cleanUps && cleanUps.length > 0) {
const userOpsNonceInfo = preparedUserOps.map(([, { nonceKey, nonce }]) => ({ nonce, nonceKey }));
const cleanUpUserOps = await prepareCleanUpUserOps(account_, userOpsNonceInfo, cleanUps, moduleAddress);
preparedUserOps.push(...cleanUpUserOps);
}
const indexPerChainId = new Map();
const userOps = await Promise.all(preparedUserOps.map(async ([callData, { nonce }, isAccountDeployed, initCode, sender, callGasLimit, chainId, isCleanUpUserOp, nexusAccount, shortEncoding]) => {
let initDataOrUndefined = undefined;
if (!indexPerChainId.has(chainId)) {
indexPerChainId.set(chainId, 0);
}
const shouldContainInitData = !hasProcessedInitData.includes(chainId) && !isAccountDeployed;
if (shouldContainInitData) {
hasProcessedInitData.push(chainId);
initDataOrUndefined = delegate
? {
eip7702Auth: await nexusAccount.toDelegation({ authorization })
}
: { initCode };
}
const verificationGasLimit = resolveVerificationGasLimit({
moduleAddress,
sponsorship,
index: indexPerChainId.get(chainId),
paymentChainId: paymentInfo.chainId,
currentChainId: chainId
});
indexPerChainId.set(chainId, indexPerChainId.get(chainId) + 1);
return {
lowerBoundTimestamp: lowerBoundTimestamp_,
upperBoundTimestamp: isCleanUpUserOp
? upperBoundTimestamp_ +
exports.CLEANUP_USEROP_EXTENDED_EXEC_WINDOW_DURATION
: upperBoundTimestamp_,
sender,
callData,
callGasLimit,
nonce: nonce.toString(),
chainId,
isCleanUpUserOp,
...initDataOrUndefined,
...verificationGasLimit,
shortEncoding: shortEncodingSuperTxn || shortEncoding
};
}));
const quoteRequest = { userOps, paymentInfo };
let quote = await client.request({
path: pathToQuery,
body: quoteRequest
});
if (sponsorship && sponsorshipOptions) {
const isSelfHostedSponsorship = ![
createMeeClient_1.DEFAULT_PATHFINDER_URL,
createMeeClient_1.DEFAULT_STAGING_PATHFINDER_URL
].includes(sponsorshipOptions.url);
if (isSelfHostedSponsorship) {
const selfHostedClient = (0, createHttpClient_1.default)(sponsorshipOptions.url);
quote = await selfHostedClient.request({
path: `sponsorship/sign/${sponsorshipOptions.gasTank.chainId}/${sponsorshipOptions.gasTank.address}`,
method: "POST",
body: quote,
...(sponsorshipOptions.customHeaders
? { headers: sponsorshipOptions.customHeaders }
: {})
});
}
}
return quote;
};
exports.getQuote = getQuote;
const preparePaymentInfo = async (client, parameters) => {
const { account: account_ = client.account, eoa, feeToken, feePayer, delegate = false, gasLimit, verificationGasLimit, authorization, sponsorship, sponsorshipOptions, shortEncodingSuperTxn, moduleAddress = viem_1.zeroAddress, paymentVerificationGasLimit } = parameters;
let paymentInfo = undefined;
let isInitDataProcessed = false;
const eoaOrFeePayer = feePayer || eoa;
if (sponsorship) {
let sender = createMeeClient_1.DEFAULT_MEE_SPONSORSHIP_PAYMASTER_ACCOUNT;
let token = createMeeClient_1.DEFAULT_MEE_SPONSORSHIP_TOKEN_ADDRESS;
let chainId = createMeeClient_1.DEFAULT_MEE_SPONSORSHIP_CHAIN_ID;
let sponsorshipUrl = createMeeClient_1.DEFAULT_PATHFINDER_URL;
if (sponsorshipOptions) {
sender = sponsorshipOptions.gasTank.address;
token = sponsorshipOptions.gasTank.token;
chainId = sponsorshipOptions.gasTank.chainId;
sponsorshipUrl = sponsorshipOptions.url;
}
const sponsorshipClient = (0, createHttpClient_1.default)(sponsorshipUrl);
const { nonce } = await sponsorshipClient.request({
path: `sponsorship/nonce/${chainId}/${sender}`,
method: "GET",
...(sponsorshipOptions?.customHeaders
? { headers: sponsorshipOptions.customHeaders }
: {})
});
paymentInfo = {
sponsored: true,
sender,
token,
nonce,
callGasLimit: gasLimit || exports.DEFAULT_GAS_LIMIT,
verificationGasLimit: verificationGasLimit || exports.DEFAULT_VERIFICATION_GAS_LIMIT,
chainId: chainId.toString(),
sponsorshipUrl,
...(eoaOrFeePayer ? { eoa: eoaOrFeePayer } : {}),
initCode: undefined
};
isInitDataProcessed = false;
}
else {
if (!feeToken)
throw Error("Fee token should be configured");
const validPaymentAccount = account_.deploymentOn(feeToken.chainId);
if (!validPaymentAccount) {
throw Error(`Account is not deployed on necessary chain(s) ${feeToken.chainId}`);
}
const validFeeToken = validPaymentAccount &&
client.info.supportedGasTokens
.map(({ chainId }) => +chainId)
.includes(feeToken.chainId);
if (!validFeeToken) {
throw Error(`Fee token ${feeToken.address} is not supported on this chain: ${feeToken.chainId}`);
}
const [nonce, isAccountDeployed, initCode] = await Promise.all([
validPaymentAccount.getNonceWithKey(validPaymentAccount.address, {
moduleAddress
}),
validPaymentAccount.isDeployed(),
validPaymentAccount.getInitCode()
]);
const initData = isAccountDeployed
? undefined
: delegate
? {
eip7702Auth: await validPaymentAccount.toDelegation({
authorization
})
}
: { initCode };
paymentInfo = {
sponsored: false,
sender: validPaymentAccount.address,
token: feeToken.address,
nonce: nonce.nonce.toString(),
callGasLimit: gasLimit || exports.DEFAULT_GAS_LIMIT,
verificationGasLimit: verificationGasLimit || exports.DEFAULT_VERIFICATION_GAS_LIMIT,
chainId: feeToken.chainId.toString(),
...(eoaOrFeePayer ? { eoa: eoaOrFeePayer } : {}),
...initData,
shortEncoding: shortEncodingSuperTxn,
...paymentVerificationGasLimit
};
isInitDataProcessed = true;
}
if (!paymentInfo)
throw new Error("Failed to generate payment info");
return { paymentInfo, isInitDataProcessed };
};
const prepareUserOps = async (account, instructions, isCleanUpUserOps = false, moduleAddress) => {
return await Promise.all(instructions.map((userOp) => {
const deployment = account.deploymentOn(userOp.chainId, true);
const accountAddress = account.addressOn(userOp.chainId, true);
let callsPromise;
if (userOp.isComposable) {
callsPromise = deployment.encodeExecuteComposable(userOp.calls);
}
else {
callsPromise =
userOp.calls.length > 1
? deployment.encodeExecuteBatch(userOp.calls)
: deployment.encodeExecute(userOp.calls[0]);
}
const shortEncoding = false;
return Promise.all([
callsPromise,
deployment.getNonceWithKey(accountAddress, { moduleAddress }),
deployment.isDeployed(),
deployment.getInitCode(),
deployment.address,
userOp.calls
.map((uo) => uo?.gasLimit ?? getMultichainContract_1.LARGE_DEFAULT_GAS_LIMIT)
.reduce((curr, acc) => curr + acc, 0n)
.toString(),
userOp.chainId.toString(),
isCleanUpUserOps,
deployment,
shortEncoding
]);
}));
};
const userOp = (userOpIndex) => {
if (userOpIndex <= 0)
throw new Error("UserOp index should be greater than zero");
return userOpIndex - 1;
};
exports.userOp = userOp;
const prepareCleanUpUserOps = async (account, userOpsNonceInfo, cleanUps, moduleAddress) => {
const cleanUpInstructions = await Promise.all(cleanUps.map(async (cleanUp) => {
let amount = cleanUp.amount ?? 0n;
if (amount === 0n) {
amount = (0, composabilityCalls_1.runtimeERC20BalanceOf)({
targetAddress: account.addressOn(cleanUp.chainId, true),
tokenAddress: cleanUp.tokenAddress,
constraints: [(0, composabilityCalls_1.greaterThanOrEqualTo)(1n)]
});
}
const [cleanUpTransferInstruction] = await (0, decorators_1.buildComposable)({ account: account, currentInstructions: [] }, {
type: "transfer",
data: {
recipient: cleanUp.recipientAddress,
tokenAddress: cleanUp.tokenAddress,
amount,
chainId: cleanUp.chainId,
...(cleanUp.gasLimit ? { gasLimit: cleanUp.gasLimit } : {})
}
});
const nonceDependencies = [];
if (cleanUp.dependsOn && cleanUp.dependsOn.length > 0) {
for (const userOpIndex of cleanUp.dependsOn) {
const userOpNonceInfo = userOpsNonceInfo[userOpIndex];
if (!userOpNonceInfo)
throw new Error("Invalid UserOp dependency, please check the dependsOn configuration");
const { nonce, nonceKey } = userOpNonceInfo;
const nonceOf = (0, composabilityCalls_1.runtimeNonceOf)({
smartAccountAddress: account.addressOn(cleanUp.chainId, true),
nonceKey: nonceKey,
constraints: [(0, composabilityCalls_1.greaterThanOrEqualTo)(nonce + 1n)]
});
nonceDependencies.push(nonceOf);
}
}
else {
const lastUserOp = userOpsNonceInfo[userOpsNonceInfo.length - 1];
const { nonce, nonceKey } = lastUserOp;
const nonceOf = (0, composabilityCalls_1.runtimeNonceOf)({
smartAccountAddress: account.addressOn(cleanUp.chainId, true),
nonceKey: nonceKey,
constraints: [(0, composabilityCalls_1.greaterThanOrEqualTo)(nonce + 1n)]
});
nonceDependencies.push(nonceOf);
}
const nonceDependencyInputParams = nonceDependencies.flatMap((dep) => dep.inputParams);
cleanUpTransferInstruction.calls = cleanUpTransferInstruction.calls.map((call) => {
call.inputParams.push(...nonceDependencyInputParams);
return call;
});
return cleanUpTransferInstruction;
}));
const cleanUpUserOps = await prepareUserOps(account, cleanUpInstructions, true, moduleAddress);
return cleanUpUserOps;
};
const resolveVerificationGasLimit = (parameters) => {
const { moduleAddress, sponsorship, index, paymentChainId, currentChainId } = parameters;
if (currentChainId === paymentChainId) {
return resolveVerificationGasLimitForPaymentChain({
moduleAddress,
sponsorship,
index
});
}
return resolveVerificationGasLimitForNonPaymentChain({
moduleAddress,
index
});
};
const resolveVerificationGasLimitForPaymentChain = (parameters) => {
const { moduleAddress, sponsorship, index } = parameters;
if (!moduleAddress) {
return undefined;
}
if ((0, Utils_1.addressEquals)(moduleAddress, constants_1.SMART_SESSIONS_ADDRESS)) {
if (sponsorship) {
if (index === 0) {
return { verificationGasLimit: 1000000n };
}
}
return { verificationGasLimit: 250000n };
}
return undefined;
};
const resolveVerificationGasLimitForNonPaymentChain = (parameters) => {
const { moduleAddress, index } = parameters;
if (!moduleAddress) {
return undefined;
}
if ((0, Utils_1.addressEquals)(moduleAddress, constants_1.SMART_SESSIONS_ADDRESS)) {
if (index === 0) {
return { verificationGasLimit: 1000000n };
}
return { verificationGasLimit: 250000n };
}
return undefined;
};
const resolvePaymentUserOpVerificationGasLimit = (parameters) => {
const { moduleAddress, sponsorship } = parameters;
if (!moduleAddress) {
return undefined;
}
if ((0, Utils_1.addressEquals)(moduleAddress, constants_1.SMART_SESSIONS_ADDRESS)) {
if (!sponsorship) {
return { verificationGasLimit: 1000000n };
}
}
return undefined;
};
exports.default = exports.getQuote;
//# sourceMappingURL=getQuote.js.map