@metamask/smart-accounts-kit 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/actions/index.cjs +5 -5
  3. package/dist/actions/index.d.cts +1 -1
  4. package/dist/actions/index.d.ts +1 -1
  5. package/dist/actions/index.mjs +4 -4
  6. package/dist/{chunk-6RN5RBOR.mjs → chunk-3OQKCVQC.mjs} +4 -4
  7. package/dist/{chunk-2EIX7ZYT.cjs → chunk-4WKZQUP4.cjs} +102 -102
  8. package/dist/{chunk-2EIX7ZYT.cjs.map → chunk-4WKZQUP4.cjs.map} +1 -1
  9. package/dist/{chunk-HD4O6IVC.cjs → chunk-AAYEHQXN.cjs} +8 -8
  10. package/dist/{chunk-HD4O6IVC.cjs.map → chunk-AAYEHQXN.cjs.map} +1 -1
  11. package/dist/{chunk-BFDBNFIP.cjs → chunk-CE3ZQE3P.cjs} +3 -3
  12. package/dist/{chunk-BFDBNFIP.cjs.map → chunk-CE3ZQE3P.cjs.map} +1 -1
  13. package/dist/{chunk-TEI2NRPU.mjs → chunk-DR5QAW34.mjs} +2 -2
  14. package/dist/{chunk-RB4SOJM3.mjs → chunk-K5C42JZ2.mjs} +44 -22
  15. package/dist/chunk-K5C42JZ2.mjs.map +1 -0
  16. package/dist/{chunk-KUEXI4ME.mjs → chunk-LCNP5VYR.mjs} +2 -2
  17. package/dist/{chunk-HLCOMYYU.cjs → chunk-MAPUND7S.cjs} +5 -15
  18. package/dist/chunk-MAPUND7S.cjs.map +1 -0
  19. package/dist/{chunk-MVKT5CLQ.mjs → chunk-PSERHFRY.mjs} +2 -2
  20. package/dist/{chunk-WA2O2K3K.cjs → chunk-PTIEXLLP.cjs} +58 -36
  21. package/dist/chunk-PTIEXLLP.cjs.map +1 -0
  22. package/dist/{chunk-D4ILRL6Z.cjs → chunk-PZM5E7L3.cjs} +12 -12
  23. package/dist/{chunk-D4ILRL6Z.cjs.map → chunk-PZM5E7L3.cjs.map} +1 -1
  24. package/dist/{chunk-UUDQWENY.mjs → chunk-Q6ZTEHYY.mjs} +44 -54
  25. package/dist/{chunk-HLCOMYYU.cjs.map → chunk-Q6ZTEHYY.mjs.map} +1 -1
  26. package/dist/{chunk-7MRTROLV.mjs → chunk-XHKSMZ7G.mjs} +2 -2
  27. package/dist/{chunk-662KDAAG.cjs → chunk-XU72WGZA.cjs} +11 -11
  28. package/dist/{chunk-662KDAAG.cjs.map → chunk-XU72WGZA.cjs.map} +1 -1
  29. package/dist/contracts/index.cjs +5 -5
  30. package/dist/contracts/index.mjs +4 -4
  31. package/dist/experimental/index.cjs +3 -3
  32. package/dist/experimental/index.mjs +1 -1
  33. package/dist/{index-CLkk7zr4.d.cts → index-DYq7aOEN.d.cts} +7 -1
  34. package/dist/{index-18Alar1P.d.ts → index-Do0GpCXe.d.ts} +7 -1
  35. package/dist/index.cjs +19 -19
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.mjs +7 -7
  39. package/dist/utils/index.cjs +5 -5
  40. package/dist/utils/index.mjs +4 -4
  41. package/package.json +4 -4
  42. package/dist/chunk-RB4SOJM3.mjs.map +0 -1
  43. package/dist/chunk-UUDQWENY.mjs.map +0 -1
  44. package/dist/chunk-WA2O2K3K.cjs.map +0 -1
  45. /package/dist/{chunk-6RN5RBOR.mjs.map → chunk-3OQKCVQC.mjs.map} +0 -0
  46. /package/dist/{chunk-TEI2NRPU.mjs.map → chunk-DR5QAW34.mjs.map} +0 -0
  47. /package/dist/{chunk-KUEXI4ME.mjs.map → chunk-LCNP5VYR.mjs.map} +0 -0
  48. /package/dist/{chunk-MVKT5CLQ.mjs.map → chunk-PSERHFRY.mjs.map} +0 -0
  49. /package/dist/{chunk-7MRTROLV.mjs.map → chunk-XHKSMZ7G.mjs.map} +0 -0
