@metamask/smart-accounts-kit 0.4.0-beta.0 → 0.4.0-beta.2

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 (79) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/dist/actions/index.cjs +5 -5
  3. package/dist/actions/index.d.cts +2 -2
  4. package/dist/actions/index.d.ts +2 -2
  5. package/dist/actions/index.mjs +4 -4
  6. package/dist/{chunk-S2Q5ZC64.cjs → chunk-23YXLKTX.cjs} +58 -59
  7. package/dist/chunk-23YXLKTX.cjs.map +1 -0
  8. package/dist/{chunk-W6ZI7GWI.mjs → chunk-33AMUJBJ.mjs} +49 -52
  9. package/dist/chunk-33AMUJBJ.mjs.map +1 -0
  10. package/dist/{chunk-TEH426Y4.mjs → chunk-C5ZEEH2Z.mjs} +283 -184
  11. package/dist/chunk-C5ZEEH2Z.mjs.map +1 -0
  12. package/dist/{chunk-NTZ57GNF.cjs → chunk-DLD377CN.cjs} +17 -33
  13. package/dist/chunk-DLD377CN.cjs.map +1 -0
  14. package/dist/{chunk-5BYJZGRI.mjs → chunk-NOCLGZGB.mjs} +174 -129
  15. package/dist/chunk-NOCLGZGB.mjs.map +1 -0
  16. package/dist/{chunk-EHIZB5U7.mjs → chunk-QCULIK3O.mjs} +211 -97
  17. package/dist/chunk-QCULIK3O.mjs.map +1 -0
  18. package/dist/{chunk-YWRHYLKB.cjs → chunk-QMRKCB7T.cjs} +204 -159
  19. package/dist/chunk-QMRKCB7T.cjs.map +1 -0
  20. package/dist/{chunk-TXN7GX6Y.cjs → chunk-SOFB2MXG.cjs} +207 -93
  21. package/dist/chunk-SOFB2MXG.cjs.map +1 -0
  22. package/dist/{chunk-RAXFJGCS.cjs → chunk-UUOH2WAW.cjs} +19 -19
  23. package/dist/chunk-UUOH2WAW.cjs.map +1 -0
  24. package/dist/{chunk-AUCZDOTJ.mjs → chunk-WPVSFOQM.mjs} +11 -27
  25. package/dist/chunk-WPVSFOQM.mjs.map +1 -0
  26. package/dist/{chunk-4A5RMDDC.mjs → chunk-WV2R7BXP.mjs} +49 -50
  27. package/dist/chunk-WV2R7BXP.mjs.map +1 -0
  28. package/dist/{chunk-YTGYVHDF.cjs → chunk-XN36L4RX.cjs} +144 -147
  29. package/dist/chunk-XN36L4RX.cjs.map +1 -0
  30. package/dist/{chunk-MIP7KJYH.cjs → chunk-YDLLC6PP.cjs} +252 -153
  31. package/dist/chunk-YDLLC6PP.cjs.map +1 -0
  32. package/dist/{chunk-DPWYECSV.mjs → chunk-YTELOQ4I.mjs} +9 -9
  33. package/dist/chunk-YTELOQ4I.mjs.map +1 -0
  34. package/dist/contracts/index.cjs +5 -5
  35. package/dist/contracts/index.d.cts +3 -3
  36. package/dist/contracts/index.d.ts +3 -3
  37. package/dist/contracts/index.mjs +4 -4
  38. package/dist/{delegation-DHjM_pVa.d.ts → delegation-DGUfyX-C.d.ts} +52 -26
  39. package/dist/{delegation-BnhAvKt4.d.cts → delegation-D_TY-tAq.d.cts} +52 -26
  40. package/dist/experimental/index.cjs +4 -4
  41. package/dist/experimental/index.cjs.map +1 -1
  42. package/dist/experimental/index.d.cts +1 -1
  43. package/dist/experimental/index.d.ts +1 -1
  44. package/dist/experimental/index.mjs +5 -5
  45. package/dist/experimental/index.mjs.map +1 -1
  46. package/dist/{index-CX3hrztI.d.cts → index-B9bsjGqI.d.ts} +240 -38
  47. package/dist/{index-D04LO0vH.d.cts → index-CZes99jV.d.cts} +95 -62
  48. package/dist/{index-i8cod4JY.d.ts → index-DvcKJcXi.d.cts} +240 -38
  49. package/dist/{index-BlgCQ80b.d.ts → index-FpCh2419.d.ts} +95 -62
  50. package/dist/index.cjs +26 -24
  51. package/dist/index.cjs.map +1 -1
  52. package/dist/index.d.cts +9 -11
  53. package/dist/index.d.ts +9 -11
  54. package/dist/index.mjs +17 -15
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/{smartAccountsEnvironment-SVknZ_3f.d.cts → smartAccountsEnvironment-BU8kjlEv.d.cts} +1 -1
  57. package/dist/{smartAccountsEnvironment-BOhrxEnt.d.ts → smartAccountsEnvironment-egxuflDO.d.ts} +1 -1
  58. package/dist/{types-Bwksz_U6.d.ts → types-BLYWtcR3.d.cts} +49 -31
  59. package/dist/{types-Bwksz_U6.d.cts → types-BLYWtcR3.d.ts} +49 -31
  60. package/dist/utils/index.cjs +7 -5
  61. package/dist/utils/index.cjs.map +1 -1
  62. package/dist/utils/index.d.cts +3 -4
  63. package/dist/utils/index.d.ts +3 -4
  64. package/dist/utils/index.mjs +12 -10
  65. package/package.json +6 -11
  66. package/dist/chunk-4A5RMDDC.mjs.map +0 -1
  67. package/dist/chunk-5BYJZGRI.mjs.map +0 -1
  68. package/dist/chunk-AUCZDOTJ.mjs.map +0 -1
  69. package/dist/chunk-DPWYECSV.mjs.map +0 -1
  70. package/dist/chunk-EHIZB5U7.mjs.map +0 -1
  71. package/dist/chunk-MIP7KJYH.cjs.map +0 -1
  72. package/dist/chunk-NTZ57GNF.cjs.map +0 -1
  73. package/dist/chunk-RAXFJGCS.cjs.map +0 -1
  74. package/dist/chunk-S2Q5ZC64.cjs.map +0 -1
  75. package/dist/chunk-TEH426Y4.mjs.map +0 -1
  76. package/dist/chunk-TXN7GX6Y.cjs.map +0 -1
  77. package/dist/chunk-W6ZI7GWI.mjs.map +0 -1
  78. package/dist/chunk-YTGYVHDF.cjs.map +0 -1
  79. package/dist/chunk-YWRHYLKB.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/actions/index.ts","../src/actions/erc7710RedeemDelegationAction.ts","../src/actions/erc7715GetGrantedExecutionPermissionsAction.ts","../src/actions/erc7715GetSupportedExecutionPermissionsAction.ts","../src/actions/erc7715RequestExecutionPermissionsAction.ts","../src/actions/getCaveatAvailableAmount.ts","../src/actions/isValid7702Implementation.ts","../src/actions/signDelegation.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';\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\nexport {\n erc7715RequestExecutionPermissionsAction as requestExecutionPermissions,\n type MetaMaskExtensionClient,\n type MetaMaskExtensionSchema,\n type RequestExecutionPermissionsParameters,\n type RequestExecutionPermissionsReturnType,\n} from './erc7715RequestExecutionPermissionsAction';\n\nexport { erc7715GetSupportedExecutionPermissionsAction as getSupportedExecutionPermissions } from './erc7715GetSupportedExecutionPermissionsAction';\n\nexport { erc7715GetGrantedExecutionPermissionsAction as getGrantedExecutionPermissions } from './erc7715GetGrantedExecutionPermissionsAction';\n\nexport {\n type GetSupportedExecutionPermissionsResult,\n type GetGrantedExecutionPermissionsResult,\n type SupportedPermissionInfo,\n} from './erc7715Types';\n\nexport type { DelegatedCall } from './erc7710RedeemDelegationAction';\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\nexport const erc7710WalletActions = () => (client: WalletClient) => ({\n sendTransactionWithDelegation: async (\n args: SendTransactionWithDelegationParameters,\n ) => sendTransactionWithDelegationAction(client, args),\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 {\n createExecution,\n encodeExecutionCalldatas,\n ExecutionMode,\n} from '../executions';\nimport { getSmartAccountsEnvironment } from '../smartAccountsEnvironment';\nimport type { Call } from '../types';\n\nexport type DelegatedCall = Call &\n OneOf<{ permissionsContext: Hex; delegationManager: Hex } | object>;\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 permissionsContext: Hex;\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 if (!args.to) {\n throw new Error(\n '`to` is required. `sendTransactionWithDelegation` cannot be used to deploy contracts.',\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.abi,\n functionName: 'redeemDelegations',\n args: [\n [args.permissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([executions]),\n ],\n });\n\n const {\n value: _value,\n permissionsContext: _permissionsContext,\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 accountMetadata?: { 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 * permissionsContext: '0x...',\n * delegationManager: '0x...',\n * },\n * ],\n * accountMetadata: [{ 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 if (parameters.accountMetadata) {\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 uniqueAccountMetadatas = parameters.accountMetadata.filter(\n (accountMetadata) => {\n if (!isAddressEqual(accountMetadata.factory, SimpleFactory)) {\n throw new Error(\n `Invalid accountMetadata: ${accountMetadata.factory} is not allowed.`,\n );\n }\n\n // ensure that factory calls are not duplicated\n const accountKey = concat([\n accountMetadata.factory,\n accountMetadata.factoryData,\n ]);\n const isDuplicate = includedAccountKeys[accountKey];\n\n includedAccountKeys[accountKey] = true;\n return !isDuplicate;\n },\n );\n\n const factoryCalls = (\n await Promise.all(\n uniqueAccountMetadatas.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 return client.sendUserOperation(\n parameters as unknown as SendUserOperationParameters,\n );\n}\n","import type {\n GetGrantedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n} 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\n * ```\n */\nexport async function erc7715GetGrantedExecutionPermissionsAction(\n client: MetaMaskExtensionClient,\n): Promise<GetGrantedExecutionPermissionsResult> {\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 result;\n}\n","import type {\n GetSupportedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n} 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\": [\"0x1\", \"0x89\"],\n * // \"ruleTypes\": [\"expiry\"]\n * // },\n * // \"erc20-token-allowance\": {\n * // \"chainIds\": [\"0x1\"],\n * // \"ruleTypes\": []\n * // }\n * // }\n * ```\n */\nexport async function erc7715GetSupportedExecutionPermissionsAction(\n client: MetaMaskExtensionClient,\n): Promise<GetSupportedExecutionPermissionsResult> {\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 result;\n}\n","import type {\n Erc20TokenPeriodicPermission,\n Erc20TokenStreamPermission,\n Erc20TokenRevocationPermission,\n NativeTokenPeriodicPermission,\n NativeTokenStreamPermission,\n PermissionRequest,\n PermissionResponse,\n PermissionTypes,\n Rule,\n Hex,\n} from '@metamask/7715-permission-types';\nimport { toHex } from 'viem';\nimport type { Address } from 'viem';\n\nimport { isDefined, toHexOrThrow } from '../utils';\nimport type { MetaMaskExtensionClient } from './erc7715Types';\n\nexport type {\n GetGrantedExecutionPermissionsResult,\n GetSupportedExecutionPermissionsResult,\n MetaMaskExtensionClient,\n MetaMaskExtensionSchema,\n SupportedPermissionInfo,\n} from './erc7715Types';\n\ntype PermissionParameter = {\n type: string;\n data: Record<string, unknown>;\n};\n\n/**\n * Represents a native token stream permission.\n * This allows for continuous token streaming with defined parameters.\n */\nexport type NativeTokenStreamPermissionParameter = PermissionParameter & {\n type: 'native-token-stream';\n data: {\n amountPerSecond: bigint;\n initialAmount?: bigint;\n maxAmount?: bigint;\n startTime?: number;\n justification?: string;\n };\n};\n\n/**\n * Represents an ERC-20 token stream permission.\n * This allows for continuous ERC-20 token streaming with defined parameters.\n */\nexport type Erc20TokenStreamPermissionParameter = PermissionParameter & {\n type: 'erc20-token-stream';\n data: {\n tokenAddress: Address;\n amountPerSecond: bigint;\n initialAmount?: bigint;\n maxAmount?: bigint;\n startTime?: number;\n justification?: string;\n };\n};\n\n/**\n * Represents a native token periodic permission.\n * This allows for periodic native token transfers with defined parameters.\n */\nexport type NativeTokenPeriodicPermissionParameter = PermissionParameter & {\n type: 'native-token-periodic';\n data: {\n periodAmount: bigint;\n periodDuration: number;\n startTime?: number;\n justification?: string;\n };\n};\n\n/**\n * Represents an ERC-20 token periodic permission.\n * This allows for periodic ERC-20 token transfers with defined parameters.\n */\nexport type Erc20TokenPeriodicPermissionParameter = PermissionParameter & {\n type: 'erc20-token-periodic';\n data: {\n tokenAddress: Address;\n periodAmount: bigint;\n periodDuration: number;\n startTime?: number;\n justification?: string;\n };\n};\n\n/**\n * Represents an ERC-20 token revocation permission.\n * This allows for revoking an ERC-20 token allowance.\n */\nexport type Erc20TokenRevocationPermissionParameter = PermissionParameter & {\n type: 'erc20-token-revocation';\n data: {\n justification?: string;\n };\n};\n\nexport type SupportedPermissionParams =\n | NativeTokenStreamPermissionParameter\n | Erc20TokenStreamPermissionParameter\n | NativeTokenPeriodicPermissionParameter\n | Erc20TokenPeriodicPermissionParameter\n | Erc20TokenRevocationPermissionParameter;\n\n/**\n * Represents a single permission request.\n */\nexport type PermissionRequestParameter = {\n chainId: number;\n // The permission to grant to the user.\n permission: SupportedPermissionParams;\n // Whether the caller allows the permission to be adjusted.\n isAdjustmentAllowed: boolean;\n // Account to assign the permission to.\n to: Hex;\n // address from which the permission should be granted.\n from?: Address | undefined | null;\n // Timestamp (in seconds) that specifies the time by which this permission MUST expire.\n expiry?: number | undefined | null;\n};\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 PermissionResponse<PermissionTypes>[];\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 const formattedPermissionRequest = parameters.map(formatPermissionsRequest);\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 result;\n}\n\n/**\n * Formats a permissions request for submission to the wallet.\n *\n * @param parameters - The permissions request to format.\n * @returns The formatted permissions request.\n * @internal\n */\nfunction formatPermissionsRequest(\n parameters: PermissionRequestParameter,\n): PermissionRequest<PermissionTypes> {\n const { chainId, from, expiry, isAdjustmentAllowed } = parameters;\n\n const permissionFormatter = getPermissionFormatter(\n parameters.permission.type,\n );\n\n const rules: Rule[] = isDefined(expiry)\n ? [\n {\n type: 'expiry',\n data: {\n timestamp: expiry,\n },\n },\n ]\n : [];\n\n const optionalFields = {\n ...(from ? { from } : {}),\n };\n\n return {\n ...optionalFields,\n chainId: toHex(chainId),\n permission: permissionFormatter({\n permission: parameters.permission,\n isAdjustmentAllowed,\n }),\n to: parameters.to,\n rules,\n };\n}\n\ntype PermissionFormatter = (params: {\n permission: PermissionParameter;\n isAdjustmentAllowed: boolean;\n}) => PermissionTypes;\n\n/**\n * Gets the appropriate formatter function for a specific permission type.\n *\n * @param permissionType - The type of permission to format.\n * @returns A formatter function for the specified permission type.\n */\nfunction getPermissionFormatter(permissionType: string): PermissionFormatter {\n switch (permissionType) {\n case 'native-token-stream':\n return ({ permission, isAdjustmentAllowed }) =>\n formatNativeTokenStreamPermission({\n permission: permission as NativeTokenStreamPermissionParameter,\n isAdjustmentAllowed,\n });\n case 'erc20-token-stream':\n return ({ permission, isAdjustmentAllowed }) =>\n formatErc20TokenStreamPermission({\n permission: permission as Erc20TokenStreamPermissionParameter,\n isAdjustmentAllowed,\n });\n\n case 'native-token-periodic':\n return ({ permission, isAdjustmentAllowed }) =>\n formatNativeTokenPeriodicPermission({\n permission: permission as NativeTokenPeriodicPermissionParameter,\n isAdjustmentAllowed,\n });\n case 'erc20-token-periodic':\n return ({ permission, isAdjustmentAllowed }) =>\n formatErc20TokenPeriodicPermission({\n permission: permission as Erc20TokenPeriodicPermissionParameter,\n isAdjustmentAllowed,\n });\n case 'erc20-token-revocation':\n return ({ permission, isAdjustmentAllowed }) =>\n formatErc20TokenRevocationPermission({\n permission: permission as Erc20TokenRevocationPermissionParameter,\n isAdjustmentAllowed,\n });\n default:\n throw new Error(`Unsupported permission type: ${permissionType}`);\n }\n}\n\n/**\n * Formats a native token stream permission for the wallet.\n *\n * @param permission - The native token stream permission to format.\n * @param permission.permission - The native token stream permission to format.\n * @param permission.isAdjustmentAllowed - Whether the permission is allowed to be adjusted.\n * @returns The formatted permission object.\n */\nfunction formatNativeTokenStreamPermission({\n permission,\n isAdjustmentAllowed,\n}: {\n permission: NativeTokenStreamPermissionParameter;\n isAdjustmentAllowed: boolean;\n}): NativeTokenStreamPermission {\n const {\n data: {\n initialAmount,\n justification,\n maxAmount,\n startTime,\n amountPerSecond,\n },\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 * Formats an ERC-20 token stream permission parameter into the required\n * Erc20TokenStreamPermission object, converting numeric values to hex strings\n * and including only specified optional fields.\n *\n * @param params - The parameters for formatting the ERC-20 token stream permission.\n * @param params.permission - The ERC-20 token stream permission parameter to format.\n * @param params.isAdjustmentAllowed - Whether adjustment of the stream is allowed.\n * @returns The formatted Erc20TokenStreamPermission object.\n */\nfunction formatErc20TokenStreamPermission({\n permission,\n isAdjustmentAllowed,\n}: {\n permission: Erc20TokenStreamPermissionParameter;\n isAdjustmentAllowed: boolean;\n}): Erc20TokenStreamPermission {\n const {\n data: {\n tokenAddress,\n amountPerSecond,\n initialAmount,\n startTime,\n maxAmount,\n justification,\n },\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 * Formats a native token periodic permission for submission to the wallet.\n *\n * @param params - The parameters for formatting the native token periodic permission.\n * @param params.permission - The native token periodic permission parameter to format.\n * @param params.isAdjustmentAllowed - Whether the permission is allowed to be adjusted.\n * @returns The formatted NativeTokenPeriodicPermission object.\n */\nfunction formatNativeTokenPeriodicPermission({\n permission,\n isAdjustmentAllowed,\n}: {\n permission: NativeTokenPeriodicPermissionParameter;\n isAdjustmentAllowed: boolean;\n}): NativeTokenPeriodicPermission {\n const {\n data: { periodAmount, periodDuration, startTime, justification },\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 * Formats an ERC20 token periodic permission for submission to the wallet.\n *\n * @param params - The parameters for formatting the ERC20 token periodic permission.\n * @param params.permission - The ERC20 token periodic permission parameter to format.\n * @param params.isAdjustmentAllowed - Whether the permission is allowed to be adjusted.\n * @returns The formatted Erc20TokenPeriodicPermission object.\n */\nfunction formatErc20TokenPeriodicPermission({\n permission,\n isAdjustmentAllowed,\n}: {\n permission: Erc20TokenPeriodicPermissionParameter;\n isAdjustmentAllowed: boolean;\n}): Erc20TokenPeriodicPermission {\n const {\n data: {\n tokenAddress,\n periodAmount,\n periodDuration,\n startTime,\n justification,\n },\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 * Formats an ERC-20 token revocation permission for submission to the wallet.\n *\n * @param params - The parameters for formatting the ERC-20 token revocation permission.\n * @param params.permission - The ERC-20 token revocation permission parameter to format.\n * @param params.isAdjustmentAllowed - Whether the permission is allowed to be adjusted.\n * @returns The formatted Erc20TokenRevocationPermission object.\n */\nfunction formatErc20TokenRevocationPermission({\n permission,\n isAdjustmentAllowed,\n}: {\n permission: Erc20TokenRevocationPermissionParameter;\n isAdjustmentAllowed: boolean;\n}): Erc20TokenRevocationPermission {\n const {\n data: { justification },\n } = permission;\n\n const data = {\n ...(justification ? { justification } : {}),\n };\n return {\n type: 'erc20-token-revocation',\n data,\n isAdjustmentAllowed,\n };\n}\n","import type { Address, Hex, Client } from 'viem';\n\nimport { getDelegationHashOffchain } 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 const enforcerName = 'ERC20PeriodTransferEnforcer';\n\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = getDelegationHashOffchain(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 const enforcerName = 'ERC20StreamingEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = getDelegationHashOffchain(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 const enforcerName = 'MultiTokenPeriodEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = getDelegationHashOffchain(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 const enforcerName = 'NativeTokenPeriodTransferEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = getDelegationHashOffchain(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 const enforcerName = 'NativeTokenStreamingEnforcer';\n const delegationManager = getDelegationManager(environment);\n const enforcerAddress = getEnforcerAddress({\n enforcerName,\n environment,\n });\n\n const delegationHash = getDelegationHashOffchain(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 { 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 {\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;;;ACAA,SAAS,yBAAyB;AAYlC,SAAS,QAAQ,oBAAoB,sBAAsB;AAoC3D,eAAsB,oCAIpB,QACA,MACA;AACA,MAAI,CAAC,KAAK,IAAI;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,aAAa;AAAA,IACjB,gBAAgB;AAAA,MACd,QAAQ,KAAK;AAAA,MACb,OAAO,KAAK;AAAA,MACZ,UAAU,KAAK;AAAA,IACjB,CAAC;AAAA,EACH;AAEA,QAAM,WAAW,mBAAmB;AAAA,IAClC,KAAK,kBAAkB;AAAA,IACvB,cAAc;AAAA,IACd,MAAM;AAAA,MACJ,CAAC,KAAK,kBAAkB;AAAA,MACxB,yFAA4B;AAAA,MAC5B,yBAAyB,CAAC,UAAU,CAAC;AAAA,IACvC;AAAA,EACF,CAAC;AAED,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,oBAAoB;AAAA,IACpB,mBAAmB;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AAA,EACnE,+BAA+B,OAC7B,SACG,oCAAoC,QAAQ,IAAI;AACvD;AAEO,IAAM,wBAAwB,MAAM,CAAC,YAAoB;AAAA,EAC9D,iCAAiC,OAC/B,SACG,sCAAsC,QAAyB,IAAI;AAC1E;","names":["read_exports","isAddressEqual","BaseError","parseAccount","BaseError","parseAccount"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/counterfactualAccountData.ts","../src/encodeCalls.ts","../src/webAuthn.ts"],"sourcesContent":["/**\n * To be used in sdk methods to call Implementation specific code\n *\n */\nexport enum Implementation {\n MultiSig = 'MultiSig',\n Hybrid = 'Hybrid',\n Stateless7702 = 'Stateless7702',\n}\n\n/**\n * Represents predefined time intervals (in seconds) for transfer windows.\n * These values are commonly used to specify the duration of transfer periods,\n * such as hourly, daily, weekly, etc., where each enum member's value is the\n * number of seconds in that interval.\n *\n * Hourly - 1 hour (3600 seconds)\n *\n * Daily - 1 day (86400 seconds)\n *\n * Weekly - 1 week (604800 seconds)\n *\n * BiWeekly - 2 weeks (1209600 seconds)\n *\n * Monthly - 1 month (30 days, 2592000 seconds)\n *\n * Quarterly - 1 quarter (90 days, 7776000 seconds)\n *\n * Yearly - 1 year (365 days, 31536000 seconds)\n */\nexport enum TransferWindow {\n Hourly = 3600, // 60 * 60 (seconds)\n Daily = 86400, // 60 * 60 * 24 (seconds)\n Weekly = 604800, // 60 * 60 * 24 * 7 (seconds)\n BiWeekly = 1209600, // 60 * 60 * 24 * 14 (seconds)\n Monthly = 2592000, // 60 * 60 * 24 * 30 (seconds)\n Quarterly = 7776000, // 60 * 60 * 24 * 90 (seconds)\n Yearly = 31536000, // 60 * 60 * 24 * 365 (seconds)\n}\n","import type { Address, Hex } from 'viem';\nimport { getContractAddress, pad } from 'viem';\n\nimport { Implementation } from './constants';\nimport { initializeHybridDeleGator } from './DelegationFramework/HybridDeleGator/encode';\nimport { initializeMultiSigDeleGator } from './DelegationFramework/MultiSigDeleGator/encode';\nimport { create2Deploy as encodeCreate2Deploy } from './DelegationFramework/SimpleFactory/encode';\nimport { encodeProxyCreationCode } from './DelegationFramework/utils';\nimport type {\n SmartAccountsEnvironment,\n HybridDeleGatorDeployParams,\n MultiSigDeleGatorDeployParams,\n DeployParams,\n} from './types';\n\n/**\n * Infers counterfactual account data for a DeleGator smart account.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @template TDeployParams - The type of deployment parameters, defaults to DeployParams<Implementation>.\n * @param options - The options for generating counterfactual account data.\n * @param options.factory - The address of the SimpleFactory contract.\n * @param options.implementations - The DeleGator implementation contracts.\n * @param options.implementation - The implementation type to use.\n * @param options.deployParams - The deployment parameters for the specified implementation.\n * @param options.deploySalt - The salt to use for CREATE2 address computation.\n * @returns An object containing the counterfactual address and factory calldata.\n * @description This function calculates the address a DeleGator contract would have if deployed,\n * and provides the calldata needed to deploy it.\n */\nexport const getCounterfactualAccountData = async <\n TImplementation extends Implementation,\n>({\n factory,\n implementations,\n implementation,\n deployParams,\n deploySalt,\n}: {\n factory: Address;\n implementations: SmartAccountsEnvironment['implementations'];\n implementation: TImplementation;\n deployParams: DeployParams<TImplementation>;\n deploySalt: Hex;\n}): Promise<{ factoryData: Hex; address: Address }> => {\n let implementationAddress: Address;\n let initcode: Hex;\n\n switch (implementation) {\n case Implementation.Hybrid: {\n const [owner, keyIds, xValues, yValues] =\n deployParams as HybridDeleGatorDeployParams;\n\n if (!implementations.HybridDeleGatorImpl) {\n throw new Error(\n 'HybridDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.HybridDeleGatorImpl;\n\n const p256Owners = keyIds.map((keyId, index) => {\n const xValue = xValues[index];\n const yValue = yValues[index];\n\n if (!xValue || !yValue) {\n throw new Error(\n `Missing X or Y value for keyId ${keyId} at index ${index}`,\n );\n }\n\n return {\n keyId,\n x: xValue,\n y: yValue,\n };\n });\n\n initcode = initializeHybridDeleGator({ eoaOwner: owner, p256Owners });\n break;\n }\n case Implementation.MultiSig: {\n const [owners, threshold] = deployParams as MultiSigDeleGatorDeployParams;\n\n if (!implementations.MultiSigDeleGatorImpl) {\n throw new Error(\n 'MultiSigDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.MultiSigDeleGatorImpl;\n initcode = initializeMultiSigDeleGator({ owners, threshold });\n break;\n }\n case Implementation.Stateless7702:\n default:\n throw new Error(`Implementation type '${implementation}' not supported`);\n }\n\n const salt = pad(deploySalt, { dir: 'left', size: 32 });\n\n const proxyCreationCode = encodeProxyCreationCode({\n implementationAddress,\n initcode,\n });\n\n const address = getContractAddress({\n bytecode: proxyCreationCode,\n from: factory,\n opcode: 'CREATE2',\n salt,\n });\n\n const factoryData = encodeCreate2Deploy(proxyCreationCode, salt);\n\n return {\n factoryData,\n address,\n };\n};\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport { encodeFunctionData } from 'viem';\nimport type { Address, Hex } from 'viem';\n\nimport type { DelegatedCall } from './actions/erc7710RedeemDelegationAction';\nimport {\n execute,\n executeWithMode,\n} from './DelegationFramework/DeleGatorCore/encode';\nimport {\n ExecutionMode,\n createExecution,\n encodeExecutionCalldatas,\n} from './executions';\nimport type { Call } from './types';\n\n/**\n * Checks if a call is a delegated call by checking for the presence of permissionsContext and delegationManager.\n *\n * @param call - The call to check.\n * @returns True if the call is a delegated call, false otherwise.\n */\nconst isDelegatedCall = (call: Call): call is DelegatedCall => {\n return 'permissionsContext' in call && 'delegationManager' in call;\n};\n\n/**\n * If there's a single call with permissionsContext and delegationManager,\n * processes it as a delegated call.\n *\n * @param call - The call to process.\n * @returns The execution object for the delegated call.\n * @description\n * This function creates an execution that calls redeemDelegations on the delegation manager.\n */\nconst processDelegatedCall = (call: DelegatedCall) => {\n const {\n permissionsContext,\n delegationManager,\n to: target,\n value,\n data: callData,\n } = call;\n\n const callAsExecution = createExecution({ target, value, callData });\n\n if (!permissionsContext) {\n return callAsExecution;\n }\n\n const redeemCalldata = encodeFunctionData({\n abi: DelegationManager.abi,\n functionName: 'redeemDelegations',\n args: [\n [permissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([[callAsExecution]]),\n ],\n });\n\n return createExecution({\n target: delegationManager,\n callData: redeemCalldata,\n });\n};\n\n/**\n * If there's a single call, encode the shorthand `execute` function. Otherwise, encode the `executeWithMode` function. Execution type will always be \"default\".\n *\n * @param calls - The calls to execute.\n * @returns The encoded calldata for the DeleGator to execute the calls.\n * @description\n * This function supports both single and batch execution modes.\n * For single calls, it uses the gas-efficient execute function.\n */\nexport const encodeCalls = (calls: readonly Call[]) => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call && !isDelegatedCall(call)) {\n const { to: target, value, data: callData } = call;\n const execution = createExecution({ target, value, callData });\n return execute({ execution });\n }\n }\n\n const executions = calls.map((call) => {\n if (isDelegatedCall(call)) {\n return processDelegatedCall(call);\n }\n const { to: target, value, data: callData } = call;\n return createExecution({ target, value, callData });\n });\n\n const mode =\n calls.length === 1\n ? ExecutionMode.SingleDefault\n : ExecutionMode.BatchDefault;\n return executeWithMode({ mode, executions });\n};\n\n/**\n * Encodes calls for execution by a DeleGator smart contract.\n *\n * @param caller - The address of the DeleGator contract.\n * @param calls - An array of Call objects, each containing 'to', optional 'data', and optional 'value'.\n * @returns A promise that resolves to the encoded function data as a hexadecimal string.\n * @description\n * - If there's a single call directly to the delegator, it returns the call data directly.\n * - For multiple calls or calls to other addresses, it creates executions and encodes them for the DeleGator's execute function.\n * - The execution mode is set to ExecutionMode.SingleDefault for a single call, or ExecutionMode.BatchDefault for multiple calls.\n *\n * todo: This doesn't fully expose the flexibility of the DeleGator's execute function, but it's a start.\n * maybe we add a mechanism where individual calls passed to this function can be encoded batches.\n */\nexport const encodeCallsForCaller = async (\n caller: Address,\n calls: readonly Call[],\n): Promise<Hex> => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call?.to === caller && !isDelegatedCall(call)) {\n // if there's a single call, and it's to the delegator, we can just return the calldata directly.\n return call.data ?? '0x';\n }\n }\n return encodeCalls(calls);\n};\n","import {\n parseAbiParameters,\n encodeAbiParameters,\n type Hex,\n encodePacked,\n keccak256,\n concat,\n hexToBytes,\n} from 'viem';\nimport { parseSignature } from 'webauthn-p256';\n\nexport const FIELD_MODULUS =\n 115792089210356248762697446949407573529996955224135760342422259061068512044369n;\nexport const MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;\n\nexport const SIGNATURE_ABI_PARAMS = parseAbiParameters(\n 'bytes32, uint256, uint256, bytes, bool, string, string, uint256',\n);\n\n/**\n * This function is used to convert the client data returned from the\n * credentials API into a format that can be consumed by the DeleGator\n * contracts. We need the flattend JSON strings before and after the\n * userOpHash/challenge. This function provides those two client data string\n * slices.\n *\n * @param clientDataJson - The client data JSON string.\n * @returns Returns [clientDataJSONPrefix and clientDataJSONSuffix]\n * ClientDataJSONPrefix contains the client data till the challengeHash\n * ClientDataJSONSuffix contains the client data after the challengeHash.\n */\nexport const splitOnChallenge = (\n clientDataJson: string,\n): [clientDataJSONPrefix: string, clientDataJSONSuffix: string] => {\n /*\n CientData looks like this:\n {\n \"type\": \"webauthn.create\" | \"webauthn.get\",\n \"challenge\": \"{userOpHash}\",\n \"origin\": \"{Domain}\",\n \"crossOrigin\": boolean\n }\n */\n try {\n const { challenge } = JSON.parse(clientDataJson);\n if (challenge === undefined) {\n throw new Error('No \"challenge\" found in the input string');\n }\n return clientDataJson.split(challenge) as [string, string];\n } catch (error) {\n throw new Error('No \"challenge\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Returns the index of '\"type\":' in the ClientData.\n *\n * @param clientDataJson - Stringified ClientDataJSON.\n * @returns The index of '\"type\":' in the ClientData.\n */\nexport const getResponseTypeLocation = (clientDataJson: string): bigint => {\n try {\n // Find the index of the `\"type\":` key in the JSON string directly\n const typeIndex = clientDataJson.indexOf('\"type\":');\n\n if (typeIndex === -1) {\n throw new Error('No \"type\" found in the input string');\n }\n // Return the index of the `\"type\":` key\n return BigInt(typeIndex);\n } catch (error) {\n // Handle any errors that occur during the search\n throw new Error('No \"type\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Encodes a signature to a hexadecimal signature that will be accepted\n * by the DeleGator contracts.\n *\n * @param keyId - The key used for the signature, represented as a hexadecimal string.\n * @param signature - The signature to convert, as Hex.\n * @param clientDataJSON - The client data used in the creation of the signature.\n * @param authenticatorData - The authenticator data used in the creation of the signature.\n * @returns The signature as a valid DeleGator signature encoded as Hexadecimal string.\n */\nexport function encodeDeleGatorSignature(\n keyId: string,\n signature: Hex,\n clientDataJSON: string,\n authenticatorData: Hex,\n): Hex {\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n\n const parsedSignature = parseSignature(signature);\n\n let { s } = parsedSignature;\n\n while (s > MALLEABILITY_THRESHOLD) {\n s = FIELD_MODULUS - s;\n }\n\n const { r } = parsedSignature;\n\n const [clientDataComponent1, clientDataComponent2] =\n splitOnChallenge(clientDataJSON);\n\n const { userVerified } = parseAuthenticatorFlags(authenticatorData);\n\n const responseTypeLocation = getResponseTypeLocation(clientDataJSON);\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n r,\n s,\n authenticatorData,\n userVerified,\n clientDataComponent1,\n clientDataComponent2,\n responseTypeLocation,\n ]);\n return encodedSignature;\n}\n\nconst AUTHENTICATOR_DATA_FLAGS_OFFSET = 32;\n// We have all of the flag bits defined here for completeness, even though we only extract the userVerified flag.\nenum AuthenticatorDataFlagBitIndex {\n UserPresence = 0,\n UserVerified = 2,\n BackupEligibility = 3,\n BackupState = 4,\n AttestedCredentialData = 6,\n ExtensionData = 7,\n}\n\nexport type AuthenticatorFlags = {\n userVerified: boolean;\n};\n\n/**\n * Parses the authenticator data and returns an authenticator flags object with the `userVerified` flag.\n * See https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data.\n *\n * @param authenticatorData - The authenticator data to parse.\n * @returns An object representing the parsed authenticator flags.\n */\nexport function parseAuthenticatorFlags(\n authenticatorData: Hex,\n): AuthenticatorFlags {\n const authenticatorDataBuffer = hexToBytes(authenticatorData);\n const dataBufferUint8 = new Uint8Array(authenticatorDataBuffer);\n const flags = dataBufferUint8[AUTHENTICATOR_DATA_FLAGS_OFFSET];\n if (flags === undefined) {\n throw new Error('Authenticator flags not found in authenticator data');\n }\n\n // Bit 0 is the least significant bit in the flags byte, so we left shift 0b1 by the bit index\n // eslint-disable-next-line no-bitwise\n const bitMask = 0b1 << AuthenticatorDataFlagBitIndex.UserVerified;\n\n return {\n // eslint-disable-next-line no-bitwise\n userVerified: (flags & bitMask) !== 0x0,\n };\n}\n\n/**\n * Creates a dummy signature.\n * This must meet all early-failure conditions of the real signature, but does not need to be a valid signature.\n *\n * @param keyId - The key ID to use for the dummy signature.\n * @returns The encoded signature.\n */\nexport const createDummyWebAuthnSignature = (keyId: Hex) => {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#data_structure\n const rpIdHash = keccak256(encodePacked(['string'], ['AuthenticatorData']));\n const flags = '0x05';\n const signCount = '0x00000000';\n const authenticatorData = concat([rpIdHash, flags, signCount]);\n\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n const rs =\n 57896044605178124381348723474703786764998477612067880171211129530534256022184n;\n const userVerification = true;\n const clientDataPrefix = '{\"type\":\"webauthn.get\",\"challenge\":\"';\n const clientDataSuffix = '\",\"origin\":\"passkey-domain\",\"crossOrigin\":false}';\n const responseTypeLocation = 1n;\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rs,\n rs,\n authenticatorData,\n userVerification,\n clientDataPrefix,\n clientDataSuffix,\n responseTypeLocation,\n ]);\n\n return encodedSignature;\n};\n"],"mappings":";;;;;;;;;;;;;;AAIO,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,cAAW;AACX,EAAAA,gBAAA,YAAS;AACT,EAAAA,gBAAA,mBAAgB;AAHN,SAAAA;AAAA,GAAA;AA0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AC,QAAQ,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAC1E,QAAM,QAAQ;AACd,QAAM,YAAY;AAClB,QAAM,oBAAoB,OAAO,CAAC,UAAU,OAAO,SAAS,CAAC;AAE7D,QAAM,YAAY,UAAU,aAAa,CAAC,QAAQ,GAAG,CAAC,KAAK,CAAC,CAAC;AAC7D,QAAM,KACJ;AACF,QAAM,mBAAmB;AACzB,QAAM,mBAAmB;AACzB,QAAM,mBAAmB;AACzB,QAAM,uBAAuB;AAE7B,QAAM,mBAAmB,oBAAoB,sBAAsB;AAAA,IACjE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["Implementation","TransferWindow","encode","encode"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/DelegationFramework/ERC20PeriodTransferEnforcer/index.ts","../src/DelegationFramework/ERC20PeriodTransferEnforcer/read.ts","../src/DelegationFramework/ERC20PeriodTransferEnforcer/methods/getAvailableAmount.ts","../src/DelegationFramework/ERC20StreamingEnforcer/index.ts","../src/DelegationFramework/ERC20StreamingEnforcer/read.ts","../src/DelegationFramework/ERC20StreamingEnforcer/methods/getAvailableAmount.ts","../src/DelegationFramework/MultiTokenPeriodEnforcer/index.ts","../src/DelegationFramework/MultiTokenPeriodEnforcer/read.ts","../src/DelegationFramework/MultiTokenPeriodEnforcer/methods/getAvailableAmount.ts","../src/DelegationFramework/NativeTokenPeriodTransferEnforcer/index.ts","../src/DelegationFramework/NativeTokenPeriodTransferEnforcer/read.ts","../src/DelegationFramework/NativeTokenPeriodTransferEnforcer/methods/getAvailableAmount.ts","../src/DelegationFramework/NativeTokenStreamingEnforcer/index.ts","../src/DelegationFramework/NativeTokenStreamingEnforcer/read.ts","../src/DelegationFramework/NativeTokenStreamingEnforcer/methods/getAvailableAmount.ts"],"sourcesContent":["import * as read from './read';\n\nexport { read };\n","import { read as getAvailableAmount } from './methods/getAvailableAmount';\n\nexport { getAvailableAmount };\n","import { ERC20PeriodTransferEnforcer } from '@metamask/delegation-abis';\nimport type { Address, Client, Hex } from 'viem';\nimport { readContract } from 'viem/actions';\n\nexport type ReadGetAvailableAmountParameters = {\n client: Client;\n contractAddress: Address;\n delegationHash: Hex;\n delegationManager: Address;\n terms: Hex;\n};\n\nexport const read = async ({\n client,\n contractAddress,\n delegationHash,\n delegationManager,\n terms,\n}: ReadGetAvailableAmountParameters) => {\n const [availableAmount, isNewPeriod, currentPeriod] = await readContract(\n client,\n {\n address: contractAddress,\n abi: ERC20PeriodTransferEnforcer.abi,\n functionName: 'getAvailableAmount',\n args: [delegationHash, delegationManager, terms],\n },\n );\n\n return {\n availableAmount,\n isNewPeriod,\n currentPeriod,\n };\n};\n","import * as read from './read';\n\nexport { read };\n","import { read as getAvailableAmount } from './methods/getAvailableAmount';\n\nexport { getAvailableAmount };\n","import { ERC20StreamingEnforcer } from '@metamask/delegation-abis';\nimport type { Address, Client, Hex } from 'viem';\nimport { readContract, getBlock } from 'viem/actions';\n\nexport type ReadGetAvailableAmountParameters = {\n client: Client;\n contractAddress: Address;\n delegationManager: Address;\n delegationHash: Hex;\n terms: Hex;\n};\n\nexport const read = async ({\n client,\n contractAddress,\n delegationManager,\n delegationHash,\n terms,\n}: ReadGetAvailableAmountParameters) => {\n // Get current block timestamp from blockchain\n const currentBlock = await getBlock(client);\n const currentTimestamp = currentBlock.timestamp;\n\n // First, get the current state from the contract\n const allowanceState = await readContract(client, {\n address: contractAddress,\n abi: ERC20StreamingEnforcer.abi,\n functionName: 'streamingAllowances',\n args: [delegationManager, delegationHash],\n });\n\n const [initialAmount, maxAmount, amountPerSecond, startTime, spent] =\n allowanceState;\n\n // Check if state exists (startTime != 0)\n if (startTime !== 0n) {\n // State exists, calculate available amount using the stored state\n const availableAmount = getAvailableAmount({\n initialAmount,\n maxAmount,\n amountPerSecond,\n startTime,\n spent,\n currentTimestamp,\n });\n\n return {\n availableAmount,\n };\n }\n\n // State doesn't exist, decode terms and simulate with spent = 0\n const decodedTerms = await readContract(client, {\n address: contractAddress,\n abi: ERC20StreamingEnforcer.abi,\n functionName: 'getTermsInfo',\n args: [terms],\n });\n\n const [\n ,\n decodedInitialAmount,\n decodedMaxAmount,\n decodedAmountPerSecond,\n decodedStartTime,\n ] = decodedTerms;\n\n // Simulate using decoded terms with spent = 0\n const availableAmount = getAvailableAmount({\n initialAmount: decodedInitialAmount,\n maxAmount: decodedMaxAmount,\n amountPerSecond: decodedAmountPerSecond,\n startTime: decodedStartTime,\n spent: 0n,\n currentTimestamp,\n });\n\n return {\n availableAmount,\n };\n};\n\n/**\n * Replicates the internal _getAvailableAmount logic from the smart contract.\n *\n * @param allowance - The allowance object containing all parameters.\n * @param allowance.initialAmount - The initial amount available.\n * @param allowance.maxAmount - The maximum amount allowed.\n * @param allowance.amountPerSecond - The amount streamed per second.\n * @param allowance.startTime - The start time of the streaming.\n * @param allowance.spent - The amount already spent.\n * @param allowance.currentTimestamp - The current timestamp.\n * @returns The available amount that can be spent.\n */\nfunction getAvailableAmount(allowance: {\n initialAmount: bigint;\n maxAmount: bigint;\n amountPerSecond: bigint;\n startTime: bigint;\n spent: bigint;\n currentTimestamp: bigint;\n}): bigint {\n // If current time is before start time, nothing is available\n if (allowance.currentTimestamp < allowance.startTime) {\n return 0n;\n }\n\n // Calculate elapsed time since start\n const elapsed = allowance.currentTimestamp - allowance.startTime;\n\n // Calculate total unlocked amount\n let unlocked = allowance.initialAmount + allowance.amountPerSecond * elapsed;\n\n // Cap by max amount\n if (unlocked > allowance.maxAmount) {\n unlocked = allowance.maxAmount;\n }\n\n // If spent >= unlocked, nothing available\n if (allowance.spent >= unlocked) {\n return 0n;\n }\n\n // Return available amount\n return unlocked - allowance.spent;\n}\n","import * as read from './read';\n\nexport { read };\n","import { read as getAvailableAmount } from './methods/getAvailableAmount';\n\nexport { getAvailableAmount };\n","import { MultiTokenPeriodEnforcer } from '@metamask/delegation-abis';\nimport type { Address, Client, Hex } from 'viem';\nimport { readContract } from 'viem/actions';\n\nexport type ReadGetAvailableAmountParameters = {\n client: Client;\n contractAddress: Address;\n delegationHash: Hex;\n delegationManager: Address;\n terms: Hex;\n args: Hex;\n};\n\nexport const read = async ({\n client,\n contractAddress,\n delegationHash,\n delegationManager,\n terms,\n args,\n}: ReadGetAvailableAmountParameters) => {\n const [availableAmount, isNewPeriod, currentPeriod] = await readContract(\n client,\n {\n address: contractAddress,\n abi: MultiTokenPeriodEnforcer.abi,\n functionName: 'getAvailableAmount',\n args: [delegationHash, delegationManager, terms, args],\n },\n );\n\n return {\n availableAmount,\n isNewPeriod,\n currentPeriod,\n };\n};\n","import * as read from './read';\n\nexport { read };\n","import { read as getAvailableAmount } from './methods/getAvailableAmount';\n\nexport { getAvailableAmount };\n","import { NativeTokenPeriodTransferEnforcer } from '@metamask/delegation-abis';\nimport type { Address, Client, Hex } from 'viem';\nimport { readContract } from 'viem/actions';\n\nexport type ReadGetAvailableAmountParameters = {\n client: Client;\n contractAddress: Address;\n delegationHash: Hex;\n delegationManager: Address;\n terms: Hex;\n};\n\nexport const read = async ({\n client,\n contractAddress,\n delegationHash,\n delegationManager,\n terms,\n}: ReadGetAvailableAmountParameters) => {\n const [availableAmount, isNewPeriod, currentPeriod] = await readContract(\n client,\n {\n address: contractAddress,\n abi: NativeTokenPeriodTransferEnforcer.abi,\n functionName: 'getAvailableAmount',\n args: [delegationHash, delegationManager, terms],\n },\n );\n\n return {\n availableAmount,\n isNewPeriod,\n currentPeriod,\n };\n};\n","import * as read from './read';\n\nexport { read };\n","import { read as getAvailableAmount } from './methods/getAvailableAmount';\n\nexport { getAvailableAmount };\n","import { NativeTokenStreamingEnforcer } from '@metamask/delegation-abis';\nimport type { Address, Client, Hex } from 'viem';\nimport { readContract, getBlock } from 'viem/actions';\n\nexport type ReadGetAvailableAmountParameters = {\n client: Client;\n contractAddress: Address;\n delegationManager: Address;\n delegationHash: Hex;\n terms: Hex;\n};\n\nexport const read = async ({\n client,\n contractAddress,\n delegationManager,\n delegationHash,\n terms,\n}: ReadGetAvailableAmountParameters) => {\n // Get current block timestamp from blockchain\n const currentBlock = await getBlock(client);\n const currentTimestamp = currentBlock.timestamp;\n\n // First, get the current state from the contract\n const allowanceState = await readContract(client, {\n address: contractAddress,\n abi: NativeTokenStreamingEnforcer.abi,\n functionName: 'streamingAllowances',\n args: [delegationManager, delegationHash],\n });\n\n const [initialAmount, maxAmount, amountPerSecond, startTime, spent] =\n allowanceState;\n\n // Check if state exists (startTime != 0)\n if (startTime !== 0n) {\n // State exists, calculate available amount using the stored state\n const availableAmount = getAvailableAmount({\n initialAmount,\n maxAmount,\n amountPerSecond,\n startTime,\n spent,\n currentTimestamp,\n });\n\n return {\n availableAmount,\n };\n }\n\n // State doesn't exist, decode terms and simulate with spent = 0\n const decodedTerms = await readContract(client, {\n address: contractAddress,\n abi: NativeTokenStreamingEnforcer.abi,\n functionName: 'getTermsInfo',\n args: [terms],\n });\n\n const [\n decodedInitialAmount,\n decodedMaxAmount,\n decodedAmountPerSecond,\n decodedStartTime,\n ] = decodedTerms;\n\n // Simulate using decoded terms with spent = 0\n const availableAmount = getAvailableAmount({\n initialAmount: decodedInitialAmount,\n maxAmount: decodedMaxAmount,\n amountPerSecond: decodedAmountPerSecond,\n startTime: decodedStartTime,\n spent: 0n,\n currentTimestamp,\n });\n\n return {\n availableAmount,\n };\n};\n\n/**\n * Replicates the internal _getAvailableAmount logic from the smart contract.\n *\n * @param allowance - The allowance object containing all parameters.\n * @param allowance.initialAmount - The initial amount available.\n * @param allowance.maxAmount - The maximum amount allowed.\n * @param allowance.amountPerSecond - The amount streamed per second.\n * @param allowance.startTime - The start time of the streaming.\n * @param allowance.spent - The amount already spent.\n * @param allowance.currentTimestamp - The current timestamp.\n * @returns The available amount that can be spent.\n */\nfunction getAvailableAmount(allowance: {\n initialAmount: bigint;\n maxAmount: bigint;\n amountPerSecond: bigint;\n startTime: bigint;\n spent: bigint;\n currentTimestamp: bigint;\n}): bigint {\n // If current time is before start time, nothing is available\n if (allowance.currentTimestamp < allowance.startTime) {\n return 0n;\n }\n\n // Calculate elapsed time since start\n const elapsed = allowance.currentTimestamp - allowance.startTime;\n\n // Calculate total unlocked amount\n let unlocked = allowance.initialAmount + allowance.amountPerSecond * elapsed;\n\n // Cap by max amount\n if (unlocked > allowance.maxAmount) {\n unlocked = allowance.maxAmount;\n }\n\n // If spent >= unlocked, nothing available\n if (allowance.spent >= unlocked) {\n return 0n;\n }\n\n // Return available amount\n return unlocked - allowance.spent;\n}\n"],"mappings":";;;;;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,mCAAmC;AAE5C,SAAS,oBAAoB;AAUtB,IAAM,OAAO,OAAO;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAwC;AACtC,QAAM,CAAC,iBAAiB,aAAa,aAAa,IAAI,MAAM;AAAA,IAC1D;AAAA,IACA;AAAA,MACE,SAAS;AAAA,MACT,KAAK,4BAA4B;AAAA,MACjC,cAAc;AAAA,MACd,MAAM,CAAC,gBAAgB,mBAAmB,KAAK;AAAA,IACjD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;AClCA;AAAA;AAAA,cAAAA;AAAA;;;ACAA,IAAAC,gBAAA;AAAA,SAAAA,eAAA;AAAA,4BAAAC;AAAA;;;ACAA,SAAS,8BAA8B;AAEvC,SAAS,gBAAAC,eAAc,gBAAgB;AAUhC,IAAMC,QAAO,OAAO;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAwC;AAEtC,QAAM,eAAe,MAAM,SAAS,MAAM;AAC1C,QAAM,mBAAmB,aAAa;AAGtC,QAAM,iBAAiB,MAAMD,cAAa,QAAQ;AAAA,IAChD,SAAS;AAAA,IACT,KAAK,uBAAuB;AAAA,IAC5B,cAAc;AAAA,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,6BAA6B;AAAA,IAClC,cAAc;AAAA,IACd,MAAM,CAAC,mBAAmB,cAAc;AAAA,EAC1C,CAAC;AAED,QAAM,CAAC,eAAe,WAAW,iBAAiB,WAAW,KAAK,IAChE;AAGF,MAAI,cAAc,IAAI;AAEpB,UAAMG,mBAAkBC,oBAAmB;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAED,WAAO;AAAA,MACL,iBAAAD;AAAA,IACF;AAAA,EACF;AAGA,QAAM,eAAe,MAAMH,cAAa,QAAQ;AAAA,IAC9C,SAAS;AAAA,IACT,KAAK,6BAA6B;AAAA,IAClC,cAAc;AAAA,IACd,MAAM,CAAC,KAAK;AAAA,EACd,CAAC;AAED,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAGJ,QAAM,kBAAkBI,oBAAmB;AAAA,IACzC,eAAe;AAAA,IACf,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAcA,SAASA,oBAAmB,WAOjB;AAET,MAAI,UAAU,mBAAmB,UAAU,WAAW;AACpD,WAAO;AAAA,EACT;AAGA,QAAM,UAAU,UAAU,mBAAmB,UAAU;AAGvD,MAAI,WAAW,UAAU,gBAAgB,UAAU,kBAAkB;AAGrE,MAAI,WAAW,UAAU,WAAW;AAClC,eAAW,UAAU;AAAA,EACvB;AAGA,MAAI,UAAU,SAAS,UAAU;AAC/B,WAAO;AAAA,EACT;AAGA,SAAO,WAAW,UAAU;AAC9B;","names":["read_exports","read_exports","read","readContract","read","availableAmount","read_exports","read_exports","read","readContract","read","read_exports","read_exports","read","readContract","read","read_exports","read_exports","read","readContract","getBlock","read","availableAmount","getAvailableAmount"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/write.ts","../src/smartAccountsEnvironment.ts","../src/userOp.ts"],"sourcesContent":["import { SimpleFactory, DelegationManager } from '@metamask/delegation-abis';\nimport type { Address, Chain, Hex, PublicClient, WalletClient } from 'viem';\n\nimport { encodePermissionContexts } from './delegation';\nimport type { ExecutionStruct, ExecutionMode } from './executions';\nimport { encodeExecutionCalldatas } from './executions';\nimport type { Delegation, ContractMetaData, Redemption } from './types';\n\n/**\n * Deploys a contract using the SimpleFactory contract.\n *\n * @param walletClient - The wallet client to use for deployment.\n * @param publicClient - The public client to use for simulation.\n * @param simpleFactoryAddress - The address of the SimpleFactory contract.\n * @param creationCode - The creation code for the contract to deploy.\n * @param salt - The salt to use for deterministic deployment.\n * @returns The transaction hash of the deployment.\n */\nexport const deployWithSimpleFactory = async (\n walletClient: WalletClient,\n publicClient: PublicClient,\n simpleFactoryAddress: Address,\n creationCode: Hex,\n salt: Hex,\n) => {\n const { request } = await publicClient.simulateContract({\n account: walletClient.account,\n address: simpleFactoryAddress,\n abi: SimpleFactory.abi,\n functionName: 'deploy',\n args: [creationCode, salt],\n });\n return await walletClient.writeContract(request);\n};\n\n/**\n * Redeems a delegation to execute the provided executions.\n *\n * @param walletClient - The wallet client to use for redemption.\n * @param publicClient - The public client to use for simulation.\n * @param delegationManagerAddress - The address of the DelegationManager contract.\n * @param redemptions - The redemptions to execute, containing permission contexts, executions, and modes.\n * @returns The transaction hash of the redemption.\n */\nexport const redeemDelegations = async (\n walletClient: WalletClient,\n publicClient: PublicClient,\n delegationManagerAddress: Address,\n redemptions: Redemption[],\n) => {\n if (redemptions.length === 0) {\n throw new Error('RedeemDelegations invalid zero redemptions');\n }\n\n const permissionContexts: Delegation[][] = [];\n const executionsBatch: ExecutionStruct[][] = [];\n const executionModes: ExecutionMode[] = [];\n\n redemptions.forEach((redemption) => {\n permissionContexts.push(redemption.permissionContext);\n executionsBatch.push(redemption.executions);\n executionModes.push(redemption.mode);\n });\n\n const encodedPermissionContexts =\n encodePermissionContexts(permissionContexts);\n const executionCalldatas = encodeExecutionCalldatas(executionsBatch);\n\n const { request } = await publicClient.simulateContract({\n account: walletClient.account,\n address: delegationManagerAddress,\n abi: DelegationManager.abi,\n functionName: 'redeemDelegations',\n args: [encodedPermissionContexts, executionModes, executionCalldatas],\n });\n return await walletClient.writeContract(request);\n};\n\n/**\n * Deploys a contract to the blockchain.\n *\n * @param walletClient - The wallet client to use for deployment.\n * @param publicClient - The public client to use for transaction receipt.\n * @param chain - The chain to deploy on.\n * @param contractMetadata - The metadata of the contract to deploy.\n * @param contractMetadata.bytecode - The bytecode of the contract to deploy.\n * @param contractMetadata.abi - The ABI of the contract to deploy.\n * @param args - The constructor arguments for the contract.\n * @returns An object containing the deployed contract address, transaction hash, and receipt.\n */\nexport async function deployContract(\n walletClient: WalletClient,\n publicClient: PublicClient,\n chain: Chain,\n { bytecode, abi }: ContractMetaData,\n args: any[] = [],\n) {\n if (!walletClient.account) {\n throw new Error('Wallet client account is required');\n }\n\n const hash = await walletClient.deployContract({\n abi,\n bytecode,\n args,\n account: walletClient.account,\n chain,\n });\n\n const receipt = await publicClient.waitForTransactionReceipt({\n hash,\n });\n\n if (!receipt.contractAddress) {\n throw new Error('No contract address in receipt');\n }\n\n return { address: receipt.contractAddress, hash, receipt };\n}\n","import {\n EntryPoint,\n SimpleFactory,\n DelegationManager,\n MultiSigDeleGator,\n HybridDeleGator,\n EIP7702StatelessDeleGator,\n SCL_RIP7212,\n AllowedTargetsEnforcer,\n AllowedMethodsEnforcer,\n DeployedEnforcer,\n TimestampEnforcer,\n NonceEnforcer,\n AllowedCalldataEnforcer,\n BlockNumberEnforcer,\n LimitedCallsEnforcer,\n ERC20BalanceChangeEnforcer,\n ERC20StreamingEnforcer,\n IdEnforcer,\n ERC20TransferAmountEnforcer,\n ValueLteEnforcer,\n NativeTokenTransferAmountEnforcer,\n NativeBalanceChangeEnforcer,\n NativeTokenStreamingEnforcer,\n NativeTokenPaymentEnforcer,\n RedeemerEnforcer,\n ArgsEqualityCheckEnforcer,\n ERC721BalanceChangeEnforcer,\n ERC721TransferEnforcer,\n ERC1155BalanceChangeEnforcer,\n OwnershipTransferEnforcer,\n SpecificActionERC20TransferBatchEnforcer,\n ERC20PeriodTransferEnforcer,\n NativeTokenPeriodTransferEnforcer,\n ExactCalldataBatchEnforcer,\n ExactCalldataEnforcer,\n ExactExecutionEnforcer,\n ExactExecutionBatchEnforcer,\n MultiTokenPeriodEnforcer,\n} from '@metamask/delegation-abis';\nimport { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';\nimport type { Chain, Hex, PublicClient, WalletClient } from 'viem';\n\nimport type { ContractMetaData, SmartAccountsEnvironment } from './types';\nimport { deployContract } from './write';\n\ntype SupportedVersion = '1.0.0' | '1.1.0' | '1.2.0' | '1.3.0';\nexport const PREFERRED_VERSION: SupportedVersion = '1.3.0';\n\nconst contractOverrideMap: Map<string, SmartAccountsEnvironment> = new Map();\n\nconst getContractOverrideKey = (chainId: number, version: SupportedVersion) =>\n `${version}:${chainId}`;\n\n/**\n * Overrides the default environment for a specific chain and version.\n *\n * @param chainId - The chain ID to override.\n * @param version - The version of the environment to override.\n * @param environment - The environment to use as override.\n */\nexport function overrideDeployedEnvironment(\n chainId: number,\n version: SupportedVersion,\n environment: SmartAccountsEnvironment,\n) {\n contractOverrideMap.set(\n getContractOverrideKey(chainId, version),\n environment,\n );\n}\n\n/**\n * Gets the SmartAccountsEnvironment for the specified chain and version.\n *\n * @param chainId - The chain ID to get the environment for.\n * @param version - The version of the environment to get.\n * @returns The SmartAccountsEnvironment.\n */\nexport function getSmartAccountsEnvironment(\n chainId: number,\n version: SupportedVersion = PREFERRED_VERSION,\n): SmartAccountsEnvironment {\n const overrideKey = getContractOverrideKey(chainId, version);\n\n const overriddenContracts = contractOverrideMap.get(overrideKey);\n if (overriddenContracts) {\n return overriddenContracts;\n }\n\n const contracts = DELEGATOR_CONTRACTS[version]?.[chainId];\n if (!contracts) {\n throw new Error(\n `No contracts found for version ${version} chain ${chainId}`,\n );\n }\n return getSmartAccountsEnvironmentV1(contracts);\n}\n\n/**\n * Creates a SmartAccountsEnvironment from contract addresses.\n *\n * @param contracts - The contract addresses to create the environment from.\n * @returns The created SmartAccountsEnvironment.\n */\nexport function getSmartAccountsEnvironmentV1(contracts: {\n [contract: string]: Hex;\n}) {\n return {\n DelegationManager: contracts.DelegationManager,\n EntryPoint: contracts.EntryPoint,\n SimpleFactory: contracts.SimpleFactory,\n implementations: {\n MultiSigDeleGatorImpl: contracts.MultiSigDeleGatorImpl,\n HybridDeleGatorImpl: contracts.HybridDeleGatorImpl,\n EIP7702StatelessDeleGatorImpl: contracts.EIP7702StatelessDeleGatorImpl,\n },\n caveatEnforcers: {\n AllowedCalldataEnforcer: contracts.AllowedCalldataEnforcer,\n AllowedMethodsEnforcer: contracts.AllowedMethodsEnforcer,\n AllowedTargetsEnforcer: contracts.AllowedTargetsEnforcer,\n ArgsEqualityCheckEnforcer: contracts.ArgsEqualityCheckEnforcer,\n BlockNumberEnforcer: contracts.BlockNumberEnforcer,\n DeployedEnforcer: contracts.DeployedEnforcer,\n ERC20BalanceChangeEnforcer: contracts.ERC20BalanceChangeEnforcer,\n ERC20TransferAmountEnforcer: contracts.ERC20TransferAmountEnforcer,\n ERC20StreamingEnforcer: contracts.ERC20StreamingEnforcer,\n ERC721BalanceChangeEnforcer: contracts.ERC721BalanceChangeEnforcer,\n ERC721TransferEnforcer: contracts.ERC721TransferEnforcer,\n ERC1155BalanceChangeEnforcer: contracts.ERC1155BalanceChangeEnforcer,\n IdEnforcer: contracts.IdEnforcer,\n LimitedCallsEnforcer: contracts.LimitedCallsEnforcer,\n NonceEnforcer: contracts.NonceEnforcer,\n TimestampEnforcer: contracts.TimestampEnforcer,\n ValueLteEnforcer: contracts.ValueLteEnforcer,\n NativeTokenTransferAmountEnforcer:\n contracts.NativeTokenTransferAmountEnforcer,\n NativeBalanceChangeEnforcer: contracts.NativeBalanceChangeEnforcer,\n NativeTokenStreamingEnforcer: contracts.NativeTokenStreamingEnforcer,\n NativeTokenPaymentEnforcer: contracts.NativeTokenPaymentEnforcer,\n OwnershipTransferEnforcer: contracts.OwnershipTransferEnforcer,\n RedeemerEnforcer: contracts.RedeemerEnforcer,\n SpecificActionERC20TransferBatchEnforcer:\n contracts.SpecificActionERC20TransferBatchEnforcer,\n ERC20PeriodTransferEnforcer: contracts.ERC20PeriodTransferEnforcer,\n NativeTokenPeriodTransferEnforcer:\n contracts.NativeTokenPeriodTransferEnforcer,\n ExactCalldataBatchEnforcer: contracts.ExactCalldataBatchEnforcer,\n ExactCalldataEnforcer: contracts.ExactCalldataEnforcer,\n ExactExecutionEnforcer: contracts.ExactExecutionEnforcer,\n ExactExecutionBatchEnforcer: contracts.ExactExecutionBatchEnforcer,\n MultiTokenPeriodEnforcer: contracts.MultiTokenPeriodEnforcer,\n },\n } as SmartAccountsEnvironment;\n}\n\nexport type DeployedContract = {\n name: string;\n address: string;\n};\n\n/**\n * Deploys the contracts needed for the Delegation Framework and MetaMask SCA to be functional as well as all Caveat Enforcers.\n *\n * @param walletClient - The wallet client to use for deployment.\n * @param publicClient - The public client to use for deployment.\n * @param chain - The chain to deploy to.\n * @param deployedContracts - Optional map of already deployed contracts.\n * @returns A promise that resolves to the SmartAccountsEnvironment.\n */\nexport async function deploySmartAccountsEnvironment(\n walletClient: WalletClient,\n publicClient: PublicClient,\n chain: Chain,\n deployedContracts: { [contract: string]: Hex } = {},\n) {\n const deployContractCurried = async (\n name: string,\n contract: ContractMetaData,\n params: any[] = [],\n ) => {\n const existingAddress = deployedContracts[name];\n if (existingAddress) {\n return {\n address: existingAddress,\n name,\n };\n }\n\n const deployedContract = await deployContract(\n walletClient,\n publicClient,\n chain,\n contract,\n params,\n );\n\n const newDeployedContracts = { ...deployedContracts };\n newDeployedContracts[name] = deployedContract.address;\n Object.assign(deployedContracts, newDeployedContracts);\n\n return { ...deployedContract, name };\n };\n\n // Deploy v1.3.0 DeleGator contracts\n // - deploy standalone contracts\n const standaloneContracts = {\n SimpleFactory,\n AllowedCalldataEnforcer,\n AllowedTargetsEnforcer,\n AllowedMethodsEnforcer,\n ArgsEqualityCheckEnforcer,\n DeployedEnforcer,\n TimestampEnforcer,\n BlockNumberEnforcer,\n LimitedCallsEnforcer,\n ERC20BalanceChangeEnforcer,\n ERC20TransferAmountEnforcer,\n ERC20StreamingEnforcer,\n ERC721BalanceChangeEnforcer,\n ERC721TransferEnforcer,\n ERC1155BalanceChangeEnforcer,\n IdEnforcer,\n NonceEnforcer,\n ValueLteEnforcer,\n NativeTokenTransferAmountEnforcer,\n NativeBalanceChangeEnforcer,\n NativeTokenStreamingEnforcer,\n OwnershipTransferEnforcer,\n RedeemerEnforcer,\n SpecificActionERC20TransferBatchEnforcer,\n ERC20PeriodTransferEnforcer,\n NativeTokenPeriodTransferEnforcer,\n ExactCalldataBatchEnforcer,\n ExactCalldataEnforcer,\n ExactExecutionEnforcer,\n ExactExecutionBatchEnforcer,\n MultiTokenPeriodEnforcer,\n };\n for (const [name, contract] of Object.entries(standaloneContracts)) {\n await deployContractCurried(name, contract);\n }\n\n // - deploy dependencies\n const delegationManager = await deployContractCurried(\n 'DelegationManager',\n DelegationManager,\n [walletClient.account?.address],\n );\n\n // - NativeTokenPaymentEnforcer DelegationManager and ArgsEqualityCheckEnforcer as constructor args\n await deployContractCurried(\n 'NativeTokenPaymentEnforcer',\n NativeTokenPaymentEnforcer,\n [delegationManager.address, deployedContracts.ArgsEqualityCheckEnforcer],\n );\n\n const entryPoint = await deployContractCurried('EntryPoint', EntryPoint);\n\n // This is a hack to work around the SCL_RIP7212 being deployed as a library.\n // Forge handles this gracefully, but in the tests we need to manually link\n // the library.\n // We don't use the curried function here because we don't need it added to\n // the environment.\n const { address: sclRIP7212 } = await deployContract(\n walletClient,\n publicClient,\n chain,\n SCL_RIP7212,\n [],\n );\n\n // replace linked library address in bytecode https://docs.soliditylang.org/en/latest/using-the-compiler.html#library-linking\n const hybridDeleGatorWithLinkedLibrary = {\n ...HybridDeleGator,\n bytecode: HybridDeleGator.bytecode.replace(\n /__\\$b8f96b288d4d0429e38b8ed50fd423070f\\$__/gu,\n sclRIP7212.slice(2),\n ) as Hex,\n };\n\n // - deploy DeleGator implementations\n await deployContractCurried(\n 'HybridDeleGatorImpl',\n hybridDeleGatorWithLinkedLibrary,\n [delegationManager.address, entryPoint.address],\n );\n\n await deployContractCurried('MultiSigDeleGatorImpl', MultiSigDeleGator, [\n delegationManager.address,\n entryPoint.address,\n ]);\n\n await deployContractCurried(\n 'EIP7702StatelessDeleGatorImpl',\n EIP7702StatelessDeleGator,\n [delegationManager.address, entryPoint.address],\n );\n\n // Format deployments\n return getSmartAccountsEnvironmentV1(deployedContracts);\n}\n","import { concat, encodeAbiParameters, keccak256, pad, toHex } from 'viem';\nimport type { Address, Hex, TypedData } from 'viem';\nimport { toPackedUserOperation } from 'viem/account-abstraction';\nimport { signTypedData } from 'viem/accounts';\n\nimport type { OptionalUserOpProps, PackedUserOperationStruct } from './types';\n\n// v7 off-chain user operation, hexlified incoming data from rpc call\nexport type UserOperationV07Hexlify = {\n sender: Hex;\n nonce: Hex;\n factory?: Hex;\n factoryData?: Hex;\n callData: Hex;\n callGasLimit: Hex;\n\n verificationGasLimit: Hex;\n preVerificationGas: Hex;\n maxFeePerGas: Hex;\n maxPriorityFeePerGas: Hex;\n\n paymaster?: Hex;\n paymasterVerificationGasLimit?: Hex;\n paymasterPostOpGasLimit?: Hex;\n paymasterData?: Hex;\n\n signature: Hex;\n};\n\n// v7 off-chain user operation with BigInt fields\nexport type UserOperationV07 = {\n sender: Hex;\n nonce: bigint;\n factory?: Hex;\n factoryData?: Hex;\n callData: Hex;\n\n callGasLimit: bigint;\n verificationGasLimit: bigint;\n preVerificationGas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n\n paymaster?: Hex;\n paymasterVerificationGasLimit?: bigint;\n paymasterPostOpGasLimit?: bigint;\n paymasterData?: Hex;\n\n signature: Hex;\n};\n\n/**\n * Creates a raw user operation data structure.\n *\n * @param sender - The smart account taking some action.\n * @param nonce - A nonce, ideally fetched from the Entry Point.\n * @param callData - Calldata to invoke on some contract.\n * @param signature - The signature for the user operation.\n * @param options - Optional properties for the user operation.\n * @returns The created raw user operation data structure.\n */\nexport const createRawUserOp = (\n sender: Hex,\n nonce: bigint,\n callData: Hex,\n signature: Hex = '0x',\n options?: OptionalUserOpProps,\n): UserOperationV07 => ({\n sender,\n nonce,\n callData,\n factory: options?.factory,\n factoryData: options?.factoryData,\n callGasLimit: options?.callGasLimit ?? 0n,\n verificationGasLimit: options?.verificationGasLimit ?? 0n,\n preVerificationGas: options?.preVerificationGas ?? 0n,\n maxFeePerGas: options?.maxFeePerGas ?? 0n,\n maxPriorityFeePerGas: options?.maxPriorityFeePerGas ?? 0n,\n paymaster: options?.paymaster,\n paymasterVerificationGasLimit: options?.paymasterVerificationGasLimit,\n paymasterPostOpGasLimit: options?.paymasterPostOpGasLimit,\n paymasterData: options?.paymasterData,\n signature,\n});\n\n// //////////////////////////////////////////////////////////////////////////////////////\n\n// TODO: These userOp functions are duplicated in ./apps/ew-client/src/utils/userOpBuilder.ts. We should move them to a shared location along with test(./apps/ew-client/test/UserOpBuilder.test.ts) to avoid duplication\n/**\n * Generates a salt value for address derivation.\n *\n * @param salt - Optional salt value.\n * @returns The chosen salt value.\n */\nexport const getSalt = (salt?: Hex): Hex => {\n return salt ?? '0x0';\n};\n\nexport const getPaymasterAndData = (userOp: UserOperationV07): Hex => {\n let paymasterAndData: Hex;\n if (userOp.paymaster) {\n paymasterAndData = concat([\n userOp.paymaster,\n pad(toHex(userOp.paymasterVerificationGasLimit ?? 0n), {\n size: 16,\n }),\n pad(toHex(userOp.paymasterPostOpGasLimit ?? 0n), {\n size: 16,\n }),\n userOp.paymasterData ?? '0x',\n ]);\n } else {\n paymasterAndData = '0x';\n }\n\n return paymasterAndData;\n};\n\nexport const getInitCode = (userOp: UserOperationV07): Hex => {\n return userOp.factory\n ? concat([userOp.factory, userOp.factoryData ?? ('0x' as Hex)])\n : '0x';\n};\n\nexport const getAccountGasLimits = (userOp: UserOperationV07): Hex => {\n return concat([\n pad(toHex(userOp.verificationGasLimit), {\n size: 16,\n }),\n pad(toHex(userOp.callGasLimit), { size: 16 }),\n ]);\n};\n\nexport const getGasFees = (userOp: UserOperationV07): Hex => {\n return concat([\n pad(toHex(userOp.maxPriorityFeePerGas), {\n size: 16,\n }),\n pad(toHex(userOp.maxFeePerGas), { size: 16 }),\n ]);\n};\n\n/**\n * Packs a user operation into a `PackedUserOperationStruct` object.\n *\n * @param userOp - The user operation to pack.\n * @returns The packed user operation.\n */\nexport const packUserOp = (\n userOp: UserOperationV07,\n): PackedUserOperationStruct => {\n const packedOp = {\n sender: userOp.sender,\n nonce: BigInt(userOp.nonce),\n initCode: getInitCode(userOp),\n callData: userOp.callData,\n accountGasLimits: getAccountGasLimits(userOp),\n preVerificationGas: BigInt(userOp.preVerificationGas),\n gasFees: getGasFees(userOp),\n paymasterAndData: getPaymasterAndData(userOp),\n signature: userOp.signature,\n };\n\n return packedOp;\n};\n\n/**\n * Calculates the user operation hash for a given packed user operation.\n *\n * @param packedOp - The packed user operation.\n * @param entryPoint - The entry point address.\n * @param chainId - The chain ID.\n * @returns The user operation hash.\n */\nexport const createUserOpHashV07 = (\n packedOp: PackedUserOperationStruct,\n entryPoint: Hex,\n chainId: bigint,\n) => {\n const hash = keccak256(\n encodeAbiParameters(\n [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'nonce',\n type: 'uint256',\n },\n {\n name: 'initCodeHash',\n type: 'bytes32',\n },\n {\n name: 'callDataHash',\n type: 'bytes32',\n },\n {\n name: 'accountGasLimits',\n type: 'bytes32',\n },\n {\n name: 'preVerificationGas',\n type: 'uint256',\n },\n {\n name: 'gasFees',\n type: 'bytes32',\n },\n {\n name: 'paymasterAndDataHash',\n type: 'bytes32',\n },\n ],\n [\n packedOp.sender,\n packedOp.nonce,\n keccak256(packedOp.initCode),\n keccak256(packedOp.callData),\n packedOp.accountGasLimits,\n packedOp.preVerificationGas,\n packedOp.gasFees,\n keccak256(packedOp.paymasterAndData),\n ],\n ),\n );\n\n return keccak256(\n encodeAbiParameters(\n [\n {\n name: 'userOpHash',\n type: 'bytes32',\n },\n {\n name: 'entryPointAddress',\n type: 'address',\n },\n {\n name: 'chainId',\n type: 'uint256',\n },\n ],\n [hash, entryPoint, chainId],\n ),\n );\n};\n\nexport const SIGNABLE_USER_OP_TYPED_DATA: TypedData = {\n PackedUserOperation: [\n { name: 'sender', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n { name: 'initCode', type: 'bytes' },\n { name: 'callData', type: 'bytes' },\n { name: 'accountGasLimits', type: 'bytes32' },\n { name: 'preVerificationGas', type: 'uint256' },\n { name: 'gasFees', type: 'bytes32' },\n { name: 'paymasterAndData', type: 'bytes' },\n { name: 'entryPoint', type: 'address' },\n ],\n} as const;\n\n/**\n * Prepares typed data for user operation signing.\n * This is an internal helper function that's not exposed in the public API.\n *\n * @param params - The parameters for preparing the typed data.\n * @param params.userOperation - The user operation to prepare for signing.\n * @param params.entryPoint - The entry point contract address.\n * @param params.entryPoint.address - The address of the entry point contract.\n * @param params.chainId - The chain ID that the entry point is deployed on.\n * @param params.name - The name of the domain of the implementation contract.\n * @param params.version - The version of the domain of the implementation contract.\n * @param params.address - The address of the smart account.\n * @returns The prepared typed data for signing.\n */\nexport const prepareSignUserOperationTypedData = ({\n userOperation,\n entryPoint,\n chainId,\n name,\n address,\n version = '1',\n}: {\n userOperation: Omit<UserOperationV07, 'signature'>;\n entryPoint: { address: Address };\n chainId: number;\n name: 'HybridDeleGator' | 'MultiSigDeleGator';\n address: Address;\n version?: string;\n}) => {\n const packedUserOp = toPackedUserOperation({\n ...userOperation,\n signature: '0x',\n });\n\n return {\n domain: {\n chainId,\n name,\n version,\n verifyingContract: address,\n },\n types: SIGNABLE_USER_OP_TYPED_DATA,\n primaryType: 'PackedUserOperation' as const,\n message: { ...packedUserOp, entryPoint: entryPoint.address },\n };\n};\n\n/**\n * Signs a user operation using a private key.\n *\n * @param params - The parameters for signing the user operation.\n * @param params.privateKey - The private key to use for signing.\n * @param params.userOperation - The user operation to sign.\n * @param params.entryPoint - The entry point contract address.\n * @param params.chainId - The chain ID that the entry point is deployed on.\n * @param params.name - The name of the domain of the implementation contract.\n * @param params.version - The version of the domain of the implementation contract.\n * @param params.address - The address of the smart account.\n * @param params.entryPoint.address - The address of the entry point contract.\n * @returns The signature of the user operation.\n */\nexport const signUserOperation = async ({\n privateKey,\n userOperation,\n entryPoint,\n chainId,\n name,\n address,\n version = '1',\n}: {\n privateKey: Hex;\n userOperation: Omit<UserOperationV07, 'signature'>;\n entryPoint: { address: Address };\n chainId: number;\n address: Address;\n name: 'HybridDeleGator' | 'MultiSigDeleGator';\n version?: string;\n}) => {\n const typedData = prepareSignUserOperationTypedData({\n userOperation,\n entryPoint,\n chainId,\n name,\n address,\n version,\n });\n\n return signTypedData({\n privateKey,\n ...typedData,\n });\n};\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe,yBAAyB;AA4C1C,IAAM,oBAAoB,OAC/B,cACA,cACA,0BACA,gBACG;AACH,MAAI,YAAY,WAAW,GAAG;AAC5B,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AAEA,QAAM,qBAAqC,CAAC;AAC5C,QAAM,kBAAuC,CAAC;AAC9C,QAAM,iBAAkC,CAAC;AAEzC,cAAY,QAAQ,CAAC,eAAe;AAClC,uBAAmB,KAAK,WAAW,iBAAiB;AACpD,oBAAgB,KAAK,WAAW,UAAU;AAC1C,mBAAe,KAAK,WAAW,IAAI;AAAA,EACrC,CAAC;AAED,QAAM,4BACJ,yBAAyB,kBAAkB;AAC7C,QAAM,qBAAqB,yBAAyB,eAAe;AAEnE,QAAM,EAAE,QAAQ,IAAI,MAAM,aAAa,iBAAiB;AAAA,IACtD,SAAS,aAAa;AAAA,IACtB,SAAS;AAAA,IACT,KAAK,kBAAkB;AAAA,IACvB,cAAc;AAAA,IACd,MAAM,CAA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