@nevermined-io/core-kit 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"sourcesContent":["import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator'\nimport {\n deserializePermissionAccount,\n serializePermissionAccount,\n toPermissionValidator,\n} from '@zerodev/permissions'\nimport { toECDSASigner } from '@zerodev/permissions/signers'\nimport {\n addressToEmptyAccount,\n createKernelAccount,\n createKernelAccountClient,\n createZeroDevPaymasterClient,\n getUserOperationGasPrice,\n KernelAccountClient,\n type KernelSmartAccountImplementation,\n} from '@zerodev/sdk'\nimport { KERNEL_V3_1, getEntryPoint } from '@zerodev/sdk/constants'\nimport {\n Address,\n encodeAbiParameters,\n getAbiItem,\n getAddress,\n getContract,\n http,\n isAddress,\n pad,\n stringToBytes,\n stringToHex,\n toBytes,\n keccak256 as viemKeccak256,\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type Account,\n type PublicClient,\n type TransactionReceipt,\n} from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport {\n english,\n generateMnemonic,\n generatePrivateKey,\n mnemonicToAccount,\n privateKeyToAccount,\n} from 'viem/accounts'\nimport { Instantiable, InstantiableConfig, Web3Clients } from '../../Instantiable.abstract.js'\nimport { ContractsError } from '../../errors/NeverminedErrors.js'\nimport { getChain } from '../../utils/Network.js'\nimport { Signer } from '@zerodev/sdk/types'\n\nconst ENTRY_POINT_VERSION = '0.7'\n\n/**\n * Utility class with methods that allow the interaction with the blockchain.\n * This class uses Viem library to interact with the blockchain.\n */\nexport class BlockchainViemUtils extends Instantiable {\n constructor(config: InstantiableConfig) {\n super()\n this.setInstanceConfig(config)\n }\n}\n\n//////////////////////////\n///// UTILITIES //////////\n//////////////////////////\n\n///// CONTRACTS\n\n// Wait budget for an L2 block to be mined and the receipt to surface.\n// Base / Base Sepolia block time is ~2s; 30s ≈ 15 blocks of headroom.\nconst TRANSACTION_RECEIPT_TIMEOUT_MS = 30_000\nconst TRANSACTION_RECEIPT_POLLING_INTERVAL_MS = 1_500\n\n/**\n * Given a transaction hash, it returns the transaction receipt.\n * Uses viem's `waitForTransactionReceipt` which polls until the receipt is\n * available, retrying on `TransactionReceiptNotFoundError` and handling\n * tx-replacement / reorgs natively.\n * @param txHash - the transaction hash\n * @returns the transaction receipt\n */\nexport async function getTransactionReceipt({\n txHash,\n publicClient,\n}: {\n txHash: `0x${string}`\n publicClient: PublicClient\n iteration?: number\n}): Promise<TransactionReceipt> {\n try {\n return await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: TRANSACTION_RECEIPT_TIMEOUT_MS,\n pollingInterval: TRANSACTION_RECEIPT_POLLING_INTERVAL_MS,\n confirmations: 1,\n })\n } catch (error) {\n throw new ContractsError(\n `Unable to get transaction receipt with hash: ${txHash}. Error: ${error}`,\n )\n }\n}\n\n/**\n * Given an already deployed contract address and the ABI, it returns the contract instance.\n *\n * @param contractAddress - the contract address\n * @param abi - the contract artifact\n * @param client - the client to interact with the blockchain\n * @returns a contract instance\n */\nexport async function getContractInstance(contractAddress: string, abi: Abi, client: Web3Clients) {\n return getContract({\n abi,\n address: contractAddress as `0x${string}`,\n client: { wallet: client.wallet, public: client.public },\n })\n}\n\n///// ABIs\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function searchAbiFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n const func = getAbiItem({ abi, name: funcName, args })\n if (!func || func.type !== 'function') {\n throw new ContractsError(`Function \"${funcName}\" is not part of contract`)\n }\n return func as AbiFunction\n}\n\n/**\n * It searchs an ABI event in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the event name\n * @returns the event found\n */\nexport function searchAbiEvent(abi: Abi, eventName: string): AbiEvent {\n const event = getAbiItem({\n abi,\n name: eventName,\n })\n if (!event || event.type !== 'event') {\n throw new ContractsError(`Event \"${event}\" is not part of contract`)\n }\n return event as AbiEvent\n}\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getSignatureOfFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n return searchAbiFunction(abi, funcName, args)\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunction(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs formatted.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunctionFormatted(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs.map((input, i) => {\n return {\n name: input.name,\n value: args[i],\n }\n })\n}\n\n//////// UTILS\n\n/**\n * Given an address it returns that address in checksum format.\n * @param address the address\n * @returns the same address in checksum format\n */\nexport function getChecksumAddress(address: string): string {\n return getAddress(address)\n}\n\n/**\n * It checks if the address is a valid address.\n * @param address the address to check\n * @returns true of the address is valid\n */\nexport function isValidAddress(address: string): boolean {\n return isAddress(address)\n}\n\n/**\n * Encodes a UTF-8 string into a byte array.\n\n * @param message the string to encode\n * @returns the encoded byte array\n */\nexport function getBytes(message: string): Uint8Array {\n return stringToBytes(message)\n}\n\n/**\n * It pads a value with zeros.\n * @param value the value to pad\n * @param length the expected longitutde of the value\n * @returns the padded value\n */\nexport function zeroPadValue(value: `0x${string}` | Uint8Array, length: number): string {\n return pad(value, { size: length }) as `0x${string}`\n}\n\n/**\n * Encodes a UTF-8 string into a hex string\n * @param message the string to encode\n * @returns the hex string\n */\nexport function encodeBytes32String(message: string) {\n return stringToHex(message, { size: 32 })\n}\n\n////// ACCOUNTS\n/**\n * Given a seedphrase, it returns an account.\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param addressIndex - the address index\n * @returns an account\n */\nexport function makeWallet(seedphrase: string, addressIndex = 0): Account {\n return mnemonicToAccount(seedphrase, { addressIndex })\n}\n\n/**\n * Given a seedphrase generates multiple accounts\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeWallets(seedphrase: string, numAccounts = 10) {\n const accounts: Account[] = []\n for (let i = 0; i < numAccounts; i++) {\n accounts.push(makeWallet(seedphrase, i))\n }\n return accounts\n}\n\n/**\n * It generates a random account.\n * @returns a new account\n */\nexport function makeRandomWallet(): Account {\n const mnemonic = generateMnemonic(english)\n return makeWallet(mnemonic)\n}\n\n/**\n * It generates a list of random accounts\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeRandomWallets(numAccounts = 10): Account[] {\n const mnemonic = generateMnemonic(english)\n return makeWallets(mnemonic, numAccounts)\n}\n\n/////// HASHES\n\n/**\n * It hashes a string using keccak256.\n * @param seed the string to hash\n * @returns the hash\n */\nexport function keccak256(seed: string): string {\n return viemKeccak256(toBytes(seed))\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256WithEncode(types: any[], values: any[]): string {\n const encoded = encodeAbiParameters(types, values as never)\n return keccak256(encoded)\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256Packed(types: any[], values: any[]): string {\n return keccak256WithEncode(types, values)\n}\n\n/////// ZERO DEV\n\n/**\n * Returns the bundler RPC URL. When `BUNDLER_RPC_URL_OVERRIDE` is set\n * (used by tests against a local Alto + anvil-fork stack), it takes precedence\n * over the canonical ZeroDev URL. When `useUltraRelay` is true, the production\n * URL is routed through ZeroDev's UltraRelay (`?provider=ULTRA_RELAY`); the\n * override branch is left untouched.\n * @param useUltraRelay - when true, append `?provider=ULTRA_RELAY` to route the\n * UserOperation through ZeroDev's UltraRelay bundler tier. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\nexport function getBundlerRpcUrl(\n zeroDevProjectId: string,\n chainId: number,\n useUltraRelay = false,\n): string {\n const base = `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n // `||` (not `??`) because Vite replaces missing browser env vars with the\n // empty string at build time; an empty override is equivalent to \"no\n // override\" for our purposes.\n return (\n process.env.BUNDLER_RPC_URL_OVERRIDE || (useUltraRelay ? `${base}?provider=ULTRA_RELAY` : base)\n )\n}\n\n/**\n * Returns the paymaster RPC URL (ZeroDev-only; the local fork stack uses\n * `ultra-relay` which sponsors via the bundler's executor key without a\n * paymaster, so this URL is not consulted when `BUNDLER_RPC_URL_OVERRIDE` is\n * set).\n */\nexport function getPaymasterRpcUrl(zeroDevProjectId: string, chainId: number): string {\n return `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n}\n\n/**\n * Returns true when the kernel client should run in \"relayer mode\" — no\n * paymaster, gas fees zeroed out. Used by tests against a local\n * `ultra-relay` (ZeroDev's fork of Alto) on top of an anvil-fork. The relayer's\n * executor key pays gas directly via `EntryPoint.handleOps`, avoiding the\n * paymaster sponsorship handshake altogether.\n */\nexport function isRelayerMode(): boolean {\n return Boolean(process.env.BUNDLER_RPC_URL_OVERRIDE)\n}\n\n/**\n * Returns gas prices for UserOperation fee estimation. ZeroDev's bundler\n * exposes a custom `zd_getUserOperationGasPrice` method; standard ERC-4337\n * bundlers do not. In relayer mode the bundler accepts UserOps with zeroed\n * `maxFeePerGas`/`maxPriorityFeePerGas` and pays gas itself.\n */\nexport async function estimateUserOperationFees(\n bundlerClient: any,\n _publicClient: any,\n): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }> {\n if (isRelayerMode()) {\n return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n }\n }\n return getUserOperationGasPrice(bundlerClient)\n}\n\n/**\n * It creates a ZeroDev Kernel client.\n * @param signer the signer account\n * @param chainId the chain id\n * @param zeroDevProjectId the zero dev project id, you can get it from the ZeroDev dashboard\n * @param useUltraRelay forwarded straight to `getBundlerRpcUrl` — when true the\n * bundler RPC is routed through ZeroDev's UltraRelay. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n * @returns the kernel client\n */\nexport async function createKernelClient(\n kernelAccount: SmartAccount,\n chainId: number,\n zeroDevProjectId: string,\n publicClient: any,\n useUltraRelay = false,\n): Promise<KernelAccountClient> {\n const bundlerRpc = getBundlerRpcUrl(zeroDevProjectId, chainId, useUltraRelay)\n const paymasterRpc = getPaymasterRpcUrl(zeroDevProjectId, chainId)\n\n return createKernelAccountClient({\n account: kernelAccount,\n chain: getChain(chainId),\n bundlerTransport: http(bundlerRpc),\n client: publicClient,\n ...(isRelayerMode()\n ? {}\n : {\n paymaster: {\n getPaymasterData: (userOperation: any) => {\n const zerodevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(chainId),\n transport: http(paymasterRpc),\n })\n return zerodevPaymaster.sponsorUserOperation({ userOperation })\n },\n },\n }),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, publicClient)\n },\n },\n })\n}\n\nexport type EcdsaValidator = Awaited<ReturnType<typeof signerToEcdsaValidator>>\n\n/**\n * Identifies the smart-account derivation inputs (entryPoint + kernel version).\n * The SCA is deterministic from `(EOA, entryPoint, kernelVersion, index)`, so a\n * bump here means the same EOA derives a different SCA. Persisted SCA caches\n * (e.g. the webapp's localStorage) should stamp this and invalidate on change.\n */\nexport const SCA_DERIVATION_VERSION = `${ENTRY_POINT_VERSION}:${KERNEL_V3_1}`\n\n/**\n * Build the ECDSA sudo validator for a signer. Both `createKernelSmartAccount`\n * and `createSessionKey` need this validator and each derives it via a ZeroDev\n * RPC round-trip. Callers that run both in sequence (e.g. the webapp API-key\n * creation path) can compute it once here and pass it into both helpers to\n * avoid the redundant round-trip.\n *\n * @param ecdsaValidator (on the consumers) must be one built for the SAME\n * `signer` — passing a validator derived from a different signer would attach\n * the wrong owner to the account.\n */\nexport async function createEcdsaValidator(\n signer: Signer,\n publicClient: PublicClient,\n): Promise<EcdsaValidator> {\n return signerToEcdsaValidator(publicClient, {\n signer,\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function createKernelSmartAccount(\n signer: Signer,\n publicClient: PublicClient,\n ecdsaValidator?: EcdsaValidator,\n): Promise<SmartAccount> {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n\n return await createKernelAccount(publicClient, {\n plugins: {\n sudo: validator,\n },\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function getApproval(signer: Signer, publicClient: any, policies: any[]) {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer,\n kernelVersion: KERNEL_V3_1,\n })\n const emptyAccount = addressToEmptyAccount(signer.address as Address)\n const emptySessionKeySigner = await toECDSASigner({ signer: emptyAccount })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: emptySessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: ecdsaValidator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return await serializePermissionAccount(sessionKeyAccount)\n}\n\nexport async function useSessionKey(approval: string, signer: Signer, publicClient: any) {\n const sessionKeySigner = await toECDSASigner({\n signer,\n })\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n approval,\n sessionKeySigner,\n )\n\n return sessionKeyAccount\n}\n\nexport async function createSessionKey(\n signer: Signer,\n publicClient: any,\n policies: any[],\n ecdsaValidator?: EcdsaValidator,\n) {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n const sessionPrivateKey = generatePrivateKey()\n const masterAccount = privateKeyToAccount(sessionPrivateKey)\n const sessionKeySigner = await toECDSASigner({\n signer: masterAccount,\n })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: validator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n}\n\nexport async function getSessionKey(serializedSessionKey: string, publicClient: any) {\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n serializedSessionKey,\n )\n\n return sessionKeyAccount\n}\n\n/**\n * Creates a delegated session key for an existing kernel account.\n * The resulting serialized session key can be deserialized into a SmartAccount\n * that shares the same address as the kernel account but enforces the given policies.\n *\n * @param kernelAccount The existing SmartAccount (kernel) to delegate from\n * @param publicClient Viem PublicClient instance\n * @param policies Array of policies to enforce for this session key\n * @returns Serialized session key string\n */\nexport async function createDelegatedSessionKeyFromKernel(\n kernelAccount: SmartAccount,\n publicClient: PublicClient,\n policies: any[],\n): Promise<string> {\n // 1) Generate ephemeral session private key (used only for the permission plugin)\n const sessionPrivateKey = generatePrivateKey()\n const sessionAccount = privateKeyToAccount(sessionPrivateKey)\n\n // 2) Wrap ephemeral key as ECDSA signer for permissions\n const sessionKeySigner = await toECDSASigner({ signer: sessionAccount })\n\n // 3) Create the permission validator plugin\n const permissionValidator = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n // 4) Extract the sudo validator from the existing kernel account\n const kernelAccountTyped = kernelAccount as SmartAccount<KernelSmartAccountImplementation>\n const sudoValidator = kernelAccountTyped.kernelPluginManager.sudoValidator\n\n if (!sudoValidator) {\n throw new Error('Kernel account does not have a sudo validator')\n }\n\n // 5) Create a new kernel account with both sudo (from original) and permission validator\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: sudoValidator, // Use existing sudo validator\n regular: permissionValidator,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n // 6) Serialize the session key account with the ephemeral private key\n const serialized = await serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n\n return serialized\n}\n\nexport const WalletUtils = {\n makeWallet,\n makeWallets,\n makeRandomWallet,\n makeRandomWallets,\n}\n"],"names":["signerToEcdsaValidator","deserializePermissionAccount","serializePermissionAccount","toPermissionValidator","toECDSASigner","addressToEmptyAccount","createKernelAccount","createKernelAccountClient","createZeroDevPaymasterClient","getUserOperationGasPrice","KERNEL_V3_1","getEntryPoint","encodeAbiParameters","getAbiItem","getAddress","getContract","http","isAddress","pad","stringToBytes","stringToHex","toBytes","keccak256","viemKeccak256","english","generateMnemonic","generatePrivateKey","mnemonicToAccount","privateKeyToAccount","Instantiable","ContractsError","getChain","ENTRY_POINT_VERSION","BlockchainViemUtils","config","setInstanceConfig","TRANSACTION_RECEIPT_TIMEOUT_MS","TRANSACTION_RECEIPT_POLLING_INTERVAL_MS","getTransactionReceipt","txHash","publicClient","waitForTransactionReceipt","hash","timeout","pollingInterval","confirmations","error","getContractInstance","contractAddress","abi","client","address","wallet","public","searchAbiFunction","funcName","args","func","name","type","searchAbiEvent","eventName","event","getSignatureOfFunction","getInputsOfFunction","inputs","getInputsOfFunctionFormatted","map","input","i","value","getChecksumAddress","isValidAddress","getBytes","message","zeroPadValue","length","size","encodeBytes32String","makeWallet","seedphrase","addressIndex","makeWallets","numAccounts","accounts","push","makeRandomWallet","mnemonic","makeRandomWallets","seed","keccak256WithEncode","types","values","encoded","keccak256Packed","getBundlerRpcUrl","zeroDevProjectId","chainId","useUltraRelay","base","process","env","BUNDLER_RPC_URL_OVERRIDE","getPaymasterRpcUrl","isRelayerMode","Boolean","estimateUserOperationFees","bundlerClient","_publicClient","maxFeePerGas","maxPriorityFeePerGas","createKernelClient","kernelAccount","bundlerRpc","paymasterRpc","account","chain","bundlerTransport","paymaster","getPaymasterData","userOperation","zerodevPaymaster","transport","sponsorUserOperation","estimateFeesPerGas","SCA_DERIVATION_VERSION","createEcdsaValidator","signer","entryPoint","kernelVersion","createKernelSmartAccount","ecdsaValidator","validator","plugins","sudo","getApproval","policies","emptyAccount","emptySessionKeySigner","permissionPlugin","sessionKeyAccount","regular","useSessionKey","approval","sessionKeySigner","createSessionKey","sessionPrivateKey","masterAccount","getSessionKey","serializedSessionKey","createDelegatedSessionKeyFromKernel","sessionAccount","permissionValidator","kernelAccountTyped","sudoValidator","kernelPluginManager","Error","serialized","WalletUtils"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,2BAA0B;AACjE,SACEC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,qBAAqB,QAChB,uBAAsB;AAC7B,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,yBAAyB,EACzBC,4BAA4B,EAC5BC,wBAAwB,QAGnB,eAAc;AACrB,SAASC,WAAW,EAAEC,aAAa,QAAQ,yBAAwB;AACnE,SAEEC,mBAAmB,EACnBC,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,IAAI,EACJC,SAAS,EACTC,GAAG,EACHC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,aAAaC,aAAa,QAO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qB;QAC1BqG,SAAS;YACPC,MAAMoB;YACNb,SAASW;QACX;QACAvB,eAAevH;IACjB;IAEA,sEAAsE;IACtE,MAAMmJ,aAAa,MAAM3J,2BAA2B0I,mBAAmBM;IAEvE,OAAOW;AACT;AAEA,OAAO,MAAMC,cAAc;IACzB/E;IACAG;IACAI;IACAE;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"sourcesContent":["import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator'\nimport {\n deserializePermissionAccount,\n serializePermissionAccount,\n toPermissionValidator,\n} from '@zerodev/permissions'\nimport { toECDSASigner } from '@zerodev/permissions/signers'\nimport {\n addressToEmptyAccount,\n createKernelAccount,\n createKernelAccountClient,\n createZeroDevPaymasterClient,\n getUserOperationGasPrice,\n KernelAccountClient,\n type KernelSmartAccountImplementation,\n} from '@zerodev/sdk'\nimport {\n KERNEL_V3_1,\n KERNEL_V3_3,\n KERNEL_7702_DELEGATION_ADDRESS,\n getEntryPoint,\n} from '@zerodev/sdk/constants'\nimport {\n Address,\n encodeAbiParameters,\n getAbiItem,\n getAddress,\n getContract,\n http,\n isAddress,\n pad,\n stringToBytes,\n stringToHex,\n toBytes,\n keccak256 as viemKeccak256,\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type Account,\n type PublicClient,\n type SignAuthorizationReturnType,\n type TransactionReceipt,\n} from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport {\n english,\n generateMnemonic,\n generatePrivateKey,\n mnemonicToAccount,\n privateKeyToAccount,\n} from 'viem/accounts'\nimport { Instantiable, InstantiableConfig, Web3Clients } from '../../Instantiable.abstract.js'\nimport { ContractsError } from '../../errors/NeverminedErrors.js'\nimport { getChain, isTempoNetwork } from '../../utils/Network.js'\nimport { Signer } from '@zerodev/sdk/types'\n\nconst ENTRY_POINT_VERSION = '0.7'\n\n/**\n * Utility class with methods that allow the interaction with the blockchain.\n * This class uses Viem library to interact with the blockchain.\n */\nexport class BlockchainViemUtils extends Instantiable {\n constructor(config: InstantiableConfig) {\n super()\n this.setInstanceConfig(config)\n }\n}\n\n//////////////////////////\n///// UTILITIES //////////\n//////////////////////////\n\n///// CONTRACTS\n\n// Wait budget for an L2 block to be mined and the receipt to surface.\n// Base / Base Sepolia block time is ~2s; 30s ≈ 15 blocks of headroom.\nconst TRANSACTION_RECEIPT_TIMEOUT_MS = 30_000\nconst TRANSACTION_RECEIPT_POLLING_INTERVAL_MS = 1_500\n\n/**\n * Given a transaction hash, it returns the transaction receipt.\n * Uses viem's `waitForTransactionReceipt` which polls until the receipt is\n * available, retrying on `TransactionReceiptNotFoundError` and handling\n * tx-replacement / reorgs natively.\n * @param txHash - the transaction hash\n * @returns the transaction receipt\n */\nexport async function getTransactionReceipt({\n txHash,\n publicClient,\n}: {\n txHash: `0x${string}`\n publicClient: PublicClient\n iteration?: number\n}): Promise<TransactionReceipt> {\n try {\n return await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: TRANSACTION_RECEIPT_TIMEOUT_MS,\n pollingInterval: TRANSACTION_RECEIPT_POLLING_INTERVAL_MS,\n confirmations: 1,\n })\n } catch (error) {\n throw new ContractsError(\n `Unable to get transaction receipt with hash: ${txHash}. Error: ${error}`,\n )\n }\n}\n\n/**\n * Given an already deployed contract address and the ABI, it returns the contract instance.\n *\n * @param contractAddress - the contract address\n * @param abi - the contract artifact\n * @param client - the client to interact with the blockchain\n * @returns a contract instance\n */\nexport async function getContractInstance(contractAddress: string, abi: Abi, client: Web3Clients) {\n return getContract({\n abi,\n address: contractAddress as `0x${string}`,\n client: { wallet: client.wallet, public: client.public },\n })\n}\n\n///// ABIs\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function searchAbiFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n const func = getAbiItem({ abi, name: funcName, args })\n if (!func || func.type !== 'function') {\n throw new ContractsError(`Function \"${funcName}\" is not part of contract`)\n }\n return func as AbiFunction\n}\n\n/**\n * It searchs an ABI event in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the event name\n * @returns the event found\n */\nexport function searchAbiEvent(abi: Abi, eventName: string): AbiEvent {\n const event = getAbiItem({\n abi,\n name: eventName,\n })\n if (!event || event.type !== 'event') {\n throw new ContractsError(`Event \"${event}\" is not part of contract`)\n }\n return event as AbiEvent\n}\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getSignatureOfFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n return searchAbiFunction(abi, funcName, args)\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunction(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs formatted.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunctionFormatted(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs.map((input, i) => {\n return {\n name: input.name,\n value: args[i],\n }\n })\n}\n\n//////// UTILS\n\n/**\n * Given an address it returns that address in checksum format.\n * @param address the address\n * @returns the same address in checksum format\n */\nexport function getChecksumAddress(address: string): string {\n return getAddress(address)\n}\n\n/**\n * It checks if the address is a valid address.\n * @param address the address to check\n * @returns true of the address is valid\n */\nexport function isValidAddress(address: string): boolean {\n return isAddress(address)\n}\n\n/**\n * Encodes a UTF-8 string into a byte array.\n\n * @param message the string to encode\n * @returns the encoded byte array\n */\nexport function getBytes(message: string): Uint8Array {\n return stringToBytes(message)\n}\n\n/**\n * It pads a value with zeros.\n * @param value the value to pad\n * @param length the expected longitutde of the value\n * @returns the padded value\n */\nexport function zeroPadValue(value: `0x${string}` | Uint8Array, length: number): string {\n return pad(value, { size: length }) as `0x${string}`\n}\n\n/**\n * Encodes a UTF-8 string into a hex string\n * @param message the string to encode\n * @returns the hex string\n */\nexport function encodeBytes32String(message: string) {\n return stringToHex(message, { size: 32 })\n}\n\n////// ACCOUNTS\n/**\n * Given a seedphrase, it returns an account.\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param addressIndex - the address index\n * @returns an account\n */\nexport function makeWallet(seedphrase: string, addressIndex = 0): Account {\n return mnemonicToAccount(seedphrase, { addressIndex })\n}\n\n/**\n * Given a seedphrase generates multiple accounts\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeWallets(seedphrase: string, numAccounts = 10) {\n const accounts: Account[] = []\n for (let i = 0; i < numAccounts; i++) {\n accounts.push(makeWallet(seedphrase, i))\n }\n return accounts\n}\n\n/**\n * It generates a random account.\n * @returns a new account\n */\nexport function makeRandomWallet(): Account {\n const mnemonic = generateMnemonic(english)\n return makeWallet(mnemonic)\n}\n\n/**\n * It generates a list of random accounts\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeRandomWallets(numAccounts = 10): Account[] {\n const mnemonic = generateMnemonic(english)\n return makeWallets(mnemonic, numAccounts)\n}\n\n/////// HASHES\n\n/**\n * It hashes a string using keccak256.\n * @param seed the string to hash\n * @returns the hash\n */\nexport function keccak256(seed: string): string {\n return viemKeccak256(toBytes(seed))\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256WithEncode(types: any[], values: any[]): string {\n const encoded = encodeAbiParameters(types, values as never)\n return keccak256(encoded)\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256Packed(types: any[], values: any[]): string {\n return keccak256WithEncode(types, values)\n}\n\n/////// ZERO DEV\n\n/**\n * Returns the bundler RPC URL. When `BUNDLER_RPC_URL_OVERRIDE` is set\n * (used by tests against a local Alto + anvil-fork stack), it takes precedence\n * over the canonical ZeroDev URL. When `useUltraRelay` is true, the production\n * URL is routed through ZeroDev's UltraRelay (`?provider=ULTRA_RELAY`); the\n * override branch is left untouched.\n * @param useUltraRelay - when true, append `?provider=ULTRA_RELAY` to route the\n * UserOperation through ZeroDev's UltraRelay bundler tier. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\nexport function getBundlerRpcUrl(\n zeroDevProjectId: string,\n chainId: number,\n useUltraRelay = false,\n): string {\n const base = `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n // Per-chain override wins, then the global override, then the canonical URL.\n // The per-chain form (`BUNDLER_RPC_URL_OVERRIDE_<chainId>`) lets a single\n // process route UserOps for different networks to different local bundlers —\n // e.g. a dual-fork dev stack (base-sepolia bundler :4337 + tempo bundler\n // :4338). `||` (not `??`) because Vite replaces missing browser env vars with\n // the empty string at build time; an empty override is equivalent to none.\n return (\n process.env[`BUNDLER_RPC_URL_OVERRIDE_${chainId}`] ||\n process.env.BUNDLER_RPC_URL_OVERRIDE ||\n (useUltraRelay ? `${base}?provider=ULTRA_RELAY` : base)\n )\n}\n\n/**\n * Returns the paymaster RPC URL (ZeroDev-only; the local fork stack uses\n * `ultra-relay` which sponsors via the bundler's executor key without a\n * paymaster, so this URL is not consulted when `BUNDLER_RPC_URL_OVERRIDE` is\n * set).\n */\nexport function getPaymasterRpcUrl(zeroDevProjectId: string, chainId: number): string {\n return `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n}\n\n/**\n * Returns true when the kernel client should run in \"relayer mode\" — no\n * paymaster, gas fees zeroed out. Used by tests against a local\n * `ultra-relay` (ZeroDev's fork of Alto) on top of an anvil-fork. The relayer's\n * executor key pays gas directly via `EntryPoint.handleOps`, avoiding the\n * paymaster sponsorship handshake altogether.\n */\nexport function isRelayerMode(): boolean {\n return Boolean(process.env.BUNDLER_RPC_URL_OVERRIDE)\n}\n\n/**\n * Returns gas prices for UserOperation fee estimation. ZeroDev's bundler\n * exposes a custom `zd_getUserOperationGasPrice` method; standard ERC-4337\n * bundlers do not. In relayer mode the bundler accepts UserOps with zeroed\n * `maxFeePerGas`/`maxPriorityFeePerGas` and pays gas itself.\n */\nexport async function estimateUserOperationFees(\n bundlerClient: any,\n _publicClient: any,\n): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }> {\n if (isRelayerMode()) {\n return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n }\n }\n return getUserOperationGasPrice(bundlerClient)\n}\n\n// Tempo undersizes the ZeroDev bundler's `verificationGasLimit` estimate (cold\n// SCA deploy + session-key enable under TIP-20 gas), so `zd_sponsorUserOperation`\n// re-simulates with that too-low ceiling and reverts `AA26 over\n// verificationGasLimit` (see #1929, staging createPlan on tempo-moderato). We give\n// the sponsor an explicit floor so it stops undersizing. A multiplier is useless\n// here — viem calls getPaymasterData with verificationGasLimit still 0/undefined,\n// so `x * n` is 0. An absolute floor covers both the 0 and the too-low cases.\n// NOTE(#1929): fixed floor — bump if a Tempo op still AA26s (env-tunable if it ever needs per-deploy calibration).\n// needs per-deploy calibration).\nconst TEMPO_MIN_VERIFICATION_GAS = 30_000_000n\n\n/**\n * Floors `verificationGasLimit` on Tempo networks before the UserOp is handed to\n * the ZeroDev paymaster, so `zd_sponsorUserOperation` has headroom and does not\n * revert AA26. No-op on every other network. Shared by both paymaster sponsor\n * call sites. Generic so the caller's UserOp type is preserved; typing\n * `verificationGasLimit?: bigint` also turns a plain-number literal (a `bigint`\n * missing its `n`) into a compile error instead of a silent floor-to-30M.\n */\nexport function applyTempoVerificationGasFloor<T extends { verificationGasLimit?: bigint }>(\n userOperation: T,\n chainId: number,\n): T {\n if (!isTempoNetwork(chainId)) return userOperation\n const current =\n typeof userOperation.verificationGasLimit === 'bigint' ? userOperation.verificationGasLimit : 0n\n const floored = current > TEMPO_MIN_VERIFICATION_GAS ? current : TEMPO_MIN_VERIFICATION_GAS\n return { ...userOperation, verificationGasLimit: floored } as T\n}\n\n/**\n * It creates a ZeroDev Kernel client.\n * @param signer the signer account\n * @param chainId the chain id\n * @param zeroDevProjectId the zero dev project id, you can get it from the ZeroDev dashboard\n * @param useUltraRelay forwarded straight to `getBundlerRpcUrl` — when true the\n * bundler RPC is routed through ZeroDev's UltraRelay. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n * @returns the kernel client\n */\nexport async function createKernelClient(\n kernelAccount: SmartAccount,\n chainId: number,\n zeroDevProjectId: string,\n publicClient: any,\n useUltraRelay = false,\n): Promise<KernelAccountClient> {\n const bundlerRpc = getBundlerRpcUrl(zeroDevProjectId, chainId, useUltraRelay)\n const paymasterRpc = getPaymasterRpcUrl(zeroDevProjectId, chainId)\n\n return createKernelAccountClient({\n account: kernelAccount,\n chain: getChain(chainId),\n bundlerTransport: http(bundlerRpc),\n client: publicClient,\n ...(isRelayerMode()\n ? {}\n : {\n paymaster: {\n getPaymasterData: (userOperation: any) => {\n const zerodevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(chainId),\n transport: http(paymasterRpc),\n })\n return zerodevPaymaster.sponsorUserOperation({\n userOperation: applyTempoVerificationGasFloor(userOperation, chainId),\n })\n },\n },\n }),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, publicClient)\n },\n },\n })\n}\n\nexport type EcdsaValidator = Awaited<ReturnType<typeof signerToEcdsaValidator>>\n\n/**\n * Identifies the smart-account derivation inputs (entryPoint + kernel version).\n * The SCA is deterministic from `(EOA, entryPoint, kernelVersion, index)`, so a\n * bump here means the same EOA derives a different SCA. Persisted SCA caches\n * (e.g. the webapp's localStorage) should stamp this and invalidate on change.\n */\nexport const SCA_DERIVATION_VERSION = `${ENTRY_POINT_VERSION}:${KERNEL_V3_1}`\n\n// ponytail: in-process memo for ZeroDev Kernel account resolution. Every\n// deserializePermissionAccount / createKernelAccount reads the EIP-1967 impl\n// slot (eth_getStorageAt) of a deployed account — ~56% of backend Infura RPC\n// volume, and the same session key/owner is re-resolved per request and twice\n// per x402 payment (verify + settle). See #2206. Safe to reuse the resolved\n// account: the Kernel account fetches its nonce fresh at send time, so a cached\n// account never signs against a stale nonce. Keyed by the deterministic inputs\n// (serialized key / owner + kernel version + chainId); short TTL bounds\n// staleness across a kernel upgrade. Single-process only — cross-pod dedup is\n// out of scope (#2206 notes). Upgrade path: swap the Map for a shared store.\nconst ACCOUNT_CACHE_TTL_MS = 60_000\n// Bound the cache: `getSessionKey` runs behind `getAccountAttributes` on every\n// authenticated request, keyed per-API-key, so an entry never re-requested\n// would otherwise sit past its TTL for the life of the (long-lived) apps/api\n// process — a slow leak. Cardinality ≈ distinct API keys ever seen; cap + sweep\n// keep it bounded (matches BlockchainCacheService's MAX_ENTRIES + cleanup()).\nexport const ACCOUNT_CACHE_MAX_ENTRIES = 5_000\nconst accountResolutionCache = new Map<string, { value: Promise<unknown>; expiresAt: number }>()\n\nfunction memoResolveAccount<T>(key: string, resolver: () => Promise<T>): Promise<T> {\n const now = Date.now()\n const cached = accountResolutionCache.get(key)\n if (cached && cached.expiresAt > now) {\n return cached.value as Promise<T>\n }\n // Sweep expired entries + bound size so keys never re-requested don't\n // accumulate for the life of the process (Map keeps insertion order → FIFO).\n for (const [k, e] of accountResolutionCache) {\n if (e.expiresAt <= now) accountResolutionCache.delete(k)\n }\n if (accountResolutionCache.size >= ACCOUNT_CACHE_MAX_ENTRIES) {\n accountResolutionCache.delete(accountResolutionCache.keys().next().value as string)\n }\n const entry: { value: Promise<unknown>; expiresAt: number } = {\n value: undefined as unknown as Promise<unknown>,\n expiresAt: now + ACCOUNT_CACHE_TTL_MS,\n }\n // Coalesce concurrent identical resolutions; evict on rejection so a transient\n // RPC failure isn't cached — but only if this exact entry is still current, so\n // a resolver that hangs past its TTL and then rejects can't drop a newer one.\n entry.value = resolver().catch((err) => {\n if (accountResolutionCache.get(key) === entry) accountResolutionCache.delete(key)\n throw err\n })\n accountResolutionCache.set(key, entry)\n return entry.value as Promise<T>\n}\n\n/** Current entry count of the Kernel account-resolution memo (#2206). */\nexport function getAccountResolutionCacheStats() {\n return { size: accountResolutionCache.size }\n}\n\n/** Clear the account-resolution memo (test isolation / kernel-upgrade invalidation). */\nexport function clearAccountResolutionCache() {\n accountResolutionCache.clear()\n}\n\nfunction chainIdOf(publicClient: any): string | number {\n const id = publicClient?.chain?.id\n // chainId is the ONLY discriminator in the sca:/7702:/sk: keys, and SCA /\n // session-key addresses are identical across chains by CREATE2 design — so an\n // id-less client must fail closed rather than alias two networks under one\n // bucket and serve a chain-A account to a chain-B request (latent until #1933).\n if (id == null) {\n throw new Error('account-resolution cache: publicClient.chain.id is required for keying')\n }\n return id\n}\n\n/**\n * Build the ECDSA sudo validator for a signer. Both `createKernelSmartAccount`\n * and `createSessionKey` need this validator and each derives it via a ZeroDev\n * RPC round-trip. Callers that run both in sequence (e.g. the webapp API-key\n * creation path) can compute it once here and pass it into both helpers to\n * avoid the redundant round-trip.\n *\n * @param ecdsaValidator (on the consumers) must be one built for the SAME\n * `signer` — passing a validator derived from a different signer would attach\n * the wrong owner to the account.\n */\nexport async function createEcdsaValidator(\n signer: Signer,\n publicClient: PublicClient,\n): Promise<EcdsaValidator> {\n return signerToEcdsaValidator(publicClient, {\n signer,\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function createKernelSmartAccount(\n signer: Signer,\n publicClient: PublicClient,\n ecdsaValidator?: EcdsaValidator,\n): Promise<SmartAccount> {\n const build = async () => {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n return createKernelAccount(publicClient, {\n plugins: {\n sudo: validator,\n },\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n }\n // A caller-supplied validator isn't part of the key — bypass the memo (like\n // createKernel7702Account does for eip7702Auth) rather than let a cache entry\n // built by a different call silently ignore it (the mismatch createEcdsaValidator warns about).\n if (ecdsaValidator) return build()\n return memoResolveAccount(\n `sca:${chainIdOf(publicClient)}:${SCA_DERIVATION_VERSION}:${signer.address}`,\n build,\n )\n}\n\nexport async function getApproval(signer: Signer, publicClient: any, policies: any[]) {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer,\n kernelVersion: KERNEL_V3_1,\n })\n const emptyAccount = addressToEmptyAccount(signer.address as Address)\n const emptySessionKeySigner = await toECDSASigner({ signer: emptyAccount })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: emptySessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: ecdsaValidator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return await serializePermissionAccount(sessionKeyAccount)\n}\n\nexport async function useSessionKey(approval: string, signer: Signer, publicClient: any) {\n const sessionKeySigner = await toECDSASigner({\n signer,\n })\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n approval,\n sessionKeySigner,\n )\n\n return sessionKeyAccount\n}\n\nexport async function createSessionKey(\n signer: Signer,\n publicClient: any,\n policies: any[],\n ecdsaValidator?: EcdsaValidator,\n sessionPrivateKey: `0x${string}` = generatePrivateKey(),\n) {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n const masterAccount = privateKeyToAccount(sessionPrivateKey)\n const sessionKeySigner = await toECDSASigner({\n signer: masterAccount,\n })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: validator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n // serializePermissionAccount embeds the ENABLE signature for `publicClient`'s\n // chain (signed by the sudo/owner). That signature is chain-bound, which is\n // why one serialization only validates on the chain it was made for. #1929\n return serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n}\n\n/**\n * Multi-network session keys (#1929). Generates ONE session private key and\n * serializes the permission account once per network — each serialization\n * carries that network's chain-bound enable signature. The SAME session key\n * works on every supported chain (the smart-account address + init code are\n * identical via CREATE2 parity); only the enable signature differs per chain.\n *\n * Use the returned map (chainId → serialized session key) to build a single\n * multi-network API key: the backend selects the entry for the operation's\n * network. Avoids the `EnableNotApproved` revert when an API key minted on one\n * chain is used on another.\n *\n * @param signer the smart-account owner (e.g. the Privy EOA) — signs each\n * network's enable signature\n * @param publicClientByChainId map of chainId → a PublicClient for that chain\n * @param policies the permission policies (same on every chain)\n */\nexport async function createSessionKeysForNetworks(\n signer: Signer,\n publicClientByChainId: Record<number, any>,\n policies: any[],\n requiredChainId?: number,\n): Promise<Record<number, string>> {\n const sessionPrivateKey = generatePrivateKey()\n const out: Record<number, string> = {}\n for (const [chainIdStr, publicClient] of Object.entries(publicClientByChainId)) {\n const chainId = Number(chainIdStr)\n try {\n out[chainId] = await createSessionKey(\n signer,\n publicClient,\n policies,\n undefined,\n sessionPrivateKey,\n )\n } catch (err) {\n // Best-effort: a secondary network whose RPC is unreachable must not break\n // key generation (e.g. login). `requiredChainId` (the primary) still throws.\n if (requiredChainId != null && chainId === Number(requiredChainId)) throw err\n console.warn(\n `[createSessionKeysForNetworks] skipping network ${chainId}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n // Enforce the `requiredChainId` contract even when it is ABSENT from the input\n // map (the loop above only throws when it is present AND fails). Without this,\n // callers read `out[primary]` → undefined → an API key with no primary session\n // key, which fails opaquely downstream.\n if (requiredChainId != null && out[requiredChainId] == null) {\n throw new Error(\n `createSessionKeysForNetworks: required network ${requiredChainId} was not in the public-client map`,\n )\n }\n return out\n}\n\n/**\n * The canonical, CREATE2-deterministic Kernel v3.3 implementation that an EOA\n * delegates to under EIP-7702 (same address on Base mainnet + Base Sepolia).\n * This is the `contract`/`address` passed to Privy `sign7702Authorization` and\n * carried in the type-4 authorization. See #2148.\n */\nexport const KERNEL_7702_IMPL_ADDRESS = KERNEL_7702_DELEGATION_ADDRESS\n\n// The two Kernel versions the platform runs: v3.1 for the legacy counterfactual\n// SCA, v3.3 for the EIP-7702-delegated EOA account. Re-exported so the API\n// layer can pick the right version for (de)serializing session keys.\nexport { KERNEL_V3_1, KERNEL_V3_3 }\nexport type KernelVersion = typeof KERNEL_V3_1 | typeof KERNEL_V3_3\n\n/**\n * Resolves a user's EIP-7702 account: the Privy EOA delegated to Kernel v3.3.\n * The resulting account's address **equals the EOA** (no counterfactual SCA),\n * so it both signs EIP-3009 as a plain EOA (Router) and acts as a 4337 smart\n * account (credits/session-keys). `eip7702Auth` is the signed type-4\n * authorization (from Privy `sign7702Authorization`); omit it once the account\n * is already delegated on-chain.\n *\n * ponytail: on-chain correctness (delegation designator, UserOp submission)\n * is validated on Base Sepolia in Phase 0 (#2153); this wrapper only pins the\n * SDK call shape.\n */\nexport async function createKernel7702Account(\n signer: Signer,\n publicClient: PublicClient,\n eip7702Auth?: SignAuthorizationReturnType,\n): Promise<SmartAccount> {\n const build = () =>\n createKernelAccount(publicClient, {\n eip7702Account: signer,\n ...(eip7702Auth ? { eip7702Auth } : {}),\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_3,\n })\n // The install path (auth attached) is a one-time mutating op — never cache it.\n if (eip7702Auth) return build()\n return memoResolveAccount(`7702:${chainIdOf(publicClient)}:${signer.address}`, build)\n}\n\nexport async function getSessionKey(\n serializedSessionKey: string,\n publicClient: any,\n kernelVersion: KernelVersion = KERNEL_V3_1,\n) {\n return memoResolveAccount(\n `sk:${chainIdOf(publicClient)}:${kernelVersion}:${serializedSessionKey}`,\n () =>\n deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion,\n serializedSessionKey,\n ),\n )\n}\n\n/**\n * Creates a delegated session key for an existing kernel account.\n * The resulting serialized session key can be deserialized into a SmartAccount\n * that shares the same address as the kernel account but enforces the given policies.\n *\n * @param kernelAccount The existing SmartAccount (kernel) to delegate from\n * @param publicClient Viem PublicClient instance\n * @param policies Array of policies to enforce for this session key\n * @returns Serialized session key string\n */\nexport async function createDelegatedSessionKeyFromKernel(\n kernelAccount: SmartAccount,\n publicClient: PublicClient,\n policies: any[],\n kernelVersion: KernelVersion = KERNEL_V3_1,\n): Promise<string> {\n // 1) Generate ephemeral session private key (used only for the permission plugin)\n const sessionPrivateKey = generatePrivateKey()\n const sessionAccount = privateKeyToAccount(sessionPrivateKey)\n\n // 2) Wrap ephemeral key as ECDSA signer for permissions\n const sessionKeySigner = await toECDSASigner({ signer: sessionAccount })\n\n // 3) Create the permission validator plugin — MUST match the parent kernel's\n // version (v3.3 for a 7702 account, v3.1 for the legacy SCA), otherwise the\n // serialized blob deserializes/validates against the wrong kernel.\n const permissionValidator = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies,\n kernelVersion,\n })\n\n // 4) Extract the sudo validator from the existing kernel account\n const kernelAccountTyped = kernelAccount as SmartAccount<KernelSmartAccountImplementation>\n const sudoValidator = kernelAccountTyped.kernelPluginManager.sudoValidator\n\n if (!sudoValidator) {\n throw new Error('Kernel account does not have a sudo validator')\n }\n\n // 5) Create a new kernel account with both sudo (from original) and permission\n // validator, at the same address as the parent kernel. For a 7702 account\n // that address is the EOA; pinning `address` keeps the session-key account\n // on the same account rather than a fresh counterfactual one.\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n address: kernelAccountTyped.address,\n plugins: {\n sudo: sudoValidator, // Use existing sudo validator\n regular: permissionValidator,\n },\n kernelVersion,\n })\n\n // 6) Serialize the session key account with the ephemeral private key\n const serialized = await serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n\n return serialized\n}\n\nexport const WalletUtils = {\n makeWallet,\n makeWallets,\n makeRandomWallet,\n makeRandomWallets,\n}\n"],"names":["signerToEcdsaValidator","deserializePermissionAccount","serializePermissionAccount","toPermissionValidator","toECDSASigner","addressToEmptyAccount","createKernelAccount","createKernelAccountClient","createZeroDevPaymasterClient","getUserOperationGasPrice","KERNEL_V3_1","KERNEL_V3_3","KERNEL_7702_DELEGATION_ADDRESS","getEntryPoint","encodeAbiParameters","getAbiItem","getAddress","getContract","http","isAddress","pad","stringToBytes","stringToHex","toBytes","keccak256","viemKeccak256","english","generateMnemonic","generatePrivateKey","mnemonicToAccount","privateKeyToAccount","Instantiable","ContractsError","getChain","isTempoNetwork","ENTRY_POINT_VERSION","BlockchainViemUtils","config","setInstanceConfig","TRANSACTION_RECEIPT_TIMEOUT_MS","TRANSACTION_RECEIPT_POLLING_INTERVAL_MS","getTransactionReceipt","txHash","publicClient","waitForTransactionReceipt","hash","timeout","pollingInterval","confirmations","error","getContractInstance","contractAddress","abi","client","address","wallet","public","searchAbiFunction","funcName","args","func","name","type","searchAbiEvent","eventName","event","getSignatureOfFunction","getInputsOfFunction","inputs","getInputsOfFunctionFormatted","map","input","i","value","getChecksumAddress","isValidAddress","getBytes","message","zeroPadValue","length","size","encodeBytes32String","makeWallet","seedphrase","addressIndex","makeWallets","numAccounts","accounts","push","makeRandomWallet","mnemonic","makeRandomWallets","seed","keccak256WithEncode","types","values","encoded","keccak256Packed","getBundlerRpcUrl","zeroDevProjectId","chainId","useUltraRelay","base","process","env","BUNDLER_RPC_URL_OVERRIDE","getPaymasterRpcUrl","isRelayerMode","Boolean","estimateUserOperationFees","bundlerClient","_publicClient","maxFeePerGas","maxPriorityFeePerGas","TEMPO_MIN_VERIFICATION_GAS","applyTempoVerificationGasFloor","userOperation","current","verificationGasLimit","floored","createKernelClient","kernelAccount","bundlerRpc","paymasterRpc","account","chain","bundlerTransport","paymaster","getPaymasterData","zerodevPaymaster","transport","sponsorUserOperation","estimateFeesPerGas","SCA_DERIVATION_VERSION","ACCOUNT_CACHE_TTL_MS","ACCOUNT_CACHE_MAX_ENTRIES","accountResolutionCache","Map","memoResolveAccount","key","resolver","now","Date","cached","get","expiresAt","k","e","delete","keys","next","entry","undefined","catch","err","set","getAccountResolutionCacheStats","clearAccountResolutionCache","clear","chainIdOf","id","Error","createEcdsaValidator","signer","entryPoint","kernelVersion","createKernelSmartAccount","ecdsaValidator","build","validator","plugins","sudo","getApproval","policies","emptyAccount","emptySessionKeySigner","permissionPlugin","sessionKeyAccount","regular","useSessionKey","approval","sessionKeySigner","createSessionKey","sessionPrivateKey","masterAccount","createSessionKeysForNetworks","publicClientByChainId","requiredChainId","out","chainIdStr","Object","entries","Number","console","warn","String","KERNEL_7702_IMPL_ADDRESS","createKernel7702Account","eip7702Auth","eip7702Account","getSessionKey","serializedSessionKey","createDelegatedSessionKeyFromKernel","sessionAccount","permissionValidator","kernelAccountTyped","sudoValidator","kernelPluginManager","serialized","WalletUtils"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,2BAA0B;AACjE,SACEC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,qBAAqB,QAChB,uBAAsB;AAC7B,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,yBAAyB,EACzBC,4BAA4B,EAC5BC,wBAAwB,QAGnB,eAAc;AACrB,SACEC,WAAW,EACXC,WAAW,EACXC,8BAA8B,EAC9BC,aAAa,QACR,yBAAwB;AAC/B,SAEEC,mBAAmB,EACnBC,UAAU,EACVC,UAAU,EAC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AMzM,sBAAsBwC,cAAc;QACpEyH,YAAYvJ,cAAcsB;QAC1BgI,QAAQkB;QACRR;QACAR;IACF;IAEA,iEAAiE;IACjE,MAAMwC,qBAAqBpF;IAC3B,MAAMqF,gBAAgBD,mBAAmBE,mBAAmB,CAACD,aAAa;IAE1E,IAAI,CAACA,eAAe;QAClB,MAAM,IAAI7C,MAAM;IAClB;IAEA,+EAA+E;IAC/E,6EAA6E;IAC7E,8EAA8E;IAC9E,iEAAiE;IACjE,MAAMgB,oBAAoB,MAAM3K,oBAAoBqC,cAAc;QAChEyH,YAAYvJ,cAAcsB;QAC1BmB,SAASuJ,mBAAmBvJ,OAAO;QACnCoH,SAAS;YACPC,MAAMmC;YACN5B,SAAS0B;QACX;QACAvC;IACF;IAEA,sEAAsE;IACtE,MAAM2C,aAAa,MAAM9M,2BAA2B+K,mBAAmBM;IAEvE,OAAOyB;AACT;AAEA,OAAO,MAAMC,cAAc;IACzB/H;IACAG;IACAI;IACAE;AACF,EAAC"}
@@ -15,8 +15,8 @@ export declare const getOrderPolicy: () => Policy;
15
15
  export declare const getMintNFTPolicy: () => Policy;
16
16
  export declare const getBurnNFTPolicy: () => Policy;
17
17
  export declare const getRegisterPolicy: () => Policy;
18
- export declare const buildPolicy: (permissions: string[], contractAddress: `0x${string}`) => Policy;
19
- export declare const getAllContractsPolicy: (contractAddress: `0x${string}`) => Policy;
18
+ export declare const buildPolicy: (permissions: string[], tokenAddresses: `0x${string}`[]) => Policy;
19
+ export declare const getAllContractsPolicy: (tokenAddresses: `0x${string}`[]) => Policy;
20
20
  export type OrderContract = {
21
21
  address: `0x${string}`;
22
22
  isPayAsYouGo: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"ZeroDevPolicies.d.ts","sourceRoot":"","sources":["../../../src/nevermined/utils/ZeroDevPolicies.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,GAAG,EAAoC,MAAM,MAAM,CAAA;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAA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AAW,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,oBAAoB,CAAC,EAAE,KAAK,MAAM,EAAE,CAAA;IACpC,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,uBAAuB,GAAI,oBAAoB,kBAAkB,KAAG,MAAM,EAgFtF,CAAA"}
@@ -9,20 +9,54 @@ export function getPolicy(permissions) {
9
9
  }
10
10
  export function getPermissions(config, functionNames) {
11
11
  const permissions = [];
12
- functionNames.forEach((functionName)=>{
13
- const abis = config.abi.filter((item)=>item.type === 'function' && item.name === functionName);
12
+ functionNames.forEach((entry)=>{
13
+ // A bare name ('register') matches every overload of that name; a full signature
14
+ // ('register(bytes32,string,uint256[])') pins ONE overload. The latter lets callers
15
+ // permit only the signature the SDK actually calls instead of all overloads, which
16
+ // keeps the CallPolicy merkle small (load-bearing on Tempo — see #1929).
17
+ const name = entry.split('(')[0];
18
+ const abis = config.abi.filter((item)=>{
19
+ if (item.type !== 'function' || item.name !== name) return false;
20
+ if (!entry.includes('(')) return true;
21
+ const sig = `${item.name}(${(item.inputs ?? []).map((i)=>i.type).join(',')})`;
22
+ return sig === entry;
23
+ });
24
+ // Fail LOUD if a requested function resolves to no ABI entry. A pinned full
25
+ // signature (#1929 register trim) that stops matching after a contract regen
26
+ // would otherwise silently emit zero permissions → every userOp for that
27
+ // function reverts `InvalidCallData` at runtime with no build-time error.
28
+ if (abis.length === 0) {
29
+ throw new Error(`getPermissions: "${entry}" matched no function in the ABI for ${config.address}. ` + `A contract regen may have changed the signature (see #1929 register-overload trim).`);
30
+ }
14
31
  abis.forEach((abi)=>{
15
32
  permissions.push({
16
33
  target: config.address,
17
34
  abi: [
18
35
  abi
19
36
  ],
20
- functionName
37
+ functionName: name
21
38
  });
22
39
  });
23
40
  });
24
41
  return permissions;
25
42
  }
43
+ // Dedupe settlement-token addresses case-insensitively (checksummed vs lowercase
44
+ // are the SAME token) and drop the zero address. Duplicate `approve` permissions
45
+ // re-bloat the CallPolicy merkle, which is load-bearing on Tempo's enable-gas
46
+ // ceiling (#1929) — a case-sensitive `new Set` would let a mixed-casing map edit
47
+ // silently regress the enable.
48
+ function dedupeTokens(tokenAddresses) {
49
+ const seen = new Set();
50
+ const out = [];
51
+ for (const t of tokenAddresses){
52
+ if (!t || t === zeroAddress) continue;
53
+ const key = t.toLowerCase();
54
+ if (seen.has(key)) continue;
55
+ seen.add(key);
56
+ out.push(t);
57
+ }
58
+ return out;
59
+ }
26
60
  export function getERC20ApprovePermissions(contractAddress) {
27
61
  return {
28
62
  target: contractAddress,
@@ -35,8 +69,21 @@ export function getERC20ApprovePermissions(contractAddress) {
35
69
  export const getERC20ApprovePolicy = (contractAddress)=>getPolicy([
36
70
  getERC20ApprovePermissions(contractAddress)
37
71
  ]);
72
+ // AssetRegistry's ABI carries 5 `register` overloads, but the SDK only ever calls
73
+ // register(bytes32 seed, string url, uint256[] plans) (AssetRegistry.register). Pinning the
74
+ // used signature drops the 4 dead overloads from the CallPolicy merkle (16 → 12 perms),
75
+ // which is what lets the session-key ENABLE fit under Tempo's verification-gas ceiling (#1929).
76
+ const REGISTER_FN = 'register(bytes32,string,uint256[])';
77
+ const REGISTER_GROUP_FNS = [
78
+ REGISTER_FN,
79
+ 'createPlan',
80
+ 'createPlanWithHooks',
81
+ 'registerAgentAndPlan',
82
+ 'addPlanToAgent',
83
+ 'removePlanFromAgent'
84
+ ];
38
85
  export const getAgentRegistrationPolicy = ()=>getPolicy(getPermissions(assetsRegistryConfig, [
39
- 'register'
86
+ REGISTER_FN
40
87
  ]));
41
88
  export const getPricingPlanRegistrationPolicy = ()=>getPolicy(getPermissions(assetsRegistryConfig, [
42
89
  'createPlan',
@@ -62,24 +109,28 @@ export const getMintNFTPolicy = ()=>getPolicy(getPermissions(nft1155CreditsConfi
62
109
  export const getBurnNFTPolicy = ()=>getPolicy(getPermissions(nft1155CreditsConfig, [
63
110
  'burn'
64
111
  ]));
65
- export const getRegisterPolicy = ()=>getPolicy(getPermissions(assetsRegistryConfig, [
66
- 'register',
67
- 'createPlan',
68
- 'createPlanWithHooks',
69
- 'registerAgentAndPlan',
70
- 'addPlanToAgent',
71
- 'removePlanFromAgent'
72
- ]));
73
- export const buildPolicy = (permissions, contractAddress)=>{
112
+ export const getRegisterPolicy = ()=>getPolicy(getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS));
113
+ // #1929: the session-key CallPolicy is a cross-network UNION (every settlement
114
+ // token's `approve` + the protocol methods) that must fit under Tempo's (most
115
+ // restrictive) verification-gas ceiling for the on-chain ENABLE. The register-
116
+ // overload trim (16 → 12 perms) exists precisely because that margin is thin, and
117
+ // each new network/currency adds an `approve` to EVERY chain's key — so guard the
118
+ // bound explicitly. Exceeding it means the next Tempo `createSessionKey` enable
119
+ // would silently revert (AA23/AA26); the fix is a per-network token subset
120
+ // (`createSessionKeysForNetworks` already loops per network), NOT raising this.
121
+ const MAX_CALLPOLICY_PERMISSIONS = 14;
122
+ const assertPolicyFitsTempoEnableGas = (perms)=>{
123
+ if (perms.length > MAX_CALLPOLICY_PERMISSIONS) {
124
+ throw new Error(`CallPolicy has ${perms.length} permissions; exceeds the Tempo session-key enable-gas budget (${MAX_CALLPOLICY_PERMISSIONS}). Split to a per-network token subset instead of growing the cross-network union.`);
125
+ }
126
+ };
127
+ // #1929: `order` keys must approve EVERY settlement token they may pay with (one
128
+ // per network/currency), not a single hardcoded one — otherwise paying a plan in
129
+ // a different token (EURC, or pathUSD on Tempo) reverts `InvalidCallData`. No spend
130
+ // limit by design (the approve permissions carry no `valueLimit`).
131
+ export const buildPolicy = (permissions, tokenAddresses)=>{
74
132
  const perms = [
75
- ...permissions.includes('register') ? getPermissions(assetsRegistryConfig, [
76
- 'register',
77
- 'createPlan',
78
- 'createPlanWithHooks',
79
- 'registerAgentAndPlan',
80
- 'addPlanToAgent',
81
- 'removePlanFromAgent'
82
- ]) : [],
133
+ ...permissions.includes('register') ? getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS) : [],
83
134
  ...permissions.includes('mint') ? getPermissions(nft1155CreditsConfig, [
84
135
  'mint'
85
136
  ]) : [],
@@ -92,21 +143,19 @@ export const buildPolicy = (permissions, contractAddress)=>{
92
143
  ...permissions.includes('order') ? getPermissions(payAsYouGoTemplateConfig, [
93
144
  'order'
94
145
  ]) : [],
95
- ...permissions.includes('order') ? [
96
- getERC20ApprovePermissions(contractAddress)
97
- ] : []
146
+ ...permissions.includes('order') ? dedupeTokens(tokenAddresses).map((t)=>getERC20ApprovePermissions(t)) : []
98
147
  ];
148
+ assertPolicyFitsTempoEnableGas(perms);
99
149
  return getPolicy(perms);
100
150
  };
101
- export const getAllContractsPolicy = (contractAddress)=>getPolicy([
102
- ...getPermissions(assetsRegistryConfig, [
103
- 'register',
104
- 'createPlan',
105
- 'createPlanWithHooks',
106
- 'registerAgentAndPlan',
107
- 'addPlanToAgent',
108
- 'removePlanFromAgent'
109
- ]),
151
+ // #1929: the session key must permit `approve` on EVERY settlement token it may
152
+ // ever pay with — one per (network, currency). A single-token policy silently
153
+ // breaks the moment the order's token differs from it (EURC plans, or pathUSD on
154
+ // Tempo), reverting validateUserOp with `InvalidCallData`. Dedupe + drop zeros
155
+ // here so callers can pass the raw per-network token list.
156
+ export const getAllContractsPolicy = (tokenAddresses)=>{
157
+ const perms = [
158
+ ...getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS),
110
159
  ...getPermissions(fixedPaymentTemplateConfig, [
111
160
  'order'
112
161
  ]),
@@ -117,8 +166,11 @@ export const getAllContractsPolicy = (contractAddress)=>getPolicy([
117
166
  'mint',
118
167
  'burn'
119
168
  ]),
120
- getERC20ApprovePermissions(contractAddress)
121
- ].filter(Boolean));
169
+ ...dedupeTokens(tokenAddresses).map((t)=>getERC20ApprovePermissions(t))
170
+ ].filter(Boolean);
171
+ assertPolicyFitsTempoEnableGas(perms);
172
+ return getPolicy(perms);
173
+ };
122
174
  export const getZeroDevOrderPolicies = (orderPolicyOptions)=>{
123
175
  const policies = [];
124
176
  const orderPermissions = orderPolicyOptions.contracts.map((contract)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/nevermined/utils/ZeroDevPolicies.ts"],"sourcesContent":["import {\n CallPolicyVersion,\n ParamCondition,\n toCallPolicy,\n toRateLimitPolicy,\n toTimestampPolicy,\n} from '@zerodev/permissions/policies'\nimport {\n assetsRegistryConfig,\n fixedPaymentTemplateConfig,\n nft1155CreditsConfig,\n payAsYouGoTemplateAddress,\n payAsYouGoTemplateConfig,\n} from '../../artifacts/generated.js'\nimport { Abi, isAddress, parseAbi, zeroAddress } from 'viem'\nimport { Policy } from '@zerodev/permissions'\n\nexport function getPolicy(permissions: any[]) {\n return toCallPolicy({\n policyVersion: CallPolicyVersion.V0_0_4,\n permissions,\n })\n}\n\nexport function getPermissions(config: any, functionNames: string[]) {\n const permissions: any[] = []\n functionNames.forEach((functionName) => {\n const abis = config.abi.filter(\n (item: any) => item.type === 'function' && item.name === functionName,\n )\n abis.forEach((abi: any) => {\n permissions.push({\n target: config.address,\n abi: [abi],\n functionName,\n })\n })\n })\n return permissions\n}\n\nexport function getERC20ApprovePermissions(contractAddress: `0x${string}`) {\n return {\n target: contractAddress,\n abi: parseAbi([\n 'function approve(address spender, uint256 amount) external returns (bool)',\n ]) as Abi,\n functionName: 'approve',\n }\n}\nexport const getERC20ApprovePolicy = (contractAddress: `0x${string}`) =>\n getPolicy([getERC20ApprovePermissions(contractAddress)])\n\nexport const getAgentRegistrationPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, ['register']))\n\nexport const getPricingPlanRegistrationPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, ['createPlan', 'createPlanWithHooks']))\n\nexport const getRegisterAssetsPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, ['registerAgentAndPlan']))\n\nexport const getOrderPolicy = () => {\n const perms = [\n ...getPermissions(fixedPaymentTemplateConfig, ['order']),\n ...getPermissions(payAsYouGoTemplateAddress, ['order']),\n ]\n return getPolicy(perms)\n}\n\nexport const getMintNFTPolicy = () => getPolicy(getPermissions(nft1155CreditsConfig, ['mint']))\n\nexport const getBurnNFTPolicy = () => getPolicy(getPermissions(nft1155CreditsConfig, ['burn']))\n\nexport const getRegisterPolicy = () =>\n getPolicy(\n getPermissions(assetsRegistryConfig, [\n 'register',\n 'createPlan',\n 'createPlanWithHooks',\n 'registerAgentAndPlan',\n 'addPlanToAgent',\n 'removePlanFromAgent',\n ]),\n )\n\nexport const buildPolicy = (permissions: string[], contractAddress: `0x${string}`) => {\n const perms = [\n ...(permissions.includes('register')\n ? getPermissions(assetsRegistryConfig, [\n 'register',\n 'createPlan',\n 'createPlanWithHooks',\n 'registerAgentAndPlan',\n 'addPlanToAgent',\n 'removePlanFromAgent',\n ])\n : []),\n ...(permissions.includes('mint') ? getPermissions(nft1155CreditsConfig, ['mint']) : []),\n ...(permissions.includes('burn') ? getPermissions(nft1155CreditsConfig, ['burn']) : []),\n ...(permissions.includes('order') ? getPermissions(fixedPaymentTemplateConfig, ['order']) : []),\n ...(permissions.includes('order') ? getPermissions(payAsYouGoTemplateConfig, ['order']) : []),\n ...(permissions.includes('order') ? [getERC20ApprovePermissions(contractAddress)] : []),\n ]\n\n return getPolicy(perms)\n}\n\nexport const getAllContractsPolicy = (contractAddress: `0x${string}`) =>\n getPolicy(\n [\n ...getPermissions(assetsRegistryConfig, [\n 'register',\n 'createPlan',\n 'createPlanWithHooks',\n 'registerAgentAndPlan',\n 'addPlanToAgent',\n 'removePlanFromAgent',\n ]),\n ...getPermissions(fixedPaymentTemplateConfig, ['order']),\n ...getPermissions(payAsYouGoTemplateConfig, ['order']),\n ...getPermissions(nft1155CreditsConfig, ['mint', 'burn']),\n getERC20ApprovePermissions(contractAddress),\n ].filter(Boolean),\n )\n\nexport type OrderContract = {\n address: `0x${string}`\n isPayAsYouGo: boolean\n}\n\nexport type OrderPolicyOptions = {\n contracts: OrderContract[]\n subscriberAddress: `0x${string}`\n numberOfPurchases: bigint\n totalAmount: bigint\n count?: number\n erc20ContractAddress?: `0x${string}`\n validUntil?: number\n}\n\nexport const getZeroDevOrderPolicies = (orderPolicyOptions: OrderPolicyOptions): Policy[] => {\n const policies: Policy[] = []\n\n const orderPermissions = orderPolicyOptions.contracts.map((contract) => {\n if (contract.isPayAsYouGo) {\n return {\n target: contract.address,\n abi: parseAbi([\n 'function order(bytes32 _seed, uint256 _planId, bytes[] memory _params) external payable',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'order',\n args: [null, null],\n }\n }\n return {\n target: contract.address,\n abi: parseAbi([\n 'function order(bytes32 _seed, uint256 _planId, address _creditsReceiver, uint256 _numberOfPurchases, bytes[] memory _params) external payable',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'order',\n args: [\n null,\n null,\n {\n condition: ParamCondition.EQUAL,\n value: orderPolicyOptions.subscriberAddress,\n },\n {\n condition: ParamCondition.EQUAL,\n value: orderPolicyOptions.numberOfPurchases,\n },\n ],\n }\n })\n\n const callPermissions: any[] = [...orderPermissions]\n\n if (\n orderPolicyOptions.erc20ContractAddress &&\n isAddress(orderPolicyOptions.erc20ContractAddress)\n ) {\n callPermissions.push({\n target: orderPolicyOptions.erc20ContractAddress,\n abi: parseAbi([\n 'function approve(address spender, uint256 amount) external returns (bool)',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'approve',\n args: [\n {\n condition: ParamCondition.NOT_EQUAL,\n value: zeroAddress,\n },\n {\n condition: ParamCondition.LESS_THAN_OR_EQUAL,\n value: orderPolicyOptions.totalAmount,\n },\n ],\n })\n }\n\n policies.push(getPolicy(callPermissions))\n\n if (orderPolicyOptions.count) {\n const rateLimitPolicy = toRateLimitPolicy({\n count: orderPolicyOptions.count,\n })\n policies.push(rateLimitPolicy)\n }\n\n if (orderPolicyOptions.validUntil) {\n const timestampPolicy = toTimestampPolicy({\n validUntil: orderPolicyOptions.validUntil,\n })\n policies.push(timestampPolicy)\n }\n\n return policies\n}\n"],"names":["CallPolicyVersion","ParamCondition","toCallPolicy","toRateLimitPolicy","toTimestampPolicy","assetsRegistryConfig","fixedPaymentTemplateConfig","nft1155CreditsConfig","payAsYouGoTemplateAddress","payAsYouGoTemplateConfig","isAddress","parseAbi","zeroAddress","getPolicy","permissions","policyVersion","V0_0_4","getPermissions","config","functionNames","forEach","functionName","abis","abi","filter","item","type","name","push","target","address","getERC20ApprovePermissions","contractAddress","getERC20ApprovePolicy","getAgentRegistrationPolicy","getPricingPlanRegistrationPolicy","getRegisterAssetsPolicy","getOrderPolicy","perms","getMintNFTPolicy","getBurnNFTPolicy","getRegisterPolicy","buildPolicy","includes","getAllContractsPolicy","Boolean","getZeroDevOrderPolicies","orderPolicyOptions","policies","orderPermissions","contracts","map","contract","isPayAsYouGo","valueLimit","args","condition","EQUAL","value","subscriberAddress","numberOfPurchases","callPermissions","erc20ContractAddress","NOT_EQUAL","LESS_THAN_OR_EQUAL","totalAmount","count","rateLimitPolicy","validUntil","timestampPolicy"],"mappings":"AAAA,SACEA,iBAAiB,EACjBC,cAAc,EACdC,YAAY,EACZC,iBAAiB,EACjBC,iBAAiB,QACZ,gCAA+B;AACtC,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,oBAAoB,EACpBC,yBAAyB,EACzBC,wBAAwB,QACnB,+BAA8B;AACrC,SAAcC,SAAS,EAAEC,QAAQ,EAAEC,WAAW,QAAQ,OAAM;AAG5D,OAAO,SAASC,UAAUC,WAAkB;IAC1C,OAAOZ,aAAa;QAClBa,eAAef,kBAAkBgB,MAAM;QACvCF;IACF;AACF;AAEA,OAAO,SAASG,eAAeC,MAAW,EAAEC,aAAuB;IACjE,MAAML,cAAqB,EAAE;IAC7BK,cAAcC,OAAO,CAAC,CAACC;QACrB,MAAMC,OAAOJ,OAAOK,GAAG,CAACC,MAAM,CAC5B,CAACC,OAAcA,KAAKC,IAAI,KAAK,cAAcD,KAAKE,IAAI,KAAKN;QAE3DC,KAAKF,OAAO,CAAC,CAACG;YACZT,YAAYc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yB;WAAIZ;KAAiB;IAEpD,IACEF,mBAAmBe,oBAAoB,IACvCpD,UAAUqC,mBAAmBe,oBAAoB,GACjD;QACAD,gBAAgBjC,IAAI,CAAC;YACnBC,QAAQkB,mBAAmBe,oBAAoB;YAC/CvC,KAAKZ,SAAS;gBACZ;aACD;YACD2C,YAAY,EAAE;YACdjC,cAAc;YACdkC,MAAM;gBACJ;oBACEC,WAAWvD,eAAe8D,SAAS;oBACnCL,OAAO9C;gBACT;gBACA;oBACE4C,WAAWvD,eAAe+D,kBAAkB;oBAC5CN,OAAOX,mBAAmBkB,WAAW;gBACvC;aACD;QACH;IACF;IAEAjB,SAASpB,IAAI,CAACf,UAAUgD;IAExB,IAAId,mBAAmBmB,KAAK,EAAE;QAC5B,MAAMC,kBAAkBhE,kBAAkB;YACxC+D,OAAOnB,mBAAmBmB,KAAK;QACjC;QACAlB,SAASpB,IAAI,CAACuC;IAChB;IAEA,IAAIpB,mBAAmBqB,UAAU,EAAE;QACjC,MAAMC,kBAAkBjE,kBAAkB;YACxCgE,YAAYrB,mBAAmBqB,UAAU;QAC3C;QACApB,SAASpB,IAAI,CAACyC;IAChB;IAEA,OAAOrB;AACT,EAAC"}
1
+ {"version":3,"sources":["../../../src/nevermined/utils/ZeroDevPolicies.ts"],"sourcesContent":["import {\n CallPolicyVersion,\n ParamCondition,\n toCallPolicy,\n toRateLimitPolicy,\n toTimestampPolicy,\n} from '@zerodev/permissions/policies'\nimport {\n assetsRegistryConfig,\n fixedPaymentTemplateConfig,\n nft1155CreditsConfig,\n payAsYouGoTemplateAddress,\n payAsYouGoTemplateConfig,\n} from '../../artifacts/generated.js'\nimport { Abi, isAddress, parseAbi, zeroAddress } from 'viem'\nimport { Policy } from '@zerodev/permissions'\n\nexport function getPolicy(permissions: any[]) {\n return toCallPolicy({\n policyVersion: CallPolicyVersion.V0_0_4,\n permissions,\n })\n}\n\nexport function getPermissions(config: any, functionNames: string[]) {\n const permissions: any[] = []\n functionNames.forEach((entry) => {\n // A bare name ('register') matches every overload of that name; a full signature\n // ('register(bytes32,string,uint256[])') pins ONE overload. The latter lets callers\n // permit only the signature the SDK actually calls instead of all overloads, which\n // keeps the CallPolicy merkle small (load-bearing on Tempo — see #1929).\n const name = entry.split('(')[0]\n const abis = config.abi.filter((item: any) => {\n if (item.type !== 'function' || item.name !== name) return false\n if (!entry.includes('(')) return true\n const sig = `${item.name}(${(item.inputs ?? []).map((i: any) => i.type).join(',')})`\n return sig === entry\n })\n // Fail LOUD if a requested function resolves to no ABI entry. A pinned full\n // signature (#1929 register trim) that stops matching after a contract regen\n // would otherwise silently emit zero permissions → every userOp for that\n // function reverts `InvalidCallData` at runtime with no build-time error.\n if (abis.length === 0) {\n throw new Error(\n `getPermissions: \"${entry}\" matched no function in the ABI for ${config.address}. ` +\n `A contract regen may have changed the signature (see #1929 register-overload trim).`,\n )\n }\n abis.forEach((abi: any) => {\n permissions.push({\n target: config.address,\n abi: [abi],\n functionName: name,\n })\n })\n })\n return permissions\n}\n\n// Dedupe settlement-token addresses case-insensitively (checksummed vs lowercase\n// are the SAME token) and drop the zero address. Duplicate `approve` permissions\n// re-bloat the CallPolicy merkle, which is load-bearing on Tempo's enable-gas\n// ceiling (#1929) — a case-sensitive `new Set` would let a mixed-casing map edit\n// silently regress the enable.\nfunction dedupeTokens(tokenAddresses: `0x${string}`[]): `0x${string}`[] {\n const seen = new Set<string>()\n const out: `0x${string}`[] = []\n for (const t of tokenAddresses) {\n if (!t || t === zeroAddress) continue\n const key = t.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n out.push(t)\n }\n return out\n}\n\nexport function getERC20ApprovePermissions(contractAddress: `0x${string}`) {\n return {\n target: contractAddress,\n abi: parseAbi([\n 'function approve(address spender, uint256 amount) external returns (bool)',\n ]) as Abi,\n functionName: 'approve',\n }\n}\nexport const getERC20ApprovePolicy = (contractAddress: `0x${string}`) =>\n getPolicy([getERC20ApprovePermissions(contractAddress)])\n\n// AssetRegistry's ABI carries 5 `register` overloads, but the SDK only ever calls\n// register(bytes32 seed, string url, uint256[] plans) (AssetRegistry.register). Pinning the\n// used signature drops the 4 dead overloads from the CallPolicy merkle (16 → 12 perms),\n// which is what lets the session-key ENABLE fit under Tempo's verification-gas ceiling (#1929).\nconst REGISTER_FN = 'register(bytes32,string,uint256[])'\nconst REGISTER_GROUP_FNS = [\n REGISTER_FN,\n 'createPlan',\n 'createPlanWithHooks',\n 'registerAgentAndPlan',\n 'addPlanToAgent',\n 'removePlanFromAgent',\n]\n\nexport const getAgentRegistrationPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, [REGISTER_FN]))\n\nexport const getPricingPlanRegistrationPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, ['createPlan', 'createPlanWithHooks']))\n\nexport const getRegisterAssetsPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, ['registerAgentAndPlan']))\n\nexport const getOrderPolicy = () => {\n const perms = [\n ...getPermissions(fixedPaymentTemplateConfig, ['order']),\n ...getPermissions(payAsYouGoTemplateAddress, ['order']),\n ]\n return getPolicy(perms)\n}\n\nexport const getMintNFTPolicy = () => getPolicy(getPermissions(nft1155CreditsConfig, ['mint']))\n\nexport const getBurnNFTPolicy = () => getPolicy(getPermissions(nft1155CreditsConfig, ['burn']))\n\nexport const getRegisterPolicy = () =>\n getPolicy(getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS))\n\n// #1929: the session-key CallPolicy is a cross-network UNION (every settlement\n// token's `approve` + the protocol methods) that must fit under Tempo's (most\n// restrictive) verification-gas ceiling for the on-chain ENABLE. The register-\n// overload trim (16 → 12 perms) exists precisely because that margin is thin, and\n// each new network/currency adds an `approve` to EVERY chain's key — so guard the\n// bound explicitly. Exceeding it means the next Tempo `createSessionKey` enable\n// would silently revert (AA23/AA26); the fix is a per-network token subset\n// (`createSessionKeysForNetworks` already loops per network), NOT raising this.\nconst MAX_CALLPOLICY_PERMISSIONS = 14\n\nconst assertPolicyFitsTempoEnableGas = (perms: unknown[]): void => {\n if (perms.length > MAX_CALLPOLICY_PERMISSIONS) {\n throw new Error(\n `CallPolicy has ${perms.length} permissions; exceeds the Tempo session-key enable-gas budget (${MAX_CALLPOLICY_PERMISSIONS}). Split to a per-network token subset instead of growing the cross-network union.`,\n )\n }\n}\n\n// #1929: `order` keys must approve EVERY settlement token they may pay with (one\n// per network/currency), not a single hardcoded one — otherwise paying a plan in\n// a different token (EURC, or pathUSD on Tempo) reverts `InvalidCallData`. No spend\n// limit by design (the approve permissions carry no `valueLimit`).\nexport const buildPolicy = (permissions: string[], tokenAddresses: `0x${string}`[]) => {\n const perms = [\n ...(permissions.includes('register')\n ? getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS)\n : []),\n ...(permissions.includes('mint') ? getPermissions(nft1155CreditsConfig, ['mint']) : []),\n ...(permissions.includes('burn') ? getPermissions(nft1155CreditsConfig, ['burn']) : []),\n ...(permissions.includes('order') ? getPermissions(fixedPaymentTemplateConfig, ['order']) : []),\n ...(permissions.includes('order') ? getPermissions(payAsYouGoTemplateConfig, ['order']) : []),\n ...(permissions.includes('order')\n ? dedupeTokens(tokenAddresses).map((t) => getERC20ApprovePermissions(t))\n : []),\n ]\n\n assertPolicyFitsTempoEnableGas(perms)\n return getPolicy(perms)\n}\n\n// #1929: the session key must permit `approve` on EVERY settlement token it may\n// ever pay with — one per (network, currency). A single-token policy silently\n// breaks the moment the order's token differs from it (EURC plans, or pathUSD on\n// Tempo), reverting validateUserOp with `InvalidCallData`. Dedupe + drop zeros\n// here so callers can pass the raw per-network token list.\nexport const getAllContractsPolicy = (tokenAddresses: `0x${string}`[]) => {\n const perms = [\n ...getPermissions(assetsRegistryConfig, REGISTER_GROUP_FNS),\n ...getPermissions(fixedPaymentTemplateConfig, ['order']),\n ...getPermissions(payAsYouGoTemplateConfig, ['order']),\n ...getPermissions(nft1155CreditsConfig, ['mint', 'burn']),\n ...dedupeTokens(tokenAddresses).map((t) => getERC20ApprovePermissions(t)),\n ].filter(Boolean)\n\n assertPolicyFitsTempoEnableGas(perms)\n return getPolicy(perms)\n}\n\nexport type OrderContract = {\n address: `0x${string}`\n isPayAsYouGo: boolean\n}\n\nexport type OrderPolicyOptions = {\n contracts: OrderContract[]\n subscriberAddress: `0x${string}`\n numberOfPurchases: bigint\n totalAmount: bigint\n count?: number\n erc20ContractAddress?: `0x${string}`\n validUntil?: number\n}\n\nexport const getZeroDevOrderPolicies = (orderPolicyOptions: OrderPolicyOptions): Policy[] => {\n const policies: Policy[] = []\n\n const orderPermissions = orderPolicyOptions.contracts.map((contract) => {\n if (contract.isPayAsYouGo) {\n return {\n target: contract.address,\n abi: parseAbi([\n 'function order(bytes32 _seed, uint256 _planId, bytes[] memory _params) external payable',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'order',\n args: [null, null],\n }\n }\n return {\n target: contract.address,\n abi: parseAbi([\n 'function order(bytes32 _seed, uint256 _planId, address _creditsReceiver, uint256 _numberOfPurchases, bytes[] memory _params) external payable',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'order',\n args: [\n null,\n null,\n {\n condition: ParamCondition.EQUAL,\n value: orderPolicyOptions.subscriberAddress,\n },\n {\n condition: ParamCondition.EQUAL,\n value: orderPolicyOptions.numberOfPurchases,\n },\n ],\n }\n })\n\n const callPermissions: any[] = [...orderPermissions]\n\n if (\n orderPolicyOptions.erc20ContractAddress &&\n isAddress(orderPolicyOptions.erc20ContractAddress)\n ) {\n callPermissions.push({\n target: orderPolicyOptions.erc20ContractAddress,\n abi: parseAbi([\n 'function approve(address spender, uint256 amount) external returns (bool)',\n ]) as Abi,\n valueLimit: 0n,\n functionName: 'approve',\n args: [\n {\n condition: ParamCondition.NOT_EQUAL,\n value: zeroAddress,\n },\n {\n condition: ParamCondition.LESS_THAN_OR_EQUAL,\n value: orderPolicyOptions.totalAmount,\n },\n ],\n })\n }\n\n policies.push(getPolicy(callPermissions))\n\n if (orderPolicyOptions.count) {\n const rateLimitPolicy = toRateLimitPolicy({\n count: orderPolicyOptions.count,\n })\n policies.push(rateLimitPolicy)\n }\n\n if (orderPolicyOptions.validUntil) {\n const timestampPolicy = toTimestampPolicy({\n validUntil: orderPolicyOptions.validUntil,\n })\n policies.push(timestampPolicy)\n }\n\n return policies\n}\n"],"names":["CallPolicyVersion","ParamCondition","toCallPolicy","toRateLimitPolicy","toTimestampPolicy","assetsRegistryConfig","fixedPaymentTemplateConfig","nft1155CreditsConfig","payAsYouGoTemplateAddress","payAsYouGoTemplateConfig","isAddress","parseAbi","zeroAddress","getPolicy","permissions","policyVersion","V0_0_4","getPermissions","config","functionNames","forEach","entry","name","split","abis","abi","filter","item","type","includes","sig","inputs","map","i","join","length","Error","address","push","target","functionName","dedupeTokens","tokenAddresses","seen","Set","out","t","key","toLowerCase","has","add","getERC20ApprovePermissions","contractAddress","getERC20ApprovePolicy","REGISTER_FN","REGISTER_GROUP_FNS","getAgentRegistrationPolicy","getPricingPlanRegistrationPolicy","getRegisterAssetsPolicy","getOrderPolicy","perms","getMintNFTPolicy","getBurnNFTPolicy","getRegisterPolicy","MAX_CALLPOLICY_PERMISSIONS","assertPolicyFitsTempoEnableGas","buildPolicy","getAllContractsPolicy","Boolean","getZeroDevOrderPolicies","orderPolicyOptions","policies","orderPermissions","contracts","contract","isPayAsYouGo","valueLimit","args","condition","EQUAL","value","subscriberAddress","numberOfPurchases","callPermissions","erc20ContractAddress","NOT_EQUAL","LESS_THAN_OR_EQUAL","totalAmount","count","rateLimitPolicy","validUntil","timestampPolicy"],"mappings":"AAAA,SACEA,iBAAiB,EACjBC,cAAc,EACdC,YAAY,EACZC,iBAAiB,EACjBC,iBAAiB,QACZ,gCAA+B;AACtC,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,oBAAoB,EACpBC,yBAAyB,EACzBC,wBAAwB,QACnB,+BAA8B;AACrC,SAAcC,SAAS,EAAEC,QAAQ,EAAEC,WAAW,QAAQ,OAAM;AAG5D,OAAO,SAASC,UAAUC,WAAkB;IAC1C,OAAOZ,aAAa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MAAMC,kBAAkBtF,kBAAkB;YACxCqF,OAAOlB,mBAAmBkB,KAAK;QACjC;QACAjB,SAASjC,IAAI,CAACmD;IAChB;IAEA,IAAInB,mBAAmBoB,UAAU,EAAE;QACjC,MAAMC,kBAAkBvF,kBAAkB;YACxCsF,YAAYpB,mBAAmBoB,UAAU;QAC3C;QACAnB,SAASjC,IAAI,CAACqD;IAChB;IAEA,OAAOpB;AACT,EAAC"}
@@ -2,4 +2,9 @@ import { type Chain } from 'viem/chains';
2
2
  export declare function getNetworkName(networkId: number): Promise<string>;
3
3
  export declare function isTestnet(networkId: number): boolean;
4
4
  export declare function getChain(networkId: number | undefined): Chain;
5
+ /**
6
+ * True for Tempo networks (mainnet 4217 + moderato 42431); name-prefixed so new
7
+ * Tempo entries are covered. See `applyTempoVerificationGasFloor` for the why.
8
+ */
9
+ export declare function isTempoNetwork(networkId: number | undefined): boolean;
5
10
  //# sourceMappingURL=Network.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Network.d.ts","sourceRoot":"","sources":["../../src/utils/Network.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,KAAK,EAeX,MAAM,aAAa,CAAA;AAGpB,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAmEvE;AACD,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAmEpD;AACD,wBAAgB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,KAAK,CAoF7D"}
1
+ {"version":3,"file":"Network.d.ts","sourceRoot":"","sources":["../../src/utils/Network.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,KAAK,EAiBX,MAAM,aAAa,CAAA;AA0EpB,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIvE;AAED,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAIpD;AAED,wBAAgB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,KAAK,CAI7D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAGrE"}