@metamask/smart-accounts-kit 1.7.0 → 2.0.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/actions/index.cjs +4 -4
  3. package/dist/actions/index.mjs +3 -3
  4. package/dist/{chunk-GHGCGV3C.cjs → chunk-4PCXDGUF.cjs} +2 -7
  5. package/dist/chunk-4PCXDGUF.cjs.map +1 -0
  6. package/dist/{chunk-YCNLPEPH.mjs → chunk-56QPXKWD.mjs} +2 -2
  7. package/dist/{chunk-EMPAUTIV.mjs → chunk-5ENRJKXL.mjs} +2 -2
  8. package/dist/{chunk-4GOGI2TA.cjs → chunk-7GIUS6HD.cjs} +106 -106
  9. package/dist/chunk-7GIUS6HD.cjs.map +1 -0
  10. package/dist/{chunk-6TSLFRJC.cjs → chunk-CKKCGKTA.cjs} +62 -62
  11. package/dist/chunk-CKKCGKTA.cjs.map +1 -0
  12. package/dist/{chunk-T6SWQZRX.mjs → chunk-D55SIIVM.mjs} +3 -3
  13. package/dist/chunk-D55SIIVM.mjs.map +1 -0
  14. package/dist/{chunk-YPUEM6YV.cjs → chunk-F7R7HDEY.cjs} +12 -12
  15. package/dist/{chunk-YPUEM6YV.cjs.map → chunk-F7R7HDEY.cjs.map} +1 -1
  16. package/dist/{chunk-KIXYMA7J.cjs → chunk-FC3W7R6D.cjs} +15 -15
  17. package/dist/{chunk-KIXYMA7J.cjs.map → chunk-FC3W7R6D.cjs.map} +1 -1
  18. package/dist/{chunk-IERUQUKJ.mjs → chunk-RDTAD64U.mjs} +4 -4
  19. package/dist/chunk-RDTAD64U.mjs.map +1 -0
  20. package/dist/{chunk-32RDDE5N.cjs → chunk-TESSVINE.cjs} +13 -13
  21. package/dist/{chunk-32RDDE5N.cjs.map → chunk-TESSVINE.cjs.map} +1 -1
  22. package/dist/{chunk-3KWKQ7PV.mjs → chunk-XBHL6PDR.mjs} +4 -9
  23. package/dist/chunk-XBHL6PDR.mjs.map +1 -0
  24. package/dist/{chunk-XUBMIW33.mjs → chunk-Z4MVJILE.mjs} +3 -3
  25. package/dist/chunk-Z4MVJILE.mjs.map +1 -0
  26. package/dist/contracts/index.cjs +5 -5
  27. package/dist/contracts/index.mjs +4 -4
  28. package/dist/experimental/index.cjs +14 -14
  29. package/dist/experimental/index.cjs.map +1 -1
  30. package/dist/experimental/index.mjs +3 -3
  31. package/dist/experimental/index.mjs.map +1 -1
  32. package/dist/index.cjs +19 -21
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.mjs +7 -9
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/utils/index.cjs +4 -4
  37. package/dist/utils/index.mjs +3 -3
  38. package/package.json +10 -10
  39. package/dist/chunk-3KWKQ7PV.mjs.map +0 -1
  40. package/dist/chunk-4GOGI2TA.cjs.map +0 -1
  41. package/dist/chunk-6TSLFRJC.cjs.map +0 -1
  42. package/dist/chunk-GHGCGV3C.cjs.map +0 -1
  43. package/dist/chunk-IERUQUKJ.mjs.map +0 -1
  44. package/dist/chunk-T6SWQZRX.mjs.map +0 -1
  45. package/dist/chunk-XUBMIW33.mjs.map +0 -1
  46. /package/dist/{chunk-YCNLPEPH.mjs.map → chunk-56QPXKWD.mjs.map} +0 -0
  47. /package/dist/{chunk-EMPAUTIV.mjs.map → chunk-5ENRJKXL.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/actions/index.ts","../src/actions/erc7710RedeemDelegationAction.ts","../src/actions/erc7715Mapping.ts","../src/actions/erc7715GetGrantedExecutionPermissionsAction.ts","../src/actions/erc7715GetSupportedExecutionPermissionsAction.ts","../src/actions/erc7715RequestExecutionPermissionsAction.ts","../src/actions/redelegatePermissionContext.ts","../src/actions/signDelegation.ts","../src/actions/getCaveatAvailableAmount.ts","../src/actions/isValid7702Implementation.ts","../src/actions/signUserOperation.ts"],"sourcesContent":["import type { Client, WalletClient } from 'viem';\nimport type { BundlerClient } from 'viem/account-abstraction';\n\nimport type {\n SendTransactionWithDelegationParameters,\n SendUserOperationWithDelegationParameters,\n} from './erc7710RedeemDelegationAction';\nimport {\n sendTransactionWithDelegationAction,\n sendUserOperationWithDelegationAction,\n} from './erc7710RedeemDelegationAction';\nimport { erc7715GetGrantedExecutionPermissionsAction } from './erc7715GetGrantedExecutionPermissionsAction';\nimport { erc7715GetSupportedExecutionPermissionsAction } from './erc7715GetSupportedExecutionPermissionsAction';\nimport { erc7715RequestExecutionPermissionsAction } from './erc7715RequestExecutionPermissionsAction';\nimport type {\n MetaMaskExtensionClient,\n RequestExecutionPermissionsParameters,\n} from './erc7715RequestExecutionPermissionsAction';\nimport {\n redelegatePermissionContextAction,\n redelegatePermissionContextOpenAction,\n} from './redelegatePermissionContext';\nimport type {\n RedelegatePermissionContextOpenParameters,\n RedelegatePermissionContextParameters,\n} from './redelegatePermissionContext';\n\nexport {\n // Individual action functions\n getErc20PeriodTransferEnforcerAvailableAmount,\n getErc20StreamingEnforcerAvailableAmount,\n getMultiTokenPeriodEnforcerAvailableAmount,\n getNativeTokenPeriodTransferEnforcerAvailableAmount,\n getNativeTokenStreamingEnforcerAvailableAmount,\n // Action builder\n caveatEnforcerActions,\n // Parameter types\n type CaveatEnforcerParams,\n // Result types\n type PeriodTransferResult,\n type StreamingResult,\n} from './getCaveatAvailableAmount';\n\nexport { isValid7702Implementation } from './isValid7702Implementation';\n\n// Signing actions\nexport {\n signDelegation,\n signDelegationActions,\n type SignDelegationParameters,\n type SignDelegationReturnType,\n} from './signDelegation';\n\nexport {\n signUserOperation,\n signUserOperationActions,\n type SignUserOperationParameters,\n type SignUserOperationReturnType,\n} from './signUserOperation';\n\n// Redelegation actions\nexport {\n redelegatePermissionContextAction,\n redelegatePermissionContextOpenAction,\n type RedelegatePermissionContextParameters,\n type RedelegatePermissionContextOpenParameters,\n type RedelegatePermissionContextReturnType,\n} from './redelegatePermissionContext';\n\nexport {\n erc7715RequestExecutionPermissionsAction as requestExecutionPermissions,\n type MetaMaskExtensionClient,\n type MetaMaskExtensionSchema,\n type RequestExecutionPermissionsParameters,\n type RequestExecutionPermissionsReturnType,\n} from './erc7715RequestExecutionPermissionsAction';\n\nexport type { PermissionRequestParameter } from './erc7715Types';\n\nexport { erc7715GetSupportedExecutionPermissionsAction as getSupportedExecutionPermissions } from './erc7715GetSupportedExecutionPermissionsAction';\n\nexport { erc7715GetGrantedExecutionPermissionsAction as getGrantedExecutionPermissions } from './erc7715GetGrantedExecutionPermissionsAction';\n\nexport {\n type GetSupportedExecutionPermissionsResult,\n type GetGrantedExecutionPermissionsResult,\n type Rule,\n type SupportedPermissionInfo,\n type PermissionTypes,\n type NativeTokenStreamPermission,\n type NativeTokenPeriodicPermission,\n type NativeTokenAllowancePermission,\n type Erc20TokenStreamPermission,\n type Erc20TokenPeriodicPermission,\n type Erc20TokenAllowancePermission,\n type Erc20TokenRevocationPermission,\n type TokenApprovalRevocationPermission,\n type RpcGetSupportedExecutionPermissionsResult,\n type RpcGetGrantedExecutionPermissionsResult,\n type RpcSupportedPermissionInfo,\n} from './erc7715Types';\n\nexport type { DelegatedCall } from './erc7710RedeemDelegationAction';\n\n/**\n * Extends a viem client with ERC-7715 provider actions.\n *\n * @returns A function that decorates a client with ERC-7715 provider actions.\n *\n * @example\n * ```typescript\n * const providerClient = createClient({\n * chain: sepolia,\n * transport: custom(window.ethereum),\n * }).extend(erc7715ProviderActions());\n *\n * await providerClient.requestExecutionPermissions({\n * requests: [permissionRequest],\n * });\n *\n * const supported = await providerClient.getSupportedExecutionPermissions();\n * const granted = await providerClient.getGrantedExecutionPermissions();\n * ```\n */\nexport const erc7715ProviderActions = () => (client: Client) => ({\n requestExecutionPermissions: async (\n parameters: RequestExecutionPermissionsParameters,\n ) => {\n return erc7715RequestExecutionPermissionsAction(\n client as MetaMaskExtensionClient,\n parameters,\n );\n },\n getSupportedExecutionPermissions: async () => {\n return erc7715GetSupportedExecutionPermissionsAction(\n client as MetaMaskExtensionClient,\n );\n },\n getGrantedExecutionPermissions: async () => {\n return erc7715GetGrantedExecutionPermissionsAction(\n client as MetaMaskExtensionClient,\n );\n },\n});\n\n/**\n * Type for a viem Client extended with ERC-7715 provider actions.\n * Use this to type variables for deferred initialization.\n *\n * @example\n * ```typescript\n * let client: Erc7715Client | null = null;\n *\n * function setupClient() {\n * client = createClient({\n * chain: sepolia,\n * transport: custom(window.ethereum),\n * }).extend(erc7715ProviderActions());\n * }\n * ```\n */\nexport type Erc7715Client = Client &\n ReturnType<ReturnType<typeof erc7715ProviderActions>>;\n\n/**\n * Type for a viem WalletClient extended with ERC-7710 wallet actions.\n * Use this to type variables for deferred initialization.\n *\n * @example\n * ```typescript\n * let walletClient: Erc7710WalletClient | null = null;\n *\n * function setupClient() {\n * walletClient = createWalletClient({\n * account,\n * chain: sepolia,\n * transport: custom(window.ethereum),\n * }).extend(erc7710WalletActions());\n * }\n * ```\n */\nexport type Erc7710WalletClient = WalletClient &\n ReturnType<ReturnType<typeof erc7710WalletActions>>;\n\n/**\n * Extends a viem wallet client with ERC-7710 wallet actions.\n *\n * @returns A function that decorates a wallet client with ERC-7710 wallet actions.\n *\n * @example\n * ```typescript\n * const walletClient = createWalletClient({\n * account,\n * chain: sepolia,\n * transport: custom(window.ethereum),\n * }).extend(erc7710WalletActions());\n *\n * await walletClient.sendTransactionWithDelegation({\n * account,\n * chain: sepolia,\n * to: recipient,\n * value: 0n,\n * data: callData,\n * permissionContext,\n * delegationManager: environment.DelegationManager,\n * });\n *\n * await walletClient.redelegatePermissionContext({\n * environment,\n * permissionContext,\n * to: anotherDelegate,\n * // optional when client.chain is configured\n * chainId: sepolia.id,\n * });\n * ```\n */\nexport const erc7710WalletActions = () => (client: WalletClient) => ({\n sendTransactionWithDelegation: async (\n args: SendTransactionWithDelegationParameters,\n ) => sendTransactionWithDelegationAction(client, args),\n redelegatePermissionContext: async (\n parameters: RedelegatePermissionContextParameters,\n ) => redelegatePermissionContextAction(client, parameters),\n redelegatePermissionContextOpen: async (\n parameters: RedelegatePermissionContextOpenParameters,\n ) => redelegatePermissionContextOpenAction(client, parameters),\n});\n\n/**\n * Extends a viem bundler client with ERC-7710 bundler actions.\n *\n * @returns A function that decorates a bundler client with ERC-7710 bundler actions.\n *\n * @example\n * ```typescript\n * const bundlerClient = createBundlerClient({\n * account: smartAccount,\n * chain: sepolia,\n * transport: http(bundlerUrl),\n * }).extend(erc7710BundlerActions());\n *\n * const userOpHash = await bundlerClient.sendUserOperationWithDelegation({\n * publicClient,\n * calls: [\n * {\n * to: recipient,\n * data: callData,\n * value: 0n,\n * permissionContext,\n * delegationManager: environment.DelegationManager,\n * },\n * ],\n * });\n * ```\n */\nexport const erc7710BundlerActions = () => (client: Client) => ({\n sendUserOperationWithDelegation: async (\n args: SendUserOperationWithDelegationParameters,\n ) => sendUserOperationWithDelegationAction(client as BundlerClient, args),\n});\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport type {\n Account,\n Chain,\n Hex,\n OneOf,\n PublicClient,\n SendTransactionParameters,\n SendTransactionRequest,\n Transport,\n WalletClient,\n} from 'viem';\nimport { concat, encodeFunctionData, isAddressEqual } from 'viem';\nimport type {\n BundlerClient,\n SendUserOperationParameters,\n SmartAccount,\n} from 'viem/account-abstraction';\n\nimport { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { encodeDelegations } from '../delegation';\nimport {\n createExecution,\n encodeExecutionCalldatas,\n ExecutionMode,\n} from '../executions';\nimport { getSmartAccountsEnvironment } from '../smartAccountsEnvironment';\nimport type { Call, PermissionContext } from '../types';\n\nexport type DelegatedCall = Call &\n OneOf<\n { permissionContext: PermissionContext; delegationManager: Hex } | object\n >;\n\nexport type SendTransactionWithDelegationParameters<\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n TChainOverride extends Chain | undefined = Chain | undefined,\n TRequest extends SendTransactionRequest<TChain, TChainOverride> =\n SendTransactionRequest<TChain, TChainOverride>,\n> = SendTransactionParameters<TChain, TAccount, TChainOverride, TRequest> & {\n permissionContext: PermissionContext;\n delegationManager: Hex;\n};\n\n/**\n * Sends a transaction using delegation to execute operations on behalf of another account.\n *\n * @param client - The wallet client to use for sending the transaction.\n * @param args - Transaction parameters with delegation details.\n * @returns Transaction hash of the executed transaction.\n */\nexport async function sendTransactionWithDelegationAction<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: WalletClient<Transport, TChain, TAccount>,\n args: SendTransactionWithDelegationParameters<TChain, TAccount>,\n) {\n trackSmartAccountsKitFunctionCall('sendTransactionWithDelegationAction', {\n chainId: client.chain?.id ?? null,\n });\n\n if (!args.to) {\n throw new Error(\n '`to` is required. `sendTransactionWithDelegation` cannot be used to deploy contracts.',\n );\n }\n\n // Validate DelegationManager address\n const chainId = client.chain?.id;\n if (!chainId) {\n throw new Error('Chain ID is not set');\n }\n\n const { DelegationManager: expectedDelegationManager } =\n getSmartAccountsEnvironment(chainId);\n if (!isAddressEqual(args.delegationManager, expectedDelegationManager)) {\n throw new Error(\n `Invalid DelegationManager: expected ${expectedDelegationManager} for chain ${chainId}, but got ${args.delegationManager}`,\n );\n }\n\n const executions = [\n createExecution({\n target: args.to,\n value: args.value,\n callData: args.data,\n }),\n ];\n\n const calldata = encodeFunctionData({\n abi: DelegationManager,\n functionName: 'redeemDelegations',\n args: [\n [encodeDelegations(args.permissionContext)],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([executions]),\n ],\n });\n\n const {\n value: _value,\n permissionContext: _permissionContext,\n delegationManager: _delegationManager,\n ...rest\n } = args;\n\n const hash = await client.sendTransaction({\n ...rest,\n to: args.delegationManager,\n data: calldata,\n } as unknown as SendTransactionParameters);\n\n return hash;\n}\n\nexport type SendUserOperationWithDelegationParameters<\n TAccount extends SmartAccount | undefined = SmartAccount | undefined,\n TAccountOverride extends SmartAccount | undefined = SmartAccount | undefined,\n> = SendUserOperationParameters<TAccount, TAccountOverride, DelegatedCall[]> & {\n dependencies?: { factory: Hex; factoryData: Hex }[];\n calls: DelegatedCall[];\n publicClient: PublicClient<Transport, Chain>;\n};\n\n/**\n * Broadcasts a User Operation with delegation to the Bundler.\n *\n * @param client - Client to use for sending the user operation.\n * @param parameters - Parameters for the user operation with delegation.\n * @returns The User Operation hash of the broadcasted operation.\n * @example\n * import { createBundlerClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const bundlerClient = createBundlerClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const userOpHash = await sendUserOperationWithDelegationAction(bundlerClient, {\n * account: bobSmartAccount,\n * calls: [\n * {\n * to: aliceCounterContractAddress,\n * data: encodeFunctionData({\n * abi: CounterMetadata.abi,\n * functionName: 'increment',\n * }),\n * value: 0n,\n * permissionContext: '0x...',\n * delegationManager: '0x...',\n * },\n * ],\n * dependencies: [{ factory: '0x...', factoryData: '0x...' }], // Optional: for deploying accounts\n * })\n */\nexport async function sendUserOperationWithDelegationAction<\n TAccount extends SmartAccount | undefined,\n TAccountOverride extends SmartAccount | undefined = undefined,\n>(\n client: BundlerClient<Transport, Chain | undefined, TAccount>,\n parameters: SendUserOperationWithDelegationParameters<\n TAccount,\n TAccountOverride\n >,\n) {\n trackSmartAccountsKitFunctionCall('sendUserOperationWithDelegationAction', {\n chainId: client.chain?.id ?? null,\n callCount: parameters.calls.length,\n hasDependencies: parameters.dependencies !== undefined,\n });\n\n if (parameters.dependencies) {\n const { publicClient } = parameters;\n\n const includedAccountKeys: Record<Hex, boolean> = {};\n\n const chainId = publicClient.chain?.id;\n\n if (!chainId) {\n throw new Error('Chain ID is not set');\n }\n\n const { SimpleFactory } = getSmartAccountsEnvironment(chainId);\n\n const uniqueDependencies = parameters.dependencies.filter((dependency) => {\n if (!isAddressEqual(dependency.factory, SimpleFactory)) {\n throw new Error(\n `Invalid dependency: ${dependency.factory} is not allowed.`,\n );\n }\n\n // ensure that factory calls are not duplicated\n const accountKey = concat([dependency.factory, dependency.factoryData]);\n const isDuplicate = includedAccountKeys[accountKey];\n\n includedAccountKeys[accountKey] = true;\n return !isDuplicate;\n });\n\n const factoryCalls = (\n await Promise.all(\n uniqueDependencies.map(async ({ factory, factoryData }) => {\n const isDeployed = await publicClient\n .call({\n to: factory,\n data: factoryData,\n })\n .then(() => false)\n .catch(() => true);\n\n if (isDeployed) {\n return undefined;\n }\n return {\n to: factory,\n value: 0n,\n data: factoryData,\n };\n }),\n )\n ).filter((call: Call | undefined) => call !== undefined) as Call[];\n\n parameters.calls = [\n ...(factoryCalls as DelegatedCall[]),\n ...parameters.calls,\n ];\n }\n\n parameters.calls = parameters.calls.map((call) => {\n if (!('permissionContext' in call)) {\n return call;\n }\n\n const { permissionContext } = call;\n if (!permissionContext) {\n return call;\n }\n\n return {\n ...call,\n permissionContext: encodeDelegations(permissionContext),\n };\n });\n\n return client.sendUserOperation(\n parameters as unknown as SendUserOperationParameters,\n );\n}\n","import type {\n Erc20TokenAllowancePermission as RpcErc20TokenAllowancePermission,\n Erc20TokenPeriodicPermission as RpcErc20TokenPeriodicPermission,\n Erc20TokenStreamPermission as RpcErc20TokenStreamPermission,\n Erc20TokenRevocationPermission as RpcErc20TokenRevocationPermission,\n NativeTokenAllowancePermission as RpcNativeTokenAllowancePermission,\n NativeTokenPeriodicPermission as RpcNativeTokenPeriodicPermission,\n NativeTokenStreamPermission as RpcNativeTokenStreamPermission,\n PermissionRequest,\n PermissionTypes as RpcPermissionTypes,\n Rule,\n TokenApprovalRevocationPermission as RpcTokenApprovalRevocationPermission,\n} from '@metamask/7715-permission-types';\nimport { getAddress, hexToNumber, isAddress, toHex } from 'viem';\nimport type { Hex } from 'viem';\n\nimport { isDefined, toHexOrThrow } from '../utils';\nimport type {\n Erc20TokenAllowancePermission,\n Erc20TokenPeriodicPermission,\n Erc20TokenRevocationPermission,\n Erc20TokenStreamPermission,\n GetGrantedExecutionPermissionsResult,\n GetSupportedExecutionPermissionsResult,\n NativeTokenAllowancePermission,\n NativeTokenPeriodicPermission,\n NativeTokenStreamPermission,\n PermissionRequestParameter,\n PermissionTypes as DeveloperPermissionTypes,\n RpcGetGrantedExecutionPermissionsResult,\n RpcGetSupportedExecutionPermissionsResult,\n TokenApprovalRevocationPermission,\n} from './erc7715Types';\n\n// =============================================================================\n// Developer → RPC (request formatting)\n// =============================================================================\n\n/**\n * Converts a developer permission request to RPC format for wallet submission.\n *\n * @param parameters the permission request parameters\n * @returns the permission request in RPC format\n */\nexport function permissionRequestToRpc(\n parameters: PermissionRequestParameter,\n): PermissionRequest<RpcPermissionTypes> {\n const { chainId, from, expiry, redeemer, payee } = parameters;\n\n const converter = getPermissionRequestToRpcConverter(\n parameters.permission.type,\n );\n\n const rules: Rule[] = [];\n if (isDefined(expiry)) {\n rules.push({\n type: 'expiry',\n data: {\n timestamp: expiry,\n },\n });\n }\n if (isDefined(redeemer)) {\n if (redeemer.length === 0) {\n throw new Error(\n 'Invalid redeemers: must specify at least one redeemer address',\n );\n }\n const addresses: Hex[] = [];\n for (const addr of redeemer) {\n if (!isAddress(addr)) {\n throw new Error('Invalid redeemers: must be a valid address');\n }\n addresses.push(getAddress(addr));\n }\n rules.push({\n type: 'redeemer',\n data: { addresses },\n });\n }\n if (isDefined(payee)) {\n if (payee.length === 0) {\n throw new Error(\n 'Invalid payees: must specify at least one payee address',\n );\n }\n const payeeAddresses: Hex[] = [];\n for (const addr of payee) {\n if (!isAddress(addr)) {\n throw new Error('Invalid payees: must be a valid address');\n }\n payeeAddresses.push(getAddress(addr));\n }\n rules.push({\n type: 'payee',\n data: { addresses: payeeAddresses },\n });\n }\n\n const optionalFields = {\n ...(from ? { from } : {}),\n };\n\n return {\n ...optionalFields,\n chainId: toHex(chainId),\n permission: converter(parameters.permission),\n to: parameters.to,\n rules,\n };\n}\n\ntype PermissionRequestToRpcConverter = (\n permission: DeveloperPermissionTypes,\n) => RpcPermissionTypes;\n\n/**\n * Get the permission request to RPC converter for the given permission type.\n *\n * @param permissionType the permission type\n * @returns the permission request to RPC converter for the given permission type\n */\nfunction getPermissionRequestToRpcConverter(\n permissionType: string,\n): PermissionRequestToRpcConverter {\n switch (permissionType) {\n case 'native-token-stream':\n return (permission) =>\n nativeTokenStreamPermissionToRpc(\n permission as NativeTokenStreamPermission,\n );\n case 'erc20-token-stream':\n return (permission) =>\n erc20TokenStreamPermissionToRpc(\n permission as Erc20TokenStreamPermission,\n );\n case 'native-token-periodic':\n return (permission) =>\n nativeTokenPeriodicPermissionToRpc(\n permission as NativeTokenPeriodicPermission,\n );\n case 'native-token-allowance':\n return (permission) =>\n nativeTokenAllowancePermissionToRpc(\n permission as NativeTokenAllowancePermission,\n );\n case 'erc20-token-periodic':\n return (permission) =>\n erc20TokenPeriodicPermissionToRpc(\n permission as Erc20TokenPeriodicPermission,\n );\n case 'erc20-token-allowance':\n return (permission) =>\n erc20TokenAllowancePermissionToRpc(\n permission as Erc20TokenAllowancePermission,\n );\n case 'erc20-token-revocation':\n return (permission) =>\n erc20TokenRevocationPermissionToRpc(\n permission as Erc20TokenRevocationPermission,\n );\n case 'token-approval-revocation':\n return (permission) =>\n tokenApprovalRevocationPermissionToRpc(\n permission as TokenApprovalRevocationPermission,\n );\n default:\n throw new Error(`Unsupported permission type: ${permissionType}`);\n }\n}\n\n/**\n * Convert native token stream permission to RPC format.\n *\n * @param permission the native token stream permission\n * @returns the native token stream permission in RPC format\n */\nfunction nativeTokenStreamPermissionToRpc(\n permission: NativeTokenStreamPermission,\n): RpcNativeTokenStreamPermission {\n const {\n data: {\n initialAmount,\n justification,\n maxAmount,\n startTime,\n amountPerSecond,\n },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(initialAmount) && {\n initialAmount: toHexOrThrow(initialAmount, 'initialAmount'),\n }),\n ...(isDefined(maxAmount) && {\n maxAmount: toHexOrThrow(maxAmount, 'maxAmount'),\n }),\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'native-token-stream',\n data: {\n amountPerSecond: toHexOrThrow(amountPerSecond, 'amountPerSecond'),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert ERC20 token stream permission to RPC format.\n *\n * @param permission the erc20 token stream permission\n * @returns the erc20 token stream permission in RPC format\n */\nfunction erc20TokenStreamPermissionToRpc(\n permission: Erc20TokenStreamPermission,\n): RpcErc20TokenStreamPermission {\n const {\n data: {\n tokenAddress,\n amountPerSecond,\n initialAmount,\n startTime,\n maxAmount,\n justification,\n },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(initialAmount) && {\n initialAmount: toHexOrThrow(initialAmount, 'initialAmount'),\n }),\n ...(isDefined(maxAmount) && {\n maxAmount: toHexOrThrow(maxAmount, 'maxAmount'),\n }),\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'erc20-token-stream',\n data: {\n tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),\n amountPerSecond: toHexOrThrow(amountPerSecond, 'amountPerSecond'),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert native token periodic permission to RPC format.\n *\n * @param permission the native token periodic permission\n * @returns the native token periodic permission in RPC format\n */\nfunction nativeTokenPeriodicPermissionToRpc(\n permission: NativeTokenPeriodicPermission,\n): RpcNativeTokenPeriodicPermission {\n const {\n data: { periodAmount, periodDuration, startTime, justification },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'native-token-periodic',\n data: {\n periodAmount: toHexOrThrow(periodAmount, 'periodAmount'),\n periodDuration: Number(periodDuration),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert ERC20 token periodic permission to RPC format.\n *\n * @param permission the erc20 token periodic permission\n * @returns the erc20 token periodic permission in RPC format\n */\nfunction erc20TokenPeriodicPermissionToRpc(\n permission: Erc20TokenPeriodicPermission,\n): RpcErc20TokenPeriodicPermission {\n const {\n data: {\n tokenAddress,\n periodAmount,\n periodDuration,\n startTime,\n justification,\n },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'erc20-token-periodic',\n data: {\n tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),\n periodAmount: toHexOrThrow(periodAmount, 'periodAmount'),\n periodDuration: Number(periodDuration),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert native token fixed allowance permission to RPC format.\n *\n * @param permission the native token fixed allowance permission\n * @returns the native token fixed allowance permission in RPC format\n */\nfunction nativeTokenAllowancePermissionToRpc(\n permission: NativeTokenAllowancePermission,\n): RpcNativeTokenAllowancePermission {\n const {\n data: { allowanceAmount, startTime, justification },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'native-token-allowance',\n data: {\n allowanceAmount: toHexOrThrow(allowanceAmount, 'allowanceAmount'),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert ERC-20 token fixed allowance permission to RPC format.\n *\n * @param permission the ERC-20 token fixed allowance permission\n * @returns the ERC-20 token fixed allowance permission in RPC format\n */\nfunction erc20TokenAllowancePermissionToRpc(\n permission: Erc20TokenAllowancePermission,\n): RpcErc20TokenAllowancePermission {\n const {\n data: { tokenAddress, allowanceAmount, startTime, justification },\n isAdjustmentAllowed,\n } = permission;\n\n const optionalFields = {\n ...(isDefined(startTime) && {\n startTime: Number(startTime),\n }),\n ...(justification ? { justification } : {}),\n };\n\n return {\n type: 'erc20-token-allowance',\n data: {\n tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),\n allowanceAmount: toHexOrThrow(allowanceAmount, 'allowanceAmount'),\n ...optionalFields,\n },\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert ERC20 token revocation permission to RPC format.\n *\n * @param permission the erc20 token revocation permission\n * @returns the erc20 token revocation permission in RPC format\n */\nfunction erc20TokenRevocationPermissionToRpc(\n permission: Erc20TokenRevocationPermission,\n): RpcErc20TokenRevocationPermission {\n const {\n data: { justification },\n isAdjustmentAllowed,\n } = permission;\n\n const data = {\n ...(justification ? { justification } : {}),\n };\n return {\n type: 'erc20-token-revocation',\n data,\n isAdjustmentAllowed,\n };\n}\n\n/**\n * Convert token approval revocation permission to RPC format.\n *\n * @param permission the token approval revocation permission\n * @returns the token approval revocation permission in RPC format\n */\nfunction tokenApprovalRevocationPermissionToRpc(\n permission: TokenApprovalRevocationPermission,\n): RpcTokenApprovalRevocationPermission {\n const {\n data: {\n erc20Approve,\n erc721Approve,\n erc721SetApprovalForAll,\n permit2Approve,\n permit2Lockdown,\n permit2InvalidateNonces,\n justification,\n },\n isAdjustmentAllowed,\n } = permission;\n\n const data = {\n erc20Approve,\n erc721Approve,\n erc721SetApprovalForAll,\n permit2Approve,\n permit2Lockdown,\n permit2InvalidateNonces,\n ...(justification ? { justification } : {}),\n };\n return {\n type: 'token-approval-revocation',\n data,\n isAdjustmentAllowed,\n };\n}\n\n// =============================================================================\n// RPC → Developer friendly types (response conversion)\n// =============================================================================\n\n/**\n * Converts RPC permission responses to developer-friendly types.\n * Converts chainId from hex to number, and token amounts from hex to bigint.\n *\n * @param result the RPC permission responses\n * @returns the developer-friendly permission responses\n */\nexport function permissionResponsesFromRpc(\n result: RpcGetGrantedExecutionPermissionsResult,\n): GetGrantedExecutionPermissionsResult {\n return result.map((permission) => ({\n ...permission,\n chainId: hexToNumber(permission.chainId),\n permission: permissionTypeFromRpc(permission.permission),\n rules: normalizeRulesFromRpc(permission.rules),\n }));\n}\n\n/**\n * Checksums addresses in `redeemer` and `payee` rules; other rules are returned unchanged.\n *\n * @param rules - Rules from the wallet RPC response.\n * @returns The same list with normalized addresses, or null/undefined if that was the input.\n */\nfunction normalizeRulesFromRpc(\n rules: Rule[] | null | undefined,\n): Rule[] | null | undefined {\n if (rules === undefined || rules === null) {\n return rules;\n }\n return rules.map((rule) => {\n if (rule.type !== 'redeemer' && rule.type !== 'payee') {\n return rule;\n }\n const rawAddresses = (rule.data as { addresses?: unknown } | undefined)\n ?.addresses;\n if (!Array.isArray(rawAddresses)) {\n return rule;\n }\n return {\n type: rule.type,\n data: {\n addresses: rawAddresses.map((addr) => getAddress(addr as Hex)),\n },\n };\n });\n}\n\n/**\n * Converts RPC permission type data to developer-friendly types.\n * Converts hex amount fields to bigint.\n *\n * @param permission the RPC permission\n * @returns the developer-friendly permission\n */\nexport function permissionTypeFromRpc(\n permission: RpcPermissionTypes,\n): DeveloperPermissionTypes {\n const convertedData: Record<string, unknown> = { ...permission.data };\n\n if ('amountPerSecond' in convertedData && convertedData.amountPerSecond) {\n convertedData.amountPerSecond = BigInt(\n convertedData.amountPerSecond as `0x${string}`,\n );\n }\n\n if ('periodAmount' in convertedData && convertedData.periodAmount) {\n convertedData.periodAmount = BigInt(\n convertedData.periodAmount as `0x${string}`,\n );\n }\n\n if ('initialAmount' in convertedData && convertedData.initialAmount) {\n convertedData.initialAmount = BigInt(\n convertedData.initialAmount as `0x${string}`,\n );\n }\n\n if ('maxAmount' in convertedData && convertedData.maxAmount) {\n convertedData.maxAmount = BigInt(convertedData.maxAmount as `0x${string}`);\n }\n\n if ('allowanceAmount' in convertedData && convertedData.allowanceAmount) {\n convertedData.allowanceAmount = BigInt(\n convertedData.allowanceAmount as `0x${string}`,\n );\n }\n\n return {\n ...permission,\n data: convertedData,\n } as DeveloperPermissionTypes;\n}\n\n/**\n * Converts RPC supported permissions result to developer-friendly types.\n * Converts chain IDs from hex to numbers.\n *\n * @param result the RPC supported permissions result\n * @returns the developer-friendly supported permissions result\n */\nexport function rpcSupportedPermissionsToDeveloper(\n result: RpcGetSupportedExecutionPermissionsResult,\n): GetSupportedExecutionPermissionsResult {\n const converted: GetSupportedExecutionPermissionsResult = {};\n\n for (const [permissionType, permissionInfo] of Object.entries(result)) {\n converted[permissionType] = {\n chainIds: permissionInfo.chainIds.map((chainId) => hexToNumber(chainId)),\n ruleTypes: permissionInfo.ruleTypes,\n };\n }\n\n return converted;\n}\n","import { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { permissionResponsesFromRpc } from './erc7715Mapping';\nimport type {\n GetGrantedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n} from './erc7715Types';\n\nexport type { GetGrantedExecutionPermissionsResult } from './erc7715Types';\n\n/**\n * Retrieves all previously granted execution permissions from the wallet according to EIP-7715 specification.\n *\n * @param client - The client to use for the request.\n * @returns A promise that resolves to an array of granted permission responses.\n * @description\n * This function queries the wallet for all granted permissions that are not yet revoked.\n * Each permission response includes the chain ID, address, signer, permission details,\n * context, and dependency information.\n * @example\n * ```typescript\n * const grantedPermissions = await erc7715GetGrantedExecutionPermissionsAction(client);\n * // Returns an array of PermissionResponse objects with user-friendly types\n * ```\n */\nexport async function erc7715GetGrantedExecutionPermissionsAction(\n client: MetaMaskExtensionClient,\n): Promise<GetGrantedExecutionPermissionsResult> {\n trackSmartAccountsKitFunctionCall(\n 'erc7715GetGrantedExecutionPermissionsAction',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n\n const result = await client.request(\n {\n method: 'wallet_getGrantedExecutionPermissions',\n params: [],\n },\n { retryCount: 0 },\n );\n\n if (!result) {\n throw new Error('Failed to get granted execution permissions');\n }\n\n return permissionResponsesFromRpc(result);\n}\n","import { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { rpcSupportedPermissionsToDeveloper } from './erc7715Mapping';\nimport type {\n GetSupportedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n} from './erc7715Types';\n\nexport type { GetSupportedExecutionPermissionsResult } from './erc7715Types';\n\n/**\n * Retrieves the supported execution permission types from the wallet according to EIP-7715 specification.\n *\n * @param client - The client to use for the request.\n * @returns A promise that resolves to a record of supported permission types with their chain IDs and rule types.\n * @description\n * This function queries the wallet for the permission types it supports.\n * The result is keyed by permission type and includes the supported chain IDs and rule types.\n * @example\n * ```typescript\n * const supported = await erc7715GetSupportedExecutionPermissionsAction(client);\n * // Returns:\n * // {\n * // \"native-token-allowance\": {\n * // \"chainIds\": [1, 137],\n * // \"ruleTypes\": [\"expiry\", \"redeemer\", \"payee\"]\n * // },\n * // \"erc20-token-allowance\": {\n * // \"chainIds\": [1],\n * // \"ruleTypes\": [\"expiry\"]\n * // }\n * // }\n * //\n * // Which strings appear in `ruleTypes` is defined by the wallet; when supported,\n * // `\"redeemer\"` indicates the wallet accepts a redeemer execution rule and\n * // `\"payee\"` indicates the wallet accepts a payee execution rule.\n * ```\n */\nexport async function erc7715GetSupportedExecutionPermissionsAction(\n client: MetaMaskExtensionClient,\n): Promise<GetSupportedExecutionPermissionsResult> {\n trackSmartAccountsKitFunctionCall(\n 'erc7715GetSupportedExecutionPermissionsAction',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n\n const result = await client.request(\n {\n method: 'wallet_getSupportedExecutionPermissions',\n params: [],\n },\n { retryCount: 0 },\n );\n\n if (!result) {\n throw new Error('Failed to get supported execution permissions');\n }\n\n return rpcSupportedPermissionsToDeveloper(result);\n}\n","import { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport {\n permissionRequestToRpc,\n permissionResponsesFromRpc,\n} from './erc7715Mapping';\nimport type {\n GetGrantedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n PermissionRequestParameter,\n} from './erc7715Types';\n\nexport type {\n GetGrantedExecutionPermissionsResult,\n GetSupportedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n MetaMaskExtensionSchema,\n SupportedPermissionInfo,\n PermissionTypes,\n PermissionRequestParameter,\n} from './erc7715Types';\n\n/**\n * Parameters for the RequestExecutionPermissions action.\n *\n * @template Signer - The type of the signer, either an Address or Account.\n */\nexport type RequestExecutionPermissionsParameters =\n PermissionRequestParameter[];\n\n/**\n * Return type for the request execution permissions action.\n */\nexport type RequestExecutionPermissionsReturnType =\n GetGrantedExecutionPermissionsResult;\n\n/**\n * Grants permissions according to EIP-7715 specification.\n *\n * @template Signer - The type of the signer, either an Address or Account.\n * @param client - The client to use for the request.\n * @param parameters - The permissions requests to grant.\n * @returns A promise that resolves to the permission responses.\n * @description\n * This function formats the permissions requests and invokes the wallet method to grant permissions.\n * It will throw an error if the permissions could not be granted.\n */\nexport async function erc7715RequestExecutionPermissionsAction(\n client: MetaMaskExtensionClient,\n parameters: RequestExecutionPermissionsParameters,\n): Promise<RequestExecutionPermissionsReturnType> {\n trackSmartAccountsKitFunctionCall(\n 'erc7715RequestExecutionPermissionsAction',\n {\n chainId: client.chain?.id ?? null,\n requestCount: parameters.length,\n },\n );\n const formattedPermissionRequest = parameters.map(permissionRequestToRpc);\n\n const result = await client.request(\n {\n method: 'wallet_requestExecutionPermissions',\n params: formattedPermissionRequest,\n },\n { retryCount: 0 },\n );\n\n if (!result) {\n throw new Error('Failed to grant permissions');\n }\n\n return permissionResponsesFromRpc(result);\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n Hex,\n Transport,\n WalletClient,\n} from 'viem';\nimport { BaseError } from 'viem';\nimport { parseAccount } from 'viem/accounts';\n\nimport { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport type { Caveats } from '../caveatBuilder';\nimport type { ScopeConfig } from '../caveatBuilder/scope';\nimport {\n ANY_BENEFICIARY,\n createDelegation,\n createOpenDelegation,\n decodeDelegations,\n encodeDelegations,\n} from '../delegation';\nimport type {\n Delegation,\n PermissionContext,\n SmartAccountsEnvironment,\n} from '../types';\nimport { signDelegation } from './signDelegation';\n\ntype BaseRedelegatePermissionContextParameters = {\n /** Account to sign the delegation with */\n account?: Account | Address;\n /** Environment configuration */\n environment: SmartAccountsEnvironment;\n /** The permission context to redelegate from (i.e., from ERC-7715 response) */\n permissionContext: PermissionContext;\n /** The chain ID for the signature (falls back to `client.chain.id`) */\n chainId?: number;\n /** Optional scope - if not provided, inherits from parent */\n scope?: ScopeConfig;\n /** Additional caveats to apply to the redelegation */\n caveats?: Caveats;\n /** Optional salt for uniqueness */\n salt?: Hex;\n};\n\nexport type RedelegatePermissionContextParameters =\n BaseRedelegatePermissionContextParameters & {\n /** The address of the delegate to redelegate to */\n to: Address;\n };\n\nexport type RedelegatePermissionContextOpenParameters =\n BaseRedelegatePermissionContextParameters;\n\nexport type RedelegatePermissionContextReturnType = {\n /** The signed delegation that was created */\n delegation: Delegation;\n /** The new permission context with the redelegation prepended (encoded) */\n permissionContext: Hex;\n};\n\ntype SigningClient<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n> = Client<Transport, TChain, TAccount> & {\n signTypedData: WalletClient['signTypedData'];\n};\n\n/**\n * Shared workflow for creating, signing and prepending a redelegation to a\n * permission context. The caller decides whether to produce a specific or open\n * redelegation by supplying the appropriate `unsignedDelegation`.\n *\n * @param client - Wallet client with signing capability.\n * @param options - Workflow options.\n * @param options.account - Account to sign the delegation with.\n * @param options.environment - Environment configuration.\n * @param options.delegations - The decoded delegation chain (leaf first).\n * @param options.unsignedDelegation - The new (unsigned) redelegation to prepend.\n * @param options.chainId - The chain ID for the signature.\n * @returns The signed delegation and updated, encoded permission context.\n */\nasync function signAndPrependRedelegation(\n client: SigningClient<Chain | undefined, Account | undefined>,\n options: {\n account: Account;\n environment: SmartAccountsEnvironment;\n delegations: Delegation[];\n unsignedDelegation: Delegation;\n chainId: number;\n },\n): Promise<RedelegatePermissionContextReturnType> {\n const { account, environment, delegations, unsignedDelegation, chainId } =\n options;\n\n const signature = await signDelegation(client, {\n account,\n delegation: unsignedDelegation,\n delegationManager: environment.DelegationManager,\n chainId,\n // Redelegations always inherit from a parent delegation (enforced by\n // `resolveRedelegationArgs`), so the parent's caveats provide the\n // restriction even when the redelegation itself adds no extra caveats.\n // This mirrors `resolveCaveats`, which also allows empty caveats in this\n // case.\n allowInsecureUnrestrictedDelegation: true,\n });\n\n const signedDelegation: Delegation = {\n ...unsignedDelegation,\n signature,\n };\n\n const newPermissionContext = encodeDelegations([\n signedDelegation,\n ...delegations,\n ]);\n\n return {\n delegation: signedDelegation,\n permissionContext: newPermissionContext,\n };\n}\n\n/**\n * Resolves and validates shared inputs used by both redelegation actions.\n *\n * @param client - Wallet client with signing capability.\n * @param parameters - The base redelegation parameters.\n * @returns The resolved account, decoded chain and parent (leaf) delegation.\n */\nfunction resolveRedelegationArgs<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: SigningClient<TChain, TAccount>,\n parameters: BaseRedelegatePermissionContextParameters,\n): {\n account: Account;\n delegations: Delegation[];\n parentDelegation: Delegation;\n from: Hex;\n} {\n const { account: accountParam = client.account, permissionContext } =\n parameters;\n\n if (!accountParam) {\n throw new BaseError('Account not found. Please provide an account.');\n }\n\n const account = parseAccount(accountParam);\n const delegations = decodeDelegations(permissionContext);\n const parentDelegation = delegations[0];\n\n if (!parentDelegation) {\n throw new BaseError(\n 'Permission context must contain at least one delegation',\n );\n }\n\n const isParentOpenDelegation =\n parentDelegation.delegate.toLowerCase() === ANY_BENEFICIARY.toLowerCase();\n\n const from = isParentOpenDelegation\n ? account.address\n : parentDelegation.delegate;\n\n return { account, delegations, parentDelegation, from };\n}\n\n/**\n * Creates a redelegation to a specific delegate from an existing permission\n * context and returns both the signed delegation and the updated permission\n * context.\n *\n * This action handles the complete redelegation workflow:\n * 1. Extracts the leaf delegation from the permission context\n * 2. Creates a new delegation inheriting from it\n * 3. Signs the new delegation\n * 4. Prepends it to the delegation chain\n * 5. Returns the encoded permission context\n *\n * Use {@link redelegatePermissionContextOpenAction} to create an open\n * redelegation\n * (delegate set to `ANY_BENEFICIARY`).\n *\n * @param client - Wallet client with signing capability.\n * @param parameters - Redelegation parameters.\n * @returns Object containing the signed delegation and new permission context.\n *\n * @example\n * ```ts\n * const result = await redelegatePermissionContextAction(walletClient, {\n * environment,\n * permissionContext: erc7715Response.context,\n * chainId: 11155111,\n * to: charlie.address,\n * caveats: [timestampCaveat],\n * });\n *\n * await client.sendUserOperationWithDelegation({\n * calls: [{\n * to: contractAddress,\n * data: callData,\n * permissionContext: result.permissionContext,\n * delegationManager: environment.DelegationManager,\n * }],\n * });\n * ```\n */\nexport async function redelegatePermissionContextAction<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: SigningClient<TChain, TAccount>,\n parameters: RedelegatePermissionContextParameters,\n): Promise<RedelegatePermissionContextReturnType> {\n const { environment, scope, caveats, salt, to } = parameters;\n const chainId = resolveChainId(client, parameters.chainId);\n\n const { account, delegations, parentDelegation, from } =\n resolveRedelegationArgs(client, parameters);\n\n trackSmartAccountsKitFunctionCall('redelegatePermissionContext', {\n chainId,\n hasScope: scope !== undefined,\n hasCaveats: caveats !== undefined,\n });\n\n const unsignedDelegation = createDelegation({\n environment,\n from,\n to,\n scope,\n caveats,\n parentDelegation,\n salt,\n });\n\n return signAndPrependRedelegation(client, {\n account,\n environment,\n delegations,\n unsignedDelegation,\n chainId,\n });\n}\n\n/**\n * Creates an open redelegation (delegate set to `ANY_BENEFICIARY`) from an\n * existing permission context and returns both the signed delegation and the\n * updated permission context.\n *\n * Use {@link redelegatePermissionContextAction} when you want to delegate to a\n * specific address.\n *\n * @param client - Wallet client with signing capability.\n * @param parameters - Open redelegation parameters.\n * @returns Object containing the signed delegation and new permission context.\n *\n * @example\n * ```ts\n * const result = await redelegatePermissionContextOpenAction(walletClient, {\n * environment,\n * permissionContext: erc7715Response.context,\n * chainId: 11155111,\n * caveats: [limitedCallsCaveat],\n * });\n * ```\n */\nexport async function redelegatePermissionContextOpenAction<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: SigningClient<TChain, TAccount>,\n parameters: RedelegatePermissionContextOpenParameters,\n): Promise<RedelegatePermissionContextReturnType> {\n const { environment, scope, caveats, salt } = parameters;\n const chainId = resolveChainId(client, parameters.chainId);\n\n const { account, delegations, parentDelegation, from } =\n resolveRedelegationArgs(client, parameters);\n\n trackSmartAccountsKitFunctionCall('redelegatePermissionContextOpen', {\n chainId,\n hasScope: scope !== undefined,\n hasCaveats: caveats !== undefined,\n });\n\n const unsignedDelegation = createOpenDelegation({\n environment,\n from,\n scope,\n caveats,\n parentDelegation,\n salt,\n });\n\n return signAndPrependRedelegation(client, {\n account,\n environment,\n delegations,\n unsignedDelegation,\n chainId,\n });\n}\n\n/**\n * Resolves the chain id, falling back to the client's configured chain.\n *\n * @param client - The client to read the chain id from.\n * @param client.chain - The client's configured chain.\n * @param chainId - The explicit chain id, if provided.\n * @returns The resolved chain id.\n */\nfunction resolveChainId(\n client: { chain?: { id: number } | undefined },\n chainId: number | undefined,\n): number {\n if (chainId !== undefined) {\n return chainId;\n }\n if (!client.chain?.id) {\n throw new BaseError(\n 'Chain ID is required. Either provide it in parameters or configure the client with a chain.',\n );\n }\n return client.chain.id;\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n Hex,\n Transport,\n WalletClient,\n} from 'viem';\nimport { BaseError } from 'viem';\nimport { parseAccount } from 'viem/accounts';\n\nimport { prepareSignDelegationTypedData } from '../delegation';\nimport type { Delegation } from '../types';\n\nexport type SignDelegationParameters = {\n /** Account to sign with */\n account?: Account | Address;\n /** The delegation to sign */\n delegation: Omit<Delegation, 'signature'>;\n /** The address of the delegation manager contract */\n delegationManager: Address;\n /** The chain ID for the signature */\n chainId: number;\n /** The name of the contract */\n name?: string;\n /** The version of the contract */\n version?: string;\n /** Whether to allow insecure unrestricted delegation */\n allowInsecureUnrestrictedDelegation?: boolean;\n};\n\nexport type SignDelegationReturnType = Hex;\n\n/**\n * Signs a delegation using a wallet client.\n *\n * @param client - The wallet client to use for signing.\n * @param parameters - The parameters for signing the delegation.\n * @returns The signature of the delegation.\n * @example\n * ```ts\n * const signature = await signDelegation(walletClient, {\n * delegation: {\n * delegate: '0x...',\n * delegator: '0x...',\n * authority: '0x...',\n * caveats: [],\n * salt: '0x'\n * },\n * delegationManager: '0x...',\n * chainId: 1\n * });\n * ```\n */\nexport async function signDelegation<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: Client<Transport, TChain, TAccount> & {\n signTypedData: WalletClient['signTypedData'];\n },\n parameters: SignDelegationParameters,\n): Promise<SignDelegationReturnType> {\n const {\n account: accountParam = client.account,\n delegation,\n delegationManager,\n chainId,\n name = 'DelegationManager',\n version = '1',\n allowInsecureUnrestrictedDelegation = false,\n } = parameters;\n\n if (!accountParam) {\n throw new BaseError('Account not found. Please provide an account.');\n }\n\n const account = parseAccount(accountParam);\n\n const typedData = prepareSignDelegationTypedData({\n delegation,\n delegationManager,\n chainId,\n name,\n version,\n allowInsecureUnrestrictedDelegation,\n });\n\n return client.signTypedData({\n account,\n ...typedData,\n });\n}\n\n/**\n * Creates a sign delegation action that can be used to extend a wallet client.\n *\n * @returns A function that can be used with wallet client extend method.\n * @example\n * ```ts\n * const walletClient = createWalletClient({\n * chain: mainnet,\n * transport: http()\n * }).extend(signDelegationActions());\n * ```\n */\nexport function signDelegationActions() {\n return <\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n >(\n client: Client<Transport, TChain, TAccount> & {\n signTypedData: WalletClient['signTypedData'];\n },\n ) => ({\n signDelegation: async (\n parameters: Omit<SignDelegationParameters, 'chainId'> & {\n chainId?: number;\n },\n ) =>\n signDelegation(client, {\n chainId:\n parameters.chainId ??\n (() => {\n if (!client.chain?.id) {\n throw new BaseError(\n 'Chain ID is required. Either provide it in parameters or configure the client with a chain.',\n );\n }\n return client.chain.id;\n })(),\n ...parameters,\n }),\n });\n}\n","import type { Address, Hex, Client } from 'viem';\n\nimport { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { hashDelegation } from '../delegation';\nimport * as ERC20PeriodTransferEnforcer from '../DelegationFramework/ERC20PeriodTransferEnforcer';\nimport * as ERC20StreamingEnforcer from '../DelegationFramework/ERC20StreamingEnforcer';\nimport * as MultiTokenPeriodEnforcer from '../DelegationFramework/MultiTokenPeriodEnforcer';\nimport * as NativeTokenPeriodTransferEnforcer from '../DelegationFramework/NativeTokenPeriodTransferEnforcer';\nimport * as NativeTokenStreamingEnforcer from '../DelegationFramework/NativeTokenStreamingEnforcer';\nimport type { SmartAccountsEnvironment, Delegation } from '../types';\n\n/**\n * Parameters for all caveat enforcer actions.\n */\nexport type CaveatEnforcerParams = {\n delegation: Delegation;\n};\n\n/**\n * Return type for period-based transfer enforcers\n */\nexport type PeriodTransferResult = {\n availableAmount: bigint;\n isNewPeriod: boolean;\n currentPeriod: bigint;\n};\n\n/**\n * Return type for streaming enforcers\n */\nexport type StreamingResult = {\n availableAmount: bigint;\n};\n\n/**\n * Finds a caveat that matches the specified enforcer address.\n *\n * @param config - The configuration object.\n * @param config.delegation - The delegation to search.\n * @param config.enforcerAddress - The enforcer address to match.\n * @param config.enforcerName - The name of the enforcer.\n * @returns The matching caveat.\n * @throws Error if no matching caveat is found.\n * @throws Error if multiple matching caveats are found.\n */\nfunction findMatchingCaveat({\n delegation,\n enforcerAddress,\n enforcerName,\n}: {\n delegation: Delegation;\n enforcerAddress: Address;\n enforcerName: keyof SmartAccountsEnvironment['caveatEnforcers'];\n}): { terms: Hex; args: Hex } {\n const matchingCaveats = delegation.caveats.filter(\n (caveat) => caveat.enforcer.toLowerCase() === enforcerAddress.toLowerCase(),\n );\n\n if (matchingCaveats.length === 0) {\n throw new Error(`No caveat found with enforcer matching ${enforcerName}`);\n }\n\n if (matchingCaveats.length > 1) {\n throw new Error(\n `Multiple caveats found with enforcer matching ${enforcerName}`,\n );\n }\n\n const [{ terms, args }] = matchingCaveats as unknown as [\n { terms: Hex; args: Hex },\n ];\n\n return {\n terms,\n args,\n };\n}\n\n/**\n * Gets the delegation manager address from environment.\n *\n * @param environment - The SmartAccountsEnvironment.\n * @returns The delegation manager address.\n */\nfunction getDelegationManager(environment: SmartAccountsEnvironment): Address {\n if (!environment.DelegationManager) {\n throw new Error('Delegation manager address not found');\n }\n\n return environment.DelegationManager;\n}\n\n/**\n * Gets the enforcer address from environment.\n *\n * @param config - The configuration object.\n * @param config.enforcerName - The name of the enforcer.\n * @param config.environment - The SmartAccountsEnvironment.\n * @returns The enforcer address.\n */\nfunction getEnforcerAddress({\n enforcerName,\n environment,\n}: {\n enforcerName: keyof SmartAccountsEnvironment['caveatEnforcers'];\n environment: SmartAccountsEnvironment;\n}): Address {\n const enforcerAddress = environment.caveatEnforcers[enforcerName];\n if (!enforcerAddress) {\n throw new Error(`${enforcerName} not found in environment`);\n }\n\n return enforcerAddress;\n}\n\n/**\n * Get available amount for ERC20 period transfer enforcer.\n *\n * @param client - The viem client.\n * @param environment - The SmartAccountsEnvironment.\n * @param params - The parameters for the ERC20 period transfer enforcer.\n * @returns Promise resolving to the period transfer result.\n */\nexport async function getErc20PeriodTransferEnforcerAvailableAmount(\n client: Client,\n environment: SmartAccountsEnvironment,\n params: CaveatEnforcerParams,\n): Promise<PeriodTransferResult> {\n trackSmartAccountsKitFunctionCall(\n 'getErc20PeriodTransferEnforcerAvailableAmount',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n const enforcerName = 'ERC20PeriodTransferEnforcer';\n\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = hashDelegation(params.delegation);\n const { terms } = findMatchingCaveat({\n delegation: params.delegation,\n enforcerAddress,\n enforcerName,\n });\n\n return ERC20PeriodTransferEnforcer.read.getAvailableAmount({\n client,\n contractAddress: enforcerAddress,\n delegationHash,\n delegationManager,\n terms,\n });\n}\n\n/**\n * Get available amount for ERC20 streaming enforcer.\n *\n * @param client - The viem client.\n * @param environment - The SmartAccountsEnvironment.\n * @param params - The parameters for the ERC20 streaming enforcer.\n * @returns Promise resolving to the streaming result.\n */\nexport async function getErc20StreamingEnforcerAvailableAmount(\n client: Client,\n environment: SmartAccountsEnvironment,\n params: CaveatEnforcerParams,\n): Promise<StreamingResult> {\n trackSmartAccountsKitFunctionCall(\n 'getErc20StreamingEnforcerAvailableAmount',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n const enforcerName = 'ERC20StreamingEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = hashDelegation(params.delegation);\n const { terms } = findMatchingCaveat({\n delegation: params.delegation,\n enforcerAddress,\n enforcerName,\n });\n\n return ERC20StreamingEnforcer.read.getAvailableAmount({\n client,\n contractAddress: enforcerAddress,\n delegationManager,\n delegationHash,\n terms,\n });\n}\n\n/**\n * Get available amount for multi-token period enforcer.\n *\n * @param client - The viem client.\n * @param environment - The SmartAccountsEnvironment.\n * @param params - The parameters for the multi-token period enforcer.\n * @returns Promise resolving to the period transfer result.\n */\nexport async function getMultiTokenPeriodEnforcerAvailableAmount(\n client: Client,\n environment: SmartAccountsEnvironment,\n params: CaveatEnforcerParams,\n): Promise<PeriodTransferResult> {\n trackSmartAccountsKitFunctionCall(\n 'getMultiTokenPeriodEnforcerAvailableAmount',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n const enforcerName = 'MultiTokenPeriodEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = hashDelegation(params.delegation);\n const { terms, args } = findMatchingCaveat({\n delegation: params.delegation,\n enforcerAddress,\n enforcerName,\n });\n\n return MultiTokenPeriodEnforcer.read.getAvailableAmount({\n client,\n contractAddress: enforcerAddress,\n delegationHash,\n delegationManager,\n terms,\n args,\n });\n}\n\n/**\n * Get available amount for native token period transfer enforcer.\n *\n * @param client - The viem client.\n * @param environment - The SmartAccountsEnvironment.\n * @param params - The parameters for the native token period transfer enforcer.\n * @returns Promise resolving to the period transfer result.\n */\nexport async function getNativeTokenPeriodTransferEnforcerAvailableAmount(\n client: Client,\n environment: SmartAccountsEnvironment,\n params: CaveatEnforcerParams,\n): Promise<PeriodTransferResult> {\n trackSmartAccountsKitFunctionCall(\n 'getNativeTokenPeriodTransferEnforcerAvailableAmount',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n const enforcerName = 'NativeTokenPeriodTransferEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = hashDelegation(params.delegation);\n const { terms } = findMatchingCaveat({\n delegation: params.delegation,\n enforcerAddress,\n enforcerName,\n });\n\n return NativeTokenPeriodTransferEnforcer.read.getAvailableAmount({\n client,\n contractAddress: enforcerAddress,\n delegationHash,\n delegationManager,\n terms,\n });\n}\n\n/**\n * Get available amount for native token streaming enforcer.\n *\n * @param client - The viem client.\n * @param environment - The SmartAccountsEnvironment.\n * @param params - The parameters for the native token streaming enforcer.\n * @returns Promise resolving to the streaming result.\n */\nexport async function getNativeTokenStreamingEnforcerAvailableAmount(\n client: Client,\n environment: SmartAccountsEnvironment,\n params: CaveatEnforcerParams,\n): Promise<StreamingResult> {\n trackSmartAccountsKitFunctionCall(\n 'getNativeTokenStreamingEnforcerAvailableAmount',\n {\n chainId: client.chain?.id ?? null,\n },\n );\n const enforcerName = 'NativeTokenStreamingEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = hashDelegation(params.delegation);\n const { terms } = findMatchingCaveat({\n delegation: params.delegation,\n enforcerAddress,\n enforcerName,\n });\n\n return NativeTokenStreamingEnforcer.read.getAvailableAmount({\n client,\n contractAddress: enforcerAddress,\n delegationManager,\n delegationHash,\n terms,\n });\n}\n\n/**\n * Caveat enforcer actions for extending viem clients.\n *\n * @param params - The parameters object.\n * @param params.environment - The SmartAccountsEnvironment.\n * @returns A function that takes a client and returns the client extension with caveat enforcer actions.\n */\nexport const caveatEnforcerActions =\n ({ environment }: { environment: SmartAccountsEnvironment }) =>\n (client: Client) => ({\n /**\n * Get available amount for ERC20 period transfer enforcer.\n *\n * @param params - The parameters for the ERC20 period transfer enforcer.\n * @returns Promise resolving to the period transfer result.\n */\n getErc20PeriodTransferEnforcerAvailableAmount: async (\n params: CaveatEnforcerParams,\n ): Promise<PeriodTransferResult> => {\n return getErc20PeriodTransferEnforcerAvailableAmount(\n client,\n environment,\n params,\n );\n },\n\n /**\n * Get available amount for ERC20 streaming enforcer.\n *\n * @param params - The parameters for the ERC20 streaming enforcer.\n * @returns Promise resolving to the streaming result.\n */\n getErc20StreamingEnforcerAvailableAmount: async (\n params: CaveatEnforcerParams,\n ): Promise<StreamingResult> => {\n return getErc20StreamingEnforcerAvailableAmount(\n client,\n environment,\n params,\n );\n },\n\n /**\n * Get available amount for multi-token period enforcer.\n *\n * @param params - The parameters for the multi-token period enforcer.\n * @returns Promise resolving to the period transfer result.\n */\n getMultiTokenPeriodEnforcerAvailableAmount: async (\n params: CaveatEnforcerParams,\n ): Promise<PeriodTransferResult> => {\n return getMultiTokenPeriodEnforcerAvailableAmount(\n client,\n environment,\n params,\n );\n },\n\n /**\n * Get available amount for native token period transfer enforcer.\n *\n * @param params - The parameters for the native token period transfer enforcer.\n * @returns Promise resolving to the period transfer result.\n */\n getNativeTokenPeriodTransferEnforcerAvailableAmount: async (\n params: CaveatEnforcerParams,\n ): Promise<PeriodTransferResult> => {\n return getNativeTokenPeriodTransferEnforcerAvailableAmount(\n client,\n environment,\n params,\n );\n },\n\n /**\n * Get available amount for native token streaming enforcer.\n *\n * @param params - The parameters for the native token streaming enforcer.\n * @returns Promise resolving to the streaming result.\n */\n getNativeTokenStreamingEnforcerAvailableAmount: async (\n params: CaveatEnforcerParams,\n ): Promise<StreamingResult> => {\n return getNativeTokenStreamingEnforcerAvailableAmount(\n client,\n environment,\n params,\n );\n },\n });\n","import type { Client, Address, Hex } from 'viem';\nimport { isAddressEqual } from 'viem';\nimport { getCode } from 'viem/actions';\n\nimport type { SmartAccountsEnvironment } from '../types';\n\n// EIP-7702 delegation prefix (0xef0100)\nconst DELEGATION_PREFIX = '0xef0100' as const;\n\n/**\n * Parameters for checking if an account is delegated to the EIP-7702 implementation.\n */\nexport type IsValid7702ImplementationParameters = {\n /** The client to use for the query. */\n client: Client;\n /** The address to check for proper delegation. */\n accountAddress: Address;\n /** The SmartAccountsEnvironment containing contract addresses. */\n environment: SmartAccountsEnvironment;\n};\n\n/**\n * Extracts the delegated contract address from EIP-7702 delegation code.\n *\n * @param code - The code returned from getCode for a delegated account.\n * @returns The delegated contract address or null if not a valid delegation.\n */\nfunction extractDelegatedAddress(code: Hex | undefined): Address | null {\n if (code?.length !== 48) {\n // 0x (2 chars) + ef0100 (6 chars) + address (40 chars) = 48 chars\n return null;\n }\n\n if (!code.toLowerCase().startsWith(DELEGATION_PREFIX.toLowerCase())) {\n return null;\n }\n\n // Extract the 20-byte address after the delegation prefix\n const addressHex = code.slice(8); // Remove '0xef0100' prefix (8 chars)\n return `0x${addressHex}`;\n}\n\n/**\n * Checks if an account is properly delegated to the EIP-7702 implementation.\n *\n * This function validates EIP-7702 delegations by checking if the EOA has a 7702\n * contract assigned to it and comparing the delegated address against the 7702\n * implementation found in the environment.\n *\n * @param params - The parameters for checking the delegation.\n * @param params.client - The client to use for the query.\n * @param params.accountAddress - The address to check for proper delegation.\n * @param params.environment - The SmartAccountsEnvironment containing contract addresses.\n * @returns A promise that resolves to true if the account is properly delegated to the 7702 implementation, false otherwise.\n * @example\n * ```typescript\n * const isValid = await isValid7702Implementation({\n * client: publicClient,\n * accountAddress: '0x...',\n * environment: smartAccountEnvironment,\n * });\n *\n * if (isValid) {\n * console.log('Account is properly delegated to EIP-7702 implementation');\n * } else {\n * console.log('Account is not properly delegated');\n * }\n * ```\n */\nexport async function isValid7702Implementation({\n client,\n accountAddress,\n environment,\n}: IsValid7702ImplementationParameters): Promise<boolean> {\n try {\n // Get the code at the account address\n const code = await getCode(client, {\n address: accountAddress,\n });\n\n // Extract the delegated contract address from the EIP-7702 delegation code\n const delegatedAddress = extractDelegatedAddress(code);\n\n // If no valid delegation found, return false\n if (!delegatedAddress) {\n return false;\n }\n\n // Compare the delegated address with the 7702 implementation in the environment\n const expectedImplementation =\n environment.implementations.EIP7702StatelessDeleGatorImpl;\n if (!expectedImplementation) {\n return false;\n }\n\n return isAddressEqual(delegatedAddress, expectedImplementation);\n } catch {\n // If the call fails (e.g., no code at address, network error),\n // then it's not properly delegated to our implementation\n return false;\n }\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n Hex,\n Transport,\n WalletClient,\n} from 'viem';\nimport { BaseError } from 'viem';\nimport { parseAccount } from 'viem/accounts';\n\nimport { prepareSignUserOperationTypedData } from '../userOp';\nimport type { UserOperationV07 } from '../userOp';\n\nexport type SignUserOperationParameters = {\n /** Account to sign with */\n account?: Account | Address;\n /** The user operation to sign */\n userOperation: Omit<UserOperationV07, 'signature'>;\n /** The entry point contract address */\n entryPoint: { address: Address };\n /** The chain ID that the entry point is deployed on */\n chainId: number;\n /** The address of the smart account */\n address: Address;\n /** The name of the domain of the implementation contract */\n name: 'HybridDeleGator' | 'MultiSigDeleGator';\n /** The version of the domain of the implementation contract */\n version?: string;\n};\n\nexport type SignUserOperationReturnType = Hex;\n\n/**\n * Signs a user operation using a wallet client.\n *\n * @param client - The wallet client to use for signing.\n * @param parameters - The parameters for signing the user operation.\n * @returns The signature of the user operation.\n * @example\n * ```ts\n * const signature = await signUserOperation(walletClient, {\n * userOperation: {\n * sender: '0x...',\n * nonce: 0n,\n * callData: '0x',\n * callGasLimit: 1000000n,\n * verificationGasLimit: 1000000n,\n * preVerificationGas: 21000n,\n * maxFeePerGas: 1000000000n,\n * maxPriorityFeePerGas: 1000000000n\n * },\n * entryPoint: { address: '0x...' },\n * chainId: 1,\n * address: '0x...',\n * name: 'HybridDeleGator'\n * });\n * ```\n */\nexport async function signUserOperation<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n>(\n client: Client<Transport, TChain, TAccount> & {\n signTypedData: WalletClient['signTypedData'];\n },\n parameters: SignUserOperationParameters,\n): Promise<SignUserOperationReturnType> {\n const {\n account: accountParam = client.account,\n userOperation,\n entryPoint,\n chainId,\n name,\n address,\n version = '1',\n } = parameters;\n\n if (!accountParam) {\n throw new BaseError('Account not found. Please provide an account.');\n }\n\n const account = parseAccount(accountParam);\n\n const typedData = prepareSignUserOperationTypedData({\n userOperation,\n entryPoint,\n chainId,\n name,\n address,\n version,\n });\n\n return client.signTypedData({\n account,\n ...typedData,\n });\n}\n\n/**\n * Creates a sign user operation action that can be used to extend a wallet client.\n *\n * @returns A function that can be used with wallet client extend method.\n * @example\n * ```ts\n * const walletClient = createWalletClient({\n * chain: mainnet,\n * transport: http()\n * }).extend(signUserOperationActions());\n * ```\n */\nexport function signUserOperationActions() {\n return <\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n >(\n client: Client<Transport, TChain, TAccount> & {\n signTypedData: WalletClient['signTypedData'];\n },\n ) => ({\n signUserOperation: async (\n parameters: Omit<SignUserOperationParameters, 'chainId'> & {\n chainId?: number;\n },\n ) =>\n signUserOperation(client, {\n chainId:\n parameters.chainId ??\n (() => {\n if (!client.chain?.id) {\n throw new BaseError(\n 'Chain ID is required. Either provide it in parameters or configure the client with a chain.',\n );\n }\n return client.chain.id;\n })(),\n ...parameters,\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,yBAAyB;AAYlC,SAAS,QAAQ,oBAAoB,sBAAsB;AAwC3D,eAAsB,oCAIpB,QACA,MACA;AACA,oCAAkC,uCAAuC;AAAA,IACvE,SAAS,OAAO,OAAO,MAAM;AAAA,EAC/B,CAAC;AAED,MAAI,CAAC,KAAK,IAAI;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAGA,QAAM,UAAU,OAAO,OAAO;AAC9B,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,QAAM,EAAE,mBAAm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ACF;AAyEO,IAAM,uBAAuB,MAAM,CAAC,YAA0B;AAAA,EACnE,+BAA+B,OAC7B,SACG,oCAAoC,QAAQ,IAAI;AAAA,EACrD,6BAA6B,OAC3B,eACG,kCAAkC,QAAQ,UAAU;AAAA,EACzD,iCAAiC,OAC/B,eACG,sCAAsC,QAAQ,UAAU;AAC/D;AA6BO,IAAM,wBAAwB,MAAM,CAAC,YAAoB;AAAA,EAC9D,iCAAiC,OAC/B,SACG,sCAAsC,QAAyB,IAAI;AAC1E;","names":["BaseError","parseAccount","BaseError","parseAccount","read_exports","isAddressEqual","BaseError","parseAccount","BaseError","parseAccount"]}
@@ -14,20 +14,20 @@
14
14
 
15
15
 
16
16
 
17
- var _chunk4GOGI2TAcjs = require('../chunk-4GOGI2TA.cjs');
17
+ var _chunk7GIUS6HDcjs = require('../chunk-7GIUS6HD.cjs');
18
18
 
19
19
 
20
20
 
21
21
 
22
22
 
23
23
 
24
- var _chunkYPUEM6YVcjs = require('../chunk-YPUEM6YV.cjs');
24
+ var _chunkF7R7HDEYcjs = require('../chunk-F7R7HDEY.cjs');
25
25
 
26
26
 
27
27
 
28
28
 
29
- var _chunk32RDDE5Ncjs = require('../chunk-32RDDE5N.cjs');
30
- require('../chunk-GHGCGV3C.cjs');
29
+ var _chunkTESSVINEcjs = require('../chunk-TESSVINE.cjs');
30
+ require('../chunk-4PCXDGUF.cjs');
31
31
 
32
32
 
33
33
 
@@ -52,5 +52,5 @@ require('../chunk-GHGCGV3C.cjs');
52
52
 
53
53
 
54
54
 
55
- exports.DeleGatorCore = _chunk4GOGI2TAcjs.DeleGatorCore_exports; exports.DelegationManager = _chunk4GOGI2TAcjs.DelegationManager_exports; exports.EIP712 = _chunk4GOGI2TAcjs.EIP712_exports; exports.ERC20PeriodTransferEnforcer = _chunkYPUEM6YVcjs.ERC20PeriodTransferEnforcer_exports; exports.ERC20StreamingEnforcer = _chunkYPUEM6YVcjs.ERC20StreamingEnforcer_exports; exports.ERC20TransferAmountEnforcer = _chunk4GOGI2TAcjs.ERC20TransferAmountEnforcer_exports; exports.EntryPoint = _chunk4GOGI2TAcjs.EntryPoint_exports; exports.HybridDeleGator = _chunk4GOGI2TAcjs.HybridDeleGator_exports; exports.IdEnforcer = _chunk4GOGI2TAcjs.IdEnforcer_exports; exports.LimitedCallsEnforcer = _chunk4GOGI2TAcjs.LimitedCallsEnforcer_exports; exports.MultiSigDeleGator = _chunk4GOGI2TAcjs.MultiSigDeleGator_exports; exports.MultiTokenPeriodEnforcer = _chunkYPUEM6YVcjs.MultiTokenPeriodEnforcer_exports; exports.NativeTokenPeriodTransferEnforcer = _chunkYPUEM6YVcjs.NativeTokenPeriodTransferEnforcer_exports; exports.NativeTokenStreamingEnforcer = _chunkYPUEM6YVcjs.NativeTokenStreamingEnforcer_exports; exports.NativeTokenTransferAmountEnforcer = _chunk4GOGI2TAcjs.NativeTokenTransferAmountEnforcer_exports; exports.NonceEnforcer = _chunk4GOGI2TAcjs.NonceEnforcer_exports; exports.Ownable2Step = _chunk4GOGI2TAcjs.Ownable2Step_exports; exports.Pausable = _chunk4GOGI2TAcjs.Pausable_exports; exports.SimpleFactory = _chunk4GOGI2TAcjs.SimpleFactory_exports; exports.SpecificActionERC20TransferBatchEnforcer = _chunk4GOGI2TAcjs.SpecificActionERC20TransferBatchEnforcer_exports; exports.encodeProxyCreationCode = _chunk32RDDE5Ncjs.encodeProxyCreationCode; exports.isContractDeployed = _chunk32RDDE5Ncjs.isContractDeployed; exports.isImplementationExpected = _chunk32RDDE5Ncjs.isImplementationExpected;
55
+ exports.DeleGatorCore = _chunk7GIUS6HDcjs.DeleGatorCore_exports; exports.DelegationManager = _chunk7GIUS6HDcjs.DelegationManager_exports; exports.EIP712 = _chunk7GIUS6HDcjs.EIP712_exports; exports.ERC20PeriodTransferEnforcer = _chunkF7R7HDEYcjs.ERC20PeriodTransferEnforcer_exports; exports.ERC20StreamingEnforcer = _chunkF7R7HDEYcjs.ERC20StreamingEnforcer_exports; exports.ERC20TransferAmountEnforcer = _chunk7GIUS6HDcjs.ERC20TransferAmountEnforcer_exports; exports.EntryPoint = _chunk7GIUS6HDcjs.EntryPoint_exports; exports.HybridDeleGator = _chunk7GIUS6HDcjs.HybridDeleGator_exports; exports.IdEnforcer = _chunk7GIUS6HDcjs.IdEnforcer_exports; exports.LimitedCallsEnforcer = _chunk7GIUS6HDcjs.LimitedCallsEnforcer_exports; exports.MultiSigDeleGator = _chunk7GIUS6HDcjs.MultiSigDeleGator_exports; exports.MultiTokenPeriodEnforcer = _chunkF7R7HDEYcjs.MultiTokenPeriodEnforcer_exports; exports.NativeTokenPeriodTransferEnforcer = _chunkF7R7HDEYcjs.NativeTokenPeriodTransferEnforcer_exports; exports.NativeTokenStreamingEnforcer = _chunkF7R7HDEYcjs.NativeTokenStreamingEnforcer_exports; exports.NativeTokenTransferAmountEnforcer = _chunk7GIUS6HDcjs.NativeTokenTransferAmountEnforcer_exports; exports.NonceEnforcer = _chunk7GIUS6HDcjs.NonceEnforcer_exports; exports.Ownable2Step = _chunk7GIUS6HDcjs.Ownable2Step_exports; exports.Pausable = _chunk7GIUS6HDcjs.Pausable_exports; exports.SimpleFactory = _chunk7GIUS6HDcjs.SimpleFactory_exports; exports.SpecificActionERC20TransferBatchEnforcer = _chunk7GIUS6HDcjs.SpecificActionERC20TransferBatchEnforcer_exports; exports.encodeProxyCreationCode = _chunkTESSVINEcjs.encodeProxyCreationCode; exports.isContractDeployed = _chunkTESSVINEcjs.isContractDeployed; exports.isImplementationExpected = _chunkTESSVINEcjs.isImplementationExpected;
56
56
  //# sourceMappingURL=index.cjs.map
@@ -14,20 +14,20 @@ import {
14
14
  Pausable_exports,
15
15
  SimpleFactory_exports,
16
16
  SpecificActionERC20TransferBatchEnforcer_exports
17
- } from "../chunk-IERUQUKJ.mjs";
17
+ } from "../chunk-RDTAD64U.mjs";
18
18
  import {
19
19
  ERC20PeriodTransferEnforcer_exports,
20
20
  ERC20StreamingEnforcer_exports,
21
21
  MultiTokenPeriodEnforcer_exports,
22
22
  NativeTokenPeriodTransferEnforcer_exports,
23
23
  NativeTokenStreamingEnforcer_exports
24
- } from "../chunk-YCNLPEPH.mjs";
24
+ } from "../chunk-56QPXKWD.mjs";
25
25
  import {
26
26
  encodeProxyCreationCode,
27
27
  isContractDeployed,
28
28
  isImplementationExpected
29
- } from "../chunk-EMPAUTIV.mjs";
30
- import "../chunk-3KWKQ7PV.mjs";
29
+ } from "../chunk-5ENRJKXL.mjs";
30
+ import "../chunk-XBHL6PDR.mjs";
31
31
  export {
32
32
  DeleGatorCore_exports as DeleGatorCore,
33
33
  DelegationManager_exports as DelegationManager,
@@ -1,11 +1,11 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
  var _chunkIQT6XFDTcjs = require('../chunk-IQT6XFDT.cjs');
4
- require('../chunk-KIXYMA7J.cjs');
4
+ require('../chunk-FC3W7R6D.cjs');
5
5
 
6
6
 
7
7
  var _chunk2OS36DVVcjs = require('../chunk-2OS36DVV.cjs');
8
- require('../chunk-32RDDE5N.cjs');
8
+ require('../chunk-TESSVINE.cjs');
9
9
 
10
10
 
11
11
 
@@ -14,7 +14,7 @@ require('../chunk-32RDDE5N.cjs');
14
14
 
15
15
 
16
16
 
17
- var _chunkGHGCGV3Ccjs = require('../chunk-GHGCGV3C.cjs');
17
+ var _chunk4PCXDGUFcjs = require('../chunk-4PCXDGUF.cjs');
18
18
 
19
19
  // src/experimental/delegationStorage.ts
20
20
  var _viem = require('viem');
@@ -35,7 +35,7 @@ var DelegationStorageClient = class {
35
35
  #apiUrl;
36
36
  constructor(config) {
37
37
  const { apiUrl } = config.environment;
38
- _chunkGHGCGV3Ccjs.trackSmartAccountsKitFunctionCall.call(void 0,
38
+ _chunk4PCXDGUFcjs.trackSmartAccountsKitFunctionCall.call(void 0,
39
39
  "experimental.DelegationStorageClient.constructor",
40
40
  {
41
41
  environment: getDelegationStorageEnvironment(apiUrl)
@@ -81,13 +81,13 @@ var DelegationStorageClient = class {
81
81
  * is not found.
82
82
  */
83
83
  async getDelegationChain(leafDelegationOrDelegationHash) {
84
- _chunkGHGCGV3Ccjs.trackSmartAccountsKitFunctionCall.call(void 0,
84
+ _chunk4PCXDGUFcjs.trackSmartAccountsKitFunctionCall.call(void 0,
85
85
  "experimental.DelegationStorageClient.getDelegationChain",
86
86
  {
87
87
  inputKind: typeof leafDelegationOrDelegationHash === "string" ? "hash" : "delegation"
88
88
  }
89
89
  );
90
- const leafDelegationHash = typeof leafDelegationOrDelegationHash === "string" ? leafDelegationOrDelegationHash : _chunkGHGCGV3Ccjs.hashDelegation.call(void 0, leafDelegationOrDelegationHash);
90
+ const leafDelegationHash = typeof leafDelegationOrDelegationHash === "string" ? leafDelegationOrDelegationHash : _chunk4PCXDGUFcjs.hashDelegation.call(void 0, leafDelegationOrDelegationHash);
91
91
  const response = await this.#fetcher(
92
92
  `${this.#apiUrl}/delegation/chain/${leafDelegationHash}`,
93
93
  {
@@ -117,7 +117,7 @@ var DelegationStorageClient = class {
117
117
  * empty array if the delegations are not found.
118
118
  */
119
119
  async fetchDelegations(deleGatorAddress, filterMode = "RECEIVED" /* Received */) {
120
- _chunkGHGCGV3Ccjs.trackSmartAccountsKitFunctionCall.call(void 0,
120
+ _chunk4PCXDGUFcjs.trackSmartAccountsKitFunctionCall.call(void 0,
121
121
  "experimental.DelegationStorageClient.fetchDelegations",
122
122
  { filterMode }
123
123
  );
@@ -144,14 +144,14 @@ var DelegationStorageClient = class {
144
144
  * @returns A promise that resolves to the delegation hash indicating successful storage.
145
145
  */
146
146
  async storeDelegation(delegation) {
147
- _chunkGHGCGV3Ccjs.trackSmartAccountsKitFunctionCall.call(void 0,
147
+ _chunk4PCXDGUFcjs.trackSmartAccountsKitFunctionCall.call(void 0,
148
148
  "experimental.DelegationStorageClient.storeDelegation",
149
149
  { caveatCount: delegation.caveats.length }
150
150
  );
151
151
  if (!delegation.signature || delegation.signature === "0x") {
152
152
  throw new Error("Delegation must be signed to be stored");
153
153
  }
154
- const delegationHash = _chunkGHGCGV3Ccjs.hashDelegation.call(void 0, delegation);
154
+ const delegationHash = _chunk4PCXDGUFcjs.hashDelegation.call(void 0, delegation);
155
155
  const body = JSON.stringify(
156
156
  {
157
157
  ...delegation,
@@ -394,7 +394,7 @@ var resolvex402DelegationCaveats = ({
394
394
  if (!timestampEnforcer) {
395
395
  throw new Error("TimestampEnforcer not found in environment");
396
396
  }
397
- const initialCaveats = _chunkGHGCGV3Ccjs.resolveCaveats.call(void 0, {
397
+ const initialCaveats = _chunk4PCXDGUFcjs.resolveCaveats.call(void 0, {
398
398
  environment,
399
399
  caveats: caveatsConfig,
400
400
  // Resolve caveats first so downstream constraint checks can append as needed.
@@ -458,7 +458,7 @@ var resolveDelegationCreationContext = async (config, requirements) => {
458
458
  maxAmount: BigInt(requirements.amount)
459
459
  };
460
460
  const facilitatorAddresses = _optionalChain([requirements, 'access', _6 => _6.extra, 'optionalAccess', _7 => _7.facilitatorAddresses]);
461
- const existingDelegations = parentPermissionContext ? _chunkGHGCGV3Ccjs.decodeDelegations.call(void 0, parentPermissionContext) : [];
461
+ const existingDelegations = parentPermissionContext ? _chunk4PCXDGUFcjs.decodeDelegations.call(void 0, parentPermissionContext) : [];
462
462
  const { DelegationManager: delegationManager } = environment;
463
463
  const caveats = resolvex402DelegationCaveats({
464
464
  environment,
@@ -521,9 +521,9 @@ function createx402DelegationProvider(config) {
521
521
  existingDelegations,
522
522
  rootDelegator
523
523
  } = await resolveDelegationCreationContext(config, requirements);
524
- const delegation = _chunkGHGCGV3Ccjs.createOpenDelegation.call(void 0, createDelegationConfig);
524
+ const delegation = _chunk4PCXDGUFcjs.createOpenDelegation.call(void 0, createDelegationConfig);
525
525
  const chainId = parseEip155ChainId(requirements.network);
526
- const typedData = _chunkGHGCGV3Ccjs.prepareSignDelegationTypedData.call(void 0, {
526
+ const typedData = _chunk4PCXDGUFcjs.prepareSignDelegationTypedData.call(void 0, {
527
527
  delegationManager,
528
528
  chainId,
529
529
  delegation
@@ -536,7 +536,7 @@ function createx402DelegationProvider(config) {
536
536
  ...delegation,
537
537
  signature
538
538
  };
539
- const permissionContext = _chunkGHGCGV3Ccjs.encodeDelegations.call(void 0, [
539
+ const permissionContext = _chunk4PCXDGUFcjs.encodeDelegations.call(void 0, [
540
540
  signedDelegation,
541
541
  ...existingDelegations
542
542
  ]);
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/experimental/index.cjs","../../src/experimental/delegationStorage.ts","../../src/experimental/x402DelegationProviderUtils.ts","../../src/experimental/x402DelegationProvider.ts"],"names":[],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;AClBA,4BAAgC;AA4BzB,IAAM,6BAAA,EAET;AAAA,EACF,GAAA,EAAK,EAAE,MAAA,EAAQ,0CAA0C,CAAA;AAAA,EACzD,IAAA,EAAM,EAAE,MAAA,EAAQ,sCAAsC;AACxD,CAAA;AASA,SAAS,+BAAA,CACP,MAAA,EAC2B;AAC3B,EAAA,MAAM,oBAAA,EAAsB,MAAA,CAAO,OAAA,CAAQ,4BAA4B,CAAA,CAAE,IAAA;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,EAAA;AAGI,EAAA;AACG,IAAA;AACP,IAAA;AACF,EAAA;AACM,EAAA;AAEA,EAAA;AACG,IAAA;AACP,IAAA;AACF,EAAA;AAGS,EAAA;AAEA,EAAA;AAEK,EAAA;AACZ,IAAA;AACc,IAAA;AACI,IAAA;AACpB,EAAA;AAEM,EAAA;AAIA,EAAA;AAIE,EAAA;AACQ,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACO,IAAA;AACP,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AAEG,EAAA;AAEA,EAAA;AACI,IAAA;AAED,IAAA;AACa,MAAA;AAClB,IAAA;AAEA,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACK,EAAA;AACL,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAEM,EAAA;AAGC,EAAA;AACL,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;AFpHsB;AACA;AG7dT;AACX,EAAA;AACA,EAAA;AACA,EAAA;AACF;AACa;AACX,EAAA;AACF;AAYgB;AAIZ,EAAA;AAEM,IAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACQ,IAAA;AAEJ,IAAA;AAEU,IAAA;AAEE,IAAA;AAChB,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AAEY,IAAA;AACK,MAAA;AAClB,IAAA;AAEkB,IAAA;AAEZ,IAAA;AACD,MAAA;AACH,MAAA;AACF,IAAA;AAEM,IAAA;AACJ,MAAA;AACG,MAAA;AACJ,IAAA;AAEM,IAAA;AACL,MAAA;AACA,MAAA;AACW,MAAA;AACb,IAAA;AACF,EAAA;AACF;AHwcsB;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/experimental/index.cjs","sourcesContent":[null,"import { type Hex, toHex } from 'viem';\n\nimport { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { hashDelegation } from '../delegation';\nimport type { Delegation } from '../types';\n\ntype ErrorResponse = {\n error: string;\n data?: any;\n};\n\nexport type APIStoreDelegationResponse = {\n delegationHash: Hex;\n};\n\n/**\n * Represents the allowed filters when querying the data store for delegations.\n */\nexport enum DelegationStoreFilter {\n Given = 'GIVEN',\n Received = 'RECEIVED',\n All = 'ALL',\n}\n\n/**\n * Public Delegation Storage Service environments. To be used in the\n * DeleGationStorageService config.\n */\nexport const DelegationStorageEnvironment: {\n [K in 'dev' | 'prod']: Environment;\n} = {\n dev: { apiUrl: 'https://passkeys.dev-api.cx.metamask.io' },\n prod: { apiUrl: 'https://passkeys.api.cx.metamask.io' },\n};\n\n/**\n * Returns the DelegationStorageEnvironment ('dev' or 'prod') for a given apiUrl,\n * or 'custom' if the apiUrl does not match a known environment.\n *\n * @param apiUrl - The API URL to check.\n * @returns The environment key ('dev' or 'prod'), or 'custom'.\n */\nfunction getDelegationStorageEnvironment(\n apiUrl: string,\n): 'dev' | 'prod' | 'custom' {\n const matchingEnvironment = Object.entries(DelegationStorageEnvironment).find(\n ([_, env]) => env.apiUrl === apiUrl,\n ) as [keyof typeof DelegationStorageEnvironment, Environment] | undefined;\n\n return matchingEnvironment ? matchingEnvironment[0] : 'custom';\n}\n\nexport type Environment = {\n apiUrl: string;\n};\n\nexport type DelegationStorageConfig = {\n apiKey: string;\n apiKeyId: string;\n environment: Environment;\n fetcher?: typeof fetch;\n};\n\nexport class DelegationStorageClient {\n readonly #apiVersionPrefix = 'api/v0';\n\n readonly #config: DelegationStorageConfig;\n\n readonly #fetcher: typeof fetch;\n\n readonly #apiUrl: string;\n\n constructor(config: DelegationStorageConfig) {\n const { apiUrl } = config.environment;\n\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.constructor',\n {\n environment: getDelegationStorageEnvironment(apiUrl),\n },\n );\n\n if (apiUrl.endsWith(this.#apiVersionPrefix)) {\n this.#apiUrl = apiUrl;\n } else {\n const separator = apiUrl.endsWith('/') ? '' : '/';\n this.#apiUrl = `${apiUrl}${separator}${this.#apiVersionPrefix}`;\n }\n this.#fetcher = this.#initializeFetcher(config);\n this.#config = config;\n }\n\n /**\n * Initializes the fetch function for HTTP requests.\n *\n * - Uses `config.fetcher` if provided.\n * - Falls back to global `fetch` if available.\n * - Throws an error if no fetch function is available.\n *\n * @param config - Configuration object that may include a custom fetch function.\n * @returns The fetch function to be used for HTTP requests.\n * @throws Error if no fetch function is available in the environment.\n */\n #initializeFetcher(config: DelegationStorageConfig): typeof fetch {\n if (config.fetcher) {\n return config.fetcher;\n } else if (typeof globalThis?.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n 'Fetch API is not available in this environment. Please provide a fetch function in the config.',\n );\n }\n\n /**\n * Fetches the delegation chain from the Delegation Storage Service, ending with\n * the specified leaf delegation.\n *\n * @param leafDelegationOrDelegationHash - The leaf delegation, or the hash\n * of the leaf delegation.\n * @returns A promise that resolves to the delegation chain - empty array if the delegation\n * is not found.\n */\n async getDelegationChain(\n leafDelegationOrDelegationHash: Hex | Delegation,\n ): Promise<Delegation[]> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.getDelegationChain',\n {\n inputKind:\n typeof leafDelegationOrDelegationHash === 'string'\n ? 'hash'\n : 'delegation',\n },\n );\n const leafDelegationHash =\n typeof leafDelegationOrDelegationHash === 'string'\n ? leafDelegationOrDelegationHash\n : hashDelegation(leafDelegationOrDelegationHash);\n\n const response = await this.#fetcher(\n `${this.#apiUrl}/delegation/chain/${leafDelegationHash}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n },\n },\n );\n\n const responseData: Delegation[] | ErrorResponse = await response.json();\n\n if ('error' in responseData) {\n throw new Error(\n `Failed to fetch delegation chain: ${responseData.error}`,\n );\n }\n\n return responseData;\n }\n\n /**\n * Fetches the delegations from the Delegation Storage Service, either `Received`\n * by, or `Given` by, (or both: `All`) the specified deleGatorAddress. Defaults\n * to `Received`.\n *\n * @param deleGatorAddress - The deleGatorAddress to retrieve the delegations for.\n * @param filterMode - The DelegationStoreFilter mode - defaults to Received.\n * @returns A promise that resolves to the list of delegations received by the deleGatorAddress,\n * empty array if the delegations are not found.\n */\n async fetchDelegations(\n deleGatorAddress: Hex,\n filterMode = DelegationStoreFilter.Received,\n ): Promise<Delegation[]> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.fetchDelegations',\n { filterMode },\n );\n const response = await this.#fetcher(\n `${this.#apiUrl}/delegation/accounts/${deleGatorAddress}?filter=${filterMode}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n },\n },\n );\n\n const responseData: Delegation[] | ErrorResponse = await response.json();\n\n if ('error' in responseData) {\n throw new Error(`Failed to fetch delegations: ${responseData.error}`);\n }\n\n return responseData;\n }\n\n /**\n * Stores the specified delegation in the Delegation Storage Service.\n *\n * @param delegation - The delegation to store.\n * @returns A promise that resolves to the delegation hash indicating successful storage.\n */\n async storeDelegation(delegation: Delegation): Promise<Hex> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.storeDelegation',\n { caveatCount: delegation.caveats.length },\n );\n if (!delegation.signature || delegation.signature === '0x') {\n throw new Error('Delegation must be signed to be stored');\n }\n\n const delegationHash = hashDelegation(delegation);\n\n const body = JSON.stringify(\n {\n ...delegation,\n metadata: [],\n },\n (_, value: any) =>\n typeof value === 'bigint' || typeof value === 'number'\n ? toHex(value)\n : value,\n 2,\n );\n\n const response = await this.#fetcher(`${this.#apiUrl}/delegation/store`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n 'Content-Type': 'application/json',\n },\n body,\n });\n\n const responseData: APIStoreDelegationResponse | ErrorResponse =\n await response.json();\n\n if ('error' in responseData) {\n throw new Error(responseData.error);\n }\n\n if (responseData.delegationHash !== delegationHash) {\n throw new Error(\n 'Failed to store the Delegation, the hash returned from the MM delegation storage API does not match the hash of the delegation',\n );\n }\n\n return responseData.delegationHash;\n }\n}\n","import {\n createAllowedCalldataTerms,\n createRedeemerTerms,\n createTimestampTerms,\n decodeRedeemerTerms,\n decodeTimestampTerms,\n} from '@metamask/delegation-core';\nimport { parseCaipChainId } from '@metamask/utils';\nimport { pad, type Account, type Address, type Hex } from 'viem';\n\nimport type { Caveats } from '../caveatBuilder';\nimport { resolveCaveats } from '../caveatBuilder';\nimport { ScopeType } from '../constants';\nimport type { createOpenDelegation } from '../delegation';\nimport { decodeDelegations } from '../delegation';\nimport { getSmartAccountsEnvironment } from '../smartAccountsEnvironment';\nimport type {\n Caveat,\n Delegation,\n PermissionContext,\n SmartAccountsEnvironment,\n} from '../types';\nimport type {\n MaybeDeferred,\n PaymentRequirements,\n x402DelegationProviderConfig,\n} from './x402DelegationProviderTypes';\nimport { generateSalt } from '../utils/';\n\n/**\n * Inputs for redeemer constraint enforcement.\n */\ntype EnsureRedeemerSufficientlyConstrainedParams = {\n redeemerEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n facilitatorAddresses: Address[] | undefined;\n redeemerAddresses: Address[] | undefined;\n requireRedeemers: boolean;\n};\n\n/**\n * Inputs for payee constraint enforcement.\n */\ntype EnsurePayeeSufficientlyConstrainedParams = {\n allowedCalldataEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n payee: Hex;\n};\n\n/**\n * Inputs for expiry constraint enforcement.\n */\ntype EnsureExpirySufficientlyConstrainedParams = {\n timestampEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n expirySeconds: number;\n};\n\n/**\n * Inputs for resolving allowed redeemer addresses.\n */\ntype ResolveRedeemerAddressesParams = Pick<\n EnsureRedeemerSufficientlyConstrainedParams,\n 'facilitatorAddresses' | 'redeemerAddresses'\n>;\n\n/**\n * Resolved context required to build and sign an x402 delegation.\n */\nexport type DelegationCreationContext = {\n account: Account;\n createDelegationConfig: Parameters<typeof createOpenDelegation>[0];\n delegationManager: Address;\n existingDelegations: Delegation[];\n rootDelegator: Address;\n};\n\n/**\n * Inputs for resolving delegation caveats with x402-specific constraints.\n */\nexport type Resolvex402DelegationCaveatsParams = {\n environment: SmartAccountsEnvironment;\n caveatsConfig: Caveats | undefined;\n existingDelegations: Delegation[];\n facilitatorAddresses: Hex[] | undefined;\n payee: Hex;\n expirySeconds?: number;\n requireRedeemers: boolean;\n redeemerAddresses: Address[] | undefined;\n};\n\n/**\n * Resolves eager or deferred values against payment requirements.\n *\n * @param maybeDeferred - Value or async resolver function.\n * @param requirements - Payment requirements passed to deferred resolvers.\n * @returns The resolved value, or undefined when no value is provided.\n */\nasync function resolveMaybeDeferred<TResult>(\n maybeDeferred: MaybeDeferred<TResult>,\n requirements: PaymentRequirements,\n): Promise<TResult> {\n if (typeof maybeDeferred === 'function') {\n const deferred = maybeDeferred as (\n deferredRequirements: PaymentRequirements,\n ) => Promise<TResult> | TResult;\n\n return await deferred(requirements);\n }\n\n return maybeDeferred;\n}\n\n/**\n * Parses an EIP-155 CAIP network identifier into a numeric chain ID.\n *\n * @param network - CAIP network identifier (for example, `eip155:1`).\n * @returns Parsed numeric chain ID.\n * @throws If the CAIP namespace is not `eip155`.\n */\nexport function parseEip155ChainId(\n network: PaymentRequirements['network'],\n): number {\n const { namespace, reference } = parseCaipChainId(\n network as `${string}:${string}`,\n );\n\n if (namespace !== 'eip155') {\n throw new Error('Unsupported chain namespace');\n }\n\n const parsedChainId = Number(reference);\n\n if (isNaN(parsedChainId)) {\n throw new Error('Invalid chain id');\n }\n\n return parsedChainId;\n}\n\n/**\n * ERC-20 `transfer(address to, uint256 value)` calldata index for `to`.\n */\nconst TRANSFER_PAYEE_INDEX = 4;\n\n/**\n * Normalizes an address-like hex string for case-insensitive comparisons.\n *\n * @param address - Address value to normalize.\n * @returns Lowercased hex string.\n */\nconst normalizeAddress = (address: Address): Address =>\n address.toLowerCase() as Address;\n\n/**\n * Returns whether any caveat in local or inherited delegations matches a predicate.\n *\n * @param caveats - Current caveat list.\n * @param delegations - Existing delegations whose caveats should also be searched.\n * @param match - Predicate used to match caveats.\n * @returns True when at least one caveat satisfies `match`.\n */\nconst hasMatchingCaveats = (\n caveats: Caveat[],\n delegations: Delegation[],\n match: (caveat: Caveat) => boolean,\n): boolean => {\n for (const caveat of caveats) {\n if (match(caveat)) {\n return true;\n }\n }\n\n for (const delegation of delegations) {\n for (const caveat of delegation.caveats) {\n if (match(caveat)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\n/**\n * Ensures caveats include an expiry timestamp constraint when requested.\n *\n * If an existing timestamp caveat already enforces a tighter (earlier) or equal\n * `validBefore` threshold than requested, caveats are returned unchanged.\n * Otherwise a new timestamp caveat is appended with `afterThreshold = 0`.\n *\n * @param options0 - Expiry constraint evaluation inputs.\n * @param options0.timestampEnforcer - Address of the TimestampEnforcer caveat contract.\n * @param options0.caveats - Currently resolved caveats for the delegation being created.\n * @param options0.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param options0.expirySeconds - Relative expiry from \"now\" in seconds.\n * @returns The original caveats when sufficiently constrained, otherwise caveats with a timestamp caveat appended.\n */\nexport const ensureExpirySufficientlyConstrained = ({\n timestampEnforcer,\n caveats,\n existingDelegations,\n expirySeconds,\n}: EnsureExpirySufficientlyConstrainedParams): Caveat[] => {\n if (expirySeconds < 0) {\n throw new Error('Expiry seconds must be a positive number');\n }\n const beforeThreshold = Math.floor(Date.now() / 1000) + expirySeconds;\n const timestampEnforcerNormalized = normalizeAddress(timestampEnforcer);\n\n const hasSupersedingTimestampConstraint = hasMatchingCaveats(\n caveats,\n existingDelegations,\n (caveat) => {\n if (normalizeAddress(caveat.enforcer) !== timestampEnforcerNormalized) {\n return false;\n }\n\n const { beforeThreshold: existingBeforeThreshold } = decodeTimestampTerms(\n caveat.terms,\n );\n return (\n existingBeforeThreshold !== 0 &&\n existingBeforeThreshold <= beforeThreshold\n );\n },\n );\n\n if (hasSupersedingTimestampConstraint) {\n return caveats;\n }\n\n const timestampCaveat: Caveat = {\n enforcer: timestampEnforcer,\n terms: createTimestampTerms({\n afterThreshold: 0,\n beforeThreshold,\n }),\n args: '0x',\n };\n\n return [...caveats, timestampCaveat];\n};\n\n/**\n * Resolves allowed redeemer addresses from facilitator and configured redeemer inputs.\n *\n * If both inputs are provided, returns their intersection.\n * If only one input is provided, returns that input.\n * If neither input is provided, returns undefined.\n *\n * @param options - Redeemer address inputs.\n * @param options.facilitatorAddresses - Optional facilitator addresses from the PaymentRequirements.\n * @param options.redeemerAddresses - Optional redeemer addresses from the RedeemersConfig.\n * @returns Resolved allowed redeemer addresses, or undefined when no input is provided.\n */\nconst resolveRedeemerAddresses = ({\n facilitatorAddresses,\n redeemerAddresses,\n}: ResolveRedeemerAddressesParams): Address[] | undefined => {\n if (!facilitatorAddresses) {\n if (!redeemerAddresses) {\n return undefined;\n }\n return redeemerAddresses;\n }\n\n if (!redeemerAddresses) {\n return facilitatorAddresses;\n }\n\n const normalizedFacilitatorAddresses =\n facilitatorAddresses.map(normalizeAddress);\n\n const normalizedRedeemerAddressSet = new Set(\n redeemerAddresses.map(normalizeAddress),\n );\n\n const redeemerAddressesIntersection = normalizedFacilitatorAddresses.filter(\n (address) => normalizedRedeemerAddressSet.has(address),\n );\n\n return redeemerAddressesIntersection;\n};\n\n/**\n * Ensures caveats include a sufficiently strict redeemer constraint.\n *\n * Returns the caveat list unchanged when an existing redeemer caveat is already\n * strict enough, or appends a new redeemer caveat scoped to facilitator addresses.\n *\n * @param config - Redeemer constraint evaluation inputs.\n * @param config.redeemerEnforcer - Address of the redeemer enforcer caveat contract.\n * @param config.caveats - Currently resolved caveats for the delegation being created.\n * @param config.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param config.redeemerAddresses - Optional addresses to which redemption should be constrained.\n * @param config.requireRedeemers - Whether at least one redeemer constraint must exist.\n * @returns The original caveats when sufficiently constrained, otherwise caveats with a redeemer caveat appended.\n * @throws If either facilitatorAddresses and/or redeemerAddresses are provided, but the intersection is empty.\n * @throws If requireRedeemers is true, but no valid redeemer addresses are provided, and no existing redeemer caveat is found in the existingDelegations.\n */\nexport const ensureRedeemerSufficientlyConstrained = (\n config: EnsureRedeemerSufficientlyConstrainedParams,\n): Caveat[] => {\n // `redeemerAddresses` is the intersection of `facilitatorAddresses` and `redeemerAddresses`.\n // If either is undefined, it implies no constraint is specified by that value, and the other is returned.\n // If both are undefined, it implies that no constraint is specified overall.\n const redeemerAddresses = resolveRedeemerAddresses(config);\n\n // If the result is defined, but zero-length, it implies no redeemers are allowed, which is a non-satisfiable constraint, so an error is thrown.\n if (redeemerAddresses?.length === 0) {\n throw new Error(\n 'No valid redeemer addresses were resolved. If both `redeemers.addresses` and `extra.facilitatorAddresses` are provided, they must overlap. If only one is provided, it must include at least one address.',\n );\n }\n\n const { caveats, existingDelegations, redeemerEnforcer } = config;\n\n const redeemerEnforcerNormalized = normalizeAddress(redeemerEnforcer);\n\n if (!redeemerAddresses) {\n if (!config.requireRedeemers) {\n return caveats;\n }\n\n const hasExistingRedeemerCaveat = hasMatchingCaveats(\n caveats,\n existingDelegations,\n ({ enforcer }) =>\n normalizeAddress(enforcer) === redeemerEnforcerNormalized,\n );\n\n if (!hasExistingRedeemerCaveat) {\n throw new Error(\n 'Redeemer must be constrained, either in the specified `caveats`, `parentPermissionContext`, or the `PaymentRequirements` as `extra.facilitatorAddresses`.',\n );\n }\n\n return caveats;\n }\n\n const redeemerAddressesSet = new Set(redeemerAddresses.map(normalizeAddress));\n\n const hasSupersedingRedeemerCaveat = hasMatchingCaveats(\n caveats,\n existingDelegations,\n (caveat) => {\n if (normalizeAddress(caveat.enforcer) !== redeemerEnforcerNormalized) {\n return false;\n }\n\n const allowedRedeemerAddresses = decodeRedeemerTerms(\n caveat.terms,\n ).redeemers.map(normalizeAddress);\n\n // If this redeemer caveat only allows redeemer addresses, it is sufficiently constrained.\n return allowedRedeemerAddresses.every((item) =>\n redeemerAddressesSet.has(item),\n );\n },\n );\n\n if (hasSupersedingRedeemerCaveat) {\n return caveats;\n }\n\n const redeemerCaveat: Caveat = {\n enforcer: redeemerEnforcer,\n terms: createRedeemerTerms({ redeemers: redeemerAddresses }),\n args: '0x',\n };\n\n return [...caveats, redeemerCaveat];\n};\n\n/**\n * Ensures caveats include an allowed-calldata constraint for the payment payee.\n *\n * Scans both the in-progress caveat list and parent delegation caveats for an\n * `AllowedCalldataEnforcer` caveat whose terms match the encoded payee calldata\n * constraint. If found, returns caveats unchanged; otherwise appends a payee caveat.\n *\n * @param options0 - Payee constraint evaluation inputs.\n * @param options0.allowedCalldataEnforcer - Address of the AllowedCalldataEnforcer caveat contract.\n * @param options0.caveats - Currently resolved caveats for the delegation being created.\n * @param options0.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param options0.payee - Expected ERC-20 transfer recipient to enforce in calldata.\n * @returns The original caveats when an equivalent payee constraint exists, otherwise caveats with a payee caveat appended.\n */\nexport const ensurePayeeSufficientlyConstrained = ({\n allowedCalldataEnforcer,\n caveats,\n existingDelegations,\n payee,\n}: EnsurePayeeSufficientlyConstrainedParams): Caveat[] => {\n const allowedCalldataTerms = createAllowedCalldataTerms({\n startIndex: TRANSFER_PAYEE_INDEX,\n value: pad(payee, { size: 32 }),\n });\n\n const allowedCalldataEnforcerNormalized = normalizeAddress(\n allowedCalldataEnforcer,\n );\n\n const lowercaseCalldataTerms = allowedCalldataTerms.toLowerCase();\n\n const hasSupersedingAllowedCalldataConstraint = hasMatchingCaveats(\n caveats,\n existingDelegations,\n ({ enforcer, terms }) =>\n normalizeAddress(enforcer) === allowedCalldataEnforcerNormalized &&\n terms.toLowerCase() === lowercaseCalldataTerms,\n );\n\n if (hasSupersedingAllowedCalldataConstraint) {\n return caveats;\n }\n\n const payeeCaveat: Caveat = {\n enforcer: allowedCalldataEnforcer,\n terms: allowedCalldataTerms,\n args: '0x',\n };\n\n return [...caveats, payeeCaveat];\n};\n\n/**\n * Resolves caveats and applies x402-specific redeemer and payee constraints.\n *\n * @param options0 - Caveat resolution inputs.\n * @param options0.environment - Environment containing caveat enforcer addresses.\n * @param options0.caveatsConfig - Optional caveat builder config.\n * @param options0.existingDelegations - Existing parent-chain delegations.\n * @param options0.facilitatorAddresses - Optional facilitator addresses used for redeemer constraints.\n * @param options0.payee - Payee address used for allowed calldata constraints.\n * @param options0.expirySeconds - Optional relative expiry in seconds for adding timestamp constraints.\n * @param options0.requireRedeemers - Whether redeemer constraints are mandatory when no facilitator or configured redeemer addresses are present.\n * @param options0.redeemerAddresses - Optional redeemer addresses from provider config to merge with facilitator addresses.\n * @returns Caveats after redeemer and payee constraints are enforced.\n */\nexport const resolvex402DelegationCaveats = ({\n environment,\n caveatsConfig,\n existingDelegations,\n facilitatorAddresses,\n payee,\n expirySeconds,\n requireRedeemers,\n redeemerAddresses,\n}: Resolvex402DelegationCaveatsParams): Caveat[] => {\n const {\n caveatEnforcers: {\n RedeemerEnforcer: redeemerEnforcer,\n AllowedCalldataEnforcer: allowedCalldataEnforcer,\n TimestampEnforcer: timestampEnforcer,\n },\n } = environment;\n\n if (!redeemerEnforcer) {\n throw new Error('RedeemerEnforcer not found in environment');\n }\n\n if (!allowedCalldataEnforcer) {\n throw new Error('AllowedCalldataEnforcer not found in environment');\n }\n\n if (!timestampEnforcer) {\n throw new Error('TimestampEnforcer not found in environment');\n }\n\n const initialCaveats = resolveCaveats({\n environment,\n caveats: caveatsConfig,\n // Resolve caveats first so downstream constraint checks can append as needed.\n // Scope is still attached later during delegation creation.\n isScopeOptional: true,\n });\n\n const caveatsWithRedeemer = ensureRedeemerSufficientlyConstrained({\n redeemerEnforcer,\n facilitatorAddresses,\n redeemerAddresses,\n caveats: initialCaveats,\n existingDelegations,\n requireRedeemers,\n });\n\n const caveatsWithPayee = ensurePayeeSufficientlyConstrained({\n allowedCalldataEnforcer,\n caveats: caveatsWithRedeemer,\n existingDelegations,\n payee,\n });\n\n if (expirySeconds === undefined) {\n return caveatsWithPayee;\n }\n\n return ensureExpirySufficientlyConstrained({\n timestampEnforcer,\n caveats: caveatsWithPayee,\n existingDelegations,\n expirySeconds,\n });\n};\n\n/**\n * Builds the delegation creation context from provider config and requirements.\n *\n * @param config - Delegation provider config for context construction.\n * @param requirements - Payment requirements used to scope caveats.\n * @returns The resolved context used to create and sign a delegation.\n */\nexport const resolveDelegationCreationContext = async (\n config: x402DelegationProviderConfig,\n requirements: PaymentRequirements,\n): Promise<DelegationCreationContext> => {\n const account = await resolveMaybeDeferred(config.account, requirements);\n const redeemersConfig = await resolveMaybeDeferred(\n config.redeemers,\n requirements,\n );\n\n const requireRedeemers = redeemersConfig?.requireRedeemers ?? false;\n const redeemerAddresses = await resolveMaybeDeferred(\n redeemersConfig?.addresses,\n requirements,\n );\n\n const specifiedEnvironment = await resolveMaybeDeferred(\n config.environment,\n requirements,\n );\n const environment =\n specifiedEnvironment ??\n getSmartAccountsEnvironment(parseEip155ChainId(requirements.network));\n\n const caveatsConfig: Caveats | undefined = await resolveMaybeDeferred(\n config.caveats,\n requirements,\n );\n const parentPermissionContext: PermissionContext | undefined =\n await resolveMaybeDeferred(config.parentPermissionContext, requirements);\n const expirySeconds = await resolveMaybeDeferred(\n config.expirySeconds,\n requirements,\n );\n\n const from =\n (await resolveMaybeDeferred(config.from, requirements)) ?? account.address;\n const salt =\n (await resolveMaybeDeferred(config.salt, requirements)) ?? generateSalt();\n\n const scope = {\n type: ScopeType.Erc20TransferAmount,\n tokenAddress: requirements.asset as Hex,\n maxAmount: BigInt(requirements.amount),\n } as const;\n\n const facilitatorAddresses = requirements.extra?.facilitatorAddresses as\n | Hex[]\n | undefined;\n\n const existingDelegations = parentPermissionContext\n ? decodeDelegations(parentPermissionContext)\n : [];\n\n const { DelegationManager: delegationManager } = environment;\n const caveats = resolvex402DelegationCaveats({\n environment,\n caveatsConfig,\n existingDelegations,\n facilitatorAddresses,\n payee: requirements.payTo as Hex,\n expirySeconds,\n requireRedeemers,\n redeemerAddresses,\n });\n\n let createDelegationConfig: Parameters<typeof createOpenDelegation>[0];\n\n if (parentPermissionContext) {\n const parentDelegation = existingDelegations[0];\n\n if (!parentDelegation) {\n throw new Error('Parent permission context is not a valid delegation');\n }\n\n createDelegationConfig = {\n environment,\n from,\n caveats,\n salt,\n scope,\n parentDelegation,\n };\n } else {\n createDelegationConfig = {\n environment,\n from,\n caveats,\n salt,\n scope,\n };\n }\n\n const rootDelegator =\n existingDelegations[existingDelegations.length - 1]?.delegator ?? from;\n\n return {\n account,\n createDelegationConfig,\n delegationManager,\n existingDelegations,\n rootDelegator,\n };\n};\n","import type { Address } from 'viem';\n\nimport {\n createOpenDelegation,\n encodeDelegations,\n prepareSignDelegationTypedData,\n} from '../delegation';\nimport type {\n PaymentRequirements,\n x402DelegationProvider,\n x402DelegationProviderConfig,\n x402DelegationProviderPaymentPayload,\n} from './x402DelegationProviderTypes';\nimport {\n parseEip155ChainId,\n resolveDelegationCreationContext,\n} from './x402DelegationProviderUtils';\n\nexport type {\n MaybeDeferred,\n PaymentRequirements,\n x402DelegationProvider,\n x402DelegationProviderConfig,\n x402DelegationProviderPaymentPayload,\n} from './x402DelegationProviderTypes';\n\nexport { parseEip155ChainId } from './x402DelegationProviderUtils';\n\nexport const METAMASK_FACILITATOR_ADDRESSES: readonly Address[] = [\n '0xB01caEa8c6C47bbf4F4b4c5080Ca642043359C2E',\n '0xC066ac5D385419B1A8c43A0E146fA439837a8B8c',\n '0xB42F812A44c22cc6b861478900401ee759EbEAD6',\n];\nexport const METAMASK_FACILITATOR_ADDRESSES_DEV: readonly Address[] = [\n '0xb4827A2a066CD2Ef88560EFdf063dD05C6c41cC7',\n];\n\n/**\n * Creates a delegation provider function for x402 payment requirements.\n *\n * The returned provider resolves deferred config values using incoming payment\n * requirements, creates an open delegation, signs it, and returns an encoded\n * permission context payload.\n *\n * @param config - Delegation creation and signing configuration.\n * @returns A provider that maps payment requirements to a signed delegation payload.\n */\nexport function createx402DelegationProvider(\n config: x402DelegationProviderConfig,\n): x402DelegationProvider {\n return async (\n requirements: PaymentRequirements,\n ): Promise<x402DelegationProviderPaymentPayload> => {\n const {\n account,\n createDelegationConfig,\n delegationManager,\n existingDelegations,\n rootDelegator,\n } = await resolveDelegationCreationContext(config, requirements);\n\n const delegation = createOpenDelegation(createDelegationConfig);\n\n const chainId = parseEip155ChainId(requirements.network);\n\n const typedData = prepareSignDelegationTypedData({\n delegationManager,\n chainId,\n delegation,\n });\n\n if (!account.signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n const signature = await account.signTypedData(typedData);\n\n const signedDelegation = {\n ...delegation,\n signature,\n };\n\n const permissionContext = encodeDelegations([\n signedDelegation,\n ...existingDelegations,\n ]);\n\n return {\n delegationManager,\n permissionContext,\n delegator: rootDelegator,\n };\n };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/experimental/index.cjs","../../src/experimental/delegationStorage.ts","../../src/experimental/x402DelegationProviderUtils.ts","../../src/experimental/x402DelegationProvider.ts"],"names":[],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;AClBA,4BAAsB;AA6Bf,IAAM,6BAAA,EAET;AAAA,EACF,GAAA,EAAK,EAAE,MAAA,EAAQ,0CAA0C,CAAA;AAAA,EACzD,IAAA,EAAM,EAAE,MAAA,EAAQ,sCAAsC;AACxD,CAAA;AASA,SAAS,+BAAA,CACP,MAAA,EAC2B;AAC3B,EAAA,MAAM,oBAAA,EAAsB,MAAA,CAAO,OAAA,CAAQ,4BAA4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ounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/experimental/index.cjs","sourcesContent":[null,"import { toHex } from 'viem';\nimport type { Hex } from 'viem';\n\nimport { trackSmartAccountsKitFunctionCall } from '../analytics';\nimport { hashDelegation } from '../delegation';\nimport type { Delegation } from '../types';\n\ntype ErrorResponse = {\n error: string;\n data?: any;\n};\n\nexport type APIStoreDelegationResponse = {\n delegationHash: Hex;\n};\n\n/**\n * Represents the allowed filters when querying the data store for delegations.\n */\nexport enum DelegationStoreFilter {\n Given = 'GIVEN',\n Received = 'RECEIVED',\n All = 'ALL',\n}\n\n/**\n * Public Delegation Storage Service environments. To be used in the\n * DeleGationStorageService config.\n */\nexport const DelegationStorageEnvironment: {\n [K in 'dev' | 'prod']: Environment;\n} = {\n dev: { apiUrl: 'https://passkeys.dev-api.cx.metamask.io' },\n prod: { apiUrl: 'https://passkeys.api.cx.metamask.io' },\n};\n\n/**\n * Returns the DelegationStorageEnvironment ('dev' or 'prod') for a given apiUrl,\n * or 'custom' if the apiUrl does not match a known environment.\n *\n * @param apiUrl - The API URL to check.\n * @returns The environment key ('dev' or 'prod'), or 'custom'.\n */\nfunction getDelegationStorageEnvironment(\n apiUrl: string,\n): 'dev' | 'prod' | 'custom' {\n const matchingEnvironment = Object.entries(DelegationStorageEnvironment).find(\n ([_, env]) => env.apiUrl === apiUrl,\n ) as [keyof typeof DelegationStorageEnvironment, Environment] | undefined;\n\n return matchingEnvironment ? matchingEnvironment[0] : 'custom';\n}\n\nexport type Environment = {\n apiUrl: string;\n};\n\nexport type DelegationStorageConfig = {\n apiKey: string;\n apiKeyId: string;\n environment: Environment;\n fetcher?: typeof fetch;\n};\n\nexport class DelegationStorageClient {\n readonly #apiVersionPrefix = 'api/v0';\n\n readonly #config: DelegationStorageConfig;\n\n readonly #fetcher: typeof fetch;\n\n readonly #apiUrl: string;\n\n constructor(config: DelegationStorageConfig) {\n const { apiUrl } = config.environment;\n\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.constructor',\n {\n environment: getDelegationStorageEnvironment(apiUrl),\n },\n );\n\n if (apiUrl.endsWith(this.#apiVersionPrefix)) {\n this.#apiUrl = apiUrl;\n } else {\n const separator = apiUrl.endsWith('/') ? '' : '/';\n this.#apiUrl = `${apiUrl}${separator}${this.#apiVersionPrefix}`;\n }\n this.#fetcher = this.#initializeFetcher(config);\n this.#config = config;\n }\n\n /**\n * Initializes the fetch function for HTTP requests.\n *\n * - Uses `config.fetcher` if provided.\n * - Falls back to global `fetch` if available.\n * - Throws an error if no fetch function is available.\n *\n * @param config - Configuration object that may include a custom fetch function.\n * @returns The fetch function to be used for HTTP requests.\n * @throws Error if no fetch function is available in the environment.\n */\n #initializeFetcher(config: DelegationStorageConfig): typeof fetch {\n if (config.fetcher) {\n return config.fetcher;\n } else if (typeof globalThis?.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n 'Fetch API is not available in this environment. Please provide a fetch function in the config.',\n );\n }\n\n /**\n * Fetches the delegation chain from the Delegation Storage Service, ending with\n * the specified leaf delegation.\n *\n * @param leafDelegationOrDelegationHash - The leaf delegation, or the hash\n * of the leaf delegation.\n * @returns A promise that resolves to the delegation chain - empty array if the delegation\n * is not found.\n */\n async getDelegationChain(\n leafDelegationOrDelegationHash: Hex | Delegation,\n ): Promise<Delegation[]> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.getDelegationChain',\n {\n inputKind:\n typeof leafDelegationOrDelegationHash === 'string'\n ? 'hash'\n : 'delegation',\n },\n );\n const leafDelegationHash =\n typeof leafDelegationOrDelegationHash === 'string'\n ? leafDelegationOrDelegationHash\n : hashDelegation(leafDelegationOrDelegationHash);\n\n const response = await this.#fetcher(\n `${this.#apiUrl}/delegation/chain/${leafDelegationHash}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n },\n },\n );\n\n const responseData: Delegation[] | ErrorResponse = await response.json();\n\n if ('error' in responseData) {\n throw new Error(\n `Failed to fetch delegation chain: ${responseData.error}`,\n );\n }\n\n return responseData;\n }\n\n /**\n * Fetches the delegations from the Delegation Storage Service, either `Received`\n * by, or `Given` by, (or both: `All`) the specified deleGatorAddress. Defaults\n * to `Received`.\n *\n * @param deleGatorAddress - The deleGatorAddress to retrieve the delegations for.\n * @param filterMode - The DelegationStoreFilter mode - defaults to Received.\n * @returns A promise that resolves to the list of delegations received by the deleGatorAddress,\n * empty array if the delegations are not found.\n */\n async fetchDelegations(\n deleGatorAddress: Hex,\n filterMode = DelegationStoreFilter.Received,\n ): Promise<Delegation[]> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.fetchDelegations',\n { filterMode },\n );\n const response = await this.#fetcher(\n `${this.#apiUrl}/delegation/accounts/${deleGatorAddress}?filter=${filterMode}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n },\n },\n );\n\n const responseData: Delegation[] | ErrorResponse = await response.json();\n\n if ('error' in responseData) {\n throw new Error(`Failed to fetch delegations: ${responseData.error}`);\n }\n\n return responseData;\n }\n\n /**\n * Stores the specified delegation in the Delegation Storage Service.\n *\n * @param delegation - The delegation to store.\n * @returns A promise that resolves to the delegation hash indicating successful storage.\n */\n async storeDelegation(delegation: Delegation): Promise<Hex> {\n trackSmartAccountsKitFunctionCall(\n 'experimental.DelegationStorageClient.storeDelegation',\n { caveatCount: delegation.caveats.length },\n );\n if (!delegation.signature || delegation.signature === '0x') {\n throw new Error('Delegation must be signed to be stored');\n }\n\n const delegationHash = hashDelegation(delegation);\n\n const body = JSON.stringify(\n {\n ...delegation,\n metadata: [],\n },\n (_, value: any) =>\n typeof value === 'bigint' || typeof value === 'number'\n ? toHex(value)\n : value,\n 2,\n );\n\n const response = await this.#fetcher(`${this.#apiUrl}/delegation/store`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.#config.apiKey}`,\n 'x-api-key-id': this.#config.apiKeyId,\n 'Content-Type': 'application/json',\n },\n body,\n });\n\n const responseData: APIStoreDelegationResponse | ErrorResponse =\n await response.json();\n\n if ('error' in responseData) {\n throw new Error(responseData.error);\n }\n\n if (responseData.delegationHash !== delegationHash) {\n throw new Error(\n 'Failed to store the Delegation, the hash returned from the MM delegation storage API does not match the hash of the delegation',\n );\n }\n\n return responseData.delegationHash;\n }\n}\n","import {\n createAllowedCalldataTerms,\n createRedeemerTerms,\n createTimestampTerms,\n decodeRedeemerTerms,\n decodeTimestampTerms,\n} from '@metamask/delegation-core';\nimport { parseCaipChainId } from '@metamask/utils';\nimport { pad } from 'viem';\nimport type { Account, Address, Hex } from 'viem';\n\nimport type { Caveats } from '../caveatBuilder';\nimport { resolveCaveats } from '../caveatBuilder';\nimport { ScopeType } from '../constants';\nimport type { createOpenDelegation } from '../delegation';\nimport { decodeDelegations } from '../delegation';\nimport { getSmartAccountsEnvironment } from '../smartAccountsEnvironment';\nimport type {\n Caveat,\n Delegation,\n PermissionContext,\n SmartAccountsEnvironment,\n} from '../types';\nimport type {\n MaybeDeferred,\n PaymentRequirements,\n x402DelegationProviderConfig,\n} from './x402DelegationProviderTypes';\nimport { generateSalt } from '../utils/';\n\n/**\n * Inputs for redeemer constraint enforcement.\n */\ntype EnsureRedeemerSufficientlyConstrainedParams = {\n redeemerEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n facilitatorAddresses: Address[] | undefined;\n redeemerAddresses: Address[] | undefined;\n requireRedeemers: boolean;\n};\n\n/**\n * Inputs for payee constraint enforcement.\n */\ntype EnsurePayeeSufficientlyConstrainedParams = {\n allowedCalldataEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n payee: Hex;\n};\n\n/**\n * Inputs for expiry constraint enforcement.\n */\ntype EnsureExpirySufficientlyConstrainedParams = {\n timestampEnforcer: Hex;\n caveats: Caveat[];\n existingDelegations: Delegation[];\n expirySeconds: number;\n};\n\n/**\n * Inputs for resolving allowed redeemer addresses.\n */\ntype ResolveRedeemerAddressesParams = Pick<\n EnsureRedeemerSufficientlyConstrainedParams,\n 'facilitatorAddresses' | 'redeemerAddresses'\n>;\n\n/**\n * Resolved context required to build and sign an x402 delegation.\n */\nexport type DelegationCreationContext = {\n account: Account;\n createDelegationConfig: Parameters<typeof createOpenDelegation>[0];\n delegationManager: Address;\n existingDelegations: Delegation[];\n rootDelegator: Address;\n};\n\n/**\n * Inputs for resolving delegation caveats with x402-specific constraints.\n */\nexport type Resolvex402DelegationCaveatsParams = {\n environment: SmartAccountsEnvironment;\n caveatsConfig: Caveats | undefined;\n existingDelegations: Delegation[];\n facilitatorAddresses: Hex[] | undefined;\n payee: Hex;\n expirySeconds?: number;\n requireRedeemers: boolean;\n redeemerAddresses: Address[] | undefined;\n};\n\n/**\n * Resolves eager or deferred values against payment requirements.\n *\n * @param maybeDeferred - Value or async resolver function.\n * @param requirements - Payment requirements passed to deferred resolvers.\n * @returns The resolved value, or undefined when no value is provided.\n */\nasync function resolveMaybeDeferred<TResult>(\n maybeDeferred: MaybeDeferred<TResult>,\n requirements: PaymentRequirements,\n): Promise<TResult> {\n if (typeof maybeDeferred === 'function') {\n const deferred = maybeDeferred as (\n deferredRequirements: PaymentRequirements,\n ) => Promise<TResult> | TResult;\n\n return await deferred(requirements);\n }\n\n return maybeDeferred;\n}\n\n/**\n * Parses an EIP-155 CAIP network identifier into a numeric chain ID.\n *\n * @param network - CAIP network identifier (for example, `eip155:1`).\n * @returns Parsed numeric chain ID.\n * @throws If the CAIP namespace is not `eip155`.\n */\nexport function parseEip155ChainId(\n network: PaymentRequirements['network'],\n): number {\n const { namespace, reference } = parseCaipChainId(\n network as `${string}:${string}`,\n );\n\n if (namespace !== 'eip155') {\n throw new Error('Unsupported chain namespace');\n }\n\n const parsedChainId = Number(reference);\n\n if (isNaN(parsedChainId)) {\n throw new Error('Invalid chain id');\n }\n\n return parsedChainId;\n}\n\n/**\n * ERC-20 `transfer(address to, uint256 value)` calldata index for `to`.\n */\nconst TRANSFER_PAYEE_INDEX = 4;\n\n/**\n * Normalizes an address-like hex string for case-insensitive comparisons.\n *\n * @param address - Address value to normalize.\n * @returns Lowercased hex string.\n */\nconst normalizeAddress = (address: Address): Address =>\n address.toLowerCase() as Address;\n\n/**\n * Returns whether any caveat in local or inherited delegations matches a predicate.\n *\n * @param caveats - Current caveat list.\n * @param delegations - Existing delegations whose caveats should also be searched.\n * @param match - Predicate used to match caveats.\n * @returns True when at least one caveat satisfies `match`.\n */\nconst hasMatchingCaveats = (\n caveats: Caveat[],\n delegations: Delegation[],\n match: (caveat: Caveat) => boolean,\n): boolean => {\n for (const caveat of caveats) {\n if (match(caveat)) {\n return true;\n }\n }\n\n for (const delegation of delegations) {\n for (const caveat of delegation.caveats) {\n if (match(caveat)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\n/**\n * Ensures caveats include an expiry timestamp constraint when requested.\n *\n * If an existing timestamp caveat already enforces a tighter (earlier) or equal\n * `validBefore` threshold than requested, caveats are returned unchanged.\n * Otherwise a new timestamp caveat is appended with `afterThreshold = 0`.\n *\n * @param options0 - Expiry constraint evaluation inputs.\n * @param options0.timestampEnforcer - Address of the TimestampEnforcer caveat contract.\n * @param options0.caveats - Currently resolved caveats for the delegation being created.\n * @param options0.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param options0.expirySeconds - Relative expiry from \"now\" in seconds.\n * @returns The original caveats when sufficiently constrained, otherwise caveats with a timestamp caveat appended.\n */\nexport const ensureExpirySufficientlyConstrained = ({\n timestampEnforcer,\n caveats,\n existingDelegations,\n expirySeconds,\n}: EnsureExpirySufficientlyConstrainedParams): Caveat[] => {\n if (expirySeconds < 0) {\n throw new Error('Expiry seconds must be a positive number');\n }\n const beforeThreshold = Math.floor(Date.now() / 1000) + expirySeconds;\n const timestampEnforcerNormalized = normalizeAddress(timestampEnforcer);\n\n const hasSupersedingTimestampConstraint = hasMatchingCaveats(\n caveats,\n existingDelegations,\n (caveat) => {\n if (normalizeAddress(caveat.enforcer) !== timestampEnforcerNormalized) {\n return false;\n }\n\n const { beforeThreshold: existingBeforeThreshold } = decodeTimestampTerms(\n caveat.terms,\n );\n return (\n existingBeforeThreshold !== 0 &&\n existingBeforeThreshold <= beforeThreshold\n );\n },\n );\n\n if (hasSupersedingTimestampConstraint) {\n return caveats;\n }\n\n const timestampCaveat: Caveat = {\n enforcer: timestampEnforcer,\n terms: createTimestampTerms({\n afterThreshold: 0,\n beforeThreshold,\n }),\n args: '0x',\n };\n\n return [...caveats, timestampCaveat];\n};\n\n/**\n * Resolves allowed redeemer addresses from facilitator and configured redeemer inputs.\n *\n * If both inputs are provided, returns their intersection.\n * If only one input is provided, returns that input.\n * If neither input is provided, returns undefined.\n *\n * @param options - Redeemer address inputs.\n * @param options.facilitatorAddresses - Optional facilitator addresses from the PaymentRequirements.\n * @param options.redeemerAddresses - Optional redeemer addresses from the RedeemersConfig.\n * @returns Resolved allowed redeemer addresses, or undefined when no input is provided.\n */\nconst resolveRedeemerAddresses = ({\n facilitatorAddresses,\n redeemerAddresses,\n}: ResolveRedeemerAddressesParams): Address[] | undefined => {\n if (!facilitatorAddresses) {\n if (!redeemerAddresses) {\n return undefined;\n }\n return redeemerAddresses;\n }\n\n if (!redeemerAddresses) {\n return facilitatorAddresses;\n }\n\n const normalizedFacilitatorAddresses =\n facilitatorAddresses.map(normalizeAddress);\n\n const normalizedRedeemerAddressSet = new Set(\n redeemerAddresses.map(normalizeAddress),\n );\n\n const redeemerAddressesIntersection = normalizedFacilitatorAddresses.filter(\n (address) => normalizedRedeemerAddressSet.has(address),\n );\n\n return redeemerAddressesIntersection;\n};\n\n/**\n * Ensures caveats include a sufficiently strict redeemer constraint.\n *\n * Returns the caveat list unchanged when an existing redeemer caveat is already\n * strict enough, or appends a new redeemer caveat scoped to facilitator addresses.\n *\n * @param config - Redeemer constraint evaluation inputs.\n * @param config.redeemerEnforcer - Address of the redeemer enforcer caveat contract.\n * @param config.caveats - Currently resolved caveats for the delegation being created.\n * @param config.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param config.redeemerAddresses - Optional addresses to which redemption should be constrained.\n * @param config.requireRedeemers - Whether at least one redeemer constraint must exist.\n * @returns The original caveats when sufficiently constrained, otherwise caveats with a redeemer caveat appended.\n * @throws If either facilitatorAddresses and/or redeemerAddresses are provided, but the intersection is empty.\n * @throws If requireRedeemers is true, but no valid redeemer addresses are provided, and no existing redeemer caveat is found in the existingDelegations.\n */\nexport const ensureRedeemerSufficientlyConstrained = (\n config: EnsureRedeemerSufficientlyConstrainedParams,\n): Caveat[] => {\n // `redeemerAddresses` is the intersection of `facilitatorAddresses` and `redeemerAddresses`.\n // If either is undefined, it implies no constraint is specified by that value, and the other is returned.\n // If both are undefined, it implies that no constraint is specified overall.\n const redeemerAddresses = resolveRedeemerAddresses(config);\n\n // If the result is defined, but zero-length, it implies no redeemers are allowed, which is a non-satisfiable constraint, so an error is thrown.\n if (redeemerAddresses?.length === 0) {\n throw new Error(\n 'No valid redeemer addresses were resolved. If both `redeemers.addresses` and `extra.facilitatorAddresses` are provided, they must overlap. If only one is provided, it must include at least one address.',\n );\n }\n\n const { caveats, existingDelegations, redeemerEnforcer } = config;\n\n const redeemerEnforcerNormalized = normalizeAddress(redeemerEnforcer);\n\n if (!redeemerAddresses) {\n if (!config.requireRedeemers) {\n return caveats;\n }\n\n const hasExistingRedeemerCaveat = hasMatchingCaveats(\n caveats,\n existingDelegations,\n ({ enforcer }) =>\n normalizeAddress(enforcer) === redeemerEnforcerNormalized,\n );\n\n if (!hasExistingRedeemerCaveat) {\n throw new Error(\n 'Redeemer must be constrained, either in the specified `caveats`, `parentPermissionContext`, or the `PaymentRequirements` as `extra.facilitatorAddresses`.',\n );\n }\n\n return caveats;\n }\n\n const redeemerAddressesSet = new Set(redeemerAddresses.map(normalizeAddress));\n\n const hasSupersedingRedeemerCaveat = hasMatchingCaveats(\n caveats,\n existingDelegations,\n (caveat) => {\n if (normalizeAddress(caveat.enforcer) !== redeemerEnforcerNormalized) {\n return false;\n }\n\n const allowedRedeemerAddresses = decodeRedeemerTerms(\n caveat.terms,\n ).redeemers.map(normalizeAddress);\n\n // If this redeemer caveat only allows redeemer addresses, it is sufficiently constrained.\n return allowedRedeemerAddresses.every((item) =>\n redeemerAddressesSet.has(item),\n );\n },\n );\n\n if (hasSupersedingRedeemerCaveat) {\n return caveats;\n }\n\n const redeemerCaveat: Caveat = {\n enforcer: redeemerEnforcer,\n terms: createRedeemerTerms({ redeemers: redeemerAddresses }),\n args: '0x',\n };\n\n return [...caveats, redeemerCaveat];\n};\n\n/**\n * Ensures caveats include an allowed-calldata constraint for the payment payee.\n *\n * Scans both the in-progress caveat list and parent delegation caveats for an\n * `AllowedCalldataEnforcer` caveat whose terms match the encoded payee calldata\n * constraint. If found, returns caveats unchanged; otherwise appends a payee caveat.\n *\n * @param options0 - Payee constraint evaluation inputs.\n * @param options0.allowedCalldataEnforcer - Address of the AllowedCalldataEnforcer caveat contract.\n * @param options0.caveats - Currently resolved caveats for the delegation being created.\n * @param options0.existingDelegations - Existing parent-chain delegations to inspect for inherited constraints.\n * @param options0.payee - Expected ERC-20 transfer recipient to enforce in calldata.\n * @returns The original caveats when an equivalent payee constraint exists, otherwise caveats with a payee caveat appended.\n */\nexport const ensurePayeeSufficientlyConstrained = ({\n allowedCalldataEnforcer,\n caveats,\n existingDelegations,\n payee,\n}: EnsurePayeeSufficientlyConstrainedParams): Caveat[] => {\n const allowedCalldataTerms = createAllowedCalldataTerms({\n startIndex: TRANSFER_PAYEE_INDEX,\n value: pad(payee, { size: 32 }),\n });\n\n const allowedCalldataEnforcerNormalized = normalizeAddress(\n allowedCalldataEnforcer,\n );\n\n const lowercaseCalldataTerms = allowedCalldataTerms.toLowerCase();\n\n const hasSupersedingAllowedCalldataConstraint = hasMatchingCaveats(\n caveats,\n existingDelegations,\n ({ enforcer, terms }) =>\n normalizeAddress(enforcer) === allowedCalldataEnforcerNormalized &&\n terms.toLowerCase() === lowercaseCalldataTerms,\n );\n\n if (hasSupersedingAllowedCalldataConstraint) {\n return caveats;\n }\n\n const payeeCaveat: Caveat = {\n enforcer: allowedCalldataEnforcer,\n terms: allowedCalldataTerms,\n args: '0x',\n };\n\n return [...caveats, payeeCaveat];\n};\n\n/**\n * Resolves caveats and applies x402-specific redeemer and payee constraints.\n *\n * @param options0 - Caveat resolution inputs.\n * @param options0.environment - Environment containing caveat enforcer addresses.\n * @param options0.caveatsConfig - Optional caveat builder config.\n * @param options0.existingDelegations - Existing parent-chain delegations.\n * @param options0.facilitatorAddresses - Optional facilitator addresses used for redeemer constraints.\n * @param options0.payee - Payee address used for allowed calldata constraints.\n * @param options0.expirySeconds - Optional relative expiry in seconds for adding timestamp constraints.\n * @param options0.requireRedeemers - Whether redeemer constraints are mandatory when no facilitator or configured redeemer addresses are present.\n * @param options0.redeemerAddresses - Optional redeemer addresses from provider config to merge with facilitator addresses.\n * @returns Caveats after redeemer and payee constraints are enforced.\n */\nexport const resolvex402DelegationCaveats = ({\n environment,\n caveatsConfig,\n existingDelegations,\n facilitatorAddresses,\n payee,\n expirySeconds,\n requireRedeemers,\n redeemerAddresses,\n}: Resolvex402DelegationCaveatsParams): Caveat[] => {\n const {\n caveatEnforcers: {\n RedeemerEnforcer: redeemerEnforcer,\n AllowedCalldataEnforcer: allowedCalldataEnforcer,\n TimestampEnforcer: timestampEnforcer,\n },\n } = environment;\n\n if (!redeemerEnforcer) {\n throw new Error('RedeemerEnforcer not found in environment');\n }\n\n if (!allowedCalldataEnforcer) {\n throw new Error('AllowedCalldataEnforcer not found in environment');\n }\n\n if (!timestampEnforcer) {\n throw new Error('TimestampEnforcer not found in environment');\n }\n\n const initialCaveats = resolveCaveats({\n environment,\n caveats: caveatsConfig,\n // Resolve caveats first so downstream constraint checks can append as needed.\n // Scope is still attached later during delegation creation.\n isScopeOptional: true,\n });\n\n const caveatsWithRedeemer = ensureRedeemerSufficientlyConstrained({\n redeemerEnforcer,\n facilitatorAddresses,\n redeemerAddresses,\n caveats: initialCaveats,\n existingDelegations,\n requireRedeemers,\n });\n\n const caveatsWithPayee = ensurePayeeSufficientlyConstrained({\n allowedCalldataEnforcer,\n caveats: caveatsWithRedeemer,\n existingDelegations,\n payee,\n });\n\n if (expirySeconds === undefined) {\n return caveatsWithPayee;\n }\n\n return ensureExpirySufficientlyConstrained({\n timestampEnforcer,\n caveats: caveatsWithPayee,\n existingDelegations,\n expirySeconds,\n });\n};\n\n/**\n * Builds the delegation creation context from provider config and requirements.\n *\n * @param config - Delegation provider config for context construction.\n * @param requirements - Payment requirements used to scope caveats.\n * @returns The resolved context used to create and sign a delegation.\n */\nexport const resolveDelegationCreationContext = async (\n config: x402DelegationProviderConfig,\n requirements: PaymentRequirements,\n): Promise<DelegationCreationContext> => {\n const account = await resolveMaybeDeferred(config.account, requirements);\n const redeemersConfig = await resolveMaybeDeferred(\n config.redeemers,\n requirements,\n );\n\n const requireRedeemers = redeemersConfig?.requireRedeemers ?? false;\n const redeemerAddresses = await resolveMaybeDeferred(\n redeemersConfig?.addresses,\n requirements,\n );\n\n const specifiedEnvironment = await resolveMaybeDeferred(\n config.environment,\n requirements,\n );\n const environment =\n specifiedEnvironment ??\n getSmartAccountsEnvironment(parseEip155ChainId(requirements.network));\n\n const caveatsConfig: Caveats | undefined = await resolveMaybeDeferred(\n config.caveats,\n requirements,\n );\n const parentPermissionContext: PermissionContext | undefined =\n await resolveMaybeDeferred(config.parentPermissionContext, requirements);\n const expirySeconds = await resolveMaybeDeferred(\n config.expirySeconds,\n requirements,\n );\n\n const from =\n (await resolveMaybeDeferred(config.from, requirements)) ?? account.address;\n const salt =\n (await resolveMaybeDeferred(config.salt, requirements)) ?? generateSalt();\n\n const scope = {\n type: ScopeType.Erc20TransferAmount,\n tokenAddress: requirements.asset as Hex,\n maxAmount: BigInt(requirements.amount),\n } as const;\n\n const facilitatorAddresses = requirements.extra?.facilitatorAddresses as\n | Hex[]\n | undefined;\n\n const existingDelegations = parentPermissionContext\n ? decodeDelegations(parentPermissionContext)\n : [];\n\n const { DelegationManager: delegationManager } = environment;\n const caveats = resolvex402DelegationCaveats({\n environment,\n caveatsConfig,\n existingDelegations,\n facilitatorAddresses,\n payee: requirements.payTo as Hex,\n expirySeconds,\n requireRedeemers,\n redeemerAddresses,\n });\n\n let createDelegationConfig: Parameters<typeof createOpenDelegation>[0];\n\n if (parentPermissionContext) {\n const parentDelegation = existingDelegations[0];\n\n if (!parentDelegation) {\n throw new Error('Parent permission context is not a valid delegation');\n }\n\n createDelegationConfig = {\n environment,\n from,\n caveats,\n salt,\n scope,\n parentDelegation,\n };\n } else {\n createDelegationConfig = {\n environment,\n from,\n caveats,\n salt,\n scope,\n };\n }\n\n const rootDelegator =\n existingDelegations[existingDelegations.length - 1]?.delegator ?? from;\n\n return {\n account,\n createDelegationConfig,\n delegationManager,\n existingDelegations,\n rootDelegator,\n };\n};\n","import type { Address } from 'viem';\n\nimport {\n createOpenDelegation,\n encodeDelegations,\n prepareSignDelegationTypedData,\n} from '../delegation';\nimport type {\n PaymentRequirements,\n x402DelegationProvider,\n x402DelegationProviderConfig,\n x402DelegationProviderPaymentPayload,\n} from './x402DelegationProviderTypes';\nimport {\n parseEip155ChainId,\n resolveDelegationCreationContext,\n} from './x402DelegationProviderUtils';\n\nexport type {\n MaybeDeferred,\n PaymentRequirements,\n x402DelegationProvider,\n x402DelegationProviderConfig,\n x402DelegationProviderPaymentPayload,\n} from './x402DelegationProviderTypes';\n\nexport { parseEip155ChainId } from './x402DelegationProviderUtils';\n\nexport const METAMASK_FACILITATOR_ADDRESSES: readonly Address[] = [\n '0xB01caEa8c6C47bbf4F4b4c5080Ca642043359C2E',\n '0xC066ac5D385419B1A8c43A0E146fA439837a8B8c',\n '0xB42F812A44c22cc6b861478900401ee759EbEAD6',\n];\nexport const METAMASK_FACILITATOR_ADDRESSES_DEV: readonly Address[] = [\n '0xb4827A2a066CD2Ef88560EFdf063dD05C6c41cC7',\n];\n\n/**\n * Creates a delegation provider function for x402 payment requirements.\n *\n * The returned provider resolves deferred config values using incoming payment\n * requirements, creates an open delegation, signs it, and returns an encoded\n * permission context payload.\n *\n * @param config - Delegation creation and signing configuration.\n * @returns A provider that maps payment requirements to a signed delegation payload.\n */\nexport function createx402DelegationProvider(\n config: x402DelegationProviderConfig,\n): x402DelegationProvider {\n return async (\n requirements: PaymentRequirements,\n ): Promise<x402DelegationProviderPaymentPayload> => {\n const {\n account,\n createDelegationConfig,\n delegationManager,\n existingDelegations,\n rootDelegator,\n } = await resolveDelegationCreationContext(config, requirements);\n\n const delegation = createOpenDelegation(createDelegationConfig);\n\n const chainId = parseEip155ChainId(requirements.network);\n\n const typedData = prepareSignDelegationTypedData({\n delegationManager,\n chainId,\n delegation,\n });\n\n if (!account.signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n const signature = await account.signTypedData(typedData);\n\n const signedDelegation = {\n ...delegation,\n signature,\n };\n\n const permissionContext = encodeDelegations([\n signedDelegation,\n ...existingDelegations,\n ]);\n\n return {\n delegationManager,\n permissionContext,\n delegator: rootDelegator,\n };\n };\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  generateSalt
3
3
  } from "../chunk-IMO6XNDJ.mjs";
4
- import "../chunk-T6SWQZRX.mjs";
4
+ import "../chunk-D55SIIVM.mjs";
5
5
  import {
6
6
  getSmartAccountsEnvironment
7
7
  } from "../chunk-GMGJRC3D.mjs";
8
- import "../chunk-EMPAUTIV.mjs";
8
+ import "../chunk-5ENRJKXL.mjs";
9
9
  import {
10
10
  createOpenDelegation,
11
11
  decodeDelegations,
@@ -14,7 +14,7 @@ import {
14
14
  prepareSignDelegationTypedData,
15
15
  resolveCaveats,
16
16
  trackSmartAccountsKitFunctionCall
17
- } from "../chunk-3KWKQ7PV.mjs";
17
+ } from "../chunk-XBHL6PDR.mjs";
18
18
 
19
19
  // src/experimental/delegationStorage.ts
20
20
  import { toHex } from "viem";