@introspectivelabs/x402-evm 0.1.0-beta.13 → 0.1.0-beta.14

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.
@@ -134,7 +134,8 @@ var ExactEvmSchemeERC4337 = class extends import_server.ExactEvmScheme {
134
134
  return {
135
135
  address: chain.usdcAddress,
136
136
  name: "USDC",
137
- version: "2"
137
+ version: "2",
138
+ decimals: 6
138
139
  };
139
140
  }
140
141
  throw new Error(`No default asset configured for network ${network}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/exact/server/index.ts","../../../../src/exact/server/scheme.ts","../../../../src/networks/registry.ts","../../../../src/networks/helpers.ts","../../../../src/exact/utils.ts"],"sourcesContent":["export { ExactEvmSchemeERC4337 } from \"./scheme\";\n","import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism-sepolia.safe.global\",\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum-sepolia.safe.global\",\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAA+B;;;ACCxB,IAAM,mBAA8C;AAAA,EACzD,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,2BAA2B;AAAA,IAC3B,SAAS;AAAA,EACX;AAAA,EACA,OAAO;AAAA,IACL,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,2BACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA,IAAI;AAAA,IACF,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,2BACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA,UAAU;AAAA,IACR,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAA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;AAAA,UACL,SAAS,MAAM;AAAA,UACf,MAAM;AAAA,UACN,SAAS;AAAA,QACX;AAAA,MACF;AACA,YAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;AAAA,IACtE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAM,2BACJ,qBACA,eAMA,eAC8B;AAE9B,UAAM,gBAAgB,+BAA+B,mBAAmB;AAGxE,UAAM,WAAW,MAAM,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAGA,QAAI,eAAe;AACjB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO;AAAA,UACL,GAAG,SAAS;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,QAAI,CAAC,SAAS,OAAO;AACnB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO,CAAC;AAAA,MACV;AAAA,IACF;AAGA,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/exact/server/index.ts","../../../../src/exact/server/scheme.ts","../../../../src/networks/registry.ts","../../../../src/networks/helpers.ts","../../../../src/exact/utils.ts"],"sourcesContent":["export { ExactEvmSchemeERC4337 } from \"./scheme\";\n","import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n decimals: 6,\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism-sepolia.safe.global\",\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum-sepolia.safe.global\",\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAA+B;;;ACCxB,IAAM,mBAA8C;AAAA,EACzD,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,2BAA2B;AAAA,IAC3B,SAAS;AAAA,EACX;AAAA,EACA,OAAO;AAAA,IACL,SAAS;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,IACP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,SAAS,+BACd,cACqC;AACrC,QAAM,cAAc,aAAa,OAAO;AACxC,MACE,eACA,OAAO,gBAAgB,YACvB,eAAe,eACf,YAAY,cAAc,MAC1B;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AHCO,IAAM,wBAAN,cAAoC,6BAAe;AAAA,EACxD,cAAc;AACZ,UAAM;AAKN,IAAC,KAAa,kBAAkB,CAAC,YAAoB;AACnD,YAAM,UAAU,WAAW,OAAO;AAClC,YAAM,QAAQ,aAAa,OAAO;AAClC,UAAI,OAAO;AACT,eAAO;AAAA,UACL,SAAS,MAAM;AAAA,UACf,MAAM;AAAA,UACN,SAAS;AAAA,UACT,UAAU;AAAA,QACZ;AAAA,MACF;AACA,YAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;AAAA,IACtE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAM,2BACJ,qBACA,eAMA,eAC8B;AAE9B,UAAM,gBAAgB,+BAA+B,mBAAmB;AAGxE,UAAM,WAAW,MAAM,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAGA,QAAI,eAAe;AACjB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO;AAAA,UACL,GAAG,SAAS;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,QAAI,CAAC,SAAS,OAAO;AACnB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO,CAAC;AAAA,MACV;AAAA,IACF;AAGA,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/cjs/index.js CHANGED
@@ -317,7 +317,8 @@ var ExactEvmSchemeERC4337 = class extends import_server.ExactEvmScheme {
317
317
  return {
318
318
  address: chain.usdcAddress,
319
319
  name: "USDC",
320
- version: "2"
320
+ version: "2",
321
+ decimals: 6
321
322
  };
322
323
  }
323
324
  throw new Error(`No default asset configured for network ${network}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/constants.ts","../../src/exact/utils.ts","../../src/exact/utils/transformRoutes.ts","../../src/exact/server/scheme.ts","../../src/networks/registry.ts","../../src/networks/helpers.ts","../../src/exact/facilitator/bundler/types.ts","../../src/exact/facilitator/bundler/client.ts","../../src/exact/facilitator/scheme.ts","../../src/exact/client/schemes/erc4337.ts","../../src/exact/client/bundler/viem.ts","../../src/exact/client/signers/safeAccountSigner.ts","../../src/exact/client/signers/safeMessageSigners.ts","../../src/exact/client/utils/callData.ts","../../src/exact/client/utils/userOperation.ts","../../src/exact/client/errors.ts","../../src/exact/client/schemes/eip3009.ts","../../src/accounts/encodeContractSignature.ts","../../src/accounts/computeSafeMessageHash.ts","../../src/accounts/toSafeSmartAccount.ts","../../src/accounts/toP256SafeSmartAccount.ts","../../src/accounts/computeSafeOpHash.ts","../../src/accounts/toWebAuthnSafeSmartAccount.ts","../../src/accounts/extractPasskeyCoordinates.ts","../../src/stamp/safeMessageHash.ts"],"sourcesContent":["export * from \"./constants\";\nexport * from \"./exact\";\nexport * from \"./accounts\";\nexport * from \"./stamp\";\nexport * from \"./networks\";\n","import type { Hex } from \"viem\";\nimport { entryPoint07Address } from \"viem/account-abstraction\";\n\nexport { entryPoint07Address };\n\nexport const SAFE_4337_MODULE_ADDRESS =\n \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\" as const satisfies Hex;\n\nexport const SAFE_WEBAUTHN_SHARED_SIGNER =\n \"0xfD90FAd33ee8b58f32c00aceEad1358e4AFC23f9\" as const satisfies Hex;\n\nexport const FCL_P256_VERIFIER =\n \"0xA86e0054C51E4894D88762a017ECc5E5235f5DBA\" as const satisfies Hex;\n\nexport const P256_OWNER_FACTORY =\n \"0x349c03Eb61e26528cbf79F5D3Ba071FcA2aE82cB\" as const satisfies Hex;\n\nexport const WEBAUTHN_SIGNER_FACTORY =\n \"0xF7488fFbe67327ac9f37D5F722d83Fc900852Fbf\" as const satisfies Hex;\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n","import type { RoutesConfig, RouteConfig, HTTPRequestContext } from \"@x402/core/server\";\nimport type { Price, Network, AssetAmount } from \"@x402/core/types\";\nimport type { ExactEvmSchemeERC4337 } from \"../server/scheme\";\nimport type { PaymentOption, DynamicPrice } from \"@x402/core/http\";\nimport type { UserOperationCapability } from \"../types\";\n\n/**\n * Transforms routes to move userOperation from PaymentOption.extra to price.extra.\n *\n * This transformation enables userOperation to flow through the natural price.extra\n * path into PaymentRequirements.extra, allowing the official middleware to work\n * without modification.\n *\n * This is a workaround to allow the official middleware to work without modification.\n * and support this proposal https://github.com/coinbase/x402/issues/639\n *\n * @param routes - The routes configuration to transform (single RouteConfig or RoutesConfig object)\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns Transformed routes with userOperation moved to price.extra\n *\n * @example\n * ```typescript\n * import { transformRoutesForUserOperation } from '@introspectivelabs/x402-evm/exact/utils';\n * import { ExactEvmSchemeERC4337Server } from '@introspectivelabs/x402-evm/exact/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337Server();\n * const transformedRoutes = await transformRoutesForUserOperation(routes, schemeServer);\n * ```\n */\nexport async function transformRoutesForUserOperation(\n routes: RoutesConfig,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<RoutesConfig> {\n // Handle single RouteConfig\n if (\"accepts\" in routes) {\n return await transformRouteForUserOperation(routes as RouteConfig, schemeServer);\n }\n\n // Handle RoutesConfig object (Record<string, RouteConfig>)\n const transformed: Record<string, RouteConfig> = {};\n for (const [path, routeConfig] of Object.entries(routes as Record<string, RouteConfig>)) {\n transformed[path] = await transformRouteForUserOperation(routeConfig, schemeServer);\n }\n return transformed;\n}\n\n/**\n * Transforms a single RouteConfig to move userOperation from PaymentOption.extra to price.extra.\n *\n * @param routeConfig - The RouteConfig to transform\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed RouteConfig\n */\nexport async function transformRouteForUserOperation(\n routeConfig: RouteConfig,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<RouteConfig> {\n // Handle single PaymentOption\n if (!Array.isArray(routeConfig.accepts)) {\n return {\n ...routeConfig,\n accepts: await transformPaymentOption(routeConfig.accepts, schemeServer),\n };\n }\n\n // Handle array of PaymentOptions\n const transformedAccepts = await Promise.all(\n routeConfig.accepts.map(option => transformPaymentOption(option, schemeServer)),\n );\n\n return {\n ...routeConfig,\n accepts: transformedAccepts,\n };\n}\n\n/**\n * Transforms a PaymentOption to move userOperation from extra to price.extra.\n *\n * @param option - The PaymentOption to transform\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed PaymentOption\n */\nasync function transformPaymentOption(\n option: PaymentOption,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<PaymentOption> {\n // Extract userOperation from PaymentOption.extra\n const userOperation = option.extra?.userOperation as UserOperationCapability | undefined;\n\n // If no userOperation, return option as-is\n if (!userOperation || !userOperation.supported) {\n return option;\n }\n\n // Transform price to include userOperation in extra\n const transformedPrice = await transformPrice(\n option.price,\n option.network,\n userOperation,\n schemeServer,\n );\n\n // Remove userOperation from PaymentOption.extra\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { userOperation: _, ...restExtra } = option.extra || {};\n\n return {\n ...option,\n price: transformedPrice,\n extra: Object.keys(restExtra).length > 0 ? restExtra : undefined,\n };\n}\n\n/**\n * Transforms a price to include userOperation in its extra field.\n *\n * @param price - The price to transform\n * @param network - The network the price is for\n * @param userOperation - The user operation to include in the price\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed price\n */\nasync function transformPrice(\n price: Price | DynamicPrice,\n network: Network,\n userOperation: UserOperationCapability,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<Price | DynamicPrice> {\n // Handle function price (DynamicPrice)\n if (typeof price === \"function\") {\n return async (context: HTTPRequestContext): Promise<Price> => {\n const resolvedPrice = await price(context);\n return await injectUserOperationIntoPrice(\n resolvedPrice,\n network,\n userOperation,\n schemeServer,\n );\n };\n }\n\n // Handle static price (string, number, or AssetAmount)\n return await injectUserOperationIntoPrice(price, network, userOperation, schemeServer);\n}\n\n/**\n * Injects userOperation into a price's extra field.\n * Handles both string/number prices (parsed to AssetAmount) and AssetAmount prices.\n *\n * @param price - The price to inject the user operation into\n * @param network - The network the price is for\n * @param userOperation - The user operation to include in the price\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed price\n */\nasync function injectUserOperationIntoPrice(\n price: Price,\n network: Network,\n userOperation: UserOperationCapability,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<Price> {\n // If price is already an AssetAmount, add userOperation to extra\n if (typeof price === \"object\" && \"asset\" in price && \"amount\" in price) {\n const assetAmount = price as AssetAmount;\n return {\n ...assetAmount,\n extra: {\n ...assetAmount.extra,\n userOperation,\n },\n };\n }\n\n // If price is string or number, parse it to AssetAmount\n // Note: We need to preserve the original format if possible\n // For now, we'll parse and return as AssetAmount\n // The scheme server will handle the conversion back if needed\n const assetAmount = await schemeServer.parsePrice(price, network);\n\n return {\n ...assetAmount,\n extra: {\n ...assetAmount.extra,\n userOperation,\n },\n };\n}\n","import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism-sepolia.safe.global\",\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum-sepolia.safe.global\",\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","/**\n * Gas estimation response from bundler\n */\nexport interface GasEstimate {\n [key: string]: unknown;\n callGasLimit?: string;\n verificationGasLimit?: string;\n preVerificationGas?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n paymasterVerificationGasLimit?: string;\n paymasterPostOpGasLimit?: string;\n}\n\n/**\n * User operation receipt from bundler\n */\nexport interface UserOperationReceipt {\n [key: string]: unknown;\n userOpHash: string;\n entryPoint: string;\n sender: string;\n nonce: string;\n paymaster?: string;\n actualGasCost: string;\n actualGasUsed: string;\n success: boolean;\n reason?: string;\n logs: unknown[];\n receipt?: {\n [key: string]: unknown;\n transactionHash: string;\n };\n transactionHash?: string;\n}\n\n/**\n * Configuration for bundler client\n */\nexport interface BundlerClientConfig {\n /**\n * Timeout for RPC calls in milliseconds\n *\n * @default 10000\n */\n timeout?: number;\n /**\n * Number of retries for failed requests\n *\n * @default 0\n */\n retries?: number;\n}\n\n/**\n * JSON-RPC error response\n */\nexport interface JsonRpcError {\n message?: string;\n code?: number;\n data?: unknown;\n}\n\n/**\n * JSON-RPC response wrapper\n */\nexport interface JsonRpcResponse<T> {\n result?: T;\n error?: JsonRpcError;\n}\n\n/**\n * Custom error class for bundler-related errors\n */\nexport class BundlerError extends Error {\n readonly code?: number;\n readonly data?: unknown;\n readonly method?: string;\n readonly bundlerUrl?: string;\n\n /**\n * Creates a new BundlerError instance\n *\n * @param message - Error message\n * @param options - Optional error details\n * @param options.code - Error code from bundler\n * @param options.data - Additional error data\n * @param options.method - RPC method that failed\n * @param options.bundlerUrl - Bundler URL that was called\n * @param options.cause - Original error that caused this error\n */\n constructor(\n message: string,\n options?: {\n code?: number;\n data?: unknown;\n method?: string;\n bundlerUrl?: string;\n cause?: Error;\n },\n ) {\n super(message);\n this.name = \"BundlerError\";\n this.code = options?.code;\n this.data = options?.data;\n this.method = options?.method;\n this.bundlerUrl = options?.bundlerUrl;\n if (options?.cause) {\n // @ts-expect-error - cause is a standard Error property but not in all TypeScript versions\n this.cause = options.cause;\n }\n }\n}\n","import type {\n BundlerClientConfig,\n GasEstimate,\n JsonRpcResponse,\n UserOperationReceipt,\n} from \"./types\";\nimport { BundlerError } from \"./types\";\n\n/**\n * Bundler RPC client for ERC-4337 user operations\n */\nexport class BundlerClient {\n private readonly rpcUrl: string;\n private readonly config: Required<BundlerClientConfig>;\n\n /**\n * Creates a new BundlerClient instance\n *\n * @param rpcUrl - The bundler RPC URL\n * @param config - Optional configuration for the client\n */\n constructor(rpcUrl: string, config?: BundlerClientConfig) {\n this.rpcUrl = rpcUrl;\n this.config = {\n timeout: config?.timeout ?? 10_000,\n retries: config?.retries ?? 0,\n };\n }\n\n /**\n * Estimates gas for a user operation\n *\n * @param userOp - The user operation to estimate gas for\n * @param entryPoint - The entry point address\n * @returns Gas estimates\n * @throws BundlerError if the estimation fails\n */\n async estimateUserOperationGas(\n userOp: Record<string, unknown>,\n entryPoint: string,\n ): Promise<GasEstimate> {\n return this.call<GasEstimate>(\"eth_estimateUserOperationGas\", [userOp, entryPoint]);\n }\n\n /**\n * Sends a user operation to the bundler\n *\n * @param userOp - The user operation to send\n * @param entryPoint - The entry point address\n * @returns The user operation hash\n * @throws BundlerError if sending fails\n */\n async sendUserOperation(userOp: Record<string, unknown>, entryPoint: string): Promise<string> {\n return this.call<string>(\"eth_sendUserOperation\", [userOp, entryPoint]);\n }\n\n /**\n * Gets the receipt for a user operation\n *\n * @param userOpHash - The user operation hash\n * @returns The receipt or null if not found\n * @throws BundlerError if the request fails\n */\n async getUserOperationReceipt(userOpHash: string): Promise<UserOperationReceipt | null> {\n return this.call<UserOperationReceipt | null>(\"eth_getUserOperationReceipt\", [userOpHash]);\n }\n\n /**\n * Makes a JSON-RPC call to the bundler\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @returns The result from the RPC call\n * @throws BundlerError if the call fails\n */\n private async call<T>(method: string, params: unknown[]): Promise<T> {\n const requestPayload = {\n jsonrpc: \"2.0\" as const,\n id: 1,\n method,\n params,\n };\n\n let lastError: Error | undefined;\n const maxAttempts = this.config.retries + 1;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n const res = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(requestPayload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!res.ok) {\n throw new BundlerError(`Bundler HTTP error: ${res.status} ${res.statusText}`, {\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n const json = (await res.json()) as JsonRpcResponse<T>;\n\n if (json.error) {\n throw new BundlerError(json.error.message ?? \"Bundler RPC error\", {\n code: json.error.code,\n data: json.error.data,\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n if (json.result === undefined) {\n throw new BundlerError(\"Bundler RPC returned no result\", {\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n return json.result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // If it's an abort error (timeout), don't retry\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new BundlerError(`Bundler request timeout after ${this.config.timeout}ms`, {\n method,\n bundlerUrl: this.rpcUrl,\n cause: error,\n });\n }\n\n // If this is the last attempt, throw the error\n if (attempt === maxAttempts - 1) {\n if (error instanceof BundlerError) {\n throw error;\n }\n throw new BundlerError(`Bundler request failed: ${lastError.message}`, {\n method,\n bundlerUrl: this.rpcUrl,\n cause: lastError,\n });\n }\n\n // Wait before retrying (exponential backoff)\n await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 100));\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw new BundlerError(\"Bundler request failed after retries\", {\n method,\n bundlerUrl: this.rpcUrl,\n cause: lastError,\n });\n }\n}\n","import type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { BundlerClient } from \"./bundler/client\";\nimport type { Erc4337Payload } from \"./types\";\n\n/**\n * Configuration for the ERC-4337 facilitator\n */\nexport interface ExactEvmSchemeNetworkERC4337Config {\n /**\n * Default bundler URL to use if not provided in payload or requirements\n */\n\n defaultBundlerUrl?: string;\n\n /**\n * Timeout for receipt polling in milliseconds\n *\n * @default 30000\n */\n\n receiptPollTimeout?: number;\n\n /**\n * Interval for receipt polling in milliseconds\n *\n * @default 1000\n */\n\n receiptPollInterval?: number;\n}\n\n/**\n * Enhanced ExactEvmScheme facilitator that supports UserOperation (ERC-4337) payments.\n *\n * This facilitator implements the `SchemeNetworkFacilitator` interface and handles\n * verification and settlement of user operations through a bundler.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeNetworkERC4337 } from '@introspectivelabs/x402-evm/exact/facilitator';\n * import { x402Facilitator } from '@x402/core/facilitator';\n *\n * const facilitator = new x402Facilitator()\n * .register('eip155:84532', new ExactEvmSchemeNetworkERC4337());\n * ```\n */\nexport class ExactEvmSchemeNetworkERC4337 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required<ExactEvmSchemeNetworkERC4337Config>;\n\n /**\n * Creates a new ExactEvmSchemeNetworkERC4337 instance\n *\n * @param config - Optional configuration for the facilitator\n */\n constructor(config?: ExactEvmSchemeNetworkERC4337Config) {\n this.config = {\n defaultBundlerUrl: config?.defaultBundlerUrl ?? \"\",\n receiptPollTimeout: config?.receiptPollTimeout ?? 30_000,\n receiptPollInterval: config?.receiptPollInterval ?? 1_000,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * Returns user operation capability if available.\n *\n * @param _ - The network identifier (unused, but required by interface)\n * @returns User operation capability or undefined\n */\n getExtra(_: Network): Record<string, unknown> | undefined {\n // Return undefined - user operation capability should be set by the server\n // This follows the pattern of the original ExactEvmScheme\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * For user operations, no facilitator signer is needed as the user signs the operation.\n *\n * @param _ - The network identifier (unused, but required by interface)\n * @returns Empty array (no facilitator signer needed)\n */\n getSigners(_: string): string[] {\n return [];\n }\n\n /**\n * Verifies a payment payload containing a user operation.\n *\n * This method:\n * - Extracts the user operation from the payload\n * - Gets the bundler URL from payload, requirements, or config\n * - Estimates gas using the bundler to validate the user operation\n *\n * @param payload - The payment payload containing the user operation\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const erc4337Payload = payload.payload as Erc4337Payload;\n\n // Extract user operation\n if (!erc4337Payload.userOperation) {\n return {\n isValid: false,\n invalidReason: \"missing_user_operation\",\n payer: undefined,\n };\n }\n\n const userOp = erc4337Payload.userOperation;\n const payer = userOp.sender;\n\n // Get bundler URL from payload, requirements, or config\n const bundlerUrl =\n erc4337Payload.bundlerRpcUrl ??\n (requirements.extra?.userOperation as { bundlerUrl?: string } | undefined)?.bundlerUrl ??\n this.config.defaultBundlerUrl;\n\n if (!bundlerUrl) {\n return {\n isValid: false,\n invalidReason: \"missing_bundler_url\",\n payer,\n };\n }\n\n // Get entry point\n const entryPoint = erc4337Payload.entryPoint;\n if (!entryPoint) {\n return {\n isValid: false,\n invalidReason: \"missing_entry_point\",\n payer,\n };\n }\n\n // Verify by estimating gas through bundler\n try {\n const bundler = new BundlerClient(bundlerUrl);\n await bundler.estimateUserOperationGas(userOp, entryPoint);\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n } catch (error) {\n return {\n isValid: false,\n invalidReason: (error as Error).message,\n payer,\n };\n }\n }\n\n /**\n * Settles a payment by sending the user operation to the bundler.\n *\n * This method:\n * - Re-verifies the payment (following original pattern)\n * - Sends the user operation to the bundler\n * - Polls for the receipt\n * - Returns the transaction hash\n *\n * @param payload - The payment payload containing the user operation\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const erc4337Payload = payload.payload as Erc4337Payload;\n\n // Re-verify before settling (following original pattern)\n const verifyResult = await this.verify(payload, requirements);\n if (!verifyResult.isValid) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: verifyResult.invalidReason ?? \"invalid\",\n payer: verifyResult.payer,\n };\n }\n\n const userOp = erc4337Payload.userOperation;\n const payer = userOp.sender;\n\n // Get bundler URL\n const bundlerUrl =\n erc4337Payload.bundlerRpcUrl ??\n (requirements.extra?.userOperation as { bundlerUrl?: string } | undefined)?.bundlerUrl ??\n this.config.defaultBundlerUrl;\n\n if (!bundlerUrl) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: \"missing_bundler_url\",\n payer,\n };\n }\n\n const entryPoint = erc4337Payload.entryPoint;\n if (!entryPoint) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: \"missing_entry_point\",\n payer,\n };\n }\n\n try {\n const bundler = new BundlerClient(bundlerUrl);\n\n // Send user operation\n const userOpHash = await bundler.sendUserOperation(userOp, entryPoint);\n\n // Poll for receipt\n const deadline = Date.now() + this.config.receiptPollTimeout;\n let receipt = null;\n\n while (Date.now() < deadline) {\n receipt = await bundler.getUserOperationReceipt(userOpHash);\n if (receipt) {\n break;\n }\n await new Promise(resolve => setTimeout(resolve, this.config.receiptPollInterval));\n }\n\n // Extract transaction hash from receipt\n const txHash = receipt?.receipt?.transactionHash ?? receipt?.transactionHash ?? userOpHash;\n\n return {\n success: true,\n network: payload.accepted.network,\n transaction: txHash,\n payer,\n errorReason: undefined,\n };\n } catch (error) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: (error as Error).message,\n payer,\n };\n }\n }\n}\n","import type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n getAddress,\n createPublicClient,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n Hex,\n} from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport { defineChain } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport type { BundlerClient } from \"../bundler\";\nimport { ViemBundlerClient } from \"../bundler/viem\";\nimport type { UserOperationSigner } from \"../signers\";\nimport { SafeAccountSigner } from \"../signers\";\nimport { extractUserOperationCapability } from \"../../utils\";\nimport type { Erc4337Payload } from \"../../facilitator/types\";\nimport { buildERC20TransferCallData } from \"../utils/callData\";\nimport { userOpToJson } from \"../utils/userOperation\";\nimport { PaymentCreationError, parseAAError } from \"../errors\";\nimport { resolveChainId } from \"../../../networks\";\n\n/**\n * Base configuration properties shared by all configuration variants\n */\ninterface ExactEvmSchemeERC4337ConfigBase {\n /**\n * Entry point address (EntryPoint v0.7)\n * Optional - can be provided in payment requirements if not set here\n */\n entrypoint?: Hex;\n\n /**\n * Bundler URL (optional, can be provided in payment requirements)\n */\n bundlerUrl?: string;\n}\n\n/**\n * Configuration variant when bundlerClient is explicitly provided.\n * Account and publicClient are NOT needed when bundlerClient is used.\n * Signer is required when using bundlerClient.\n */\ntype ExactEvmSchemeERC4337ConfigWithBundler = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client for preparing and sending user operations.\n */\n bundlerClient: BundlerClient;\n /**\n * Signer for signing user operations (required when bundlerClient is provided).\n */\n signer: UserOperationSigner;\n} & {\n /**\n * Account must not be provided when bundlerClient is used.\n * Using `never` type prevents this property from being set.\n */\n account?: never;\n /**\n * Public client must not be provided when bundlerClient is used.\n * The bundlerClient already has its own publicClient configured.\n */\n publicClient?: never;\n};\n\n/**\n * Configuration variant when bundlerClient is not provided.\n * Account is required for dynamic bundlerClient creation.\n * Signer is optional - will be auto-created from account if not provided.\n * PublicClient is optional - will create a default from network if not provided.\n */\ntype ExactEvmSchemeERC4337ConfigWithAccount = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client is not provided - will be created dynamically from PaymentRequirements.\n * Using `never` type prevents this property from being set.\n */\n bundlerClient?: never;\n} & {\n /**\n * Smart account for user operation preparation.\n * Required when bundlerClient is not provided.\n */\n account: SmartAccount;\n /**\n * Signer for signing user operations.\n * Optional - will be auto-created from account using SafeAccountSigner if not provided.\n * The account must support signUserOperation method for auto-creation to work.\n */\n signer?: UserOperationSigner;\n /**\n * Public client for blockchain interactions.\n * Optional - will create a default from network if not provided.\n */\n publicClient?: PublicClient<Transport, Chain>;\n};\n\n/**\n * Configuration for the ERC-4337 client scheme.\n *\n * This is a discriminated union that enforces type-safe combinations:\n * - Either `bundlerClient` is provided (account and publicClient must NOT be provided)\n * - Or `account` is provided when bundlerClient is not (for dynamic creation, publicClient optional)\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer auto-created)\n * const scheme1 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * // signer will be auto-created from account\n * // bundlerClient will be created dynamically from PaymentRequirements\n * });\n *\n * // With account and custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * signer: myCustomSigner,\n * publicClient: myPublicClient, // Optional\n * });\n *\n * // With explicit bundlerClient (backward compatible)\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient: myBundlerClient,\n * signer: mySigner, // Required when bundlerClient is provided\n * // account and publicClient must NOT be provided (bundlerClient has its own)\n * });\n * ```\n */\nexport type ExactEvmSchemeERC4337Config =\n | ExactEvmSchemeERC4337ConfigWithBundler\n | ExactEvmSchemeERC4337ConfigWithAccount;\n\n/**\n * Resolves a network string to a Chain object.\n * Handles both CAIP-2 format (\"eip155:84532\") and v1 plain names (\"base-sepolia\").\n *\n * @param network - Network string in CAIP-2 or v1 plain name format\n * @returns The Chain object\n */\nfunction resolveChain(network: string): Chain {\n const chainId = resolveChainId(network);\n\n const known = Object.values(allChains).find((c: Chain) => c.id === chainId);\n if (known) return known;\n\n return defineChain({\n id: chainId,\n name: network,\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: { default: { http: [] } },\n });\n}\n\n/**\n * Creates a default public client from a network string.\n *\n * @param network - The network string in CAIP-2 format (e.g., \"eip155:84532\")\n * @returns A PublicClient instance\n */\nfunction createDefaultPublicClient(network: string): PublicClient<Transport, Chain> {\n const chain = resolveChain(network);\n return createPublicClient({\n chain,\n transport: http(),\n });\n}\n\n/**\n * EVM client implementation for the Exact payment scheme using ERC-4337 UserOperations.\n *\n * This implementation creates payment payloads by building and signing UserOperations\n * that execute ERC20 transfers. The UserOperations are prepared using a bundler client\n * and signed using a user operation signer (e.g., Safe account, EOA).\n *\n * Supports minimal configuration: when bundlerClient is not provided and\n * PaymentRequirements.extra.userOperation.supported is true, a ViemBundlerClient\n * will be created dynamically from the payment requirements.\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer and bundlerClient auto-created)\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/client';\n * import { x402Client } from '@x402/core/client';\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * account: safeAccount, // SmartAccount - signer will be auto-created\n * });\n *\n * // With custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: safeAccount,\n * signer: customSigner, // Optional - overrides auto-creation\n * });\n *\n * // Explicit config (backward compatible)\n * import { ViemBundlerClient } from '@introspectivelabs/x402-evm/exact/client/bundler';\n *\n * const bundlerClient = new ViemBundlerClient({\n * publicClient,\n * account,\n * chain,\n * bundlerUrl: 'https://bundler.example.com',\n * });\n *\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer: account, // Required when bundlerClient is provided\n * });\n *\n * const client = new x402Client();\n * client.register('eip155:84532', scheme);\n * ```\n */\nexport class ExactEvmSchemeERC4337 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly bundlerClient?: BundlerClient;\n private readonly account?: SmartAccount;\n private readonly publicClient?: PublicClient<Transport, Chain>;\n private readonly signer: UserOperationSigner;\n private readonly entrypoint?: Hex;\n private readonly bundlerUrl?: string;\n\n /**\n * Creates a new ExactEvmSchemeERC4337 instance.\n *\n * @param config - Configuration for the scheme (type-safe: either bundlerClient or account must be provided)\n * @throws Error if bundlerClient is not provided and account is also not provided (runtime safety check)\n * @throws Error if signer is not provided and account doesn't support signUserOperation\n */\n constructor(config: ExactEvmSchemeERC4337Config) {\n this.bundlerClient = config.bundlerClient;\n this.account = config.account;\n this.publicClient = config.publicClient;\n this.entrypoint = config.entrypoint;\n this.bundlerUrl = config.bundlerUrl;\n\n // Validate: if bundlerClient is not provided, account must be provided\n if (!this.bundlerClient && !this.account) {\n throw new Error(\n \"Either bundlerClient or account must be provided. \" +\n \"If bundlerClient is not provided, account (SmartAccount) is required for dynamic bundlerClient creation.\",\n );\n }\n\n // Handle signer: use provided signer or auto-create from account\n if (config.signer) {\n this.signer = config.signer;\n } else if (this.account) {\n // Auto-create signer from account if not provided\n if (!this.account.signUserOperation) {\n throw new Error(\n \"Account does not support signUserOperation. \" +\n \"Either provide a signer explicitly or use an account that supports signUserOperation.\",\n );\n }\n this.signer = new SafeAccountSigner(this.account);\n } else {\n // This should not happen due to type system, but add runtime check for safety\n throw new Error(\n \"Signer is required when bundlerClient is provided. \" +\n \"Either provide a signer explicitly or use account-based configuration.\",\n );\n }\n }\n\n /**\n * Creates a payment payload for the Exact scheme using ERC-4337 UserOperations.\n *\n * This method:\n * 1. Extracts user operation capability from payment requirements\n * 2. Creates bundlerClient dynamically if not provided (when userOperation.supported is true)\n * 3. Builds ERC20 transfer call data\n * 4. Prepares the user operation using the bundler client\n * 5. Signs the user operation\n * 6. Converts to JSON-RPC format\n * 7. Returns the x402 payment payload\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n * @throws Error if user operation capability is not found or required fields are missing\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n // Extract user operation capability (optional - config defaults used when missing)\n const capability = extractUserOperationCapability(paymentRequirements);\n\n // Determine which bundlerClient to use\n let bundlerClient: BundlerClient;\n\n if (this.bundlerClient) {\n // Use provided bundlerClient (explicit config, backward compatible)\n bundlerClient = this.bundlerClient;\n } else {\n // Create bundlerClient dynamically from PaymentRequirements\n if (!this.account) {\n throw new Error(\n \"Account (SmartAccount) is required when bundlerClient is not provided. \" +\n \"Either provide bundlerClient in config or account for dynamic creation.\",\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Derive chain from network (supports both CAIP-2 and v1 plain names)\n const chain = resolveChain(paymentRequirements.network);\n\n // Use provided publicClient or create default from network\n const publicClient =\n this.publicClient ?? createDefaultPublicClient(paymentRequirements.network);\n\n // Create ViemBundlerClient dynamically\n bundlerClient = new ViemBundlerClient({\n publicClient,\n account: this.account,\n chain,\n bundlerUrl,\n });\n }\n\n // Get entry point (prioritize config defaults over PaymentRequirements)\n const entryPoint = this.entrypoint ?? (capability?.entrypoint as `0x${string}` | undefined);\n\n if (!entryPoint) {\n throw new PaymentCreationError(\n \"Entry point not provided\",\n {\n phase: \"validation\",\n reason: \"Set entrypoint in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.entrypoint\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Normalize addresses\n const token = getAddress(paymentRequirements.asset);\n const payTo = getAddress(paymentRequirements.payTo);\n // Handle both v2 (amount) and v1 (maxAmountRequired) fields\n const amountStr =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n if (!amountStr) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n const amount = BigInt(amountStr);\n\n // Build ERC20 transfer call data\n const callData = buildERC20TransferCallData(token, payTo, amount);\n\n // Prepare user operation (unsigned)\n let unsignedUserOp;\n try {\n unsignedUserOp = await bundlerClient.prepareUserOperation(\n [\n {\n to: token,\n value: BigInt(0), // ERC20 transfers don't send ETH\n data: callData,\n },\n ],\n entryPoint,\n );\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment preparation failed: ${aaError.reason}`\n : `Payment preparation failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"preparation\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Sign the user operation\n let signature;\n try {\n signature = await this.signer.signUserOperation(unsignedUserOp);\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment signing failed: ${aaError.reason}`\n : `Payment signing failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"signing\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Create signed user operation\n const signedUserOp = {\n ...unsignedUserOp,\n signature,\n };\n\n // Convert to JSON-RPC format (bigint -> hex)\n const jsonUserOp = userOpToJson(signedUserOp);\n\n // Build the ERC-4337 payload\n const payload: Erc4337Payload = {\n type: \"erc4337\",\n entryPoint,\n bundlerRpcUrl: bundlerUrl,\n userOperation: jsonUserOp,\n };\n\n return {\n x402Version,\n // v1 requires scheme and network at top level\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import type { Chain, PublicClient, Transport } from \"viem\";\nimport { http } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { createBundlerClient as createViemBundlerClient } from \"viem/account-abstraction\";\nimport type {\n BundlerClient,\n BundlerClientConfig,\n GasEstimate,\n PreparedUserOperation,\n UserOperationCall,\n} from \"./client\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Configuration for creating a viem-based bundler client\n */\nexport interface ViemBundlerClientConfig extends BundlerClientConfig {\n /**\n * Viem public client for blockchain interactions\n */\n publicClient: PublicClient<Transport, Chain>;\n\n /**\n * Smart account for user operation preparation (must be a SmartAccount, not a regular Account)\n */\n account: SmartAccount;\n\n /**\n * Chain configuration\n */\n chain: Chain;\n\n /**\n * Bundler RPC URL\n */\n bundlerUrl: string;\n}\n\n/**\n * Viem-based implementation of BundlerClient.\n * Uses viem's account-abstraction utilities for user operation handling.\n */\nexport class ViemBundlerClient implements BundlerClient {\n private readonly bundlerClient: ReturnType<typeof createViemBundlerClient>;\n private readonly account: SmartAccount;\n private readonly entryPoint: `0x${string}`;\n\n /**\n * Creates a new ViemBundlerClient instance.\n *\n * @param config - Configuration for the bundler client\n */\n constructor(config: ViemBundlerClientConfig) {\n this.account = config.account;\n this.entryPoint = \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\" as `0x${string}`; // EntryPoint v0.7\n\n // Create viem bundler client with bundler-specific transport\n this.bundlerClient = createViemBundlerClient({\n client: config.publicClient,\n chain: config.chain,\n account: config.account,\n transport: http(config.bundlerUrl),\n });\n }\n\n /**\n * Prepares an unsigned user operation for the given calls.\n *\n * @param calls - Array of calls to execute in the user operation\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to a prepared (unsigned) user operation\n */\n async prepareUserOperation(\n calls: UserOperationCall[],\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<PreparedUserOperation> {\n const prepared = await this.bundlerClient.prepareUserOperation({\n account: this.account,\n calls: calls.map(call => ({\n to: call.to,\n value: call.value,\n data: call.data,\n })),\n });\n\n // viem v2 EntryPoint v0.7 returns separate fields (not v0.6 paymasterAndData)\n const p = prepared as Record<string, unknown>;\n\n return {\n sender: prepared.sender,\n nonce: prepared.nonce,\n callData: prepared.callData,\n callGasLimit: prepared.callGasLimit,\n verificationGasLimit: prepared.verificationGasLimit,\n preVerificationGas: prepared.preVerificationGas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n // v0.7 factory fields (for account deployment)\n ...(p.factory ? { factory: p.factory as `0x${string}` } : {}),\n ...(p.factoryData ? { factoryData: p.factoryData as `0x${string}` } : {}),\n // v0.7 paymaster fields (separate, not paymasterAndData)\n ...(p.paymaster ? { paymaster: p.paymaster as `0x${string}` } : {}),\n ...(p.paymasterData ? { paymasterData: p.paymasterData as `0x${string}` } : {}),\n ...(p.paymasterVerificationGasLimit != null\n ? { paymasterVerificationGasLimit: p.paymasterVerificationGasLimit as bigint }\n : {}),\n ...(p.paymasterPostOpGasLimit != null\n ? { paymasterPostOpGasLimit: p.paymasterPostOpGasLimit as bigint }\n : {}),\n signature: prepared.signature,\n } as PreparedUserOperation;\n }\n\n /**\n * Estimates gas for a user operation.\n * Note: This is typically done as part of prepareUserOperation,\n * but is available as a separate method for flexibility.\n *\n * @param _userOp - The user operation to estimate gas for\n * @param _entryPoint - The entry point address\n * @returns Promise resolving to gas estimates\n */\n async estimateGas(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<GasEstimate> {\n // Note: Gas estimation is typically done as part of prepareUserOperation\n // This method is provided for flexibility but may not be used in practice\n // The return type from estimateUserOperationGas doesn't include maxFeePerGas/maxPriorityFeePerGas\n // as those are determined by the network, not the bundler\n throw new Error(\n \"estimateGas should be called through prepareUserOperation, which includes gas estimation\",\n );\n }\n\n /**\n * Sends a user operation to the bundler.\n *\n * @param userOp - The signed user operation to send\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to the user operation hash\n */\n async sendUserOperation(\n userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<string> {\n // Convert JSON user operation to format expected by viem\n // viem's sendUserOperation accepts UserOperation fields directly (not nested)\n const hash = await this.bundlerClient.sendUserOperation({\n account: this.account,\n sender: userOp.sender as `0x${string}`,\n nonce: BigInt(userOp.nonce),\n callData: userOp.callData as `0x${string}`,\n callGasLimit: BigInt(userOp.callGasLimit),\n verificationGasLimit: BigInt(userOp.verificationGasLimit),\n preVerificationGas: BigInt(userOp.preVerificationGas),\n maxFeePerGas: BigInt(userOp.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(userOp.maxPriorityFeePerGas),\n // Combine paymaster and paymasterData into paymasterAndData\n paymasterAndData:\n userOp.paymaster && userOp.paymasterData\n ? ((userOp.paymaster + userOp.paymasterData.slice(2)) as `0x${string}`)\n : userOp.paymaster\n ? (userOp.paymaster as `0x${string}`)\n : (\"0x\" as `0x${string}`),\n signature: userOp.signature as `0x${string}`,\n });\n\n return hash;\n }\n}\n","import type { SmartAccount } from \"viem/account-abstraction\";\nimport type { PreparedUserOperation } from \"../bundler\";\nimport type { UserOperationSigner } from \"./types\";\n\n/**\n * Adapter to make a SmartAccount (e.g., Safe account) work as a UserOperationSigner.\n *\n * This class wraps a SmartAccount that supports `signUserOperation` and adapts it\n * to the UserOperationSigner interface required by the x402 ERC-4337 scheme.\n *\n * @example\n * ```typescript\n * import { SafeAccountSigner } from \"@introspectivelabs/x402-evm/exact/client\";\n * import { toSafeSmartAccount } from \"permissionless/accounts\";\n *\n * const safeAccount = await toSafeSmartAccount({ ... });\n * const signer = new SafeAccountSigner(safeAccount);\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer,\n * });\n * ```\n */\nexport class SafeAccountSigner implements UserOperationSigner {\n readonly address: `0x${string}`;\n\n /**\n * Creates a new SafeAccountSigner instance.\n *\n * @param account - The SmartAccount instance (e.g., from permissionless/accounts)\n * @throws Error if the account is not initialized or missing an address\n */\n constructor(private readonly account: SmartAccount) {\n if (!account?.address) {\n throw new Error(\"Smart account not initialized\");\n }\n this.address = account.address as `0x${string}`;\n }\n\n /**\n * Signs a prepared (unsigned) user operation.\n *\n * @param userOp - The prepared user operation to sign\n * @returns Promise resolving to the signature\n * @throws Error if the account does not support signUserOperation\n */\n async signUserOperation(userOp: PreparedUserOperation): Promise<`0x${string}`> {\n if (!this.account?.signUserOperation) {\n throw new Error(\"Smart account does not support signUserOperation\");\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await this.account.signUserOperation(userOp as any);\n }\n}\n","import { type Hex, concat, encodeAbiParameters } from \"viem\";\nimport type { WebAuthnAccount } from \"viem/account-abstraction\";\nimport type { P256Signer, SafeMessageSigner } from \"../../../accounts/types\";\n\n/**\n * Creates a SafeMessageSigner from a P256Signer.\n * The sign method returns concat([r, s]) (64 bytes raw P256 signature).\n */\nexport function createP256SafeMessageSigner(\n p256Signer: P256Signer,\n): SafeMessageSigner {\n return {\n ownerAddress: p256Signer.p256OwnerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n const { r, s } = await p256Signer.sign(safeMessageHash);\n return concat([r, s]);\n },\n };\n}\n\n/**\n * Creates a SafeMessageSigner from a WebAuthnAccount.\n * The sign method triggers navigator.credentials.get() and returns\n * ABI-encoded WebAuthn struct compatible with Safe's verifier.\n *\n * @param webAuthnAccount - viem WebAuthnAccount (wraps credential + getFn)\n * @param deployedSignerAddress - Address of the per-credential signer deployed\n * via SafeWebAuthnSignerFactory (NOT the SharedSigner)\n */\nexport function createWebAuthnSafeMessageSigner(\n webAuthnAccount: WebAuthnAccount,\n deployedSignerAddress: Hex,\n): SafeMessageSigner {\n return {\n ownerAddress: deployedSignerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n return encodeWebAuthnSignature(webAuthnAccount, safeMessageHash);\n },\n };\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n","import { encodeFunctionData } from \"viem\";\n\n/**\n * Standard ERC20 transfer function ABI\n */\nexport const ERC20_TRANSFER_ABI = [\n {\n type: \"function\",\n name: \"transfer\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n/**\n * Builds ERC20 transfer call data.\n *\n * @param token - The ERC20 token contract address\n * @param to - The recipient address\n * @param amount - The amount to transfer (in token's smallest unit)\n * @returns The encoded call data for the transfer function\n */\nexport function buildERC20TransferCallData(\n token: `0x${string}`,\n to: `0x${string}`,\n amount: bigint,\n): `0x${string}` {\n return encodeFunctionData({\n abi: ERC20_TRANSFER_ABI,\n functionName: \"transfer\",\n args: [to, amount],\n });\n}\n","import type { Hex } from \"viem\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Converts a bigint value to a hex string in JSON-RPC format.\n *\n * @param value - The bigint value to convert\n * @returns The hex string representation\n */\nfunction toRpcHex(value: bigint): Hex {\n return `0x${value.toString(16)}` as Hex;\n}\n\n/**\n * Converts a user operation with bigint values to JSON-RPC compatible format.\n * This recursively converts all bigint values to hex strings.\n *\n * @param userOp - The user operation object (may contain bigints)\n * @returns The user operation in JSON-RPC format (all bigints converted to hex)\n */\nexport function userOpToJson(userOp: Record<string, unknown>): UserOperation07Json {\n const json: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(userOp)) {\n // Skip internal viem fields that bundlers reject\n if (key === \"account\") continue;\n\n if (typeof value === \"bigint\") {\n json[key] = toRpcHex(value);\n } else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n // Recursively handle nested objects with bigints\n const inner: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n inner[k] = typeof v === \"bigint\" ? toRpcHex(v) : v;\n }\n json[key] = inner;\n } else {\n json[key] = value;\n }\n }\n\n return json as UserOperation07Json;\n}\n","export type PaymentCreationPhase = \"preparation\" | \"signing\" | \"validation\";\n\nconst AA_ERROR_MESSAGES: Record<string, string> = {\n AA10: \"Sender already constructed\",\n AA13: \"InitCode failed or OOG\",\n AA14: \"InitCode must return sender\",\n AA15: \"InitCode must create sender\",\n AA20: \"Account not deployed\",\n AA21: \"Insufficient funds for gas prefund\",\n AA22: \"Expired or not due\",\n AA23: \"Reverted (or OOG)\",\n AA24: \"Signature validation failed\",\n AA25: \"Nonce validation failed\",\n AA26: \"Account accessed global state\",\n AA30: \"Paymaster not deployed\",\n AA31: \"Paymaster deposit too low\",\n AA32: \"Paymaster expired or not due\",\n AA33: \"Paymaster reverted (or OOG)\",\n AA34: \"Paymaster context reverted\",\n AA40: \"Over verification gas limit\",\n AA41: \"Over max fee per gas\",\n AA50: \"Over max priority fee per gas\",\n AA51: \"Prefund below actualGasCost\",\n};\n\n/**\n * Extracts an AA error code (e.g. \"AA21\") from an error and returns\n * a human-readable reason. Returns null if no AA code is found.\n */\nexport function parseAAError(error: unknown): { code: string; reason: string } | null {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/\\b(AA[0-9]{2})\\b/);\n if (!match) return null;\n const code = match[1];\n const reason = AA_ERROR_MESSAGES[code] ?? \"Unknown AA error\";\n return { code, reason };\n}\n\nexport class PaymentCreationError extends Error {\n readonly phase: PaymentCreationPhase;\n readonly reason: string;\n readonly safeAddress?: string;\n readonly network?: string;\n readonly code?: string;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n phase: PaymentCreationPhase;\n reason: string;\n safeAddress?: string;\n network?: string;\n code?: string;\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"PaymentCreationError\";\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n this.phase = options.phase;\n this.reason = options.reason;\n this.safeAddress = options.safeAddress;\n this.network = options.network;\n this.code = options.code;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n phase: this.phase,\n reason: this.reason,\n ...(this.code && { code: this.code }),\n ...(this.safeAddress && { safeAddress: this.safeAddress }),\n ...(this.network && { network: this.network }),\n };\n }\n}\n","import type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport {\n type Hex,\n getAddress,\n hashTypedData,\n toHex,\n} from \"viem\";\nimport type { SafeMessageSigner } from \"../../../accounts/types\";\nimport { encodeContractSignature } from \"../../../accounts/encodeContractSignature\";\nimport { computeSafeMessageHash } from \"../../../accounts/computeSafeMessageHash\";\nimport { resolveChainId } from \"../../../networks\";\n\nconst authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\nfunction createNonce(): Hex {\n const cryptoObj = globalThis.crypto;\n if (!cryptoObj) throw new Error(\"Crypto API not available\");\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n\nexport interface ExactEvmSchemeEIP3009Config {\n safeAddress: Hex;\n signer: SafeMessageSigner;\n}\n\n/**\n * EVM client scheme that produces standard EIP-3009 `{ authorization, signature }`\n * payloads from a Safe Smart Account using EIP-1271 contract signatures.\n *\n * Unlike ExactEvmSchemeERC4337 (which creates UserOperation payloads), this scheme\n * creates payloads compatible with any standard x402 facilitator. The facilitator\n * verifies via `verifyTypedData` (which falls back to EIP-1271 for contract addresses)\n * and settles via `transferWithAuthorization(bytes)` (which uses SignatureChecker).\n *\n * Signing flow:\n * 1. Build EIP-3009 authorization (from=Safe, to=payTo, value, nonce, etc.)\n * 2. Compute EIP-712 hash of the authorization\n * 3. Wrap in Safe's message hash (what isValidSignature expects)\n * 4. Sign the Safe message hash via SafeMessageSigner (P256 or WebAuthn)\n * 5. Encode as Safe contract signature (v=0 format)\n *\n * Prerequisites:\n * - Safe must be deployed (EIP-1271 requires on-chain code)\n * - Safe must hold USDC balance (EIP-3009 transfers directly)\n * - USDC must support transferWithAuthorization(bytes) overload (v2.2+)\n */\nexport class ExactEvmSchemeEIP3009 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly safeAddress: Hex;\n private readonly signer: SafeMessageSigner;\n\n constructor(config: ExactEvmSchemeEIP3009Config) {\n this.safeAddress = config.safeAddress;\n this.signer = config.signer;\n }\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n const chainId = resolveChainId(paymentRequirements.network);\n\n // v1 uses maxAmountRequired, v2 uses amount\n const amount =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n\n if (!amount) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization = {\n from: getAddress(this.safeAddress),\n to: getAddress(paymentRequirements.payTo),\n value: amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Build EIP-712 domain from payment requirements extra fields\n const extra = paymentRequirements.extra as Record<string, unknown> | undefined;\n if (!extra?.name || !extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`,\n );\n }\n\n const domain = {\n name: extra.name as string,\n version: extra.version as string,\n chainId,\n verifyingContract: getAddress(paymentRequirements.asset) as Hex,\n };\n\n const message = {\n from: getAddress(authorization.from) as Hex,\n to: getAddress(authorization.to) as Hex,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as Hex,\n };\n\n // Step 1: Compute the EIP-712 typed data hash\n const eip712Hash = hashTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Step 2: Wrap in Safe's message hash (what Safe.isValidSignature expects)\n const safeMessageHash = computeSafeMessageHash(\n this.safeAddress,\n chainId,\n eip712Hash,\n );\n\n // Step 3: Sign the Safe message hash (P256 or WebAuthn)\n const innerSignature = await this.signer.sign(safeMessageHash);\n\n // Step 4: Encode as Safe contract signature (v=0)\n const signature = encodeContractSignature(\n this.signer.ownerAddress,\n innerSignature,\n );\n\n const payload = { authorization, signature };\n\n return {\n x402Version,\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import { type Hex, concat, pad, toHex } from \"viem\";\n\n/**\n * Encodes a signature in Safe's contract signature format (v=0).\n *\n * Safe's `checkNSignatures` expects this layout for contract owners:\n *\n * Static part (65 bytes):\n * - r (32 bytes): owner address padded to 32 bytes\n * - s (32 bytes): offset to dynamic data (relative to start of signatures)\n * - v (1 byte): 0x00 (indicates contract signature)\n *\n * Dynamic part (at the offset):\n * - length (32 bytes): length of the signature data\n * - data (variable): the actual signature bytes\n *\n * For a single signer, the static part is 65 bytes, so the dynamic data\n * starts at offset 65.\n */\nexport function encodeContractSignature(ownerAddress: Hex, signatureData: Hex): Hex {\n // Static part: r = address padded to 32 bytes\n const r = pad(ownerAddress, { size: 32 });\n\n // For a single signature, dynamic data starts right after the 65-byte static part\n const dynamicOffset = 65;\n const s = pad(toHex(dynamicOffset), { size: 32 });\n\n // v = 0x00 for contract signature\n const v = \"0x00\" as Hex;\n\n // Dynamic part: length-prefixed signature data\n const signatureBytes = (signatureData.length - 2) / 2;\n const length = pad(toHex(signatureBytes), { size: 32 });\n\n return concat([r, s, v, length, signatureData]);\n}\n","import {\n type Hex,\n encodeAbiParameters,\n encodePacked,\n keccak256,\n} from \"viem\";\n\nconst DOMAIN_SEPARATOR_TYPEHASH = keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n);\n\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Computes the Safe message hash for EIP-1271 signature verification.\n *\n * This is what Safe's `isValidSignature(hash, sig)` expects: the hash is\n * first wrapped in Safe's EIP-712 domain before `checkNSignatures` runs.\n *\n * Flow: keccak256(0x19 || 0x01 || domainSeparator || structHash)\n * where structHash = keccak256(SAFE_MSG_TYPEHASH || keccak256(abi.encode(messageHash)))\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"uint256\" }, { type: \"address\" }],\n [DOMAIN_SEPARATOR_TYPEHASH, BigInt(chainId), safeAddress],\n ),\n );\n\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n","import type { Hex, LocalAccount } from \"viem\";\nimport { concat, encodeAbiParameters, pad, toHex } from \"viem\";\nimport type { SmartAccount, WebAuthnAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount as toPermissionlessSafeSmartAccount } from \"permissionless/accounts\";\n\nimport type { P256Signer, ToSafeSmartAccountParams } from \"./types\";\nimport { toP256SafeSmartAccount } from \"./toP256SafeSmartAccount\";\nimport { toWebAuthnSafeSmartAccount } from \"./toWebAuthnSafeSmartAccount\";\nimport { encodeContractSignature } from \"./encodeContractSignature\";\nimport { computeSafeOpHash } from \"./computeSafeOpHash\";\nimport type { SafeOpHashParams } from \"./computeSafeOpHash\";\nimport {\n SAFE_4337_MODULE_ADDRESS,\n SAFE_WEBAUTHN_SHARED_SIGNER,\n entryPoint07Address,\n} from \"../constants\";\n\n/**\n * Creates a Safe SmartAccount with a unified signer configuration.\n *\n * Dispatches to the appropriate implementation based on `signerConfig.type`:\n * - `\"p256\"`: P256 contract owner (existing `toP256SafeSmartAccount`)\n * - `\"webauthn\"`: WebAuthn passkey via permissionless native support\n * - `\"multi\"`: Both P256 and WebAuthn owners on a single Safe\n *\n * @example\n * ```typescript\n * // P256 only\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: { type: \"p256\", p256Signer },\n * });\n *\n * // WebAuthn only\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: { type: \"webauthn\", webAuthnAccount },\n * });\n *\n * // Multi-signer (threshold 1, P256 signs by default)\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: {\n * type: \"multi\",\n * signers: { p256: p256Signer, webAuthn: webAuthnAccount },\n * threshold: 1,\n * },\n * });\n * ```\n */\nexport async function toSafeSmartAccount(\n params: ToSafeSmartAccountParams,\n): Promise<SmartAccount> {\n const { signerConfig } = params;\n\n switch (signerConfig.type) {\n case \"p256\":\n return toP256SafeSmartAccount({\n client: params.client,\n p256Signer: signerConfig.p256Signer,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n });\n\n case \"webauthn\":\n return toWebAuthnSafeSmartAccount({\n client: params.client,\n webAuthnAccount: signerConfig.webAuthnAccount,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n safeWebAuthnSharedSignerAddress: signerConfig.safeWebAuthnSharedSignerAddress,\n });\n\n case \"multi\":\n return buildMultiSignerAccount(params, signerConfig.signers, signerConfig.threshold ?? 1);\n }\n}\n\nfunction createMockLocalAccount(address: Hex): LocalAccount {\n const notImplemented = () => {\n throw new Error(\"Mock owner: use signUserOperation instead\");\n };\n\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: notImplemented,\n signTypedData: notImplemented,\n signTransaction: notImplemented,\n sign: notImplemented,\n } as unknown as LocalAccount;\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n *\n * permissionless does not export this helper, so we implement it here.\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n // Extract r, s from the DER-encoded P256 signature\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n // Extract the fields after \"challenge\":\"...\" from clientDataJSON\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n\nasync function buildMultiSignerAccount(\n params: ToSafeSmartAccountParams,\n signers: { p256?: P256Signer; webAuthn?: WebAuthnAccount },\n threshold: number,\n): Promise<SmartAccount> {\n if (!signers.p256 && !signers.webAuthn) {\n throw new Error(\"Multi-signer config requires at least one signer\");\n }\n\n // If only one signer is provided, delegate to the single-signer function\n if (signers.p256 && !signers.webAuthn) {\n return toP256SafeSmartAccount({\n client: params.client,\n p256Signer: signers.p256,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n });\n }\n if (signers.webAuthn && !signers.p256) {\n const signerConfig = params.signerConfig;\n const sharedSignerAddr = signerConfig.type === \"multi\"\n ? signerConfig.safeWebAuthnSharedSignerAddress\n : undefined;\n return toWebAuthnSafeSmartAccount({\n client: params.client,\n webAuthnAccount: signers.webAuthn,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n safeWebAuthnSharedSignerAddress: sharedSignerAddr,\n });\n }\n\n // Both signers present\n const p256Signer = signers.p256!;\n const webAuthnAccount = signers.webAuthn!;\n\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress = params.entryPoint?.address ?? entryPoint07Address;\n\n const mockP256Owner = createMockLocalAccount(p256Signer.p256OwnerAddress);\n\n // Build account with both owners: mock LocalAccount for P256 + WebAuthnAccount\n const baseAccount = await toPermissionlessSafeSmartAccount({\n client: params.client,\n owners: [mockP256Owner, webAuthnAccount],\n version: \"1.5.0\",\n threshold: BigInt(threshold),\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n });\n\n const chainId = await params.client.getChainId();\n\n if (threshold >= 2) {\n return buildThreshold2Account(\n baseAccount as SmartAccount,\n p256Signer,\n webAuthnAccount,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n }\n\n // Threshold 1: P256 signs by default (no browser interaction needed)\n return buildThreshold1Account(\n baseAccount as SmartAccount,\n p256Signer,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n}\n\nfunction buildThreshold1Account(\n baseAccount: SmartAccount,\n p256Signer: P256Signer,\n chainId: number,\n safe4337ModuleAddress: Hex,\n entryPointAddress: Hex,\n): SmartAccount {\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const safeOpHash = computeSafeOpHash(\n extractSafeOpHashParams(userOp),\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n const { r, s } = await p256Signer.sign(safeOpHash);\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256Signature = concat([rPadded, sPadded]);\n\n const contractSig = encodeContractSignature(\n p256Signer.p256OwnerAddress,\n p256Signature,\n );\n\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, contractSig]);\n },\n } as SmartAccount;\n}\n\nfunction buildThreshold2Account(\n baseAccount: SmartAccount,\n p256Signer: P256Signer,\n webAuthnAccount: WebAuthnAccount,\n chainId: number,\n safe4337ModuleAddress: Hex,\n entryPointAddress: Hex,\n): SmartAccount {\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const safeOpHash = computeSafeOpHash(\n extractSafeOpHashParams(userOp),\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n // Sign with P256\n const { r, s } = await p256Signer.sign(safeOpHash);\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256SignatureData = concat([rPadded, sPadded]);\n\n // Sign with WebAuthn\n const webAuthnSignatureData = await encodeWebAuthnSignature(\n webAuthnAccount,\n safeOpHash,\n );\n\n // Build sorted multi-signature\n // Safe requires signatures sorted by signer address (ascending)\n const p256SignerAddress = p256Signer.p256OwnerAddress.toLowerCase();\n const webAuthnSignerAddress = SAFE_WEBAUTHN_SHARED_SIGNER.toLowerCase();\n\n type SignerEntry = {\n address: string;\n data: Hex;\n dynamic: boolean;\n contractOwner: boolean;\n };\n\n const signerEntries: SignerEntry[] = [\n {\n address: p256SignerAddress,\n data: p256SignatureData,\n dynamic: true,\n contractOwner: true,\n },\n {\n address: webAuthnSignerAddress,\n data: webAuthnSignatureData,\n dynamic: true,\n contractOwner: false,\n },\n ].sort((a, b) => (a.address < b.address ? -1 : 1));\n\n const concatenatedSig = concatSafeSignatures(signerEntries);\n\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, concatenatedSig]);\n },\n } as SmartAccount;\n}\n\n/**\n * Concatenates multiple Safe signatures with proper static/dynamic layout.\n *\n * Safe's `checkNSignatures` expects:\n * - N x 65-byte static parts (sorted by signer address)\n * - Dynamic data appended after all static parts\n *\n * For dynamic signatures (contract or WebAuthn):\n * Static: r = address padded to 32 bytes, s = offset to dynamic data, v = 0x00\n * Dynamic: 32-byte length prefix + signature data\n *\n * For ECDSA signatures:\n * Static: r (32 bytes) + s (32 bytes) + v (1 byte)\n */\nfunction concatSafeSignatures(\n entries: { address: string; data: Hex; dynamic: boolean; contractOwner: boolean }[],\n): Hex {\n const staticPartSize = 65; // per signer\n const totalStaticSize = staticPartSize * entries.length;\n\n const staticParts: Hex[] = [];\n const dynamicParts: Hex[] = [];\n let dynamicOffset = totalStaticSize;\n\n for (const entry of entries) {\n if (entry.dynamic) {\n // Dynamic signature: static part points to dynamic data\n const r = pad(entry.address as Hex, { size: 32 });\n const s = pad(toHex(dynamicOffset), { size: 32 });\n const v = \"0x00\" as Hex;\n staticParts.push(concat([r, s, v]));\n\n // Dynamic part: length-prefixed data\n const dataBytes = (entry.data.length - 2) / 2;\n const length = pad(toHex(dataBytes), { size: 32 });\n dynamicParts.push(concat([length, entry.data]));\n\n // Advance offset: 32 bytes for length + actual data length\n dynamicOffset += 32 + dataBytes;\n } else {\n // ECDSA: direct 65-byte signature (not used in current multi-signer paths)\n staticParts.push(entry.data);\n }\n }\n\n return concat([...staticParts, ...dynamicParts]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractSafeOpHashParams(userOp: any): SafeOpHashParams {\n const op = userOp as Record<string, unknown>;\n return {\n sender: op.sender as Hex,\n nonce: BigInt(op.nonce as bigint),\n factory: (op.factory as Hex) ?? null,\n factoryData: (op.factoryData as Hex) ?? null,\n callData: op.callData as Hex,\n verificationGasLimit: BigInt(op.verificationGasLimit as bigint),\n callGasLimit: BigInt(op.callGasLimit as bigint),\n preVerificationGas: BigInt(op.preVerificationGas as bigint),\n maxPriorityFeePerGas: BigInt(op.maxPriorityFeePerGas as bigint),\n maxFeePerGas: BigInt(op.maxFeePerGas as bigint),\n paymaster: (op.paymaster as Hex) ?? null,\n paymasterVerificationGasLimit: op.paymasterVerificationGasLimit\n ? BigInt(op.paymasterVerificationGasLimit as bigint)\n : null,\n paymasterPostOpGasLimit: op.paymasterPostOpGasLimit\n ? BigInt(op.paymasterPostOpGasLimit as bigint)\n : null,\n paymasterData: (op.paymasterData as Hex) ?? null,\n };\n}\n","import type { Hex, LocalAccount } from \"viem\";\nimport { concat, pad, toHex } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\n\nimport type { ToP256SafeSmartAccountParams } from \"./types\";\nimport { encodeContractSignature } from \"./encodeContractSignature\";\nimport type { SafeOpHashParams } from \"./computeSafeOpHash\";\nimport { computeSafeOpHash } from \"./computeSafeOpHash\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\n/**\n * Creates a mock LocalAccount that has the P256Owner contract address.\n *\n * This is needed because `toSafeSmartAccount` requires a `LocalAccount` owner,\n * but our actual signer is a P256Owner contract (ERC-1271). The mock provides\n * the correct address so the Safe is configured with the right owner. The\n * signing methods are never called since we override `signUserOperation`.\n */\nfunction createMockLocalAccount(address: Hex): LocalAccount {\n const notImplemented = () => {\n throw new Error(\"P256 contract owner: use signUserOperation instead\");\n };\n\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: notImplemented,\n signTypedData: notImplemented,\n signTransaction: notImplemented,\n sign: notImplemented,\n } as unknown as LocalAccount;\n}\n\n/**\n * Creates a Safe SmartAccount that signs UserOperations with a P256 contract owner.\n *\n * This wraps permissionless's `toSafeSmartAccount` and overrides `signUserOperation`\n * to produce P256 signatures in Safe's contract signature format (v=0). The resulting\n * account is compatible with `SafeAccountSigner` and `ExactEvmSchemeERC4337`.\n *\n * The caller is responsible for:\n * - Deploying the P256Owner contract (or computing its deterministic address)\n * - Providing the `sign()` function (e.g., using `@noble/curves/p256` with `prehash: false`)\n * - Ensuring the P256Owner is an owner of the Safe\n *\n * @example\n * ```typescript\n * import { toP256SafeSmartAccount } from '@introspectivelabs/x402-evm';\n * import { p256 } from '@noble/curves/p256';\n *\n * const account = await toP256SafeSmartAccount({\n * client: publicClient,\n * p256Signer: {\n * p256OwnerAddress: '0x349c...',\n * sign: async (hash) => {\n * const sig = p256.sign(hash.slice(2), privateKey, { prehash: false, lowS: true });\n * return {\n * r: `0x${sig.r.toString(16).padStart(64, '0')}`,\n * s: `0x${sig.s.toString(16).padStart(64, '0')}`,\n * };\n * },\n * },\n * safeAddress: '0x...',\n * });\n *\n * const scheme = new ExactEvmSchemeERC4337({ account });\n * ```\n */\nexport async function toP256SafeSmartAccount(\n params: ToP256SafeSmartAccountParams,\n): Promise<SmartAccount> {\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress =\n params.entryPoint?.address ?? entryPoint07Address;\n\n const mockOwner = createMockLocalAccount(params.p256Signer.p256OwnerAddress);\n\n const baseAccount = await toSafeSmartAccount({\n client: params.client,\n owners: [mockOwner],\n version: \"1.5.0\",\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n });\n\n const chainId = await params.client.getChainId();\n\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const op = userOp as Record<string, unknown>;\n // Compute the SafeOp EIP-712 hash (what Safe4337Module verifies)\n const hashParams: SafeOpHashParams = {\n sender: op.sender as Hex,\n nonce: BigInt(op.nonce as bigint),\n factory: (op.factory as Hex) ?? null,\n factoryData: (op.factoryData as Hex) ?? null,\n callData: op.callData as Hex,\n verificationGasLimit: BigInt(op.verificationGasLimit as bigint),\n callGasLimit: BigInt(op.callGasLimit as bigint),\n preVerificationGas: BigInt(op.preVerificationGas as bigint),\n maxPriorityFeePerGas: BigInt(op.maxPriorityFeePerGas as bigint),\n maxFeePerGas: BigInt(op.maxFeePerGas as bigint),\n paymaster: (op.paymaster as Hex) ?? null,\n paymasterVerificationGasLimit: op.paymasterVerificationGasLimit\n ? BigInt(op.paymasterVerificationGasLimit as bigint)\n : null,\n paymasterPostOpGasLimit: op.paymasterPostOpGasLimit\n ? BigInt(op.paymasterPostOpGasLimit as bigint)\n : null,\n paymasterData: (op.paymasterData as Hex) ?? null,\n };\n const safeOpHash = computeSafeOpHash(\n hashParams,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n // Sign the SafeOp hash with P256\n const { r, s } = await params.p256Signer.sign(safeOpHash);\n\n // Encode r || s as 64-byte signature\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256Signature = concat([rPadded, sPadded]);\n\n // Wrap in Safe contract signature format (v=0)\n const contractSig = encodeContractSignature(\n params.p256Signer.p256OwnerAddress,\n p256Signature,\n );\n\n // Safe4337Module expects: validAfter (6 bytes) || validUntil (6 bytes) || signatures\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, contractSig]);\n },\n } as SmartAccount;\n}\n","import {\n type Hex,\n concat,\n hashTypedData,\n isAddress,\n pad,\n toHex,\n} from \"viem\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\nconst SAFE_OP_TYPES = {\n SafeOp: [\n { type: \"address\", name: \"safe\" },\n { type: \"uint256\", name: \"nonce\" },\n { type: \"bytes\", name: \"initCode\" },\n { type: \"bytes\", name: \"callData\" },\n { type: \"uint128\", name: \"verificationGasLimit\" },\n { type: \"uint128\", name: \"callGasLimit\" },\n { type: \"uint256\", name: \"preVerificationGas\" },\n { type: \"uint128\", name: \"maxPriorityFeePerGas\" },\n { type: \"uint128\", name: \"maxFeePerGas\" },\n { type: \"bytes\", name: \"paymasterAndData\" },\n { type: \"uint48\", name: \"validAfter\" },\n { type: \"uint48\", name: \"validUntil\" },\n { type: \"address\", name: \"entryPoint\" },\n ],\n} as const;\n\nexport interface SafeOpHashParams {\n sender: Hex;\n nonce: bigint;\n factory?: Hex | null;\n factoryData?: Hex | null;\n callData: Hex;\n verificationGasLimit: bigint;\n callGasLimit: bigint;\n preVerificationGas: bigint;\n maxPriorityFeePerGas: bigint;\n maxFeePerGas: bigint;\n paymaster?: Hex | null;\n paymasterVerificationGasLimit?: bigint | null;\n paymasterPostOpGasLimit?: bigint | null;\n paymasterData?: Hex | null;\n}\n\n/**\n * Computes the EIP-712 SafeOp hash that Safe4337Module uses for signature verification.\n *\n * The Safe4337Module converts the EntryPoint v0.7 UserOperation into a SafeOp struct,\n * packing initCode and paymasterAndData into their v0.6-style concatenated forms,\n * then hashes the struct using EIP-712.\n */\nexport function computeSafeOpHash(\n userOp: SafeOpHashParams,\n chainId: number,\n safe4337ModuleAddress: Hex = SAFE_4337_MODULE_ADDRESS,\n entryPointAddress: Hex = entryPoint07Address,\n): Hex {\n // Reconstruct initCode: factory || factoryData (v0.7 -> v0.6 style)\n const initCode =\n userOp.factory && isAddress(userOp.factory)\n ? concat([userOp.factory, (userOp.factoryData || \"0x\") as Hex])\n : (\"0x\" as Hex);\n\n // Reconstruct paymasterAndData: paymaster || verificationGasLimit(16) || postOpGasLimit(16) || data\n let paymasterAndData: Hex = \"0x\";\n if (userOp.paymaster && isAddress(userOp.paymaster)) {\n paymasterAndData = concat([\n userOp.paymaster,\n pad(toHex(userOp.paymasterVerificationGasLimit || 0n), { size: 16 }),\n pad(toHex(userOp.paymasterPostOpGasLimit || 0n), { size: 16 }),\n (userOp.paymasterData || \"0x\") as Hex,\n ]);\n }\n\n return hashTypedData({\n domain: {\n chainId,\n verifyingContract: safe4337ModuleAddress,\n },\n types: SAFE_OP_TYPES,\n primaryType: \"SafeOp\",\n message: {\n safe: userOp.sender,\n nonce: userOp.nonce,\n initCode,\n callData: userOp.callData,\n verificationGasLimit: userOp.verificationGasLimit,\n callGasLimit: userOp.callGasLimit,\n preVerificationGas: userOp.preVerificationGas,\n maxPriorityFeePerGas: userOp.maxPriorityFeePerGas,\n maxFeePerGas: userOp.maxFeePerGas,\n paymasterAndData,\n validAfter: 0,\n validUntil: 0,\n entryPoint: entryPointAddress,\n },\n });\n}\n","import type { Hex } from \"viem\";\nimport type { SmartAccount, WebAuthnAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\nimport type { PublicClient, Transport, Chain } from \"viem\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\nexport type ToWebAuthnSafeSmartAccountParams = {\n client: PublicClient<Transport, Chain>;\n webAuthnAccount: WebAuthnAccount;\n safeAddress?: Hex;\n entryPoint?: { address: Hex; version: \"0.7\" };\n safe4337ModuleAddress?: Hex;\n safeWebAuthnSharedSignerAddress?: Hex;\n};\n\n/**\n * Creates a Safe SmartAccount that signs UserOperations with a WebAuthn passkey.\n */\nexport async function toWebAuthnSafeSmartAccount(\n params: ToWebAuthnSafeSmartAccountParams,\n): Promise<SmartAccount> {\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress = params.entryPoint?.address ?? entryPoint07Address;\n\n const baseAccount = await toSafeSmartAccount({\n client: params.client,\n owners: [params.webAuthnAccount],\n version: \"1.5.0\",\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n ...(params.safeWebAuthnSharedSignerAddress\n ? { safeWebAuthnSharedSignerAddress: params.safeWebAuthnSharedSignerAddress }\n : {}),\n });\n\n return baseAccount as SmartAccount;\n}\n","/// <reference lib=\"dom\" />\nimport type { Hex } from \"viem\";\n\nfunction bufferToHex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction base64urlToHex(base64url: string): string {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(base64);\n return Array.from(binary, (c) => c.charCodeAt(0).toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Extracts P256 public key coordinates from a WebAuthn credential.\n *\n * Replaces `extractPasskeyData` from `@safe-global/protocol-kit`.\n * Uses only the Web Crypto API (no external dependencies).\n */\nexport async function extractPasskeyCoordinates(\n credential: PublicKeyCredential,\n): Promise<{ rawId: string; x: Hex; y: Hex }> {\n const rawId = bufferToHex(credential.rawId);\n const response = credential.response as AuthenticatorAttestationResponse;\n const publicKey = response.getPublicKey();\n if (!publicKey) throw new Error(\"Failed to extract public key from credential\");\n\n const key = await crypto.subtle.importKey(\n \"spki\",\n publicKey,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n true,\n [\"verify\"],\n );\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"Missing coordinates in JWK\");\n\n return {\n rawId,\n x: (\"0x\" + base64urlToHex(jwk.x)) as Hex,\n y: (\"0x\" + base64urlToHex(jwk.y)) as Hex,\n };\n}\n","import {\n type Hex,\n encodeAbiParameters,\n keccak256,\n encodePacked,\n} from \"viem\";\n\n/**\n * The typehash used by Safe's `isValidSignature` (CompatibilityFallbackHandler).\n *\n * `SafeMessage(bytes message)` -- the Safe wraps any message inside this\n * EIP-712 struct before delegating to owners for verification.\n */\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Compute the domain separator for a Safe contract.\n *\n * The Safe uses a minimal EIP-712 domain: `{ chainId, verifyingContract }`.\n */\nfunction computeSafeDomainSeparator(safeAddress: Hex, chainId: number): Hex {\n return keccak256(\n encodeAbiParameters(\n [\n { type: \"bytes32\" },\n { type: \"uint256\" },\n { type: \"address\" },\n ],\n [\n // DOMAIN_SEPARATOR_TYPEHASH = keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\")\n keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n ),\n BigInt(chainId),\n safeAddress,\n ],\n ),\n );\n}\n\n/**\n * Compute the EIP-712 message hash that Safe's `isValidSignature` uses internally.\n *\n * When `isValidSignature(bytes32 _dataHash, bytes signature)` is called on a Safe,\n * the CompatibilityFallbackHandler computes:\n *\n * messageHash = keccak256(\n * 0x19 || 0x01 || domainSeparator || keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(abi.encode(_dataHash))))\n * )\n *\n * This hash is what gets passed to the owner contracts (e.g. P256Owner) for verification.\n * The P256Owner then does `keccak256(messageHash)` and verifies the P256 signature over that.\n *\n * Wait -- actually the Safe's `isValidSignature(bytes32, bytes)` internally converts\n * the bytes32 into `bytes` via `abi.encode()`, then calls `getMessageHash()`:\n * messageData = encodeTypedData(domainSeparator, SafeMessage(abi.encode(dataHash)))\n *\n * The P256Owner receives the full `messageData` from checkSignatures and computes\n * `hash = sha256(messageData)` or `keccak256(messageData)` depending on variant.\n *\n * For our purposes we compute the same hash the Safe produces.\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = computeSafeDomainSeparator(safeAddress, chainId);\n\n // SafeMessage struct hash: keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(abi.encode(messageHash))))\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n // EIP-712: 0x19 || 0x01 || domainSeparator || structHash\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,qCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iCAAoC;AAI7B,IAAM,2BACX;AAEK,IAAM,8BACX;AAEK,IAAM,oBACX;AAEK,IAAM,qBACX;AAEK,IAAM,0BACX;;;ACTK,SAAS,+BACd,cACqC;AACrC,QAAM,cAAc,aAAa,OAAO;AACxC,MACE,eACA,OAAO,gBAAgB,YACvB,eAAe,eACf,YAAY,cAAc,MAC1B;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;ACOA,eAAsB,gCACpB,QACA,cACuB;AAEvB,MAAI,aAAa,QAAQ;AACvB,WAAO,MAAM,+BAA+B,QAAuB,YAAY;AAAA,EACjF;AAGA,QAAM,cAA2C,CAAC;AAClD,aAAW,CAAC,MAAM,WAAW,KAAK,OAAO,QAAQ,MAAqC,GAAG;AACvF,gBAAY,IAAI,IAAI,MAAM,+BAA+B,aAAa,YAAY;AAAA,EACpF;AACA,SAAO;AACT;AASA,eAAsB,+BACpB,aACA,cACsB;AAEtB,MAAI,CAAC,MAAM,QAAQ,YAAY,OAAO,GAAG;AACvC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,SAAS,MA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W,SAAS;AAAA,MACzC,CAAC,QAAQ,QAAQ,iBAAiB,UAAU;AAAA,IAC9C;AAAA,EACF;AACF;","names":["ExactEvmSchemeERC4337","computeSafeMessageHash","toSafeSmartAccount","assetAmount","import_viem","import_account_abstraction","createViemBundlerClient","import_viem","import_viem","ExactEvmSchemeERC4337","bundlerUrl","import_viem","import_viem","import_viem","import_viem","import_accounts","import_viem","import_viem","import_accounts","toSafeSmartAccount","createMockLocalAccount","encodeWebAuthnSignature","toPermissionlessSafeSmartAccount","import_viem","SAFE_MSG_TYPEHASH","computeSafeMessageHash"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/constants.ts","../../src/exact/utils.ts","../../src/exact/utils/transformRoutes.ts","../../src/exact/server/scheme.ts","../../src/networks/registry.ts","../../src/networks/helpers.ts","../../src/exact/facilitator/bundler/types.ts","../../src/exact/facilitator/bundler/client.ts","../../src/exact/facilitator/scheme.ts","../../src/exact/client/schemes/erc4337.ts","../../src/exact/client/bundler/viem.ts","../../src/exact/client/signers/safeAccountSigner.ts","../../src/exact/client/signers/safeMessageSigners.ts","../../src/exact/client/utils/callData.ts","../../src/exact/client/utils/userOperation.ts","../../src/exact/client/errors.ts","../../src/exact/client/schemes/eip3009.ts","../../src/accounts/encodeContractSignature.ts","../../src/accounts/computeSafeMessageHash.ts","../../src/accounts/toSafeSmartAccount.ts","../../src/accounts/toP256SafeSmartAccount.ts","../../src/accounts/computeSafeOpHash.ts","../../src/accounts/toWebAuthnSafeSmartAccount.ts","../../src/accounts/extractPasskeyCoordinates.ts","../../src/stamp/safeMessageHash.ts"],"sourcesContent":["export * from \"./constants\";\nexport * from \"./exact\";\nexport * from \"./accounts\";\nexport * from \"./stamp\";\nexport * from \"./networks\";\n","import type { Hex } from \"viem\";\nimport { entryPoint07Address } from \"viem/account-abstraction\";\n\nexport { entryPoint07Address };\n\nexport const SAFE_4337_MODULE_ADDRESS =\n \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\" as const satisfies Hex;\n\nexport const SAFE_WEBAUTHN_SHARED_SIGNER =\n \"0xfD90FAd33ee8b58f32c00aceEad1358e4AFC23f9\" as const satisfies Hex;\n\nexport const FCL_P256_VERIFIER =\n \"0xA86e0054C51E4894D88762a017ECc5E5235f5DBA\" as const satisfies Hex;\n\nexport const P256_OWNER_FACTORY =\n \"0x349c03Eb61e26528cbf79F5D3Ba071FcA2aE82cB\" as const satisfies Hex;\n\nexport const WEBAUTHN_SIGNER_FACTORY =\n \"0xF7488fFbe67327ac9f37D5F722d83Fc900852Fbf\" as const satisfies Hex;\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n","import type { RoutesConfig, RouteConfig, HTTPRequestContext } from \"@x402/core/server\";\nimport type { Price, Network, AssetAmount } from \"@x402/core/types\";\nimport type { ExactEvmSchemeERC4337 } from \"../server/scheme\";\nimport type { PaymentOption, DynamicPrice } from \"@x402/core/http\";\nimport type { UserOperationCapability } from \"../types\";\n\n/**\n * Transforms routes to move userOperation from PaymentOption.extra to price.extra.\n *\n * This transformation enables userOperation to flow through the natural price.extra\n * path into PaymentRequirements.extra, allowing the official middleware to work\n * without modification.\n *\n * This is a workaround to allow the official middleware to work without modification.\n * and support this proposal https://github.com/coinbase/x402/issues/639\n *\n * @param routes - The routes configuration to transform (single RouteConfig or RoutesConfig object)\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns Transformed routes with userOperation moved to price.extra\n *\n * @example\n * ```typescript\n * import { transformRoutesForUserOperation } from '@introspectivelabs/x402-evm/exact/utils';\n * import { ExactEvmSchemeERC4337Server } from '@introspectivelabs/x402-evm/exact/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337Server();\n * const transformedRoutes = await transformRoutesForUserOperation(routes, schemeServer);\n * ```\n */\nexport async function transformRoutesForUserOperation(\n routes: RoutesConfig,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<RoutesConfig> {\n // Handle single RouteConfig\n if (\"accepts\" in routes) {\n return await transformRouteForUserOperation(routes as RouteConfig, schemeServer);\n }\n\n // Handle RoutesConfig object (Record<string, RouteConfig>)\n const transformed: Record<string, RouteConfig> = {};\n for (const [path, routeConfig] of Object.entries(routes as Record<string, RouteConfig>)) {\n transformed[path] = await transformRouteForUserOperation(routeConfig, schemeServer);\n }\n return transformed;\n}\n\n/**\n * Transforms a single RouteConfig to move userOperation from PaymentOption.extra to price.extra.\n *\n * @param routeConfig - The RouteConfig to transform\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed RouteConfig\n */\nexport async function transformRouteForUserOperation(\n routeConfig: RouteConfig,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<RouteConfig> {\n // Handle single PaymentOption\n if (!Array.isArray(routeConfig.accepts)) {\n return {\n ...routeConfig,\n accepts: await transformPaymentOption(routeConfig.accepts, schemeServer),\n };\n }\n\n // Handle array of PaymentOptions\n const transformedAccepts = await Promise.all(\n routeConfig.accepts.map(option => transformPaymentOption(option, schemeServer)),\n );\n\n return {\n ...routeConfig,\n accepts: transformedAccepts,\n };\n}\n\n/**\n * Transforms a PaymentOption to move userOperation from extra to price.extra.\n *\n * @param option - The PaymentOption to transform\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed PaymentOption\n */\nasync function transformPaymentOption(\n option: PaymentOption,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<PaymentOption> {\n // Extract userOperation from PaymentOption.extra\n const userOperation = option.extra?.userOperation as UserOperationCapability | undefined;\n\n // If no userOperation, return option as-is\n if (!userOperation || !userOperation.supported) {\n return option;\n }\n\n // Transform price to include userOperation in extra\n const transformedPrice = await transformPrice(\n option.price,\n option.network,\n userOperation,\n schemeServer,\n );\n\n // Remove userOperation from PaymentOption.extra\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { userOperation: _, ...restExtra } = option.extra || {};\n\n return {\n ...option,\n price: transformedPrice,\n extra: Object.keys(restExtra).length > 0 ? restExtra : undefined,\n };\n}\n\n/**\n * Transforms a price to include userOperation in its extra field.\n *\n * @param price - The price to transform\n * @param network - The network the price is for\n * @param userOperation - The user operation to include in the price\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed price\n */\nasync function transformPrice(\n price: Price | DynamicPrice,\n network: Network,\n userOperation: UserOperationCapability,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<Price | DynamicPrice> {\n // Handle function price (DynamicPrice)\n if (typeof price === \"function\") {\n return async (context: HTTPRequestContext): Promise<Price> => {\n const resolvedPrice = await price(context);\n return await injectUserOperationIntoPrice(\n resolvedPrice,\n network,\n userOperation,\n schemeServer,\n );\n };\n }\n\n // Handle static price (string, number, or AssetAmount)\n return await injectUserOperationIntoPrice(price, network, userOperation, schemeServer);\n}\n\n/**\n * Injects userOperation into a price's extra field.\n * Handles both string/number prices (parsed to AssetAmount) and AssetAmount prices.\n *\n * @param price - The price to inject the user operation into\n * @param network - The network the price is for\n * @param userOperation - The user operation to include in the price\n * @param schemeServer - The scheme server instance used for parsing prices\n * @returns The transformed price\n */\nasync function injectUserOperationIntoPrice(\n price: Price,\n network: Network,\n userOperation: UserOperationCapability,\n schemeServer: ExactEvmSchemeERC4337,\n): Promise<Price> {\n // If price is already an AssetAmount, add userOperation to extra\n if (typeof price === \"object\" && \"asset\" in price && \"amount\" in price) {\n const assetAmount = price as AssetAmount;\n return {\n ...assetAmount,\n extra: {\n ...assetAmount.extra,\n userOperation,\n },\n };\n }\n\n // If price is string or number, parse it to AssetAmount\n // Note: We need to preserve the original format if possible\n // For now, we'll parse and return as AssetAmount\n // The scheme server will handle the conversion back if needed\n const assetAmount = await schemeServer.parsePrice(price, network);\n\n return {\n ...assetAmount,\n extra: {\n ...assetAmount.extra,\n userOperation,\n },\n };\n}\n","import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n decimals: 6,\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism-sepolia.safe.global\",\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum-sepolia.safe.global\",\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","/**\n * Gas estimation response from bundler\n */\nexport interface GasEstimate {\n [key: string]: unknown;\n callGasLimit?: string;\n verificationGasLimit?: string;\n preVerificationGas?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n paymasterVerificationGasLimit?: string;\n paymasterPostOpGasLimit?: string;\n}\n\n/**\n * User operation receipt from bundler\n */\nexport interface UserOperationReceipt {\n [key: string]: unknown;\n userOpHash: string;\n entryPoint: string;\n sender: string;\n nonce: string;\n paymaster?: string;\n actualGasCost: string;\n actualGasUsed: string;\n success: boolean;\n reason?: string;\n logs: unknown[];\n receipt?: {\n [key: string]: unknown;\n transactionHash: string;\n };\n transactionHash?: string;\n}\n\n/**\n * Configuration for bundler client\n */\nexport interface BundlerClientConfig {\n /**\n * Timeout for RPC calls in milliseconds\n *\n * @default 10000\n */\n timeout?: number;\n /**\n * Number of retries for failed requests\n *\n * @default 0\n */\n retries?: number;\n}\n\n/**\n * JSON-RPC error response\n */\nexport interface JsonRpcError {\n message?: string;\n code?: number;\n data?: unknown;\n}\n\n/**\n * JSON-RPC response wrapper\n */\nexport interface JsonRpcResponse<T> {\n result?: T;\n error?: JsonRpcError;\n}\n\n/**\n * Custom error class for bundler-related errors\n */\nexport class BundlerError extends Error {\n readonly code?: number;\n readonly data?: unknown;\n readonly method?: string;\n readonly bundlerUrl?: string;\n\n /**\n * Creates a new BundlerError instance\n *\n * @param message - Error message\n * @param options - Optional error details\n * @param options.code - Error code from bundler\n * @param options.data - Additional error data\n * @param options.method - RPC method that failed\n * @param options.bundlerUrl - Bundler URL that was called\n * @param options.cause - Original error that caused this error\n */\n constructor(\n message: string,\n options?: {\n code?: number;\n data?: unknown;\n method?: string;\n bundlerUrl?: string;\n cause?: Error;\n },\n ) {\n super(message);\n this.name = \"BundlerError\";\n this.code = options?.code;\n this.data = options?.data;\n this.method = options?.method;\n this.bundlerUrl = options?.bundlerUrl;\n if (options?.cause) {\n // @ts-expect-error - cause is a standard Error property but not in all TypeScript versions\n this.cause = options.cause;\n }\n }\n}\n","import type {\n BundlerClientConfig,\n GasEstimate,\n JsonRpcResponse,\n UserOperationReceipt,\n} from \"./types\";\nimport { BundlerError } from \"./types\";\n\n/**\n * Bundler RPC client for ERC-4337 user operations\n */\nexport class BundlerClient {\n private readonly rpcUrl: string;\n private readonly config: Required<BundlerClientConfig>;\n\n /**\n * Creates a new BundlerClient instance\n *\n * @param rpcUrl - The bundler RPC URL\n * @param config - Optional configuration for the client\n */\n constructor(rpcUrl: string, config?: BundlerClientConfig) {\n this.rpcUrl = rpcUrl;\n this.config = {\n timeout: config?.timeout ?? 10_000,\n retries: config?.retries ?? 0,\n };\n }\n\n /**\n * Estimates gas for a user operation\n *\n * @param userOp - The user operation to estimate gas for\n * @param entryPoint - The entry point address\n * @returns Gas estimates\n * @throws BundlerError if the estimation fails\n */\n async estimateUserOperationGas(\n userOp: Record<string, unknown>,\n entryPoint: string,\n ): Promise<GasEstimate> {\n return this.call<GasEstimate>(\"eth_estimateUserOperationGas\", [userOp, entryPoint]);\n }\n\n /**\n * Sends a user operation to the bundler\n *\n * @param userOp - The user operation to send\n * @param entryPoint - The entry point address\n * @returns The user operation hash\n * @throws BundlerError if sending fails\n */\n async sendUserOperation(userOp: Record<string, unknown>, entryPoint: string): Promise<string> {\n return this.call<string>(\"eth_sendUserOperation\", [userOp, entryPoint]);\n }\n\n /**\n * Gets the receipt for a user operation\n *\n * @param userOpHash - The user operation hash\n * @returns The receipt or null if not found\n * @throws BundlerError if the request fails\n */\n async getUserOperationReceipt(userOpHash: string): Promise<UserOperationReceipt | null> {\n return this.call<UserOperationReceipt | null>(\"eth_getUserOperationReceipt\", [userOpHash]);\n }\n\n /**\n * Makes a JSON-RPC call to the bundler\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @returns The result from the RPC call\n * @throws BundlerError if the call fails\n */\n private async call<T>(method: string, params: unknown[]): Promise<T> {\n const requestPayload = {\n jsonrpc: \"2.0\" as const,\n id: 1,\n method,\n params,\n };\n\n let lastError: Error | undefined;\n const maxAttempts = this.config.retries + 1;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n const res = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(requestPayload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!res.ok) {\n throw new BundlerError(`Bundler HTTP error: ${res.status} ${res.statusText}`, {\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n const json = (await res.json()) as JsonRpcResponse<T>;\n\n if (json.error) {\n throw new BundlerError(json.error.message ?? \"Bundler RPC error\", {\n code: json.error.code,\n data: json.error.data,\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n if (json.result === undefined) {\n throw new BundlerError(\"Bundler RPC returned no result\", {\n method,\n bundlerUrl: this.rpcUrl,\n });\n }\n\n return json.result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // If it's an abort error (timeout), don't retry\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new BundlerError(`Bundler request timeout after ${this.config.timeout}ms`, {\n method,\n bundlerUrl: this.rpcUrl,\n cause: error,\n });\n }\n\n // If this is the last attempt, throw the error\n if (attempt === maxAttempts - 1) {\n if (error instanceof BundlerError) {\n throw error;\n }\n throw new BundlerError(`Bundler request failed: ${lastError.message}`, {\n method,\n bundlerUrl: this.rpcUrl,\n cause: lastError,\n });\n }\n\n // Wait before retrying (exponential backoff)\n await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 100));\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw new BundlerError(\"Bundler request failed after retries\", {\n method,\n bundlerUrl: this.rpcUrl,\n cause: lastError,\n });\n }\n}\n","import type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { BundlerClient } from \"./bundler/client\";\nimport type { Erc4337Payload } from \"./types\";\n\n/**\n * Configuration for the ERC-4337 facilitator\n */\nexport interface ExactEvmSchemeNetworkERC4337Config {\n /**\n * Default bundler URL to use if not provided in payload or requirements\n */\n\n defaultBundlerUrl?: string;\n\n /**\n * Timeout for receipt polling in milliseconds\n *\n * @default 30000\n */\n\n receiptPollTimeout?: number;\n\n /**\n * Interval for receipt polling in milliseconds\n *\n * @default 1000\n */\n\n receiptPollInterval?: number;\n}\n\n/**\n * Enhanced ExactEvmScheme facilitator that supports UserOperation (ERC-4337) payments.\n *\n * This facilitator implements the `SchemeNetworkFacilitator` interface and handles\n * verification and settlement of user operations through a bundler.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeNetworkERC4337 } from '@introspectivelabs/x402-evm/exact/facilitator';\n * import { x402Facilitator } from '@x402/core/facilitator';\n *\n * const facilitator = new x402Facilitator()\n * .register('eip155:84532', new ExactEvmSchemeNetworkERC4337());\n * ```\n */\nexport class ExactEvmSchemeNetworkERC4337 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required<ExactEvmSchemeNetworkERC4337Config>;\n\n /**\n * Creates a new ExactEvmSchemeNetworkERC4337 instance\n *\n * @param config - Optional configuration for the facilitator\n */\n constructor(config?: ExactEvmSchemeNetworkERC4337Config) {\n this.config = {\n defaultBundlerUrl: config?.defaultBundlerUrl ?? \"\",\n receiptPollTimeout: config?.receiptPollTimeout ?? 30_000,\n receiptPollInterval: config?.receiptPollInterval ?? 1_000,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * Returns user operation capability if available.\n *\n * @param _ - The network identifier (unused, but required by interface)\n * @returns User operation capability or undefined\n */\n getExtra(_: Network): Record<string, unknown> | undefined {\n // Return undefined - user operation capability should be set by the server\n // This follows the pattern of the original ExactEvmScheme\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * For user operations, no facilitator signer is needed as the user signs the operation.\n *\n * @param _ - The network identifier (unused, but required by interface)\n * @returns Empty array (no facilitator signer needed)\n */\n getSigners(_: string): string[] {\n return [];\n }\n\n /**\n * Verifies a payment payload containing a user operation.\n *\n * This method:\n * - Extracts the user operation from the payload\n * - Gets the bundler URL from payload, requirements, or config\n * - Estimates gas using the bundler to validate the user operation\n *\n * @param payload - The payment payload containing the user operation\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const erc4337Payload = payload.payload as Erc4337Payload;\n\n // Extract user operation\n if (!erc4337Payload.userOperation) {\n return {\n isValid: false,\n invalidReason: \"missing_user_operation\",\n payer: undefined,\n };\n }\n\n const userOp = erc4337Payload.userOperation;\n const payer = userOp.sender;\n\n // Get bundler URL from payload, requirements, or config\n const bundlerUrl =\n erc4337Payload.bundlerRpcUrl ??\n (requirements.extra?.userOperation as { bundlerUrl?: string } | undefined)?.bundlerUrl ??\n this.config.defaultBundlerUrl;\n\n if (!bundlerUrl) {\n return {\n isValid: false,\n invalidReason: \"missing_bundler_url\",\n payer,\n };\n }\n\n // Get entry point\n const entryPoint = erc4337Payload.entryPoint;\n if (!entryPoint) {\n return {\n isValid: false,\n invalidReason: \"missing_entry_point\",\n payer,\n };\n }\n\n // Verify by estimating gas through bundler\n try {\n const bundler = new BundlerClient(bundlerUrl);\n await bundler.estimateUserOperationGas(userOp, entryPoint);\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n } catch (error) {\n return {\n isValid: false,\n invalidReason: (error as Error).message,\n payer,\n };\n }\n }\n\n /**\n * Settles a payment by sending the user operation to the bundler.\n *\n * This method:\n * - Re-verifies the payment (following original pattern)\n * - Sends the user operation to the bundler\n * - Polls for the receipt\n * - Returns the transaction hash\n *\n * @param payload - The payment payload containing the user operation\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const erc4337Payload = payload.payload as Erc4337Payload;\n\n // Re-verify before settling (following original pattern)\n const verifyResult = await this.verify(payload, requirements);\n if (!verifyResult.isValid) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: verifyResult.invalidReason ?? \"invalid\",\n payer: verifyResult.payer,\n };\n }\n\n const userOp = erc4337Payload.userOperation;\n const payer = userOp.sender;\n\n // Get bundler URL\n const bundlerUrl =\n erc4337Payload.bundlerRpcUrl ??\n (requirements.extra?.userOperation as { bundlerUrl?: string } | undefined)?.bundlerUrl ??\n this.config.defaultBundlerUrl;\n\n if (!bundlerUrl) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: \"missing_bundler_url\",\n payer,\n };\n }\n\n const entryPoint = erc4337Payload.entryPoint;\n if (!entryPoint) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: \"missing_entry_point\",\n payer,\n };\n }\n\n try {\n const bundler = new BundlerClient(bundlerUrl);\n\n // Send user operation\n const userOpHash = await bundler.sendUserOperation(userOp, entryPoint);\n\n // Poll for receipt\n const deadline = Date.now() + this.config.receiptPollTimeout;\n let receipt = null;\n\n while (Date.now() < deadline) {\n receipt = await bundler.getUserOperationReceipt(userOpHash);\n if (receipt) {\n break;\n }\n await new Promise(resolve => setTimeout(resolve, this.config.receiptPollInterval));\n }\n\n // Extract transaction hash from receipt\n const txHash = receipt?.receipt?.transactionHash ?? receipt?.transactionHash ?? userOpHash;\n\n return {\n success: true,\n network: payload.accepted.network,\n transaction: txHash,\n payer,\n errorReason: undefined,\n };\n } catch (error) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: \"\",\n errorReason: (error as Error).message,\n payer,\n };\n }\n }\n}\n","import type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n getAddress,\n createPublicClient,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n Hex,\n} from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport { defineChain } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport type { BundlerClient } from \"../bundler\";\nimport { ViemBundlerClient } from \"../bundler/viem\";\nimport type { UserOperationSigner } from \"../signers\";\nimport { SafeAccountSigner } from \"../signers\";\nimport { extractUserOperationCapability } from \"../../utils\";\nimport type { Erc4337Payload } from \"../../facilitator/types\";\nimport { buildERC20TransferCallData } from \"../utils/callData\";\nimport { userOpToJson } from \"../utils/userOperation\";\nimport { PaymentCreationError, parseAAError } from \"../errors\";\nimport { resolveChainId } from \"../../../networks\";\n\n/**\n * Base configuration properties shared by all configuration variants\n */\ninterface ExactEvmSchemeERC4337ConfigBase {\n /**\n * Entry point address (EntryPoint v0.7)\n * Optional - can be provided in payment requirements if not set here\n */\n entrypoint?: Hex;\n\n /**\n * Bundler URL (optional, can be provided in payment requirements)\n */\n bundlerUrl?: string;\n}\n\n/**\n * Configuration variant when bundlerClient is explicitly provided.\n * Account and publicClient are NOT needed when bundlerClient is used.\n * Signer is required when using bundlerClient.\n */\ntype ExactEvmSchemeERC4337ConfigWithBundler = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client for preparing and sending user operations.\n */\n bundlerClient: BundlerClient;\n /**\n * Signer for signing user operations (required when bundlerClient is provided).\n */\n signer: UserOperationSigner;\n} & {\n /**\n * Account must not be provided when bundlerClient is used.\n * Using `never` type prevents this property from being set.\n */\n account?: never;\n /**\n * Public client must not be provided when bundlerClient is used.\n * The bundlerClient already has its own publicClient configured.\n */\n publicClient?: never;\n};\n\n/**\n * Configuration variant when bundlerClient is not provided.\n * Account is required for dynamic bundlerClient creation.\n * Signer is optional - will be auto-created from account if not provided.\n * PublicClient is optional - will create a default from network if not provided.\n */\ntype ExactEvmSchemeERC4337ConfigWithAccount = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client is not provided - will be created dynamically from PaymentRequirements.\n * Using `never` type prevents this property from being set.\n */\n bundlerClient?: never;\n} & {\n /**\n * Smart account for user operation preparation.\n * Required when bundlerClient is not provided.\n */\n account: SmartAccount;\n /**\n * Signer for signing user operations.\n * Optional - will be auto-created from account using SafeAccountSigner if not provided.\n * The account must support signUserOperation method for auto-creation to work.\n */\n signer?: UserOperationSigner;\n /**\n * Public client for blockchain interactions.\n * Optional - will create a default from network if not provided.\n */\n publicClient?: PublicClient<Transport, Chain>;\n};\n\n/**\n * Configuration for the ERC-4337 client scheme.\n *\n * This is a discriminated union that enforces type-safe combinations:\n * - Either `bundlerClient` is provided (account and publicClient must NOT be provided)\n * - Or `account` is provided when bundlerClient is not (for dynamic creation, publicClient optional)\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer auto-created)\n * const scheme1 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * // signer will be auto-created from account\n * // bundlerClient will be created dynamically from PaymentRequirements\n * });\n *\n * // With account and custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * signer: myCustomSigner,\n * publicClient: myPublicClient, // Optional\n * });\n *\n * // With explicit bundlerClient (backward compatible)\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient: myBundlerClient,\n * signer: mySigner, // Required when bundlerClient is provided\n * // account and publicClient must NOT be provided (bundlerClient has its own)\n * });\n * ```\n */\nexport type ExactEvmSchemeERC4337Config =\n | ExactEvmSchemeERC4337ConfigWithBundler\n | ExactEvmSchemeERC4337ConfigWithAccount;\n\n/**\n * Resolves a network string to a Chain object.\n * Handles both CAIP-2 format (\"eip155:84532\") and v1 plain names (\"base-sepolia\").\n *\n * @param network - Network string in CAIP-2 or v1 plain name format\n * @returns The Chain object\n */\nfunction resolveChain(network: string): Chain {\n const chainId = resolveChainId(network);\n\n const known = Object.values(allChains).find((c: Chain) => c.id === chainId);\n if (known) return known;\n\n return defineChain({\n id: chainId,\n name: network,\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: { default: { http: [] } },\n });\n}\n\n/**\n * Creates a default public client from a network string.\n *\n * @param network - The network string in CAIP-2 format (e.g., \"eip155:84532\")\n * @returns A PublicClient instance\n */\nfunction createDefaultPublicClient(network: string): PublicClient<Transport, Chain> {\n const chain = resolveChain(network);\n return createPublicClient({\n chain,\n transport: http(),\n });\n}\n\n/**\n * EVM client implementation for the Exact payment scheme using ERC-4337 UserOperations.\n *\n * This implementation creates payment payloads by building and signing UserOperations\n * that execute ERC20 transfers. The UserOperations are prepared using a bundler client\n * and signed using a user operation signer (e.g., Safe account, EOA).\n *\n * Supports minimal configuration: when bundlerClient is not provided and\n * PaymentRequirements.extra.userOperation.supported is true, a ViemBundlerClient\n * will be created dynamically from the payment requirements.\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer and bundlerClient auto-created)\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/client';\n * import { x402Client } from '@x402/core/client';\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * account: safeAccount, // SmartAccount - signer will be auto-created\n * });\n *\n * // With custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: safeAccount,\n * signer: customSigner, // Optional - overrides auto-creation\n * });\n *\n * // Explicit config (backward compatible)\n * import { ViemBundlerClient } from '@introspectivelabs/x402-evm/exact/client/bundler';\n *\n * const bundlerClient = new ViemBundlerClient({\n * publicClient,\n * account,\n * chain,\n * bundlerUrl: 'https://bundler.example.com',\n * });\n *\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer: account, // Required when bundlerClient is provided\n * });\n *\n * const client = new x402Client();\n * client.register('eip155:84532', scheme);\n * ```\n */\nexport class ExactEvmSchemeERC4337 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly bundlerClient?: BundlerClient;\n private readonly account?: SmartAccount;\n private readonly publicClient?: PublicClient<Transport, Chain>;\n private readonly signer: UserOperationSigner;\n private readonly entrypoint?: Hex;\n private readonly bundlerUrl?: string;\n\n /**\n * Creates a new ExactEvmSchemeERC4337 instance.\n *\n * @param config - Configuration for the scheme (type-safe: either bundlerClient or account must be provided)\n * @throws Error if bundlerClient is not provided and account is also not provided (runtime safety check)\n * @throws Error if signer is not provided and account doesn't support signUserOperation\n */\n constructor(config: ExactEvmSchemeERC4337Config) {\n this.bundlerClient = config.bundlerClient;\n this.account = config.account;\n this.publicClient = config.publicClient;\n this.entrypoint = config.entrypoint;\n this.bundlerUrl = config.bundlerUrl;\n\n // Validate: if bundlerClient is not provided, account must be provided\n if (!this.bundlerClient && !this.account) {\n throw new Error(\n \"Either bundlerClient or account must be provided. \" +\n \"If bundlerClient is not provided, account (SmartAccount) is required for dynamic bundlerClient creation.\",\n );\n }\n\n // Handle signer: use provided signer or auto-create from account\n if (config.signer) {\n this.signer = config.signer;\n } else if (this.account) {\n // Auto-create signer from account if not provided\n if (!this.account.signUserOperation) {\n throw new Error(\n \"Account does not support signUserOperation. \" +\n \"Either provide a signer explicitly or use an account that supports signUserOperation.\",\n );\n }\n this.signer = new SafeAccountSigner(this.account);\n } else {\n // This should not happen due to type system, but add runtime check for safety\n throw new Error(\n \"Signer is required when bundlerClient is provided. \" +\n \"Either provide a signer explicitly or use account-based configuration.\",\n );\n }\n }\n\n /**\n * Creates a payment payload for the Exact scheme using ERC-4337 UserOperations.\n *\n * This method:\n * 1. Extracts user operation capability from payment requirements\n * 2. Creates bundlerClient dynamically if not provided (when userOperation.supported is true)\n * 3. Builds ERC20 transfer call data\n * 4. Prepares the user operation using the bundler client\n * 5. Signs the user operation\n * 6. Converts to JSON-RPC format\n * 7. Returns the x402 payment payload\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n * @throws Error if user operation capability is not found or required fields are missing\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n // Extract user operation capability (optional - config defaults used when missing)\n const capability = extractUserOperationCapability(paymentRequirements);\n\n // Determine which bundlerClient to use\n let bundlerClient: BundlerClient;\n\n if (this.bundlerClient) {\n // Use provided bundlerClient (explicit config, backward compatible)\n bundlerClient = this.bundlerClient;\n } else {\n // Create bundlerClient dynamically from PaymentRequirements\n if (!this.account) {\n throw new Error(\n \"Account (SmartAccount) is required when bundlerClient is not provided. \" +\n \"Either provide bundlerClient in config or account for dynamic creation.\",\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Derive chain from network (supports both CAIP-2 and v1 plain names)\n const chain = resolveChain(paymentRequirements.network);\n\n // Use provided publicClient or create default from network\n const publicClient =\n this.publicClient ?? createDefaultPublicClient(paymentRequirements.network);\n\n // Create ViemBundlerClient dynamically\n bundlerClient = new ViemBundlerClient({\n publicClient,\n account: this.account,\n chain,\n bundlerUrl,\n });\n }\n\n // Get entry point (prioritize config defaults over PaymentRequirements)\n const entryPoint = this.entrypoint ?? (capability?.entrypoint as `0x${string}` | undefined);\n\n if (!entryPoint) {\n throw new PaymentCreationError(\n \"Entry point not provided\",\n {\n phase: \"validation\",\n reason: \"Set entrypoint in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.entrypoint\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Normalize addresses\n const token = getAddress(paymentRequirements.asset);\n const payTo = getAddress(paymentRequirements.payTo);\n // Handle both v2 (amount) and v1 (maxAmountRequired) fields\n const amountStr =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n if (!amountStr) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n const amount = BigInt(amountStr);\n\n // Build ERC20 transfer call data\n const callData = buildERC20TransferCallData(token, payTo, amount);\n\n // Prepare user operation (unsigned)\n let unsignedUserOp;\n try {\n unsignedUserOp = await bundlerClient.prepareUserOperation(\n [\n {\n to: token,\n value: BigInt(0), // ERC20 transfers don't send ETH\n data: callData,\n },\n ],\n entryPoint,\n );\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment preparation failed: ${aaError.reason}`\n : `Payment preparation failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"preparation\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Sign the user operation\n let signature;\n try {\n signature = await this.signer.signUserOperation(unsignedUserOp);\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment signing failed: ${aaError.reason}`\n : `Payment signing failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"signing\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Create signed user operation\n const signedUserOp = {\n ...unsignedUserOp,\n signature,\n };\n\n // Convert to JSON-RPC format (bigint -> hex)\n const jsonUserOp = userOpToJson(signedUserOp);\n\n // Build the ERC-4337 payload\n const payload: Erc4337Payload = {\n type: \"erc4337\",\n entryPoint,\n bundlerRpcUrl: bundlerUrl,\n userOperation: jsonUserOp,\n };\n\n return {\n x402Version,\n // v1 requires scheme and network at top level\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import type { Chain, PublicClient, Transport } from \"viem\";\nimport { http } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { createBundlerClient as createViemBundlerClient } from \"viem/account-abstraction\";\nimport type {\n BundlerClient,\n BundlerClientConfig,\n GasEstimate,\n PreparedUserOperation,\n UserOperationCall,\n} from \"./client\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Configuration for creating a viem-based bundler client\n */\nexport interface ViemBundlerClientConfig extends BundlerClientConfig {\n /**\n * Viem public client for blockchain interactions\n */\n publicClient: PublicClient<Transport, Chain>;\n\n /**\n * Smart account for user operation preparation (must be a SmartAccount, not a regular Account)\n */\n account: SmartAccount;\n\n /**\n * Chain configuration\n */\n chain: Chain;\n\n /**\n * Bundler RPC URL\n */\n bundlerUrl: string;\n}\n\n/**\n * Viem-based implementation of BundlerClient.\n * Uses viem's account-abstraction utilities for user operation handling.\n */\nexport class ViemBundlerClient implements BundlerClient {\n private readonly bundlerClient: ReturnType<typeof createViemBundlerClient>;\n private readonly account: SmartAccount;\n private readonly entryPoint: `0x${string}`;\n\n /**\n * Creates a new ViemBundlerClient instance.\n *\n * @param config - Configuration for the bundler client\n */\n constructor(config: ViemBundlerClientConfig) {\n this.account = config.account;\n this.entryPoint = \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\" as `0x${string}`; // EntryPoint v0.7\n\n // Create viem bundler client with bundler-specific transport\n this.bundlerClient = createViemBundlerClient({\n client: config.publicClient,\n chain: config.chain,\n account: config.account,\n transport: http(config.bundlerUrl),\n });\n }\n\n /**\n * Prepares an unsigned user operation for the given calls.\n *\n * @param calls - Array of calls to execute in the user operation\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to a prepared (unsigned) user operation\n */\n async prepareUserOperation(\n calls: UserOperationCall[],\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<PreparedUserOperation> {\n const prepared = await this.bundlerClient.prepareUserOperation({\n account: this.account,\n calls: calls.map(call => ({\n to: call.to,\n value: call.value,\n data: call.data,\n })),\n });\n\n // viem v2 EntryPoint v0.7 returns separate fields (not v0.6 paymasterAndData)\n const p = prepared as Record<string, unknown>;\n\n return {\n sender: prepared.sender,\n nonce: prepared.nonce,\n callData: prepared.callData,\n callGasLimit: prepared.callGasLimit,\n verificationGasLimit: prepared.verificationGasLimit,\n preVerificationGas: prepared.preVerificationGas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n // v0.7 factory fields (for account deployment)\n ...(p.factory ? { factory: p.factory as `0x${string}` } : {}),\n ...(p.factoryData ? { factoryData: p.factoryData as `0x${string}` } : {}),\n // v0.7 paymaster fields (separate, not paymasterAndData)\n ...(p.paymaster ? { paymaster: p.paymaster as `0x${string}` } : {}),\n ...(p.paymasterData ? { paymasterData: p.paymasterData as `0x${string}` } : {}),\n ...(p.paymasterVerificationGasLimit != null\n ? { paymasterVerificationGasLimit: p.paymasterVerificationGasLimit as bigint }\n : {}),\n ...(p.paymasterPostOpGasLimit != null\n ? { paymasterPostOpGasLimit: p.paymasterPostOpGasLimit as bigint }\n : {}),\n signature: prepared.signature,\n } as PreparedUserOperation;\n }\n\n /**\n * Estimates gas for a user operation.\n * Note: This is typically done as part of prepareUserOperation,\n * but is available as a separate method for flexibility.\n *\n * @param _userOp - The user operation to estimate gas for\n * @param _entryPoint - The entry point address\n * @returns Promise resolving to gas estimates\n */\n async estimateGas(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<GasEstimate> {\n // Note: Gas estimation is typically done as part of prepareUserOperation\n // This method is provided for flexibility but may not be used in practice\n // The return type from estimateUserOperationGas doesn't include maxFeePerGas/maxPriorityFeePerGas\n // as those are determined by the network, not the bundler\n throw new Error(\n \"estimateGas should be called through prepareUserOperation, which includes gas estimation\",\n );\n }\n\n /**\n * Sends a user operation to the bundler.\n *\n * @param userOp - The signed user operation to send\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to the user operation hash\n */\n async sendUserOperation(\n userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<string> {\n // Convert JSON user operation to format expected by viem\n // viem's sendUserOperation accepts UserOperation fields directly (not nested)\n const hash = await this.bundlerClient.sendUserOperation({\n account: this.account,\n sender: userOp.sender as `0x${string}`,\n nonce: BigInt(userOp.nonce),\n callData: userOp.callData as `0x${string}`,\n callGasLimit: BigInt(userOp.callGasLimit),\n verificationGasLimit: BigInt(userOp.verificationGasLimit),\n preVerificationGas: BigInt(userOp.preVerificationGas),\n maxFeePerGas: BigInt(userOp.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(userOp.maxPriorityFeePerGas),\n // Combine paymaster and paymasterData into paymasterAndData\n paymasterAndData:\n userOp.paymaster && userOp.paymasterData\n ? ((userOp.paymaster + userOp.paymasterData.slice(2)) as `0x${string}`)\n : userOp.paymaster\n ? (userOp.paymaster as `0x${string}`)\n : (\"0x\" as `0x${string}`),\n signature: userOp.signature as `0x${string}`,\n });\n\n return hash;\n }\n}\n","import type { SmartAccount } from \"viem/account-abstraction\";\nimport type { PreparedUserOperation } from \"../bundler\";\nimport type { UserOperationSigner } from \"./types\";\n\n/**\n * Adapter to make a SmartAccount (e.g., Safe account) work as a UserOperationSigner.\n *\n * This class wraps a SmartAccount that supports `signUserOperation` and adapts it\n * to the UserOperationSigner interface required by the x402 ERC-4337 scheme.\n *\n * @example\n * ```typescript\n * import { SafeAccountSigner } from \"@introspectivelabs/x402-evm/exact/client\";\n * import { toSafeSmartAccount } from \"permissionless/accounts\";\n *\n * const safeAccount = await toSafeSmartAccount({ ... });\n * const signer = new SafeAccountSigner(safeAccount);\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer,\n * });\n * ```\n */\nexport class SafeAccountSigner implements UserOperationSigner {\n readonly address: `0x${string}`;\n\n /**\n * Creates a new SafeAccountSigner instance.\n *\n * @param account - The SmartAccount instance (e.g., from permissionless/accounts)\n * @throws Error if the account is not initialized or missing an address\n */\n constructor(private readonly account: SmartAccount) {\n if (!account?.address) {\n throw new Error(\"Smart account not initialized\");\n }\n this.address = account.address as `0x${string}`;\n }\n\n /**\n * Signs a prepared (unsigned) user operation.\n *\n * @param userOp - The prepared user operation to sign\n * @returns Promise resolving to the signature\n * @throws Error if the account does not support signUserOperation\n */\n async signUserOperation(userOp: PreparedUserOperation): Promise<`0x${string}`> {\n if (!this.account?.signUserOperation) {\n throw new Error(\"Smart account does not support signUserOperation\");\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await this.account.signUserOperation(userOp as any);\n }\n}\n","import { type Hex, concat, encodeAbiParameters } from \"viem\";\nimport type { WebAuthnAccount } from \"viem/account-abstraction\";\nimport type { P256Signer, SafeMessageSigner } from \"../../../accounts/types\";\n\n/**\n * Creates a SafeMessageSigner from a P256Signer.\n * The sign method returns concat([r, s]) (64 bytes raw P256 signature).\n */\nexport function createP256SafeMessageSigner(\n p256Signer: P256Signer,\n): SafeMessageSigner {\n return {\n ownerAddress: p256Signer.p256OwnerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n const { r, s } = await p256Signer.sign(safeMessageHash);\n return concat([r, s]);\n },\n };\n}\n\n/**\n * Creates a SafeMessageSigner from a WebAuthnAccount.\n * The sign method triggers navigator.credentials.get() and returns\n * ABI-encoded WebAuthn struct compatible with Safe's verifier.\n *\n * @param webAuthnAccount - viem WebAuthnAccount (wraps credential + getFn)\n * @param deployedSignerAddress - Address of the per-credential signer deployed\n * via SafeWebAuthnSignerFactory (NOT the SharedSigner)\n */\nexport function createWebAuthnSafeMessageSigner(\n webAuthnAccount: WebAuthnAccount,\n deployedSignerAddress: Hex,\n): SafeMessageSigner {\n return {\n ownerAddress: deployedSignerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n return encodeWebAuthnSignature(webAuthnAccount, safeMessageHash);\n },\n };\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n","import { encodeFunctionData } from \"viem\";\n\n/**\n * Standard ERC20 transfer function ABI\n */\nexport const ERC20_TRANSFER_ABI = [\n {\n type: \"function\",\n name: \"transfer\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n/**\n * Builds ERC20 transfer call data.\n *\n * @param token - The ERC20 token contract address\n * @param to - The recipient address\n * @param amount - The amount to transfer (in token's smallest unit)\n * @returns The encoded call data for the transfer function\n */\nexport function buildERC20TransferCallData(\n token: `0x${string}`,\n to: `0x${string}`,\n amount: bigint,\n): `0x${string}` {\n return encodeFunctionData({\n abi: ERC20_TRANSFER_ABI,\n functionName: \"transfer\",\n args: [to, amount],\n });\n}\n","import type { Hex } from \"viem\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Converts a bigint value to a hex string in JSON-RPC format.\n *\n * @param value - The bigint value to convert\n * @returns The hex string representation\n */\nfunction toRpcHex(value: bigint): Hex {\n return `0x${value.toString(16)}` as Hex;\n}\n\n/**\n * Converts a user operation with bigint values to JSON-RPC compatible format.\n * This recursively converts all bigint values to hex strings.\n *\n * @param userOp - The user operation object (may contain bigints)\n * @returns The user operation in JSON-RPC format (all bigints converted to hex)\n */\nexport function userOpToJson(userOp: Record<string, unknown>): UserOperation07Json {\n const json: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(userOp)) {\n // Skip internal viem fields that bundlers reject\n if (key === \"account\") continue;\n\n if (typeof value === \"bigint\") {\n json[key] = toRpcHex(value);\n } else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n // Recursively handle nested objects with bigints\n const inner: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n inner[k] = typeof v === \"bigint\" ? toRpcHex(v) : v;\n }\n json[key] = inner;\n } else {\n json[key] = value;\n }\n }\n\n return json as UserOperation07Json;\n}\n","export type PaymentCreationPhase = \"preparation\" | \"signing\" | \"validation\";\n\nconst AA_ERROR_MESSAGES: Record<string, string> = {\n AA10: \"Sender already constructed\",\n AA13: \"InitCode failed or OOG\",\n AA14: \"InitCode must return sender\",\n AA15: \"InitCode must create sender\",\n AA20: \"Account not deployed\",\n AA21: \"Insufficient funds for gas prefund\",\n AA22: \"Expired or not due\",\n AA23: \"Reverted (or OOG)\",\n AA24: \"Signature validation failed\",\n AA25: \"Nonce validation failed\",\n AA26: \"Account accessed global state\",\n AA30: \"Paymaster not deployed\",\n AA31: \"Paymaster deposit too low\",\n AA32: \"Paymaster expired or not due\",\n AA33: \"Paymaster reverted (or OOG)\",\n AA34: \"Paymaster context reverted\",\n AA40: \"Over verification gas limit\",\n AA41: \"Over max fee per gas\",\n AA50: \"Over max priority fee per gas\",\n AA51: \"Prefund below actualGasCost\",\n};\n\n/**\n * Extracts an AA error code (e.g. \"AA21\") from an error and returns\n * a human-readable reason. Returns null if no AA code is found.\n */\nexport function parseAAError(error: unknown): { code: string; reason: string } | null {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/\\b(AA[0-9]{2})\\b/);\n if (!match) return null;\n const code = match[1];\n const reason = AA_ERROR_MESSAGES[code] ?? \"Unknown AA error\";\n return { code, reason };\n}\n\nexport class PaymentCreationError extends Error {\n readonly phase: PaymentCreationPhase;\n readonly reason: string;\n readonly safeAddress?: string;\n readonly network?: string;\n readonly code?: string;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n phase: PaymentCreationPhase;\n reason: string;\n safeAddress?: string;\n network?: string;\n code?: string;\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"PaymentCreationError\";\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n this.phase = options.phase;\n this.reason = options.reason;\n this.safeAddress = options.safeAddress;\n this.network = options.network;\n this.code = options.code;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n phase: this.phase,\n reason: this.reason,\n ...(this.code && { code: this.code }),\n ...(this.safeAddress && { safeAddress: this.safeAddress }),\n ...(this.network && { network: this.network }),\n };\n }\n}\n","import type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport {\n type Hex,\n getAddress,\n hashTypedData,\n toHex,\n} from \"viem\";\nimport type { SafeMessageSigner } from \"../../../accounts/types\";\nimport { encodeContractSignature } from \"../../../accounts/encodeContractSignature\";\nimport { computeSafeMessageHash } from \"../../../accounts/computeSafeMessageHash\";\nimport { resolveChainId } from \"../../../networks\";\n\nconst authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\nfunction createNonce(): Hex {\n const cryptoObj = globalThis.crypto;\n if (!cryptoObj) throw new Error(\"Crypto API not available\");\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n\nexport interface ExactEvmSchemeEIP3009Config {\n safeAddress: Hex;\n signer: SafeMessageSigner;\n}\n\n/**\n * EVM client scheme that produces standard EIP-3009 `{ authorization, signature }`\n * payloads from a Safe Smart Account using EIP-1271 contract signatures.\n *\n * Unlike ExactEvmSchemeERC4337 (which creates UserOperation payloads), this scheme\n * creates payloads compatible with any standard x402 facilitator. The facilitator\n * verifies via `verifyTypedData` (which falls back to EIP-1271 for contract addresses)\n * and settles via `transferWithAuthorization(bytes)` (which uses SignatureChecker).\n *\n * Signing flow:\n * 1. Build EIP-3009 authorization (from=Safe, to=payTo, value, nonce, etc.)\n * 2. Compute EIP-712 hash of the authorization\n * 3. Wrap in Safe's message hash (what isValidSignature expects)\n * 4. Sign the Safe message hash via SafeMessageSigner (P256 or WebAuthn)\n * 5. Encode as Safe contract signature (v=0 format)\n *\n * Prerequisites:\n * - Safe must be deployed (EIP-1271 requires on-chain code)\n * - Safe must hold USDC balance (EIP-3009 transfers directly)\n * - USDC must support transferWithAuthorization(bytes) overload (v2.2+)\n */\nexport class ExactEvmSchemeEIP3009 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly safeAddress: Hex;\n private readonly signer: SafeMessageSigner;\n\n constructor(config: ExactEvmSchemeEIP3009Config) {\n this.safeAddress = config.safeAddress;\n this.signer = config.signer;\n }\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n const chainId = resolveChainId(paymentRequirements.network);\n\n // v1 uses maxAmountRequired, v2 uses amount\n const amount =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n\n if (!amount) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization = {\n from: getAddress(this.safeAddress),\n to: getAddress(paymentRequirements.payTo),\n value: amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Build EIP-712 domain from payment requirements extra fields\n const extra = paymentRequirements.extra as Record<string, unknown> | undefined;\n if (!extra?.name || !extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`,\n );\n }\n\n const domain = {\n name: extra.name as string,\n version: extra.version as string,\n chainId,\n verifyingContract: getAddress(paymentRequirements.asset) as Hex,\n };\n\n const message = {\n from: getAddress(authorization.from) as Hex,\n to: getAddress(authorization.to) as Hex,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as Hex,\n };\n\n // Step 1: Compute the EIP-712 typed data hash\n const eip712Hash = hashTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Step 2: Wrap in Safe's message hash (what Safe.isValidSignature expects)\n const safeMessageHash = computeSafeMessageHash(\n this.safeAddress,\n chainId,\n eip712Hash,\n );\n\n // Step 3: Sign the Safe message hash (P256 or WebAuthn)\n const innerSignature = await this.signer.sign(safeMessageHash);\n\n // Step 4: Encode as Safe contract signature (v=0)\n const signature = encodeContractSignature(\n this.signer.ownerAddress,\n innerSignature,\n );\n\n const payload = { authorization, signature };\n\n return {\n x402Version,\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import { type Hex, concat, pad, toHex } from \"viem\";\n\n/**\n * Encodes a signature in Safe's contract signature format (v=0).\n *\n * Safe's `checkNSignatures` expects this layout for contract owners:\n *\n * Static part (65 bytes):\n * - r (32 bytes): owner address padded to 32 bytes\n * - s (32 bytes): offset to dynamic data (relative to start of signatures)\n * - v (1 byte): 0x00 (indicates contract signature)\n *\n * Dynamic part (at the offset):\n * - length (32 bytes): length of the signature data\n * - data (variable): the actual signature bytes\n *\n * For a single signer, the static part is 65 bytes, so the dynamic data\n * starts at offset 65.\n */\nexport function encodeContractSignature(ownerAddress: Hex, signatureData: Hex): Hex {\n // Static part: r = address padded to 32 bytes\n const r = pad(ownerAddress, { size: 32 });\n\n // For a single signature, dynamic data starts right after the 65-byte static part\n const dynamicOffset = 65;\n const s = pad(toHex(dynamicOffset), { size: 32 });\n\n // v = 0x00 for contract signature\n const v = \"0x00\" as Hex;\n\n // Dynamic part: length-prefixed signature data\n const signatureBytes = (signatureData.length - 2) / 2;\n const length = pad(toHex(signatureBytes), { size: 32 });\n\n return concat([r, s, v, length, signatureData]);\n}\n","import {\n type Hex,\n encodeAbiParameters,\n encodePacked,\n keccak256,\n} from \"viem\";\n\nconst DOMAIN_SEPARATOR_TYPEHASH = keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n);\n\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Computes the Safe message hash for EIP-1271 signature verification.\n *\n * This is what Safe's `isValidSignature(hash, sig)` expects: the hash is\n * first wrapped in Safe's EIP-712 domain before `checkNSignatures` runs.\n *\n * Flow: keccak256(0x19 || 0x01 || domainSeparator || structHash)\n * where structHash = keccak256(SAFE_MSG_TYPEHASH || keccak256(abi.encode(messageHash)))\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"uint256\" }, { type: \"address\" }],\n [DOMAIN_SEPARATOR_TYPEHASH, BigInt(chainId), safeAddress],\n ),\n );\n\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n","import type { Hex, LocalAccount } from \"viem\";\nimport { concat, encodeAbiParameters, pad, toHex } from \"viem\";\nimport type { SmartAccount, WebAuthnAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount as toPermissionlessSafeSmartAccount } from \"permissionless/accounts\";\n\nimport type { P256Signer, ToSafeSmartAccountParams } from \"./types\";\nimport { toP256SafeSmartAccount } from \"./toP256SafeSmartAccount\";\nimport { toWebAuthnSafeSmartAccount } from \"./toWebAuthnSafeSmartAccount\";\nimport { encodeContractSignature } from \"./encodeContractSignature\";\nimport { computeSafeOpHash } from \"./computeSafeOpHash\";\nimport type { SafeOpHashParams } from \"./computeSafeOpHash\";\nimport {\n SAFE_4337_MODULE_ADDRESS,\n SAFE_WEBAUTHN_SHARED_SIGNER,\n entryPoint07Address,\n} from \"../constants\";\n\n/**\n * Creates a Safe SmartAccount with a unified signer configuration.\n *\n * Dispatches to the appropriate implementation based on `signerConfig.type`:\n * - `\"p256\"`: P256 contract owner (existing `toP256SafeSmartAccount`)\n * - `\"webauthn\"`: WebAuthn passkey via permissionless native support\n * - `\"multi\"`: Both P256 and WebAuthn owners on a single Safe\n *\n * @example\n * ```typescript\n * // P256 only\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: { type: \"p256\", p256Signer },\n * });\n *\n * // WebAuthn only\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: { type: \"webauthn\", webAuthnAccount },\n * });\n *\n * // Multi-signer (threshold 1, P256 signs by default)\n * const account = await toSafeSmartAccount({\n * client,\n * signerConfig: {\n * type: \"multi\",\n * signers: { p256: p256Signer, webAuthn: webAuthnAccount },\n * threshold: 1,\n * },\n * });\n * ```\n */\nexport async function toSafeSmartAccount(\n params: ToSafeSmartAccountParams,\n): Promise<SmartAccount> {\n const { signerConfig } = params;\n\n switch (signerConfig.type) {\n case \"p256\":\n return toP256SafeSmartAccount({\n client: params.client,\n p256Signer: signerConfig.p256Signer,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n });\n\n case \"webauthn\":\n return toWebAuthnSafeSmartAccount({\n client: params.client,\n webAuthnAccount: signerConfig.webAuthnAccount,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n safeWebAuthnSharedSignerAddress: signerConfig.safeWebAuthnSharedSignerAddress,\n });\n\n case \"multi\":\n return buildMultiSignerAccount(params, signerConfig.signers, signerConfig.threshold ?? 1);\n }\n}\n\nfunction createMockLocalAccount(address: Hex): LocalAccount {\n const notImplemented = () => {\n throw new Error(\"Mock owner: use signUserOperation instead\");\n };\n\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: notImplemented,\n signTypedData: notImplemented,\n signTransaction: notImplemented,\n sign: notImplemented,\n } as unknown as LocalAccount;\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n *\n * permissionless does not export this helper, so we implement it here.\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n // Extract r, s from the DER-encoded P256 signature\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n // Extract the fields after \"challenge\":\"...\" from clientDataJSON\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n\nasync function buildMultiSignerAccount(\n params: ToSafeSmartAccountParams,\n signers: { p256?: P256Signer; webAuthn?: WebAuthnAccount },\n threshold: number,\n): Promise<SmartAccount> {\n if (!signers.p256 && !signers.webAuthn) {\n throw new Error(\"Multi-signer config requires at least one signer\");\n }\n\n // If only one signer is provided, delegate to the single-signer function\n if (signers.p256 && !signers.webAuthn) {\n return toP256SafeSmartAccount({\n client: params.client,\n p256Signer: signers.p256,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n });\n }\n if (signers.webAuthn && !signers.p256) {\n const signerConfig = params.signerConfig;\n const sharedSignerAddr = signerConfig.type === \"multi\"\n ? signerConfig.safeWebAuthnSharedSignerAddress\n : undefined;\n return toWebAuthnSafeSmartAccount({\n client: params.client,\n webAuthnAccount: signers.webAuthn,\n safeAddress: params.safeAddress,\n entryPoint: params.entryPoint,\n safe4337ModuleAddress: params.safe4337ModuleAddress,\n safeWebAuthnSharedSignerAddress: sharedSignerAddr,\n });\n }\n\n // Both signers present\n const p256Signer = signers.p256!;\n const webAuthnAccount = signers.webAuthn!;\n\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress = params.entryPoint?.address ?? entryPoint07Address;\n\n const mockP256Owner = createMockLocalAccount(p256Signer.p256OwnerAddress);\n\n // Build account with both owners: mock LocalAccount for P256 + WebAuthnAccount\n const baseAccount = await toPermissionlessSafeSmartAccount({\n client: params.client,\n owners: [mockP256Owner, webAuthnAccount],\n version: \"1.5.0\",\n threshold: BigInt(threshold),\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n });\n\n const chainId = await params.client.getChainId();\n\n if (threshold >= 2) {\n return buildThreshold2Account(\n baseAccount as SmartAccount,\n p256Signer,\n webAuthnAccount,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n }\n\n // Threshold 1: P256 signs by default (no browser interaction needed)\n return buildThreshold1Account(\n baseAccount as SmartAccount,\n p256Signer,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n}\n\nfunction buildThreshold1Account(\n baseAccount: SmartAccount,\n p256Signer: P256Signer,\n chainId: number,\n safe4337ModuleAddress: Hex,\n entryPointAddress: Hex,\n): SmartAccount {\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const safeOpHash = computeSafeOpHash(\n extractSafeOpHashParams(userOp),\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n const { r, s } = await p256Signer.sign(safeOpHash);\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256Signature = concat([rPadded, sPadded]);\n\n const contractSig = encodeContractSignature(\n p256Signer.p256OwnerAddress,\n p256Signature,\n );\n\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, contractSig]);\n },\n } as SmartAccount;\n}\n\nfunction buildThreshold2Account(\n baseAccount: SmartAccount,\n p256Signer: P256Signer,\n webAuthnAccount: WebAuthnAccount,\n chainId: number,\n safe4337ModuleAddress: Hex,\n entryPointAddress: Hex,\n): SmartAccount {\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const safeOpHash = computeSafeOpHash(\n extractSafeOpHashParams(userOp),\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n // Sign with P256\n const { r, s } = await p256Signer.sign(safeOpHash);\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256SignatureData = concat([rPadded, sPadded]);\n\n // Sign with WebAuthn\n const webAuthnSignatureData = await encodeWebAuthnSignature(\n webAuthnAccount,\n safeOpHash,\n );\n\n // Build sorted multi-signature\n // Safe requires signatures sorted by signer address (ascending)\n const p256SignerAddress = p256Signer.p256OwnerAddress.toLowerCase();\n const webAuthnSignerAddress = SAFE_WEBAUTHN_SHARED_SIGNER.toLowerCase();\n\n type SignerEntry = {\n address: string;\n data: Hex;\n dynamic: boolean;\n contractOwner: boolean;\n };\n\n const signerEntries: SignerEntry[] = [\n {\n address: p256SignerAddress,\n data: p256SignatureData,\n dynamic: true,\n contractOwner: true,\n },\n {\n address: webAuthnSignerAddress,\n data: webAuthnSignatureData,\n dynamic: true,\n contractOwner: false,\n },\n ].sort((a, b) => (a.address < b.address ? -1 : 1));\n\n const concatenatedSig = concatSafeSignatures(signerEntries);\n\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, concatenatedSig]);\n },\n } as SmartAccount;\n}\n\n/**\n * Concatenates multiple Safe signatures with proper static/dynamic layout.\n *\n * Safe's `checkNSignatures` expects:\n * - N x 65-byte static parts (sorted by signer address)\n * - Dynamic data appended after all static parts\n *\n * For dynamic signatures (contract or WebAuthn):\n * Static: r = address padded to 32 bytes, s = offset to dynamic data, v = 0x00\n * Dynamic: 32-byte length prefix + signature data\n *\n * For ECDSA signatures:\n * Static: r (32 bytes) + s (32 bytes) + v (1 byte)\n */\nfunction concatSafeSignatures(\n entries: { address: string; data: Hex; dynamic: boolean; contractOwner: boolean }[],\n): Hex {\n const staticPartSize = 65; // per signer\n const totalStaticSize = staticPartSize * entries.length;\n\n const staticParts: Hex[] = [];\n const dynamicParts: Hex[] = [];\n let dynamicOffset = totalStaticSize;\n\n for (const entry of entries) {\n if (entry.dynamic) {\n // Dynamic signature: static part points to dynamic data\n const r = pad(entry.address as Hex, { size: 32 });\n const s = pad(toHex(dynamicOffset), { size: 32 });\n const v = \"0x00\" as Hex;\n staticParts.push(concat([r, s, v]));\n\n // Dynamic part: length-prefixed data\n const dataBytes = (entry.data.length - 2) / 2;\n const length = pad(toHex(dataBytes), { size: 32 });\n dynamicParts.push(concat([length, entry.data]));\n\n // Advance offset: 32 bytes for length + actual data length\n dynamicOffset += 32 + dataBytes;\n } else {\n // ECDSA: direct 65-byte signature (not used in current multi-signer paths)\n staticParts.push(entry.data);\n }\n }\n\n return concat([...staticParts, ...dynamicParts]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractSafeOpHashParams(userOp: any): SafeOpHashParams {\n const op = userOp as Record<string, unknown>;\n return {\n sender: op.sender as Hex,\n nonce: BigInt(op.nonce as bigint),\n factory: (op.factory as Hex) ?? null,\n factoryData: (op.factoryData as Hex) ?? null,\n callData: op.callData as Hex,\n verificationGasLimit: BigInt(op.verificationGasLimit as bigint),\n callGasLimit: BigInt(op.callGasLimit as bigint),\n preVerificationGas: BigInt(op.preVerificationGas as bigint),\n maxPriorityFeePerGas: BigInt(op.maxPriorityFeePerGas as bigint),\n maxFeePerGas: BigInt(op.maxFeePerGas as bigint),\n paymaster: (op.paymaster as Hex) ?? null,\n paymasterVerificationGasLimit: op.paymasterVerificationGasLimit\n ? BigInt(op.paymasterVerificationGasLimit as bigint)\n : null,\n paymasterPostOpGasLimit: op.paymasterPostOpGasLimit\n ? BigInt(op.paymasterPostOpGasLimit as bigint)\n : null,\n paymasterData: (op.paymasterData as Hex) ?? null,\n };\n}\n","import type { Hex, LocalAccount } from \"viem\";\nimport { concat, pad, toHex } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\n\nimport type { ToP256SafeSmartAccountParams } from \"./types\";\nimport { encodeContractSignature } from \"./encodeContractSignature\";\nimport type { SafeOpHashParams } from \"./computeSafeOpHash\";\nimport { computeSafeOpHash } from \"./computeSafeOpHash\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\n/**\n * Creates a mock LocalAccount that has the P256Owner contract address.\n *\n * This is needed because `toSafeSmartAccount` requires a `LocalAccount` owner,\n * but our actual signer is a P256Owner contract (ERC-1271). The mock provides\n * the correct address so the Safe is configured with the right owner. The\n * signing methods are never called since we override `signUserOperation`.\n */\nfunction createMockLocalAccount(address: Hex): LocalAccount {\n const notImplemented = () => {\n throw new Error(\"P256 contract owner: use signUserOperation instead\");\n };\n\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: notImplemented,\n signTypedData: notImplemented,\n signTransaction: notImplemented,\n sign: notImplemented,\n } as unknown as LocalAccount;\n}\n\n/**\n * Creates a Safe SmartAccount that signs UserOperations with a P256 contract owner.\n *\n * This wraps permissionless's `toSafeSmartAccount` and overrides `signUserOperation`\n * to produce P256 signatures in Safe's contract signature format (v=0). The resulting\n * account is compatible with `SafeAccountSigner` and `ExactEvmSchemeERC4337`.\n *\n * The caller is responsible for:\n * - Deploying the P256Owner contract (or computing its deterministic address)\n * - Providing the `sign()` function (e.g., using `@noble/curves/p256` with `prehash: false`)\n * - Ensuring the P256Owner is an owner of the Safe\n *\n * @example\n * ```typescript\n * import { toP256SafeSmartAccount } from '@introspectivelabs/x402-evm';\n * import { p256 } from '@noble/curves/p256';\n *\n * const account = await toP256SafeSmartAccount({\n * client: publicClient,\n * p256Signer: {\n * p256OwnerAddress: '0x349c...',\n * sign: async (hash) => {\n * const sig = p256.sign(hash.slice(2), privateKey, { prehash: false, lowS: true });\n * return {\n * r: `0x${sig.r.toString(16).padStart(64, '0')}`,\n * s: `0x${sig.s.toString(16).padStart(64, '0')}`,\n * };\n * },\n * },\n * safeAddress: '0x...',\n * });\n *\n * const scheme = new ExactEvmSchemeERC4337({ account });\n * ```\n */\nexport async function toP256SafeSmartAccount(\n params: ToP256SafeSmartAccountParams,\n): Promise<SmartAccount> {\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress =\n params.entryPoint?.address ?? entryPoint07Address;\n\n const mockOwner = createMockLocalAccount(params.p256Signer.p256OwnerAddress);\n\n const baseAccount = await toSafeSmartAccount({\n client: params.client,\n owners: [mockOwner],\n version: \"1.5.0\",\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n });\n\n const chainId = await params.client.getChainId();\n\n return {\n ...baseAccount,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async signUserOperation(userOp: any) {\n const op = userOp as Record<string, unknown>;\n // Compute the SafeOp EIP-712 hash (what Safe4337Module verifies)\n const hashParams: SafeOpHashParams = {\n sender: op.sender as Hex,\n nonce: BigInt(op.nonce as bigint),\n factory: (op.factory as Hex) ?? null,\n factoryData: (op.factoryData as Hex) ?? null,\n callData: op.callData as Hex,\n verificationGasLimit: BigInt(op.verificationGasLimit as bigint),\n callGasLimit: BigInt(op.callGasLimit as bigint),\n preVerificationGas: BigInt(op.preVerificationGas as bigint),\n maxPriorityFeePerGas: BigInt(op.maxPriorityFeePerGas as bigint),\n maxFeePerGas: BigInt(op.maxFeePerGas as bigint),\n paymaster: (op.paymaster as Hex) ?? null,\n paymasterVerificationGasLimit: op.paymasterVerificationGasLimit\n ? BigInt(op.paymasterVerificationGasLimit as bigint)\n : null,\n paymasterPostOpGasLimit: op.paymasterPostOpGasLimit\n ? BigInt(op.paymasterPostOpGasLimit as bigint)\n : null,\n paymasterData: (op.paymasterData as Hex) ?? null,\n };\n const safeOpHash = computeSafeOpHash(\n hashParams,\n chainId,\n safe4337ModuleAddress,\n entryPointAddress,\n );\n\n // Sign the SafeOp hash with P256\n const { r, s } = await params.p256Signer.sign(safeOpHash);\n\n // Encode r || s as 64-byte signature\n const rPadded = pad(r as Hex, { size: 32 });\n const sPadded = pad(s as Hex, { size: 32 });\n const p256Signature = concat([rPadded, sPadded]);\n\n // Wrap in Safe contract signature format (v=0)\n const contractSig = encodeContractSignature(\n params.p256Signer.p256OwnerAddress,\n p256Signature,\n );\n\n // Safe4337Module expects: validAfter (6 bytes) || validUntil (6 bytes) || signatures\n const validAfter = pad(toHex(0), { size: 6 });\n const validUntil = pad(toHex(0), { size: 6 });\n\n return concat([validAfter, validUntil, contractSig]);\n },\n } as SmartAccount;\n}\n","import {\n type Hex,\n concat,\n hashTypedData,\n isAddress,\n pad,\n toHex,\n} from \"viem\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\nconst SAFE_OP_TYPES = {\n SafeOp: [\n { type: \"address\", name: \"safe\" },\n { type: \"uint256\", name: \"nonce\" },\n { type: \"bytes\", name: \"initCode\" },\n { type: \"bytes\", name: \"callData\" },\n { type: \"uint128\", name: \"verificationGasLimit\" },\n { type: \"uint128\", name: \"callGasLimit\" },\n { type: \"uint256\", name: \"preVerificationGas\" },\n { type: \"uint128\", name: \"maxPriorityFeePerGas\" },\n { type: \"uint128\", name: \"maxFeePerGas\" },\n { type: \"bytes\", name: \"paymasterAndData\" },\n { type: \"uint48\", name: \"validAfter\" },\n { type: \"uint48\", name: \"validUntil\" },\n { type: \"address\", name: \"entryPoint\" },\n ],\n} as const;\n\nexport interface SafeOpHashParams {\n sender: Hex;\n nonce: bigint;\n factory?: Hex | null;\n factoryData?: Hex | null;\n callData: Hex;\n verificationGasLimit: bigint;\n callGasLimit: bigint;\n preVerificationGas: bigint;\n maxPriorityFeePerGas: bigint;\n maxFeePerGas: bigint;\n paymaster?: Hex | null;\n paymasterVerificationGasLimit?: bigint | null;\n paymasterPostOpGasLimit?: bigint | null;\n paymasterData?: Hex | null;\n}\n\n/**\n * Computes the EIP-712 SafeOp hash that Safe4337Module uses for signature verification.\n *\n * The Safe4337Module converts the EntryPoint v0.7 UserOperation into a SafeOp struct,\n * packing initCode and paymasterAndData into their v0.6-style concatenated forms,\n * then hashes the struct using EIP-712.\n */\nexport function computeSafeOpHash(\n userOp: SafeOpHashParams,\n chainId: number,\n safe4337ModuleAddress: Hex = SAFE_4337_MODULE_ADDRESS,\n entryPointAddress: Hex = entryPoint07Address,\n): Hex {\n // Reconstruct initCode: factory || factoryData (v0.7 -> v0.6 style)\n const initCode =\n userOp.factory && isAddress(userOp.factory)\n ? concat([userOp.factory, (userOp.factoryData || \"0x\") as Hex])\n : (\"0x\" as Hex);\n\n // Reconstruct paymasterAndData: paymaster || verificationGasLimit(16) || postOpGasLimit(16) || data\n let paymasterAndData: Hex = \"0x\";\n if (userOp.paymaster && isAddress(userOp.paymaster)) {\n paymasterAndData = concat([\n userOp.paymaster,\n pad(toHex(userOp.paymasterVerificationGasLimit || 0n), { size: 16 }),\n pad(toHex(userOp.paymasterPostOpGasLimit || 0n), { size: 16 }),\n (userOp.paymasterData || \"0x\") as Hex,\n ]);\n }\n\n return hashTypedData({\n domain: {\n chainId,\n verifyingContract: safe4337ModuleAddress,\n },\n types: SAFE_OP_TYPES,\n primaryType: \"SafeOp\",\n message: {\n safe: userOp.sender,\n nonce: userOp.nonce,\n initCode,\n callData: userOp.callData,\n verificationGasLimit: userOp.verificationGasLimit,\n callGasLimit: userOp.callGasLimit,\n preVerificationGas: userOp.preVerificationGas,\n maxPriorityFeePerGas: userOp.maxPriorityFeePerGas,\n maxFeePerGas: userOp.maxFeePerGas,\n paymasterAndData,\n validAfter: 0,\n validUntil: 0,\n entryPoint: entryPointAddress,\n },\n });\n}\n","import type { Hex } from \"viem\";\nimport type { SmartAccount, WebAuthnAccount } from \"viem/account-abstraction\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\nimport type { PublicClient, Transport, Chain } from \"viem\";\nimport { SAFE_4337_MODULE_ADDRESS, entryPoint07Address } from \"../constants\";\n\nexport type ToWebAuthnSafeSmartAccountParams = {\n client: PublicClient<Transport, Chain>;\n webAuthnAccount: WebAuthnAccount;\n safeAddress?: Hex;\n entryPoint?: { address: Hex; version: \"0.7\" };\n safe4337ModuleAddress?: Hex;\n safeWebAuthnSharedSignerAddress?: Hex;\n};\n\n/**\n * Creates a Safe SmartAccount that signs UserOperations with a WebAuthn passkey.\n */\nexport async function toWebAuthnSafeSmartAccount(\n params: ToWebAuthnSafeSmartAccountParams,\n): Promise<SmartAccount> {\n const safe4337ModuleAddress = params.safe4337ModuleAddress ?? SAFE_4337_MODULE_ADDRESS;\n const entryPointAddress = params.entryPoint?.address ?? entryPoint07Address;\n\n const baseAccount = await toSafeSmartAccount({\n client: params.client,\n owners: [params.webAuthnAccount],\n version: \"1.5.0\",\n ...(params.safeAddress ? { address: params.safeAddress } : {}),\n entryPoint: {\n address: entryPointAddress,\n version: \"0.7\",\n },\n safe4337ModuleAddress,\n ...(params.safeWebAuthnSharedSignerAddress\n ? { safeWebAuthnSharedSignerAddress: params.safeWebAuthnSharedSignerAddress }\n : {}),\n });\n\n return baseAccount as SmartAccount;\n}\n","/// <reference lib=\"dom\" />\nimport type { Hex } from \"viem\";\n\nfunction bufferToHex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction base64urlToHex(base64url: string): string {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(base64);\n return Array.from(binary, (c) => c.charCodeAt(0).toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Extracts P256 public key coordinates from a WebAuthn credential.\n *\n * Replaces `extractPasskeyData` from `@safe-global/protocol-kit`.\n * Uses only the Web Crypto API (no external dependencies).\n */\nexport async function extractPasskeyCoordinates(\n credential: PublicKeyCredential,\n): Promise<{ rawId: string; x: Hex; y: Hex }> {\n const rawId = bufferToHex(credential.rawId);\n const response = credential.response as AuthenticatorAttestationResponse;\n const publicKey = response.getPublicKey();\n if (!publicKey) throw new Error(\"Failed to extract public key from credential\");\n\n const key = await crypto.subtle.importKey(\n \"spki\",\n publicKey,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n true,\n [\"verify\"],\n );\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n if (!jwk.x || !jwk.y) throw new Error(\"Missing coordinates in JWK\");\n\n return {\n rawId,\n x: (\"0x\" + base64urlToHex(jwk.x)) as Hex,\n y: (\"0x\" + base64urlToHex(jwk.y)) as Hex,\n };\n}\n","import {\n type Hex,\n encodeAbiParameters,\n keccak256,\n encodePacked,\n} from \"viem\";\n\n/**\n * The typehash used by Safe's `isValidSignature` (CompatibilityFallbackHandler).\n *\n * `SafeMessage(bytes message)` -- the Safe wraps any message inside this\n * EIP-712 struct before delegating to owners for verification.\n */\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Compute the domain separator for a Safe contract.\n *\n * The Safe uses a minimal EIP-712 domain: `{ chainId, verifyingContract }`.\n */\nfunction computeSafeDomainSeparator(safeAddress: Hex, chainId: number): Hex {\n return keccak256(\n encodeAbiParameters(\n [\n { type: \"bytes32\" },\n { type: \"uint256\" },\n { type: \"address\" },\n ],\n [\n // DOMAIN_SEPARATOR_TYPEHASH = keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\")\n keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n ),\n BigInt(chainId),\n safeAddress,\n ],\n ),\n );\n}\n\n/**\n * Compute the EIP-712 message hash that Safe's `isValidSignature` uses internally.\n *\n * When `isValidSignature(bytes32 _dataHash, bytes signature)` is called on a Safe,\n * the CompatibilityFallbackHandler computes:\n *\n * messageHash = keccak256(\n * 0x19 || 0x01 || domainSeparator || keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(abi.encode(_dataHash))))\n * )\n *\n * This hash is what gets passed to the owner contracts (e.g. P256Owner) for verification.\n * The P256Owner then does `keccak256(messageHash)` and verifies the P256 signature over that.\n *\n * Wait -- actually the Safe's `isValidSignature(bytes32, bytes)` internally converts\n * the bytes32 into `bytes` via `abi.encode()`, then calls `getMessageHash()`:\n * messageData = encodeTypedData(domainSeparator, SafeMessage(abi.encode(dataHash)))\n *\n * The P256Owner receives the full `messageData` from checkSignatures and computes\n * `hash = sha256(messageData)` or `keccak256(messageData)` depending on variant.\n *\n * For our purposes we compute the same hash the Safe produces.\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = computeSafeDomainSeparator(safeAddress, chainId);\n\n // SafeMessage struct hash: keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(abi.encode(messageHash))))\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n // EIP-712: 0x19 || 0x01 || domainSeparator || structHash\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,qCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iCAAoC;AAI7B,IAAM,2BACX;AAEK,IAAM,8BACX;AAEK,IAAM,oBACX;AAEK,IAAM,qBACX;AAEK,IAAM,0BACX;;;ACTK,SAAS,+BACd,cACqC;AACrC,QAAM,cAAc,aAAa,OAAO;AACxC,MACE,eACA,OAAO,gBAAgB,YACvB,eAAe,eACf,YAAY,cAAc,MAC1B;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;ACOA,eAAsB,gCACpB,QACA,cACuB;AAEvB,MAAI,aAAa,QAAQ;AACvB,WA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2B,aAAa,OAAO;AAGvE,QAAM,qBAAiB;AAAA,IACrB,CAAC,EAAE,MAAM,UAAU,CAAC;AAAA,IACpB,CAAC,WAAW;AAAA,EACd;AACA,QAAM,uBAAmB,yBAAU,cAAc;AAEjD,QAAM,iBAAa;AAAA,QACjB;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAACD,oBAAmB,gBAAgB;AAAA,IACtC;AAAA,EACF;AAGA,aAAO;AAAA,QACL;AAAA,MACE,CAAC,UAAU,UAAU,WAAW,SAAS;AAAA,MACzC,CAAC,QAAQ,QAAQ,iBAAiB,UAAU;AAAA,IAC9C;AAAA,EACF;AACF;","names":["ExactEvmSchemeERC4337","computeSafeMessageHash","toSafeSmartAccount","assetAmount","import_viem","import_account_abstraction","createViemBundlerClient","import_viem","import_viem","ExactEvmSchemeERC4337","bundlerUrl","import_viem","import_viem","import_viem","import_viem","import_accounts","import_viem","import_viem","import_accounts","toSafeSmartAccount","createMockLocalAccount","encodeWebAuthnSignature","toPermissionlessSafeSmartAccount","import_viem","SAFE_MSG_TYPEHASH","computeSafeMessageHash"]}
@@ -18,7 +18,8 @@ var ExactEvmSchemeERC4337 = class extends ExactEvmScheme {
18
18
  return {
19
19
  address: chain.usdcAddress,
20
20
  name: "USDC",
21
- version: "2"
21
+ version: "2",
22
+ decimals: 6
22
23
  };
23
24
  }
24
25
  throw new Error(`No default asset configured for network ${network}`);
@@ -69,4 +70,4 @@ var ExactEvmSchemeERC4337 = class extends ExactEvmScheme {
69
70
  export {
70
71
  ExactEvmSchemeERC4337
71
72
  };
72
- //# sourceMappingURL=chunk-NZIZ7SXW.mjs.map
73
+ //# sourceMappingURL=chunk-YHT77ES6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/exact/server/scheme.ts"],"sourcesContent":["import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n decimals: 6,\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,sBAAsB;AAsBxB,IAAM,wBAAN,cAAoC,eAAe;AAAA,EACxD,cAAc;AACZ,UAAM;AAKN,IAAC,KAAa,kBAAkB,CAAC,YAAoB;AACnD,YAAM,UAAU,WAAW,OAAO;AAClC,YAAM,QAAQ,aAAa,OAAO;AAClC,UAAI,OAAO;AACT,eAAO;AAAA,UACL,SAAS,MAAM;AAAA,UACf,MAAM;AAAA,UACN,SAAS;AAAA,UACT,UAAU;AAAA,QACZ;AAAA,MACF;AACA,YAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;AAAA,IACtE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAM,2BACJ,qBACA,eAMA,eAC8B;AAE9B,UAAM,gBAAgB,+BAA+B,mBAAmB;AAGxE,UAAM,WAAW,MAAM,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAGA,QAAI,eAAe;AACjB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO;AAAA,UACL,GAAG,SAAS;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,QAAI,CAAC,SAAS,OAAO;AACnB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO,CAAC;AAAA,MACV;AAAA,IACF;AAGA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ExactEvmSchemeERC4337
3
- } from "../../chunk-NZIZ7SXW.mjs";
3
+ } from "../../chunk-YHT77ES6.mjs";
4
4
  import "../../chunk-GGPRPAM4.mjs";
5
5
  import "../../chunk-JIQ3WKXV.mjs";
6
6
  export {
@@ -10,7 +10,7 @@ import {
10
10
  } from "./chunk-EZJUSNWE.mjs";
11
11
  import {
12
12
  ExactEvmSchemeERC4337
13
- } from "./chunk-NZIZ7SXW.mjs";
13
+ } from "./chunk-YHT77ES6.mjs";
14
14
  import {
15
15
  extractUserOperationCapability
16
16
  } from "./chunk-GGPRPAM4.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@introspectivelabs/x402-evm",
3
- "version": "0.1.0-beta.13",
3
+ "version": "0.1.0-beta.14",
4
4
  "main": "./dist/cjs/index.js",
5
5
  "module": "./dist/esm/index.js",
6
6
  "types": "./dist/cjs/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/exact/server/scheme.ts"],"sourcesContent":["import type { PaymentRequirements, Network } from \"@x402/core/types\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { getChainById, parseCAIP2 } from \"../../networks/helpers\";\nimport { extractUserOperationCapability } from \"../utils\";\n\n/**\n * Enhanced ExactEvmScheme that preserves UserOperation capability in payment requirements.\n *\n * This class extends ExactEvmScheme and enhances the `enhancePaymentRequirements` method\n * to preserve `userOperation` from `paymentRequirements.extra`. This ensures that when routes\n * are transformed using `transformRoutesForUserOperation`, the userOperation data flows through\n * the entire payment requirements pipeline.\n *\n * @example\n * ```typescript\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/server';\n * import { x402ResourceServer } from '@x402/core/server';\n *\n * const schemeServer = new ExactEvmSchemeERC4337();\n * const server = new x402ResourceServer(facilitatorClient);\n * server.register('eip155:84532', schemeServer);\n * ```\n */\nexport class ExactEvmSchemeERC4337 extends ExactEvmScheme {\n constructor() {\n super();\n // Patch getDefaultAsset to support all networks in our registry.\n // The upstream ExactEvmScheme only has USDC addresses for Base and Base Sepolia.\n // We override at the instance level since upstream marks the method as private.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).getDefaultAsset = (network: string) => {\n const chainId = parseCAIP2(network);\n const chain = getChainById(chainId);\n if (chain) {\n return {\n address: chain.usdcAddress,\n name: \"USDC\",\n version: \"2\",\n };\n }\n throw new Error(`No default asset configured for network ${network}`);\n };\n }\n\n /**\n * Enhance payment requirements while preserving UserOperation capability.\n *\n * This method calls the parent's enhancePaymentRequirements and then ensures\n * that any userOperation from the original paymentRequirements.extra is preserved\n * in the returned requirements.\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind from facilitator\n * @param supportedKind.x402Version - The x402 version supported by the facilitator\n * @param supportedKind.scheme - The scheme supported by the facilitator\n * @param supportedKind.network - The network supported by the facilitator\n * @param supportedKind.extra - The extra supported by the facilitator\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with userOperation preserved\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n // Extract userOperation from the original requirements before enhancement\n const userOperation = extractUserOperationCapability(paymentRequirements);\n\n // Call parent's enhancePaymentRequirements\n const enhanced = await super.enhancePaymentRequirements(\n paymentRequirements,\n supportedKind,\n extensionKeys,\n );\n\n // If userOperation was present in the original requirements, preserve it\n if (userOperation) {\n return {\n ...enhanced,\n extra: {\n ...enhanced.extra,\n userOperation,\n },\n };\n }\n\n // No userOperation to preserve, but ensure extra exists\n if (!enhanced.extra) {\n return {\n ...enhanced,\n extra: {},\n };\n }\n\n // Return enhanced requirements as-is\n return enhanced;\n }\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,sBAAsB;AAsBxB,IAAM,wBAAN,cAAoC,eAAe;AAAA,EACxD,cAAc;AACZ,UAAM;AAKN,IAAC,KAAa,kBAAkB,CAAC,YAAoB;AACnD,YAAM,UAAU,WAAW,OAAO;AAClC,YAAM,QAAQ,aAAa,OAAO;AAClC,UAAI,OAAO;AACT,eAAO;AAAA,UACL,SAAS,MAAM;AAAA,UACf,MAAM;AAAA,UACN,SAAS;AAAA,QACX;AAAA,MACF;AACA,YAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;AAAA,IACtE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAM,2BACJ,qBACA,eAMA,eAC8B;AAE9B,UAAM,gBAAgB,+BAA+B,mBAAmB;AAGxE,UAAM,WAAW,MAAM,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAGA,QAAI,eAAe;AACjB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO;AAAA,UACL,GAAG,SAAS;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,QAAI,CAAC,SAAS,OAAO;AACnB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,OAAO,CAAC;AAAA,MACV;AAAA,IACF;AAGA,WAAO;AAAA,EACT;AACF;","names":[]}