@@ -3,7 +3,7 @@
3
3
  var _chunkT6PSFUOZcjs = require('./chunk-T6PSFUOZ.cjs');
4
4
 
5
5
 
6
- var _chunkHLCOMYYUcjs = require('./chunk-HLCOMYYU.cjs');
6
+ var _chunkMAPUND7Scjs = require('./chunk-MAPUND7S.cjs');
7
7
 
8
8
  // src/write.ts
9
9
  var _delegationabis = require('@metamask/delegation-abis');
@@ -19,7 +19,7 @@ var redeemDelegations = async (walletClient, publicClient, delegationManagerAddr
19
19
  executionsBatch.push(redemption.executions);
20
20
  executionModes.push(redemption.mode);
21
21
  });
22
- const encodedPermissionContexts = _chunkHLCOMYYUcjs.encodePermissionContexts.call(void 0, permissionContexts);
22
+ const encodedPermissionContexts = _chunkMAPUND7Scjs.encodePermissionContexts.call(void 0, permissionContexts);
23
23
  const executionCalldatas = _chunkT6PSFUOZcjs.encodeExecutionCalldatas.call(void 0, executionsBatch);
24
24
  const { request } = await publicClient.simulateContract({
25
25
  account: walletClient.account,
@@ -333,4 +333,4 @@ var signUserOperation = async ({
333
333
 
334
334
 
335
335
  exports.redeemDelegations = redeemDelegations; exports.PREFERRED_VERSION = PREFERRED_VERSION; exports.overrideDeployedEnvironment = overrideDeployedEnvironment; exports.getSmartAccountsEnvironment = getSmartAccountsEnvironment; exports.deploySmartAccountsEnvironment = deploySmartAccountsEnvironment; exports.SIGNABLE_USER_OP_TYPED_DATA = SIGNABLE_USER_OP_TYPED_DATA; exports.prepareSignUserOperationTypedData = prepareSignUserOperationTypedData; exports.signUserOperation = signUserOperation;
336
- //# sourceMappingURL=chunk-BFDBNFIP.cjs.map
336
+ //# sourceMappingURL=chunk-CE3ZQE3P.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-BFDBNFIP.cjs","../src/write.ts","../src/smartAccountsEnvironment.ts","../src/userOp.ts"],"names":["SimpleFactory","DelegationManager"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPA,2DAAiD;AA0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IAAA;AAC8C,IAAA;AAChD,EAAA;AAE+C,EAAA;AAOT,EAAA;AACpC,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACC,IAAA;AACH,EAAA;AAGyC,EAAA;AACpC,IAAA;AACgC,IAAA;AACjC,MAAA;AACkB,MAAA;AACpB,IAAA;AACF,EAAA;AAGM,EAAA;AACJ,IAAA;AACA,IAAA;AAC8C,IAAA;AAChD,EAAA;AAE4B,EAAA;AACR,IAAA;AACP,IAAA;AACZ,EAAA;AAEK,EAAA;AACJ,IAAA;AACA,IAAA;AAC8C,IAAA;AAChD,EAAA;AAGqC,EAAA;AACvC;AFrCoD;AACA;AGrQH;AAEX;AACR;AAmPwB;AAC/B,EAAA;AACe,IAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACU,IAAA;AACE,IAAA;AACX,IAAA;AACO,IAAA;AACJ,IAAA;AACxC,EAAA;AACF;AAgBkD;AAChD,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACU,EAAA;AAQN;AACuC,EAAA;AACtC,IAAA;AACQ,IAAA;AACZ,EAAA;AAEM,EAAA;AACG,IAAA;AACN,MAAA;AACA,MAAA;AACA,MAAA;AACmB,MAAA;AACrB,IAAA;AACO,IAAA;AACM,IAAA;AAC2B,IAAA;AAC1C,EAAA;AACF;AAewC;AACtC,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACU,EAAA;AASN;AACc,EAAA;AAChB,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AAEoB,EAAA;AACnB,IAAA;AACG,IAAA;AACJ,EAAA;AACH;AH1BoD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-BFDBNFIP.cjs","sourcesContent":[null,"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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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"]}
1
+ {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-CE3ZQE3P.cjs","../src/write.ts","../src/smartAccountsEnvironment.ts","../src/userOp.ts"],"names":["SimpleFactory","DelegationManager"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPA,2DAAiD;AA0C1C,IAAM,kBAAA,EAAoB,MAAA,CAC/B,YAAA,EACA,YAAA,EACA,wBAAA,EACA,WAAA,EAAA,GACG;AACH,EAAA,GAAA,CAAI,WAAA,CAAY,OAAA,IAAW,CAAA,EAAG;AAC5B,IAAA,MAAM,IAAI,KAAA,CAAM,4CAA4C,CAAA;AAAA,EAC9D;AAEA,EAAA,MAAM,mBAAA,EAAqC,CAAC,CAAA;AAC5C,EAAA,MAAM,gBAAA,EAAuC,CAAC,CAAA;AAC9C,EAAA,MAAM,eAAA,EAAkC,CAAC,CAAA;AAEzC,EAAA,WAAA,CAAY,OAAA,CAAQ,CAAC,UAAA,EAAA,GAAe;AAClC,IAAA,kBAAA,CAAmB,IAAA,CAAK,UAAA,CAAW,iBAAiB,CAAA;AACpD,IAAA,eAAA,C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IAAA;AACE,IAAA;AACX,IAAA;AACO,IAAA;AACJ,IAAA;AACxC,EAAA;AACF;AAgBkD;AAChD,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACU,EAAA;AAQN;AACuC,EAAA;AACtC,IAAA;AACQ,IAAA;AACZ,EAAA;AAEM,EAAA;AACG,IAAA;AACN,MAAA;AACA,MAAA;AACA,MAAA;AACmB,MAAA;AACrB,IAAA;AACO,IAAA;AACM,IAAA;AAC2B,IAAA;AAC1C,EAAA;AACF;AAewC;AACtC,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACU,EAAA;AASN;AACc,EAAA;AAChB,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AAEoB,EAAA;AACnB,IAAA;AACG,IAAA;AACJ,EAAA;AACH;AH1BoD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-CE3ZQE3P.cjs","sourcesContent":[null,"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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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"]}
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  __export,
6
6
  toDelegationStruct
7
- } from "./chunk-UUDQWENY.mjs";
7
+ } from "./chunk-Q6ZTEHYY.mjs";
8
8
 
9
9
  // src/DelegationFramework/utils.ts
10
10
  import { ERC1967Proxy } from "@metamask/delegation-abis";
@@ -828,4 +828,4 @@ export {
828
828
  execute6,
829
829
  encode_exports4
830
830
  };
831
- //# sourceMappingURL=chunk-TEI2NRPU.mjs.map
831
+ //# sourceMappingURL=chunk-DR5QAW34.mjs.map
@@ -4,11 +4,11 @@ import {
4
4
  read_exports3,
5
5
  read_exports4,
6
6
  read_exports5
7
- } from "./chunk-KUEXI4ME.mjs";
7
+ } from "./chunk-LCNP5VYR.mjs";
8
8
  import {
9
9
  getSmartAccountsEnvironment,
10
10
  prepareSignUserOperationTypedData
11
- } from "./chunk-MVKT5CLQ.mjs";
11
+ } from "./chunk-PSERHFRY.mjs";
12
12
  import {
13
13
  createExecution,
14
14
  encodeExecutionCalldatas
@@ -17,7 +17,7 @@ import {
17
17
  __export,
18
18
  getDelegationHashOffchain,
19
19
  prepareSignDelegationTypedData
20
- } from "./chunk-UUDQWENY.mjs";
20
+ } from "./chunk-Q6ZTEHYY.mjs";
21
21
 
