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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/dist/actions/index.d.cts +2 -2
  3. package/dist/actions/index.d.ts +2 -2
  4. package/dist/{chunk-WPVSFOQM.mjs → chunk-45GHWVQA.mjs} +8 -9
  5. package/dist/chunk-45GHWVQA.mjs.map +1 -0
  6. package/dist/{chunk-DLD377CN.cjs → chunk-BYWRJGSK.cjs} +8 -9
  7. package/dist/chunk-BYWRJGSK.cjs.map +1 -0
  8. package/dist/contracts/index.d.cts +3 -3
  9. package/dist/contracts/index.d.ts +3 -3
  10. package/dist/{delegation-DGUfyX-C.d.ts → delegation-CvVXs0PO.d.ts} +1 -1
  11. package/dist/{delegation-D_TY-tAq.d.cts → delegation-DIriDFkq.d.cts} +1 -1
  12. package/dist/experimental/index.d.cts +1 -1
  13. package/dist/experimental/index.d.ts +1 -1
  14. package/dist/{index-FpCh2419.d.ts → index-5EdxVa_d.d.ts} +1 -1
  15. package/dist/{index-B9bsjGqI.d.ts → index-ChTryO1-.d.ts} +2 -2
  16. package/dist/{index-DvcKJcXi.d.cts → index-DC9baw8F.d.cts} +2 -2
  17. package/dist/{index-CZes99jV.d.cts → index-Dvc4ir4O.d.cts} +1 -1
  18. package/dist/index.cjs +45 -17
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +7 -7
  21. package/dist/index.d.ts +7 -7
  22. package/dist/index.mjs +42 -14
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/{smartAccountsEnvironment-BU8kjlEv.d.cts → smartAccountsEnvironment-Czw9KUYZ.d.cts} +1 -1
  25. package/dist/{smartAccountsEnvironment-egxuflDO.d.ts → smartAccountsEnvironment-u1CcFcGE.d.ts} +1 -1
  26. package/dist/{types-BLYWtcR3.d.cts → types-qdEHxd5Q.d.cts} +1 -1
  27. package/dist/{types-BLYWtcR3.d.ts → types-qdEHxd5Q.d.ts} +1 -1
  28. package/dist/utils/index.cjs +2 -2
  29. package/dist/utils/index.d.cts +3 -3
  30. package/dist/utils/index.d.ts +3 -3
  31. package/dist/utils/index.mjs +1 -1
  32. package/package.json +5 -5
  33. package/dist/chunk-DLD377CN.cjs.map +0 -1
  34. package/dist/chunk-WPVSFOQM.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.0]
11
+
12
+ ### Changed
13
+
14
+ - Migrate from `webauthn-p256` to `0x` p256 module ([#193](https://github.com/metamask/smart-accounts-kit/pull/193))
15
+ - `signer` param is now optional in `toMetaMaskSmartAccount` ([#178](https://github.com/metamask/smart-accounts-kit/pull/178))
16
+
10
17
  ## [0.4.0-beta.2]
11
18
 
12
19
  ### Added
@@ -88,7 +95,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
95
 
89
96
  - Promote readable permissions actions (`requestExecutionPermissions`, `sendTransactionWithDelegation`, and `sendUserOperationWithDelegation`) from experimental ([#91](https://github.com/MetaMask/smart-accounts-kit/pull/91))
90
97
 
91
- [Unreleased]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@0.4.0-beta.2...HEAD
98
+ [Unreleased]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@1.0.0...HEAD
99
+ [1.0.0]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@0.4.0-beta.2...@metamask/smart-accounts-kit@1.0.0
92
100
  [0.4.0-beta.2]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@0.4.0-beta.1...@metamask/smart-accounts-kit@0.4.0-beta.2
93
101
  [0.4.0-beta.1]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@0.4.0-beta.0...@metamask/smart-accounts-kit@0.4.0-beta.1
94
102
  [0.4.0-beta.0]: https://github.com/metamask/smart-accounts-kit/compare/@metamask/smart-accounts-kit@0.3.0...@metamask/smart-accounts-kit@0.4.0-beta.0
@@ -1,8 +1,8 @@
1
- export { C as CaveatEnforcerParams, O as DelegatedCall, H as Erc20TokenPeriodicPermission, I as Erc20TokenRevocationPermission, F as Erc20TokenStreamPermission, E as Erc7715Client, z as GetGrantedExecutionPermissionsResult, G as GetSupportedExecutionPermissionsResult, M as MetaMaskExtensionClient, u as MetaMaskExtensionSchema, D as NativeTokenPeriodicPermission, N as NativeTokenStreamPermission, P as PeriodTransferResult, w as PermissionRequestParameter, B as PermissionTypes, R as RequestExecutionPermissionsParameters, v as RequestExecutionPermissionsReturnType, K as RpcGetGrantedExecutionPermissionsResult, J as RpcGetSupportedExecutionPermissionsResult, L as RpcSupportedPermissionInfo, m as SignDelegationParameters, n as SignDelegationReturnType, q as SignUserOperationParameters, r as SignUserOperationReturnType, S as StreamingResult, A as SupportedPermissionInfo, c as caveatEnforcerActions, b as erc7710BundlerActions, a as erc7710WalletActions, e as erc7715ProviderActions, g as getErc20PeriodTransferEnforcerAvailableAmount, d as getErc20StreamingEnforcerAvailableAmount, y as getGrantedExecutionPermissions, f as getMultiTokenPeriodEnforcerAvailableAmount, h as getNativeTokenPeriodTransferEnforcerAvailableAmount, j as getNativeTokenStreamingEnforcerAvailableAmount, x as getSupportedExecutionPermissions, k as isValid7702Implementation, t as requestExecutionPermissions, s as signDelegation, l as signDelegationActions, o as signUserOperation, p as signUserOperationActions } from '../index-CZes99jV.cjs';
1
+ export { C as CaveatEnforcerParams, O as DelegatedCall, H as Erc20TokenPeriodicPermission, I as Erc20TokenRevocationPermission, F as Erc20TokenStreamPermission, E as Erc7715Client, z as GetGrantedExecutionPermissionsResult, G as GetSupportedExecutionPermissionsResult, M as MetaMaskExtensionClient, u as MetaMaskExtensionSchema, D as NativeTokenPeriodicPermission, N as NativeTokenStreamPermission, P as PeriodTransferResult, w as PermissionRequestParameter, B as PermissionTypes, R as RequestExecutionPermissionsParameters, v as RequestExecutionPermissionsReturnType, K as RpcGetGrantedExecutionPermissionsResult, J as RpcGetSupportedExecutionPermissionsResult, L as RpcSupportedPermissionInfo, m as SignDelegationParameters, n as SignDelegationReturnType, q as SignUserOperationParameters, r as SignUserOperationReturnType, S as StreamingResult, A as SupportedPermissionInfo, c as caveatEnforcerActions, b as erc7710BundlerActions, a as erc7710WalletActions, e as erc7715ProviderActions, g as getErc20PeriodTransferEnforcerAvailableAmount, d as getErc20StreamingEnforcerAvailableAmount, y as getGrantedExecutionPermissions, f as getMultiTokenPeriodEnforcerAvailableAmount, h as getNativeTokenPeriodTransferEnforcerAvailableAmount, j as getNativeTokenStreamingEnforcerAvailableAmount, x as getSupportedExecutionPermissions, k as isValid7702Implementation, t as requestExecutionPermissions, s as signDelegation, l as signDelegationActions, o as signUserOperation, p as signUserOperationActions } from '../index-Dvc4ir4O.cjs';
2
2
  import 'viem';
3
3
  import '@metamask/7715-permission-types';
4
4
  import 'viem/account-abstraction';
5
- import '../types-BLYWtcR3.cjs';
5
+ import '../types-qdEHxd5Q.cjs';
6
6
  import '@metamask/delegation-abis';
7
7
  import 'viem/chains';
8
8
  import '../userOp-DKgjzz7B.cjs';
@@ -1,8 +1,8 @@
1
- export { C as CaveatEnforcerParams, O as DelegatedCall, H as Erc20TokenPeriodicPermission, I as Erc20TokenRevocationPermission, F as Erc20TokenStreamPermission, E as Erc7715Client, z as GetGrantedExecutionPermissionsResult, G as GetSupportedExecutionPermissionsResult, M as MetaMaskExtensionClient, u as MetaMaskExtensionSchema, D as NativeTokenPeriodicPermission, N as NativeTokenStreamPermission, P as PeriodTransferResult, w as PermissionRequestParameter, B as PermissionTypes, R as RequestExecutionPermissionsParameters, v as RequestExecutionPermissionsReturnType, K as RpcGetGrantedExecutionPermissionsResult, J as RpcGetSupportedExecutionPermissionsResult, L as RpcSupportedPermissionInfo, m as SignDelegationParameters, n as SignDelegationReturnType, q as SignUserOperationParameters, r as SignUserOperationReturnType, S as StreamingResult, A as SupportedPermissionInfo, c as caveatEnforcerActions, b as erc7710BundlerActions, a as erc7710WalletActions, e as erc7715ProviderActions, g as getErc20PeriodTransferEnforcerAvailableAmount, d as getErc20StreamingEnforcerAvailableAmount, y as getGrantedExecutionPermissions, f as getMultiTokenPeriodEnforcerAvailableAmount, h as getNativeTokenPeriodTransferEnforcerAvailableAmount, j as getNativeTokenStreamingEnforcerAvailableAmount, x as getSupportedExecutionPermissions, k as isValid7702Implementation, t as requestExecutionPermissions, s as signDelegation, l as signDelegationActions, o as signUserOperation, p as signUserOperationActions } from '../index-FpCh2419.js';
1
+ export { C as CaveatEnforcerParams, O as DelegatedCall, H as Erc20TokenPeriodicPermission, I as Erc20TokenRevocationPermission, F as Erc20TokenStreamPermission, E as Erc7715Client, z as GetGrantedExecutionPermissionsResult, G as GetSupportedExecutionPermissionsResult, M as MetaMaskExtensionClient, u as MetaMaskExtensionSchema, D as NativeTokenPeriodicPermission, N as NativeTokenStreamPermission, P as PeriodTransferResult, w as PermissionRequestParameter, B as PermissionTypes, R as RequestExecutionPermissionsParameters, v as RequestExecutionPermissionsReturnType, K as RpcGetGrantedExecutionPermissionsResult, J as RpcGetSupportedExecutionPermissionsResult, L as RpcSupportedPermissionInfo, m as SignDelegationParameters, n as SignDelegationReturnType, q as SignUserOperationParameters, r as SignUserOperationReturnType, S as StreamingResult, A as SupportedPermissionInfo, c as caveatEnforcerActions, b as erc7710BundlerActions, a as erc7710WalletActions, e as erc7715ProviderActions, g as getErc20PeriodTransferEnforcerAvailableAmount, d as getErc20StreamingEnforcerAvailableAmount, y as getGrantedExecutionPermissions, f as getMultiTokenPeriodEnforcerAvailableAmount, h as getNativeTokenPeriodTransferEnforcerAvailableAmount, j as getNativeTokenStreamingEnforcerAvailableAmount, x as getSupportedExecutionPermissions, k as isValid7702Implementation, t as requestExecutionPermissions, s as signDelegation, l as signDelegationActions, o as signUserOperation, p as signUserOperationActions } from '../index-5EdxVa_d.js';
2
2
  import 'viem';
3
3
  import '@metamask/7715-permission-types';
4
4
  import 'viem/account-abstraction';
5
- import '../types-BLYWtcR3.js';
5
+ import '../types-qdEHxd5Q.js';
6
6
  import '@metamask/delegation-abis';
7
7
  import 'viem/chains';
8
8
  import '../userOp-DKgjzz7B.js';
@@ -147,6 +147,7 @@ var encodeCallsForCaller = async (caller, calls) => {
147
147
  };
148
148
 
149
149
  // src/webAuthn.ts
150
+ import { Signature } from "ox";
150
151
  import {
151
152
  parseAbiParameters,
152
153
  encodeAbiParameters,
@@ -155,7 +156,6 @@ import {
155
156
  concat,
156
157
  hexToBytes
157
158
  } from "viem";
158
- import { parseSignature } from "webauthn-p256";
159
159
  var FIELD_MODULUS = 115792089210356248762697446949407573529996955224135760342422259061068512044369n;
160
160
  var MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;
161
161
  var SIGNATURE_ABI_PARAMS = parseAbiParameters(
@@ -189,19 +189,18 @@ var getResponseTypeLocation = (clientDataJson) => {
189
189
  };
190
190
  function encodeDeleGatorSignature(keyId, signature, clientDataJSON, authenticatorData) {
191
191
  const keyIdHash = keccak256(encodePacked(["string"], [keyId]));
192
- const parsedSignature = parseSignature(signature);
193
- let { s } = parsedSignature;
194
- while (s > MALLEABILITY_THRESHOLD) {
195
- s = FIELD_MODULUS - s;
192
+ const { r: rValue, s: sValue } = Signature.fromHex(signature);
193
+ let normalizedS = sValue;
194
+ while (normalizedS > MALLEABILITY_THRESHOLD) {
195
+ normalizedS = FIELD_MODULUS - normalizedS;
196
196
  }
197
- const { r } = parsedSignature;
198
197
  const [clientDataComponent1, clientDataComponent2] = splitOnChallenge(clientDataJSON);
199
198
  const { userVerified } = parseAuthenticatorFlags(authenticatorData);
200
199
  const responseTypeLocation = getResponseTypeLocation(clientDataJSON);
201
200
  const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [
202
201
  keyIdHash,
203
- r,
204
- s,
202
+ rValue,
203
+ normalizedS,
205
204
  authenticatorData,
206
205
  userVerified,
207
206
  clientDataComponent1,
@@ -256,4 +255,4 @@ export {
256
255
  encodeDeleGatorSignature,
257
256
  createDummyWebAuthnSignature
258
257
  };
259
- //# sourceMappingURL=chunk-WPVSFOQM.mjs.map
258
+ //# sourceMappingURL=chunk-45GHWVQA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/counterfactualAccountData.ts","../src/encodeCalls.ts","../src/webAuthn.ts"],"sourcesContent":["import type { Address, Hex } from 'viem';\nimport { getContractAddress, pad } from 'viem';\n\nimport { Implementation } from './constants';\nimport { initializeHybridDeleGator } from './DelegationFramework/HybridDeleGator/encode';\nimport { initializeMultiSigDeleGator } from './DelegationFramework/MultiSigDeleGator/encode';\nimport { create2Deploy as encodeCreate2Deploy } from './DelegationFramework/SimpleFactory/encode';\nimport { encodeProxyCreationCode } from './DelegationFramework/utils';\nimport type {\n SmartAccountsEnvironment,\n HybridDeleGatorDeployParams,\n MultiSigDeleGatorDeployParams,\n DeployParams,\n} from './types';\n\n/**\n * Infers counterfactual account data for a DeleGator smart account.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @template TDeployParams - The type of deployment parameters, defaults to DeployParams<Implementation>.\n * @param options - The options for generating counterfactual account data.\n * @param options.factory - The address of the SimpleFactory contract.\n * @param options.implementations - The DeleGator implementation contracts.\n * @param options.implementation - The implementation type to use.\n * @param options.deployParams - The deployment parameters for the specified implementation.\n * @param options.deploySalt - The salt to use for CREATE2 address computation.\n * @returns An object containing the counterfactual address and factory calldata.\n * @description This function calculates the address a DeleGator contract would have if deployed,\n * and provides the calldata needed to deploy it.\n */\nexport const getCounterfactualAccountData = async <\n TImplementation extends Implementation,\n>({\n factory,\n implementations,\n implementation,\n deployParams,\n deploySalt,\n}: {\n factory: Address;\n implementations: SmartAccountsEnvironment['implementations'];\n implementation: TImplementation;\n deployParams: DeployParams<TImplementation>;\n deploySalt: Hex;\n}): Promise<{ factoryData: Hex; address: Address }> => {\n let implementationAddress: Address;\n let initcode: Hex;\n\n switch (implementation) {\n case Implementation.Hybrid: {\n const [owner, keyIds, xValues, yValues] =\n deployParams as HybridDeleGatorDeployParams;\n\n if (!implementations.HybridDeleGatorImpl) {\n throw new Error(\n 'HybridDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.HybridDeleGatorImpl;\n\n const p256Owners = keyIds.map((keyId, index) => {\n const xValue = xValues[index];\n const yValue = yValues[index];\n\n if (!xValue || !yValue) {\n throw new Error(\n `Missing X or Y value for keyId ${keyId} at index ${index}`,\n );\n }\n\n return {\n keyId,\n x: xValue,\n y: yValue,\n };\n });\n\n initcode = initializeHybridDeleGator({ eoaOwner: owner, p256Owners });\n break;\n }\n case Implementation.MultiSig: {\n const [owners, threshold] = deployParams as MultiSigDeleGatorDeployParams;\n\n if (!implementations.MultiSigDeleGatorImpl) {\n throw new Error(\n 'MultiSigDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.MultiSigDeleGatorImpl;\n initcode = initializeMultiSigDeleGator({ owners, threshold });\n break;\n }\n case Implementation.Stateless7702:\n default:\n throw new Error(`Implementation type '${implementation}' not supported`);\n }\n\n const salt = pad(deploySalt, { dir: 'left', size: 32 });\n\n const proxyCreationCode = encodeProxyCreationCode({\n implementationAddress,\n initcode,\n });\n\n const address = getContractAddress({\n bytecode: proxyCreationCode,\n from: factory,\n opcode: 'CREATE2',\n salt,\n });\n\n const factoryData = encodeCreate2Deploy(proxyCreationCode, salt);\n\n return {\n factoryData,\n address,\n };\n};\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport { encodeFunctionData } from 'viem';\nimport type { Address, Hex } from 'viem';\n\nimport type { DelegatedCall } from './actions/erc7710RedeemDelegationAction';\nimport { encodeDelegations } from './delegation';\nimport {\n execute,\n executeWithMode,\n} from './DelegationFramework/DeleGatorCore/encode';\nimport {\n ExecutionMode,\n createExecution,\n encodeExecutionCalldatas,\n} from './executions';\nimport type { Call } from './types';\n\n/**\n * Checks if a call is a delegated call by checking for the presence of permissionContext and delegationManager.\n *\n * @param call - The call to check.\n * @returns True if the call is a delegated call, false otherwise.\n */\nconst isDelegatedCall = (call: Call): call is DelegatedCall => {\n return 'permissionContext' in call && 'delegationManager' in call;\n};\n\n/**\n * If there's a single call with permissionContext and delegationManager,\n * processes it as a delegated call.\n *\n * @param call - The call to process.\n * @returns The execution object for the delegated call.\n * @description\n * This function creates an execution that calls redeemDelegations on the delegation manager.\n */\nconst processDelegatedCall = (call: DelegatedCall) => {\n const {\n permissionContext,\n delegationManager,\n to: target,\n value,\n data: callData,\n } = call;\n\n const callAsExecution = createExecution({ target, value, callData });\n\n if (!permissionContext) {\n return callAsExecution;\n }\n\n const encodedPermissionsContext = encodeDelegations(permissionContext);\n\n const redeemCalldata = encodeFunctionData({\n abi: DelegationManager,\n functionName: 'redeemDelegations',\n args: [\n [encodedPermissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([[callAsExecution]]),\n ],\n });\n\n return createExecution({\n target: delegationManager,\n callData: redeemCalldata,\n });\n};\n\n/**\n * If there's a single call, encode the shorthand `execute` function. Otherwise, encode the `executeWithMode` function. Execution type will always be \"default\".\n *\n * @param calls - The calls to execute.\n * @returns The encoded calldata for the DeleGator to execute the calls.\n * @description\n * This function supports both single and batch execution modes.\n * For single calls, it uses the gas-efficient execute function.\n */\nexport const encodeCalls = (calls: readonly Call[]) => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call && !isDelegatedCall(call)) {\n const { to: target, value, data: callData } = call;\n const execution = createExecution({ target, value, callData });\n return execute({ execution });\n }\n }\n\n const executions = calls.map((call) => {\n if (isDelegatedCall(call)) {\n return processDelegatedCall(call);\n }\n const { to: target, value, data: callData } = call;\n return createExecution({ target, value, callData });\n });\n\n const mode =\n calls.length === 1\n ? ExecutionMode.SingleDefault\n : ExecutionMode.BatchDefault;\n return executeWithMode({ mode, executions });\n};\n\n/**\n * Encodes calls for execution by a DeleGator smart contract.\n *\n * @param caller - The address of the DeleGator contract.\n * @param calls - An array of Call objects, each containing 'to', optional 'data', and optional 'value'.\n * @returns A promise that resolves to the encoded function data as a hexadecimal string.\n * @description\n * - If there's a single call directly to the delegator, it returns the call data directly.\n * - For multiple calls or calls to other addresses, it creates executions and encodes them for the DeleGator's execute function.\n * - The execution mode is set to ExecutionMode.SingleDefault for a single call, or ExecutionMode.BatchDefault for multiple calls.\n *\n * todo: This doesn't fully expose the flexibility of the DeleGator's execute function, but it's a start.\n * maybe we add a mechanism where individual calls passed to this function can be encoded batches.\n */\nexport const encodeCallsForCaller = async (\n caller: Address,\n calls: readonly Call[],\n): Promise<Hex> => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call?.to === caller && !isDelegatedCall(call)) {\n // if there's a single call, and it's to the delegator, we can just return the calldata directly.\n return call.data ?? '0x';\n }\n }\n return encodeCalls(calls);\n};\n","import { Signature } from 'ox';\nimport {\n parseAbiParameters,\n encodeAbiParameters,\n type Hex,\n encodePacked,\n keccak256,\n concat,\n hexToBytes,\n} from 'viem';\n\nexport const FIELD_MODULUS =\n 115792089210356248762697446949407573529996955224135760342422259061068512044369n;\nexport const MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;\n\nexport const SIGNATURE_ABI_PARAMS = parseAbiParameters(\n 'bytes32, uint256, uint256, bytes, bool, string, string, uint256',\n);\n\n/**\n * This function is used to convert the client data returned from the\n * credentials API into a format that can be consumed by the DeleGator\n * contracts. We need the flattend JSON strings before and after the\n * userOpHash/challenge. This function provides those two client data string\n * slices.\n *\n * @param clientDataJson - The client data JSON string.\n * @returns Returns [clientDataJSONPrefix and clientDataJSONSuffix]\n * ClientDataJSONPrefix contains the client data till the challengeHash\n * ClientDataJSONSuffix contains the client data after the challengeHash.\n */\nexport const splitOnChallenge = (\n clientDataJson: string,\n): [clientDataJSONPrefix: string, clientDataJSONSuffix: string] => {\n /*\n CientData looks like this:\n {\n \"type\": \"webauthn.create\" | \"webauthn.get\",\n \"challenge\": \"{userOpHash}\",\n \"origin\": \"{Domain}\",\n \"crossOrigin\": boolean\n }\n */\n try {\n const { challenge } = JSON.parse(clientDataJson);\n if (challenge === undefined) {\n throw new Error('No \"challenge\" found in the input string');\n }\n return clientDataJson.split(challenge) as [string, string];\n } catch (error) {\n throw new Error('No \"challenge\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Returns the index of '\"type\":' in the ClientData.\n *\n * @param clientDataJson - Stringified ClientDataJSON.\n * @returns The index of '\"type\":' in the ClientData.\n */\nexport const getResponseTypeLocation = (clientDataJson: string): bigint => {\n try {\n // Find the index of the `\"type\":` key in the JSON string directly\n const typeIndex = clientDataJson.indexOf('\"type\":');\n\n if (typeIndex === -1) {\n throw new Error('No \"type\" found in the input string');\n }\n // Return the index of the `\"type\":` key\n return BigInt(typeIndex);\n } catch (error) {\n // Handle any errors that occur during the search\n throw new Error('No \"type\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Encodes a signature to a hexadecimal signature that will be accepted\n * by the DeleGator contracts.\n *\n * @param keyId - The key used for the signature, represented as a hexadecimal string.\n * @param signature - The signature to convert, as Hex.\n * @param clientDataJSON - The client data used in the creation of the signature.\n * @param authenticatorData - The authenticator data used in the creation of the signature.\n * @returns The signature as a valid DeleGator signature encoded as Hexadecimal string.\n */\nexport function encodeDeleGatorSignature(\n keyId: string,\n signature: Hex,\n clientDataJSON: string,\n authenticatorData: Hex,\n): Hex {\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n\n const { r: rValue, s: sValue } = Signature.fromHex(signature);\n\n let normalizedS = sValue;\n\n while (normalizedS > MALLEABILITY_THRESHOLD) {\n normalizedS = FIELD_MODULUS - normalizedS;\n }\n\n const [clientDataComponent1, clientDataComponent2] =\n splitOnChallenge(clientDataJSON);\n\n const { userVerified } = parseAuthenticatorFlags(authenticatorData);\n\n const responseTypeLocation = getResponseTypeLocation(clientDataJSON);\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rValue,\n normalizedS,\n authenticatorData,\n userVerified,\n clientDataComponent1,\n clientDataComponent2,\n responseTypeLocation,\n ]);\n return encodedSignature;\n}\n\nconst AUTHENTICATOR_DATA_FLAGS_OFFSET = 32;\n// We have all of the flag bits defined here for completeness, even though we only extract the userVerified flag.\nenum AuthenticatorDataFlagBitIndex {\n UserPresence = 0,\n UserVerified = 2,\n BackupEligibility = 3,\n BackupState = 4,\n AttestedCredentialData = 6,\n ExtensionData = 7,\n}\n\nexport type AuthenticatorFlags = {\n userVerified: boolean;\n};\n\n/**\n * Parses the authenticator data and returns an authenticator flags object with the `userVerified` flag.\n * See https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data.\n *\n * @param authenticatorData - The authenticator data to parse.\n * @returns An object representing the parsed authenticator flags.\n */\nexport function parseAuthenticatorFlags(\n authenticatorData: Hex,\n): AuthenticatorFlags {\n const authenticatorDataBuffer = hexToBytes(authenticatorData);\n const dataBufferUint8 = new Uint8Array(authenticatorDataBuffer);\n const flags = dataBufferUint8[AUTHENTICATOR_DATA_FLAGS_OFFSET];\n if (flags === undefined) {\n throw new Error('Authenticator flags not found in authenticator data');\n }\n\n // Bit 0 is the least significant bit in the flags byte, so we left shift 0b1 by the bit index\n // eslint-disable-next-line no-bitwise\n const bitMask = 0b1 << AuthenticatorDataFlagBitIndex.UserVerified;\n\n return {\n // eslint-disable-next-line no-bitwise\n userVerified: (flags & bitMask) !== 0x0,\n };\n}\n\n/**\n * Creates a dummy signature.\n * This must meet all early-failure conditions of the real signature, but does not need to be a valid signature.\n *\n * @param keyId - The key ID to use for the dummy signature.\n * @returns The encoded signature.\n */\nexport const createDummyWebAuthnSignature = (keyId: Hex) => {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#data_structure\n const rpIdHash = keccak256(encodePacked(['string'], ['AuthenticatorData']));\n const flags = '0x05';\n const signCount = '0x00000000';\n const authenticatorData = concat([rpIdHash, flags, signCount]);\n\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n const rs =\n 57896044605178124381348723474703786764998477612067880171211129530534256022184n;\n const userVerification = true;\n const clientDataPrefix = '{\"type\":\"webauthn.get\",\"challenge\":\"';\n const clientDataSuffix = '\",\"origin\":\"passkey-domain\",\"crossOrigin\":false}';\n const responseTypeLocation = 1n;\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rs,\n rs,\n authenticatorData,\n userVerification,\n clientDataPrefix,\n clientDataSuffix,\n responseTypeLocation,\n ]);\n\n return encodedSignature;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AACA,SAAS,oBAAoB,WAAW;AA6BjC,IAAM,+BAA+B,OAE1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAMuD;AACrD,MAAI;AACJ,MAAI;AAEJ,UAAQ,gBAAgB;AAAA,IACtB,4BAA4B;AAC1B,YAAM,CAAC,OAAO,QAAQ,SAAS,OAAO,IACpC;AAEF,UAAI,CAAC,gBAAgB,qBAAqB;AACxC,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,8BAAwB,gBAAgB;AAExC,YAAM,aAAa,OAAO,IAAI,CAAC,OAAO,UAAU;AAC9C,cAAM,SAAS,QAAQ,KAAK;AAC5B,cAAM,SAAS,QAAQ,KAAK;AAE5B,YAAI,CAAC,UAAU,CAAC,QAAQ;AACtB,gBAAM,IAAI;AAAA,YACR,kCAAkC,KAAK,aAAa,KAAK;AAAA,UAC3D;AAAA,QACF;AAEA,eAAO;AAAA,UACL;AAAA,UACA,GAAG;AAAA,UACH,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAED,iBAAW,OAA0B,EAAE,UAAU,OAAO,WAAW,CAAC;AACpE;AAAA,IACF;AAAA,IACA,gCAA8B;AAC5B,YAAM,CAAC,QAAQ,SAAS,IAAI;AAE5B,UAAI,CAAC,gBAAgB,uBAAuB;AAC1C,cAA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,KAAO;AAEvB,SAAO;AAAA;AAAA,IAEL,eAAe,QAAQ,aAAa;AAAA,EACtC;AACF;AASO,IAAM,+BAA+B,CAAC,UAAe;AAE1D,QAAM,WAAW,UAAU,aAAa,CAAC,QAAQ,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAC1E,QAAM,QAAQ;AACd,QAAM,YAAY;AAClB,QAAM,oBAAoB,OAAO,CAAC,UAAU,OAAO,SAAS,CAAC;AAE7D,QAAM,YAAY,UAAU,aAAa,CAAC,QAAQ,GAAG,CAAC,KAAK,CAAC,CAAC;AAC7D,QAAM,KACJ;AACF,QAAM,mBAAmB;AACzB,QAAM,mBAAmB;AACzB,QAAM,mBAAmB;AACzB,QAAM,uBAAuB;AAE7B,QAAM,mBAAmB,oBAAoB,sBAAsB;AAAA,IACjE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["encode","encode"]}
@@ -147,6 +147,7 @@ var encodeCallsForCaller = async (caller, calls) => {
147
147
  };
148
148
 
149
149
  // src/webAuthn.ts
150
+ var _ox = require('ox');
150
151
 
151
152
 
152
153
 
@@ -155,7 +156,6 @@ var encodeCallsForCaller = async (caller, calls) => {
155
156
 
156
157
 
157
158
 
158
- var _webauthnp256 = require('webauthn-p256');
159
159
  var FIELD_MODULUS = 115792089210356248762697446949407573529996955224135760342422259061068512044369n;
160
160
  var MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;
161
161
  var SIGNATURE_ABI_PARAMS = _viem.parseAbiParameters.call(void 0,
@@ -189,19 +189,18 @@ var getResponseTypeLocation = (clientDataJson) => {
189
189
  };
190
190
  function encodeDeleGatorSignature(keyId, signature, clientDataJSON, authenticatorData) {
191
191
  const keyIdHash = _viem.keccak256.call(void 0, _viem.encodePacked.call(void 0, ["string"], [keyId]));
192
- const parsedSignature = _webauthnp256.parseSignature.call(void 0, signature);
193
- let { s } = parsedSignature;
194
- while (s > MALLEABILITY_THRESHOLD) {
195
- s = FIELD_MODULUS - s;
192
+ const { r: rValue, s: sValue } = _ox.Signature.fromHex(signature);
193
+ let normalizedS = sValue;
194
+ while (normalizedS > MALLEABILITY_THRESHOLD) {
195
+ normalizedS = FIELD_MODULUS - normalizedS;
196
196
  }
197
- const { r } = parsedSignature;
198
197
  const [clientDataComponent1, clientDataComponent2] = splitOnChallenge(clientDataJSON);
199
198
  const { userVerified } = parseAuthenticatorFlags(authenticatorData);
200
199
  const responseTypeLocation = getResponseTypeLocation(clientDataJSON);
201
200
  const encodedSignature = _viem.encodeAbiParameters.call(void 0, SIGNATURE_ABI_PARAMS, [
202
201
  keyIdHash,
203
- r,
204
- s,
202
+ rValue,
203
+ normalizedS,
205
204
  authenticatorData,
206
205
  userVerified,
207
206
  clientDataComponent1,
@@ -256,4 +255,4 @@ var createDummyWebAuthnSignature = (keyId) => {
256
255
 
257
256
 
258
257
  exports.getCounterfactualAccountData = getCounterfactualAccountData; exports.encodeCalls = encodeCalls; exports.encodeCallsForCaller = encodeCallsForCaller; exports.SIGNATURE_ABI_PARAMS = SIGNATURE_ABI_PARAMS; exports.encodeDeleGatorSignature = encodeDeleGatorSignature; exports.createDummyWebAuthnSignature = createDummyWebAuthnSignature;
259
- //# sourceMappingURL=chunk-DLD377CN.cjs.map
258
+ //# sourceMappingURL=chunk-BYWRJGSK.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-BYWRJGSK.cjs","../src/counterfactualAccountData.ts","../src/encodeCalls.ts","../src/webAuthn.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACfA,4BAAwC;AA6BjC,IAAM,6BAAA,EAA+B,MAAA,CAE1C;AAAA,EACA,OAAA;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;AAGA,EAAA;AAEA,EAAA;AAEA,EAAA;AAAmE,IAAA;AACjE,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,EAAA;AAEF,EAAA;AACF;AAEA;AAsBO;AAGL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AAAqE,EAAA;AAKvE,EAAA;AAEA,EAAA;AAAO;AAAA,IAAA;AAE+B,EAAA;AAExC;AASO;AAEL,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AAAmE,IAAA;AACjE,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,EAAA;AAGF,EAAA;AACF;AH8CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-BYWRJGSK.cjs","sourcesContent":[null,"import type { Address, Hex } from 'viem';\nimport { getContractAddress, pad } from 'viem';\n\nimport { Implementation } from './constants';\nimport { initializeHybridDeleGator } from './DelegationFramework/HybridDeleGator/encode';\nimport { initializeMultiSigDeleGator } from './DelegationFramework/MultiSigDeleGator/encode';\nimport { create2Deploy as encodeCreate2Deploy } from './DelegationFramework/SimpleFactory/encode';\nimport { encodeProxyCreationCode } from './DelegationFramework/utils';\nimport type {\n SmartAccountsEnvironment,\n HybridDeleGatorDeployParams,\n MultiSigDeleGatorDeployParams,\n DeployParams,\n} from './types';\n\n/**\n * Infers counterfactual account data for a DeleGator smart account.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @template TDeployParams - The type of deployment parameters, defaults to DeployParams<Implementation>.\n * @param options - The options for generating counterfactual account data.\n * @param options.factory - The address of the SimpleFactory contract.\n * @param options.implementations - The DeleGator implementation contracts.\n * @param options.implementation - The implementation type to use.\n * @param options.deployParams - The deployment parameters for the specified implementation.\n * @param options.deploySalt - The salt to use for CREATE2 address computation.\n * @returns An object containing the counterfactual address and factory calldata.\n * @description This function calculates the address a DeleGator contract would have if deployed,\n * and provides the calldata needed to deploy it.\n */\nexport const getCounterfactualAccountData = async <\n TImplementation extends Implementation,\n>({\n factory,\n implementations,\n implementation,\n deployParams,\n deploySalt,\n}: {\n factory: Address;\n implementations: SmartAccountsEnvironment['implementations'];\n implementation: TImplementation;\n deployParams: DeployParams<TImplementation>;\n deploySalt: Hex;\n}): Promise<{ factoryData: Hex; address: Address }> => {\n let implementationAddress: Address;\n let initcode: Hex;\n\n switch (implementation) {\n case Implementation.Hybrid: {\n const [owner, keyIds, xValues, yValues] =\n deployParams as HybridDeleGatorDeployParams;\n\n if (!implementations.HybridDeleGatorImpl) {\n throw new Error(\n 'HybridDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.HybridDeleGatorImpl;\n\n const p256Owners = keyIds.map((keyId, index) => {\n const xValue = xValues[index];\n const yValue = yValues[index];\n\n if (!xValue || !yValue) {\n throw new Error(\n `Missing X or Y value for keyId ${keyId} at index ${index}`,\n );\n }\n\n return {\n keyId,\n x: xValue,\n y: yValue,\n };\n });\n\n initcode = initializeHybridDeleGator({ eoaOwner: owner, p256Owners });\n break;\n }\n case Implementation.MultiSig: {\n const [owners, threshold] = deployParams as MultiSigDeleGatorDeployParams;\n\n if (!implementations.MultiSigDeleGatorImpl) {\n throw new Error(\n 'MultiSigDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.MultiSigDeleGatorImpl;\n initcode = initializeMultiSigDeleGator({ owners, threshold });\n break;\n }\n case Implementation.Stateless7702:\n default:\n throw new Error(`Implementation type '${implementation}' not supported`);\n }\n\n const salt = pad(deploySalt, { dir: 'left', size: 32 });\n\n const proxyCreationCode = encodeProxyCreationCode({\n implementationAddress,\n initcode,\n });\n\n const address = getContractAddress({\n bytecode: proxyCreationCode,\n from: factory,\n opcode: 'CREATE2',\n salt,\n });\n\n const factoryData = encodeCreate2Deploy(proxyCreationCode, salt);\n\n return {\n factoryData,\n address,\n };\n};\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport { encodeFunctionData } from 'viem';\nimport type { Address, Hex } from 'viem';\n\nimport type { DelegatedCall } from './actions/erc7710RedeemDelegationAction';\nimport { encodeDelegations } from './delegation';\nimport {\n execute,\n executeWithMode,\n} from './DelegationFramework/DeleGatorCore/encode';\nimport {\n ExecutionMode,\n createExecution,\n encodeExecutionCalldatas,\n} from './executions';\nimport type { Call } from './types';\n\n/**\n * Checks if a call is a delegated call by checking for the presence of permissionContext and delegationManager.\n *\n * @param call - The call to check.\n * @returns True if the call is a delegated call, false otherwise.\n */\nconst isDelegatedCall = (call: Call): call is DelegatedCall => {\n return 'permissionContext' in call && 'delegationManager' in call;\n};\n\n/**\n * If there's a single call with permissionContext and delegationManager,\n * processes it as a delegated call.\n *\n * @param call - The call to process.\n * @returns The execution object for the delegated call.\n * @description\n * This function creates an execution that calls redeemDelegations on the delegation manager.\n */\nconst processDelegatedCall = (call: DelegatedCall) => {\n const {\n permissionContext,\n delegationManager,\n to: target,\n value,\n data: callData,\n } = call;\n\n const callAsExecution = createExecution({ target, value, callData });\n\n if (!permissionContext) {\n return callAsExecution;\n }\n\n const encodedPermissionsContext = encodeDelegations(permissionContext);\n\n const redeemCalldata = encodeFunctionData({\n abi: DelegationManager,\n functionName: 'redeemDelegations',\n args: [\n [encodedPermissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([[callAsExecution]]),\n ],\n });\n\n return createExecution({\n target: delegationManager,\n callData: redeemCalldata,\n });\n};\n\n/**\n * If there's a single call, encode the shorthand `execute` function. Otherwise, encode the `executeWithMode` function. Execution type will always be \"default\".\n *\n * @param calls - The calls to execute.\n * @returns The encoded calldata for the DeleGator to execute the calls.\n * @description\n * This function supports both single and batch execution modes.\n * For single calls, it uses the gas-efficient execute function.\n */\nexport const encodeCalls = (calls: readonly Call[]) => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call && !isDelegatedCall(call)) {\n const { to: target, value, data: callData } = call;\n const execution = createExecution({ target, value, callData });\n return execute({ execution });\n }\n }\n\n const executions = calls.map((call) => {\n if (isDelegatedCall(call)) {\n return processDelegatedCall(call);\n }\n const { to: target, value, data: callData } = call;\n return createExecution({ target, value, callData });\n });\n\n const mode =\n calls.length === 1\n ? ExecutionMode.SingleDefault\n : ExecutionMode.BatchDefault;\n return executeWithMode({ mode, executions });\n};\n\n/**\n * Encodes calls for execution by a DeleGator smart contract.\n *\n * @param caller - The address of the DeleGator contract.\n * @param calls - An array of Call objects, each containing 'to', optional 'data', and optional 'value'.\n * @returns A promise that resolves to the encoded function data as a hexadecimal string.\n * @description\n * - If there's a single call directly to the delegator, it returns the call data directly.\n * - For multiple calls or calls to other addresses, it creates executions and encodes them for the DeleGator's execute function.\n * - The execution mode is set to ExecutionMode.SingleDefault for a single call, or ExecutionMode.BatchDefault for multiple calls.\n *\n * todo: This doesn't fully expose the flexibility of the DeleGator's execute function, but it's a start.\n * maybe we add a mechanism where individual calls passed to this function can be encoded batches.\n */\nexport const encodeCallsForCaller = async (\n caller: Address,\n calls: readonly Call[],\n): Promise<Hex> => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call?.to === caller && !isDelegatedCall(call)) {\n // if there's a single call, and it's to the delegator, we can just return the calldata directly.\n return call.data ?? '0x';\n }\n }\n return encodeCalls(calls);\n};\n","import { Signature } from 'ox';\nimport {\n parseAbiParameters,\n encodeAbiParameters,\n type Hex,\n encodePacked,\n keccak256,\n concat,\n hexToBytes,\n} from 'viem';\n\nexport const FIELD_MODULUS =\n 115792089210356248762697446949407573529996955224135760342422259061068512044369n;\nexport const MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;\n\nexport const SIGNATURE_ABI_PARAMS = parseAbiParameters(\n 'bytes32, uint256, uint256, bytes, bool, string, string, uint256',\n);\n\n/**\n * This function is used to convert the client data returned from the\n * credentials API into a format that can be consumed by the DeleGator\n * contracts. We need the flattend JSON strings before and after the\n * userOpHash/challenge. This function provides those two client data string\n * slices.\n *\n * @param clientDataJson - The client data JSON string.\n * @returns Returns [clientDataJSONPrefix and clientDataJSONSuffix]\n * ClientDataJSONPrefix contains the client data till the challengeHash\n * ClientDataJSONSuffix contains the client data after the challengeHash.\n */\nexport const splitOnChallenge = (\n clientDataJson: string,\n): [clientDataJSONPrefix: string, clientDataJSONSuffix: string] => {\n /*\n CientData looks like this:\n {\n \"type\": \"webauthn.create\" | \"webauthn.get\",\n \"challenge\": \"{userOpHash}\",\n \"origin\": \"{Domain}\",\n \"crossOrigin\": boolean\n }\n */\n try {\n const { challenge } = JSON.parse(clientDataJson);\n if (challenge === undefined) {\n throw new Error('No \"challenge\" found in the input string');\n }\n return clientDataJson.split(challenge) as [string, string];\n } catch (error) {\n throw new Error('No \"challenge\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Returns the index of '\"type\":' in the ClientData.\n *\n * @param clientDataJson - Stringified ClientDataJSON.\n * @returns The index of '\"type\":' in the ClientData.\n */\nexport const getResponseTypeLocation = (clientDataJson: string): bigint => {\n try {\n // Find the index of the `\"type\":` key in the JSON string directly\n const typeIndex = clientDataJson.indexOf('\"type\":');\n\n if (typeIndex === -1) {\n throw new Error('No \"type\" found in the input string');\n }\n // Return the index of the `\"type\":` key\n return BigInt(typeIndex);\n } catch (error) {\n // Handle any errors that occur during the search\n throw new Error('No \"type\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Encodes a signature to a hexadecimal signature that will be accepted\n * by the DeleGator contracts.\n *\n * @param keyId - The key used for the signature, represented as a hexadecimal string.\n * @param signature - The signature to convert, as Hex.\n * @param clientDataJSON - The client data used in the creation of the signature.\n * @param authenticatorData - The authenticator data used in the creation of the signature.\n * @returns The signature as a valid DeleGator signature encoded as Hexadecimal string.\n */\nexport function encodeDeleGatorSignature(\n keyId: string,\n signature: Hex,\n clientDataJSON: string,\n authenticatorData: Hex,\n): Hex {\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n\n const { r: rValue, s: sValue } = Signature.fromHex(signature);\n\n let normalizedS = sValue;\n\n while (normalizedS > MALLEABILITY_THRESHOLD) {\n normalizedS = FIELD_MODULUS - normalizedS;\n }\n\n const [clientDataComponent1, clientDataComponent2] =\n splitOnChallenge(clientDataJSON);\n\n const { userVerified } = parseAuthenticatorFlags(authenticatorData);\n\n const responseTypeLocation = getResponseTypeLocation(clientDataJSON);\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rValue,\n normalizedS,\n authenticatorData,\n userVerified,\n clientDataComponent1,\n clientDataComponent2,\n responseTypeLocation,\n ]);\n return encodedSignature;\n}\n\nconst AUTHENTICATOR_DATA_FLAGS_OFFSET = 32;\n// We have all of the flag bits defined here for completeness, even though we only extract the userVerified flag.\nenum AuthenticatorDataFlagBitIndex {\n UserPresence = 0,\n UserVerified = 2,\n BackupEligibility = 3,\n BackupState = 4,\n AttestedCredentialData = 6,\n ExtensionData = 7,\n}\n\nexport type AuthenticatorFlags = {\n userVerified: boolean;\n};\n\n/**\n * Parses the authenticator data and returns an authenticator flags object with the `userVerified` flag.\n * See https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data.\n *\n * @param authenticatorData - The authenticator data to parse.\n * @returns An object representing the parsed authenticator flags.\n */\nexport function parseAuthenticatorFlags(\n authenticatorData: Hex,\n): AuthenticatorFlags {\n const authenticatorDataBuffer = hexToBytes(authenticatorData);\n const dataBufferUint8 = new Uint8Array(authenticatorDataBuffer);\n const flags = dataBufferUint8[AUTHENTICATOR_DATA_FLAGS_OFFSET];\n if (flags === undefined) {\n throw new Error('Authenticator flags not found in authenticator data');\n }\n\n // Bit 0 is the least significant bit in the flags byte, so we left shift 0b1 by the bit index\n // eslint-disable-next-line no-bitwise\n const bitMask = 0b1 << AuthenticatorDataFlagBitIndex.UserVerified;\n\n return {\n // eslint-disable-next-line no-bitwise\n userVerified: (flags & bitMask) !== 0x0,\n };\n}\n\n/**\n * Creates a dummy signature.\n * This must meet all early-failure conditions of the real signature, but does not need to be a valid signature.\n *\n * @param keyId - The key ID to use for the dummy signature.\n * @returns The encoded signature.\n */\nexport const createDummyWebAuthnSignature = (keyId: Hex) => {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#data_structure\n const rpIdHash = keccak256(encodePacked(['string'], ['AuthenticatorData']));\n const flags = '0x05';\n const signCount = '0x00000000';\n const authenticatorData = concat([rpIdHash, flags, signCount]);\n\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n const rs =\n 57896044605178124381348723474703786764998477612067880171211129530534256022184n;\n const userVerification = true;\n const clientDataPrefix = '{\"type\":\"webauthn.get\",\"challenge\":\"';\n const clientDataSuffix = '\",\"origin\":\"passkey-domain\",\"crossOrigin\":false}';\n const responseTypeLocation = 1n;\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rs,\n rs,\n authenticatorData,\n userVerification,\n clientDataPrefix,\n clientDataSuffix,\n responseTypeLocation,\n ]);\n\n return encodedSignature;\n};\n"]}
@@ -1,8 +1,8 @@
1
- export { b as DeleGatorCore, a as DelegationManager, c as EIP712, o as ERC20PeriodTransferEnforcer, p as ERC20StreamingEnforcer, q as ERC20TransferAmountEnforcer, d as EntryPoint, e as HybridDeleGator, f as IdEnforcer, I as InitializedClient, g as LimitedCallsEnforcer, h as MultiSigDeleGator, r as MultiTokenPeriodEnforcer, s as NativeTokenPeriodTransferEnforcer, t as NativeTokenStreamingEnforcer, u as NativeTokenTransferAmountEnforcer, j as NonceEnforcer, k as Ownable2Step, P as P256Owner, l as Pausable, m as SimpleFactory, n as SpecificActionERC20TransferBatchEnforcer, x as encodeProxyCreationCode, v as isContractDeployed, w as isImplementationExpected } from '../index-DvcKJcXi.cjs';
1
+ export { b as DeleGatorCore, a as DelegationManager, c as EIP712, o as ERC20PeriodTransferEnforcer, p as ERC20StreamingEnforcer, q as ERC20TransferAmountEnforcer, d as EntryPoint, e as HybridDeleGator, f as IdEnforcer, I as InitializedClient, g as LimitedCallsEnforcer, h as MultiSigDeleGator, r as MultiTokenPeriodEnforcer, s as NativeTokenPeriodTransferEnforcer, t as NativeTokenStreamingEnforcer, u as NativeTokenTransferAmountEnforcer, j as NonceEnforcer, k as Ownable2Step, P as P256Owner, l as Pausable, m as SimpleFactory, n as SpecificActionERC20TransferBatchEnforcer, x as encodeProxyCreationCode, v as isContractDeployed, w as isImplementationExpected } from '../index-DC9baw8F.cjs';
2
2
  import '@metamask/delegation-core';
3
3
  import 'viem';
4
- import '../delegation-D_TY-tAq.cjs';
5
- import '../types-BLYWtcR3.cjs';
4
+ import '../delegation-DIriDFkq.cjs';
5
+ import '../types-qdEHxd5Q.cjs';
6
6
  import '@metamask/delegation-abis';
7
7
  import 'viem/account-abstraction';
8
8
  import 'viem/chains';
@@ -1,8 +1,8 @@
1
- export { b as DeleGatorCore, a as DelegationManager, c as EIP712, o as ERC20PeriodTransferEnforcer, p as ERC20StreamingEnforcer, q as ERC20TransferAmountEnforcer, d as EntryPoint, e as HybridDeleGator, f as IdEnforcer, I as InitializedClient, g as LimitedCallsEnforcer, h as MultiSigDeleGator, r as MultiTokenPeriodEnforcer, s as NativeTokenPeriodTransferEnforcer, t as NativeTokenStreamingEnforcer, u as NativeTokenTransferAmountEnforcer, j as NonceEnforcer, k as Ownable2Step, P as P256Owner, l as Pausable, m as SimpleFactory, n as SpecificActionERC20TransferBatchEnforcer, x as encodeProxyCreationCode, v as isContractDeployed, w as isImplementationExpected } from '../index-B9bsjGqI.js';
1
+ export { b as DeleGatorCore, a as DelegationManager, c as EIP712, o as ERC20PeriodTransferEnforcer, p as ERC20StreamingEnforcer, q as ERC20TransferAmountEnforcer, d as EntryPoint, e as HybridDeleGator, f as IdEnforcer, I as InitializedClient, g as LimitedCallsEnforcer, h as MultiSigDeleGator, r as MultiTokenPeriodEnforcer, s as NativeTokenPeriodTransferEnforcer, t as NativeTokenStreamingEnforcer, u as NativeTokenTransferAmountEnforcer, j as NonceEnforcer, k as Ownable2Step, P as P256Owner, l as Pausable, m as SimpleFactory, n as SpecificActionERC20TransferBatchEnforcer, x as encodeProxyCreationCode, v as isContractDeployed, w as isImplementationExpected } from '../index-ChTryO1-.js';
2
2
  import '@metamask/delegation-core';
3
3
  import 'viem';
4
- import '../delegation-DGUfyX-C.js';
5
- import '../types-BLYWtcR3.js';
4
+ import '../delegation-CvVXs0PO.js';
5
+ import '../types-qdEHxd5Q.js';
6
6
  import '@metamask/delegation-abis';
7
7
  import 'viem/account-abstraction';
8
8
  import 'viem/chains';
@@ -1,5 +1,5 @@
1
1
  import { Hex, AbiFunction, Address, AbiParameter, TypedData } from 'viem';
2
- import { S as SmartAccountsEnvironment, C as Caveat, k as CaveatType, j as ScopeType, D as Delegation, P as PermissionContext } from './types-BLYWtcR3.js';
2
+ import { S as SmartAccountsEnvironment, C as Caveat, k as CaveatType, j as ScopeType, D as Delegation, P as PermissionContext } from './types-qdEHxd5Q.js';
3
3
 
4
4
  type AllowedCalldataBuilderConfig = {
5
5
  startIndex: number;
@@ -1,5 +1,5 @@
1
1
  import { Hex, AbiFunction, Address, AbiParameter, TypedData } from 'viem';
2
- import { S as SmartAccountsEnvironment, C as Caveat, k as CaveatType, j as ScopeType, D as Delegation, P as PermissionContext } from './types-BLYWtcR3.cjs';
2
+ import { S as SmartAccountsEnvironment, C as Caveat, k as CaveatType, j as ScopeType, D as Delegation, P as PermissionContext } from './types-qdEHxd5Q.cjs';
3
3
 
4
4
  type AllowedCalldataBuilderConfig = {
5
5
  startIndex: number;
@@ -1,5 +1,5 @@
1
1
  import { Hex } from 'viem';
2
- import { D as Delegation } from '../types-BLYWtcR3.cjs';
2
+ import { D as Delegation } from '../types-qdEHxd5Q.cjs';
3
3
  import '@metamask/delegation-abis';
4
4
  import 'viem/account-abstraction';
5
5
  import 'viem/chains';
@@ -1,5 +1,5 @@
1
1
  import { Hex } from 'viem';
2
- import { D as Delegation } from '../types-BLYWtcR3.js';
2
+ import { D as Delegation } from '../types-qdEHxd5Q.js';
3
3
  import '@metamask/delegation-abis';
4
4
  import 'viem/account-abstraction';
5
5
  import 'viem/chains';
@@ -1,7 +1,7 @@
1
1
  import { PermissionRequest as PermissionRequest$1, PermissionTypes as PermissionTypes$1, PermissionResponse as PermissionResponse$1 } from '@metamask/7715-permission-types';
2
2
  import { Address, Hex, Client, Transport, Chain, Account, RpcSchema, SendTransactionRequest, SendTransactionParameters, OneOf, PublicClient, WalletClient } from 'viem';
3
3
  import { SmartAccount, SendUserOperationParameters } from 'viem/account-abstraction';
4
- import { P as PermissionContext, l as Call, S as SmartAccountsEnvironment, D as Delegation } from './types-BLYWtcR3.js';
4
+ import { P as PermissionContext, l as Call, S as SmartAccountsEnvironment, D as Delegation } from './types-qdEHxd5Q.js';
5
5
  import { U as UserOperationV07 } from './userOp-DKgjzz7B.js';
6
6
 
7
7
  type BasePermission = {
@@ -1,8 +1,8 @@
1
1
  import { ANY_BENEFICIARY, ROOT_AUTHORITY } from '@metamask/delegation-core';
2
2
  import * as viem from 'viem';
3
3
  import { Client, Transport, Chain, Account, Address, Hex } from 'viem';
4
- import { p as DelegationStruct, E as ExecutionMode, e as ExecutionStruct } from './delegation-DGUfyX-C.js';
5
- import { D as Delegation, P as PermissionContext } from './types-BLYWtcR3.js';
4
+ import { p as DelegationStruct, E as ExecutionMode, e as ExecutionStruct } from './delegation-CvVXs0PO.js';
5
+ import { D as Delegation, P as PermissionContext } from './types-qdEHxd5Q.js';
6
6
 
7
7
  declare const NAME$1 = "DelegationManager";
8
8
  declare const VERSION$1 = "1.3.0";
@@ -1,8 +1,8 @@
1
1
  import { ANY_BENEFICIARY, ROOT_AUTHORITY } from '@metamask/delegation-core';
2
2
  import * as viem from 'viem';
3
3
  import { Client, Transport, Chain, Account, Address, Hex } from 'viem';
4
- import { p as DelegationStruct, E as ExecutionMode, e as ExecutionStruct } from './delegation-D_TY-tAq.cjs';
5
- import { D as Delegation, P as PermissionContext } from './types-BLYWtcR3.cjs';
4
+ import { p as DelegationStruct, E as ExecutionMode, e as ExecutionStruct } from './delegation-DIriDFkq.cjs';
5
+ import { D as Delegation, P as PermissionContext } from './types-qdEHxd5Q.cjs';
6
6
 
7
7
  declare const NAME$1 = "DelegationManager";
8
8
  declare const VERSION$1 = "1.3.0";
@@ -1,7 +1,7 @@
1
1
  import { PermissionRequest as PermissionRequest$1, PermissionTypes as PermissionTypes$1, PermissionResponse as PermissionResponse$1 } from '@metamask/7715-permission-types';
2
2
  import { Address, Hex, Client, Transport, Chain, Account, RpcSchema, SendTransactionRequest, SendTransactionParameters, OneOf, PublicClient, WalletClient } from 'viem';
3
3
  import { SmartAccount, SendUserOperationParameters } from 'viem/account-abstraction';
4
- import { P as PermissionContext, l as Call, S as SmartAccountsEnvironment, D as Delegation } from './types-BLYWtcR3.cjs';
4
+ import { P as PermissionContext, l as Call, S as SmartAccountsEnvironment, D as Delegation } from './types-qdEHxd5Q.cjs';
5
5
  import { U as UserOperationV07 } from './userOp-DKgjzz7B.cjs';
6
6
 
7
7
  type BasePermission = {
package/dist/index.cjs CHANGED
@@ -13,7 +13,7 @@ require('./chunk-UUOH2WAW.cjs');
13
13
 
14
14
 
15
15
 
16
- var _chunkDLD377CNcjs = require('./chunk-DLD377CN.cjs');
16
+ var _chunkBYWRJGSKcjs = require('./chunk-BYWRJGSK.cjs');
17
17
 
18
18
 
19
19
 
@@ -115,15 +115,15 @@ var resolveHybridSigner = (config) => {
115
115
  if (webAuthnAccount.type !== "webAuthn") {
116
116
  throw new Error("Account is not a webAuthn account");
117
117
  }
118
- const encodeSignature = ({ signature, webauthn }) => _chunkDLD377CNcjs.encodeDeleGatorSignature.call(void 0,
118
+ const encodeSignature = (result) => _chunkBYWRJGSKcjs.encodeDeleGatorSignature.call(void 0,
119
119
  keyId,
120
- signature,
121
- webauthn.clientDataJSON,
122
- webauthn.authenticatorData
120
+ result.signature,
121
+ result.webauthn.clientDataJSON,
122
+ result.webauthn.authenticatorData
123
123
  );
124
124
  const signMessage = async (args) => webAuthnAccount.signMessage(args).then(encodeSignature);
125
125
  const signTypedData = async (typedDataDefinition) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);
126
- const getStubSignature = async () => _chunkDLD377CNcjs.createDummyWebAuthnSignature.call(void 0, keyId);
126
+ const getStubSignature = async () => _chunkBYWRJGSKcjs.createDummyWebAuthnSignature.call(void 0, keyId);
127
127
  return {
128
128
  signMessage,
129
129
  signTypedData,
@@ -210,19 +210,20 @@ var resolveStateless7702Signer = (config) => {
210
210
  }
211
211
  throw new Error("Invalid signer config");
212
212
  };
213
- var resolveSigner = (config) => {
214
- const { implementation } = config;
213
+ function resolveSigner(config) {
214
+ const { implementation, signer } = config;
215
+ if (!signer) {
216
+ return null;
217
+ }
215
218
  if (implementation === "Hybrid" /* Hybrid */) {
216
- return resolveHybridSigner(config.signer);
219
+ return resolveHybridSigner(signer);
217
220
  } else if (implementation === "MultiSig" /* MultiSig */) {
218
- return resolveMultiSigSigner(config.signer);
221
+ return resolveMultiSigSigner(signer);
219
222
  } else if (implementation === "Stateless7702" /* Stateless7702 */) {
220
- return resolveStateless7702Signer(
221
- config.signer
222
- );
223
+ return resolveStateless7702Signer(signer);
223
224
  }
224
225
  throw new Error(`Implementation type '${implementation}' not supported`);
225
- };
226
+ }
226
227
 
227
228
  // src/toMetaMaskSmartAccount.ts
228
229
  var ENTRYPOINT_VERSION = "0.7";
@@ -248,7 +249,7 @@ async function toMetaMaskSmartAccount(params) {
248
249
  if (implementation === "Stateless7702" /* Stateless7702 */) {
249
250
  throw new Error("Stateless7702 does not support counterfactual accounts");
250
251
  }
251
- const accountData = await _chunkDLD377CNcjs.getCounterfactualAccountData.call(void 0, {
252
+ const accountData = await _chunkBYWRJGSKcjs.getCounterfactualAccountData.call(void 0, {
252
253
  factory: environment.SimpleFactory,
253
254
  implementations: environment.implementations,
254
255
  implementation,
@@ -289,6 +290,11 @@ async function toMetaMaskSmartAccount(params) {
289
290
  };
290
291
  };
291
292
  const signDelegation2 = async (delegationParams) => {
293
+ if (!signer) {
294
+ throw new Error(
295
+ "Cannot sign delegation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
296
+ );
297
+ }
292
298
  const { delegation, chainId } = delegationParams;
293
299
  const delegationStruct = _chunkYDLLC6PPcjs.toDelegationStruct.call(void 0, {
294
300
  ...delegation,
@@ -308,6 +314,11 @@ async function toMetaMaskSmartAccount(params) {
308
314
  return signature;
309
315
  };
310
316
  const signUserOperation2 = async (userOpParams) => {
317
+ if (!signer) {
318
+ throw new Error(
319
+ "Cannot sign user operation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
320
+ );
321
+ }
311
322
  const { chainId } = userOpParams;
312
323
  const packedUserOp = _accountabstraction.toPackedUserOperation.call(void 0, {
313
324
  sender: address,
@@ -334,7 +345,24 @@ async function toMetaMaskSmartAccount(params) {
334
345
  contractAddress: address,
335
346
  key: 0n
336
347
  });
337
- const encodeCalls = async (calls) => _chunkDLD377CNcjs.encodeCallsForCaller.call(void 0, address, calls);
348
+ const encodeCalls = async (calls) => _chunkBYWRJGSKcjs.encodeCallsForCaller.call(void 0, address, calls);
349
+ const signerMethods = _nullishCoalesce(signer, () => ( {
350
+ signMessage: async () => {
351
+ throw new Error(
352
+ "Cannot sign message: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
353
+ );
354
+ },
355
+ signTypedData: async () => {
356
+ throw new Error(
357
+ "Cannot sign typed data: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
358
+ );
359
+ },
360
+ getStubSignature: async () => {
361
+ throw new Error(
362
+ "Cannot get stub signature: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
363
+ );
364
+ }
365
+ }));
338
366
  const smartAccount = await _accountabstraction.toSmartAccount.call(void 0, {
339
367
  abi,
340
368
  client,
@@ -346,7 +374,7 @@ async function toMetaMaskSmartAccount(params) {
346
374
  getNonce,
347
375
  signUserOperation: signUserOperation2,
348
376
  signDelegation: signDelegation2,
349
- ...signer
377
+ ...signerMethods
350
378
  });
351
379
  if (implementation === "Stateless7702" /* Stateless7702 */) {
352
380
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/index.cjs","../src/toMetaMaskSmartAccount.ts","../src/signer.ts","../src/signatures.ts","../src/actions/caveatEnforcerClient.ts","../src/actions/infuraBundlerClient.ts"],"names":["signTypedData","signMessage","getStubSignature","signUserOperation","signDelegation"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC3CA;AACE;AACA;AACA;AAAA,2DACK;AAEP;AACE;AACA;AACA;AAAA,8DACK;AD4CP;AACA;AEvDA,4BAAuB;AFyDvB;AACA;AGzDA;AAEA,IAAM,eAAA,EAAiB,CAAC,OAAO,CAAA;AAoBxB,IAAM,mBAAA,EAAqB,CAAC;AAAA,EACjC;AACF,CAAA,EAAA,GAEW;AACT,EAAA,GAAA,CAAI,UAAA,CAAW,OAAA,IAAW,CAAA,EAAG;AAC3B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,IAAA,CAAA,MAAW,EAAE,KAAK,EAAA,GAAK,UAAA,EAAY;AACjC,IAAA,GAAA,CAAI,CAAC,cAAA,CAAe,QAAA,CAAS,IAAI,CAAA,EAAG;AAClC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,wBAAA,EAA2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A;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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/index.cjs","sourcesContent":[null,"import {\n EIP7702StatelessDeleGator,\n HybridDeleGator,\n MultiSigDeleGator,\n} from '@metamask/delegation-abis';\nimport { type Address, type Hex } from 'viem';\nimport {\n entryPoint07Abi,\n toPackedUserOperation,\n toSmartAccount,\n} from 'viem/account-abstraction';\n\nimport { isValid7702Implementation } from './actions/isValid7702Implementation';\nimport { Implementation } from './constants';\nimport { getCounterfactualAccountData } from './counterfactualAccountData';\nimport {\n SIGNABLE_DELEGATION_TYPED_DATA,\n toDelegationStruct,\n} from './delegation';\nimport { entryPointGetNonce as _getNonce } from './DelegationFramework/EntryPoint/read';\nimport { encodeCallsForCaller } from './encodeCalls';\nimport { resolveSigner } from './signer';\nimport { getSmartAccountsEnvironment } from './smartAccountsEnvironment';\nimport type {\n Call,\n ToMetaMaskSmartAccountParameters,\n ToMetaMaskSmartAccountReturnType,\n SignDelegationParams,\n SignUserOperationParams,\n AbiByImplementation,\n} from './types';\nimport { SIGNABLE_USER_OP_TYPED_DATA } from './userOp';\n\nconst ENTRYPOINT_VERSION = '0.7' as const;\n\n/**\n * Creates a MetaMask DeleGator smart account instance.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @param params - The parameters for creating the smart account.\n * @returns A promise that resolves to a MetaMaskSmartAccount instance.\n * @description\n * This function sets up a MetaMask DeleGator smart account with the specified implementation.\n * It handles both deployed accounts, and counterfactual accounts.\n * A caller may specify a SmartAccountsEnvironment, otherwise the environment will be inferred from the chain.\n */\nexport async function toMetaMaskSmartAccount<\n TImplementation extends Implementation,\n>(\n params: ToMetaMaskSmartAccountParameters<TImplementation>,\n): Promise<ToMetaMaskSmartAccountReturnType<TImplementation>> {\n const {\n client,\n client: { chain },\n implementation,\n } = params;\n\n if (!chain) {\n throw new Error('Chain not specified');\n }\n\n const signer = resolveSigner({\n implementation,\n signer: params.signer,\n });\n\n const environment =\n params.environment ?? getSmartAccountsEnvironment(chain.id);\n\n let address: Address, factoryData: Hex | undefined;\n\n if (params.address) {\n factoryData = undefined;\n address = params.address;\n } else {\n if (implementation === Implementation.Stateless7702) {\n throw new Error('Stateless7702 does not support counterfactual accounts');\n }\n\n const accountData = await getCounterfactualAccountData({\n factory: environment.SimpleFactory,\n implementations: environment.implementations,\n implementation,\n deployParams: params.deployParams,\n deploySalt: params.deploySalt,\n });\n\n address = accountData.address;\n factoryData = accountData.factoryData;\n }\n\n const entryPoint = {\n abi: entryPoint07Abi,\n address: environment.EntryPoint,\n version: ENTRYPOINT_VERSION,\n } as const;\n\n const { abi, contractName } = {\n [Implementation.Hybrid]: {\n contractName: 'HybridDeleGator',\n abi: HybridDeleGator,\n },\n [Implementation.MultiSig]: {\n contractName: 'MultiSigDeleGator',\n abi: MultiSigDeleGator,\n },\n [Implementation.Stateless7702]: {\n contractName: 'EIP7702StatelessDeleGator',\n abi: EIP7702StatelessDeleGator,\n },\n }[implementation] as {\n contractName: string;\n abi: AbiByImplementation[TImplementation];\n };\n\n const getFactoryArgs = async () => {\n if (factoryData === undefined) {\n throw new Error(\n 'Deploy params were not provided, so factory args cannot be inferred',\n );\n }\n return {\n factoryData,\n factory: environment.SimpleFactory,\n };\n };\n\n const signDelegation = async (delegationParams: SignDelegationParams) => {\n const { delegation, chainId } = delegationParams;\n\n const delegationStruct = toDelegationStruct({\n ...delegation,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: 'DelegationManager',\n version: '1',\n verifyingContract: environment.DelegationManager,\n },\n types: SIGNABLE_DELEGATION_TYPED_DATA,\n primaryType: 'Delegation',\n message: delegationStruct,\n });\n\n return signature;\n };\n\n const signUserOperation = async (userOpParams: SignUserOperationParams) => {\n const { chainId } = userOpParams;\n\n const packedUserOp = toPackedUserOperation({\n sender: address,\n ...userOpParams,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: contractName,\n version: '1',\n verifyingContract: address,\n },\n types: SIGNABLE_USER_OP_TYPED_DATA,\n primaryType: 'PackedUserOperation',\n message: { ...packedUserOp, entryPoint: entryPoint.address },\n });\n\n return signature;\n };\n\n const getAddress = async () => address;\n\n const getNonce = async () =>\n _getNonce({\n client,\n entryPoint: environment.EntryPoint,\n contractAddress: address,\n key: 0n,\n });\n\n const encodeCalls = async (calls: readonly Call[]) =>\n encodeCallsForCaller(address, calls);\n\n const smartAccount = await toSmartAccount({\n abi,\n client,\n entryPoint,\n environment,\n getAddress,\n getFactoryArgs,\n encodeCalls,\n getNonce,\n signUserOperation,\n signDelegation,\n ...signer,\n });\n\n // Override isDeployed only for EIP-7702 implementation to check proper delegation code\n if (implementation === Implementation.Stateless7702) {\n return {\n ...smartAccount,\n isDeployed: async () =>\n isValid7702Implementation({\n client,\n accountAddress: address,\n environment,\n }),\n };\n }\n\n // For other implementations, use the default isDeployed behavior\n return smartAccount;\n}\n","import { concat } from 'viem';\nimport type {\n Address,\n SignableMessage,\n TypedData,\n TypedDataDefinition,\n} from 'viem';\nimport type { SignReturnType as WebAuthnSignReturnType } from 'webauthn-p256';\n\nimport { Implementation } from './constants';\nimport { aggregateSignature } from './signatures';\nimport type {\n AccountSignerConfig,\n HybridSignerConfig,\n InternalSigner,\n MultiSigSignerConfig,\n SignerConfigByImplementation,\n Stateless7702SignerConfig,\n WalletSignerConfig,\n} from './types';\nimport {\n createDummyWebAuthnSignature,\n encodeDeleGatorSignature,\n} from './webAuthn';\n\n// A valid ECDSA signature, this must be able to ecrecover an address, otherwise the contracts will revert in isValidSignature\nconst EOA_STUB_SIGNATURE =\n '0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000011b' as const;\n\nconst resolveSignerFromWalletConfig = (\n config: WalletSignerConfig,\n): InternalSigner => {\n return {\n signMessage: config.walletClient.signMessage,\n signTypedData: async (typedData) => {\n // todo: figure out this type so that we don't need the type assertion\n return config.walletClient.signTypedData(typedData as any);\n },\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveSignerFromAccountConfig = (config: AccountSignerConfig) => {\n return {\n signMessage: config.account.signMessage,\n signTypedData: config.account.signTypedData,\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveHybridSigner = (config: HybridSignerConfig): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n const { keyId, webAuthnAccount } = config;\n\n if (webAuthnAccount.type !== 'webAuthn') {\n throw new Error('Account is not a webAuthn account');\n }\n\n const encodeSignature = ({ signature, webauthn }: WebAuthnSignReturnType) =>\n encodeDeleGatorSignature(\n keyId,\n signature,\n webauthn.clientDataJSON,\n webauthn.authenticatorData,\n );\n\n const signMessage = async (args: { message: SignableMessage }) =>\n webAuthnAccount.signMessage(args).then(encodeSignature);\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);\n\n const getStubSignature = async () => createDummyWebAuthnSignature(keyId);\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveMultiSigSigner = (\n config: MultiSigSignerConfig,\n): InternalSigner => {\n const resolvedSigners = config.map((signer) => {\n let individualSignMessage: InternalSigner['signMessage'];\n let individualSignTypedData: InternalSigner['signTypedData'];\n let address: Address;\n if ('walletClient' in signer) {\n const { signMessage, signTypedData } =\n resolveSignerFromWalletConfig(signer);\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.walletClient.account.address;\n } else {\n const { signMessage, signTypedData } =\n resolveSignerFromAccountConfig(signer);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.account.address;\n }\n return {\n address,\n individualSignMessage,\n individualSignTypedData,\n };\n });\n\n const signMessage = async (args: { message: SignableMessage }) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignMessage, address }) => ({\n signature: await individualSignMessage(args),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignTypedData, address }) => ({\n signature: await individualSignTypedData(typedDataDefinition),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const getStubSignature = async () =>\n concat(resolvedSigners.map(() => EOA_STUB_SIGNATURE));\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveStateless7702Signer = (\n config: Stateless7702SignerConfig,\n): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n\n throw new Error('Invalid signer config');\n};\n\nexport const resolveSigner = <TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner => {\n const { implementation } = config;\n\n if (implementation === Implementation.Hybrid) {\n return resolveHybridSigner(config.signer as HybridSignerConfig);\n } else if (implementation === Implementation.MultiSig) {\n return resolveMultiSigSigner(config.signer as MultiSigSignerConfig);\n } else if (implementation === Implementation.Stateless7702) {\n return resolveStateless7702Signer(\n config.signer as Stateless7702SignerConfig,\n );\n }\n throw new Error(`Implementation type '${implementation}' not supported`);\n};\n","import type { Address, Hex } from 'viem';\nimport { concat } from 'viem';\n\nconst signatureTypes = ['ECDSA'] as const;\n\nexport type SignatureType = (typeof signatureTypes)[number];\n\n/**\n * Represents a partial signature that can be aggregated with others.\n */\nexport type PartialSignature = {\n signer: Address;\n signature: Hex;\n type: SignatureType;\n};\n\n/**\n * Aggregates signatures into a single signature as expected by the MultiSig implementation.\n *\n * @param params - The parameters for signature aggregation.\n * @param params.signatures - The array of partial signatures to aggregate.\n * @returns The aggregated signature.\n */\nexport const aggregateSignature = ({\n signatures,\n}: {\n signatures: PartialSignature[];\n}): Hex => {\n if (signatures.length === 0) {\n return '0x';\n }\n\n for (const { type } of signatures) {\n if (!signatureTypes.includes(type)) {\n throw new Error(`Invalid signature type: ${type}`);\n }\n }\n\n // Sort signatures by signer address as required by MultiSig implementation\n const sortedSignatures = [...signatures].sort((a, b) =>\n a.signer.localeCompare(b.signer),\n );\n\n // Concatenate all signatures\n return concat(sortedSignatures.map(({ signature }) => signature));\n};\n\n/**\n * Type definition for the aggregateSignature function parameters.\n */\nexport type AggregateSignatureParams = {\n signatures: PartialSignature[];\n};\n","import type { Client, Transport, Chain, Account } from 'viem';\n\nimport type { SmartAccountsEnvironment } from '../types';\nimport {\n caveatEnforcerActions,\n type CaveatEnforcerParams,\n type PeriodTransferResult,\n type StreamingResult,\n} from './getCaveatAvailableAmount';\n\n/**\n * Type for client extended with caveat enforcer actions.\n */\nexport type CaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n> = Client<TTransport, TChain, TAccount> &\n ReturnType<ReturnType<typeof caveatEnforcerActions>>;\n\n/**\n * Create a viem client extended with caveat enforcer actions.\n *\n * @param params - The parameters object.\n * @param params.client - The viem client.\n * @param params.environment - The SmartAccountsEnvironment.\n * @returns The extended client with caveat enforcer actions.\n */\nexport function createCaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n>({\n client,\n environment,\n}: {\n client: Client<TTransport, TChain, TAccount>;\n environment: SmartAccountsEnvironment;\n}): CaveatEnforcerClient<TTransport, TChain, TAccount> {\n return client.extend(caveatEnforcerActions({ environment }));\n}\n\n// Re-export types for convenience\nexport type { CaveatEnforcerParams, PeriodTransferResult, StreamingResult };\n","import type { Transport, Chain, Hex, Client, Account } from 'viem';\nimport {\n createBundlerClient,\n type BundlerClient,\n type BundlerClientConfig,\n type SmartAccount,\n} from 'viem/account-abstraction';\n\n/**\n * Gas price tiers returned by pimlico_getUserOperationGasPrice\n */\nexport type GasPriceTier = {\n /** Maximum fee per gas in hex format */\n maxFeePerGas: Hex;\n /** Maximum priority fee per gas in hex format */\n maxPriorityFeePerGas: Hex;\n};\n\n/**\n * Response from pimlico_getUserOperationGasPrice RPC method\n */\nexport type UserOperationGasPriceResponse = {\n /** Slow gas price tier */\n slow: GasPriceTier;\n /** Standard gas price tier */\n standard: GasPriceTier;\n /** Fast gas price tier */\n fast: GasPriceTier;\n};\n\n/**\n * Pimlico bundler schema for type-safe RPC method calls\n */\n/* eslint-disable @typescript-eslint/naming-convention */\ntype PimlicoBundlerSchema = [\n {\n Method: 'pimlico_getUserOperationGasPrice';\n Parameters: [];\n ReturnType: UserOperationGasPriceResponse;\n },\n];\n\n/**\n * Infura bundler actions for extending bundler clients.\n *\n * @returns A function that takes a client and returns the client extension with Infura bundler actions.\n */\nconst infuraBundlerActions = () => (client: Client) => ({\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n * @example\n * ```typescript\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * console.log(gasPrices.standard.maxFeePerGas);\n * ```\n */\n async getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse> {\n const pimlicoClient = client as Client<\n Transport,\n Chain | undefined,\n Account | undefined,\n PimlicoBundlerSchema\n >;\n\n return await pimlicoClient.request({\n method: 'pimlico_getUserOperationGasPrice',\n params: [],\n });\n },\n});\n\n/**\n * Type for bundler client extended with Infura bundler actions.\n */\nexport type InfuraBundlerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends SmartAccount | undefined = SmartAccount | undefined,\n> = BundlerClient<TTransport, TChain, TAccount> & {\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n */\n getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse>;\n};\n\n/**\n * Creates an Infura bundler client extended with Infura bundler actions.\n *\n * This is a wrapper around viem's createBundlerClient that extends it with\n * the getUserOperationGasPrice method for retrieving gas prices from Pimlico's\n * bundler infrastructure via Infura's proxy.\n *\n * @param config - Configuration for the bundler client.\n * @returns Extended bundler client with Infura bundler actions.\n * @example\n * ```typescript\n * import { createPublicClient, http } from 'viem';\n * import { sepolia } from 'viem/chains';\n * import { createInfuraBundlerClient } from '@metamask/smart-accounts-kit';\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * });\n *\n * const bundlerClient = createInfuraBundlerClient({\n * client: publicClient,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * chain: sepolia,\n * });\n *\n * // Use standard bundler methods\n * const userOpHash = await bundlerClient.sendUserOperation({...});\n *\n * // Use Infura specific methods\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * ```\n */\nexport function createInfuraBundlerClient<\n TTransport extends Transport,\n TChain extends Chain | undefined = undefined,\n TAccount extends SmartAccount | undefined = undefined,\n>(\n config: BundlerClientConfig<TTransport, TChain, TAccount>,\n): InfuraBundlerClient<TTransport, TChain, TAccount> {\n // Create the base bundler client using viem's function\n const baseBundlerClient = createBundlerClient(config);\n\n // Extend the client with Infura bundler actions\n return baseBundlerClient.extend(\n infuraBundlerActions(),\n ) as unknown as InfuraBundlerClient<TTransport, TChain, TAccount>;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/index.cjs","../src/toMetaMaskSmartAccount.ts","../src/signer.ts","../src/signatures.ts","../src/actions/caveatEnforcerClient.ts","../src/actions/infuraBundlerClient.ts"],"names":["signTypedData","signMessage","getStubSignature","signUserOperation","signDelegation"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC3CA;AACE;AACA;AACA;AAAA,2DACK;AAEP;AACE;AACA;AACA;AAAA,8DACK;AD4CP;AACA;AEvDA,4BAAuB;AFyDvB;AACA;AGzDA;AAEA,IAAM,eAAA,EAAiB,CAAC,OAAO,CAAA;AAoBxB,IAAM,mBAAA,EAAqB,CAAC;AAAA,EACjC;AACF,CAAA,EAAA,GAEW;AACT,EAAA,GAAA,CAAI,UAAA,CAAW,OA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AAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACAG,IAAAA;AACAC,IAAAA;AACG,IAAA;AACJ,EAAA;AAGG,EAAA;AACK,IAAA;AACF,MAAA;AAED,MAAA;AACE,QAAA;AACgB,QAAA;AAChB,QAAA;AACD,MAAA;AACL,IAAA;AACF,EAAA;AAGO,EAAA;AACT;ADgJsD;AACA;AIvWpD;AACA,EAAA;AACA,EAAA;AAIqD;AACR,EAAA;AAC/C;AJsWsD;AACA;AK9YtD;AACE;AAIK;AAyCiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYmB,EAAA;AACjD,IAAA;AAOa,IAAA;AACzB,MAAA;AACC,MAAA;AACV,IAAA;AACH,EAAA;AACF;AA0DqD;AAEC,EAAA;AAG3B,EAAA;AACF,IAAA;AACvB,EAAA;AACF;ALmSsD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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/index.cjs","sourcesContent":[null,"import {\n EIP7702StatelessDeleGator,\n HybridDeleGator,\n MultiSigDeleGator,\n} from '@metamask/delegation-abis';\nimport { type Address, type Hex } from 'viem';\nimport {\n entryPoint07Abi,\n toPackedUserOperation,\n toSmartAccount,\n} from 'viem/account-abstraction';\n\nimport { isValid7702Implementation } from './actions/isValid7702Implementation';\nimport { Implementation } from './constants';\nimport { getCounterfactualAccountData } from './counterfactualAccountData';\nimport {\n SIGNABLE_DELEGATION_TYPED_DATA,\n toDelegationStruct,\n} from './delegation';\nimport { entryPointGetNonce as _getNonce } from './DelegationFramework/EntryPoint/read';\nimport { encodeCallsForCaller } from './encodeCalls';\nimport { resolveSigner } from './signer';\nimport { getSmartAccountsEnvironment } from './smartAccountsEnvironment';\nimport type {\n Call,\n ToMetaMaskSmartAccountParameters,\n ToMetaMaskSmartAccountReturnType,\n SignDelegationParams,\n SignUserOperationParams,\n AbiByImplementation,\n} from './types';\nimport { SIGNABLE_USER_OP_TYPED_DATA } from './userOp';\n\nconst ENTRYPOINT_VERSION = '0.7' as const;\n\n/**\n * Creates a MetaMask DeleGator smart account instance.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @param params - The parameters for creating the smart account.\n * @returns A promise that resolves to a MetaMaskSmartAccount instance.\n * @description\n * This function sets up a MetaMask DeleGator smart account with the specified implementation.\n * It handles both deployed accounts, and counterfactual accounts.\n * A caller may specify a SmartAccountsEnvironment, otherwise the environment will be inferred from the chain.\n */\nexport async function toMetaMaskSmartAccount<\n TImplementation extends Implementation,\n>(\n params: ToMetaMaskSmartAccountParameters<TImplementation>,\n): Promise<ToMetaMaskSmartAccountReturnType<TImplementation>> {\n const {\n client,\n client: { chain },\n implementation,\n } = params;\n\n if (!chain) {\n throw new Error('Chain not specified');\n }\n\n const signer = resolveSigner({\n implementation,\n signer: params.signer,\n });\n\n const environment =\n params.environment ?? getSmartAccountsEnvironment(chain.id);\n\n let address: Address, factoryData: Hex | undefined;\n\n if (params.address) {\n factoryData = undefined;\n address = params.address;\n } else {\n if (implementation === Implementation.Stateless7702) {\n throw new Error('Stateless7702 does not support counterfactual accounts');\n }\n\n const accountData = await getCounterfactualAccountData({\n factory: environment.SimpleFactory,\n implementations: environment.implementations,\n implementation,\n deployParams: params.deployParams,\n deploySalt: params.deploySalt,\n });\n\n address = accountData.address;\n factoryData = accountData.factoryData;\n }\n\n const entryPoint = {\n abi: entryPoint07Abi,\n address: environment.EntryPoint,\n version: ENTRYPOINT_VERSION,\n } as const;\n\n const { abi, contractName } = {\n [Implementation.Hybrid]: {\n contractName: 'HybridDeleGator',\n abi: HybridDeleGator,\n },\n [Implementation.MultiSig]: {\n contractName: 'MultiSigDeleGator',\n abi: MultiSigDeleGator,\n },\n [Implementation.Stateless7702]: {\n contractName: 'EIP7702StatelessDeleGator',\n abi: EIP7702StatelessDeleGator,\n },\n }[implementation] as {\n contractName: string;\n abi: AbiByImplementation[TImplementation];\n };\n\n const getFactoryArgs = async () => {\n if (factoryData === undefined) {\n throw new Error(\n 'Deploy params were not provided, so factory args cannot be inferred',\n );\n }\n return {\n factoryData,\n factory: environment.SimpleFactory,\n };\n };\n\n const signDelegation = async (delegationParams: SignDelegationParams) => {\n if (!signer) {\n throw new Error(\n 'Cannot sign delegation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n }\n\n const { delegation, chainId } = delegationParams;\n\n const delegationStruct = toDelegationStruct({\n ...delegation,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: 'DelegationManager',\n version: '1',\n verifyingContract: environment.DelegationManager,\n },\n types: SIGNABLE_DELEGATION_TYPED_DATA,\n primaryType: 'Delegation',\n message: delegationStruct,\n });\n\n return signature;\n };\n\n const signUserOperation = async (userOpParams: SignUserOperationParams) => {\n if (!signer) {\n throw new Error(\n 'Cannot sign user operation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n }\n\n const { chainId } = userOpParams;\n\n const packedUserOp = toPackedUserOperation({\n sender: address,\n ...userOpParams,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: contractName,\n version: '1',\n verifyingContract: address,\n },\n types: SIGNABLE_USER_OP_TYPED_DATA,\n primaryType: 'PackedUserOperation',\n message: { ...packedUserOp, entryPoint: entryPoint.address },\n });\n\n return signature;\n };\n\n const getAddress = async () => address;\n\n const getNonce = async () =>\n _getNonce({\n client,\n entryPoint: environment.EntryPoint,\n contractAddress: address,\n key: 0n,\n });\n\n const encodeCalls = async (calls: readonly Call[]) =>\n encodeCallsForCaller(address, calls);\n\n const signerMethods = signer ?? {\n signMessage: async () => {\n throw new Error(\n 'Cannot sign message: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n signTypedData: async () => {\n throw new Error(\n 'Cannot sign typed data: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n getStubSignature: async () => {\n throw new Error(\n 'Cannot get stub signature: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n };\n\n const smartAccount = await toSmartAccount({\n abi,\n client,\n entryPoint,\n environment,\n getAddress,\n getFactoryArgs,\n encodeCalls,\n getNonce,\n signUserOperation,\n signDelegation,\n ...signerMethods,\n });\n\n // Override isDeployed only for EIP-7702 implementation to check proper delegation code\n if (implementation === Implementation.Stateless7702) {\n return {\n ...smartAccount,\n isDeployed: async () =>\n isValid7702Implementation({\n client,\n accountAddress: address,\n environment,\n }),\n };\n }\n\n // For other implementations, use the default isDeployed behavior\n return smartAccount;\n}\n","import { concat } from 'viem';\nimport type {\n Address,\n SignableMessage,\n TypedData,\n TypedDataDefinition,\n} from 'viem';\nimport type { WebAuthnAccount } from 'viem/account-abstraction';\n\nimport { Implementation } from './constants';\nimport { aggregateSignature } from './signatures';\nimport type {\n AccountSignerConfig,\n HybridSignerConfig,\n InternalSigner,\n MultiSigSignerConfig,\n SignerConfigByImplementation,\n Stateless7702SignerConfig,\n WalletSignerConfig,\n} from './types';\nimport {\n createDummyWebAuthnSignature,\n encodeDeleGatorSignature,\n} from './webAuthn';\n\n// A valid ECDSA signature, this must be able to ecrecover an address, otherwise the contracts will revert in isValidSignature\nconst EOA_STUB_SIGNATURE =\n '0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000011b' as const;\n\nconst resolveSignerFromWalletConfig = (\n config: WalletSignerConfig,\n): InternalSigner => {\n return {\n signMessage: config.walletClient.signMessage,\n signTypedData: async (typedData) => {\n // todo: figure out this type so that we don't need the type assertion\n return config.walletClient.signTypedData(typedData as any);\n },\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveSignerFromAccountConfig = (config: AccountSignerConfig) => {\n return {\n signMessage: config.account.signMessage,\n signTypedData: config.account.signTypedData,\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveHybridSigner = (config: HybridSignerConfig): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n const { keyId, webAuthnAccount } = config;\n\n if (webAuthnAccount.type !== 'webAuthn') {\n throw new Error('Account is not a webAuthn account');\n }\n\n const encodeSignature = (\n result: Awaited<ReturnType<WebAuthnAccount['signMessage']>>,\n ) =>\n encodeDeleGatorSignature(\n keyId,\n result.signature,\n result.webauthn.clientDataJSON,\n result.webauthn.authenticatorData,\n );\n\n const signMessage = async (args: { message: SignableMessage }) =>\n webAuthnAccount.signMessage(args).then(encodeSignature);\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);\n\n const getStubSignature = async () => createDummyWebAuthnSignature(keyId);\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveMultiSigSigner = (\n config: MultiSigSignerConfig,\n): InternalSigner => {\n const resolvedSigners = config.map((signer) => {\n let individualSignMessage: InternalSigner['signMessage'];\n let individualSignTypedData: InternalSigner['signTypedData'];\n let address: Address;\n if ('walletClient' in signer) {\n const { signMessage, signTypedData } =\n resolveSignerFromWalletConfig(signer);\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.walletClient.account.address;\n } else {\n const { signMessage, signTypedData } =\n resolveSignerFromAccountConfig(signer);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.account.address;\n }\n return {\n address,\n individualSignMessage,\n individualSignTypedData,\n };\n });\n\n const signMessage = async (args: { message: SignableMessage }) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignMessage, address }) => ({\n signature: await individualSignMessage(args),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignTypedData, address }) => ({\n signature: await individualSignTypedData(typedDataDefinition),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const getStubSignature = async () =>\n concat(resolvedSigners.map(() => EOA_STUB_SIGNATURE));\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveStateless7702Signer = (\n config: Stateless7702SignerConfig,\n): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n\n throw new Error('Invalid signer config');\n};\n\n/**\n * Resolve a signer from a configuration object.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner;\n\n/**\n * Resolve a signer from a configuration object. If no signer is provided, return null.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer or null if no signer is provided.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer?: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner | null;\n\n/**\n * Resolve a signer from a configuration object. If no signer is provided, return null.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer or null if no signer is provided.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer?: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner | null {\n const { implementation, signer } = config;\n\n if (!signer) {\n return null;\n }\n\n if (implementation === Implementation.Hybrid) {\n return resolveHybridSigner(signer as HybridSignerConfig);\n } else if (implementation === Implementation.MultiSig) {\n return resolveMultiSigSigner(signer as MultiSigSignerConfig);\n } else if (implementation === Implementation.Stateless7702) {\n return resolveStateless7702Signer(signer as Stateless7702SignerConfig);\n }\n throw new Error(`Implementation type '${implementation}' not supported`);\n}\n","import type { Address, Hex } from 'viem';\nimport { concat } from 'viem';\n\nconst signatureTypes = ['ECDSA'] as const;\n\nexport type SignatureType = (typeof signatureTypes)[number];\n\n/**\n * Represents a partial signature that can be aggregated with others.\n */\nexport type PartialSignature = {\n signer: Address;\n signature: Hex;\n type: SignatureType;\n};\n\n/**\n * Aggregates signatures into a single signature as expected by the MultiSig implementation.\n *\n * @param params - The parameters for signature aggregation.\n * @param params.signatures - The array of partial signatures to aggregate.\n * @returns The aggregated signature.\n */\nexport const aggregateSignature = ({\n signatures,\n}: {\n signatures: PartialSignature[];\n}): Hex => {\n if (signatures.length === 0) {\n return '0x';\n }\n\n for (const { type } of signatures) {\n if (!signatureTypes.includes(type)) {\n throw new Error(`Invalid signature type: ${type}`);\n }\n }\n\n // Sort signatures by signer address as required by MultiSig implementation\n const sortedSignatures = [...signatures].sort((a, b) =>\n a.signer.localeCompare(b.signer),\n );\n\n // Concatenate all signatures\n return concat(sortedSignatures.map(({ signature }) => signature));\n};\n\n/**\n * Type definition for the aggregateSignature function parameters.\n */\nexport type AggregateSignatureParams = {\n signatures: PartialSignature[];\n};\n","import type { Client, Transport, Chain, Account } from 'viem';\n\nimport type { SmartAccountsEnvironment } from '../types';\nimport {\n caveatEnforcerActions,\n type CaveatEnforcerParams,\n type PeriodTransferResult,\n type StreamingResult,\n} from './getCaveatAvailableAmount';\n\n/**\n * Type for client extended with caveat enforcer actions.\n */\nexport type CaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n> = Client<TTransport, TChain, TAccount> &\n ReturnType<ReturnType<typeof caveatEnforcerActions>>;\n\n/**\n * Create a viem client extended with caveat enforcer actions.\n *\n * @param params - The parameters object.\n * @param params.client - The viem client.\n * @param params.environment - The SmartAccountsEnvironment.\n * @returns The extended client with caveat enforcer actions.\n */\nexport function createCaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n>({\n client,\n environment,\n}: {\n client: Client<TTransport, TChain, TAccount>;\n environment: SmartAccountsEnvironment;\n}): CaveatEnforcerClient<TTransport, TChain, TAccount> {\n return client.extend(caveatEnforcerActions({ environment }));\n}\n\n// Re-export types for convenience\nexport type { CaveatEnforcerParams, PeriodTransferResult, StreamingResult };\n","import type { Transport, Chain, Hex, Client, Account } from 'viem';\nimport {\n createBundlerClient,\n type BundlerClient,\n type BundlerClientConfig,\n type SmartAccount,\n} from 'viem/account-abstraction';\n\n/**\n * Gas price tiers returned by pimlico_getUserOperationGasPrice\n */\nexport type GasPriceTier = {\n /** Maximum fee per gas in hex format */\n maxFeePerGas: Hex;\n /** Maximum priority fee per gas in hex format */\n maxPriorityFeePerGas: Hex;\n};\n\n/**\n * Response from pimlico_getUserOperationGasPrice RPC method\n */\nexport type UserOperationGasPriceResponse = {\n /** Slow gas price tier */\n slow: GasPriceTier;\n /** Standard gas price tier */\n standard: GasPriceTier;\n /** Fast gas price tier */\n fast: GasPriceTier;\n};\n\n/**\n * Pimlico bundler schema for type-safe RPC method calls\n */\n/* eslint-disable @typescript-eslint/naming-convention */\ntype PimlicoBundlerSchema = [\n {\n Method: 'pimlico_getUserOperationGasPrice';\n Parameters: [];\n ReturnType: UserOperationGasPriceResponse;\n },\n];\n\n/**\n * Infura bundler actions for extending bundler clients.\n *\n * @returns A function that takes a client and returns the client extension with Infura bundler actions.\n */\nconst infuraBundlerActions = () => (client: Client) => ({\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n * @example\n * ```typescript\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * console.log(gasPrices.standard.maxFeePerGas);\n * ```\n */\n async getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse> {\n const pimlicoClient = client as Client<\n Transport,\n Chain | undefined,\n Account | undefined,\n PimlicoBundlerSchema\n >;\n\n return await pimlicoClient.request({\n method: 'pimlico_getUserOperationGasPrice',\n params: [],\n });\n },\n});\n\n/**\n * Type for bundler client extended with Infura bundler actions.\n */\nexport type InfuraBundlerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends SmartAccount | undefined = SmartAccount | undefined,\n> = BundlerClient<TTransport, TChain, TAccount> & {\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n */\n getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse>;\n};\n\n/**\n * Creates an Infura bundler client extended with Infura bundler actions.\n *\n * This is a wrapper around viem's createBundlerClient that extends it with\n * the getUserOperationGasPrice method for retrieving gas prices from Pimlico's\n * bundler infrastructure via Infura's proxy.\n *\n * @param config - Configuration for the bundler client.\n * @returns Extended bundler client with Infura bundler actions.\n * @example\n * ```typescript\n * import { createPublicClient, http } from 'viem';\n * import { sepolia } from 'viem/chains';\n * import { createInfuraBundlerClient } from '@metamask/smart-accounts-kit';\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * });\n *\n * const bundlerClient = createInfuraBundlerClient({\n * client: publicClient,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * chain: sepolia,\n * });\n *\n * // Use standard bundler methods\n * const userOpHash = await bundlerClient.sendUserOperation({...});\n *\n * // Use Infura specific methods\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * ```\n */\nexport function createInfuraBundlerClient<\n TTransport extends Transport,\n TChain extends Chain | undefined = undefined,\n TAccount extends SmartAccount | undefined = undefined,\n>(\n config: BundlerClientConfig<TTransport, TChain, TAccount>,\n): InfuraBundlerClient<TTransport, TChain, TAccount> {\n // Create the base bundler client using viem's function\n const baseBundlerClient = createBundlerClient(config);\n\n // Extend the client with Infura bundler actions\n return baseBundlerClient.extend(\n infuraBundlerActions(),\n ) as unknown as InfuraBundlerClient<TTransport, TChain, TAccount>;\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,12 +1,12 @@
1
- import { I as Implementation, T as ToMetaMaskSmartAccountParameters, a as ToMetaMaskSmartAccountReturnType, C as Caveat, S as SmartAccountsEnvironment } from './types-BLYWtcR3.cjs';
2
- export { A as AccountSignerConfig, k as CaveatType, D as Delegation, H as HybridDeleGatorDeployParams, g as HybridSignerConfig, e as MetaMaskSmartAccount, d as MetaMaskSmartAccountImplementation, M as MultiSigDeleGatorDeployParams, h as MultiSigSignerConfig, P as PermissionContext, j as ScopeType, c as SignDelegationParams, b as SignUserOperationParams, i as TransferWindow, W as WalletSignerConfig, f as WebAuthnSignerConfig } from './types-BLYWtcR3.cjs';
3
- export { B as BalanceChangeType, g as Caveats, C as CreateDelegationOptions, f as CreateExecutionArgs, b as CreateOpenDelegationOptions, E as ExecutionMode, e as ExecutionStruct, c as createDelegation, d as createExecution, a as createOpenDelegation, s as signDelegation } from './delegation-D_TY-tAq.cjs';
4
- export { P as PREFERRED_VERSION, g as getSmartAccountsEnvironment } from './smartAccountsEnvironment-BU8kjlEv.cjs';
1
+ import { I as Implementation, T as ToMetaMaskSmartAccountParameters, a as ToMetaMaskSmartAccountReturnType, C as Caveat, S as SmartAccountsEnvironment } from './types-qdEHxd5Q.cjs';
2
+ export { A as AccountSignerConfig, k as CaveatType, D as Delegation, H as HybridDeleGatorDeployParams, g as HybridSignerConfig, e as MetaMaskSmartAccount, d as MetaMaskSmartAccountImplementation, M as MultiSigDeleGatorDeployParams, h as MultiSigSignerConfig, P as PermissionContext, j as ScopeType, c as SignDelegationParams, b as SignUserOperationParams, i as TransferWindow, W as WalletSignerConfig, f as WebAuthnSignerConfig } from './types-qdEHxd5Q.cjs';
3
+ export { B as BalanceChangeType, g as Caveats, C as CreateDelegationOptions, f as CreateExecutionArgs, b as CreateOpenDelegationOptions, E as ExecutionMode, e as ExecutionStruct, c as createDelegation, d as createExecution, a as createOpenDelegation, s as signDelegation } from './delegation-DIriDFkq.cjs';
4
+ export { P as PREFERRED_VERSION, g as getSmartAccountsEnvironment } from './smartAccountsEnvironment-Czw9KUYZ.cjs';
5
5
  import { Hex, Address, Transport, Chain, Account, Client } from 'viem';
6
6
  export { s as signUserOperation } from './userOp-DKgjzz7B.cjs';
7
- export { i as contracts } from './index-DvcKJcXi.cjs';
8
- import { c as caveatEnforcerActions } from './index-CZes99jV.cjs';
9
- export { i as actions } from './index-CZes99jV.cjs';
7
+ export { i as contracts } from './index-DC9baw8F.cjs';
8
+ import { c as caveatEnforcerActions } from './index-Dvc4ir4O.cjs';
9
+ export { i as actions } from './index-Dvc4ir4O.cjs';
10
10
  import { SmartAccount, BundlerClientConfig, BundlerClient } from 'viem/account-abstraction';
11
11
  export { ANY_BENEFICIARY, ROOT_AUTHORITY } from '@metamask/delegation-core';
12
12
  import '@metamask/delegation-abis';
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { I as Implementation, T as ToMetaMaskSmartAccountParameters, a as ToMetaMaskSmartAccountReturnType, C as Caveat, S as SmartAccountsEnvironment } from './types-BLYWtcR3.js';
2
- export { A as AccountSignerConfig, k as CaveatType, D as Delegation, H as HybridDeleGatorDeployParams, g as HybridSignerConfig, e as MetaMaskSmartAccount, d as MetaMaskSmartAccountImplementation, M as MultiSigDeleGatorDeployParams, h as MultiSigSignerConfig, P as PermissionContext, j as ScopeType, c as SignDelegationParams, b as SignUserOperationParams, i as TransferWindow, W as WalletSignerConfig, f as WebAuthnSignerConfig } from './types-BLYWtcR3.js';
3
- export { B as BalanceChangeType, g as Caveats, C as CreateDelegationOptions, f as CreateExecutionArgs, b as CreateOpenDelegationOptions, E as ExecutionMode, e as ExecutionStruct, c as createDelegation, d as createExecution, a as createOpenDelegation, s as signDelegation } from './delegation-DGUfyX-C.js';
4
- export { P as PREFERRED_VERSION, g as getSmartAccountsEnvironment } from './smartAccountsEnvironment-egxuflDO.js';
1
+ import { I as Implementation, T as ToMetaMaskSmartAccountParameters, a as ToMetaMaskSmartAccountReturnType, C as Caveat, S as SmartAccountsEnvironment } from './types-qdEHxd5Q.js';
2
+ export { A as AccountSignerConfig, k as CaveatType, D as Delegation, H as HybridDeleGatorDeployParams, g as HybridSignerConfig, e as MetaMaskSmartAccount, d as MetaMaskSmartAccountImplementation, M as MultiSigDeleGatorDeployParams, h as MultiSigSignerConfig, P as PermissionContext, j as ScopeType, c as SignDelegationParams, b as SignUserOperationParams, i as TransferWindow, W as WalletSignerConfig, f as WebAuthnSignerConfig } from './types-qdEHxd5Q.js';
3
+ export { B as BalanceChangeType, g as Caveats, C as CreateDelegationOptions, f as CreateExecutionArgs, b as CreateOpenDelegationOptions, E as ExecutionMode, e as ExecutionStruct, c as createDelegation, d as createExecution, a as createOpenDelegation, s as signDelegation } from './delegation-CvVXs0PO.js';
4
+ export { P as PREFERRED_VERSION, g as getSmartAccountsEnvironment } from './smartAccountsEnvironment-u1CcFcGE.js';
5
5
  import { Hex, Address, Transport, Chain, Account, Client } from 'viem';
6
6
  export { s as signUserOperation } from './userOp-DKgjzz7B.js';
7
- export { i as contracts } from './index-B9bsjGqI.js';
8
- import { c as caveatEnforcerActions } from './index-FpCh2419.js';
9
- export { i as actions } from './index-FpCh2419.js';
7
+ export { i as contracts } from './index-ChTryO1-.js';
8
+ import { c as caveatEnforcerActions } from './index-5EdxVa_d.js';
9
+ export { i as actions } from './index-5EdxVa_d.js';
10
10
  import { SmartAccount, BundlerClientConfig, BundlerClient } from 'viem/account-abstraction';
11
11
  export { ANY_BENEFICIARY, ROOT_AUTHORITY } from '@metamask/delegation-core';
12
12
  import '@metamask/delegation-abis';
package/dist/index.mjs CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  encodeCallsForCaller,
14
14
  encodeDeleGatorSignature,
15
15
  getCounterfactualAccountData
16
- } from "./chunk-WPVSFOQM.mjs";
16
+ } from "./chunk-45GHWVQA.mjs";
17
17
  import {
18
18
  PREFERRED_VERSION,
19
19
  SIGNABLE_USER_OP_TYPED_DATA,
@@ -115,11 +115,11 @@ var resolveHybridSigner = (config) => {
115
115
  if (webAuthnAccount.type !== "webAuthn") {
116
116
  throw new Error("Account is not a webAuthn account");
117
117
  }
118
- const encodeSignature = ({ signature, webauthn }) => encodeDeleGatorSignature(
118
+ const encodeSignature = (result) => encodeDeleGatorSignature(
119
119
  keyId,
120
- signature,
121
- webauthn.clientDataJSON,
122
- webauthn.authenticatorData
120
+ result.signature,
121
+ result.webauthn.clientDataJSON,
122
+ result.webauthn.authenticatorData
123
123
  );
124
124
  const signMessage = async (args) => webAuthnAccount.signMessage(args).then(encodeSignature);
125
125
  const signTypedData = async (typedDataDefinition) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);
@@ -210,19 +210,20 @@ var resolveStateless7702Signer = (config) => {
210
210
  }
211
211
  throw new Error("Invalid signer config");
212
212
  };
213
- var resolveSigner = (config) => {
214
- const { implementation } = config;
213
+ function resolveSigner(config) {
214
+ const { implementation, signer } = config;
215
+ if (!signer) {
216
+ return null;
217
+ }
215
218
  if (implementation === "Hybrid" /* Hybrid */) {
216
- return resolveHybridSigner(config.signer);
219
+ return resolveHybridSigner(signer);
217
220
  } else if (implementation === "MultiSig" /* MultiSig */) {
218
- return resolveMultiSigSigner(config.signer);
221
+ return resolveMultiSigSigner(signer);
219
222
  } else if (implementation === "Stateless7702" /* Stateless7702 */) {
220
- return resolveStateless7702Signer(
221
- config.signer
222
- );
223
+ return resolveStateless7702Signer(signer);
223
224
  }
224
225
  throw new Error(`Implementation type '${implementation}' not supported`);
225
- };
226
+ }
226
227
 
227
228
  // src/toMetaMaskSmartAccount.ts
228
229
  var ENTRYPOINT_VERSION = "0.7";
@@ -289,6 +290,11 @@ async function toMetaMaskSmartAccount(params) {
289
290
  };
290
291
  };
291
292
  const signDelegation2 = async (delegationParams) => {
293
+ if (!signer) {
294
+ throw new Error(
295
+ "Cannot sign delegation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
296
+ );
297
+ }
292
298
  const { delegation, chainId } = delegationParams;
293
299
  const delegationStruct = toDelegationStruct({
294
300
  ...delegation,
@@ -308,6 +314,11 @@ async function toMetaMaskSmartAccount(params) {
308
314
  return signature;
309
315
  };
310
316
  const signUserOperation2 = async (userOpParams) => {
317
+ if (!signer) {
318
+ throw new Error(
319
+ "Cannot sign user operation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
320
+ );
321
+ }
311
322
  const { chainId } = userOpParams;
312
323
  const packedUserOp = toPackedUserOperation({
313
324
  sender: address,
@@ -335,6 +346,23 @@ async function toMetaMaskSmartAccount(params) {
335
346
  key: 0n
336
347
  });
337
348
  const encodeCalls = async (calls) => encodeCallsForCaller(address, calls);
349
+ const signerMethods = signer ?? {
350
+ signMessage: async () => {
351
+ throw new Error(
352
+ "Cannot sign message: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
353
+ );
354
+ },
355
+ signTypedData: async () => {
356
+ throw new Error(
357
+ "Cannot sign typed data: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
358
+ );
359
+ },
360
+ getStubSignature: async () => {
361
+ throw new Error(
362
+ "Cannot get stub signature: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations."
363
+ );
364
+ }
365
+ };
338
366
  const smartAccount = await toSmartAccount({
339
367
  abi,
340
368
  client,
@@ -346,7 +374,7 @@ async function toMetaMaskSmartAccount(params) {
346
374
  getNonce,
347
375
  signUserOperation: signUserOperation2,
348
376
  signDelegation: signDelegation2,
349
- ...signer
377
+ ...signerMethods
350
378
  });
351
379
  if (implementation === "Stateless7702" /* Stateless7702 */) {
352
380
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/toMetaMaskSmartAccount.ts","../src/signer.ts","../src/signatures.ts","../src/actions/caveatEnforcerClient.ts","../src/actions/infuraBundlerClient.ts"],"sourcesContent":["import {\n EIP7702StatelessDeleGator,\n HybridDeleGator,\n MultiSigDeleGator,\n} from '@metamask/delegation-abis';\nimport { type Address, type Hex } from 'viem';\nimport {\n entryPoint07Abi,\n toPackedUserOperation,\n toSmartAccount,\n} from 'viem/account-abstraction';\n\nimport { isValid7702Implementation } from './actions/isValid7702Implementation';\nimport { Implementation } from './constants';\nimport { getCounterfactualAccountData } from './counterfactualAccountData';\nimport {\n SIGNABLE_DELEGATION_TYPED_DATA,\n toDelegationStruct,\n} from './delegation';\nimport { entryPointGetNonce as _getNonce } from './DelegationFramework/EntryPoint/read';\nimport { encodeCallsForCaller } from './encodeCalls';\nimport { resolveSigner } from './signer';\nimport { getSmartAccountsEnvironment } from './smartAccountsEnvironment';\nimport type {\n Call,\n ToMetaMaskSmartAccountParameters,\n ToMetaMaskSmartAccountReturnType,\n SignDelegationParams,\n SignUserOperationParams,\n AbiByImplementation,\n} from './types';\nimport { SIGNABLE_USER_OP_TYPED_DATA } from './userOp';\n\nconst ENTRYPOINT_VERSION = '0.7' as const;\n\n/**\n * Creates a MetaMask DeleGator smart account instance.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @param params - The parameters for creating the smart account.\n * @returns A promise that resolves to a MetaMaskSmartAccount instance.\n * @description\n * This function sets up a MetaMask DeleGator smart account with the specified implementation.\n * It handles both deployed accounts, and counterfactual accounts.\n * A caller may specify a SmartAccountsEnvironment, otherwise the environment will be inferred from the chain.\n */\nexport async function toMetaMaskSmartAccount<\n TImplementation extends Implementation,\n>(\n params: ToMetaMaskSmartAccountParameters<TImplementation>,\n): Promise<ToMetaMaskSmartAccountReturnType<TImplementation>> {\n const {\n client,\n client: { chain },\n implementation,\n } = params;\n\n if (!chain) {\n throw new Error('Chain not specified');\n }\n\n const signer = resolveSigner({\n implementation,\n signer: params.signer,\n });\n\n const environment =\n params.environment ?? getSmartAccountsEnvironment(chain.id);\n\n let address: Address, factoryData: Hex | undefined;\n\n if (params.address) {\n factoryData = undefined;\n address = params.address;\n } else {\n if (implementation === Implementation.Stateless7702) {\n throw new Error('Stateless7702 does not support counterfactual accounts');\n }\n\n const accountData = await getCounterfactualAccountData({\n factory: environment.SimpleFactory,\n implementations: environment.implementations,\n implementation,\n deployParams: params.deployParams,\n deploySalt: params.deploySalt,\n });\n\n address = accountData.address;\n factoryData = accountData.factoryData;\n }\n\n const entryPoint = {\n abi: entryPoint07Abi,\n address: environment.EntryPoint,\n version: ENTRYPOINT_VERSION,\n } as const;\n\n const { abi, contractName } = {\n [Implementation.Hybrid]: {\n contractName: 'HybridDeleGator',\n abi: HybridDeleGator,\n },\n [Implementation.MultiSig]: {\n contractName: 'MultiSigDeleGator',\n abi: MultiSigDeleGator,\n },\n [Implementation.Stateless7702]: {\n contractName: 'EIP7702StatelessDeleGator',\n abi: EIP7702StatelessDeleGator,\n },\n }[implementation] as {\n contractName: string;\n abi: AbiByImplementation[TImplementation];\n };\n\n const getFactoryArgs = async () => {\n if (factoryData === undefined) {\n throw new Error(\n 'Deploy params were not provided, so factory args cannot be inferred',\n );\n }\n return {\n factoryData,\n factory: environment.SimpleFactory,\n };\n };\n\n const signDelegation = async (delegationParams: SignDelegationParams) => {\n const { delegation, chainId } = delegationParams;\n\n const delegationStruct = toDelegationStruct({\n ...delegation,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: 'DelegationManager',\n version: '1',\n verifyingContract: environment.DelegationManager,\n },\n types: SIGNABLE_DELEGATION_TYPED_DATA,\n primaryType: 'Delegation',\n message: delegationStruct,\n });\n\n return signature;\n };\n\n const signUserOperation = async (userOpParams: SignUserOperationParams) => {\n const { chainId } = userOpParams;\n\n const packedUserOp = toPackedUserOperation({\n sender: address,\n ...userOpParams,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: contractName,\n version: '1',\n verifyingContract: address,\n },\n types: SIGNABLE_USER_OP_TYPED_DATA,\n primaryType: 'PackedUserOperation',\n message: { ...packedUserOp, entryPoint: entryPoint.address },\n });\n\n return signature;\n };\n\n const getAddress = async () => address;\n\n const getNonce = async () =>\n _getNonce({\n client,\n entryPoint: environment.EntryPoint,\n contractAddress: address,\n key: 0n,\n });\n\n const encodeCalls = async (calls: readonly Call[]) =>\n encodeCallsForCaller(address, calls);\n\n const smartAccount = await toSmartAccount({\n abi,\n client,\n entryPoint,\n environment,\n getAddress,\n getFactoryArgs,\n encodeCalls,\n getNonce,\n signUserOperation,\n signDelegation,\n ...signer,\n });\n\n // Override isDeployed only for EIP-7702 implementation to check proper delegation code\n if (implementation === Implementation.Stateless7702) {\n return {\n ...smartAccount,\n isDeployed: async () =>\n isValid7702Implementation({\n client,\n accountAddress: address,\n environment,\n }),\n };\n }\n\n // For other implementations, use the default isDeployed behavior\n return smartAccount;\n}\n","import { concat } from 'viem';\nimport type {\n Address,\n SignableMessage,\n TypedData,\n TypedDataDefinition,\n} from 'viem';\nimport type { SignReturnType as WebAuthnSignReturnType } from 'webauthn-p256';\n\nimport { Implementation } from './constants';\nimport { aggregateSignature } from './signatures';\nimport type {\n AccountSignerConfig,\n HybridSignerConfig,\n InternalSigner,\n MultiSigSignerConfig,\n SignerConfigByImplementation,\n Stateless7702SignerConfig,\n WalletSignerConfig,\n} from './types';\nimport {\n createDummyWebAuthnSignature,\n encodeDeleGatorSignature,\n} from './webAuthn';\n\n// A valid ECDSA signature, this must be able to ecrecover an address, otherwise the contracts will revert in isValidSignature\nconst EOA_STUB_SIGNATURE =\n '0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000011b' as const;\n\nconst resolveSignerFromWalletConfig = (\n config: WalletSignerConfig,\n): InternalSigner => {\n return {\n signMessage: config.walletClient.signMessage,\n signTypedData: async (typedData) => {\n // todo: figure out this type so that we don't need the type assertion\n return config.walletClient.signTypedData(typedData as any);\n },\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveSignerFromAccountConfig = (config: AccountSignerConfig) => {\n return {\n signMessage: config.account.signMessage,\n signTypedData: config.account.signTypedData,\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveHybridSigner = (config: HybridSignerConfig): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n const { keyId, webAuthnAccount } = config;\n\n if (webAuthnAccount.type !== 'webAuthn') {\n throw new Error('Account is not a webAuthn account');\n }\n\n const encodeSignature = ({ signature, webauthn }: WebAuthnSignReturnType) =>\n encodeDeleGatorSignature(\n keyId,\n signature,\n webauthn.clientDataJSON,\n webauthn.authenticatorData,\n );\n\n const signMessage = async (args: { message: SignableMessage }) =>\n webAuthnAccount.signMessage(args).then(encodeSignature);\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);\n\n const getStubSignature = async () => createDummyWebAuthnSignature(keyId);\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveMultiSigSigner = (\n config: MultiSigSignerConfig,\n): InternalSigner => {\n const resolvedSigners = config.map((signer) => {\n let individualSignMessage: InternalSigner['signMessage'];\n let individualSignTypedData: InternalSigner['signTypedData'];\n let address: Address;\n if ('walletClient' in signer) {\n const { signMessage, signTypedData } =\n resolveSignerFromWalletConfig(signer);\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.walletClient.account.address;\n } else {\n const { signMessage, signTypedData } =\n resolveSignerFromAccountConfig(signer);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.account.address;\n }\n return {\n address,\n individualSignMessage,\n individualSignTypedData,\n };\n });\n\n const signMessage = async (args: { message: SignableMessage }) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignMessage, address }) => ({\n signature: await individualSignMessage(args),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignTypedData, address }) => ({\n signature: await individualSignTypedData(typedDataDefinition),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const getStubSignature = async () =>\n concat(resolvedSigners.map(() => EOA_STUB_SIGNATURE));\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveStateless7702Signer = (\n config: Stateless7702SignerConfig,\n): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n\n throw new Error('Invalid signer config');\n};\n\nexport const resolveSigner = <TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner => {\n const { implementation } = config;\n\n if (implementation === Implementation.Hybrid) {\n return resolveHybridSigner(config.signer as HybridSignerConfig);\n } else if (implementation === Implementation.MultiSig) {\n return resolveMultiSigSigner(config.signer as MultiSigSignerConfig);\n } else if (implementation === Implementation.Stateless7702) {\n return resolveStateless7702Signer(\n config.signer as Stateless7702SignerConfig,\n );\n }\n throw new Error(`Implementation type '${implementation}' not supported`);\n};\n","import type { Address, Hex } from 'viem';\nimport { concat } from 'viem';\n\nconst signatureTypes = ['ECDSA'] as const;\n\nexport type SignatureType = (typeof signatureTypes)[number];\n\n/**\n * Represents a partial signature that can be aggregated with others.\n */\nexport type PartialSignature = {\n signer: Address;\n signature: Hex;\n type: SignatureType;\n};\n\n/**\n * Aggregates signatures into a single signature as expected by the MultiSig implementation.\n *\n * @param params - The parameters for signature aggregation.\n * @param params.signatures - The array of partial signatures to aggregate.\n * @returns The aggregated signature.\n */\nexport const aggregateSignature = ({\n signatures,\n}: {\n signatures: PartialSignature[];\n}): Hex => {\n if (signatures.length === 0) {\n return '0x';\n }\n\n for (const { type } of signatures) {\n if (!signatureTypes.includes(type)) {\n throw new Error(`Invalid signature type: ${type}`);\n }\n }\n\n // Sort signatures by signer address as required by MultiSig implementation\n const sortedSignatures = [...signatures].sort((a, b) =>\n a.signer.localeCompare(b.signer),\n );\n\n // Concatenate all signatures\n return concat(sortedSignatures.map(({ signature }) => signature));\n};\n\n/**\n * Type definition for the aggregateSignature function parameters.\n */\nexport type AggregateSignatureParams = {\n signatures: PartialSignature[];\n};\n","import type { Client, Transport, Chain, Account } from 'viem';\n\nimport type { SmartAccountsEnvironment } from '../types';\nimport {\n caveatEnforcerActions,\n type CaveatEnforcerParams,\n type PeriodTransferResult,\n type StreamingResult,\n} from './getCaveatAvailableAmount';\n\n/**\n * Type for client extended with caveat enforcer actions.\n */\nexport type CaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n> = Client<TTransport, TChain, TAccount> &\n ReturnType<ReturnType<typeof caveatEnforcerActions>>;\n\n/**\n * Create a viem client extended with caveat enforcer actions.\n *\n * @param params - The parameters object.\n * @param params.client - The viem client.\n * @param params.environment - The SmartAccountsEnvironment.\n * @returns The extended client with caveat enforcer actions.\n */\nexport function createCaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n>({\n client,\n environment,\n}: {\n client: Client<TTransport, TChain, TAccount>;\n environment: SmartAccountsEnvironment;\n}): CaveatEnforcerClient<TTransport, TChain, TAccount> {\n return client.extend(caveatEnforcerActions({ environment }));\n}\n\n// Re-export types for convenience\nexport type { CaveatEnforcerParams, PeriodTransferResult, StreamingResult };\n","import type { Transport, Chain, Hex, Client, Account } from 'viem';\nimport {\n createBundlerClient,\n type BundlerClient,\n type BundlerClientConfig,\n type SmartAccount,\n} from 'viem/account-abstraction';\n\n/**\n * Gas price tiers returned by pimlico_getUserOperationGasPrice\n */\nexport type GasPriceTier = {\n /** Maximum fee per gas in hex format */\n maxFeePerGas: Hex;\n /** Maximum priority fee per gas in hex format */\n maxPriorityFeePerGas: Hex;\n};\n\n/**\n * Response from pimlico_getUserOperationGasPrice RPC method\n */\nexport type UserOperationGasPriceResponse = {\n /** Slow gas price tier */\n slow: GasPriceTier;\n /** Standard gas price tier */\n standard: GasPriceTier;\n /** Fast gas price tier */\n fast: GasPriceTier;\n};\n\n/**\n * Pimlico bundler schema for type-safe RPC method calls\n */\n/* eslint-disable @typescript-eslint/naming-convention */\ntype PimlicoBundlerSchema = [\n {\n Method: 'pimlico_getUserOperationGasPrice';\n Parameters: [];\n ReturnType: UserOperationGasPriceResponse;\n },\n];\n\n/**\n * Infura bundler actions for extending bundler clients.\n *\n * @returns A function that takes a client and returns the client extension with Infura bundler actions.\n */\nconst infuraBundlerActions = () => (client: Client) => ({\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n * @example\n * ```typescript\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * console.log(gasPrices.standard.maxFeePerGas);\n * ```\n */\n async getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse> {\n const pimlicoClient = client as Client<\n Transport,\n Chain | undefined,\n Account | undefined,\n PimlicoBundlerSchema\n >;\n\n return await pimlicoClient.request({\n method: 'pimlico_getUserOperationGasPrice',\n params: [],\n });\n },\n});\n\n/**\n * Type for bundler client extended with Infura bundler actions.\n */\nexport type InfuraBundlerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends SmartAccount | undefined = SmartAccount | undefined,\n> = BundlerClient<TTransport, TChain, TAccount> & {\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n */\n getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse>;\n};\n\n/**\n * Creates an Infura bundler client extended with Infura bundler actions.\n *\n * This is a wrapper around viem's createBundlerClient that extends it with\n * the getUserOperationGasPrice method for retrieving gas prices from Pimlico's\n * bundler infrastructure via Infura's proxy.\n *\n * @param config - Configuration for the bundler client.\n * @returns Extended bundler client with Infura bundler actions.\n * @example\n * ```typescript\n * import { createPublicClient, http } from 'viem';\n * import { sepolia } from 'viem/chains';\n * import { createInfuraBundlerClient } from '@metamask/smart-accounts-kit';\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * });\n *\n * const bundlerClient = createInfuraBundlerClient({\n * client: publicClient,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * chain: sepolia,\n * });\n *\n * // Use standard bundler methods\n * const userOpHash = await bundlerClient.sendUserOperation({...});\n *\n * // Use Infura specific methods\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * ```\n */\nexport function createInfuraBundlerClient<\n TTransport extends Transport,\n TChain extends Chain | undefined = undefined,\n TAccount extends SmartAccount | undefined = undefined,\n>(\n config: BundlerClientConfig<TTransport, TChain, TAccount>,\n): InfuraBundlerClient<TTransport, TChain, TAccount> {\n // Create the base bundler client using viem's function\n const baseBundlerClient = createBundlerClient(config);\n\n // Extend the client with Infura bundler actions\n return baseBundlerClient.extend(\n infuraBundlerActions(),\n ) as unknown as InfuraBundlerClient<TTransport, TChain, TAccount>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACVP,SAAS,UAAAA,eAAc;;;ACCvB,SAAS,cAAc;AAEvB,IA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AK;AAErC,QAAM,eAAe,MAAM,eAAe;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,mBAAAA;AAAA,IACA,gBAAAD;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AAGD,MAAI,wDAAiD;AACnD,WAAO;AAAA,MACL,GAAG;AAAA,MACH,YAAY,YACV,0BAA0B;AAAA,QACxB;AAAA,QACA,gBAAgB;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACL;AAAA,EACF;AAGA,SAAO;AACT;;;AG5LO,SAAS,2BAId;AAAA,EACA;AAAA,EACA;AACF,GAGuD;AACrD,SAAO,OAAO,OAAO,sBAAsB,EAAE,YAAY,CAAC,CAAC;AAC7D;;;ACvCA;AAAA,EACE;AAAA,OAIK;AAyCP,IAAM,uBAAuB,MAAM,CAAC,YAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYtD,MAAM,2BAAmE;AACvE,UAAM,gBAAgB;AAOtB,WAAO,MAAM,cAAc,QAAQ;AAAA,MACjC,QAAQ;AAAA,MACR,QAAQ,CAAC;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAoDO,SAAS,0BAKd,QACmD;AAEnD,QAAM,oBAAoB,oBAAoB,MAAM;AAGpD,SAAO,kBAAkB;AAAA,IACvB,qBAAqB;AAAA,EACvB;AACF;","names":["concat","signMessage","signTypedData","getStubSignature","concat","signDelegation","signUserOperation"]}
1
+ {"version":3,"sources":["../src/toMetaMaskSmartAccount.ts","../src/signer.ts","../src/signatures.ts","../src/actions/caveatEnforcerClient.ts","../src/actions/infuraBundlerClient.ts"],"sourcesContent":["import {\n EIP7702StatelessDeleGator,\n HybridDeleGator,\n MultiSigDeleGator,\n} from '@metamask/delegation-abis';\nimport { type Address, type Hex } from 'viem';\nimport {\n entryPoint07Abi,\n toPackedUserOperation,\n toSmartAccount,\n} from 'viem/account-abstraction';\n\nimport { isValid7702Implementation } from './actions/isValid7702Implementation';\nimport { Implementation } from './constants';\nimport { getCounterfactualAccountData } from './counterfactualAccountData';\nimport {\n SIGNABLE_DELEGATION_TYPED_DATA,\n toDelegationStruct,\n} from './delegation';\nimport { entryPointGetNonce as _getNonce } from './DelegationFramework/EntryPoint/read';\nimport { encodeCallsForCaller } from './encodeCalls';\nimport { resolveSigner } from './signer';\nimport { getSmartAccountsEnvironment } from './smartAccountsEnvironment';\nimport type {\n Call,\n ToMetaMaskSmartAccountParameters,\n ToMetaMaskSmartAccountReturnType,\n SignDelegationParams,\n SignUserOperationParams,\n AbiByImplementation,\n} from './types';\nimport { SIGNABLE_USER_OP_TYPED_DATA } from './userOp';\n\nconst ENTRYPOINT_VERSION = '0.7' as const;\n\n/**\n * Creates a MetaMask DeleGator smart account instance.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @param params - The parameters for creating the smart account.\n * @returns A promise that resolves to a MetaMaskSmartAccount instance.\n * @description\n * This function sets up a MetaMask DeleGator smart account with the specified implementation.\n * It handles both deployed accounts, and counterfactual accounts.\n * A caller may specify a SmartAccountsEnvironment, otherwise the environment will be inferred from the chain.\n */\nexport async function toMetaMaskSmartAccount<\n TImplementation extends Implementation,\n>(\n params: ToMetaMaskSmartAccountParameters<TImplementation>,\n): Promise<ToMetaMaskSmartAccountReturnType<TImplementation>> {\n const {\n client,\n client: { chain },\n implementation,\n } = params;\n\n if (!chain) {\n throw new Error('Chain not specified');\n }\n\n const signer = resolveSigner({\n implementation,\n signer: params.signer,\n });\n\n const environment =\n params.environment ?? getSmartAccountsEnvironment(chain.id);\n\n let address: Address, factoryData: Hex | undefined;\n\n if (params.address) {\n factoryData = undefined;\n address = params.address;\n } else {\n if (implementation === Implementation.Stateless7702) {\n throw new Error('Stateless7702 does not support counterfactual accounts');\n }\n\n const accountData = await getCounterfactualAccountData({\n factory: environment.SimpleFactory,\n implementations: environment.implementations,\n implementation,\n deployParams: params.deployParams,\n deploySalt: params.deploySalt,\n });\n\n address = accountData.address;\n factoryData = accountData.factoryData;\n }\n\n const entryPoint = {\n abi: entryPoint07Abi,\n address: environment.EntryPoint,\n version: ENTRYPOINT_VERSION,\n } as const;\n\n const { abi, contractName } = {\n [Implementation.Hybrid]: {\n contractName: 'HybridDeleGator',\n abi: HybridDeleGator,\n },\n [Implementation.MultiSig]: {\n contractName: 'MultiSigDeleGator',\n abi: MultiSigDeleGator,\n },\n [Implementation.Stateless7702]: {\n contractName: 'EIP7702StatelessDeleGator',\n abi: EIP7702StatelessDeleGator,\n },\n }[implementation] as {\n contractName: string;\n abi: AbiByImplementation[TImplementation];\n };\n\n const getFactoryArgs = async () => {\n if (factoryData === undefined) {\n throw new Error(\n 'Deploy params were not provided, so factory args cannot be inferred',\n );\n }\n return {\n factoryData,\n factory: environment.SimpleFactory,\n };\n };\n\n const signDelegation = async (delegationParams: SignDelegationParams) => {\n if (!signer) {\n throw new Error(\n 'Cannot sign delegation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n }\n\n const { delegation, chainId } = delegationParams;\n\n const delegationStruct = toDelegationStruct({\n ...delegation,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: 'DelegationManager',\n version: '1',\n verifyingContract: environment.DelegationManager,\n },\n types: SIGNABLE_DELEGATION_TYPED_DATA,\n primaryType: 'Delegation',\n message: delegationStruct,\n });\n\n return signature;\n };\n\n const signUserOperation = async (userOpParams: SignUserOperationParams) => {\n if (!signer) {\n throw new Error(\n 'Cannot sign user operation: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n }\n\n const { chainId } = userOpParams;\n\n const packedUserOp = toPackedUserOperation({\n sender: address,\n ...userOpParams,\n signature: '0x',\n });\n\n const signature = await signer.signTypedData({\n domain: {\n chainId: chainId ?? chain.id,\n name: contractName,\n version: '1',\n verifyingContract: address,\n },\n types: SIGNABLE_USER_OP_TYPED_DATA,\n primaryType: 'PackedUserOperation',\n message: { ...packedUserOp, entryPoint: entryPoint.address },\n });\n\n return signature;\n };\n\n const getAddress = async () => address;\n\n const getNonce = async () =>\n _getNonce({\n client,\n entryPoint: environment.EntryPoint,\n contractAddress: address,\n key: 0n,\n });\n\n const encodeCalls = async (calls: readonly Call[]) =>\n encodeCallsForCaller(address, calls);\n\n const signerMethods = signer ?? {\n signMessage: async () => {\n throw new Error(\n 'Cannot sign message: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n signTypedData: async () => {\n throw new Error(\n 'Cannot sign typed data: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n getStubSignature: async () => {\n throw new Error(\n 'Cannot get stub signature: signer not provided. Specify a signer in toMetaMaskSmartAccount() to perform signing operations.',\n );\n },\n };\n\n const smartAccount = await toSmartAccount({\n abi,\n client,\n entryPoint,\n environment,\n getAddress,\n getFactoryArgs,\n encodeCalls,\n getNonce,\n signUserOperation,\n signDelegation,\n ...signerMethods,\n });\n\n // Override isDeployed only for EIP-7702 implementation to check proper delegation code\n if (implementation === Implementation.Stateless7702) {\n return {\n ...smartAccount,\n isDeployed: async () =>\n isValid7702Implementation({\n client,\n accountAddress: address,\n environment,\n }),\n };\n }\n\n // For other implementations, use the default isDeployed behavior\n return smartAccount;\n}\n","import { concat } from 'viem';\nimport type {\n Address,\n SignableMessage,\n TypedData,\n TypedDataDefinition,\n} from 'viem';\nimport type { WebAuthnAccount } from 'viem/account-abstraction';\n\nimport { Implementation } from './constants';\nimport { aggregateSignature } from './signatures';\nimport type {\n AccountSignerConfig,\n HybridSignerConfig,\n InternalSigner,\n MultiSigSignerConfig,\n SignerConfigByImplementation,\n Stateless7702SignerConfig,\n WalletSignerConfig,\n} from './types';\nimport {\n createDummyWebAuthnSignature,\n encodeDeleGatorSignature,\n} from './webAuthn';\n\n// A valid ECDSA signature, this must be able to ecrecover an address, otherwise the contracts will revert in isValidSignature\nconst EOA_STUB_SIGNATURE =\n '0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000011b' as const;\n\nconst resolveSignerFromWalletConfig = (\n config: WalletSignerConfig,\n): InternalSigner => {\n return {\n signMessage: config.walletClient.signMessage,\n signTypedData: async (typedData) => {\n // todo: figure out this type so that we don't need the type assertion\n return config.walletClient.signTypedData(typedData as any);\n },\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveSignerFromAccountConfig = (config: AccountSignerConfig) => {\n return {\n signMessage: config.account.signMessage,\n signTypedData: config.account.signTypedData,\n getStubSignature: async () => EOA_STUB_SIGNATURE,\n };\n};\n\nconst resolveHybridSigner = (config: HybridSignerConfig): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n const { keyId, webAuthnAccount } = config;\n\n if (webAuthnAccount.type !== 'webAuthn') {\n throw new Error('Account is not a webAuthn account');\n }\n\n const encodeSignature = (\n result: Awaited<ReturnType<WebAuthnAccount['signMessage']>>,\n ) =>\n encodeDeleGatorSignature(\n keyId,\n result.signature,\n result.webauthn.clientDataJSON,\n result.webauthn.authenticatorData,\n );\n\n const signMessage = async (args: { message: SignableMessage }) =>\n webAuthnAccount.signMessage(args).then(encodeSignature);\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => webAuthnAccount.signTypedData(typedDataDefinition).then(encodeSignature);\n\n const getStubSignature = async () => createDummyWebAuthnSignature(keyId);\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveMultiSigSigner = (\n config: MultiSigSignerConfig,\n): InternalSigner => {\n const resolvedSigners = config.map((signer) => {\n let individualSignMessage: InternalSigner['signMessage'];\n let individualSignTypedData: InternalSigner['signTypedData'];\n let address: Address;\n if ('walletClient' in signer) {\n const { signMessage, signTypedData } =\n resolveSignerFromWalletConfig(signer);\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.walletClient.account.address;\n } else {\n const { signMessage, signTypedData } =\n resolveSignerFromAccountConfig(signer);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n individualSignMessage = signMessage;\n individualSignTypedData = signTypedData;\n\n address = signer.account.address;\n }\n return {\n address,\n individualSignMessage,\n individualSignTypedData,\n };\n });\n\n const signMessage = async (args: { message: SignableMessage }) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignMessage, address }) => ({\n signature: await individualSignMessage(args),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const signTypedData = async <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | 'EIP712Domain' = keyof TTypedData,\n >(\n typedDataDefinition: TypedDataDefinition<TTypedData, TPrimaryType>,\n ) => {\n const addressAndSignatures = resolvedSigners.map(\n async ({ individualSignTypedData, address }) => ({\n signature: await individualSignTypedData(typedDataDefinition),\n signer: address,\n type: 'ECDSA' as const,\n }),\n );\n\n const signatures = await Promise.all(addressAndSignatures);\n\n return aggregateSignature({\n signatures,\n });\n };\n\n const getStubSignature = async () =>\n concat(resolvedSigners.map(() => EOA_STUB_SIGNATURE));\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n};\n\nconst resolveStateless7702Signer = (\n config: Stateless7702SignerConfig,\n): InternalSigner => {\n if ('walletClient' in config) {\n return resolveSignerFromWalletConfig(config);\n } else if ('account' in config) {\n const { signMessage, signTypedData, getStubSignature } =\n resolveSignerFromAccountConfig(config);\n if (!signMessage) {\n throw new Error('Account does not support signMessage');\n }\n if (!signTypedData) {\n throw new Error('Account does not support signTypedData');\n }\n\n return {\n signMessage,\n signTypedData,\n getStubSignature,\n };\n }\n\n throw new Error('Invalid signer config');\n};\n\n/**\n * Resolve a signer from a configuration object.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner;\n\n/**\n * Resolve a signer from a configuration object. If no signer is provided, return null.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer or null if no signer is provided.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer?: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner | null;\n\n/**\n * Resolve a signer from a configuration object. If no signer is provided, return null.\n *\n * @param config - The configuration object.\n * @param config.implementation - The implementation type.\n * @param config.signer - The signer configuration object.\n * @returns The resolved signer or null if no signer is provided.\n */\nexport function resolveSigner<TImplementation extends Implementation>(config: {\n implementation: TImplementation;\n signer?: SignerConfigByImplementation<TImplementation>;\n}): InternalSigner | null {\n const { implementation, signer } = config;\n\n if (!signer) {\n return null;\n }\n\n if (implementation === Implementation.Hybrid) {\n return resolveHybridSigner(signer as HybridSignerConfig);\n } else if (implementation === Implementation.MultiSig) {\n return resolveMultiSigSigner(signer as MultiSigSignerConfig);\n } else if (implementation === Implementation.Stateless7702) {\n return resolveStateless7702Signer(signer as Stateless7702SignerConfig);\n }\n throw new Error(`Implementation type '${implementation}' not supported`);\n}\n","import type { Address, Hex } from 'viem';\nimport { concat } from 'viem';\n\nconst signatureTypes = ['ECDSA'] as const;\n\nexport type SignatureType = (typeof signatureTypes)[number];\n\n/**\n * Represents a partial signature that can be aggregated with others.\n */\nexport type PartialSignature = {\n signer: Address;\n signature: Hex;\n type: SignatureType;\n};\n\n/**\n * Aggregates signatures into a single signature as expected by the MultiSig implementation.\n *\n * @param params - The parameters for signature aggregation.\n * @param params.signatures - The array of partial signatures to aggregate.\n * @returns The aggregated signature.\n */\nexport const aggregateSignature = ({\n signatures,\n}: {\n signatures: PartialSignature[];\n}): Hex => {\n if (signatures.length === 0) {\n return '0x';\n }\n\n for (const { type } of signatures) {\n if (!signatureTypes.includes(type)) {\n throw new Error(`Invalid signature type: ${type}`);\n }\n }\n\n // Sort signatures by signer address as required by MultiSig implementation\n const sortedSignatures = [...signatures].sort((a, b) =>\n a.signer.localeCompare(b.signer),\n );\n\n // Concatenate all signatures\n return concat(sortedSignatures.map(({ signature }) => signature));\n};\n\n/**\n * Type definition for the aggregateSignature function parameters.\n */\nexport type AggregateSignatureParams = {\n signatures: PartialSignature[];\n};\n","import type { Client, Transport, Chain, Account } from 'viem';\n\nimport type { SmartAccountsEnvironment } from '../types';\nimport {\n caveatEnforcerActions,\n type CaveatEnforcerParams,\n type PeriodTransferResult,\n type StreamingResult,\n} from './getCaveatAvailableAmount';\n\n/**\n * Type for client extended with caveat enforcer actions.\n */\nexport type CaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n> = Client<TTransport, TChain, TAccount> &\n ReturnType<ReturnType<typeof caveatEnforcerActions>>;\n\n/**\n * Create a viem client extended with caveat enforcer actions.\n *\n * @param params - The parameters object.\n * @param params.client - The viem client.\n * @param params.environment - The SmartAccountsEnvironment.\n * @returns The extended client with caveat enforcer actions.\n */\nexport function createCaveatEnforcerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends Account | undefined = Account | undefined,\n>({\n client,\n environment,\n}: {\n client: Client<TTransport, TChain, TAccount>;\n environment: SmartAccountsEnvironment;\n}): CaveatEnforcerClient<TTransport, TChain, TAccount> {\n return client.extend(caveatEnforcerActions({ environment }));\n}\n\n// Re-export types for convenience\nexport type { CaveatEnforcerParams, PeriodTransferResult, StreamingResult };\n","import type { Transport, Chain, Hex, Client, Account } from 'viem';\nimport {\n createBundlerClient,\n type BundlerClient,\n type BundlerClientConfig,\n type SmartAccount,\n} from 'viem/account-abstraction';\n\n/**\n * Gas price tiers returned by pimlico_getUserOperationGasPrice\n */\nexport type GasPriceTier = {\n /** Maximum fee per gas in hex format */\n maxFeePerGas: Hex;\n /** Maximum priority fee per gas in hex format */\n maxPriorityFeePerGas: Hex;\n};\n\n/**\n * Response from pimlico_getUserOperationGasPrice RPC method\n */\nexport type UserOperationGasPriceResponse = {\n /** Slow gas price tier */\n slow: GasPriceTier;\n /** Standard gas price tier */\n standard: GasPriceTier;\n /** Fast gas price tier */\n fast: GasPriceTier;\n};\n\n/**\n * Pimlico bundler schema for type-safe RPC method calls\n */\n/* eslint-disable @typescript-eslint/naming-convention */\ntype PimlicoBundlerSchema = [\n {\n Method: 'pimlico_getUserOperationGasPrice';\n Parameters: [];\n ReturnType: UserOperationGasPriceResponse;\n },\n];\n\n/**\n * Infura bundler actions for extending bundler clients.\n *\n * @returns A function that takes a client and returns the client extension with Infura bundler actions.\n */\nconst infuraBundlerActions = () => (client: Client) => ({\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n * @example\n * ```typescript\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * console.log(gasPrices.standard.maxFeePerGas);\n * ```\n */\n async getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse> {\n const pimlicoClient = client as Client<\n Transport,\n Chain | undefined,\n Account | undefined,\n PimlicoBundlerSchema\n >;\n\n return await pimlicoClient.request({\n method: 'pimlico_getUserOperationGasPrice',\n params: [],\n });\n },\n});\n\n/**\n * Type for bundler client extended with Infura bundler actions.\n */\nexport type InfuraBundlerClient<\n TTransport extends Transport = Transport,\n TChain extends Chain | undefined = Chain | undefined,\n TAccount extends SmartAccount | undefined = SmartAccount | undefined,\n> = BundlerClient<TTransport, TChain, TAccount> & {\n /**\n * Get user operation gas prices from Infura bundler.\n * Calls the pimlico_getUserOperationGasPrice RPC method.\n *\n * @returns Promise resolving to gas price tiers (slow, standard, fast).\n */\n getUserOperationGasPrice(): Promise<UserOperationGasPriceResponse>;\n};\n\n/**\n * Creates an Infura bundler client extended with Infura bundler actions.\n *\n * This is a wrapper around viem's createBundlerClient that extends it with\n * the getUserOperationGasPrice method for retrieving gas prices from Pimlico's\n * bundler infrastructure via Infura's proxy.\n *\n * @param config - Configuration for the bundler client.\n * @returns Extended bundler client with Infura bundler actions.\n * @example\n * ```typescript\n * import { createPublicClient, http } from 'viem';\n * import { sepolia } from 'viem/chains';\n * import { createInfuraBundlerClient } from '@metamask/smart-accounts-kit';\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * });\n *\n * const bundlerClient = createInfuraBundlerClient({\n * client: publicClient,\n * transport: http('https://sepolia.infura.io/v3/YOUR_API_KEY'),\n * chain: sepolia,\n * });\n *\n * // Use standard bundler methods\n * const userOpHash = await bundlerClient.sendUserOperation({...});\n *\n * // Use Infura specific methods\n * const gasPrices = await bundlerClient.getUserOperationGasPrice();\n * ```\n */\nexport function createInfuraBundlerClient<\n TTransport extends Transport,\n TChain extends Chain | undefined = undefined,\n TAccount extends SmartAccount | undefined = undefined,\n>(\n config: BundlerClientConfig<TTransport, TChain, TAccount>,\n): InfuraBundlerClient<TTransport, TChain, TAccount> {\n // Create the base bundler client using viem's function\n const baseBundlerClient = createBundlerClient(config);\n\n // Extend the client with Infura bundler actions\n return baseBundlerClient.extend(\n infuraBundlerActions(),\n ) as unknown as InfuraBundlerClient<TTransport, TChain, TAccount>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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;AAAA;AAAA;AAAA;AAAA,EAYtD,MAAM,2BAAmE;AACvE,UAAM,gBAAgB;AAOtB,WAAO,MAAM,cAAc,QAAQ;AAAA,MACjC,QAAQ;AAAA,MACR,QAAQ,CAAC;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAoDO,SAAS,0BAKd,QACmD;AAEnD,QAAM,oBAAoB,oBAAoB,MAAM;AAGpD,SAAO,kBAAkB;AAAA,IACvB,qBAAqB;AAAA,EACvB;AACF;","names":["concat","signMessage","signTypedData","getStubSignature","concat","signDelegation","signUserOperation"]}
@@ -1,5 +1,5 @@
1
1
  import { WalletClient, PublicClient, Chain, Hex } from 'viem';
2
- import { S as SmartAccountsEnvironment } from './types-BLYWtcR3.cjs';
2
+ import { S as SmartAccountsEnvironment } from './types-qdEHxd5Q.cjs';
3
3
 
4
4
  type SupportedVersion = '1.0.0' | '1.1.0' | '1.2.0' | '1.3.0';
5
5
  declare const PREFERRED_VERSION: SupportedVersion;
@@ -1,5 +1,5 @@
1
1
  import { WalletClient, PublicClient, Chain, Hex } from 'viem';
2
- import { S as SmartAccountsEnvironment } from './types-BLYWtcR3.js';
2
+ import { S as SmartAccountsEnvironment } from './types-qdEHxd5Q.js';
3
3
 
4
4
  type SupportedVersion = '1.0.0' | '1.1.0' | '1.2.0' | '1.3.0';
5
5
  declare const PREFERRED_VERSION: SupportedVersion;
@@ -102,7 +102,7 @@ type DeployParams<TImplementation extends Implementation> = {
102
102
  type ToMetaMaskSmartAccountParameters<TImplementation extends Implementation> = {
103
103
  client: PublicClient;
104
104
  implementation: TImplementation;
105
- signer: SignerConfigByImplementation<TImplementation>;
105
+ signer?: SignerConfigByImplementation<TImplementation>;
106
106
  environment?: SmartAccountsEnvironment;
107
107
  } & OneOf<{
108
108
  deployParams: DeployParams<TImplementation>;
@@ -102,7 +102,7 @@ type DeployParams<TImplementation extends Implementation> = {
102
102
  type ToMetaMaskSmartAccountParameters<TImplementation extends Implementation> = {
103
103
  client: PublicClient;
104
104
  implementation: TImplementation;
105
- signer: SignerConfigByImplementation<TImplementation>;
105
+ signer?: SignerConfigByImplementation<TImplementation>;
106
106
  environment?: SmartAccountsEnvironment;
107
107
  } & OneOf<{
108
108
  deployParams: DeployParams<TImplementation>;
@@ -3,7 +3,7 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkDLD377CNcjs = require('../chunk-DLD377CN.cjs');
6
+ var _chunkBYWRJGSKcjs = require('../chunk-BYWRJGSK.cjs');
7
7
 
8
8
 
9
9
 
@@ -58,5 +58,5 @@ var _chunkYDLLC6PPcjs = require('../chunk-YDLLC6PP.cjs');
58
58
 
59
59
 
60
60
 
61
- exports.CaveatBuilder = _chunkYDLLC6PPcjs.CaveatBuilder; exports.DELEGATION_ABI_TYPE = _chunkYDLLC6PPcjs.DELEGATION_ABI_TYPE; exports.DELEGATION_ABI_TYPE_COMPONENTS = _chunkYDLLC6PPcjs.DELEGATION_ABI_TYPE_COMPONENTS; exports.DELEGATION_ARRAY_ABI_TYPE = _chunkYDLLC6PPcjs.DELEGATION_ARRAY_ABI_TYPE; exports.DELEGATION_TYPEHASH = _chunkYDLLC6PPcjs.DELEGATION_TYPEHASH; exports.SIGNABLE_DELEGATION_TYPED_DATA = _chunkYDLLC6PPcjs.SIGNABLE_DELEGATION_TYPED_DATA; exports.SIGNABLE_USER_OP_TYPED_DATA = _chunkSOFB2MXGcjs.SIGNABLE_USER_OP_TYPED_DATA; exports.SIGNATURE_ABI_PARAMS = _chunkDLD377CNcjs.SIGNATURE_ABI_PARAMS; exports.createCaveatBuilder = _chunkYDLLC6PPcjs.createCaveatBuilder; exports.decodeDelegation = _chunkYDLLC6PPcjs.decodeDelegation; exports.decodeDelegations = _chunkYDLLC6PPcjs.decodeDelegations; exports.deploySmartAccountsEnvironment = _chunkSOFB2MXGcjs.deploySmartAccountsEnvironment; exports.encodeBatchExecution = _chunkVLKX4BR6cjs.encodeBatchExecution; exports.encodeCalls = _chunkDLD377CNcjs.encodeCalls; exports.encodeCallsForCaller = _chunkDLD377CNcjs.encodeCallsForCaller; exports.encodeDelegation = _chunkYDLLC6PPcjs.encodeDelegation; exports.encodeDelegations = _chunkYDLLC6PPcjs.encodeDelegations; exports.encodeExecutionCalldata = _chunkVLKX4BR6cjs.encodeExecutionCalldata; exports.encodeExecutionCalldatas = _chunkVLKX4BR6cjs.encodeExecutionCalldatas; exports.encodeSingleExecution = _chunkVLKX4BR6cjs.encodeSingleExecution; exports.getCounterfactualAccountData = _chunkDLD377CNcjs.getCounterfactualAccountData; exports.hashDelegation = _chunkYDLLC6PPcjs.hashDelegation; exports.overrideDeployedEnvironment = _chunkSOFB2MXGcjs.overrideDeployedEnvironment; exports.toDelegation = _chunkYDLLC6PPcjs.toDelegation; exports.toDelegationStruct = _chunkYDLLC6PPcjs.toDelegationStruct;
61
+ exports.CaveatBuilder = _chunkYDLLC6PPcjs.CaveatBuilder; exports.DELEGATION_ABI_TYPE = _chunkYDLLC6PPcjs.DELEGATION_ABI_TYPE; exports.DELEGATION_ABI_TYPE_COMPONENTS = _chunkYDLLC6PPcjs.DELEGATION_ABI_TYPE_COMPONENTS; exports.DELEGATION_ARRAY_ABI_TYPE = _chunkYDLLC6PPcjs.DELEGATION_ARRAY_ABI_TYPE; exports.DELEGATION_TYPEHASH = _chunkYDLLC6PPcjs.DELEGATION_TYPEHASH; exports.SIGNABLE_DELEGATION_TYPED_DATA = _chunkYDLLC6PPcjs.SIGNABLE_DELEGATION_TYPED_DATA; exports.SIGNABLE_USER_OP_TYPED_DATA = _chunkSOFB2MXGcjs.SIGNABLE_USER_OP_TYPED_DATA; exports.SIGNATURE_ABI_PARAMS = _chunkBYWRJGSKcjs.SIGNATURE_ABI_PARAMS; exports.createCaveatBuilder = _chunkYDLLC6PPcjs.createCaveatBuilder; exports.decodeDelegation = _chunkYDLLC6PPcjs.decodeDelegation; exports.decodeDelegations = _chunkYDLLC6PPcjs.decodeDelegations; exports.deploySmartAccountsEnvironment = _chunkSOFB2MXGcjs.deploySmartAccountsEnvironment; exports.encodeBatchExecution = _chunkVLKX4BR6cjs.encodeBatchExecution; exports.encodeCalls = _chunkBYWRJGSKcjs.encodeCalls; exports.encodeCallsForCaller = _chunkBYWRJGSKcjs.encodeCallsForCaller; exports.encodeDelegation = _chunkYDLLC6PPcjs.encodeDelegation; exports.encodeDelegations = _chunkYDLLC6PPcjs.encodeDelegations; exports.encodeExecutionCalldata = _chunkVLKX4BR6cjs.encodeExecutionCalldata; exports.encodeExecutionCalldatas = _chunkVLKX4BR6cjs.encodeExecutionCalldatas; exports.encodeSingleExecution = _chunkVLKX4BR6cjs.encodeSingleExecution; exports.getCounterfactualAccountData = _chunkBYWRJGSKcjs.getCounterfactualAccountData; exports.hashDelegation = _chunkYDLLC6PPcjs.hashDelegation; exports.overrideDeployedEnvironment = _chunkSOFB2MXGcjs.overrideDeployedEnvironment; exports.toDelegation = _chunkYDLLC6PPcjs.toDelegation; exports.toDelegationStruct = _chunkYDLLC6PPcjs.toDelegationStruct;
62
62
  //# sourceMappingURL=index.cjs.map
@@ -1,8 +1,8 @@
1
- export { z as CaveatBuilder, x as CaveatBuilderConfig, w as CoreCaveatBuilder, m as DELEGATION_ABI_TYPE, n as DELEGATION_ABI_TYPE_COMPONENTS, D as DELEGATION_ARRAY_ABI_TYPE, p as DelegationStruct, e as ExecutionStruct, S as SIGNABLE_DELEGATION_TYPED_DATA, y as createCaveatBuilder, k as decodeDelegation, i as decodeDelegations, v as encodeBatchExecution, j as encodeDelegation, h as encodeDelegations, q as encodeExecutionCalldata, r as encodeExecutionCalldatas, u as encodeSingleExecution, o as hashDelegation, l as toDelegation, t as toDelegationStruct } from '../delegation-D_TY-tAq.cjs';
1
+ export { z as CaveatBuilder, x as CaveatBuilderConfig, w as CoreCaveatBuilder, m as DELEGATION_ABI_TYPE, n as DELEGATION_ABI_TYPE_COMPONENTS, D as DELEGATION_ARRAY_ABI_TYPE, p as DelegationStruct, e as ExecutionStruct, S as SIGNABLE_DELEGATION_TYPED_DATA, y as createCaveatBuilder, k as decodeDelegation, i as decodeDelegations, v as encodeBatchExecution, j as encodeDelegation, h as encodeDelegations, q as encodeExecutionCalldata, r as encodeExecutionCalldatas, u as encodeSingleExecution, o as hashDelegation, l as toDelegation, t as toDelegationStruct } from '../delegation-DIriDFkq.cjs';
2
2
  export { S as SIGNABLE_USER_OP_TYPED_DATA } from '../userOp-DKgjzz7B.cjs';
3
3
  import { Address, Hex } from 'viem';
4
- import { l as Call, I as Implementation, S as SmartAccountsEnvironment, m as DeployParams } from '../types-BLYWtcR3.cjs';
5
- export { d as deploySmartAccountsEnvironment, o as overrideDeployedEnvironment } from '../smartAccountsEnvironment-BU8kjlEv.cjs';
4
+ import { l as Call, I as Implementation, S as SmartAccountsEnvironment, m as DeployParams } from '../types-qdEHxd5Q.cjs';
5
+ export { d as deploySmartAccountsEnvironment, o as overrideDeployedEnvironment } from '../smartAccountsEnvironment-Czw9KUYZ.cjs';
6
6
  export { DELEGATION_TYPEHASH } from '@metamask/delegation-core';
7
7
  import '@metamask/delegation-abis';
8
8
  import 'viem/account-abstraction';
@@ -1,8 +1,8 @@
1
- export { z as CaveatBuilder, x as CaveatBuilderConfig, w as CoreCaveatBuilder, m as DELEGATION_ABI_TYPE, n as DELEGATION_ABI_TYPE_COMPONENTS, D as DELEGATION_ARRAY_ABI_TYPE, p as DelegationStruct, e as ExecutionStruct, S as SIGNABLE_DELEGATION_TYPED_DATA, y as createCaveatBuilder, k as decodeDelegation, i as decodeDelegations, v as encodeBatchExecution, j as encodeDelegation, h as encodeDelegations, q as encodeExecutionCalldata, r as encodeExecutionCalldatas, u as encodeSingleExecution, o as hashDelegation, l as toDelegation, t as toDelegationStruct } from '../delegation-DGUfyX-C.js';
1
+ export { z as CaveatBuilder, x as CaveatBuilderConfig, w as CoreCaveatBuilder, m as DELEGATION_ABI_TYPE, n as DELEGATION_ABI_TYPE_COMPONENTS, D as DELEGATION_ARRAY_ABI_TYPE, p as DelegationStruct, e as ExecutionStruct, S as SIGNABLE_DELEGATION_TYPED_DATA, y as createCaveatBuilder, k as decodeDelegation, i as decodeDelegations, v as encodeBatchExecution, j as encodeDelegation, h as encodeDelegations, q as encodeExecutionCalldata, r as encodeExecutionCalldatas, u as encodeSingleExecution, o as hashDelegation, l as toDelegation, t as toDelegationStruct } from '../delegation-CvVXs0PO.js';
2
2
  export { S as SIGNABLE_USER_OP_TYPED_DATA } from '../userOp-DKgjzz7B.js';
3
3
  import { Address, Hex } from 'viem';
4
- import { l as Call, I as Implementation, S as SmartAccountsEnvironment, m as DeployParams } from '../types-BLYWtcR3.js';
5
- export { d as deploySmartAccountsEnvironment, o as overrideDeployedEnvironment } from '../smartAccountsEnvironment-egxuflDO.js';
4
+ import { l as Call, I as Implementation, S as SmartAccountsEnvironment, m as DeployParams } from '../types-qdEHxd5Q.js';
5
+ export { d as deploySmartAccountsEnvironment, o as overrideDeployedEnvironment } from '../smartAccountsEnvironment-u1CcFcGE.js';
6
6
  export { DELEGATION_TYPEHASH } from '@metamask/delegation-core';
7
7
  import '@metamask/delegation-abis';
8
8
  import 'viem/account-abstraction';
@@ -3,7 +3,7 @@ import {
3
3
  encodeCalls,
4
4
  encodeCallsForCaller,
5
5
  getCounterfactualAccountData
6
- } from "../chunk-WPVSFOQM.mjs";
6
+ } from "../chunk-45GHWVQA.mjs";
7
7
  import {
8
8
  SIGNABLE_USER_OP_TYPED_DATA,
9
9
  deploySmartAccountsEnvironment,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/smart-accounts-kit",
3
- "version": "0.4.0-beta.2",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
5
  "description": "Toolkit for managing and interacting with MetaMask Smart Accounts, built on Viem",
6
6
  "license": "(MIT-0 OR Apache-2.0)",
@@ -125,11 +125,11 @@
125
125
  },
126
126
  "dependencies": {
127
127
  "@metamask/7715-permission-types": "^0.5.0",
128
- "@metamask/delegation-abis": "^0.12.0-beta.0",
129
- "@metamask/delegation-core": "^0.4.0",
130
- "@metamask/delegation-deployments": "^0.17.0",
128
+ "@metamask/delegation-abis": "^1.0.0",
129
+ "@metamask/delegation-core": "^1.0.0",
130
+ "@metamask/delegation-deployments": "^1.0.0",
131
131
  "buffer": "^6.0.3",
132
- "webauthn-p256": "^0.0.10"
132
+ "ox": "0.8.1"
133
133
  },
134
134
  "devDependencies": {
135
135
  "@lavamoat/allow-scripts": "^3.4.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/smart-accounts-kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-DLD377CN.cjs","../src/counterfactualAccountData.ts","../src/encodeCalls.ts","../src/webAuthn.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACfA,4BAAwC;AA6BjC,IAAM,6BAAA,EAA+B,MAAA,CAE1C;AAAA,EACA,OAAA;AAAA,EACA,eAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA;AACF,CAAA,EAAA,GAMuD;AACrD,EAAA,IAAI,qBAAA;AACJ,EAAA,IAAI,QAAA;AAEJ,EAAA,OAAA,CAAQ,cAAA,EAAgB;AAAA,IACtB,KAAA,qBAAA,EAA4B;AAC1B,MAAA,MAAM,CAAC,KAAA,EAAO,MAAA,EAAQ,OAAA,EAAS,OAAO,EAAA,EACpC,YAAA;AAEF,MAAA,GAAA,CAAI,CAAC,eAAA,CAAgB,mBAAA,EAAqB;AACxC,QAAA,MAAM,IAAI,KAAA;AAAA,UACR;AAAA,QACF,CAAA;AAAA,MACF;AAEA,MAAA,sBAAA,EAAwB,eAAA,CAAgB,mBAAA;AAExC,MAAA,MAAM,WAAA,EAAa,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,EAAA,GAAU;AAC9C,QAAA,MAAM,OAAA,EAAS,OAAA,CAAQ,KAAK,CAAA;AAC5B,QAAA,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kit/smart-accounts-kit/packages/smart-accounts-kit/dist/chunk-DLD377CN.cjs","sourcesContent":[null,"import type { Address, Hex } from 'viem';\nimport { getContractAddress, pad } from 'viem';\n\nimport { Implementation } from './constants';\nimport { initializeHybridDeleGator } from './DelegationFramework/HybridDeleGator/encode';\nimport { initializeMultiSigDeleGator } from './DelegationFramework/MultiSigDeleGator/encode';\nimport { create2Deploy as encodeCreate2Deploy } from './DelegationFramework/SimpleFactory/encode';\nimport { encodeProxyCreationCode } from './DelegationFramework/utils';\nimport type {\n SmartAccountsEnvironment,\n HybridDeleGatorDeployParams,\n MultiSigDeleGatorDeployParams,\n DeployParams,\n} from './types';\n\n/**\n * Infers counterfactual account data for a DeleGator smart account.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @template TDeployParams - The type of deployment parameters, defaults to DeployParams<Implementation>.\n * @param options - The options for generating counterfactual account data.\n * @param options.factory - The address of the SimpleFactory contract.\n * @param options.implementations - The DeleGator implementation contracts.\n * @param options.implementation - The implementation type to use.\n * @param options.deployParams - The deployment parameters for the specified implementation.\n * @param options.deploySalt - The salt to use for CREATE2 address computation.\n * @returns An object containing the counterfactual address and factory calldata.\n * @description This function calculates the address a DeleGator contract would have if deployed,\n * and provides the calldata needed to deploy it.\n */\nexport const getCounterfactualAccountData = async <\n TImplementation extends Implementation,\n>({\n factory,\n implementations,\n implementation,\n deployParams,\n deploySalt,\n}: {\n factory: Address;\n implementations: SmartAccountsEnvironment['implementations'];\n implementation: TImplementation;\n deployParams: DeployParams<TImplementation>;\n deploySalt: Hex;\n}): Promise<{ factoryData: Hex; address: Address }> => {\n let implementationAddress: Address;\n let initcode: Hex;\n\n switch (implementation) {\n case Implementation.Hybrid: {\n const [owner, keyIds, xValues, yValues] =\n deployParams as HybridDeleGatorDeployParams;\n\n if (!implementations.HybridDeleGatorImpl) {\n throw new Error(\n 'HybridDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.HybridDeleGatorImpl;\n\n const p256Owners = keyIds.map((keyId, index) => {\n const xValue = xValues[index];\n const yValue = yValues[index];\n\n if (!xValue || !yValue) {\n throw new Error(\n `Missing X or Y value for keyId ${keyId} at index ${index}`,\n );\n }\n\n return {\n keyId,\n x: xValue,\n y: yValue,\n };\n });\n\n initcode = initializeHybridDeleGator({ eoaOwner: owner, p256Owners });\n break;\n }\n case Implementation.MultiSig: {\n const [owners, threshold] = deployParams as MultiSigDeleGatorDeployParams;\n\n if (!implementations.MultiSigDeleGatorImpl) {\n throw new Error(\n 'MultiSigDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.MultiSigDeleGatorImpl;\n initcode = initializeMultiSigDeleGator({ owners, threshold });\n break;\n }\n case Implementation.Stateless7702:\n default:\n throw new Error(`Implementation type '${implementation}' not supported`);\n }\n\n const salt = pad(deploySalt, { dir: 'left', size: 32 });\n\n const proxyCreationCode = encodeProxyCreationCode({\n implementationAddress,\n initcode,\n });\n\n const address = getContractAddress({\n bytecode: proxyCreationCode,\n from: factory,\n opcode: 'CREATE2',\n salt,\n });\n\n const factoryData = encodeCreate2Deploy(proxyCreationCode, salt);\n\n return {\n factoryData,\n address,\n };\n};\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport { encodeFunctionData } from 'viem';\nimport type { Address, Hex } from 'viem';\n\nimport type { DelegatedCall } from './actions/erc7710RedeemDelegationAction';\nimport { encodeDelegations } from './delegation';\nimport {\n execute,\n executeWithMode,\n} from './DelegationFramework/DeleGatorCore/encode';\nimport {\n ExecutionMode,\n createExecution,\n encodeExecutionCalldatas,\n} from './executions';\nimport type { Call } from './types';\n\n/**\n * Checks if a call is a delegated call by checking for the presence of permissionContext and delegationManager.\n *\n * @param call - The call to check.\n * @returns True if the call is a delegated call, false otherwise.\n */\nconst isDelegatedCall = (call: Call): call is DelegatedCall => {\n return 'permissionContext' in call && 'delegationManager' in call;\n};\n\n/**\n * If there's a single call with permissionContext and delegationManager,\n * processes it as a delegated call.\n *\n * @param call - The call to process.\n * @returns The execution object for the delegated call.\n * @description\n * This function creates an execution that calls redeemDelegations on the delegation manager.\n */\nconst processDelegatedCall = (call: DelegatedCall) => {\n const {\n permissionContext,\n delegationManager,\n to: target,\n value,\n data: callData,\n } = call;\n\n const callAsExecution = createExecution({ target, value, callData });\n\n if (!permissionContext) {\n return callAsExecution;\n }\n\n const encodedPermissionsContext = encodeDelegations(permissionContext);\n\n const redeemCalldata = encodeFunctionData({\n abi: DelegationManager,\n functionName: 'redeemDelegations',\n args: [\n [encodedPermissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([[callAsExecution]]),\n ],\n });\n\n return createExecution({\n target: delegationManager,\n callData: redeemCalldata,\n });\n};\n\n/**\n * If there's a single call, encode the shorthand `execute` function. Otherwise, encode the `executeWithMode` function. Execution type will always be \"default\".\n *\n * @param calls - The calls to execute.\n * @returns The encoded calldata for the DeleGator to execute the calls.\n * @description\n * This function supports both single and batch execution modes.\n * For single calls, it uses the gas-efficient execute function.\n */\nexport const encodeCalls = (calls: readonly Call[]) => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call && !isDelegatedCall(call)) {\n const { to: target, value, data: callData } = call;\n const execution = createExecution({ target, value, callData });\n return execute({ execution });\n }\n }\n\n const executions = calls.map((call) => {\n if (isDelegatedCall(call)) {\n return processDelegatedCall(call);\n }\n const { to: target, value, data: callData } = call;\n return createExecution({ target, value, callData });\n });\n\n const mode =\n calls.length === 1\n ? ExecutionMode.SingleDefault\n : ExecutionMode.BatchDefault;\n return executeWithMode({ mode, executions });\n};\n\n/**\n * Encodes calls for execution by a DeleGator smart contract.\n *\n * @param caller - The address of the DeleGator contract.\n * @param calls - An array of Call objects, each containing 'to', optional 'data', and optional 'value'.\n * @returns A promise that resolves to the encoded function data as a hexadecimal string.\n * @description\n * - If there's a single call directly to the delegator, it returns the call data directly.\n * - For multiple calls or calls to other addresses, it creates executions and encodes them for the DeleGator's execute function.\n * - The execution mode is set to ExecutionMode.SingleDefault for a single call, or ExecutionMode.BatchDefault for multiple calls.\n *\n * todo: This doesn't fully expose the flexibility of the DeleGator's execute function, but it's a start.\n * maybe we add a mechanism where individual calls passed to this function can be encoded batches.\n */\nexport const encodeCallsForCaller = async (\n caller: Address,\n calls: readonly Call[],\n): Promise<Hex> => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call?.to === caller && !isDelegatedCall(call)) {\n // if there's a single call, and it's to the delegator, we can just return the calldata directly.\n return call.data ?? '0x';\n }\n }\n return encodeCalls(calls);\n};\n","import {\n parseAbiParameters,\n encodeAbiParameters,\n type Hex,\n encodePacked,\n keccak256,\n concat,\n hexToBytes,\n} from 'viem';\nimport { parseSignature } from 'webauthn-p256';\n\nexport const FIELD_MODULUS =\n 115792089210356248762697446949407573529996955224135760342422259061068512044369n;\nexport const MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;\n\nexport const SIGNATURE_ABI_PARAMS = parseAbiParameters(\n 'bytes32, uint256, uint256, bytes, bool, string, string, uint256',\n);\n\n/**\n * This function is used to convert the client data returned from the\n * credentials API into a format that can be consumed by the DeleGator\n * contracts. We need the flattend JSON strings before and after the\n * userOpHash/challenge. This function provides those two client data string\n * slices.\n *\n * @param clientDataJson - The client data JSON string.\n * @returns Returns [clientDataJSONPrefix and clientDataJSONSuffix]\n * ClientDataJSONPrefix contains the client data till the challengeHash\n * ClientDataJSONSuffix contains the client data after the challengeHash.\n */\nexport const splitOnChallenge = (\n clientDataJson: string,\n): [clientDataJSONPrefix: string, clientDataJSONSuffix: string] => {\n /*\n CientData looks like this:\n {\n \"type\": \"webauthn.create\" | \"webauthn.get\",\n \"challenge\": \"{userOpHash}\",\n \"origin\": \"{Domain}\",\n \"crossOrigin\": boolean\n }\n */\n try {\n const { challenge } = JSON.parse(clientDataJson);\n if (challenge === undefined) {\n throw new Error('No \"challenge\" found in the input string');\n }\n return clientDataJson.split(challenge) as [string, string];\n } catch (error) {\n throw new Error('No \"challenge\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Returns the index of '\"type\":' in the ClientData.\n *\n * @param clientDataJson - Stringified ClientDataJSON.\n * @returns The index of '\"type\":' in the ClientData.\n */\nexport const getResponseTypeLocation = (clientDataJson: string): bigint => {\n try {\n // Find the index of the `\"type\":` key in the JSON string directly\n const typeIndex = clientDataJson.indexOf('\"type\":');\n\n if (typeIndex === -1) {\n throw new Error('No \"type\" found in the input string');\n }\n // Return the index of the `\"type\":` key\n return BigInt(typeIndex);\n } catch (error) {\n // Handle any errors that occur during the search\n throw new Error('No \"type\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Encodes a signature to a hexadecimal signature that will be accepted\n * by the DeleGator contracts.\n *\n * @param keyId - The key used for the signature, represented as a hexadecimal string.\n * @param signature - The signature to convert, as Hex.\n * @param clientDataJSON - The client data used in the creation of the signature.\n * @param authenticatorData - The authenticator data used in the creation of the signature.\n * @returns The signature as a valid DeleGator signature encoded as Hexadecimal string.\n */\nexport function encodeDeleGatorSignature(\n keyId: string,\n signature: Hex,\n clientDataJSON: string,\n authenticatorData: Hex,\n): Hex {\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n\n const parsedSignature = parseSignature(signature);\n\n let { s } = parsedSignature;\n\n while (s > MALLEABILITY_THRESHOLD) {\n s = FIELD_MODULUS - s;\n }\n\n const { r } = parsedSignature;\n\n const [clientDataComponent1, clientDataComponent2] =\n splitOnChallenge(clientDataJSON);\n\n const { userVerified } = parseAuthenticatorFlags(authenticatorData);\n\n const responseTypeLocation = getResponseTypeLocation(clientDataJSON);\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n r,\n s,\n authenticatorData,\n userVerified,\n clientDataComponent1,\n clientDataComponent2,\n responseTypeLocation,\n ]);\n return encodedSignature;\n}\n\nconst AUTHENTICATOR_DATA_FLAGS_OFFSET = 32;\n// We have all of the flag bits defined here for completeness, even though we only extract the userVerified flag.\nenum AuthenticatorDataFlagBitIndex {\n UserPresence = 0,\n UserVerified = 2,\n BackupEligibility = 3,\n BackupState = 4,\n AttestedCredentialData = 6,\n ExtensionData = 7,\n}\n\nexport type AuthenticatorFlags = {\n userVerified: boolean;\n};\n\n/**\n * Parses the authenticator data and returns an authenticator flags object with the `userVerified` flag.\n * See https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data.\n *\n * @param authenticatorData - The authenticator data to parse.\n * @returns An object representing the parsed authenticator flags.\n */\nexport function parseAuthenticatorFlags(\n authenticatorData: Hex,\n): AuthenticatorFlags {\n const authenticatorDataBuffer = hexToBytes(authenticatorData);\n const dataBufferUint8 = new Uint8Array(authenticatorDataBuffer);\n const flags = dataBufferUint8[AUTHENTICATOR_DATA_FLAGS_OFFSET];\n if (flags === undefined) {\n throw new Error('Authenticator flags not found in authenticator data');\n }\n\n // Bit 0 is the least significant bit in the flags byte, so we left shift 0b1 by the bit index\n // eslint-disable-next-line no-bitwise\n const bitMask = 0b1 << AuthenticatorDataFlagBitIndex.UserVerified;\n\n return {\n // eslint-disable-next-line no-bitwise\n userVerified: (flags & bitMask) !== 0x0,\n };\n}\n\n/**\n * Creates a dummy signature.\n * This must meet all early-failure conditions of the real signature, but does not need to be a valid signature.\n *\n * @param keyId - The key ID to use for the dummy signature.\n * @returns The encoded signature.\n */\nexport const createDummyWebAuthnSignature = (keyId: Hex) => {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#data_structure\n const rpIdHash = keccak256(encodePacked(['string'], ['AuthenticatorData']));\n const flags = '0x05';\n const signCount = '0x00000000';\n const authenticatorData = concat([rpIdHash, flags, signCount]);\n\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n const rs =\n 57896044605178124381348723474703786764998477612067880171211129530534256022184n;\n const userVerification = true;\n const clientDataPrefix = '{\"type\":\"webauthn.get\",\"challenge\":\"';\n const clientDataSuffix = '\",\"origin\":\"passkey-domain\",\"crossOrigin\":false}';\n const responseTypeLocation = 1n;\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rs,\n rs,\n authenticatorData,\n userVerification,\n clientDataPrefix,\n clientDataSuffix,\n responseTypeLocation,\n ]);\n\n return encodedSignature;\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/counterfactualAccountData.ts","../src/encodeCalls.ts","../src/webAuthn.ts"],"sourcesContent":["import type { Address, Hex } from 'viem';\nimport { getContractAddress, pad } from 'viem';\n\nimport { Implementation } from './constants';\nimport { initializeHybridDeleGator } from './DelegationFramework/HybridDeleGator/encode';\nimport { initializeMultiSigDeleGator } from './DelegationFramework/MultiSigDeleGator/encode';\nimport { create2Deploy as encodeCreate2Deploy } from './DelegationFramework/SimpleFactory/encode';\nimport { encodeProxyCreationCode } from './DelegationFramework/utils';\nimport type {\n SmartAccountsEnvironment,\n HybridDeleGatorDeployParams,\n MultiSigDeleGatorDeployParams,\n DeployParams,\n} from './types';\n\n/**\n * Infers counterfactual account data for a DeleGator smart account.\n *\n * @template TImplementation - The type of implementation, extending Implementation.\n * @template TDeployParams - The type of deployment parameters, defaults to DeployParams<Implementation>.\n * @param options - The options for generating counterfactual account data.\n * @param options.factory - The address of the SimpleFactory contract.\n * @param options.implementations - The DeleGator implementation contracts.\n * @param options.implementation - The implementation type to use.\n * @param options.deployParams - The deployment parameters for the specified implementation.\n * @param options.deploySalt - The salt to use for CREATE2 address computation.\n * @returns An object containing the counterfactual address and factory calldata.\n * @description This function calculates the address a DeleGator contract would have if deployed,\n * and provides the calldata needed to deploy it.\n */\nexport const getCounterfactualAccountData = async <\n TImplementation extends Implementation,\n>({\n factory,\n implementations,\n implementation,\n deployParams,\n deploySalt,\n}: {\n factory: Address;\n implementations: SmartAccountsEnvironment['implementations'];\n implementation: TImplementation;\n deployParams: DeployParams<TImplementation>;\n deploySalt: Hex;\n}): Promise<{ factoryData: Hex; address: Address }> => {\n let implementationAddress: Address;\n let initcode: Hex;\n\n switch (implementation) {\n case Implementation.Hybrid: {\n const [owner, keyIds, xValues, yValues] =\n deployParams as HybridDeleGatorDeployParams;\n\n if (!implementations.HybridDeleGatorImpl) {\n throw new Error(\n 'HybridDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.HybridDeleGatorImpl;\n\n const p256Owners = keyIds.map((keyId, index) => {\n const xValue = xValues[index];\n const yValue = yValues[index];\n\n if (!xValue || !yValue) {\n throw new Error(\n `Missing X or Y value for keyId ${keyId} at index ${index}`,\n );\n }\n\n return {\n keyId,\n x: xValue,\n y: yValue,\n };\n });\n\n initcode = initializeHybridDeleGator({ eoaOwner: owner, p256Owners });\n break;\n }\n case Implementation.MultiSig: {\n const [owners, threshold] = deployParams as MultiSigDeleGatorDeployParams;\n\n if (!implementations.MultiSigDeleGatorImpl) {\n throw new Error(\n 'MultiSigDeleGatorImpl address not provided in environment',\n );\n }\n\n implementationAddress = implementations.MultiSigDeleGatorImpl;\n initcode = initializeMultiSigDeleGator({ owners, threshold });\n break;\n }\n case Implementation.Stateless7702:\n default:\n throw new Error(`Implementation type '${implementation}' not supported`);\n }\n\n const salt = pad(deploySalt, { dir: 'left', size: 32 });\n\n const proxyCreationCode = encodeProxyCreationCode({\n implementationAddress,\n initcode,\n });\n\n const address = getContractAddress({\n bytecode: proxyCreationCode,\n from: factory,\n opcode: 'CREATE2',\n salt,\n });\n\n const factoryData = encodeCreate2Deploy(proxyCreationCode, salt);\n\n return {\n factoryData,\n address,\n };\n};\n","import { DelegationManager } from '@metamask/delegation-abis';\nimport { encodeFunctionData } from 'viem';\nimport type { Address, Hex } from 'viem';\n\nimport type { DelegatedCall } from './actions/erc7710RedeemDelegationAction';\nimport { encodeDelegations } from './delegation';\nimport {\n execute,\n executeWithMode,\n} from './DelegationFramework/DeleGatorCore/encode';\nimport {\n ExecutionMode,\n createExecution,\n encodeExecutionCalldatas,\n} from './executions';\nimport type { Call } from './types';\n\n/**\n * Checks if a call is a delegated call by checking for the presence of permissionContext and delegationManager.\n *\n * @param call - The call to check.\n * @returns True if the call is a delegated call, false otherwise.\n */\nconst isDelegatedCall = (call: Call): call is DelegatedCall => {\n return 'permissionContext' in call && 'delegationManager' in call;\n};\n\n/**\n * If there's a single call with permissionContext and delegationManager,\n * processes it as a delegated call.\n *\n * @param call - The call to process.\n * @returns The execution object for the delegated call.\n * @description\n * This function creates an execution that calls redeemDelegations on the delegation manager.\n */\nconst processDelegatedCall = (call: DelegatedCall) => {\n const {\n permissionContext,\n delegationManager,\n to: target,\n value,\n data: callData,\n } = call;\n\n const callAsExecution = createExecution({ target, value, callData });\n\n if (!permissionContext) {\n return callAsExecution;\n }\n\n const encodedPermissionsContext = encodeDelegations(permissionContext);\n\n const redeemCalldata = encodeFunctionData({\n abi: DelegationManager,\n functionName: 'redeemDelegations',\n args: [\n [encodedPermissionsContext],\n [ExecutionMode.SingleDefault],\n encodeExecutionCalldatas([[callAsExecution]]),\n ],\n });\n\n return createExecution({\n target: delegationManager,\n callData: redeemCalldata,\n });\n};\n\n/**\n * If there's a single call, encode the shorthand `execute` function. Otherwise, encode the `executeWithMode` function. Execution type will always be \"default\".\n *\n * @param calls - The calls to execute.\n * @returns The encoded calldata for the DeleGator to execute the calls.\n * @description\n * This function supports both single and batch execution modes.\n * For single calls, it uses the gas-efficient execute function.\n */\nexport const encodeCalls = (calls: readonly Call[]) => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call && !isDelegatedCall(call)) {\n const { to: target, value, data: callData } = call;\n const execution = createExecution({ target, value, callData });\n return execute({ execution });\n }\n }\n\n const executions = calls.map((call) => {\n if (isDelegatedCall(call)) {\n return processDelegatedCall(call);\n }\n const { to: target, value, data: callData } = call;\n return createExecution({ target, value, callData });\n });\n\n const mode =\n calls.length === 1\n ? ExecutionMode.SingleDefault\n : ExecutionMode.BatchDefault;\n return executeWithMode({ mode, executions });\n};\n\n/**\n * Encodes calls for execution by a DeleGator smart contract.\n *\n * @param caller - The address of the DeleGator contract.\n * @param calls - An array of Call objects, each containing 'to', optional 'data', and optional 'value'.\n * @returns A promise that resolves to the encoded function data as a hexadecimal string.\n * @description\n * - If there's a single call directly to the delegator, it returns the call data directly.\n * - For multiple calls or calls to other addresses, it creates executions and encodes them for the DeleGator's execute function.\n * - The execution mode is set to ExecutionMode.SingleDefault for a single call, or ExecutionMode.BatchDefault for multiple calls.\n *\n * todo: This doesn't fully expose the flexibility of the DeleGator's execute function, but it's a start.\n * maybe we add a mechanism where individual calls passed to this function can be encoded batches.\n */\nexport const encodeCallsForCaller = async (\n caller: Address,\n calls: readonly Call[],\n): Promise<Hex> => {\n if (calls.length === 1) {\n const call = calls[0];\n if (call?.to === caller && !isDelegatedCall(call)) {\n // if there's a single call, and it's to the delegator, we can just return the calldata directly.\n return call.data ?? '0x';\n }\n }\n return encodeCalls(calls);\n};\n","import {\n parseAbiParameters,\n encodeAbiParameters,\n type Hex,\n encodePacked,\n keccak256,\n concat,\n hexToBytes,\n} from 'viem';\nimport { parseSignature } from 'webauthn-p256';\n\nexport const FIELD_MODULUS =\n 115792089210356248762697446949407573529996955224135760342422259061068512044369n;\nexport const MALLEABILITY_THRESHOLD = FIELD_MODULUS / 2n;\n\nexport const SIGNATURE_ABI_PARAMS = parseAbiParameters(\n 'bytes32, uint256, uint256, bytes, bool, string, string, uint256',\n);\n\n/**\n * This function is used to convert the client data returned from the\n * credentials API into a format that can be consumed by the DeleGator\n * contracts. We need the flattend JSON strings before and after the\n * userOpHash/challenge. This function provides those two client data string\n * slices.\n *\n * @param clientDataJson - The client data JSON string.\n * @returns Returns [clientDataJSONPrefix and clientDataJSONSuffix]\n * ClientDataJSONPrefix contains the client data till the challengeHash\n * ClientDataJSONSuffix contains the client data after the challengeHash.\n */\nexport const splitOnChallenge = (\n clientDataJson: string,\n): [clientDataJSONPrefix: string, clientDataJSONSuffix: string] => {\n /*\n CientData looks like this:\n {\n \"type\": \"webauthn.create\" | \"webauthn.get\",\n \"challenge\": \"{userOpHash}\",\n \"origin\": \"{Domain}\",\n \"crossOrigin\": boolean\n }\n */\n try {\n const { challenge } = JSON.parse(clientDataJson);\n if (challenge === undefined) {\n throw new Error('No \"challenge\" found in the input string');\n }\n return clientDataJson.split(challenge) as [string, string];\n } catch (error) {\n throw new Error('No \"challenge\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Returns the index of '\"type\":' in the ClientData.\n *\n * @param clientDataJson - Stringified ClientDataJSON.\n * @returns The index of '\"type\":' in the ClientData.\n */\nexport const getResponseTypeLocation = (clientDataJson: string): bigint => {\n try {\n // Find the index of the `\"type\":` key in the JSON string directly\n const typeIndex = clientDataJson.indexOf('\"type\":');\n\n if (typeIndex === -1) {\n throw new Error('No \"type\" found in the input string');\n }\n // Return the index of the `\"type\":` key\n return BigInt(typeIndex);\n } catch (error) {\n // Handle any errors that occur during the search\n throw new Error('No \"type\" found in the input string', {\n cause: error,\n });\n }\n};\n\n/**\n * Encodes a signature to a hexadecimal signature that will be accepted\n * by the DeleGator contracts.\n *\n * @param keyId - The key used for the signature, represented as a hexadecimal string.\n * @param signature - The signature to convert, as Hex.\n * @param clientDataJSON - The client data used in the creation of the signature.\n * @param authenticatorData - The authenticator data used in the creation of the signature.\n * @returns The signature as a valid DeleGator signature encoded as Hexadecimal string.\n */\nexport function encodeDeleGatorSignature(\n keyId: string,\n signature: Hex,\n clientDataJSON: string,\n authenticatorData: Hex,\n): Hex {\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n\n const parsedSignature = parseSignature(signature);\n\n let { s } = parsedSignature;\n\n while (s > MALLEABILITY_THRESHOLD) {\n s = FIELD_MODULUS - s;\n }\n\n const { r } = parsedSignature;\n\n const [clientDataComponent1, clientDataComponent2] =\n splitOnChallenge(clientDataJSON);\n\n const { userVerified } = parseAuthenticatorFlags(authenticatorData);\n\n const responseTypeLocation = getResponseTypeLocation(clientDataJSON);\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n r,\n s,\n authenticatorData,\n userVerified,\n clientDataComponent1,\n clientDataComponent2,\n responseTypeLocation,\n ]);\n return encodedSignature;\n}\n\nconst AUTHENTICATOR_DATA_FLAGS_OFFSET = 32;\n// We have all of the flag bits defined here for completeness, even though we only extract the userVerified flag.\nenum AuthenticatorDataFlagBitIndex {\n UserPresence = 0,\n UserVerified = 2,\n BackupEligibility = 3,\n BackupState = 4,\n AttestedCredentialData = 6,\n ExtensionData = 7,\n}\n\nexport type AuthenticatorFlags = {\n userVerified: boolean;\n};\n\n/**\n * Parses the authenticator data and returns an authenticator flags object with the `userVerified` flag.\n * See https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data.\n *\n * @param authenticatorData - The authenticator data to parse.\n * @returns An object representing the parsed authenticator flags.\n */\nexport function parseAuthenticatorFlags(\n authenticatorData: Hex,\n): AuthenticatorFlags {\n const authenticatorDataBuffer = hexToBytes(authenticatorData);\n const dataBufferUint8 = new Uint8Array(authenticatorDataBuffer);\n const flags = dataBufferUint8[AUTHENTICATOR_DATA_FLAGS_OFFSET];\n if (flags === undefined) {\n throw new Error('Authenticator flags not found in authenticator data');\n }\n\n // Bit 0 is the least significant bit in the flags byte, so we left shift 0b1 by the bit index\n // eslint-disable-next-line no-bitwise\n const bitMask = 0b1 << AuthenticatorDataFlagBitIndex.UserVerified;\n\n return {\n // eslint-disable-next-line no-bitwise\n userVerified: (flags & bitMask) !== 0x0,\n };\n}\n\n/**\n * Creates a dummy signature.\n * This must meet all early-failure conditions of the real signature, but does not need to be a valid signature.\n *\n * @param keyId - The key ID to use for the dummy signature.\n * @returns The encoded signature.\n */\nexport const createDummyWebAuthnSignature = (keyId: Hex) => {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#data_structure\n const rpIdHash = keccak256(encodePacked(['string'], ['AuthenticatorData']));\n const flags = '0x05';\n const signCount = '0x00000000';\n const authenticatorData = concat([rpIdHash, flags, signCount]);\n\n const keyIdHash = keccak256(encodePacked(['string'], [keyId]));\n const rs =\n 57896044605178124381348723474703786764998477612067880171211129530534256022184n;\n const userVerification = true;\n const clientDataPrefix = '{\"type\":\"webauthn.get\",\"challenge\":\"';\n const clientDataSuffix = '\",\"origin\":\"passkey-domain\",\"crossOrigin\":false}';\n const responseTypeLocation = 1n;\n\n const encodedSignature = encodeAbiParameters(SIGNATURE_ABI_PARAMS, [\n keyIdHash,\n rs,\n rs,\n authenticatorData,\n userVerification,\n clientDataPrefix,\n clientDataSuffix,\n responseTypeLocation,\n ]);\n\n return encodedSignature;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AACA,SAAS,oBAAoB,WAAW;AA6BjC,IAAM,+BAA+B,OAE1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAMuD;AACrD,MAAI;AACJ,MAAI;AAEJ,UAAQ,gBAAgB;AAAA,IACtB,4BAA4B;AAC1B,YAAM,CAAC,OAAO,QAAQ,SAAS,OAAO,IACpC;AAEF,UAAI,CAAC,gBAAgB,qBAAqB;AACxC,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,8BAAwB,gBAAgB;AAExC,YAAM,aAAa,OAAO,IAAI,CAAC,OAAO,UAAU;AAC9C,cAAM,SAAS,QAAQ,KAAK;AAC5B,cAAM,SAAS,QAAQ,KAAK;AAE5B,YAAI,CAAC,UAAU,CAAC,QAAQ;AACtB,gBAAM,IAAI;AAAA,YACR,kCAAkC,KAAK,aAAa,KAAK;AAAA,UAC3D;AAAA,QACF;AAEA,eAAO;AAAA,UACL;AAAA,UACA,GAAG;AAAA,UACH,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAED,iBAAW,OAA0B,EAAE,UAAU,OAAO,WAAW,CAAC;AACpE;AAAA,IACF;AAAA,IACA,gCAA8B;AAC5B,YAAM,CAAC,QAAQ,SAAS,IAAI;AAE5B,UAAI,CAAC,gBAAgB,uBAAuB;AAC1C,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,8BAAwB,gBAAgB;AACxC,iBAAWA,QAA4B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