22
22
  // src/actions/index.ts
23
23
  var actions_exports = {};
@@ -182,16 +182,20 @@ function formatPermissionsRequest(parameters) {
182
182
  function isDefined(value) {
183
183
  return value !== void 0 && value !== null;
184
184
  }
185
- function assertIsDefined(value, message) {
185
+ function assertIsDefined(value, parameterName) {
186
186
  if (!isDefined(value)) {
187
- throw new Error(message ?? "Invalid parameters: value is required");
187
+ throw new Error(
188
+ `Invalid parameters: ${parameterName ?? "value"} is required`
189
+ );
188
190
  }
189
191
  }
190
- function toHexOrThrow(value, message) {
191
- assertIsDefined(value, message);
192
+ function toHexOrThrow(value, parameterName) {
193
+ assertIsDefined(value, parameterName);
192
194
  if (typeof value === "string") {
193
195
  if (!isHex(value)) {
194
- throw new Error("Invalid parameters: invalid hex value");
196
+ throw new Error(
197
+ `Invalid parameters: ${parameterName ?? "value"} is not a valid hex value`
198
+ );
195
199
  }
196
200
  return value;
197
201
  }
@@ -219,6 +223,11 @@ function getPermissionFormatter(permissionType) {
219
223
  permission,
220
224
  isAdjustmentAllowed
221
225
  });
226
+ case "erc20-token-revocation":
227
+ return ({ permission, isAdjustmentAllowed }) => formatErc20TokenRevocationPermission({
228
+ permission,
229
+ isAdjustmentAllowed
230
+ });
222
231
  default:
223
232
  throw new Error(`Unsupported permission type: ${permissionType}`);
224
233
  }
@@ -238,10 +247,10 @@ function formatNativeTokenStreamPermission({
238
247
  } = permission;
239
248
  const optionalFields = {
240
249
  ...isDefined(initialAmount) && {
241
- initialAmount: toHexOrThrow(initialAmount)
250
+ initialAmount: toHexOrThrow(initialAmount, "initialAmount")
242
251
  },
243
252
  ...isDefined(maxAmount) && {
244
- maxAmount: toHexOrThrow(maxAmount)
253
+ maxAmount: toHexOrThrow(maxAmount, "maxAmount")
245
254
  },
246
255
  ...isDefined(startTime) && {
247
256
  startTime: Number(startTime)
@@ -251,10 +260,7 @@ function formatNativeTokenStreamPermission({
251
260
  return {
252
261
  type: "native-token-stream",
253
262
  data: {
254
- amountPerSecond: toHexOrThrow(
255
- amountPerSecond,
256
- "Invalid parameters: amountPerSecond is required"
257
- ),
263
+ amountPerSecond: toHexOrThrow(amountPerSecond, "amountPerSecond"),
258
264
  ...optionalFields
259
265
  },
260
266
  isAdjustmentAllowed
@@ -276,10 +282,10 @@ function formatErc20TokenStreamPermission({
276
282
  } = permission;
277
283
  const optionalFields = {
278
284
  ...isDefined(initialAmount) && {
279
- initialAmount: toHexOrThrow(initialAmount)
285
+ initialAmount: toHexOrThrow(initialAmount, "initialAmount")
280
286
  },
281
287
  ...isDefined(maxAmount) && {
282
- maxAmount: toHexOrThrow(maxAmount)
288
+ maxAmount: toHexOrThrow(maxAmount, "maxAmount")
283
289
  },
284
290
  ...isDefined(startTime) && {
285
291
  startTime: Number(startTime)
@@ -289,8 +295,8 @@ function formatErc20TokenStreamPermission({
289
295
  return {
290
296
  type: "erc20-token-stream",
291
297
  data: {
292
- tokenAddress: toHexOrThrow(tokenAddress),
293
- amountPerSecond: toHexOrThrow(amountPerSecond),
298
+ tokenAddress: toHexOrThrow(tokenAddress, "tokenAddress"),
299
+ amountPerSecond: toHexOrThrow(amountPerSecond, "amountPerSecond"),
294
300
  ...optionalFields
295
301
  },
296
302
  isAdjustmentAllowed
@@ -312,7 +318,7 @@ function formatNativeTokenPeriodicPermission({
312
318
  return {
313
319
  type: "native-token-periodic",
314
320
  data: {
315
- periodAmount: toHexOrThrow(periodAmount),
321
+ periodAmount: toHexOrThrow(periodAmount, "periodAmount"),
316
322
  periodDuration: Number(periodDuration),
317
323
  ...optionalFields
318
324
  },
@@ -341,14 +347,30 @@ function formatErc20TokenPeriodicPermission({
341
347
  return {
342
348
  type: "erc20-token-periodic",
343
349
  data: {
344
- tokenAddress: toHexOrThrow(tokenAddress),
345
- periodAmount: toHexOrThrow(periodAmount),
350
+ tokenAddress: toHexOrThrow(tokenAddress, "tokenAddress"),
351
+ periodAmount: toHexOrThrow(periodAmount, "periodAmount"),
346
352
  periodDuration: Number(periodDuration),
347
353
  ...optionalFields
348
354
  },
349
355
  isAdjustmentAllowed
350
356
  };
351
357
  }
358
+ function formatErc20TokenRevocationPermission({
359
+ permission,
360
+ isAdjustmentAllowed
361
+ }) {
362
+ const {
363
+ data: { justification }
364
+ } = permission;
365
+ const data = {
366
+ ...justification ? { justification } : {}
367
+ };
368
+ return {
369
+ type: "erc20-token-revocation",
370
+ data,
371
+ isAdjustmentAllowed
372
+ };
373
+ }
352
374
 
353
375
  // src/actions/getCaveatAvailableAmount.ts
354
376
  function findMatchingCaveat({
@@ -726,4 +748,4 @@ export {
726
748
  erc7710BundlerActions,
727
749
  actions_exports
728
750
  };
729
- //# sourceMappingURL=chunk-RB4SOJM3.mjs.map
751
+ //# sourceMappingURL=chunk-K5C42JZ2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/actions/index.ts","../src/actions/erc7710RedeemDelegationAction.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 { 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 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});\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<\n TChain,\n 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 AccountSigner,\n Erc20TokenPeriodicPermission,\n Erc20TokenStreamPermission,\n Erc20TokenRevocationPermission,\n NativeTokenPeriodicPermission,\n NativeTokenStreamPermission,\n PermissionRequest,\n PermissionResponse,\n PermissionTypes,\n Rule,\n} from '@metamask/7715-permission-types';\nimport { isHex, toHex } from 'viem';\nimport type {\n Client,\n Account,\n RpcSchema,\n Transport,\n Chain,\n Address,\n} from 'viem';\n\n/**\n * RPC schema for MetaMask related methods.\n *\n * Extends the base RPC schema with methods specific to interacting with EIP-7715:\n * - `wallet_invokeSnap`: Invokes a method on a specific Snap.\n */\nexport type MetaMaskExtensionSchema = RpcSchema &\n [\n {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Method: 'wallet_requestExecutionPermissions';\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Params: PermissionRequest<AccountSigner, PermissionTypes>[];\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ReturnType: PermissionResponse<AccountSigner, PermissionTypes>[];\n },\n ];\n\n/**\n * A Viem client extended with MetaMask Snap-specific RPC methods.\n *\n * This client type allows for interaction with MetaMask Snaps through\n * the standard Viem client interface, with added type safety for\n * Snap-specific methods.\n */\nexport type MetaMaskExtensionClient = Client<\n Transport,\n Chain | undefined,\n Account | undefined,\n MetaMaskExtensionSchema\n>;\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\nexport type SignerParam = Address | AccountSigner;\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 signer: SignerParam;\n // address from which the permission should be granted.\n address?: Address;\n // Timestamp (in seconds) that specifies the time by which this permission MUST expire.\n expiry: number;\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 = PermissionResponse<\n AccountSigner,\n PermissionTypes\n>[];\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<AccountSigner, PermissionTypes> {\n const { chainId, address, expiry, isAdjustmentAllowed } = parameters;\n\n const permissionFormatter = getPermissionFormatter(\n parameters.permission.type,\n );\n\n const signerAddress =\n typeof parameters.signer === 'string'\n ? parameters.signer\n : parameters.signer.data.address;\n\n const rules: Rule[] = [\n {\n type: 'expiry',\n isAdjustmentAllowed,\n data: {\n timestamp: expiry,\n },\n },\n ];\n\n const optionalFields = {\n ...(address ? { address } : {}),\n };\n\n return {\n ...optionalFields,\n chainId: toHex(chainId),\n permission: permissionFormatter({\n permission: parameters.permission,\n isAdjustmentAllowed,\n }),\n signer: {\n // MetaMask 7715 implementation only supports AccountSigner\n type: 'account',\n data: {\n address: signerAddress,\n },\n },\n rules,\n };\n}\n\n/**\n * Checks if a value is defined (not null or undefined).\n *\n * @param value - The value to check.\n * @returns A boolean indicating whether the value is defined.\n */\nfunction isDefined<TValue>(value: TValue | null | undefined): value is TValue {\n return value !== undefined && value !== null;\n}\n\n/**\n * Asserts that a value is defined (not null or undefined).\n *\n * @param value - The value to check.\n * @param parameterName - Optional: The name of the parameter that is being checked.\n * @throws {Error} If the value is null or undefined.\n */\nfunction assertIsDefined<TValue>(\n value: TValue | null | undefined,\n parameterName?: string,\n): asserts value is TValue {\n if (!isDefined(value)) {\n throw new Error(\n `Invalid parameters: ${parameterName ?? 'value'} is required`,\n );\n }\n}\n\n/**\n * Converts a value to a hex string or throws an error if the value is invalid.\n *\n * @param value - The value to convert to hex.\n * @param parameterName - Optional: The name of the parameter that is being converted to hex.\n * @returns The value as a hex string.\n */\nfunction toHexOrThrow(\n value: Parameters<typeof toHex>[0] | undefined,\n parameterName?: string,\n) {\n assertIsDefined(value, parameterName);\n\n if (typeof value === 'string') {\n if (!isHex(value)) {\n throw new Error(\n `Invalid parameters: ${parameterName ?? 'value'} is not a valid hex value`,\n );\n }\n return value;\n }\n\n return toHex(value);\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 * @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 (error) {\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 * @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 * @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 * @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 * @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;;;ACAA,SAAS,yBAAyB;AAYlC,SAAS,QAAQ,oBAAoB,sBAAsB;AAsC3D,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;AAAA,IACnB,GAAG;AAAA,EACL,IAAI;AAEJ,QAAM,OAAO,MAAM,OAAO,gBAAgB;AAAA,IACxC,GAAG;AAAA,IACH,IAAI,KAAK;AAAA,IACT,MAAM;AAAA,EACR,CAAyC;AAEzC,SAAO;AACT;AA2CA,eAAsB,sCAIpB,QACA,YAIA;AACA,MAAI,WAAW,iBAAiB;AAC9B,UAAM,EAAE,aAAa,IAAI;AAEzB,UAAM,sBAA4C,CAAC;AAEnD,UAAM,UA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ACJ,SAAS,eAAe,OAAO;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ,IAAI;AAEJ,MAAI,CAAC,cAAc;AACjB,UAAM,IAAIC,WAAU,+CAA+C;AAAA,EACrE;AAEA,QAAM,UAAUC,cAAa,YAAY;AAEzC,QAAM,YAAY,kCAAkC;AAAA,IAClD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO,OAAO,cAAc;AAAA,IAC1B;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AACH;AAaO,SAAS,2BAA2B;AACzC,SAAO,CAIL,YAGI;AAAA,IACJ,mBAAmB,OACjB,eAIA,kBAAkB,QAAQ;AAAA,MACxB,SACE,WAAW,YACV,MAAM;AACL,YAAI,CAAC,OAAO,OAAO,IAAI;AACrB,gBAAM,IAAID;AAAA,YACR;AAAA,UACF;AAAA,QACF;AACA,eAAO,OAAO,MAAM;AAAA,MACtB,GAAG;AAAA,MACL,GAAG;AAAA,IACL,CAAC;AAAA,EACL;AACF;;;AN9EO,IAAM,yBAAyB,MAAM,CAAC,YAAoB;AAAA,EAC/D,6BAA6B,OAC3B,eACG;AACH,WAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB,MAAM,CAAC,YAA0B;AAAA,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,6 +1,6 @@
1
1
  import {
2
2
  __export
3
- } from "./chunk-UUDQWENY.mjs";
3
+ } from "./chunk-Q6ZTEHYY.mjs";
4
4
 
5
5
  // src/DelegationFramework/ERC20PeriodTransferEnforcer/index.ts
6
6
  var ERC20PeriodTransferEnforcer_exports = {};
@@ -296,4 +296,4 @@ export {
296
296
  read_exports5,
297
297
  NativeTokenStreamingEnforcer_exports
298
298
  };
299
- //# sourceMappingURL=chunk-KUEXI4ME.mjs.map
299
+ //# sourceMappingURL=chunk-LCNP5VYR.mjs.map
@@ -77,21 +77,11 @@ var BalanceChangeType = /* @__PURE__ */ ((BalanceChangeType2) => {
77
77
  })(BalanceChangeType || {});
78
78
 
79
79
  // src/caveatBuilder/allowedCalldataBuilder.ts
80
- var _viem = require('viem');
80
+ var _delegationcore = require('@metamask/delegation-core');
81
81
  var allowedCalldata = "allowedCalldata";
82
82
  var allowedCalldataBuilder = (environment, config) => {
83
83
  const { startIndex, value } = config;
84
- if (!_viem.isHex.call(void 0, value)) {
85
- throw new Error("Invalid value: must be a valid hex string");
86
- }
87
- if (startIndex < 0) {
88
- throw new Error("Invalid startIndex: must be zero or positive");
89
- }
90
- if (!Number.isInteger(startIndex)) {
91
- throw new Error("Invalid startIndex: must be a whole number");
92
- }
93
- const startIndexHex = _viem.toHex.call(void 0, startIndex, { size: 32 });
94
- const terms = _viem.concat.call(void 0, [startIndexHex, value]);
84
+ const terms = _delegationcore.createAllowedCalldataTerms.call(void 0, { startIndex, value });
95
85
  const {
96
86
  caveatEnforcers: { AllowedCalldataEnforcer }
97
87
  } = environment;
@@ -106,7 +96,7 @@ var allowedCalldataBuilder = (environment, config) => {
106
96
  };
107
97
 
108
98
  // src/caveatBuilder/allowedMethodsBuilder.ts
109
-
99
+ var _viem = require('viem');
110
100
  var allowedMethods = "allowedMethods";
111
101
  var FUNCTION_SELECTOR_STRING_LENGTH = 10;
112
102
  var allowedMethodsBuilder = (environment, config) => {
@@ -333,7 +323,7 @@ var erc20BalanceChangeBuilder = (environment, config) => {
333
323
  };
334
324
 
335
325
  // src/caveatBuilder/erc20PeriodTransferBuilder.ts
336
- var _delegationcore = require('@metamask/delegation-core');
326
+
337
327
  var erc20PeriodTransfer = "erc20PeriodTransfer";
338
328
  var erc20PeriodTransferBuilder = (environment, config) => {
339
329
  const { tokenAddress, periodAmount, periodDuration, startDate } = config;
@@ -1469,4 +1459,4 @@ var signDelegation = async ({
1469
1459
 
1470
1460
 
1471
1461
  exports.__export = __export; exports.CaveatBuilder = CaveatBuilder; exports.BalanceChangeType = BalanceChangeType; exports.createCaveatBuilder = createCaveatBuilder; exports.createCaveat = createCaveat; exports.ANY_BENEFICIARY = _delegationcore.ANY_BENEFICIARY; exports.DELEGATION_TYPEHASH = _delegationcore.DELEGATION_TYPEHASH; exports.ROOT_AUTHORITY = _delegationcore.ROOT_AUTHORITY; exports.DELEGATION_ABI_TYPE_COMPONENTS = DELEGATION_ABI_TYPE_COMPONENTS; exports.toDelegationStruct = toDelegationStruct; exports.toDelegation = toDelegation; exports.encodeDelegations = encodeDelegations; exports.encodePermissionContexts = encodePermissionContexts; exports.decodeDelegations = decodeDelegations; exports.decodePermissionContexts = decodePermissionContexts; exports.SIGNABLE_DELEGATION_TYPED_DATA = SIGNABLE_DELEGATION_TYPED_DATA; exports.DELEGATION_ARRAY_ABI_TYPE = DELEGATION_ARRAY_ABI_TYPE; exports.getDelegationHashOffchain = getDelegationHashOffchain; exports.createDelegation = createDelegation; exports.createOpenDelegation = createOpenDelegation; exports.prepareSignDelegationTypedData = prepareSignDelegationTypedData; exports.signDelegation = signDelegation;
1472
- //# sourceMappingURL=chunk-HLCOMYYU.cjs.map
1462
+ //# sourceMappingURL=chunk-MAPUND7S.cjs.map