@x402x/extensions 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +359 -180
- package/dist/index.d.ts +359 -180
- package/dist/index.js +547 -345
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +543 -330
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/middleware-utils.ts","../src/commitment.ts","../src/network-utils.ts","../src/networks.ts","../src/chains.ts","../src/hooks/transfer.ts","../src/hooks/demo.ts","../src/validation.ts","../src/utils.ts","../src/extensions.ts","../src/server-extension.ts","../src/settlement-routes.ts","../src/helpers.ts","../src/amount.ts","../src/facilitator.ts","../src/abi.ts","../src/facilitator-types.ts","../src/legacy-compat.ts"],"names":["bytes","canonicalNetwork","TransferHook","NFTMintHook","encodeAbiParameters","RewardHook","isValidAddress","isValidHex","registerRouterSettlement"],"mappings":";;;;AA0JO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF;;;AC3GO,SAAS,qBAAqB,MAAA,EAAsC;AACzE,EAAA,MAAM,mBAAmB,MAAA,CAAO,WAAA;AAAA,IAC9B,MAAA,CAAO,QAAQ,MAAM,CAAA,CAAE,IAAI,CAAC,CAAC,OAAA,EAAS,KAAK,CAAA,KAAM;AAAA,MAC/C,OAAA;AAAA,MACA,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAA,KAAU,QAAA,GACzC,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,cAAA,EAAe,GACxC;AAAA,KACN;AAAA,GACH;AAEA,EAAA,OAAO,MAAA,CAAO,QAAQ,gBAAgB,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KO,SAAS,aAAa,OAAA,EAA2B;AAEtD,EAAA,MAAM,IAAI,MAAM,4EAA4E,CAAA;AAC9F","file":"index.mjs","sourcesContent":["/**\n * Type definitions for @x402x/extensions\n * \n * Re-exports official x402 v2 types from @x402/core\n */\n\nimport type { PaymentRequirements, PaymentPayload } from \"@x402/core/types\";\n\n// Re-export x402 v2 types for convenience\nexport type { PaymentRequirements, PaymentPayload };\n\n/**\n * Signer interface for x402x\n * Compatible with x402 v2 client signer patterns\n */\nexport interface Signer {\n address: string;\n signTypedData?: (params: unknown) => Promise<string>;\n [key: string]: unknown;\n}\n\n/**\n * Commitment calculation parameters\n * All parameters must match exactly with SettlementRouter.sol\n */\nexport interface CommitmentParams {\n /** Chain ID (e.g., 84532 for Base Sepolia) */\n chainId: number;\n /** SettlementRouter contract address */\n hub: string;\n /** Asset contract address (ERC-3009 token, e.g., USDC) */\n asset: string;\n /** Payer address */\n from: string;\n /** Payment amount in asset's smallest unit */\n value: string;\n /** Authorization valid after timestamp */\n validAfter: string;\n /** Authorization valid before timestamp */\n validBefore: string;\n /** Unique salt for idempotency (32 bytes) */\n salt: string;\n /** Final recipient address */\n payTo: string;\n /** Facilitator fee amount */\n facilitatorFee: string;\n /** Hook contract address */\n hook: string;\n /** Encoded hook parameters */\n hookData: string;\n}\n\n/**\n * Gas model for different networks\n */\nexport type GasModel = \"eip1559\" | \"legacy\";\n\n/**\n * Network metadata containing protocol-level information\n */\nexport interface NetworkMetadata {\n /** Gas pricing model used by the network */\n gasModel: GasModel;\n /** Native token symbol */\n nativeToken: string;\n}\n\n/**\n * Demo hooks configuration for showcase examples\n */\nexport interface DemoHooks {\n /** NFTMintHook contract address */\n nftMint?: string;\n /** RandomNFT contract address */\n randomNFT?: string;\n /** RewardHook contract address */\n reward?: string;\n /** RewardToken contract address */\n rewardToken?: string;\n}\n\n/**\n * Network configuration for x402x\n */\nexport interface NetworkConfig {\n /** Chain ID */\n chainId: number;\n /** Network Name */\n name: string;\n /** Network Type */\n type: \"mainnet\" | \"testnet\";\n /** Network Address Explorer Base URL */\n addressExplorerBaseUrl: string;\n /** Network Transaction Explorer Base URL */\n txExplorerBaseUrl: string;\n /** SettlementRouter contract address */\n settlementRouter: string;\n /** Default asset configuration (ERC-3009 token, typically USDC) */\n defaultAsset: {\n /** Asset contract address */\n address: string;\n /** Asset decimals */\n decimals: number;\n /** EIP-712 domain info for signing */\n eip712: {\n /** Asset contract name (for EIP-712) */\n name: string;\n /** Asset contract version (for EIP-712) */\n version: string;\n };\n };\n /** Builtin hook addresses */\n hooks: {\n /** TransferHook address */\n transfer: string;\n };\n /** Demo hooks configuration (optional, for showcase examples) */\n demoHooks?: DemoHooks;\n /** Network metadata */\n metadata?: NetworkMetadata;\n}\n\n/**\n * Core settlement parameters (without EIP-712 domain info)\n */\nexport interface SettlementExtraCore {\n /** SettlementRouter contract address */\n settlementRouter: string;\n /** Unique salt for idempotency (32 bytes) */\n salt: string;\n /** Final recipient address */\n payTo: string;\n /** Facilitator fee amount */\n facilitatorFee: string;\n /** Hook contract address */\n hook: string;\n /** Encoded hook parameters */\n hookData: string;\n}\n\n/**\n * Settlement extra parameters for PaymentRequirements\n * Includes EIP-712 domain info (name, version) for asset signature validation\n */\nexport interface SettlementExtra extends SettlementExtraCore {\n /** Asset contract name (for EIP-712) */\n name: string;\n /** Asset contract version (for EIP-712) */\n version: string;\n}\n\n/**\n * Error thrown when settlement extra parameters are invalid\n */\nexport class SettlementExtraError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SettlementExtraError\";\n }\n}\n\n/**\n * Additional types for middleware compatibility\n */\n\n// Re-export Network type from @x402/core\nexport type { Network } from \"@x402/core/types\";\n\n/**\n * Money type - string or number representing USD amount\n */\nexport type Money = string | number;\n\n/**\n * Resource information for payment required responses\n */\nexport interface Resource {\n url: string;\n description?: string;\n mimeType?: string;\n}\n\n/**\n * Facilitator configuration for middleware\n */\nexport interface FacilitatorConfig {\n url: string;\n apiKey?: string;\n}\n\n","/**\n * Middleware utility functions for x402x v2 packages\n * \n * These utilities provide helpers for route matching, JSON encoding,\n * and other common middleware operations.\n */\n\n/**\n * Route configuration for payment requirements\n */\nexport interface RouteConfig {\n price: string | number;\n network?: string;\n extra?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Routes configuration - mapping of route patterns to configs\n */\nexport type RoutesConfig = Record<string, RouteConfig | string | number>;\n\n/**\n * Compiled route pattern with regex\n */\nexport interface RoutePattern {\n verb: string;\n pattern: RegExp;\n config: RouteConfig;\n}\n\n/**\n * Compute route patterns from routes config\n * \n * Converts route configuration into compiled patterns with regex matching.\n * \n * **Note**: When a route is specified as a simple price value (string or number),\n * it is automatically converted to a RouteConfig with network defaulting to \"base-sepolia\".\n * For production use, explicitly specify the network in your route configuration.\n * \n * @param routes - Routes configuration\n * @returns Array of route patterns\n * \n * @example\n * ```typescript\n * const routes = {\n * 'GET /api/data': { price: '0.01', network: 'base-sepolia' },\n * '/public/*': '0' // Defaults to base-sepolia network\n * };\n * const patterns = computeRoutePatterns(routes);\n * ```\n */\nexport function computeRoutePatterns(routes: RoutesConfig): RoutePattern[] {\n const normalizedRoutes = Object.fromEntries(\n Object.entries(routes).map(([pattern, value]) => [\n pattern,\n typeof value === \"string\" || typeof value === \"number\"\n ? ({ price: value, network: \"base-sepolia\" } as RouteConfig)\n : (value as RouteConfig),\n ]),\n );\n\n return Object.entries(normalizedRoutes).map(([pattern, routeConfig]) => {\n // Split pattern into verb and path, defaulting to \"*\" for verb if not specified\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n if (!path) {\n throw new Error(`Invalid route pattern: ${pattern}`);\n }\n return {\n verb: verb.toUpperCase(),\n pattern: new RegExp(\n `^${\n path\n // First escape backslashes to prevent regex injection\n .replace(/\\\\/g, \"\\\\\\\\\")\n // Then escape all special regex characters except * and []\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\")\n // Then handle our special pattern characters\n .replace(/\\*/g, \".*?\") // Make wildcard non-greedy\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Convert [param] to regex capture\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n ),\n config: routeConfig,\n };\n });\n}\n\n/**\n * Find matching route for given path and method\n * \n * @param routePatterns - Compiled route patterns\n * @param path - Request path\n * @param method - HTTP method\n * @returns Matching route pattern or undefined\n * \n * @example\n * ```typescript\n * const route = findMatchingRoute(patterns, '/api/data', 'GET');\n * ```\n */\nexport function findMatchingRoute(\n routePatterns: RoutePattern[],\n path: string,\n method: string,\n): RoutePattern | undefined {\n // Normalize the path\n let normalizedPath: string;\n try {\n // First split off query parameters and hash fragments\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n // Then decode the path\n const decodedPath = decodeURIComponent(pathWithoutQuery);\n\n // Normalize the path (just clean up slashes)\n normalizedPath = decodedPath\n .replace(/\\\\/g, \"/\") // replace backslashes\n .replace(/\\/+/g, \"/\") // collapse slashes\n .replace(/(.+?)\\/+$/, \"$1\"); // trim trailing slashes\n } catch {\n // If decoding fails, return undefined\n return undefined;\n }\n\n // Find matching route pattern\n const matchingRoutes = routePatterns.filter(({ pattern, verb }) => {\n const matchesPath = pattern.test(normalizedPath);\n const upperMethod = method.toUpperCase();\n const matchesVerb = verb === \"*\" || upperMethod === verb;\n return matchesPath && matchesVerb;\n });\n\n // Return first matching route (most specific)\n return matchingRoutes[0];\n}\n\n/**\n * Find matching payment requirements from list\n * \n * This is a placeholder for finding requirements that match certain criteria.\n * In v2, this logic is typically handled by the x402Client/x402ResourceServer classes.\n * \n * @param requirements - List of payment requirements\n * @param network - Optional network filter\n * @returns First matching requirement or undefined\n */\nexport function findMatchingPaymentRequirements<T>(\n requirements: T[],\n network?: string,\n): T | undefined {\n // For now, just return the first requirement\n // In a real implementation, this would filter by network, scheme, etc.\n void network; // Mark as intentionally unused\n return requirements[0];\n}\n\n/**\n * Convert value to JSON-safe format\n * \n * Handles BigInt and other non-JSON-serializable types.\n * \n * @param value - Value to convert\n * @returns JSON-safe representation\n * \n * @example\n * ```typescript\n * const safe = toJsonSafe({ amount: 1000000n }); // { amount: \"1000000\" }\n * ```\n */\nexport function toJsonSafe(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n return value.map(toJsonSafe);\n }\n\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = toJsonSafe(val);\n }\n return result;\n }\n\n return value;\n}\n","/**\n * Commitment calculation utilities\n *\n * The commitment hash binds all settlement parameters to the client's signature,\n * preventing parameter tampering attacks.\n */\n\nimport { keccak256, encodePacked, hexToBytes, bytesToHex, type Hex } from \"viem\";\nimport type { CommitmentParams } from \"./types.js\";\n\n/**\n * Calculate commitment hash for x402x settlement\n *\n * This hash becomes the EIP-3009 nonce, cryptographically binding all settlement\n * parameters to the client's signature. The parameter order must exactly match\n * SettlementRouter.sol.\n *\n * @param params - All settlement parameters\n * @returns bytes32 commitment hash\n *\n * @example\n * ```typescript\n * const commitment = calculateCommitment({\n * chainId: 84532,\n * hub: '0x...',\n * asset: '0x...',\n * from: '0x...',\n * value: '100000',\n * validAfter: '0',\n * validBefore: '1234567890',\n * salt: '0x...',\n * payTo: '0x...',\n * facilitatorFee: '10000',\n * hook: '0x...',\n * hookData: '0x',\n * });\n * ```\n */\nexport function calculateCommitment(params: CommitmentParams): string {\n // Pack parameters in exact order as in SettlementRouter.sol\n return keccak256(\n encodePacked(\n [\n \"string\", // Protocol identifier\n \"uint256\", // Chain ID\n \"address\", // Hub address\n \"address\", // Token address\n \"address\", // From (payer)\n \"uint256\", // Value\n \"uint256\", // Valid after\n \"uint256\", // Valid before\n \"bytes32\", // Salt\n \"address\", // Pay to\n \"uint256\", // Facilitator fee\n \"address\", // Hook\n \"bytes32\", // keccak256(hookData)\n ],\n [\n \"X402/settle/v1\",\n BigInt(params.chainId),\n params.hub as Hex,\n params.asset as Hex,\n params.from as Hex,\n BigInt(params.value),\n BigInt(params.validAfter),\n BigInt(params.validBefore),\n params.salt as Hex,\n params.payTo as Hex,\n BigInt(params.facilitatorFee),\n params.hook as Hex,\n keccak256(params.hookData as Hex),\n ],\n ),\n );\n}\n\n/**\n * Generate a random salt for settlement uniqueness\n *\n * Works in both Node.js and browser environments.\n * Uses crypto.getRandomValues (Web Crypto API) which is available in:\n * - Modern browsers\n * - Node.js 15+ (via global crypto)\n * - Older Node.js (via crypto.webcrypto)\n *\n * @returns bytes32 hex string (0x + 64 hex characters)\n *\n * @example\n * ```typescript\n * const salt = generateSalt();\n * // => '0x1234567890abcdef...'\n * ```\n */\nexport function generateSalt(): string {\n // Try to get crypto from global (browser or Node.js 15+)\n const globalCrypto = typeof crypto !== \"undefined\" ? crypto : undefined;\n\n if (globalCrypto?.getRandomValues) {\n // Use Web Crypto API (works in browser and modern Node.js)\n const bytes = new Uint8Array(32);\n globalCrypto.getRandomValues(bytes);\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n }\n\n // Fallback: use Math.random() (less secure, but works everywhere)\n // Note: Salt doesn't require cryptographic security - it's just for uniqueness\n console.warn(\n \"[generateSalt] Using Math.random() fallback - consider upgrading to Node.js 15+ or use in browser\",\n );\n const bytes = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate commitment parameters\n *\n * @param params - Commitment parameters to validate\n * @throws Error if validation fails\n */\nexport function validateCommitmentParams(params: CommitmentParams): void {\n // Validate addresses\n if (!isValidAddress(params.hub)) {\n throw new Error(\"Invalid hub address\");\n }\n if (!isValidAddress(params.asset)) {\n throw new Error(\"Invalid asset address\");\n }\n if (!isValidAddress(params.from)) {\n throw new Error(\"Invalid from address\");\n }\n if (!isValidAddress(params.payTo)) {\n throw new Error(\"Invalid payTo address\");\n }\n if (!isValidAddress(params.hook)) {\n throw new Error(\"Invalid hook address\");\n }\n\n // Validate numeric values\n try {\n BigInt(params.value);\n BigInt(params.validAfter);\n BigInt(params.validBefore);\n BigInt(params.facilitatorFee);\n } catch (e) {\n throw new Error(\"Invalid numeric parameter\");\n }\n\n // Validate bytes32 values\n if (!isValidHex(params.salt) || params.salt.length !== 66) {\n throw new Error(\"Invalid salt: must be bytes32 (0x + 64 hex chars)\");\n }\n\n if (!isValidHex(params.hookData)) {\n throw new Error(\"Invalid hookData: must be hex string\");\n }\n}\n\n/**\n * Check if a string is a valid Ethereum address\n */\nfunction isValidAddress(address: string): boolean {\n return /^0x[0-9a-fA-F]{40}$/.test(address);\n}\n\n/**\n * Check if a string is a valid hex string\n */\nfunction isValidHex(hex: string): boolean {\n return /^0x[0-9a-fA-F]*$/.test(hex);\n}\n","/**\n * Network utility functions for x402x core_v2\n * \n * These utilities provide helpers for working with CAIP-2 network identifiers\n * and accessing network-specific asset information.\n */\n\nimport type { Network } from \"@x402/core/types\";\n\n/**\n * Asset information including EIP-712 domain parameters\n */\nexport interface AssetInfo {\n address: string;\n decimals: number;\n eip712: {\n name: string;\n version: string;\n };\n}\n\n/**\n * Network name to CAIP-2 network ID mapping\n */\nconst NETWORK_IDS: Record<string, Network> = {\n \"base-sepolia\": \"eip155:84532\",\n \"x-layer-testnet\": \"eip155:1952\",\n \"skale-base-sepolia\": \"eip155:324705682\",\n \"base\": \"eip155:8453\",\n \"x-layer\": \"eip155:196\",\n \"bsc-testnet\": \"eip155:97\",\n \"bsc\": \"eip155:56\",\n};\n\n/**\n * CAIP-2 network ID to network name mapping (reverse lookup)\n */\nconst NETWORK_NAMES: Record<Network, string> = {\n \"eip155:84532\": \"base-sepolia\",\n \"eip155:1952\": \"x-layer-testnet\",\n \"eip155:324705682\": \"skale-base-sepolia\",\n \"eip155:8453\": \"base\",\n \"eip155:196\": \"x-layer\",\n \"eip155:97\": \"bsc-testnet\",\n \"eip155:56\": \"bsc\",\n};\n\n/**\n * Default asset (USDC) configuration per network\n */\nconst DEFAULT_ASSETS: Record<Network, AssetInfo> = {\n \"eip155:84532\": {\n address: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n decimals: 6,\n eip712: {\n name: \"USDC\",\n version: \"2\",\n },\n },\n \"eip155:1952\": {\n address: \"0xcb8bf24c6ce16ad21d707c9505421a17f2bec79d\",\n decimals: 6,\n eip712: {\n name: \"USDC_TEST\",\n version: \"2\",\n },\n },\n \"eip155:324705682\": {\n address: \"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD\",\n decimals: 6,\n eip712: {\n name: \"Bridged USDC (SKALE Bridge)\",\n version: \"2\",\n },\n },\n \"eip155:8453\": {\n address: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n decimals: 6,\n eip712: {\n name: \"USD Coin\",\n version: \"2\",\n },\n },\n \"eip155:196\": {\n address: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\",\n decimals: 6,\n eip712: {\n name: \"USD Coin\",\n version: \"2\",\n },\n },\n \"eip155:97\": {\n address: \"0xdac693b5f14e7ee5923a4830cd2f82ff178f5098\",\n decimals: 18,\n eip712: {\n name: \"x402 Wrapped USDT\",\n version: \"1\",\n },\n },\n \"eip155:56\": {\n address: \"0x2fDb94bAa9D664a1879BEe1f944F5F5d2dad4451\",\n decimals: 18,\n eip712: {\n name: \"x402 Wrapped USDT\",\n version: \"1\",\n },\n },\n};\n\n/**\n * Get CAIP-2 network ID from network name\n * \n * @param networkName - Network name (e.g., 'base-sepolia', 'base')\n * @returns CAIP-2 network identifier (e.g., 'eip155:84532')\n * @throws Error if network name is not supported\n * \n * @example\n * ```typescript\n * const networkId = getNetworkId('base-sepolia'); // 'eip155:84532'\n * ```\n */\nexport function getNetworkId(networkName: string): Network {\n const networkId = NETWORK_IDS[networkName];\n if (!networkId) {\n throw new Error(\n `Unsupported network: ${networkName}. ` +\n `Supported networks: ${Object.keys(NETWORK_IDS).join(\", \")}`\n );\n }\n return networkId;\n}\n\n/**\n * Get network name from CAIP-2 network ID\n * \n * @param network - CAIP-2 network identifier (e.g., 'eip155:84532')\n * @returns Network name (e.g., 'base-sepolia')\n * @throws Error if network ID is not supported\n * \n * @example\n * ```typescript\n * const networkName = getNetworkName('eip155:84532'); // 'base-sepolia'\n * ```\n */\nexport function getNetworkName(network: Network): string {\n const networkName = NETWORK_NAMES[network];\n if (!networkName) {\n throw new Error(\n `Unsupported network ID: ${network}. ` +\n `Supported network IDs: ${Object.keys(NETWORK_NAMES).join(\", \")}`\n );\n }\n return networkName;\n}\n\n/**\n * Get default asset (USDC) information for a network\n * \n * @param network - CAIP-2 network identifier (e.g., 'eip155:84532')\n * @returns Asset information including address, decimals, and EIP-712 domain\n * @throws Error if network is not supported\n * \n * @example\n * ```typescript\n * const asset = getDefaultAsset('eip155:84532');\n * // { address: '0x036Cb...', decimals: 6, eip712: { name: 'USDC', version: '2' } }\n * ```\n */\nexport function getDefaultAsset(network: Network): AssetInfo {\n const assetInfo = DEFAULT_ASSETS[network];\n if (!assetInfo) {\n throw new Error(`No default asset configured for network: ${network}`);\n }\n return assetInfo;\n}\n\n/**\n * Parse money value to decimal number\n * \n * Handles various formats:\n * - Dollar sign: '$1.50' -> 1.50\n * - Decimal string: '1.50' -> 1.50\n * - Number: 1.50 -> 1.50\n * \n * @param money - Money value as string or number\n * @returns Decimal number\n * @throws Error if money format is invalid\n * \n * @example\n * ```typescript\n * parseMoneyToDecimal('$1.50'); // 1.50\n * parseMoneyToDecimal('1.50'); // 1.50\n * parseMoneyToDecimal(1.50); // 1.50\n * ```\n */\nexport function parseMoneyToDecimal(money: string | number): number {\n if (typeof money === \"number\") {\n return money;\n }\n\n // Remove $ sign and whitespace, then parse\n const cleanMoney = money.replace(/^\\$/, \"\").trim();\n const amount = parseFloat(cleanMoney);\n\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`);\n }\n\n return amount;\n}\n\n/**\n * Process price to atomic amount for the default asset on a network\n * \n * This function converts various price formats to atomic units (smallest denomination).\n * For USDC with 6 decimals: 1.5 USD -> '1500000'\n * \n * @param price - Price as string or number (in USD, not atomic units)\n * @param network - CAIP-2 network identifier\n * @returns Object with amount as string in atomic units, or error\n * \n * @example\n * ```typescript\n * const result = processPriceToAtomicAmount('1.5', 'eip155:84532');\n * // { amount: '1500000' }\n * ```\n */\nexport function processPriceToAtomicAmount(\n price: string | number,\n network: Network\n): { amount: string } | { error: string } {\n try {\n const amount = parseMoneyToDecimal(price);\n const asset = getDefaultAsset(network);\n const decimals = asset.decimals;\n\n // Convert to smallest unit using integer-only arithmetic to avoid floating-point precision issues\n // Split the amount into whole and fractional parts\n const [whole, fractional = '0'] = amount.toString().split('.');\n const paddedFractional = fractional.padEnd(decimals, '0').slice(0, decimals);\n const atomicAmount = BigInt(whole) * BigInt(10 ** decimals) + BigInt(paddedFractional);\n\n return { amount: atomicAmount.toString() };\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : \"Unknown error processing price\",\n };\n }\n}\n\n/**\n * Alias mapping from v1 network names to v2 CAIP-2 identifiers\n * This provides backward compatibility for v1 network names\n */\nexport const NETWORK_ALIASES_V1_TO_V2: Record<string, Network> = {\n // V1 human-readable names -> V2 CAIP-2 canonical keys\n \"base-sepolia\": \"eip155:84532\",\n \"x-layer-testnet\": \"eip155:1952\",\n \"skale-base-sepolia\": \"eip155:324705682\",\n \"base\": \"eip155:8453\",\n \"x-layer\": \"eip155:196\",\n \"bsc-testnet\": \"eip155:97\",\n \"bsc\": \"eip155:56\",\n};\n\n/**\n * Get list of all supported network IDs (CAIP-2 identifiers)\n *\n * Returns protocol-level CAIP-2 network identifiers like \"eip155:84532\".\n * Use this for x402 v2 protocol operations and facilitator configuration.\n *\n * @returns Array of CAIP-2 network identifiers\n *\n * @example\n * ```typescript\n * const networkIds = getSupportedNetworkIds();\n * // => ['eip155:84532', 'eip155:8453', 'eip155:1952', ...]\n * \n * // For x402 v2 protocol\n * const facilitator = createFacilitator({\n * networks: getSupportedNetworkIds()\n * });\n * ```\n */\nexport function getSupportedNetworkIds(): Network[] {\n return Object.keys(NETWORK_NAMES) as Network[];\n}\n\n/**\n * @deprecated Use getSupportedNetworkIds() instead for clarity\n * Get list of all supported networks using v2 CAIP-2 identifiers\n */\nexport function getSupportedNetworksV2(): Network[] {\n return getSupportedNetworkIds();\n}\n\n/**\n * Get the alias mapping from v1 network names to v2 CAIP-2 identifiers\n *\n * @returns Record mapping v1 names to v2 CAIP-2 keys\n *\n * @example\n * ```typescript\n * const aliases = getNetworkAliasesV1ToV2();\n * // => { 'base-sepolia': 'eip155:84532', 'x-layer-testnet': 'eip155:1952', ... }\n * ```\n */\nexport function getNetworkAliasesV1ToV2(): Record<string, Network> {\n return { ...NETWORK_ALIASES_V1_TO_V2 };\n}\n\n/**\n * Convert any network identifier to its canonical v2 CAIP-2 key\n *\n * Handles both v1 human-readable names and v2 CAIP-2 identifiers,\n * returning the canonical v2 CAIP-2 identifier for all inputs.\n *\n * @param network - Network identifier (v1 name or v2 CAIP-2)\n * @returns Canonical v2 CAIP-2 network identifier\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * toCanonicalNetworkKey('base-sepolia'); // 'eip155:84532'\n * toCanonicalNetworkKey('eip155:84532'); // 'eip155:84532'\n * toCanonicalNetworkKey('x-layer'); // 'eip155:196'\n * ```\n */\nexport function toCanonicalNetworkKey(network: string): Network {\n // If it's already a CAIP-2 identifier, validate it\n if (network.startsWith('eip155:')) {\n const canonicalNetwork = network as Network;\n if (canonicalNetwork in NETWORK_NAMES) {\n return canonicalNetwork;\n }\n throw new Error(\n `Unsupported CAIP-2 network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_NAMES).join(\", \")}`\n );\n }\n\n // If it's a v1 name, convert it using the alias map\n const canonicalNetwork = NETWORK_ALIASES_V1_TO_V2[network];\n if (!canonicalNetwork) {\n throw new Error(\n `Unsupported network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES_V1_TO_V2).join(\", \")}`\n );\n }\n return canonicalNetwork;\n}\n","/**\n * Network configuration for x402x\n *\n * Contains deployed contract addresses and configuration for each supported network.\n * Uses official x402 v2 CAIP-2 network identifiers.\n */\n\nimport type { Network } from \"@x402/core/types\";\nimport { getDefaultAsset, getNetworkId } from \"./network-utils.js\";\nimport type { NetworkConfig } from \"./types.js\";\n\n/**\n * Helper to get default asset config\n */\nfunction getDefaultAssetConfig(network: Network) {\n const defaultAsset = getDefaultAsset(network);\n return {\n address: defaultAsset.address as string,\n decimals: defaultAsset.decimals,\n eip712: {\n name: defaultAsset.eip712.name,\n version: defaultAsset.eip712.version,\n },\n };\n}\n\n/**\n * Network configurations for all supported networks\n *\n * Uses getNetworkId() and getDefaultAsset() to ensure consistency\n * with CAIP-2 network identifiers.\n */\nexport const networks: Record<string, NetworkConfig> = {\n \"base-sepolia\": {\n chainId: parseInt(getNetworkId(\"base-sepolia\").split(\":\")[1]),\n name: \"Base Sepolia\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://sepolia.basescan.org/address/\",\n txExplorerBaseUrl: \"https://sepolia.basescan.org/tx/\",\n settlementRouter: \"0x817e4f0ee2fbdaac426f1178e149f7dc98873ecb\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"base-sepolia\")),\n hooks: {\n transfer: \"0x4DE234059C6CcC94B8fE1eb1BD24804794083569\",\n },\n demoHooks: {\n nftMint: \"0x261206558E6eEd104Cba4AD913b2Eec85D21108e\",\n randomNFT: \"0x5756A67a33118F5Ad9840411f252E14d84Dd7c02\",\n reward: \"0xf05cE06e7ee4ffCb67a509003DbD73A6d95Cc960\",\n rewardToken: \"0xb6854e33BfD428d15B4f5398cFf8e84d4196FDA6\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"ETH\",\n },\n },\n \"x-layer-testnet\": {\n chainId: parseInt(getNetworkId(\"x-layer-testnet\").split(\":\")[1]),\n name: \"X Layer Testnet\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://www.oklink.com/xlayer-test/address/\",\n txExplorerBaseUrl: \"https://www.oklink.com/xlayer-test/tx/\",\n settlementRouter: \"0xba9980fb08771e2fd10c17450f52d39bcb9ed576\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"x-layer-testnet\")),\n hooks: {\n transfer: \"0xD4b98dd614c1Ea472fC4547a5d2B93f3D3637BEE\",\n },\n demoHooks: {\n nftMint: \"0x468F666314b070338841422012AB2f6539bfcE48\",\n randomNFT: \"0xBA931bB5B2F2DC5354aFAED1d3996B0c6e417518\",\n reward: \"0xda8B270Ec442Ff797807b95604E3319e36Aad05d\",\n rewardToken: \"0x348AFDE3B4B70dCb02053aF95588a4ab41e95FbC\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"OKB\",\n },\n },\n \"skale-base-sepolia\": {\n chainId: parseInt(getNetworkId(\"skale-base-sepolia\").split(\":\")[1]),\n name: \"SKALE Base Sepolia\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://base-sepolia-testnet-explorer.skalenodes.com/address/\",\n txExplorerBaseUrl: \"https://base-sepolia-testnet-explorer.skalenodes.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"skale-base-sepolia\")),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659cd5494e69852be8d9d23fe05aab14b29b\",\n randomNFT: \"0x081258287f692d61575387ee2a4075f34dd7aef7\",\n reward: \"0xc20634ea518985901e32fbc1ba27fa673d37601a\",\n rewardToken: \"0x9fc2c199170b039f093abcd54008038f0c0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"Credits\",\n },\n },\n \"bsc-testnet\": {\n chainId: parseInt(getNetworkId(\"bsc-testnet\").split(\":\")[1]),\n name: \"BSC Testnet\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://testnet.bscscan.com/address/\",\n txExplorerBaseUrl: \"https://testnet.bscscan.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"bsc-testnet\")),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n randomNFT: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n reward: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n rewardToken: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"BNB\",\n },\n },\n // Mainnet configurations\n base: {\n chainId: parseInt(getNetworkId(\"base\").split(\":\")[1]),\n name: \"Base Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://basescan.org/address/\",\n txExplorerBaseUrl: \"https://basescan.org/tx/\",\n settlementRouter: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"base\")),\n hooks: {\n transfer: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n },\n demoHooks: {\n nftMint: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n randomNFT: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n reward: \"0x4B566FD5eFf76e3BdF20Ca5c3F2FA7cdbb3bD99A\",\n rewardToken: \"0x12d41108f9F12064f792418C9BA0ACF6EdcE7790\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"ETH\",\n },\n },\n \"x-layer\": {\n chainId: parseInt(getNetworkId(\"x-layer\").split(\":\")[1]),\n name: \"X Layer Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://www.oklink.com/xlayer/address/\",\n txExplorerBaseUrl: \"https://www.oklink.com/xlayer/tx/\",\n settlementRouter: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"x-layer\")),\n hooks: {\n transfer: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n },\n demoHooks: {\n nftMint: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n randomNFT: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n reward: \"0x4B566FD5eFf76e3BdF20Ca5c3F2FA7cdbb3bD99A\",\n rewardToken: \"0x12d41108f9F12064f792418C9BA0ACF6EdcE7790\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"OKB\",\n },\n },\n bsc: {\n chainId: parseInt(getNetworkId(\"bsc\").split(\":\")[1]),\n name: \"BSC Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://bscscan.com/address/\",\n txExplorerBaseUrl: \"https://bscscan.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(getNetworkId(\"bsc\")),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n randomNFT: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n reward: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n rewardToken: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"BNB\",\n },\n },\n};\n\n/**\n * Get network configuration by network name\n *\n * @param network - Network name (e.g., 'base-sepolia', 'skale-base-sepolia')\n * @returns Network configuration\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * const config = getNetworkConfig('base-sepolia');\n * console.log(config.settlementRouter);\n * ```\n */\nexport function getNetworkConfig(network: string): NetworkConfig {\n const config = networks[network];\n if (!config) {\n throw new Error(\n `Unsupported network: ${network}. ` +\n `Supported networks: ${Object.keys(networks).join(\", \")}`,\n );\n }\n return config;\n}\n\n/**\n * Check if a network is supported\n *\n * @param network - Network name to check\n * @returns True if network is supported\n *\n * @example\n * ```typescript\n * if (isNetworkSupported('base-sepolia')) {\n * // proceed...\n * }\n * ```\n */\nexport function isNetworkSupported(network: string): boolean {\n return network in networks;\n}\n\n/**\n * Get list of all supported network names (human-readable identifiers)\n *\n * Returns user-friendly network names like \"base-sepolia\", \"base\", etc.\n * Use this for UI display, configuration, and user-facing operations.\n *\n * @returns Array of supported network names\n *\n * @example\n * ```typescript\n * const networks = getSupportedNetworkNames();\n * // => ['base-sepolia', 'base', 'x-layer-testnet', ...]\n * \n * // For UI dropdown\n * <select>\n * {networks.map(name => <option key={name}>{name}</option>)}\n * </select>\n * ```\n */\nexport function getSupportedNetworkNames(): string[] {\n return Object.keys(networks);\n}\n\n/**\n * @deprecated Use getSupportedNetworkNames() instead for clarity\n * Get list of all supported networks\n */\nexport function getSupportedNetworks(): string[] {\n return getSupportedNetworkNames();\n}\n","/**\n * Chain definitions for x402x supported networks\n * \n * This module provides viem chain configurations for all supported networks,\n * including custom definitions for chains not in viem's standard list.\n */\n\nimport { defineChain, type Chain } from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport { getNetworkId } from \"./network-utils.js\";\n\n/**\n * Custom chain definitions for networks not in viem's standard list\n */\nconst customChains: Record<number, Chain> = {\n // X Layer Testnet\n 1952: defineChain({\n id: 1952,\n name: \"X Layer Testnet\",\n nativeCurrency: { name: \"OKB\", symbol: \"OKB\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://testrpc.xlayer.tech\"] },\n },\n blockExplorers: {\n default: { name: \"OKLink\", url: \"https://www.oklink.com/xlayer-test\" },\n },\n testnet: true,\n }),\n\n // SKALE Nebula Testnet (Base Sepolia)\n 324705682: defineChain({\n id: 324705682,\n name: \"SKALE Nebula Testnet\",\n nativeCurrency: { name: \"sFUEL\", symbol: \"sFUEL\", decimals: 18 },\n rpcUrls: {\n default: {\n http: [\"https://testnet.skalenodes.com/v1/lanky-ill-funny-testnet\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"SKALE Explorer\",\n url: \"https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com\",\n },\n },\n testnet: true,\n }),\n\n // X Layer Mainnet\n 196: defineChain({\n id: 196,\n name: \"X Layer\",\n nativeCurrency: { name: \"OKB\", symbol: \"OKB\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://rpc.xlayer.tech\"] },\n },\n blockExplorers: {\n default: { name: \"OKLink\", url: \"https://www.oklink.com/xlayer\" },\n },\n testnet: false,\n }),\n};\n\n/**\n * Get viem chain configuration for a network name\n * \n * Checks custom chains first, then falls back to viem's standard chains.\n * \n * @param network - Network name (e.g., \"base-sepolia\", \"x-layer-testnet\")\n * @returns Viem chain configuration\n * @throws Error if network is not supported\n * \n * @example\n * ```typescript\n * const chain = getChain(\"x-layer-testnet\");\n * // => { id: 1952, name: \"X Layer Testnet\", ... }\n * \n * const baseChain = getChain(\"base-sepolia\");\n * // => { id: 84532, name: \"Base Sepolia\", ... }\n * ```\n */\nexport function getChain(network: string): Chain {\n // Get the CAIP-2 network ID (e.g., \"base-sepolia\" -> \"eip155:84532\")\n const networkId = getNetworkId(network);\n const chainId = parseInt(networkId.split(\":\")[1]);\n\n // Check custom chains first\n if (customChains[chainId]) {\n return customChains[chainId];\n }\n\n // Then check viem's standard chains\n const chain = Object.values(allChains).find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(\n `Unsupported network: ${network} (chain ID: ${chainId}). ` +\n `Please add custom chain definition in chains.ts`\n );\n }\n return chain;\n}\n\n/**\n * Get viem chain configuration by chain ID\n * \n * @param chainId - Chain ID\n * @returns Viem chain configuration\n * @throws Error if chain ID is not supported\n * \n * @example\n * ```typescript\n * const chain = getChainById(1952);\n * // => { id: 1952, name: \"X Layer Testnet\", ... }\n * ```\n */\nexport function getChainById(chainId: number): Chain {\n // Check custom chains first\n if (customChains[chainId]) {\n return customChains[chainId];\n }\n\n // Then check viem's standard chains\n const chain = Object.values(allChains).find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(\n `Unsupported chain ID: ${chainId}. ` +\n `Please add custom chain definition in chains.ts`\n );\n }\n return chain;\n}\n\n/**\n * Get all custom chain definitions\n * \n * @returns Record of chain ID to chain configuration\n * \n * @example\n * ```typescript\n * const customs = getCustomChains();\n * // => { 1952: { id: 1952, name: \"X Layer Testnet\", ... }, ... }\n * ```\n */\nexport function getCustomChains(): Record<number, Chain> {\n return { ...customChains };\n}\n\n/**\n * Check if a chain ID has a custom definition\n * \n * @param chainId - Chain ID to check\n * @returns True if chain has custom definition\n * \n * @example\n * ```typescript\n * isCustomChain(1952); // true (X Layer Testnet)\n * isCustomChain(84532); // false (Base Sepolia - in viem)\n * ```\n */\nexport function isCustomChain(chainId: number): boolean {\n return chainId in customChains;\n}\n\n","/**\n * TransferHook utilities\n *\n * TransferHook is a builtin hook that supports two modes:\n * 1. Simple Transfer: Direct transfer to a single recipient (data = '0x')\n * 2. Distributed Transfer: Split transfer to multiple recipients by percentage\n */\n\nimport { encodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\nimport { getNetworkConfig } from \"../networks.js\";\n\n/**\n * Split configuration for distributed transfer\n */\nexport interface Split {\n /** Recipient address */\n recipient: Address;\n /** Basis points (1-10000, where 10000 = 100%, 1 = 0.01%) */\n bips: number;\n}\n\n/**\n * TransferHook utilities namespace\n */\nexport namespace TransferHook {\n /**\n * Encode hookData for TransferHook\n *\n * Supports two modes:\n *\n * **Mode 1 - Simple Transfer** (no parameters):\n * - Transfers entire amount to the `recipient` address in ExecuteParams\n * - Most gas efficient\n * - Returns '0x'\n *\n * **Mode 2 - Distributed Transfer** (with splits):\n * - Distributes amount to multiple recipients based on percentage (bips)\n * - Each split specifies recipient address and basis points (1-10000)\n * - If total bips < 10000, remaining goes to the `recipient` in ExecuteParams\n * - If total bips = 10000, `recipient` receives nothing\n *\n * @param splits - Optional array of split configurations\n * @returns Encoded hookData as hex string\n * @throws Error if validation fails (invalid addresses, bips > 10000, etc.)\n *\n * @example Simple transfer\n * ```typescript\n * // All amount goes to recipient\n * const hookData = TransferHook.encode();\n * // => '0x'\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xAlice...' // Alice receives 100%\n * });\n * ```\n *\n * @example Distributed transfer - full split\n * ```typescript\n * // Split between Alice (60%) and Bob (40%)\n * const hookData = TransferHook.encode([\n * { recipient: '0xAlice...', bips: 6000 }, // 60%\n * { recipient: '0xBob...', bips: 4000 } // 40%\n * ]);\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xCharity...' // Charity receives 0% (total = 100%)\n * });\n * ```\n *\n * @example Distributed transfer - partial split\n * ```typescript\n * // Platform takes 30%, creator gets the rest\n * const hookData = TransferHook.encode([\n * { recipient: '0xPlatform...', bips: 3000 } // 30%\n * ]);\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xCreator...' // Creator receives 70%\n * });\n * ```\n */\n export function encode(splits?: Split[]): string {\n // Mode 1: Simple Transfer\n if (!splits || splits.length === 0) {\n return \"0x\";\n }\n\n // Mode 2: Distributed Transfer - Validate splits\n let totalBips = 0;\n for (const split of splits) {\n // Validate recipient\n if (!split.recipient || split.recipient === \"0x0000000000000000000000000000000000000000\") {\n throw new Error(`Invalid recipient address: ${split.recipient}`);\n }\n\n // Validate bips\n if (split.bips <= 0) {\n throw new Error(`Bips must be greater than 0, got: ${split.bips}`);\n }\n if (split.bips > 10000) {\n throw new Error(`Individual bips cannot exceed 10000, got: ${split.bips}`);\n }\n\n totalBips += split.bips;\n }\n\n // Validate total bips\n if (totalBips > 10000) {\n throw new Error(`Total bips (${totalBips}) exceeds 10000 (100%)`);\n }\n\n // Encode as tuple(address,uint16)[]\n // viem requires component definitions for tuple types\n return encodeAbiParameters(\n [\n {\n type: \"tuple[]\",\n name: \"splits\",\n components: [\n { name: \"recipient\", type: \"address\" },\n { name: \"bips\", type: \"uint16\" },\n ],\n },\n ],\n [splits.map((s) => ({ recipient: s.recipient, bips: s.bips }))],\n );\n }\n\n /**\n * Get TransferHook address for a specific network\n *\n * @param network - Network name (e.g., 'base-sepolia')\n * @returns TransferHook contract address\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * const address = TransferHook.getAddress('base-sepolia');\n * // => '0x4DE234059C6CcC94B8fE1eb1BD24804794083569'\n * ```\n */\n export function getAddress(network: string): string {\n const config = getNetworkConfig(network);\n return config.hooks.transfer;\n }\n}\n","/**\n * Demo hooks utilities for showcase examples\n *\n * Provides encoding/decoding and address lookup for demo hooks used in showcase examples.\n * These hooks are optional and may not be deployed on all networks.\n */\n\nimport { encodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\nimport { getNetworkConfig } from \"../networks.js\";\n\n/**\n * NFT Mint Configuration\n */\nexport interface MintConfig {\n /** Address of the NFT contract to mint from */\n nftContract: Address;\n}\n\n/**\n * Reward Hook Configuration\n */\nexport interface RewardConfig {\n /** Address of the ERC20 reward token contract */\n rewardToken: Address;\n}\n\n/**\n * NFTMintHook utilities for showcase examples\n */\nexport namespace NFTMintHook {\n /**\n * Get NFTMintHook contract address for a specific network\n *\n * @param network - Network identifier (e.g., 'base-sepolia', 'skale-base-sepolia')\n * @returns The contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getAddress(network: string): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.nftMint) {\n throw new Error(\n `NFTMintHook not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.nftMint as `0x${string}`;\n }\n\n /**\n * Get the NFT contract address for a specific network\n *\n * This is the address of the ERC721 contract that will be minted from.\n *\n * @param network - Network identifier (e.g., 'base-sepolia', 'skale-base-sepolia')\n * @returns The NFT contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getNFTContractAddress(network: string): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.randomNFT) {\n throw new Error(\n `RandomNFT contract not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.randomNFT as `0x${string}`;\n }\n\n /**\n * Encode MintConfig into hookData for NFTMintHook\n *\n * The NFTMintHook contract expects a specific ABI-encoded struct format.\n * This method handles the encoding for you.\n *\n * @param config - The mint configuration\n * @returns ABI-encoded hookData ready to use with x402x execute\n */\n export function encode(config: MintConfig): `0x${string}` {\n // Encode as tuple matching the Solidity struct:\n // struct MintConfig {\n // address nftContract;\n // }\n return encodeAbiParameters(\n [\n {\n type: \"tuple\",\n components: [{ name: \"nftContract\", type: \"address\" }],\n },\n ],\n [\n {\n nftContract: config.nftContract,\n },\n ],\n );\n }\n}\n\n/**\n * RewardHook utilities for showcase examples\n */\nexport namespace RewardHook {\n /**\n * Get RewardHook contract address for a specific network\n *\n * @param network - Network identifier (e.g., 'base-sepolia', 'skale-base-sepolia')\n * @returns The contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getAddress(network: string): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.reward) {\n throw new Error(\n `RewardHook not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.reward as `0x${string}`;\n }\n\n /**\n * Get the reward token (ERC20) address for a specific network\n *\n * This is the address of the ERC20 contract that will be distributed as rewards.\n *\n * @param network - Network identifier (e.g., 'base-sepolia', 'skale-base-sepolia')\n * @returns The reward token contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getTokenAddress(network: string): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.rewardToken) {\n throw new Error(\n `Reward token not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.rewardToken as `0x${string}`;\n }\n\n /**\n * Encode RewardConfig into hookData for RewardHook\n *\n * The RewardHook contract expects a specific ABI-encoded struct format.\n * This method handles the encoding for you.\n *\n * @param config - The reward configuration\n * @returns ABI-encoded hookData ready to use with x402x execute\n */\n export function encode(config: RewardConfig): `0x${string}` {\n // Encode as tuple matching the Solidity struct:\n // struct RewardConfig {\n // address rewardToken;\n // }\n return encodeAbiParameters(\n [\n {\n type: \"tuple\",\n components: [{ name: \"rewardToken\", type: \"address\" }],\n },\n ],\n [\n {\n rewardToken: config.rewardToken,\n },\n ],\n );\n }\n}\n","/**\n * Validation helpers for PaymentRequirements.extra (settlement parameters)\n */\n\nimport type { SettlementExtra } from \"./types.js\";\nimport { SettlementExtraError } from \"./types.js\";\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /** Whether the validation passed */\n valid: boolean;\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Validate Ethereum address format (0x followed by 40 hex characters)\n * \n * @param address - Address to validate\n * @returns true if valid Ethereum address\n */\nexport function isValidAddress(address: string): boolean {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Validate hex string format (0x followed by even number of hex characters)\n * \n * @param hex - Hex string to validate\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n return /^0x[a-fA-F0-9]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Validate 32-byte hex string (0x followed by 64 hex characters)\n * \n * @param hex - Hex string to validate\n * @returns true if valid 32-byte hex string\n */\nexport function isValid32ByteHex(hex: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(hex);\n}\n\n/**\n * Validate numeric string (non-negative integer)\n * \n * @param value - Value to validate\n * @returns true if valid numeric string\n */\nexport function isValidNumericString(value: string): boolean {\n return /^\\d+$/.test(value);\n}\n\n/**\n * Validate settlement extra parameters\n * \n * This validates all required fields for settlement through SettlementRouter.\n * \n * @param extra - Settlement extra parameters to validate\n * @returns Validation result with error message if invalid\n * \n * @example\n * ```typescript\n * const result = validateSettlementExtra({\n * settlementRouter: \"0x1234...\",\n * payTo: \"0x5678...\",\n * facilitatorFee: \"10000\",\n * hook: \"0xabcd...\",\n * hookData: \"0x\",\n * name: \"USDC\",\n * version: \"2\",\n * salt: \"0x1234...\"\n * });\n * \n * if (!result.valid) {\n * throw new Error(result.error);\n * }\n * ```\n */\nexport function validateSettlementExtra(\n extra: Partial<SettlementExtra>\n): ValidationResult {\n // Validate settlementRouter\n if (!extra.settlementRouter) {\n return { valid: false, error: \"settlementRouter is required\" };\n }\n if (!isValidAddress(extra.settlementRouter)) {\n return { valid: false, error: \"settlementRouter must be a valid Ethereum address\" };\n }\n\n // Validate payTo\n if (!extra.payTo) {\n return { valid: false, error: \"payTo is required\" };\n }\n if (!isValidAddress(extra.payTo)) {\n return { valid: false, error: \"payTo must be a valid Ethereum address\" };\n }\n\n // Validate facilitatorFee\n if (extra.facilitatorFee === undefined || extra.facilitatorFee === null) {\n return { valid: false, error: \"facilitatorFee is required\" };\n }\n if (!isValidNumericString(extra.facilitatorFee)) {\n return { valid: false, error: \"facilitatorFee must be a non-negative numeric string\" };\n }\n\n // Validate hook\n if (!extra.hook) {\n return { valid: false, error: \"hook is required\" };\n }\n if (!isValidAddress(extra.hook)) {\n return { valid: false, error: \"hook must be a valid Ethereum address\" };\n }\n\n // Validate hookData\n if (extra.hookData === undefined || extra.hookData === null) {\n return { valid: false, error: \"hookData is required\" };\n }\n if (!isValidHex(extra.hookData)) {\n return { valid: false, error: \"hookData must be a valid hex string\" };\n }\n\n // Validate name (EIP-712 domain)\n if (!extra.name) {\n return { valid: false, error: \"name is required (EIP-712 domain name)\" };\n }\n if (typeof extra.name !== \"string\" || extra.name.trim().length === 0) {\n return { valid: false, error: \"name must be a non-empty string\" };\n }\n\n // Validate version (EIP-712 domain)\n if (!extra.version) {\n return { valid: false, error: \"version is required (EIP-712 domain version)\" };\n }\n if (typeof extra.version !== \"string\" || extra.version.trim().length === 0) {\n return { valid: false, error: \"version must be a non-empty string\" };\n }\n\n // Validate salt\n if (!extra.salt) {\n return { valid: false, error: \"salt is required\" };\n }\n if (!isValid32ByteHex(extra.salt)) {\n return { valid: false, error: \"salt must be a 32-byte hex string (0x followed by 64 hex characters)\" };\n }\n\n return { valid: true };\n}\n\n/**\n * Assert that settlement extra parameters are valid\n * Throws SettlementExtraError if validation fails\n * \n * @param extra - Settlement extra parameters to validate\n * @throws {SettlementExtraError} If validation fails\n * \n * @example\n * ```typescript\n * try {\n * assertValidSettlementExtra(extra);\n * // Extra is valid, proceed with settlement\n * } catch (error) {\n * console.error(\"Invalid settlement extra:\", error.message);\n * }\n * ```\n */\nexport function assertValidSettlementExtra(\n extra: Partial<SettlementExtra>\n): asserts extra is SettlementExtra {\n const result = validateSettlementExtra(extra);\n if (!result.valid) {\n throw new SettlementExtraError(result.error || \"Invalid settlement extra\");\n }\n}\n","/**\n * Utility functions for x402x\n */\n\nimport type { PaymentRequirements, SettlementExtra } from \"./types.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { generateSalt } from \"./commitment.js\";\nimport { assertValidSettlementExtra } from \"./validation.js\";\nimport { getNetworkName } from \"./network-utils.js\";\n\n/**\n * Add settlement extension to PaymentRequirements\n *\n * This function enriches standard x402 PaymentRequirements with settlement-specific\n * parameters in the `extra` field.\n *\n * @param requirements - Base PaymentRequirements (standard x402)\n * @param params - Settlement parameters\n * @returns Enhanced PaymentRequirements with settlement extra\n *\n * @example\n * ```typescript\n * import { addSettlementExtra, TransferHook, getNetworkConfig } from '@x402x/core';\n *\n * const baseRequirements = {\n * scheme: 'exact',\n * network: 'base-sepolia',\n * maxAmountRequired: '100000',\n * asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n * payTo: '0x...',\n * resource: '/api/payment',\n * };\n *\n * const requirements = addSettlementExtra(baseRequirements, {\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData: TransferHook.encode(),\n * facilitatorFee: '10000',\n * payTo: merchantAddress,\n * });\n * ```\n */\nexport function addSettlementExtra(\n requirements: PaymentRequirements,\n params: {\n hook: string;\n hookData: string;\n facilitatorFee?: string;\n payTo?: string;\n salt?: string;\n },\n): PaymentRequirements {\n // Convert CAIP-2 network ID to friendly name for config lookup\n const networkName = getNetworkName(requirements.network);\n const config = getNetworkConfig(networkName);\n\n // Preserve existing name/version from requirements.extra if they exist (from x402 official middleware)\n // Only use config values as fallback\n const existingExtra = requirements.extra || {};\n const name = (existingExtra.name as string) || config.defaultAsset.eip712.name;\n const version = (existingExtra.version as string) || config.defaultAsset.eip712.version;\n\n const extra: SettlementExtra = {\n // Asset EIP-712 domain info (preserve existing if available)\n name,\n version,\n // Settlement parameters\n settlementRouter: config.settlementRouter,\n salt: params.salt || generateSalt(),\n payTo: params.payTo || requirements.payTo,\n facilitatorFee: params.facilitatorFee || \"0\",\n hook: params.hook,\n hookData: params.hookData,\n };\n\n // Validate the settlement extra parameters\n assertValidSettlementExtra(extra);\n\n return {\n ...requirements,\n // Override payTo to point to SettlementRouter\n payTo: config.settlementRouter,\n extra: {\n ...requirements.extra,\n ...extra,\n },\n };\n}\n","/**\n * Extension helpers for x402x\n * Implements x402x-router-settlement extension for PaymentRequired.extensions\n */\n\n/**\n * Router settlement extension info\n * Contains all settlement-specific parameters that were previously in extra\n */\nexport interface RouterSettlementExtensionInfo {\n /** Schema version for the extension */\n schemaVersion: number;\n /** Optional description of the extension */\n description?: string;\n /** Unique salt for idempotency (32 bytes hex, dynamically generated) */\n salt?: string;\n /** Settlement router contract address */\n settlementRouter?: string;\n /** Hook contract address */\n hook?: string;\n /** Encoded hook parameters (hex string) */\n hookData?: string;\n /** Final recipient address (renamed from payTo to avoid confusion with accepts[].payTo) */\n finalPayTo?: string;\n /** Facilitator fee amount in token's smallest unit */\n facilitatorFee?: string;\n}\n\n/**\n * Router settlement extension structure\n * Location: PaymentRequired.extensions[\"x402x-router-settlement\"]\n */\nexport interface RouterSettlementExtension {\n /** Extension information */\n info: RouterSettlementExtensionInfo;\n /** Optional JSON schema for validation */\n schema?: Record<string, unknown>;\n}\n\n/**\n * Create x402x-router-settlement extension declaration\n * \n * This extension informs clients that the server supports router settlement functionality.\n * Clients MUST echo extensions in their payment payload.\n * \n * @param params - Extension parameters\n * @param params.description - Optional description of the extension\n * @param params.schema - Optional JSON schema for validation\n * @param params.settlementRouter - Settlement router contract address\n * @param params.hook - Hook contract address\n * @param params.hookData - Encoded hook parameters\n * @param params.finalPayTo - Final recipient address\n * @param params.facilitatorFee - Facilitator fee amount\n * @returns Extension object for PaymentRequired.extensions[\"x402x-router-settlement\"]\n * \n * @example\n * ```typescript\n * const extension = createRouterSettlementExtension({\n * description: \"Settlement router with atomic fee distribution\",\n * settlementRouter: \"0x...\",\n * hook: \"0x...\",\n * hookData: \"0x\",\n * finalPayTo: \"0x...\",\n * facilitatorFee: \"0\"\n * });\n * \n * const paymentRequired = {\n * x402Version: 2,\n * resource: { url: \"/api/payment\", ... },\n * accepts: [...],\n * extensions: {\n * \"x402x-router-settlement\": extension\n * }\n * };\n * ```\n */\nexport function createRouterSettlementExtension(\n params?: {\n description?: string;\n schema?: Record<string, unknown>;\n settlementRouter?: string;\n hook?: string;\n hookData?: string;\n finalPayTo?: string;\n facilitatorFee?: string;\n }\n): RouterSettlementExtension {\n const info: RouterSettlementExtensionInfo = {\n schemaVersion: 1,\n };\n\n // Add optional fields\n if (params?.description !== undefined) {\n info.description = params.description;\n }\n\n // Add settlement parameters if provided\n // Note: salt will be dynamically generated by enrichDeclaration\n if (params?.settlementRouter) info.settlementRouter = params.settlementRouter;\n if (params?.hook) info.hook = params.hook;\n if (params?.hookData) info.hookData = params.hookData;\n if (params?.finalPayTo) info.finalPayTo = params.finalPayTo;\n if (params?.facilitatorFee !== undefined) info.facilitatorFee = params.facilitatorFee;\n\n // Create schema if not provided but we have settlement params\n // Note: salt is marked as required but will be added by enrichDeclaration\n let schema = params?.schema;\n if (!schema && params?.settlementRouter) {\n schema = {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"number\" },\n description: { type: \"string\" },\n salt: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{64}$\" },\n settlementRouter: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n hook: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n hookData: { type: \"string\", pattern: \"^0x[a-fA-F0-9]*$\" },\n finalPayTo: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n facilitatorFee: { type: \"string\" },\n },\n // Salt is required in the final enriched version but not in the initial declaration\n required: [\"schemaVersion\", \"settlementRouter\", \"hook\", \"hookData\", \"finalPayTo\"],\n };\n }\n\n return {\n info,\n ...(schema !== undefined && { schema }),\n };\n}\n\n/**\n * Get the extension key for router settlement\n * \n * @returns The extension key \"x402x-router-settlement\"\n */\nexport function getRouterSettlementExtensionKey(): string {\n return \"x402x-router-settlement\";\n}\n","/**\n * x402x Router Settlement Server Extension\n * \n * Implements ResourceServerExtension interface to integrate router settlement\n * functionality into x402 v2 resource servers.\n */\n\nimport type { ResourceServerExtension } from \"@x402/core/types\";\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport { createRouterSettlementExtension } from \"./extensions.js\";\nimport { generateSalt } from \"./commitment.js\";\n\n/**\n * Extension key constant\n */\nexport const ROUTER_SETTLEMENT_KEY = \"x402x-router-settlement\";\n\n/**\n * Type guard to check if context is an HTTP request context.\n * \n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is { method?: string; adapter?: unknown } {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx;\n}\n\n/**\n * Router settlement extension declaration type\n */\ninterface RouterSettlementDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n schemaVersion?: number;\n description?: string;\n /** Dynamic fields that need to be generated per-request */\n dynamic?: {\n salt?: boolean;\n [key: string]: unknown;\n };\n };\n schema?: Record<string, unknown>;\n}\n\n/**\n * x402x Router Settlement ResourceServerExtension\n * \n * This extension enriches PaymentRequired responses with router settlement\n * information, enabling clients to use the SettlementRouter for atomic payments.\n * \n * The extension dynamically generates per-request values like salt to ensure\n * each payment authorization is unique and cannot be replayed.\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { routerSettlementServerExtension } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * server.registerExtension(routerSettlementServerExtension);\n * ```\n */\nexport const routerSettlementServerExtension: ResourceServerExtension = {\n key: ROUTER_SETTLEMENT_KEY,\n\n enrichDeclaration: (declaration, transportContext) => {\n // Cast to typed declaration\n const extension = declaration as RouterSettlementDeclaration;\n\n // Generate dynamic salt for this request\n const salt = generateSalt();\n\n // Basic enrichment - ensure proper structure with dynamic salt\n const enriched: RouterSettlementDeclaration = {\n ...extension,\n info: {\n schemaVersion: 1,\n ...(extension.info || {}),\n // Add the generated salt to the info\n salt,\n },\n };\n\n // If HTTP context is available, we could add additional metadata\n if (isHTTPRequestContext(transportContext)) {\n // Future: could add HTTP-specific metadata here\n // For now, the salt generation is the main dynamic enhancement\n }\n\n return enriched;\n },\n};\n\n/**\n * Register router settlement extension with an x402ResourceServer\n * \n * Convenience function to register the routerSettlementServerExtension.\n * Also registers necessary hooks for handling settlement parameters.\n * \n * @param server - x402ResourceServer instance\n * @returns The server instance for chaining\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { registerExactEvmScheme } from \"@x402/evm/exact/server/register\";\n * import { registerRouterSettlement } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * registerExactEvmScheme(server, {});\n * registerRouterSettlement(server);\n * ```\n */\nexport function registerRouterSettlement(server: x402ResourceServer): x402ResourceServer {\n // Register the extension for enriching PaymentRequired responses\n server.registerExtension(routerSettlementServerExtension);\n \n // Note: Hooks for verify/settle are registered separately via \n // registerSettlementHooks if needed for custom validation logic\n \n return server;\n}\n\n/**\n * Create extension declaration for routes\n * \n * Helper function to create properly formatted extension declarations\n * for use in route configurations. The extension enables dynamic salt\n * generation per request and includes all settlement parameters.\n * \n * @param params - Extension parameters including settlement info\n * @returns Extension declaration object\n * \n * @example\n * ```typescript\n * const routes = {\n * \"GET /api/data\": {\n * accepts: { scheme: \"exact\", price: \"$0.01\", network: \"eip155:84532\", payTo: \"0x...\" },\n * extensions: createExtensionDeclaration({ \n * description: \"Router settlement with dynamic salt\",\n * settlementRouter: \"0x...\",\n * hook: \"0x...\",\n * hookData: \"0x\",\n * finalPayTo: \"0x...\",\n * facilitatorFee: \"0\"\n * })\n * }\n * };\n * ```\n */\nexport function createExtensionDeclaration(params?: {\n description?: string;\n schema?: Record<string, unknown>;\n settlementRouter?: string;\n hook?: string;\n hookData?: string;\n finalPayTo?: string;\n facilitatorFee?: string;\n}): Record<string, unknown> {\n return {\n [ROUTER_SETTLEMENT_KEY]: createRouterSettlementExtension(params),\n };\n}\n\n","/**\n * Settlement Routes Helper\n * \n * Provides utilities for creating route configurations with router settlement support.\n * This module bridges the gap between x402 v2 official SDK's RoutesConfig and x402x\n * settlement requirements.\n */\n\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport type { PaymentRequirements } from \"@x402/core/types\";\nimport { createExtensionDeclaration } from \"./server-extension.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { TransferHook } from \"./hooks/index.js\";\n\n/**\n * Route configuration from @x402/core\n * Re-exported for convenience with settlement prefix to avoid naming conflicts\n */\nexport interface SettlementRouteConfig {\n accepts: SettlementPaymentOption | SettlementPaymentOption[];\n resource?: string;\n description?: string;\n mimeType?: string;\n extensions?: Record<string, unknown>;\n unpaidResponseBody?: (context: unknown) => Promise<{ contentType: string; body: unknown }> | { contentType: string; body: unknown };\n customPaywallHtml?: string;\n}\n\n/**\n * Payment option from @x402/core\n */\nexport interface SettlementPaymentOption {\n scheme: string;\n network: string;\n payTo: string | ((context: unknown) => string | Promise<string>);\n price: string | ((context: unknown) => string | Promise<string>);\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Settlement options for route configuration\n */\nexport interface SettlementOptions {\n /** Hook contract address (optional, defaults to TransferHook for the network) */\n hook?: string;\n /** Encoded hook data (optional, defaults to TransferHook.encode()) */\n hookData?: string;\n /** Facilitator fee amount (optional, will be dynamically calculated if not provided) */\n facilitatorFee?: string;\n /** Final recipient address (the actual merchant/payee) */\n finalPayTo: string;\n /** Optional description for the extension */\n description?: string;\n}\n\n/**\n * Configuration for settlement hooks\n */\nexport interface SettlementHooksConfig {\n /** Whether to enable automatic salt extraction from extension info */\n enableSaltExtraction?: boolean;\n /** Whether to validate settlement router parameters */\n validateSettlementParams?: boolean;\n}\n\n/**\n * Create a route configuration with router settlement support\n * \n * This helper wraps the standard x402 RouteConfig and adds settlement-specific\n * configuration including hooks, settlement router address, and dynamic extensions.\n * \n * The key insight: We add settlement info to the `extra` field of PaymentRequirements,\n * which gets passed through verify/settle. The extension generates dynamic salt per request.\n * \n * @param baseConfig - Base route configuration\n * @param settlementOptions - Settlement-specific options\n * @returns Enhanced route configuration with settlement support\n * \n * @example\n * ```typescript\n * import { createSettlementRouteConfig, TransferHook } from \"@x402x/extensions\";\n * \n * const routes = {\n * \"POST /api/purchase\": createSettlementRouteConfig({\n * accepts: {\n * scheme: \"exact\",\n * network: \"eip155:84532\",\n * payTo: \"0x...\", // Will be overridden with settlementRouter\n * price: \"$1.00\",\n * },\n * description: \"Purchase endpoint\",\n * }, {\n * hook: TransferHook.getAddress(\"base-sepolia\"),\n * hookData: TransferHook.encode(),\n * finalPayTo: \"0xMerchantAddress\",\n * })\n * };\n * ```\n */\nexport function createSettlementRouteConfig(\n baseConfig: SettlementRouteConfig,\n settlementOptions: SettlementOptions,\n): SettlementRouteConfig {\n // Normalize accepts to array\n const acceptsArray = Array.isArray(baseConfig.accepts) \n ? baseConfig.accepts \n : [baseConfig.accepts];\n\n // Store network config and settlement params for extension\n // We need to get these from the first option to pass to the extension\n const firstOption = acceptsArray[0];\n const firstNetwork = firstOption.network;\n const networkConfig = getNetworkConfig(firstNetwork);\n if (!networkConfig) {\n throw new Error(`Network configuration not found for: ${firstNetwork}`);\n }\n\n // Resolve hook address (default to TransferHook)\n const hook = settlementOptions.hook || TransferHook.getAddress(firstNetwork);\n const hookData = settlementOptions.hookData || TransferHook.encode();\n\n // Enhance each payment option - only add EIP-712 domain info to extra\n const enhancedAccepts = acceptsArray.map((option) => {\n const network = typeof option.network === \"string\" ? option.network : option.network;\n const optionNetworkConfig = getNetworkConfig(network);\n if (!optionNetworkConfig) {\n throw new Error(`Network configuration not found for: ${network}`);\n }\n\n // Only keep EIP-712 domain parameters in extra (scheme-specific)\n const enhancedOption: SettlementPaymentOption = {\n ...option,\n // Override payTo to use settlementRouter as the immediate recipient\n payTo: optionNetworkConfig.settlementRouter,\n // Only include EIP-712 domain info in extra\n extra: {\n ...(option.extra || {}),\n name: optionNetworkConfig.defaultAsset.eip712.name,\n version: optionNetworkConfig.defaultAsset.eip712.version,\n },\n };\n\n return enhancedOption;\n });\n\n // Add settlement extension to the route with all settlement parameters\n const extensions = {\n ...(baseConfig.extensions || {}),\n ...createExtensionDeclaration({\n description: settlementOptions.description || \"Router settlement with atomic fee distribution\",\n // Pass settlement parameters to be included in extension info\n settlementRouter: networkConfig.settlementRouter,\n hook,\n hookData,\n finalPayTo: settlementOptions.finalPayTo,\n facilitatorFee: settlementOptions.facilitatorFee || \"0\",\n }),\n };\n\n return {\n ...baseConfig,\n accepts: enhancedAccepts.length === 1 ? enhancedAccepts[0] : enhancedAccepts,\n extensions,\n };\n}\n\n/**\n * Register settlement-specific hooks with the resource server\n * \n * This function registers lifecycle hooks for handling settlement-specific logic:\n * - Extract salt from extension info before verification\n * - Validate settlement router parameters\n * \n * @param server - x402ResourceServer instance\n * @param config - Hook configuration options\n * \n * @example\n * ```typescript\n * import { registerSettlementHooks } from \"@x402x/extensions\";\n * \n * registerSettlementHooks(server, {\n * enableSaltExtraction: true,\n * validateSettlementParams: true,\n * });\n * ```\n */\nexport function registerSettlementHooks(\n server: x402ResourceServer,\n config: SettlementHooksConfig = {},\n): void {\n const {\n enableSaltExtraction = true,\n validateSettlementParams = true,\n } = config;\n\n if (enableSaltExtraction) {\n // Hook to extract settlement params from PaymentPayload extensions and add to requirements.extra\n // This is needed because the facilitator currently reads from requirements.extra\n server.onBeforeVerify(async (context) => {\n const { paymentPayload, requirements } = context;\n \n // Check if payment has settlement extension\n if (paymentPayload.extensions && \n \"x402x-router-settlement\" in paymentPayload.extensions) {\n const extension = paymentPayload.extensions[\"x402x-router-settlement\"] as any;\n \n if (extension?.info) {\n // Ensure requirements.extra exists\n if (!requirements.extra) {\n (requirements as any).extra = {};\n }\n \n // Extract all settlement params from extension and add to extra\n // (for backward compatibility with facilitator that reads from extra)\n const info = extension.info;\n if (info.salt) (requirements.extra as any).salt = info.salt;\n if (info.settlementRouter) (requirements.extra as any).settlementRouter = info.settlementRouter;\n if (info.hook) (requirements.extra as any).hook = info.hook;\n if (info.hookData) (requirements.extra as any).hookData = info.hookData;\n if (info.finalPayTo) (requirements.extra as any).payTo = info.finalPayTo;\n if (info.facilitatorFee !== undefined) (requirements.extra as any).facilitatorFee = info.facilitatorFee;\n }\n }\n \n // Don't abort - continue with verification\n return undefined;\n });\n }\n\n if (validateSettlementParams) {\n // Hook to validate settlement router parameters before settlement\n server.onBeforeSettle(async (context) => {\n const { paymentPayload, requirements } = context;\n \n // Try to get params from extensions first (v2 standard), then fall back to extra\n let settlementParams: any = {};\n \n if (paymentPayload.extensions && \"x402x-router-settlement\" in paymentPayload.extensions) {\n const extension = paymentPayload.extensions[\"x402x-router-settlement\"] as any;\n if (extension?.info) {\n settlementParams = extension.info;\n }\n }\n \n // Fallback to extra if not in extensions\n if (!settlementParams.settlementRouter && requirements.extra) {\n settlementParams = requirements.extra;\n }\n \n // Validate that required settlement fields are present\n const requiredFields = ['settlementRouter', 'hook', 'hookData'];\n const payToField = 'finalPayTo' in settlementParams ? 'finalPayTo' : 'payTo';\n const missingFields = requiredFields.filter(field => !settlementParams[field]);\n if (!settlementParams[payToField]) {\n missingFields.push(payToField);\n }\n \n if (missingFields.length > 0) {\n return {\n abort: true,\n reason: `Missing settlement parameters: ${missingFields.join(', ')}`,\n };\n }\n \n // All checks passed\n return undefined;\n });\n }\n}\n\n","/**\n * Helper functions for x402x router settlement integration\n * \n * Provides convenient utilities for working with x402 v2 resource servers\n * and router settlement extensions.\n */\n\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport type { PaymentRequirements, SchemeNetworkFacilitator } from \"@x402/core/types\";\nimport type { FacilitatorConfig } from \"./facilitator-types.js\";\nimport { registerRouterSettlement as registerExtension } from \"./server-extension.js\";\nimport { createRouterSettlementExtension, getRouterSettlementExtensionKey } from \"./extensions.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { generateSalt } from \"./commitment.js\";\nimport type { SettlementExtra } from \"./types.js\";\n\n/**\n * Register router settlement extension with a resource server\n * \n * @param server - x402ResourceServer instance\n * @returns The server instance for chaining\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { registerExactEvmScheme } from \"@x402/evm/exact/server/register\";\n * import { registerRouterSettlement } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * registerExactEvmScheme(server, {});\n * registerRouterSettlement(server);\n * ```\n */\nexport function registerRouterSettlement(server: x402ResourceServer): x402ResourceServer {\n return registerExtension(server);\n}\n\n/**\n * Create a router settlement facilitator\n * \n * Factory function to create a RouterSettlementFacilitator instance.\n * \n * Note: This requires @x402x/facilitator-sdk to be installed separately.\n * \n * @param config - Facilitator configuration\n * @returns RouterSettlementFacilitator instance\n * \n * @example\n * ```typescript\n * // First install the dependency:\n * // pnpm install @x402x/facilitator-sdk\n * \n * import { createX402xFacilitator } from \"@x402x/extensions\";\n * // Or import directly:\n * // import { createRouterSettlementFacilitator } from \"@x402x/facilitator-sdk\";\n * \n * const facilitator = createX402xFacilitator({\n * privateKey: process.env.FACILITATOR_PRIVATE_KEY,\n * rpcUrls: {\n * \"base-sepolia\": \"https://sepolia.base.org\",\n * },\n * allowedRouters: {\n * \"base-sepolia\": [\"0x817e4f0ee2fbdaac426f1178e149f7dc98873ecb\"],\n * },\n * });\n * ```\n */\nexport async function createX402xFacilitator(\n config: FacilitatorConfig,\n): Promise<SchemeNetworkFacilitator> {\n // Dynamic import to avoid hard dependency\n // Using Function constructor to avoid static analysis during build\n try {\n const importFn = new Function('specifier', 'return import(specifier)');\n const facilitatorModule = await importFn('@x402x/facilitator-sdk') as {\n createRouterSettlementFacilitator: (config: FacilitatorConfig) => SchemeNetworkFacilitator;\n };\n return facilitatorModule.createRouterSettlementFacilitator(config);\n } catch (error) {\n throw new Error(\n \"createX402xFacilitator requires @x402x/facilitator-sdk to be installed. \" +\n \"Please install it using your package manager.\",\n );\n }\n}\n\n/**\n * Options for adding router settlement parameters\n */\nexport interface WithRouterSettlementOptions {\n /** Hook contract address (required) */\n hook: string;\n /** Encoded hook data (required) */\n hookData: string;\n /** Facilitator fee amount in atomic units (required) */\n facilitatorFee: string;\n /** Final recipient address (required) */\n payTo: string;\n /** Unique salt for idempotency (optional, will be auto-generated if not provided) */\n salt?: string;\n /** Asset name for EIP-712 (optional, will use network config default if not provided) */\n name?: string;\n /** Asset version for EIP-712 (optional, will use network config default if not provided) */\n version?: string;\n}\n\n/**\n * Add router settlement parameters to PaymentRequirements\n * \n * Enriches payment requirements with settlement router extra fields needed\n * for atomic settlement through the SettlementRouter contract.\n * \n * @param requirements - Base payment requirements from x402 middleware\n * @param options - Router settlement options\n * @returns Enhanced payment requirements with settlement extra\n * \n * @example\n * ```typescript\n * import { withRouterSettlement, TransferHook } from \"@x402x/extensions\";\n * \n * const baseRequirements = {\n * scheme: \"exact\",\n * network: \"eip155:84532\",\n * asset: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n * amount: \"1000000\", // 1 USDC\n * payTo: merchantAddress,\n * };\n * \n * const requirements = withRouterSettlement(baseRequirements, {\n * hook: TransferHook.getAddress(\"base-sepolia\"),\n * hookData: TransferHook.encode(),\n * facilitatorFee: \"10000\", // 0.01 USDC\n * payTo: merchantAddress,\n * });\n * ```\n */\nexport function withRouterSettlement(\n requirements: Partial<PaymentRequirements>,\n options: WithRouterSettlementOptions,\n): PaymentRequirements {\n // Validate required fields\n if (!requirements.network) {\n throw new Error(\"Network is required in payment requirements\");\n }\n\n if (!requirements.asset) {\n throw new Error(\"Asset is required in payment requirements\");\n }\n\n // Get network configuration\n const networkConfig = getNetworkConfig(requirements.network);\n if (!networkConfig) {\n throw new Error(`Network configuration not found for network: ${requirements.network}`);\n }\n\n // Generate salt if not provided\n const salt = options.salt || generateSalt();\n\n // Build settlement extra with EIP-712 domain info\n const settlementExtra: SettlementExtra = {\n settlementRouter: networkConfig.settlementRouter,\n salt,\n payTo: options.payTo,\n facilitatorFee: options.facilitatorFee,\n hook: options.hook,\n hookData: options.hookData,\n name: options.name || networkConfig.defaultAsset.eip712.name,\n version: options.version || networkConfig.defaultAsset.eip712.version,\n };\n\n // Create extension declaration\n const extensionKey = getRouterSettlementExtensionKey();\n const extensionDeclaration = createRouterSettlementExtension({\n description: \"Router settlement with atomic fee distribution\",\n });\n\n // Merge with existing requirements\n const reqWithExtensions = requirements as any;\n return {\n ...requirements,\n extra: {\n ...(reqWithExtensions.extra || {}),\n ...settlementExtra,\n },\n extensions: {\n ...(reqWithExtensions.extensions || {}),\n [extensionKey]: extensionDeclaration,\n },\n } as PaymentRequirements;\n}\n\n/**\n * Check if payment requirements use router settlement mode\n * \n * @param requirements - Payment requirements to check\n * @returns True if router settlement is enabled\n * \n * @example\n * ```typescript\n * if (isRouterSettlement(requirements)) {\n * console.log(\"Using router settlement mode\");\n * }\n * ```\n */\nexport function isRouterSettlement(requirements: PaymentRequirements): boolean {\n return !!(requirements.extra && \"settlementRouter\" in requirements.extra);\n}\n\n","/**\n * Amount parsing and formatting utilities for x402x default asset (USDC)\n */\n\nimport type { Network } from \"@x402/core/types\";\nimport { processPriceToAtomicAmount, getDefaultAsset } from \"./network-utils.js\";\n\n/**\n * Error class for amount-related validation errors\n */\nexport class AmountError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AmountError\";\n }\n}\n\n/**\n * Parse amount from various formats to atomic units for the default asset (USDC)\n *\n * Supports multiple input formats:\n * - Dollar format: '$1.2' or '$1.20' → '1200000' (1.2 USDC)\n * - Decimal string: '1.2' or '1.20' → '1200000'\n * - Number: 1.2 → '1200000'\n *\n * Uses x402's processPriceToAtomicAmount for parsing. All string/number inputs\n * are treated as USD amounts, not atomic units.\n *\n * @param amount - Amount in various formats (USD, not atomic units)\n * @param network - Network name (required) - used to determine token decimals\n * @returns Amount in atomic units as string\n * @throws AmountError if amount format is invalid\n *\n * @example\n * ```typescript\n * parseDefaultAssetAmount('$1.2', 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount('1.2', 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount(1.2, 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount('100', 'base-sepolia') // '100000000' (100 USDC, not 100 atomic units)\n * ```\n */\nexport function parseDefaultAssetAmount(amount: string | number, network: Network): string {\n // Handle empty/invalid input\n if (amount === null || amount === undefined || amount === \"\") {\n throw new AmountError(\"Amount is required\");\n }\n\n // Use x402's processPriceToAtomicAmount for parsing\n // This handles all string/number inputs as USD amounts\n const result = processPriceToAtomicAmount(amount, network);\n\n if (\"error\" in result) {\n throw new AmountError(`Invalid amount format: ${result.error}`);\n }\n\n return result.amount;\n}\n\n/**\n * Format atomic units to human-readable decimal string for the default asset (USDC)\n *\n * Automatically determines decimals from the network's default asset configuration.\n *\n * @param amount - Amount in atomic units\n * @param network - Network name (required) - used to determine token decimals\n * @returns Human-readable decimal string\n * @throws AmountError if amount is invalid\n *\n * @example\n * ```typescript\n * formatDefaultAssetAmount('1200000', 'base-sepolia') // '1.2'\n * formatDefaultAssetAmount('1000000', 'base-sepolia') // '1'\n * formatDefaultAssetAmount('1', 'base-sepolia') // '0.000001'\n * ```\n */\nexport function formatDefaultAssetAmount(amount: string, network: Network): string {\n const atomicAmount = BigInt(amount);\n if (atomicAmount < 0n) {\n throw new AmountError(\"Amount cannot be negative\");\n }\n\n // Get decimals from network's default asset\n const asset = getDefaultAsset(network);\n const decimals = asset.decimals;\n\n const amountStr = atomicAmount.toString().padStart(decimals + 1, \"0\");\n const integerPart = amountStr.slice(0, -decimals) || \"0\";\n const decimalPart = amountStr.slice(-decimals);\n\n // Remove trailing zeros from decimal part\n const trimmedDecimal = decimalPart.replace(/0+$/, \"\");\n\n if (trimmedDecimal) {\n return `${integerPart}.${trimmedDecimal}`;\n }\n return integerPart;\n}\n","/**\n * Facilitator API client utilities for x402x\n *\n * Provides client-side functions to interact with facilitator HTTP APIs.\n * This includes fee calculation and caching utilities, as well as\n * helper functions for settlement mode detection and validation.\n */\n\nimport type { PaymentRequirements, PaymentPayload, SettlementExtraCore } from \"./types.js\";\nimport { SettlementExtraError } from \"./types.js\";\n\n/**\n * Check if a payment request requires SettlementRouter mode\n *\n * This is a client-side utility to determine which settlement flow to use.\n *\n * @param paymentRequirements - Payment requirements from 402 response\n * @returns True if settlement mode is required\n *\n * @example\n * ```typescript\n * if (isSettlementMode(paymentRequirements)) {\n * // Use Settlement Router mode\n * await submitToFacilitator(...);\n * } else {\n * // Use standard x402 mode\n * await settle(...);\n * }\n * ```\n */\nexport function isSettlementMode(paymentRequirements: PaymentRequirements): boolean {\n return !!paymentRequirements.extra?.settlementRouter;\n}\n\n/**\n * Parse and validate settlement extra parameters\n *\n * This is useful for clients to validate payment requirements before submission.\n *\n * @param extra - Extra field from PaymentRequirements\n * @returns Parsed settlement extra parameters\n * @throws SettlementExtraError if parameters are invalid\n *\n * @example\n * ```typescript\n * try {\n * const extra = parseSettlementExtra(paymentRequirements.extra);\n * console.log('Hook:', extra.hook);\n * console.log('Facilitator Fee:', extra.facilitatorFee);\n * } catch (error) {\n * console.error('Invalid settlement parameters:', error);\n * }\n * ```\n */\nexport function parseSettlementExtra(extra: unknown): SettlementExtraCore {\n if (!extra || typeof extra !== \"object\") {\n throw new SettlementExtraError(\"Missing or invalid extra field\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = extra as Record<string, any>;\n\n // Validate required fields\n if (!e.settlementRouter || typeof e.settlementRouter !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid settlementRouter\");\n }\n if (!e.salt || typeof e.salt !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid salt\");\n }\n if (!e.payTo || typeof e.payTo !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid payTo\");\n }\n if (!e.facilitatorFee || typeof e.facilitatorFee !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid facilitatorFee\");\n }\n if (!e.hook || typeof e.hook !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid hook\");\n }\n if (!e.hookData || typeof e.hookData !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid hookData\");\n }\n\n return {\n settlementRouter: e.settlementRouter,\n salt: e.salt,\n payTo: e.payTo,\n facilitatorFee: e.facilitatorFee,\n hook: e.hook,\n hookData: e.hookData,\n };\n}\n\n/**\n * Result of facilitator fee calculation\n *\n * This interface represents the response from facilitator's /calculate-fee endpoint.\n * Only essential information is included - internal cost breakdown is not exposed.\n */\nexport interface FeeCalculationResult {\n network: string;\n hook: string;\n hookData?: string;\n hookAllowed: boolean;\n\n // Main result - recommended facilitator fee\n facilitatorFee: string; // Atomic units (e.g., USDC with 6 decimals)\n facilitatorFeeUSD: string; // USD value for display\n\n // Metadata\n calculatedAt: string; // ISO 8601 timestamp\n validitySeconds: number; // How long this fee is valid (typically 60 seconds)\n\n token: {\n address: string;\n symbol: string;\n decimals: number;\n };\n}\n\n/**\n * Simple in-memory cache for fee calculations\n */\nclass FeeCache {\n private cache: Map<string, { result: FeeCalculationResult; expiresAt: number }> = new Map();\n private ttlMs: number;\n\n constructor(ttlSeconds: number = 60) {\n this.ttlMs = ttlSeconds * 1000;\n }\n\n private getCacheKey(network: string, hook: string, hookData?: string): string {\n return `${network}:${hook}:${hookData || \"\"}`;\n }\n\n get(network: string, hook: string, hookData?: string): FeeCalculationResult | null {\n const key = this.getCacheKey(network, hook, hookData);\n const cached = this.cache.get(key);\n\n if (!cached) {\n return null;\n }\n\n if (Date.now() > cached.expiresAt) {\n this.cache.delete(key);\n return null;\n }\n\n return cached.result;\n }\n\n set(result: FeeCalculationResult): void {\n const key = this.getCacheKey(result.network, result.hook, result.hookData);\n this.cache.set(key, {\n result,\n expiresAt: Date.now() + this.ttlMs,\n });\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n// Global cache instance\nconst feeCache = new FeeCache(60);\n\n/**\n * Calculate recommended facilitator fee by querying the facilitator service\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param network - Network name\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters\n * @param useCache - Whether to use caching (default: true)\n * @returns Fee calculation result with sufficient safety margin\n *\n * @example\n * ```typescript\n * const feeResult = await calculateFacilitatorFee(\n * 'https://facilitator.x402x.dev',\n * 'base-sepolia',\n * '0x1234...',\n * '0x'\n * );\n * console.log(`Recommended fee: ${feeResult.facilitatorFee} (${feeResult.facilitatorFeeUSD} USD)`);\n * ```\n */\nexport async function calculateFacilitatorFee(\n facilitatorUrl: string,\n network: string,\n hook: string,\n hookData?: string,\n useCache: boolean = true,\n): Promise<FeeCalculationResult> {\n // Check cache first\n if (useCache) {\n const cached = feeCache.get(network, hook, hookData);\n if (cached) {\n return cached;\n }\n }\n\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n\n // Build query parameters\n const params = new URLSearchParams({\n network,\n hook,\n });\n\n if (hookData) {\n params.append(\"hookData\", hookData);\n }\n\n // Query facilitator service\n const url = `${baseUrl}/calculate-fee?${params.toString()}`;\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n // Add timeout\n signal: AbortSignal.timeout(3000),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Facilitator fee calculation failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const result: FeeCalculationResult = await response.json();\n\n // Validate response\n if (!result.facilitatorFee || !result.network || !result.hook) {\n throw new Error(\"Invalid response from facilitator service\");\n }\n\n // Cache the result\n if (useCache) {\n feeCache.set(result);\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to calculate facilitator fee: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Clear the fee calculation cache\n *\n * Useful for testing or forcing fresh calculations\n */\nexport function clearFeeCache(): void {\n feeCache.clear();\n}\n\n/**\n * Response from facilitator verify endpoint\n *\n * Indicates whether a payment payload is valid without executing it.\n */\nexport interface VerifyResponse {\n /** Whether the payment payload is valid */\n isValid: boolean;\n /** Reason for invalidity if isValid is false */\n invalidReason?: string;\n /** Payer address extracted from the payload */\n payer: string;\n}\n\n/**\n * Response from facilitator settle endpoint\n *\n * Contains the result of settlement execution on-chain.\n */\nexport interface SettleResponse {\n /** Whether the settlement was successful */\n success: boolean;\n /** Transaction hash of the settlement */\n transaction: string;\n /** Network the settlement was executed on */\n network: string;\n /** Payer address */\n payer: string;\n /** Error reason if settlement failed */\n errorReason?: string;\n}\n\n/**\n * Verify a payment payload with the facilitator\n *\n * Calls the facilitator's `/verify` endpoint to validate a payment without executing it.\n * This is useful for pre-validation before actual settlement.\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param paymentPayload - Payment payload from client (x402 standard)\n * @param paymentRequirements - Payment requirements (x402 standard)\n * @returns Verification response indicating validity\n *\n * @throws Error if network request fails or response is invalid\n *\n * @example\n * ```typescript\n * import { verify } from '@x402x/core';\n *\n * const result = await verify(\n * 'https://facilitator.x402x.dev',\n * paymentPayload,\n * paymentRequirements\n * );\n *\n * if (result.isValid) {\n * console.log('Payment is valid, payer:', result.payer);\n * } else {\n * console.error('Invalid payment:', result.invalidReason);\n * }\n * ```\n */\nexport async function verify(\n facilitatorUrl: string,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n): Promise<VerifyResponse> {\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n const url = `${baseUrl}/verify`;\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n paymentPayload,\n paymentRequirements,\n }),\n // Add timeout\n signal: AbortSignal.timeout(10000),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Facilitator verify failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const result: VerifyResponse = await response.json();\n\n // Validate response structure\n if (typeof result.isValid !== \"boolean\") {\n throw new Error(\"Invalid response from facilitator: missing isValid field\");\n }\n\n if (typeof result.payer !== \"string\") {\n throw new Error(\"Invalid response from facilitator: missing payer field\");\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to verify with facilitator: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Settle a payment with the facilitator\n *\n * Calls the facilitator's `/settle` endpoint to execute the payment on-chain.\n * This is the core function that submits a signed payment for blockchain execution.\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param paymentPayload - Payment payload from client (x402 standard)\n * @param paymentRequirements - Payment requirements (x402 standard)\n * @param timeout - Optional timeout in milliseconds (default: 30000)\n * @returns Settlement response with transaction details\n *\n * @throws Error if network request fails, response is invalid, or settlement fails\n *\n * @example\n * ```typescript\n * import { settle } from '@x402x/core';\n *\n * const result = await settle(\n * 'https://facilitator.x402x.dev',\n * paymentPayload,\n * paymentRequirements,\n * 30000 // 30 second timeout\n * );\n *\n * if (result.success) {\n * console.log('Settlement successful!');\n * console.log('Transaction:', result.transaction);\n * console.log('Network:', result.network);\n * } else {\n * console.error('Settlement failed:', result.errorReason);\n * }\n * ```\n */\nexport async function settle(\n facilitatorUrl: string,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n timeout: number = 30000,\n): Promise<SettleResponse> {\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n const url = `${baseUrl}/settle`;\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n paymentPayload,\n paymentRequirements,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const result: any = await response.json();\n\n if (!response.ok) {\n throw new Error(\n result.error || result.message || `Facilitator settle failed: ${response.status}`,\n );\n }\n\n // Validate result structure\n if (typeof result.success !== \"boolean\") {\n throw new Error(\"Invalid response from facilitator: missing success field\");\n }\n\n if (!result.success) {\n throw new Error(result.errorReason || \"Settlement failed\");\n }\n\n if (!result.transaction) {\n throw new Error(\"Invalid response from facilitator: missing transaction hash\");\n }\n\n return {\n success: result.success,\n transaction: result.transaction,\n network: result.network || paymentRequirements.network,\n payer: result.payer || \"\",\n errorReason: result.errorReason,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new Error(`Facilitator settle timed out after ${timeout}ms`);\n }\n throw new Error(`Failed to settle with facilitator: ${error.message}`);\n }\n throw error;\n }\n}\n","/**\n * ABI definitions for x402x contracts\n */\n\n/**\n * Settlement Router ABI\n *\n * Contains functions used by facilitators for settlement and fee management.\n */\nexport const SETTLEMENT_ROUTER_ABI = [\n {\n type: \"function\",\n name: \"settleAndExecute\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n { name: \"salt\", type: \"bytes32\" },\n { name: \"payTo\", type: \"address\" },\n { name: \"facilitatorFee\", type: \"uint256\" },\n { name: \"hook\", type: \"address\" },\n { name: \"hookData\", type: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"calculateCommitment\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"salt\", type: \"bytes32\" },\n { name: \"payTo\", type: \"address\" },\n { name: \"facilitatorFee\", type: \"uint256\" },\n { name: \"hook\", type: \"address\" },\n { name: \"hookData\", type: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"calculateContextKey\",\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"pure\",\n },\n {\n type: \"function\",\n name: \"isSettled\",\n inputs: [{ name: \"contextKey\", type: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getPendingFees\",\n inputs: [\n { name: \"facilitator\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"claimFees\",\n inputs: [{ name: \"tokens\", type: \"address[]\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","/**\n * Type definitions for facilitator services\n * \n * These types define the interfaces and configurations used by facilitator\n * implementations that handle payment verification and settlement.\n */\n\nimport type { Network } from \"@x402/core/types\";\n\n/**\n * Ethereum address type\n */\nexport type Address = `0x${string}`;\n\n/**\n * Response from facilitator verification\n */\nexport interface VerifyResponse {\n /** Whether the payment payload is valid */\n isValid: boolean;\n /** Reason for invalidity if isValid is false */\n invalidReason?: string;\n /** Payer address extracted from the payload */\n payer?: string;\n}\n\n/**\n * Response from facilitator settlement\n */\nexport interface SettleResponse {\n /** Whether the settlement was successful */\n success: boolean;\n /** Transaction hash of the settlement */\n transaction: string;\n /** Network the settlement was executed on (CAIP-2 format) */\n network: Network;\n /** Payer address */\n payer?: string;\n /** Error reason if settlement failed */\n errorReason?: string;\n}\n\n/**\n * Configuration for RouterSettlementFacilitator\n */\nexport interface FacilitatorConfig {\n /** Signer address for facilitating settlements (optional, will be derived from privateKey if not provided) */\n signer?: Address;\n /** Private key for local signing (enables sending transactions on standard RPC providers) */\n privateKey?: string;\n /** Allowed SettlementRouter addresses per network */\n allowedRouters?: Record<string, string[]>;\n /** Optional RPC URLs per network */\n rpcUrls?: Record<string, string>;\n /** Gas configuration */\n gasConfig?: {\n maxGasLimit: bigint;\n gasMultiplier: number;\n };\n /** Fee configuration */\n feeConfig?: {\n minFee: string;\n maxFee: string;\n };\n /** Timeouts in milliseconds */\n timeouts?: {\n verify: number;\n settle: number;\n };\n}\n\n/**\n * Parameters for SettlementRouter.settleAndExecute\n */\nexport interface SettlementRouterParams {\n token: Address;\n from: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: string;\n signature: string;\n salt: string;\n payTo: Address;\n facilitatorFee: string;\n hook: Address;\n hookData: string;\n settlementRouter: Address;\n}\n\n/**\n * Error types for facilitator operations\n */\nexport class FacilitatorValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorValidationError\";\n }\n}\n\nexport class SettlementRouterError extends Error {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"SettlementRouterError\";\n }\n}\n\n","/**\n * Legacy compatibility types and stubs for x402x v2 middleware\n * \n * These provide compatibility shims for patterns from x402 v1 that are not\n * part of the v2 API but are needed by x402x middleware implementations.\n */\n\nimport type { Network } from \"@x402/core/types\";\n\n/**\n * Supported EVM networks (legacy v1 pattern)\n * In v2, networks use CAIP-2 format (e.g., 'eip155:84532')\n */\nexport const SupportedEVMNetworks: Network[] = [\n \"eip155:84532\", // Base Sepolia\n \"eip155:1444673419\", // SKALE Base Sepolia\n \"eip155:8453\", // Base Mainnet\n];\n\n/**\n * Money schema validator (legacy v1 pattern)\n * In v2, validation is typically done through zod schemas in @x402/core\n */\nexport const moneySchema = {\n parse: (value: unknown): string | number => {\n if (typeof value === \"string\" || typeof value === \"number\") {\n return value;\n }\n throw new Error(\"Invalid money value\");\n },\n};\n\n/**\n * Settle response header name (legacy v1 pattern)\n * In v2, this is typically handled by x402HTTPResourceServer\n */\nexport const settleResponseHeader = \"X-Payment-Response\";\n\n/**\n * EVM utilities placeholder (legacy v1 pattern)\n * In v2, EVM functionality is provided by @x402/evm package\n */\nexport const evm = {\n /**\n * Check if a value is a valid EVM address\n */\n isAddress: (value: unknown): boolean => {\n if (typeof value !== \"string\") return false;\n return /^0x[a-fA-F0-9]{40}$/.test(value);\n },\n};\n\n/**\n * Payment scheme stub (legacy v1 pattern)\n * In v2, schemes are implemented as classes extending SchemeNetworkClient/Server\n */\nexport const exact = {\n name: \"exact\" as const,\n // Additional scheme properties would go here\n};\n\n/**\n * Chain ID to network mapping (legacy v1 pattern)\n */\nexport const ChainIdToNetwork: Record<number, Network> = {\n 84532: \"eip155:84532\", // Base Sepolia\n 1444673419: \"eip155:1444673419\", // SKALE Base Sepolia \n 8453: \"eip155:8453\", // Base Mainnet\n};\n\n/**\n * Check if a signer is a multi-network signer\n */\nexport function isMultiNetworkSigner(signer: unknown): boolean {\n // Simple type guard - would need more sophisticated logic in production\n return !!(signer && typeof signer === \"object\" && \"signTransaction\" in signer);\n}\n\n/**\n * Check if a signer is an SVM (Solana) signer wallet\n */\nexport function isSvmSignerWallet(signer: unknown): boolean {\n // Simple type guard for Solana wallets\n return !!(signer && typeof signer === \"object\" && \"publicKey\" in signer);\n}\n\n/**\n * Multi-network signer interface (legacy v1 pattern)\n */\nexport interface MultiNetworkSigner {\n address?: string;\n signTransaction?: (tx: unknown) => Promise<unknown>;\n [key: string]: unknown;\n}\n\n/**\n * X402 configuration interface (legacy v1 pattern)\n */\nexport interface X402Config {\n signer?: MultiNetworkSigner;\n [key: string]: unknown;\n}\n\n/**\n * Payment requirements selector type (legacy v1 pattern)\n */\nexport type PaymentRequirementsSelector = (requirements: unknown[]) => unknown;\n\n/**\n * Create payment header (legacy v1 stub)\n * In v2, this is handled by x402Client.createPaymentPayload()\n */\nexport function createPaymentHeader(_requirements: unknown, _signer: unknown): Promise<string> {\n // This should not be called in v2 - kept for compatibility during migration\n throw new Error(\"createPaymentHeader is not implemented in v2 - use x402Client instead\");\n}\n\n/**\n * Select payment requirements (legacy v1 stub)\n * In v2, this is handled by x402Client.createPaymentPayload()\n */\nexport function selectPaymentRequirements(\n _requirements: unknown[],\n _selector?: PaymentRequirementsSelector,\n): unknown {\n // This should not be called in v2 - kept for compatibility during migration\n throw new Error(\"selectPaymentRequirements is not implemented in v2 - use x402Client instead\");\n}\n\n/**\n * Decode X-Payment-Response header (legacy v1 stub)\n * In v2, response handling is done through x402HTTPClient\n */\nexport function decodeXPaymentResponse(_header: string): unknown {\n // This should not be called in v2 - kept for compatibility during migration\n throw new Error(\"decodeXPaymentResponse is not implemented in v2 - use x402HTTPClient instead\");\n}\n\n/**\n * Use facilitator for verification (legacy v1 stub)\n * In v2, this is handled through FacilitatorClient\n */\nexport function useFacilitator(_config: unknown) {\n // This should not be called in v2 - kept for compatibility during migration\n throw new Error(\"useFacilitator is not implemented in v2 - use FacilitatorClient instead\");\n}\n\n/**\n * Create a signer instance (legacy v1 stub)\n */\nexport function createSigner(_config: unknown): unknown {\n // This should not be called in v2 - kept for compatibility during migration\n throw new Error(\"createSigner is not implemented in v2 - use appropriate v2 signer patterns\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/middleware-utils.ts","../src/commitment.ts","../src/network-utils.ts","../src/networks.ts","../src/chains.ts","../src/hooks/transfer.ts","../src/hooks/demo.ts","../src/validation.ts","../src/utils.ts","../src/extensions.ts","../src/server-extension.ts","../src/facilitator.ts","../src/settlement-routes.ts","../src/helpers.ts","../src/amount.ts","../src/abi.ts","../src/facilitator-types.ts","../src/client/exact-evm-scheme.ts","../src/client/extension-handler.ts"],"names":["bytes","canonicalNetwork","caip2","TransferHook","getAddress","NFTMintHook","encodeAbiParameters","RewardHook","isValidAddress","isValidHex","registerRouterSettlement"],"mappings":";;;;;AA0JO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF;;;AC3GO,SAAS,qBAAqB,MAAA,EAAsC;AACzE,EAAA,MAAM,mBAAmB,MAAA,CAAO,WAAA;AAAA,IAC9B,MAAA,CAAO,QAAQ,MAAM,CAAA,CAAE,IAAI,CAAC,CAAC,OAAA,EAAS,KAAK,CAAA,KAAM;AAAA,MAC/C,OAAA;AAAA,MACA,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAA,KAAU,QAAA,GACzC,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,cAAA,EAAe,GACxC;AAAA,KACN;AAAA,GACH;AAEA,EAAA,OAAO,MAAA,CAAO,QAAQ,gBAAgB,CAAA,CAAE,IAAI,CAAC,CAAC,OAAA,EAAS,WAAW,CAAA,KAAM;AAEtE,IAAA,MAAM,CAAC,IAAA,EAAM,IAAI,CAAA,GAAI,QAAQ,QAAA,CAAS,GAAG,CAAA,GAAI,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAA,GAAI,CAAC,KAAK,OAAO,CAAA;AACjF,IAAA,IAAI,CAAC,IAA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A;AAI5D,EAAA,2BAAA,CAA4B,MAAA,EAAQ,CAAC,GAAA,KAAQ;AAI3C,IAAA,MAAA,CAAO,gDAAgD,GAAG,CAAA;AAAA,EAC5D,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,QAAA,CAAS,SAAS,MAAM,CAAA;AAE/B,EAAA,OAAO,MAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * Type definitions for @x402x/extensions\n * \n * Re-exports official x402 v2 types from @x402/core\n */\n\nimport type { PaymentRequirements, PaymentPayload } from \"@x402/core/types\";\n\n// Re-export x402 v2 types for convenience\nexport type { PaymentRequirements, PaymentPayload };\n\n/**\n * Signer interface for x402x\n * Compatible with x402 v2 client signer patterns\n */\nexport interface Signer {\n address: string;\n signTypedData?: (params: unknown) => Promise<string>;\n [key: string]: unknown;\n}\n\n/**\n * Commitment calculation parameters\n * All parameters must match exactly with SettlementRouter.sol\n */\nexport interface CommitmentParams {\n /** Chain ID (e.g., 84532 for Base Sepolia) */\n chainId: number;\n /** SettlementRouter contract address */\n hub: string;\n /** Asset contract address (ERC-3009 token, e.g., USDC) */\n asset: string;\n /** Payer address */\n from: string;\n /** Payment amount in asset's smallest unit */\n value: string;\n /** Authorization valid after timestamp */\n validAfter: string;\n /** Authorization valid before timestamp */\n validBefore: string;\n /** Unique salt for idempotency (32 bytes) */\n salt: string;\n /** Final recipient address */\n payTo: string;\n /** Facilitator fee amount */\n facilitatorFee: string;\n /** Hook contract address */\n hook: string;\n /** Encoded hook parameters */\n hookData: string;\n}\n\n/**\n * Gas model for different networks\n */\nexport type GasModel = \"eip1559\" | \"legacy\";\n\n/**\n * Network metadata containing protocol-level information\n */\nexport interface NetworkMetadata {\n /** Gas pricing model used by the network */\n gasModel: GasModel;\n /** Native token symbol */\n nativeToken: string;\n}\n\n/**\n * Demo hooks configuration for showcase examples\n */\nexport interface DemoHooks {\n /** NFTMintHook contract address */\n nftMint?: string;\n /** RandomNFT contract address */\n randomNFT?: string;\n /** RewardHook contract address */\n reward?: string;\n /** RewardToken contract address */\n rewardToken?: string;\n}\n\n/**\n * Network configuration for x402x\n */\nexport interface NetworkConfig {\n /** Chain ID */\n chainId: number;\n /** Network Name */\n name: string;\n /** Network Type */\n type: \"mainnet\" | \"testnet\";\n /** Network Address Explorer Base URL */\n addressExplorerBaseUrl: string;\n /** Network Transaction Explorer Base URL */\n txExplorerBaseUrl: string;\n /** SettlementRouter contract address */\n settlementRouter: string;\n /** Default asset configuration (ERC-3009 token, typically USDC) */\n defaultAsset: {\n /** Asset contract address */\n address: string;\n /** Asset decimals */\n decimals: number;\n /** EIP-712 domain info for signing */\n eip712: {\n /** Asset contract name (for EIP-712) */\n name: string;\n /** Asset contract version (for EIP-712) */\n version: string;\n };\n };\n /** Builtin hook addresses */\n hooks: {\n /** TransferHook address */\n transfer: string;\n };\n /** Demo hooks configuration (optional, for showcase examples) */\n demoHooks?: DemoHooks;\n /** Network metadata */\n metadata?: NetworkMetadata;\n}\n\n/**\n * Core settlement parameters (without EIP-712 domain info)\n */\nexport interface SettlementExtraCore {\n /** SettlementRouter contract address */\n settlementRouter: string;\n /** Unique salt for idempotency (32 bytes) */\n salt: string;\n /** Final recipient address */\n payTo: string;\n /** Facilitator fee amount */\n facilitatorFee: string;\n /** Hook contract address */\n hook: string;\n /** Encoded hook parameters */\n hookData: string;\n}\n\n/**\n * Settlement extra parameters for PaymentRequirements\n * Includes EIP-712 domain info (name, version) for asset signature validation\n */\nexport interface SettlementExtra extends SettlementExtraCore {\n /** Asset contract name (for EIP-712) */\n name: string;\n /** Asset contract version (for EIP-712) */\n version: string;\n}\n\n/**\n * Error thrown when settlement extra parameters are invalid\n */\nexport class SettlementExtraError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SettlementExtraError\";\n }\n}\n\n/**\n * Additional types for middleware compatibility\n */\n\n// Re-export Network type from @x402/core\nexport type { Network } from \"@x402/core/types\";\n\n/**\n * Money type - string or number representing USD amount\n */\nexport type Money = string | number;\n\n/**\n * Resource information for payment required responses\n */\nexport interface Resource {\n url: string;\n description?: string;\n mimeType?: string;\n}\n\n/**\n * Facilitator configuration for middleware\n */\nexport interface FacilitatorConfig {\n url: string;\n apiKey?: string;\n}\n\n","/**\n * Middleware utility functions for x402x v2 packages\n * \n * These utilities provide helpers for route matching, JSON encoding,\n * and other common middleware operations.\n */\n\n/**\n * Route configuration for payment requirements\n */\nexport interface RouteConfig {\n price: string | number;\n network?: string;\n extra?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Routes configuration - mapping of route patterns to configs\n */\nexport type RoutesConfig = Record<string, RouteConfig | string | number>;\n\n/**\n * Compiled route pattern with regex\n */\nexport interface RoutePattern {\n verb: string;\n pattern: RegExp;\n config: RouteConfig;\n}\n\n/**\n * Compute route patterns from routes config\n * \n * Converts route configuration into compiled patterns with regex matching.\n * \n * **Note**: When a route is specified as a simple price value (string or number),\n * it is automatically converted to a RouteConfig with network defaulting to \"base-sepolia\".\n * For production use, explicitly specify the network in your route configuration.\n * \n * @param routes - Routes configuration\n * @returns Array of route patterns\n * \n * @example\n * ```typescript\n * const routes = {\n * 'GET /api/data': { price: '0.01', network: 'base-sepolia' },\n * '/public/*': '0' // Defaults to base-sepolia network\n * };\n * const patterns = computeRoutePatterns(routes);\n * ```\n */\nexport function computeRoutePatterns(routes: RoutesConfig): RoutePattern[] {\n const normalizedRoutes = Object.fromEntries(\n Object.entries(routes).map(([pattern, value]) => [\n pattern,\n typeof value === \"string\" || typeof value === \"number\"\n ? ({ price: value, network: \"base-sepolia\" } as RouteConfig)\n : (value as RouteConfig),\n ]),\n );\n\n return Object.entries(normalizedRoutes).map(([pattern, routeConfig]) => {\n // Split pattern into verb and path, defaulting to \"*\" for verb if not specified\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n if (!path) {\n throw new Error(`Invalid route pattern: ${pattern}`);\n }\n return {\n verb: verb.toUpperCase(),\n pattern: new RegExp(\n `^${\n path\n // First escape backslashes to prevent regex injection\n .replace(/\\\\/g, \"\\\\\\\\\")\n // Then escape all special regex characters except * and []\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\")\n // Then handle our special pattern characters\n .replace(/\\*/g, \".*?\") // Make wildcard non-greedy\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Convert [param] to regex capture\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n ),\n config: routeConfig,\n };\n });\n}\n\n/**\n * Find matching route for given path and method\n * \n * @param routePatterns - Compiled route patterns\n * @param path - Request path\n * @param method - HTTP method\n * @returns Matching route pattern or undefined\n * \n * @example\n * ```typescript\n * const route = findMatchingRoute(patterns, '/api/data', 'GET');\n * ```\n */\nexport function findMatchingRoute(\n routePatterns: RoutePattern[],\n path: string,\n method: string,\n): RoutePattern | undefined {\n // Normalize the path\n let normalizedPath: string;\n try {\n // First split off query parameters and hash fragments\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n // Then decode the path\n const decodedPath = decodeURIComponent(pathWithoutQuery);\n\n // Normalize the path (just clean up slashes)\n normalizedPath = decodedPath\n .replace(/\\\\/g, \"/\") // replace backslashes\n .replace(/\\/+/g, \"/\") // collapse slashes\n .replace(/(.+?)\\/+$/, \"$1\"); // trim trailing slashes\n } catch {\n // If decoding fails, return undefined\n return undefined;\n }\n\n // Find matching route pattern\n const matchingRoutes = routePatterns.filter(({ pattern, verb }) => {\n const matchesPath = pattern.test(normalizedPath);\n const upperMethod = method.toUpperCase();\n const matchesVerb = verb === \"*\" || upperMethod === verb;\n return matchesPath && matchesVerb;\n });\n\n // Return first matching route (most specific)\n return matchingRoutes[0];\n}\n\n/**\n * Find matching payment requirements from list\n * \n * This is a placeholder for finding requirements that match certain criteria.\n * In v2, this logic is typically handled by the x402Client/x402ResourceServer classes.\n * \n * @param requirements - List of payment requirements\n * @param network - Optional network filter\n * @returns First matching requirement or undefined\n */\nexport function findMatchingPaymentRequirements<T>(\n requirements: T[],\n network?: string,\n): T | undefined {\n // For now, just return the first requirement\n // In a real implementation, this would filter by network, scheme, etc.\n void network; // Mark as intentionally unused\n return requirements[0];\n}\n\n/**\n * Convert value to JSON-safe format\n * \n * Handles BigInt and other non-JSON-serializable types.\n * \n * @param value - Value to convert\n * @returns JSON-safe representation\n * \n * @example\n * ```typescript\n * const safe = toJsonSafe({ amount: 1000000n }); // { amount: \"1000000\" }\n * ```\n */\nexport function toJsonSafe(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n return value.map(toJsonSafe);\n }\n\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = toJsonSafe(val);\n }\n return result;\n }\n\n return value;\n}\n","/**\n * Commitment calculation utilities\n *\n * The commitment hash binds all settlement parameters to the client's signature,\n * preventing parameter tampering attacks.\n */\n\nimport { keccak256, encodePacked, hexToBytes, bytesToHex, type Hex } from \"viem\";\nimport type { CommitmentParams } from \"./types.js\";\n\n/**\n * Calculate commitment hash for x402x settlement\n *\n * This hash becomes the EIP-3009 nonce, cryptographically binding all settlement\n * parameters to the client's signature. The parameter order must exactly match\n * SettlementRouter.sol.\n *\n * @param params - All settlement parameters\n * @returns bytes32 commitment hash\n *\n * @example\n * ```typescript\n * const commitment = calculateCommitment({\n * chainId: 84532,\n * hub: '0x...',\n * asset: '0x...',\n * from: '0x...',\n * value: '100000',\n * validAfter: '0',\n * validBefore: '1234567890',\n * salt: '0x...',\n * payTo: '0x...',\n * facilitatorFee: '10000',\n * hook: '0x...',\n * hookData: '0x',\n * });\n * ```\n */\nexport function calculateCommitment(params: CommitmentParams): string {\n // Pack parameters in exact order as in SettlementRouter.sol\n return keccak256(\n encodePacked(\n [\n \"string\", // Protocol identifier\n \"uint256\", // Chain ID\n \"address\", // Hub address\n \"address\", // Token address\n \"address\", // From (payer)\n \"uint256\", // Value\n \"uint256\", // Valid after\n \"uint256\", // Valid before\n \"bytes32\", // Salt\n \"address\", // Pay to\n \"uint256\", // Facilitator fee\n \"address\", // Hook\n \"bytes32\", // keccak256(hookData)\n ],\n [\n \"X402/settle/v1\",\n BigInt(params.chainId),\n params.hub as Hex,\n params.asset as Hex,\n params.from as Hex,\n BigInt(params.value),\n BigInt(params.validAfter),\n BigInt(params.validBefore),\n params.salt as Hex,\n params.payTo as Hex,\n BigInt(params.facilitatorFee),\n params.hook as Hex,\n keccak256(params.hookData as Hex),\n ],\n ),\n );\n}\n\n/**\n * Generate a random salt for settlement uniqueness\n *\n * Works in both Node.js and browser environments.\n * Uses crypto.getRandomValues (Web Crypto API) which is available in:\n * - Modern browsers\n * - Node.js 15+ (via global crypto)\n * - Older Node.js (via crypto.webcrypto)\n *\n * @returns bytes32 hex string (0x + 64 hex characters)\n *\n * @example\n * ```typescript\n * const salt = generateSalt();\n * // => '0x1234567890abcdef...'\n * ```\n */\nexport function generateSalt(): string {\n // Try to get crypto from global (browser or Node.js 15+)\n const globalCrypto = typeof crypto !== \"undefined\" ? crypto : undefined;\n\n if (globalCrypto?.getRandomValues) {\n // Use Web Crypto API (works in browser and modern Node.js)\n const bytes = new Uint8Array(32);\n globalCrypto.getRandomValues(bytes);\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n }\n\n // Fallback: use Math.random() (less secure, but works everywhere)\n // Note: Salt doesn't require cryptographic security - it's just for uniqueness\n console.warn(\n \"[generateSalt] Using Math.random() fallback - consider upgrading to Node.js 15+ or use in browser\",\n );\n const bytes = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate commitment parameters\n *\n * @param params - Commitment parameters to validate\n * @throws Error if validation fails\n */\nexport function validateCommitmentParams(params: CommitmentParams): void {\n // Validate addresses\n if (!isValidAddress(params.hub)) {\n throw new Error(\"Invalid hub address\");\n }\n if (!isValidAddress(params.asset)) {\n throw new Error(\"Invalid asset address\");\n }\n if (!isValidAddress(params.from)) {\n throw new Error(\"Invalid from address\");\n }\n if (!isValidAddress(params.payTo)) {\n throw new Error(\"Invalid payTo address\");\n }\n if (!isValidAddress(params.hook)) {\n throw new Error(\"Invalid hook address\");\n }\n\n // Validate numeric values\n try {\n BigInt(params.value);\n BigInt(params.validAfter);\n BigInt(params.validBefore);\n BigInt(params.facilitatorFee);\n } catch (e) {\n throw new Error(\"Invalid numeric parameter\");\n }\n\n // Validate bytes32 values\n if (!isValidHex(params.salt) || params.salt.length !== 66) {\n throw new Error(\"Invalid salt: must be bytes32 (0x + 64 hex chars)\");\n }\n\n if (!isValidHex(params.hookData)) {\n throw new Error(\"Invalid hookData: must be hex string\");\n }\n}\n\n/**\n * Check if a string is a valid Ethereum address\n */\nfunction isValidAddress(address: string): boolean {\n return /^0x[0-9a-fA-F]{40}$/.test(address);\n}\n\n/**\n * Check if a string is a valid hex string\n */\nfunction isValidHex(hex: string): boolean {\n return /^0x[0-9a-fA-F]*$/.test(hex);\n}\n","/**\n * Network utility functions for x402x core_v2\n * \n * These utilities provide helpers for working with CAIP-2 network identifiers\n * and accessing network-specific asset information.\n */\n\nimport type { Network } from \"@x402/core/types\";\n\n/**\n * Asset information including EIP-712 domain parameters\n */\nexport interface AssetInfo {\n address: string;\n decimals: number;\n eip712: {\n name: string;\n version: string;\n };\n}\n\n/**\n * Primary mapping from human-readable network names to CAIP-2 identifiers\n * \n * This is the SINGLE SOURCE OF TRUTH for network name mappings.\n * When adding a new network, only update this mapping and the corresponding\n * entries in networks.ts and DEFAULT_ASSETS.\n */\nexport const NETWORK_ALIASES_V1_TO_V2: Record<string, Network> = {\n // V1 human-readable names -> V2 CAIP-2 canonical keys\n \"base-sepolia\": \"eip155:84532\",\n \"x-layer-testnet\": \"eip155:1952\",\n \"skale-base-sepolia\": \"eip155:324705682\",\n \"base\": \"eip155:8453\",\n \"x-layer\": \"eip155:196\",\n \"bsc-testnet\": \"eip155:97\",\n \"bsc\": \"eip155:56\",\n};\n\n/**\n * CAIP-2 network ID to network alias mapping (reverse lookup)\n * \n * Maps CAIP-2 identifiers to v1 configuration aliases (e.g., \"eip155:84532\" → \"base-sepolia\").\n * These aliases are used in configuration files and for backward compatibility.\n * \n * Automatically generated from NETWORK_ALIASES_V1_TO_V2.\n * DO NOT edit this manually - it will be regenerated.\n */\nexport const NETWORK_ALIASES: Record<Network, string> = Object.entries(\n NETWORK_ALIASES_V1_TO_V2\n).reduce((acc, [name, caip2]) => {\n acc[caip2] = name;\n return acc;\n}, {} as Record<Network, string>);\n\n/**\n * Default asset (USDC) configuration per network\n */\nconst DEFAULT_ASSETS: Record<Network, AssetInfo> = {\n \"eip155:84532\": {\n address: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n decimals: 6,\n eip712: {\n name: \"USDC\",\n version: \"2\",\n },\n },\n \"eip155:1952\": {\n address: \"0xcb8bf24c6ce16ad21d707c9505421a17f2bec79d\",\n decimals: 6,\n eip712: {\n name: \"USDC_TEST\",\n version: \"2\",\n },\n },\n \"eip155:324705682\": {\n address: \"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD\",\n decimals: 6,\n eip712: {\n name: \"Bridged USDC (SKALE Bridge)\",\n version: \"2\",\n },\n },\n \"eip155:8453\": {\n address: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n decimals: 6,\n eip712: {\n name: \"USD Coin\",\n version: \"2\",\n },\n },\n \"eip155:196\": {\n address: \"0x74b7f16337b8972027f6196a17a631ac6de26d22\",\n decimals: 6,\n eip712: {\n name: \"USD Coin\",\n version: \"2\",\n },\n },\n \"eip155:97\": {\n address: \"0xdac693b5f14e7ee5923a4830cd2f82ff178f5098\",\n decimals: 18,\n eip712: {\n name: \"x402 Wrapped USDT\",\n version: \"1\",\n },\n },\n \"eip155:56\": {\n address: \"0x2fDb94bAa9D664a1879BEe1f944F5F5d2dad4451\",\n decimals: 18,\n eip712: {\n name: \"x402 Wrapped USDT\",\n version: \"1\",\n },\n },\n};\n\n/**\n * Get network alias from CAIP-2 network ID\n * \n * Returns the v1 configuration alias (e.g., \"base-sepolia\") for a given CAIP-2 identifier.\n * These aliases are used in configuration files and for backward compatibility.\n * \n * @param network - CAIP-2 network identifier (e.g., 'eip155:84532')\n * @returns Network alias (e.g., 'base-sepolia')\n * @throws Error if network ID is not supported\n * \n * @example\n * ```typescript\n * const alias = getNetworkAlias('eip155:84532'); // 'base-sepolia'\n * ```\n */\nexport function getNetworkAlias(network: Network): string {\n const networkAlias = NETWORK_ALIASES[network];\n if (!networkAlias) {\n throw new Error(\n `Unsupported network ID: ${network}. ` +\n `Supported network IDs: ${Object.keys(NETWORK_ALIASES).join(\", \")}`\n );\n }\n return networkAlias;\n}\n\n/**\n * Get default asset (USDC) information for a network\n * \n * @param network - CAIP-2 network identifier (e.g., 'eip155:84532')\n * @returns Asset information including address, decimals, and EIP-712 domain\n * @throws Error if network is not supported\n * \n * @example\n * ```typescript\n * const asset = getDefaultAsset('eip155:84532');\n * // { address: '0x036Cb...', decimals: 6, eip712: { name: 'USDC', version: '2' } }\n * ```\n */\nexport function getDefaultAsset(network: Network): AssetInfo {\n const assetInfo = DEFAULT_ASSETS[network];\n if (!assetInfo) {\n throw new Error(`No default asset configured for network: ${network}`);\n }\n return assetInfo;\n}\n\n/**\n * Parse money value to decimal number\n * \n * Handles various formats:\n * - Dollar sign: '$1.50' -> 1.50\n * - Decimal string: '1.50' -> 1.50\n * - Number: 1.50 -> 1.50\n * \n * @param money - Money value as string or number\n * @returns Decimal number\n * @throws Error if money format is invalid\n * \n * @example\n * ```typescript\n * parseMoneyToDecimal('$1.50'); // 1.50\n * parseMoneyToDecimal('1.50'); // 1.50\n * parseMoneyToDecimal(1.50); // 1.50\n * ```\n */\nexport function parseMoneyToDecimal(money: string | number): number {\n if (typeof money === \"number\") {\n return money;\n }\n\n // Remove $ sign and whitespace, then parse\n const cleanMoney = money.replace(/^\\$/, \"\").trim();\n const amount = parseFloat(cleanMoney);\n\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`);\n }\n\n return amount;\n}\n\n/**\n * Process price to atomic amount for the default asset on a network\n * \n * This function converts various price formats to atomic units (smallest denomination).\n * For USDC with 6 decimals: 1.5 USD -> '1500000'\n * \n * @param price - Price as string or number (in USD, not atomic units)\n * @param network - CAIP-2 network identifier\n * @returns Object with amount as string in atomic units, or error\n * \n * @example\n * ```typescript\n * const result = processPriceToAtomicAmount('1.5', 'eip155:84532');\n * // { amount: '1500000' }\n * ```\n */\nexport function processPriceToAtomicAmount(\n price: string | number,\n network: Network\n): { amount: string } | { error: string } {\n try {\n const amount = parseMoneyToDecimal(price);\n const asset = getDefaultAsset(network);\n const decimals = asset.decimals;\n\n // Convert to smallest unit using integer-only arithmetic to avoid floating-point precision issues\n // Split the amount into whole and fractional parts\n const [whole, fractional = '0'] = amount.toString().split('.');\n const paddedFractional = fractional.padEnd(decimals, '0').slice(0, decimals);\n const atomicAmount = BigInt(whole) * BigInt(10 ** decimals) + BigInt(paddedFractional);\n\n return { amount: atomicAmount.toString() };\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : \"Unknown error processing price\",\n };\n }\n}\n\n/**\n * Get list of all supported network IDs (CAIP-2 identifiers)\n *\n * Returns protocol-level CAIP-2 network identifiers like \"eip155:84532\".\n * Use this for x402 v2 protocol operations and facilitator configuration.\n *\n * @returns Array of CAIP-2 network identifiers\n *\n * @example\n * ```typescript\n * const networkIds = getSupportedNetworkIds();\n * // => ['eip155:84532', 'eip155:8453', 'eip155:1952', ...]\n * \n * // For x402 v2 protocol\n * const facilitator = createFacilitator({\n * networks: getSupportedNetworkIds()\n * });\n * ```\n */\nexport function getSupportedNetworkIds(): Network[] {\n return Object.keys(NETWORK_ALIASES) as Network[];\n}\n\n/**\n * Get the alias mapping from v1 network names to v2 CAIP-2 identifiers\n *\n * @returns Record mapping v1 names to v2 CAIP-2 keys\n *\n * @example\n * ```typescript\n * const aliases = getNetworkAliasesV1ToV2();\n * // => { 'base-sepolia': 'eip155:84532', 'x-layer-testnet': 'eip155:1952', ... }\n * ```\n */\nexport function getNetworkAliasesV1ToV2(): Record<string, Network> {\n return { ...NETWORK_ALIASES_V1_TO_V2 };\n}\n\n/**\n * Convert any network identifier to its canonical v2 CAIP-2 key\n *\n * Handles both v1 human-readable names and v2 CAIP-2 identifiers,\n * returning the canonical v2 CAIP-2 identifier for all inputs.\n *\n * @param network - Network identifier (v1 name or v2 CAIP-2)\n * @returns Canonical v2 CAIP-2 network identifier\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * toCanonicalNetworkKey('base-sepolia'); // 'eip155:84532'\n * toCanonicalNetworkKey('eip155:84532'); // 'eip155:84532'\n * toCanonicalNetworkKey('x-layer'); // 'eip155:196'\n * ```\n */\nexport function toCanonicalNetworkKey(network: string): Network {\n // If it's already a CAIP-2 identifier, validate it\n if (network.startsWith('eip155:')) {\n const canonicalNetwork = network as Network;\n if (canonicalNetwork in NETWORK_ALIASES) {\n return canonicalNetwork;\n }\n throw new Error(\n `Unsupported CAIP-2 network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES).join(\", \")}`\n );\n }\n\n // If it's a v1 name, convert it using the alias map\n const canonicalNetwork = NETWORK_ALIASES_V1_TO_V2[network];\n if (!canonicalNetwork) {\n throw new Error(\n `Unsupported network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES_V1_TO_V2).join(\", \")}`\n );\n }\n return canonicalNetwork;\n}\n","/**\n * Network configuration for x402x\n *\n * Contains deployed contract addresses and configuration for each supported network.\n * Uses official x402 v2 CAIP-2 network identifiers as keys.\n */\n\nimport type { Network } from \"@x402/core/types\";\nimport { getDefaultAsset, NETWORK_ALIASES_V1_TO_V2, getNetworkAlias } from \"./network-utils.js\";\nimport type { NetworkConfig } from \"./types.js\";\n\n/**\n * Helper to get default asset config\n */\nfunction getDefaultAssetConfig(network: Network) {\n const defaultAsset = getDefaultAsset(network);\n return {\n address: defaultAsset.address as string,\n decimals: defaultAsset.decimals,\n eip712: {\n name: defaultAsset.eip712.name,\n version: defaultAsset.eip712.version,\n },\n };\n}\n\n/**\n * Normalize network identifier to CAIP-2 format\n * \n * Accepts both human-readable names (string) and CAIP-2 format (Network type).\n * This enables backward compatibility while supporting the new CAIP-2 standard.\n * \n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns CAIP-2 network identifier\n * @throws Error if network is not supported\n * \n * @example\n * ```typescript\n * normalizeToCAIP2('base-sepolia'); // => 'eip155:84532'\n * normalizeToCAIP2('eip155:84532'); // => 'eip155:84532'\n * ```\n */\nfunction normalizeToCAIP2(network: string | Network): Network {\n // Already CAIP-2 format - validate it's supported\n if (network.startsWith('eip155:')) {\n const caip2 = network as Network;\n // Check if this CAIP-2 identifier is in our supported networks\n if (!(caip2 in networks)) {\n throw new Error(\n `Unsupported CAIP-2 network: ${network}. ` +\n `Supported networks: ${Object.keys(networks).join(\", \")}`\n );\n }\n return caip2;\n }\n // Convert from human-readable name using alias mapping\n const caip2 = NETWORK_ALIASES_V1_TO_V2[network];\n if (!caip2) {\n throw new Error(\n `Unknown network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES_V1_TO_V2).join(\", \")}`\n );\n }\n return caip2;\n}\n\n/**\n * Network configurations for all supported networks\n *\n * Uses CAIP-2 format as keys for consistency with x402 v2 protocol.\n * This ensures compatibility across different ecosystems and simplifies\n * adding new networks (only need chain ID).\n */\nexport const networks: Record<Network, NetworkConfig> = {\n \"eip155:84532\": {\n chainId: 84532,\n name: \"Base Sepolia\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://sepolia.basescan.org/address/\",\n txExplorerBaseUrl: \"https://sepolia.basescan.org/tx/\",\n settlementRouter: \"0x817e4f0ee2fbdaac426f1178e149f7dc98873ecb\",\n defaultAsset: getDefaultAssetConfig(\"eip155:84532\"),\n hooks: {\n transfer: \"0x4DE234059C6CcC94B8fE1eb1BD24804794083569\",\n },\n demoHooks: {\n nftMint: \"0x261206558E6eEd104Cba4AD913b2Eec85D21108e\",\n randomNFT: \"0x5756A67a33118F5Ad9840411f252E14d84Dd7c02\",\n reward: \"0xf05cE06e7ee4ffCb67a509003DbD73A6d95Cc960\",\n rewardToken: \"0xb6854e33BfD428d15B4f5398cFf8e84d4196FDA6\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"ETH\",\n },\n },\n \"eip155:1952\": {\n chainId: 1952,\n name: \"X Layer Testnet\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://www.oklink.com/xlayer-test/address/\",\n txExplorerBaseUrl: \"https://www.oklink.com/xlayer-test/tx/\",\n settlementRouter: \"0xba9980fb08771e2fd10c17450f52d39bcb9ed576\",\n defaultAsset: getDefaultAssetConfig(\"eip155:1952\"),\n hooks: {\n transfer: \"0xD4b98dd614c1Ea472fC4547a5d2B93f3D3637BEE\",\n },\n demoHooks: {\n nftMint: \"0x468F666314b070338841422012AB2f6539bfcE48\",\n randomNFT: \"0xBA931bB5B2F2DC5354aFAED1d3996B0c6e417518\",\n reward: \"0xda8B270Ec442Ff797807b95604E3319e36Aad05d\",\n rewardToken: \"0x348AFDE3B4B70dCb02053aF95588a4ab41e95FbC\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"OKB\",\n },\n },\n \"eip155:324705682\": {\n chainId: 324705682,\n name: \"SKALE Base Sepolia\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://base-sepolia-testnet-explorer.skalenodes.com/address/\",\n txExplorerBaseUrl: \"https://base-sepolia-testnet-explorer.skalenodes.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(\"eip155:324705682\"),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659cd5494e69852be8d9d23fe05aab14b29b\",\n randomNFT: \"0x081258287f692d61575387ee2a4075f34dd7aef7\",\n reward: \"0xc20634ea518985901e32fbc1ba27fa673d37601a\",\n rewardToken: \"0x9fc2c199170b039f093abcd54008038f0c0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"Credits\",\n },\n },\n \"eip155:97\": {\n chainId: 97,\n name: \"BSC Testnet\",\n type: \"testnet\",\n addressExplorerBaseUrl: \"https://testnet.bscscan.com/address/\",\n txExplorerBaseUrl: \"https://testnet.bscscan.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(\"eip155:97\"),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n randomNFT: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n reward: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n rewardToken: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"BNB\",\n },\n },\n // Mainnet configurations\n \"eip155:8453\": {\n chainId: 8453,\n name: \"Base Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://basescan.org/address/\",\n txExplorerBaseUrl: \"https://basescan.org/tx/\",\n settlementRouter: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n defaultAsset: getDefaultAssetConfig(\"eip155:8453\"),\n hooks: {\n transfer: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n },\n demoHooks: {\n nftMint: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n randomNFT: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n reward: \"0x4B566FD5eFf76e3BdF20Ca5c3F2FA7cdbb3bD99A\",\n rewardToken: \"0x12d41108f9F12064f792418C9BA0ACF6EdcE7790\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"ETH\",\n },\n },\n \"eip155:196\": {\n chainId: 196,\n name: \"X Layer Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://www.oklink.com/xlayer/address/\",\n txExplorerBaseUrl: \"https://www.oklink.com/xlayer/tx/\",\n settlementRouter: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n defaultAsset: getDefaultAssetConfig(\"eip155:196\"),\n hooks: {\n transfer: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n },\n demoHooks: {\n nftMint: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n randomNFT: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n reward: \"0x4B566FD5eFf76e3BdF20Ca5c3F2FA7cdbb3bD99A\",\n rewardToken: \"0x12d41108f9F12064f792418C9BA0ACF6EdcE7790\",\n },\n metadata: {\n gasModel: \"eip1559\",\n nativeToken: \"OKB\",\n },\n },\n \"eip155:56\": {\n chainId: 56,\n name: \"BSC Mainnet\",\n type: \"mainnet\",\n addressExplorerBaseUrl: \"https://bscscan.com/address/\",\n txExplorerBaseUrl: \"https://bscscan.com/tx/\",\n settlementRouter: \"0x1Ae0E196dC18355aF3a19985faf67354213F833D\",\n defaultAsset: getDefaultAssetConfig(\"eip155:56\"),\n hooks: {\n transfer: \"0x2f05fe5674aE756E25C26855258B4877E9e021Fd\",\n },\n demoHooks: {\n nftMint: \"0x73fc659Cd5494E69852bE8D9D23FE05Aab14b29B\",\n randomNFT: \"0x081258287F692D61575387ee2a4075f34dd7Aef7\",\n reward: \"0xC20634ea518985901e32Fbc1bA27fa673D37601A\",\n rewardToken: \"0x9Fc2c199170B039f093ABCd54008038F0C0a31d6\",\n },\n metadata: {\n gasModel: \"legacy\",\n nativeToken: \"BNB\",\n },\n },\n};\n\n/**\n * Get network configuration by network identifier\n *\n * Accepts both CAIP-2 format (preferred) and human-readable network names (legacy).\n * This provides backward compatibility while encouraging migration to CAIP-2.\n *\n * @param network - Network identifier, accepts either:\n * - CAIP-2 format (preferred): 'eip155:84532', 'eip155:8453'\n * - Human-readable name (legacy): 'base-sepolia', 'base'\n * @returns Network configuration\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * // Preferred: CAIP-2 format\n * const config = getNetworkConfig('eip155:84532');\n * \n * // Legacy: human-readable name\n * const config2 = getNetworkConfig('base-sepolia');\n * \n * console.log(config.settlementRouter);\n * ```\n */\nexport function getNetworkConfig(network: string | Network): NetworkConfig {\n const caip2Network = normalizeToCAIP2(network);\n const config = networks[caip2Network];\n if (!config) {\n throw new Error(\n `Unsupported network: ${network}. ` +\n `Supported networks: ${Object.keys(networks).join(\", \")}`,\n );\n }\n return config;\n}\n\n/**\n * Check if a network is supported\n *\n * Accepts both CAIP-2 format and human-readable network names.\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns True if network is supported\n *\n * @example\n * ```typescript\n * if (isNetworkSupported('eip155:84532')) {\n * // proceed...\n * }\n * \n * if (isNetworkSupported('base-sepolia')) {\n * // also works...\n * }\n * ```\n */\nexport function isNetworkSupported(network: string | Network): boolean {\n try {\n const caip2Network = normalizeToCAIP2(network);\n return caip2Network in networks;\n } catch {\n return false;\n }\n}\n\n/**\n * Get list of all supported network aliases (v1 configuration names)\n *\n * Returns user-friendly network aliases like \"base-sepolia\", \"base\", etc.\n * These aliases are used for configuration files and backward compatibility.\n * Use this for UI display, configuration, and user-facing operations.\n * \n * This function provides backward compatibility by returning v1 aliases\n * even though the internal storage uses CAIP-2 format.\n *\n * @returns Array of v1 network aliases\n *\n * @example\n * ```typescript\n * const aliases = getSupportedNetworkAliases();\n * // => ['base-sepolia', 'base', 'x-layer-testnet', ...]\n * \n * // For UI dropdown\n * <select>\n * {aliases.map(alias => <option key={alias}>{alias}</option>)}\n * </select>\n * ```\n */\nexport function getSupportedNetworkAliases(): string[] {\n // Convert CAIP-2 keys to v1 aliases using reverse mapping\n return Object.keys(networks).map(caip2 => getNetworkAlias(caip2 as Network));\n}\n\n/**\n * Get list of all supported networks (CAIP-2 format)\n *\n * Returns network identifiers in CAIP-2 format (e.g., \"eip155:84532\").\n * This is the canonical format used internally and in x402 v2.\n *\n * @returns Array of CAIP-2 network identifiers\n *\n * @example\n * ```typescript\n * const networks = getSupportedNetworks();\n * // => ['eip155:84532', 'eip155:8453', 'eip155:1952', ...]\n * ```\n */\nexport function getSupportedNetworks(): Network[] {\n return Object.keys(networks) as Network[];\n}\n","/**\n * Chain definitions for x402x supported networks\n * \n * This module provides viem chain configurations for all supported networks,\n * including custom definitions for chains not in viem's standard list.\n */\n\nimport { defineChain, type Chain } from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport type { Network } from \"@x402/core/types\";\nimport { NETWORK_ALIASES_V1_TO_V2, NETWORK_ALIASES } from \"./network-utils.js\";\n\n/**\n * Custom chain definitions for networks not in viem's standard list\n */\nconst customChains: Record<number, Chain> = {\n // X Layer Testnet\n 1952: defineChain({\n id: 1952,\n name: \"X Layer Testnet\",\n nativeCurrency: { name: \"OKB\", symbol: \"OKB\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://testrpc.xlayer.tech\"] },\n },\n blockExplorers: {\n default: { name: \"OKLink\", url: \"https://www.oklink.com/xlayer-test\" },\n },\n testnet: true,\n }),\n\n // SKALE Nebula Testnet (Base Sepolia)\n 324705682: defineChain({\n id: 324705682,\n name: \"SKALE Nebula Testnet\",\n nativeCurrency: { name: \"sFUEL\", symbol: \"sFUEL\", decimals: 18 },\n rpcUrls: {\n default: {\n http: [\"https://testnet.skalenodes.com/v1/lanky-ill-funny-testnet\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"SKALE Explorer\",\n url: \"https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com\",\n },\n },\n testnet: true,\n }),\n\n // X Layer Mainnet\n 196: defineChain({\n id: 196,\n name: \"X Layer\",\n nativeCurrency: { name: \"OKB\", symbol: \"OKB\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://rpc.xlayer.tech\"] },\n },\n blockExplorers: {\n default: { name: \"OKLink\", url: \"https://www.oklink.com/xlayer\" },\n },\n testnet: false,\n }),\n};\n\n/**\n * Get viem chain configuration for a network\n * \n * Accepts both CAIP-2 format (preferred) and human-readable network names (legacy).\n * Checks custom chains first, then falls back to viem's standard chains.\n * \n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns Viem chain configuration\n * @throws Error if network is not supported\n * \n * @example\n * ```typescript\n * // Preferred: CAIP-2 format\n * const chain = getChain(\"eip155:1952\");\n * // => { id: 1952, name: \"X Layer Testnet\", ... }\n * \n * // Legacy: human-readable name\n * const baseChain = getChain(\"base-sepolia\");\n * // => { id: 84532, name: \"Base Sepolia\", ... }\n * ```\n */\nexport function getChain(network: string | Network): Chain {\n let chainId: number;\n \n // If already CAIP-2 format, validate it's supported before extracting chainId\n if (network.startsWith('eip155:')) {\n const caip2 = network as Network;\n // Validate that this CAIP-2 identifier is in our supported networks\n if (!(caip2 in NETWORK_ALIASES)) {\n throw new Error(\n `Unsupported CAIP-2 network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES).join(\", \")}`\n );\n }\n chainId = parseInt(network.split(\":\")[1]);\n } else {\n // Convert name to CAIP-2, then extract chainId\n const caip2 = NETWORK_ALIASES_V1_TO_V2[network];\n if (!caip2) {\n throw new Error(\n `Unknown network: ${network}. ` +\n `Supported networks: ${Object.keys(NETWORK_ALIASES_V1_TO_V2).join(\", \")}`\n );\n }\n chainId = parseInt(caip2.split(\":\")[1]);\n }\n\n // Check custom chains first\n if (customChains[chainId]) {\n return customChains[chainId];\n }\n\n // Then check viem's standard chains\n const chain = Object.values(allChains).find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(\n `Unsupported chain ID: ${chainId}. ` +\n `Please add custom chain definition in chains.ts`\n );\n }\n return chain;\n}\n\n/**\n * Get viem chain configuration by chain ID\n * \n * @param chainId - Chain ID\n * @returns Viem chain configuration\n * @throws Error if chain ID is not supported\n * \n * @example\n * ```typescript\n * const chain = getChainById(1952);\n * // => { id: 1952, name: \"X Layer Testnet\", ... }\n * ```\n */\nexport function getChainById(chainId: number): Chain {\n // Check custom chains first\n if (customChains[chainId]) {\n return customChains[chainId];\n }\n\n // Then check viem's standard chains\n const chain = Object.values(allChains).find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(\n `Unsupported chain ID: ${chainId}. ` +\n `Please add custom chain definition in chains.ts`\n );\n }\n return chain;\n}\n\n/**\n * Get all custom chain definitions\n * \n * @returns Record of chain ID to chain configuration\n * \n * @example\n * ```typescript\n * const customs = getCustomChains();\n * // => { 1952: { id: 1952, name: \"X Layer Testnet\", ... }, ... }\n * ```\n */\nexport function getCustomChains(): Record<number, Chain> {\n return { ...customChains };\n}\n\n/**\n * Check if a chain ID has a custom definition\n * \n * @param chainId - Chain ID to check\n * @returns True if chain has custom definition\n * \n * @example\n * ```typescript\n * isCustomChain(1952); // true (X Layer Testnet)\n * isCustomChain(84532); // false (Base Sepolia - in viem)\n * ```\n */\nexport function isCustomChain(chainId: number): boolean {\n return chainId in customChains;\n}\n\n","/**\n * TransferHook utilities\n *\n * TransferHook is a builtin hook that supports two modes:\n * 1. Simple Transfer: Direct transfer to a single recipient (data = '0x')\n * 2. Distributed Transfer: Split transfer to multiple recipients by percentage\n */\n\nimport { encodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { Network } from \"@x402/core/types\";\nimport { getNetworkConfig } from \"../networks.js\";\n\n/**\n * Split configuration for distributed transfer\n */\nexport interface Split {\n /** Recipient address */\n recipient: Address;\n /** Basis points (1-10000, where 10000 = 100%, 1 = 0.01%) */\n bips: number;\n}\n\n/**\n * TransferHook utilities namespace\n */\nexport namespace TransferHook {\n /**\n * Encode hookData for TransferHook\n *\n * Supports two modes:\n *\n * **Mode 1 - Simple Transfer** (no parameters):\n * - Transfers entire amount to the `recipient` address in ExecuteParams\n * - Most gas efficient\n * - Returns '0x'\n *\n * **Mode 2 - Distributed Transfer** (with splits):\n * - Distributes amount to multiple recipients based on percentage (bips)\n * - Each split specifies recipient address and basis points (1-10000)\n * - If total bips < 10000, remaining goes to the `recipient` in ExecuteParams\n * - If total bips = 10000, `recipient` receives nothing\n *\n * @param splits - Optional array of split configurations\n * @returns Encoded hookData as hex string\n * @throws Error if validation fails (invalid addresses, bips > 10000, etc.)\n *\n * @example Simple transfer\n * ```typescript\n * // All amount goes to recipient\n * const hookData = TransferHook.encode();\n * // => '0x'\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xAlice...' // Alice receives 100%\n * });\n * ```\n *\n * @example Distributed transfer - full split\n * ```typescript\n * // Split between Alice (60%) and Bob (40%)\n * const hookData = TransferHook.encode([\n * { recipient: '0xAlice...', bips: 6000 }, // 60%\n * { recipient: '0xBob...', bips: 4000 } // 40%\n * ]);\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xCharity...' // Charity receives 0% (total = 100%)\n * });\n * ```\n *\n * @example Distributed transfer - partial split\n * ```typescript\n * // Platform takes 30%, creator gets the rest\n * const hookData = TransferHook.encode([\n * { recipient: '0xPlatform...', bips: 3000 } // 30%\n * ]);\n *\n * await client.execute({\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData,\n * amount: '100',\n * recipient: '0xCreator...' // Creator receives 70%\n * });\n * ```\n */\n export function encode(splits?: Split[]): string {\n // Mode 1: Simple Transfer\n if (!splits || splits.length === 0) {\n return \"0x\";\n }\n\n // Mode 2: Distributed Transfer - Validate splits\n let totalBips = 0;\n for (const split of splits) {\n // Validate recipient\n if (!split.recipient || split.recipient === \"0x0000000000000000000000000000000000000000\") {\n throw new Error(`Invalid recipient address: ${split.recipient}`);\n }\n\n // Validate bips\n if (split.bips <= 0) {\n throw new Error(`Bips must be greater than 0, got: ${split.bips}`);\n }\n if (split.bips > 10000) {\n throw new Error(`Individual bips cannot exceed 10000, got: ${split.bips}`);\n }\n\n totalBips += split.bips;\n }\n\n // Validate total bips\n if (totalBips > 10000) {\n throw new Error(`Total bips (${totalBips}) exceeds 10000 (100%)`);\n }\n\n // Encode as tuple(address,uint16)[]\n // viem requires component definitions for tuple types\n return encodeAbiParameters(\n [\n {\n type: \"tuple[]\",\n name: \"splits\",\n components: [\n { name: \"recipient\", type: \"address\" },\n { name: \"bips\", type: \"uint16\" },\n ],\n },\n ],\n [splits.map((s) => ({ recipient: s.recipient, bips: s.bips }))],\n );\n }\n\n /**\n * Get TransferHook address for a specific network\n *\n * Accepts both CAIP-2 format (preferred) and human-readable network names (legacy).\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns TransferHook contract address\n * @throws Error if network is not supported\n *\n * @example\n * ```typescript\n * // Preferred: CAIP-2 format\n * const address = TransferHook.getAddress('eip155:84532');\n * // => '0x4DE234059C6CcC94B8fE1eb1BD24804794083569'\n * \n * // Legacy: human-readable name\n * const address2 = TransferHook.getAddress('base-sepolia');\n * // => '0x4DE234059C6CcC94B8fE1eb1BD24804794083569'\n * ```\n */\n export function getAddress(network: string | Network): string {\n const config = getNetworkConfig(network);\n return config.hooks.transfer;\n }\n}\n","/**\n * Demo hooks utilities for showcase examples\n *\n * Provides encoding/decoding and address lookup for demo hooks used in showcase examples.\n * These hooks are optional and may not be deployed on all networks.\n */\n\nimport { encodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { Network } from \"@x402/core/types\";\nimport { getNetworkConfig } from \"../networks.js\";\n\n/**\n * NFT Mint Configuration\n */\nexport interface MintConfig {\n /** Address of the NFT contract to mint from */\n nftContract: Address;\n}\n\n/**\n * Reward Hook Configuration\n */\nexport interface RewardConfig {\n /** Address of the ERC20 reward token contract */\n rewardToken: Address;\n}\n\n/**\n * NFTMintHook utilities for showcase examples\n */\nexport namespace NFTMintHook {\n /**\n * Get NFTMintHook contract address for a specific network\n *\n * Accepts both CAIP-2 format and human-readable network names.\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns The contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getAddress(network: string | Network): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.nftMint) {\n throw new Error(\n `NFTMintHook not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.nftMint as `0x${string}`;\n }\n\n /**\n * Get the NFT contract address for a specific network\n *\n * This is the address of the ERC721 contract that will be minted from.\n * Accepts both CAIP-2 format and human-readable network names.\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns The NFT contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getNFTContractAddress(network: string | Network): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.randomNFT) {\n throw new Error(\n `RandomNFT contract not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.randomNFT as `0x${string}`;\n }\n\n /**\n * Encode MintConfig into hookData for NFTMintHook\n *\n * The NFTMintHook contract expects a specific ABI-encoded struct format.\n * This method handles the encoding for you.\n *\n * @param config - The mint configuration\n * @returns ABI-encoded hookData ready to use with x402x execute\n */\n export function encode(config: MintConfig): `0x${string}` {\n // Encode as tuple matching the Solidity struct:\n // struct MintConfig {\n // address nftContract;\n // }\n return encodeAbiParameters(\n [\n {\n type: \"tuple\",\n components: [{ name: \"nftContract\", type: \"address\" }],\n },\n ],\n [\n {\n nftContract: config.nftContract,\n },\n ],\n );\n }\n}\n\n/**\n * RewardHook utilities for showcase examples\n */\nexport namespace RewardHook {\n /**\n * Get RewardHook contract address for a specific network\n *\n * Accepts both CAIP-2 format and human-readable network names.\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns The contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getAddress(network: string | Network): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.reward) {\n throw new Error(\n `RewardHook not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.reward as `0x${string}`;\n }\n\n /**\n * Get the reward token (ERC20) address for a specific network\n *\n * This is the address of the ERC20 contract that will be distributed as rewards.\n * Accepts both CAIP-2 format and human-readable network names.\n *\n * @param network - Network identifier (CAIP-2 or human-readable name)\n * @returns The reward token contract address for the specified network\n * @throws Error if demo hooks are not configured for the network\n */\n export function getTokenAddress(network: string | Network): `0x${string}` {\n const config = getNetworkConfig(network);\n if (!config.demoHooks?.rewardToken) {\n throw new Error(\n `Reward token not configured for network \"${network}\". Demo hooks are optional and may not be deployed on all networks.`,\n );\n }\n return config.demoHooks.rewardToken as `0x${string}`;\n }\n\n /**\n * Encode RewardConfig into hookData for RewardHook\n *\n * The RewardHook contract expects a specific ABI-encoded struct format.\n * This method handles the encoding for you.\n *\n * @param config - The reward configuration\n * @returns ABI-encoded hookData ready to use with x402x execute\n */\n export function encode(config: RewardConfig): `0x${string}` {\n // Encode as tuple matching the Solidity struct:\n // struct RewardConfig {\n // address rewardToken;\n // }\n return encodeAbiParameters(\n [\n {\n type: \"tuple\",\n components: [{ name: \"rewardToken\", type: \"address\" }],\n },\n ],\n [\n {\n rewardToken: config.rewardToken,\n },\n ],\n );\n }\n}\n","/**\n * Validation helpers for PaymentRequirements.extra (settlement parameters)\n */\n\nimport type { SettlementExtra } from \"./types.js\";\nimport { SettlementExtraError } from \"./types.js\";\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /** Whether the validation passed */\n valid: boolean;\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Validate Ethereum address format (0x followed by 40 hex characters)\n * \n * @param address - Address to validate\n * @returns true if valid Ethereum address\n */\nexport function isValidAddress(address: string): boolean {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Validate hex string format (0x followed by even number of hex characters)\n * \n * @param hex - Hex string to validate\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n return /^0x[a-fA-F0-9]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Validate 32-byte hex string (0x followed by 64 hex characters)\n * \n * @param hex - Hex string to validate\n * @returns true if valid 32-byte hex string\n */\nexport function isValid32ByteHex(hex: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(hex);\n}\n\n/**\n * Validate numeric string (non-negative integer)\n * \n * @param value - Value to validate\n * @returns true if valid numeric string\n */\nexport function isValidNumericString(value: string): boolean {\n return /^\\d+$/.test(value);\n}\n\n/**\n * Validate settlement extra parameters\n * \n * This validates all required fields for settlement through SettlementRouter.\n * \n * @param extra - Settlement extra parameters to validate\n * @returns Validation result with error message if invalid\n * \n * @example\n * ```typescript\n * const result = validateSettlementExtra({\n * settlementRouter: \"0x1234...\",\n * payTo: \"0x5678...\",\n * facilitatorFee: \"10000\",\n * hook: \"0xabcd...\",\n * hookData: \"0x\",\n * name: \"USDC\",\n * version: \"2\",\n * salt: \"0x1234...\"\n * });\n * \n * if (!result.valid) {\n * throw new Error(result.error);\n * }\n * ```\n */\nexport function validateSettlementExtra(\n extra: Partial<SettlementExtra>\n): ValidationResult {\n // Validate settlementRouter\n if (!extra.settlementRouter) {\n return { valid: false, error: \"settlementRouter is required\" };\n }\n if (!isValidAddress(extra.settlementRouter)) {\n return { valid: false, error: \"settlementRouter must be a valid Ethereum address\" };\n }\n\n // Validate payTo\n if (!extra.payTo) {\n return { valid: false, error: \"payTo is required\" };\n }\n if (!isValidAddress(extra.payTo)) {\n return { valid: false, error: \"payTo must be a valid Ethereum address\" };\n }\n\n // Validate facilitatorFee\n if (extra.facilitatorFee === undefined || extra.facilitatorFee === null) {\n return { valid: false, error: \"facilitatorFee is required\" };\n }\n if (!isValidNumericString(extra.facilitatorFee)) {\n return { valid: false, error: \"facilitatorFee must be a non-negative numeric string\" };\n }\n\n // Validate hook\n if (!extra.hook) {\n return { valid: false, error: \"hook is required\" };\n }\n if (!isValidAddress(extra.hook)) {\n return { valid: false, error: \"hook must be a valid Ethereum address\" };\n }\n\n // Validate hookData\n if (extra.hookData === undefined || extra.hookData === null) {\n return { valid: false, error: \"hookData is required\" };\n }\n if (!isValidHex(extra.hookData)) {\n return { valid: false, error: \"hookData must be a valid hex string\" };\n }\n\n // Validate name (EIP-712 domain)\n if (!extra.name) {\n return { valid: false, error: \"name is required (EIP-712 domain name)\" };\n }\n if (typeof extra.name !== \"string\" || extra.name.trim().length === 0) {\n return { valid: false, error: \"name must be a non-empty string\" };\n }\n\n // Validate version (EIP-712 domain)\n if (!extra.version) {\n return { valid: false, error: \"version is required (EIP-712 domain version)\" };\n }\n if (typeof extra.version !== \"string\" || extra.version.trim().length === 0) {\n return { valid: false, error: \"version must be a non-empty string\" };\n }\n\n // Validate salt\n if (!extra.salt) {\n return { valid: false, error: \"salt is required\" };\n }\n if (!isValid32ByteHex(extra.salt)) {\n return { valid: false, error: \"salt must be a 32-byte hex string (0x followed by 64 hex characters)\" };\n }\n\n return { valid: true };\n}\n\n/**\n * Assert that settlement extra parameters are valid\n * Throws SettlementExtraError if validation fails\n * \n * @param extra - Settlement extra parameters to validate\n * @throws {SettlementExtraError} If validation fails\n * \n * @example\n * ```typescript\n * try {\n * assertValidSettlementExtra(extra);\n * // Extra is valid, proceed with settlement\n * } catch (error) {\n * console.error(\"Invalid settlement extra:\", error.message);\n * }\n * ```\n */\nexport function assertValidSettlementExtra(\n extra: Partial<SettlementExtra>\n): asserts extra is SettlementExtra {\n const result = validateSettlementExtra(extra);\n if (!result.valid) {\n throw new SettlementExtraError(result.error || \"Invalid settlement extra\");\n }\n}\n","/**\n * Utility functions for x402x\n */\n\nimport type { PaymentRequirements, SettlementExtra } from \"./types.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { generateSalt } from \"./commitment.js\";\nimport { assertValidSettlementExtra } from \"./validation.js\";\nimport { getNetworkAlias } from \"./network-utils.js\";\n\n/**\n * Add settlement extension to PaymentRequirements\n *\n * This function enriches standard x402 PaymentRequirements with settlement-specific\n * parameters in the `extra` field.\n *\n * @param requirements - Base PaymentRequirements (standard x402)\n * @param params - Settlement parameters\n * @returns Enhanced PaymentRequirements with settlement extra\n *\n * @example\n * ```typescript\n * import { addSettlementExtra, TransferHook, getNetworkConfig } from '@x402x/core';\n *\n * const baseRequirements = {\n * scheme: 'exact',\n * network: 'base-sepolia',\n * maxAmountRequired: '100000',\n * asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n * payTo: '0x...',\n * resource: '/api/payment',\n * };\n *\n * const requirements = addSettlementExtra(baseRequirements, {\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData: TransferHook.encode(),\n * facilitatorFee: '10000',\n * payTo: merchantAddress,\n * });\n * ```\n */\nexport function addSettlementExtra(\n requirements: PaymentRequirements,\n params: {\n hook: string;\n hookData: string;\n facilitatorFee?: string;\n payTo?: string;\n salt?: string;\n },\n): PaymentRequirements {\n // Convert CAIP-2 network ID to friendly name for config lookup\n const networkAlias = getNetworkAlias(requirements.network);\n const config = getNetworkConfig(networkAlias);\n\n // Preserve existing name/version from requirements.extra if they exist (from x402 official middleware)\n // Only use config values as fallback\n const existingExtra = requirements.extra || {};\n const name = (existingExtra.name as string) || config.defaultAsset.eip712.name;\n const version = (existingExtra.version as string) || config.defaultAsset.eip712.version;\n\n const extra: SettlementExtra = {\n // Asset EIP-712 domain info (preserve existing if available)\n name,\n version,\n // Settlement parameters\n settlementRouter: config.settlementRouter,\n salt: params.salt || generateSalt(),\n payTo: params.payTo || requirements.payTo,\n facilitatorFee: params.facilitatorFee || \"0\",\n hook: params.hook,\n hookData: params.hookData,\n };\n\n // Validate the settlement extra parameters\n assertValidSettlementExtra(extra);\n\n return {\n ...requirements,\n // Override payTo to point to SettlementRouter\n payTo: config.settlementRouter,\n extra: {\n ...requirements.extra,\n ...extra,\n },\n };\n}\n","/**\n * Extension helpers for x402x\n * Implements x402x-router-settlement extension for PaymentRequired.extensions\n */\n\n/**\n * Router settlement extension info\n * Contains all settlement-specific parameters that were previously in extra\n */\nexport interface RouterSettlementExtensionInfo {\n /** Schema version for the extension */\n schemaVersion: number;\n /** Optional description of the extension */\n description?: string;\n /** Unique salt for idempotency (32 bytes hex, dynamically generated) */\n salt?: string;\n /** Settlement router contract address */\n settlementRouter?: string;\n /** Hook contract address */\n hook?: string;\n /** Encoded hook parameters (hex string) */\n hookData?: string;\n /** Final recipient address (renamed from payTo to avoid confusion with accepts[].payTo) */\n finalPayTo?: string;\n /** Facilitator fee amount in token's smallest unit */\n facilitatorFee?: string;\n}\n\n/**\n * Router settlement extension structure\n * Location: PaymentRequired.extensions[\"x402x-router-settlement\"]\n */\nexport interface RouterSettlementExtension {\n /** Extension information */\n info: RouterSettlementExtensionInfo;\n /** Optional JSON schema for validation */\n schema?: Record<string, unknown>;\n}\n\n/**\n * Create x402x-router-settlement extension declaration\n * \n * This extension informs clients that the server supports router settlement functionality.\n * Clients MUST echo extensions in their payment payload.\n * \n * @param params - Extension parameters\n * @param params.description - Optional description of the extension\n * @param params.schema - Optional JSON schema for validation\n * @param params.salt - Optional salt (will be auto-generated by enrichDeclaration if not provided)\n * @param params.settlementRouter - Settlement router contract address\n * @param params.hook - Hook contract address\n * @param params.hookData - Encoded hook parameters\n * @param params.finalPayTo - Final recipient address\n * @param params.facilitatorFee - Facilitator fee amount\n * @returns Extension object for PaymentRequired.extensions[\"x402x-router-settlement\"]\n * \n * @example\n * ```typescript\n * const extension = createRouterSettlementExtension({\n * description: \"Settlement router with atomic fee distribution\",\n * settlementRouter: \"0x...\",\n * hook: \"0x...\",\n * hookData: \"0x\",\n * finalPayTo: \"0x...\",\n * facilitatorFee: \"0\",\n * salt: \"0x...\" // Optional, will be auto-generated if not provided\n * });\n * \n * const paymentRequired = {\n * x402Version: 2,\n * resource: { url: \"/api/payment\", ... },\n * accepts: [...],\n * extensions: {\n * \"x402x-router-settlement\": extension\n * }\n * };\n * ```\n */\nexport function createRouterSettlementExtension(\n params?: {\n description?: string;\n schema?: Record<string, unknown>;\n salt?: string; // Optional salt, will be auto-generated if not provided\n settlementRouter?: string;\n hook?: string;\n hookData?: string;\n finalPayTo?: string;\n facilitatorFee?: string;\n }\n): RouterSettlementExtension {\n const info: RouterSettlementExtensionInfo = {\n schemaVersion: 1,\n };\n\n // Add optional fields\n if (params?.description !== undefined) {\n info.description = params.description;\n }\n\n // Add salt if explicitly provided (otherwise enrichDeclaration will generate it)\n if (params?.salt) {\n info.salt = params.salt;\n }\n\n // Add settlement parameters if provided\n if (params?.settlementRouter) info.settlementRouter = params.settlementRouter;\n if (params?.hook) info.hook = params.hook;\n if (params?.hookData) info.hookData = params.hookData;\n if (params?.finalPayTo) info.finalPayTo = params.finalPayTo;\n // Only add facilitatorFee if explicitly provided (undefined = let facilitator calculate)\n if (params?.facilitatorFee !== undefined) info.facilitatorFee = params.facilitatorFee;\n\n // Create schema if not provided but we have settlement params\n let schema = params?.schema;\n if (!schema && params?.settlementRouter) {\n schema = {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"number\" },\n description: { type: \"string\" },\n salt: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{64}$\" },\n settlementRouter: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n hook: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n hookData: { type: \"string\", pattern: \"^0x[a-fA-F0-9]*$\" },\n finalPayTo: { type: \"string\", pattern: \"^0x[a-fA-F0-9]{40}$\" },\n facilitatorFee: { type: \"string\" },\n },\n // Salt is required in the final enriched version\n // facilitatorFee is optional (facilitator will calculate if missing)\n required: [\"schemaVersion\", \"salt\", \"settlementRouter\", \"hook\", \"hookData\", \"finalPayTo\"],\n };\n }\n\n return {\n info,\n ...(schema !== undefined && { schema }),\n };\n}\n\n/**\n * Get the extension key for router settlement\n * \n * @returns The extension key \"x402x-router-settlement\"\n */\nexport function getRouterSettlementExtensionKey(): string {\n return \"x402x-router-settlement\";\n}\n","/**\n * x402x Router Settlement Server Extension\n * \n * Implements ResourceServerExtension interface to integrate router settlement\n * functionality into x402 v2 resource servers.\n */\n\nimport type { ResourceServerExtension } from \"@x402/core/types\";\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport { createRouterSettlementExtension } from \"./extensions.js\";\nimport { generateSalt } from \"./commitment.js\";\n\n/**\n * Extension key constant\n */\nexport const ROUTER_SETTLEMENT_KEY = \"x402x-router-settlement\";\n\n/**\n * Type guard to check if context is an HTTP request context.\n * \n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is { method?: string; adapter?: unknown } {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx;\n}\n\n/**\n * Router settlement extension declaration type\n */\ninterface RouterSettlementDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n schemaVersion?: number;\n description?: string;\n /** Dynamic fields that need to be generated per-request */\n dynamic?: {\n salt?: boolean;\n [key: string]: unknown;\n };\n };\n schema?: Record<string, unknown>;\n}\n\n/**\n * x402x Router Settlement ResourceServerExtension\n * \n * This extension enriches PaymentRequired responses with router settlement\n * information, enabling clients to use the SettlementRouter for atomic payments.\n * \n * The extension dynamically generates per-request values like salt to ensure\n * each payment authorization is unique and cannot be replayed.\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { routerSettlementServerExtension } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * server.registerExtension(routerSettlementServerExtension);\n * ```\n */\nexport const routerSettlementServerExtension: ResourceServerExtension = {\n key: ROUTER_SETTLEMENT_KEY,\n\n enrichDeclaration: (declaration, transportContext) => {\n // Cast to typed declaration\n const extension = declaration as RouterSettlementDeclaration;\n\n // Generate dynamic salt for this request\n const salt = generateSalt();\n\n // Basic enrichment - ensure proper structure with dynamic salt\n const enriched: RouterSettlementDeclaration = {\n ...extension,\n info: {\n schemaVersion: 1,\n ...(extension.info || {}),\n // Add the generated salt to the info\n salt,\n },\n };\n\n // If HTTP context is available, we could add additional metadata\n if (isHTTPRequestContext(transportContext)) {\n // Future: could add HTTP-specific metadata here\n // For now, the salt generation is the main dynamic enhancement\n }\n\n return enriched;\n },\n};\n\n/**\n * Register router settlement extension with an x402ResourceServer\n * \n * Convenience function to register the routerSettlementServerExtension.\n * Also registers necessary hooks for handling settlement parameters.\n * \n * @param server - x402ResourceServer instance\n * @returns The server instance for chaining\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { registerExactEvmScheme } from \"@x402/evm/exact/server/register\";\n * import { registerRouterSettlement } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * registerExactEvmScheme(server, {});\n * registerRouterSettlement(server);\n * ```\n */\nexport function registerRouterSettlement(server: x402ResourceServer): x402ResourceServer {\n // Register the extension for enriching PaymentRequired responses\n server.registerExtension(routerSettlementServerExtension);\n \n // Note: Hooks for verify/settle are registered separately via \n // registerSettlementHooks if needed for custom validation logic\n \n return server;\n}\n\n/**\n * Create extension declaration for routes\n * \n * Helper function to create properly formatted extension declarations\n * for use in route configurations. The extension enables dynamic salt\n * generation per request and includes all settlement parameters.\n * \n * @param params - Extension parameters including settlement info\n * @returns Extension declaration object\n * \n * @example\n * ```typescript\n * const routes = {\n * \"GET /api/data\": {\n * accepts: { scheme: \"exact\", price: \"$0.01\", network: \"eip155:84532\", payTo: \"0x...\" },\n * extensions: createExtensionDeclaration({ \n * description: \"Router settlement with dynamic salt\",\n * settlementRouter: \"0x...\",\n * hook: \"0x...\",\n * hookData: \"0x\",\n * finalPayTo: \"0x...\",\n * facilitatorFee: \"0\",\n * salt: \"0x...\" // Optional, will be auto-generated if not provided\n * })\n * }\n * };\n * ```\n */\nexport function createExtensionDeclaration(params?: {\n description?: string;\n schema?: Record<string, unknown>;\n settlementRouter?: string;\n hook?: string;\n hookData?: string;\n finalPayTo?: string;\n facilitatorFee?: string;\n salt?: string; // Optional salt, will be auto-generated if not provided\n}): Record<string, unknown> {\n return {\n [ROUTER_SETTLEMENT_KEY]: createRouterSettlementExtension(params),\n };\n}\n\n","/**\n * Facilitator API client utilities for x402x\n *\n * Provides client-side functions to interact with facilitator HTTP APIs.\n * This includes fee calculation and caching utilities, as well as\n * helper functions for settlement mode detection and validation.\n */\n\nimport type { PaymentRequirements, PaymentPayload, SettlementExtraCore } from \"./types.js\";\nimport { SettlementExtraError } from \"./types.js\";\n\n/**\n * Check if a payment request requires SettlementRouter mode\n *\n * This is a client-side utility to determine which settlement flow to use.\n *\n * @param paymentRequirements - Payment requirements from 402 response\n * @returns True if settlement mode is required\n *\n * @example\n * ```typescript\n * if (isSettlementMode(paymentRequirements)) {\n * // Use Settlement Router mode\n * await submitToFacilitator(...);\n * } else {\n * // Use standard x402 mode\n * await settle(...);\n * }\n * ```\n */\nexport function isSettlementMode(paymentRequirements: PaymentRequirements): boolean {\n return !!paymentRequirements.extra?.settlementRouter;\n}\n\n/**\n * Parse and validate settlement extra parameters\n *\n * This is useful for clients to validate payment requirements before submission.\n *\n * @param extra - Extra field from PaymentRequirements\n * @returns Parsed settlement extra parameters\n * @throws SettlementExtraError if parameters are invalid\n *\n * @example\n * ```typescript\n * try {\n * const extra = parseSettlementExtra(paymentRequirements.extra);\n * console.log('Hook:', extra.hook);\n * console.log('Facilitator Fee:', extra.facilitatorFee);\n * } catch (error) {\n * console.error('Invalid settlement parameters:', error);\n * }\n * ```\n */\nexport function parseSettlementExtra(extra: unknown): SettlementExtraCore {\n if (!extra || typeof extra !== \"object\") {\n throw new SettlementExtraError(\"Missing or invalid extra field\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = extra as Record<string, any>;\n\n // Validate required fields\n if (!e.settlementRouter || typeof e.settlementRouter !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid settlementRouter\");\n }\n if (!e.salt || typeof e.salt !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid salt\");\n }\n if (!e.payTo || typeof e.payTo !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid payTo\");\n }\n if (!e.facilitatorFee || typeof e.facilitatorFee !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid facilitatorFee\");\n }\n if (!e.hook || typeof e.hook !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid hook\");\n }\n if (!e.hookData || typeof e.hookData !== \"string\") {\n throw new SettlementExtraError(\"Missing or invalid hookData\");\n }\n\n return {\n settlementRouter: e.settlementRouter,\n salt: e.salt,\n payTo: e.payTo,\n facilitatorFee: e.facilitatorFee,\n hook: e.hook,\n hookData: e.hookData,\n };\n}\n\n/**\n * Result of facilitator fee calculation\n *\n * This interface represents the response from facilitator's /calculate-fee endpoint.\n * Only essential information is included - internal cost breakdown is not exposed.\n */\nexport interface FeeCalculationResult {\n network: string;\n hook: string;\n hookData?: string;\n hookAllowed: boolean;\n\n // Main result - recommended facilitator fee\n facilitatorFee: string; // Atomic units (e.g., USDC with 6 decimals)\n facilitatorFeeUSD: string; // USD value for display\n\n // Metadata\n calculatedAt: string; // ISO 8601 timestamp\n validitySeconds: number; // How long this fee is valid (typically 60 seconds)\n\n token: {\n address: string;\n symbol: string;\n decimals: number;\n };\n}\n\n/**\n * Simple in-memory cache for fee calculations\n */\nclass FeeCache {\n private cache: Map<string, { result: FeeCalculationResult; expiresAt: number }> = new Map();\n private ttlMs: number;\n\n constructor(ttlSeconds: number = 60) {\n this.ttlMs = ttlSeconds * 1000;\n }\n\n private getCacheKey(network: string, hook: string, hookData?: string): string {\n return `${network}:${hook}:${hookData || \"\"}`;\n }\n\n get(network: string, hook: string, hookData?: string): FeeCalculationResult | null {\n const key = this.getCacheKey(network, hook, hookData);\n const cached = this.cache.get(key);\n\n if (!cached) {\n return null;\n }\n\n if (Date.now() > cached.expiresAt) {\n this.cache.delete(key);\n return null;\n }\n\n return cached.result;\n }\n\n set(result: FeeCalculationResult): void {\n const key = this.getCacheKey(result.network, result.hook, result.hookData);\n this.cache.set(key, {\n result,\n expiresAt: Date.now() + this.ttlMs,\n });\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n// Global cache instance\nconst feeCache = new FeeCache(60);\n\n/**\n * Calculate recommended facilitator fee by querying the facilitator service\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param network - Network name\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters\n * @param useCache - Whether to use caching (default: true)\n * @returns Fee calculation result with sufficient safety margin\n *\n * @example\n * ```typescript\n * const feeResult = await calculateFacilitatorFee(\n * 'https://facilitator.x402x.dev',\n * 'base-sepolia',\n * '0x1234...',\n * '0x'\n * );\n * console.log(`Recommended fee: ${feeResult.facilitatorFee} (${feeResult.facilitatorFeeUSD} USD)`);\n * ```\n */\nexport async function calculateFacilitatorFee(\n facilitatorUrl: string,\n network: string,\n hook: string,\n hookData?: string,\n useCache: boolean = true,\n): Promise<FeeCalculationResult> {\n // Check cache first\n if (useCache) {\n const cached = feeCache.get(network, hook, hookData);\n if (cached) {\n return cached;\n }\n }\n\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n\n // Build query parameters\n const params = new URLSearchParams({\n network,\n hook,\n });\n\n if (hookData) {\n params.append(\"hookData\", hookData);\n }\n\n // Query facilitator service\n const url = `${baseUrl}/calculate-fee?${params.toString()}`;\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n // Add timeout\n signal: AbortSignal.timeout(3000),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Facilitator fee calculation failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const result: FeeCalculationResult = await response.json();\n\n // Validate response\n if (!result.facilitatorFee || !result.network || !result.hook) {\n throw new Error(\"Invalid response from facilitator service\");\n }\n\n // Cache the result\n if (useCache) {\n feeCache.set(result);\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to calculate facilitator fee: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Clear the fee calculation cache\n *\n * Useful for testing or forcing fresh calculations\n */\nexport function clearFeeCache(): void {\n feeCache.clear();\n}\n\n/**\n * Response from facilitator verify endpoint\n *\n * Indicates whether a payment payload is valid without executing it.\n */\nexport interface VerifyResponse {\n /** Whether the payment payload is valid */\n isValid: boolean;\n /** Reason for invalidity if isValid is false */\n invalidReason?: string;\n /** Payer address extracted from the payload */\n payer: string;\n}\n\n/**\n * Response from facilitator settle endpoint\n *\n * Contains the result of settlement execution on-chain.\n */\nexport interface SettleResponse {\n /** Whether the settlement was successful */\n success: boolean;\n /** Transaction hash of the settlement */\n transaction: string;\n /** Network the settlement was executed on */\n network: string;\n /** Payer address */\n payer: string;\n /** Error reason if settlement failed */\n errorReason?: string;\n}\n\n/**\n * Verify a payment payload with the facilitator\n *\n * Calls the facilitator's `/verify` endpoint to validate a payment without executing it.\n * This is useful for pre-validation before actual settlement.\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param paymentPayload - Payment payload from client (x402 standard)\n * @param paymentRequirements - Payment requirements (x402 standard)\n * @returns Verification response indicating validity\n *\n * @throws Error if network request fails or response is invalid\n *\n * @example\n * ```typescript\n * import { verify } from '@x402x/core';\n *\n * const result = await verify(\n * 'https://facilitator.x402x.dev',\n * paymentPayload,\n * paymentRequirements\n * );\n *\n * if (result.isValid) {\n * console.log('Payment is valid, payer:', result.payer);\n * } else {\n * console.error('Invalid payment:', result.invalidReason);\n * }\n * ```\n */\nexport async function verify(\n facilitatorUrl: string,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n): Promise<VerifyResponse> {\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n const url = `${baseUrl}/verify`;\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n paymentPayload,\n paymentRequirements,\n }),\n // Add timeout\n signal: AbortSignal.timeout(10000),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Facilitator verify failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const result: VerifyResponse = await response.json();\n\n // Validate response structure\n if (typeof result.isValid !== \"boolean\") {\n throw new Error(\"Invalid response from facilitator: missing isValid field\");\n }\n\n if (typeof result.payer !== \"string\") {\n throw new Error(\"Invalid response from facilitator: missing payer field\");\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to verify with facilitator: ${error.message}`);\n }\n throw error;\n }\n}\n\n/**\n * Settle a payment with the facilitator\n *\n * Calls the facilitator's `/settle` endpoint to execute the payment on-chain.\n * This is the core function that submits a signed payment for blockchain execution.\n *\n * @param facilitatorUrl - Facilitator service base URL\n * @param paymentPayload - Payment payload from client (x402 standard)\n * @param paymentRequirements - Payment requirements (x402 standard)\n * @param timeout - Optional timeout in milliseconds (default: 30000)\n * @returns Settlement response with transaction details\n *\n * @throws Error if network request fails, response is invalid, or settlement fails\n *\n * @example\n * ```typescript\n * import { settle } from '@x402x/core';\n *\n * const result = await settle(\n * 'https://facilitator.x402x.dev',\n * paymentPayload,\n * paymentRequirements,\n * 30000 // 30 second timeout\n * );\n *\n * if (result.success) {\n * console.log('Settlement successful!');\n * console.log('Transaction:', result.transaction);\n * console.log('Network:', result.network);\n * } else {\n * console.error('Settlement failed:', result.errorReason);\n * }\n * ```\n */\nexport async function settle(\n facilitatorUrl: string,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n timeout: number = 30000,\n): Promise<SettleResponse> {\n // Remove trailing slash from URL\n const baseUrl = facilitatorUrl.endsWith(\"/\") ? facilitatorUrl.slice(0, -1) : facilitatorUrl;\n const url = `${baseUrl}/settle`;\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n paymentPayload,\n paymentRequirements,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const result: any = await response.json();\n\n if (!response.ok) {\n throw new Error(\n result.error || result.message || `Facilitator settle failed: ${response.status}`,\n );\n }\n\n // Validate result structure\n if (typeof result.success !== \"boolean\") {\n throw new Error(\"Invalid response from facilitator: missing success field\");\n }\n\n if (!result.success) {\n throw new Error(result.errorReason || \"Settlement failed\");\n }\n\n if (!result.transaction) {\n throw new Error(\"Invalid response from facilitator: missing transaction hash\");\n }\n\n return {\n success: result.success,\n transaction: result.transaction,\n network: result.network || paymentRequirements.network,\n payer: result.payer || \"\",\n errorReason: result.errorReason,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new Error(`Facilitator settle timed out after ${timeout}ms`);\n }\n throw new Error(`Failed to settle with facilitator: ${error.message}`);\n }\n throw error;\n }\n}\n","/**\n * Settlement Routes Helper\n * \n * Provides utilities for creating route configurations with router settlement support.\n * This module bridges the gap between x402 v2 official SDK's RoutesConfig and x402x\n * settlement requirements.\n * \n * Key Design: Use AssetAmount with x402x default assets to bypass official SDK's hardcoded default asset table.\n */\n\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport type { PaymentRequirements } from \"@x402/core/types\";\nimport { decodePaymentSignatureHeader } from \"@x402/core/http\";\nimport { createExtensionDeclaration } from \"./server-extension.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { generateSalt } from \"./commitment.js\";\nimport { TransferHook } from \"./hooks/index.js\";\nimport { ROUTER_SETTLEMENT_KEY } from \"./server-extension.js\";\nimport { calculateFacilitatorFee } from \"./facilitator.js\";\n\n/**\n * Default facilitator URL\n * Can be overridden in SettlementOptions.facilitatorUrl\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\n\n/**\n * Route configuration from @x402/core\n * Re-exported for convenience with settlement prefix to avoid naming conflicts\n */\nexport interface SettlementRouteConfig {\n accepts: SettlementPaymentOption | SettlementPaymentOption[];\n resource?: string;\n description?: string;\n mimeType?: string;\n extensions?: Record<string, unknown>;\n unpaidResponseBody?: (context: unknown) => Promise<{ contentType: string; body: unknown }> | { contentType: string; body: unknown };\n customPaywallHtml?: string;\n}\n\n/**\n * Payment option from @x402/core\n * Enhanced to support dynamic price generation with x402x assets\n */\nexport interface SettlementPaymentOption {\n scheme: string;\n network: string;\n payTo: string | ((context: unknown) => string | Promise<string>);\n price: string | number | AssetAmount | ((context: unknown) => string | number | AssetAmount | Promise<string | number | AssetAmount>);\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n}\n\n/**\n * AssetAmount type from @x402/core\n * Represents explicit asset/amount specification bypassing default asset lookup\n */\nexport interface AssetAmount {\n asset: string;\n amount: string;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Settlement options for route configuration\n */\nexport interface SettlementOptions {\n /** Hook contract address (optional, defaults to TransferHook for the network) */\n hook?: string;\n /** Encoded hook data (optional, defaults to TransferHook.encode()) */\n hookData?: string;\n /** \n * Facilitator fee amount (optional).\n * - If not provided, will be dynamically calculated by calling facilitator /calculate-fee endpoint\n * - If provided, will be used as fixed fee for all networks\n */\n facilitatorFee?: string;\n /** Final recipient address (optional, defaults to original option.payTo before settlementRouter override) */\n finalPayTo?: string;\n /** Optional description for the extension */\n description?: string;\n /**\n * Facilitator service URL for dynamic fee calculation (optional)\n * Defaults to https://facilitator.x402x.dev\n * Only used when facilitatorFee is not explicitly provided\n */\n facilitatorUrl?: string;\n}\n\n/**\n * Configuration for settlement hooks\n */\nexport interface SettlementHooksConfig {\n /** Whether to enable automatic salt extraction from extension info */\n enableSaltExtraction?: boolean;\n /** Whether to validate settlement router parameters */\n validateSettlementParams?: boolean;\n}\n\n/**\n * Create a route configuration with router settlement support\n * \n * This helper wraps the standard x402 RouteConfig and adds settlement-specific\n * configuration including hooks, settlement router address, and dynamic extensions.\n * \n * Key Design (v2 + x402x + dynamic fee):\n * - Uses DynamicPrice to enable probe-quote-replay flow:\n * - First request (no payment): generates salt + queries facilitator fee → returns AssetAmount\n * - Retry (with payment): decodes paymentPayload.accepted and replays it → ensures deepEqual match\n * - Converts Money price to AssetAmount using x402x default asset config per network\n * - Embeds EIP-712 domain + x402x settlement info into price.extra\n * - This bypasses official SDK's hardcoded getDefaultAsset() and allows x402x to define assets for all networks\n * \n * @param baseConfig - Base route configuration (accepts can use Money price like \"$1.00\")\n * @param settlementOptions - Settlement-specific options (all fields optional with sensible defaults)\n * @returns Enhanced route configuration with dynamic AssetAmount prices containing full x402x context\n * \n * @example Minimal usage (all defaults, dynamic fee from facilitator)\n * ```typescript\n * const routes = {\n * \"POST /api/purchase\": createSettlementRouteConfig({\n * accepts: supportedNetworks.map(network => ({\n * scheme: \"exact\",\n * network,\n * payTo: merchantAddress, // Used as finalPayTo, overridden to settlementRouter\n * price: \"$1.00\",\n * })),\n * description: \"Purchase endpoint\",\n * })\n * // settlementOptions omitted: uses DEFAULT_FACILITATOR_URL for fee query\n * };\n * ```\n * \n * @example With custom facilitator URL\n * ```typescript\n * const routes = {\n * \"POST /api/purchase\": createSettlementRouteConfig({\n * accepts: [...],\n * description: \"Purchase endpoint\",\n * }, {\n * facilitatorUrl: \"https://custom-facilitator.example.com\",\n * })\n * };\n * ```\n * \n * @example With fixed facilitator fee (no dynamic query)\n * ```typescript\n * const routes = {\n * \"POST /api/purchase\": createSettlementRouteConfig({\n * accepts: [...],\n * description: \"Purchase endpoint\",\n * }, {\n * facilitatorFee: \"1000\", // Fixed fee, skips dynamic calculation\n * })\n * };\n * ```\n */\nexport function createSettlementRouteConfig(\n baseConfig: SettlementRouteConfig,\n settlementOptions?: SettlementOptions,\n): SettlementRouteConfig {\n // Normalize accepts to array\n const acceptsArray = Array.isArray(baseConfig.accepts) \n ? baseConfig.accepts \n : [baseConfig.accepts];\n\n // Enhance each payment option with its own network-specific settlement extension\n const enhancedAccepts = acceptsArray.map((option) => {\n const network = typeof option.network === \"string\" ? option.network : option.network;\n const optionNetworkConfig = getNetworkConfig(network);\n if (!optionNetworkConfig) {\n throw new Error(`Network configuration not found for: ${network}`);\n }\n\n // Resolve original payTo (before settlementRouter override)\n const originalPayTo = typeof option.payTo === 'string' ? option.payTo : undefined;\n \n // Use finalPayTo from options, or fallback to original payTo\n const finalPayTo = settlementOptions?.finalPayTo || originalPayTo;\n if (!finalPayTo) {\n throw new Error(`Cannot determine finalPayTo: neither settlementOptions.finalPayTo nor option.payTo (string) is provided for network ${network}`);\n }\n\n // Resolve hook address (default to TransferHook for this network)\n const hook = settlementOptions?.hook || TransferHook.getAddress(network);\n const hookData = settlementOptions?.hookData || TransferHook.encode();\n\n // Determine facilitator URL (use provided or default)\n const facilitatorUrl = settlementOptions?.facilitatorUrl || DEFAULT_FACILITATOR_URL;\n\n // Check if facilitatorFee is explicitly provided (fixed fee mode)\n const hasFixedFee = settlementOptions?.facilitatorFee !== undefined;\n\n // Create DynamicPrice function that handles both probe and retry scenarios\n const dynamicPrice = async (context: any): Promise<AssetAmount> => {\n // Check if this is a retry request (has payment header)\n const httpContext = context as { paymentHeader?: string; method?: string; adapter?: unknown };\n const isRetry = !!httpContext.paymentHeader;\n\n if (isRetry) {\n // === RETRY PATH: Replay accepted from client ===\n console.log(\"[x402x-settlement] Retry request detected, replaying accepted\");\n \n try {\n const paymentPayload = decodePaymentSignatureHeader(httpContext.paymentHeader!);\n const accepted = paymentPayload.accepted;\n \n // Verify this is for the same network/scheme\n if (accepted.network === network && accepted.scheme === option.scheme) {\n console.log(\"[x402x-settlement] Replaying accepted for network:\", network);\n \n // Return exactly what client sent (ensures deepEqual match)\n return {\n asset: accepted.asset,\n amount: accepted.amount,\n extra: accepted.extra,\n };\n } else {\n console.warn(\"[x402x-settlement] Network/scheme mismatch in retry, falling back to probe\");\n }\n } catch (error) {\n console.error(\"[x402x-settlement] Failed to decode payment header, falling back to probe:\", error);\n }\n }\n\n // === PROBE PATH: Generate salt + query fee ===\n console.log(\"[x402x-settlement] Probe request, generating new salt and querying fee\");\n\n // Parse the base price\n const basePrice = typeof option.price === 'function' \n ? await option.price(context)\n : option.price;\n \n let moneyPrice: string | number;\n if (typeof basePrice === 'object' && basePrice !== null && 'asset' in basePrice) {\n // Already an AssetAmount (shouldn't happen in normal flow, but handle it)\n return basePrice as AssetAmount;\n } else {\n moneyPrice = basePrice;\n }\n\n // Parse the money amount (e.g., \"$1.00\" -> 1.0)\n const amountStr = typeof moneyPrice === 'number' \n ? moneyPrice.toString() \n : moneyPrice.toString().replace(/[^0-9.]/g, '');\n const amountFloat = parseFloat(amountStr);\n \n if (isNaN(amountFloat)) {\n throw new Error(`Invalid price format: ${moneyPrice}`);\n }\n\n // Get x402x default asset config for this network\n const { address, decimals, eip712 } = optionNetworkConfig.defaultAsset;\n\n // Convert to atomic units using x402x decimals\n const atomicAmount = BigInt(Math.floor(amountFloat * (10 ** decimals))).toString();\n\n // Generate fresh salt for this request\n const salt = generateSalt();\n\n // Query facilitator fee (if not fixed)\n let facilitatorFee: string;\n if (hasFixedFee) {\n facilitatorFee = settlementOptions!.facilitatorFee!;\n console.log(\"[x402x-settlement] Using fixed facilitatorFee:\", facilitatorFee);\n } else {\n console.log(\"[x402x-settlement] Querying facilitator for fee:\", { network, hook, hookData });\n try {\n const feeResult = await calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);\n \n if (!feeResult.hookAllowed) {\n throw new Error(`Hook not allowed by facilitator: ${hook} on network ${network}`);\n }\n \n facilitatorFee = feeResult.facilitatorFee;\n console.log(\"[x402x-settlement] Got facilitatorFee from facilitator:\", facilitatorFee);\n } catch (error) {\n console.error(\"[x402x-settlement] Failed to query facilitator fee:\", error);\n throw new Error(\n `Failed to calculate facilitator fee for network ${network}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Create network-specific settlement extension with fresh salt and queried/fixed fee\n const settlementExtension = createExtensionDeclaration({\n description: settlementOptions?.description || \"Router settlement with atomic fee distribution\",\n settlementRouter: optionNetworkConfig.settlementRouter,\n hook,\n hookData,\n finalPayTo,\n facilitatorFee,\n salt,\n });\n\n // Return AssetAmount with all context embedded in extra\n return {\n asset: address,\n amount: atomicAmount,\n extra: {\n // EIP-712 domain parameters (scheme-specific for signing)\n name: eip712.name,\n version: eip712.version,\n // Network-specific settlement extension parameters (per-option x402x declaration with salt + fee)\n [ROUTER_SETTLEMENT_KEY]: settlementExtension[ROUTER_SETTLEMENT_KEY],\n },\n };\n };\n\n // Build enhanced option with DynamicPrice\n const enhancedOption: SettlementPaymentOption = {\n ...option,\n // Override payTo to use settlementRouter as the immediate recipient\n payTo: optionNetworkConfig.settlementRouter,\n // Use DynamicPrice that queries fee on probe and replays on retry\n price: dynamicPrice,\n // Keep option.extra for any user-provided context (primary data is now in price.extra via dynamic function)\n extra: option.extra,\n };\n\n return enhancedOption;\n });\n\n // For route-level extensions, we only include schema/description (no network-specific info)\n // to avoid ambiguity when multiple networks are present\n const extensions = {\n ...(baseConfig.extensions || {}),\n // Only include non-network-specific metadata at root level\n // Per-option x402x info is already in accepts[i].price.extra[ROUTER_SETTLEMENT_KEY]\n };\n\n return {\n ...baseConfig,\n accepts: enhancedAccepts.length === 1 ? enhancedAccepts[0] : enhancedAccepts,\n extensions,\n };\n}\n\n/**\n * Register settlement-specific hooks with the resource server\n * \n * This function registers lifecycle hooks for handling settlement-specific logic:\n * - Extract salt from extension info before verification\n * - Validate settlement router parameters\n * \n * @param server - x402ResourceServer instance\n * @param config - Hook configuration options\n * \n * @example\n * ```typescript\n * import { registerSettlementHooks } from \"@x402x/extensions\";\n * \n * registerSettlementHooks(server, {\n * enableSaltExtraction: true,\n * validateSettlementParams: true,\n * });\n * ```\n */\nexport function registerSettlementHooks(\n server: x402ResourceServer,\n config: SettlementHooksConfig = {},\n): void {\n const {\n enableSaltExtraction = true,\n validateSettlementParams = true,\n } = config;\n\n if (enableSaltExtraction) {\n // Hook to extract settlement params from PaymentPayload extensions and add to requirements.extra\n // This is needed because the facilitator currently reads from requirements.extra\n server.onBeforeVerify(async (context) => {\n const { paymentPayload, requirements } = context;\n \n // Check if payment has settlement extension\n if (paymentPayload.extensions && \n \"x402x-router-settlement\" in paymentPayload.extensions) {\n const extension = paymentPayload.extensions[\"x402x-router-settlement\"] as any;\n \n if (extension?.info) {\n // Ensure requirements.extra exists\n if (!requirements.extra) {\n (requirements as any).extra = {};\n }\n \n // Extract all settlement params from extension and add to extra\n // (for backward compatibility with facilitator that reads from extra)\n const info = extension.info;\n if (info.salt) (requirements.extra as any).salt = info.salt;\n if (info.settlementRouter) (requirements.extra as any).settlementRouter = info.settlementRouter;\n if (info.hook) (requirements.extra as any).hook = info.hook;\n if (info.hookData) (requirements.extra as any).hookData = info.hookData;\n if (info.finalPayTo) (requirements.extra as any).payTo = info.finalPayTo;\n if (info.facilitatorFee !== undefined) (requirements.extra as any).facilitatorFee = info.facilitatorFee;\n }\n }\n \n // Don't abort - continue with verification\n return undefined;\n });\n }\n\n if (validateSettlementParams) {\n // Hook to validate settlement router parameters before settlement\n server.onBeforeSettle(async (context) => {\n const { paymentPayload, requirements } = context;\n \n // Try to get params from extensions first (v2 standard), then fall back to extra\n let settlementParams: any = {};\n \n if (paymentPayload.extensions && \"x402x-router-settlement\" in paymentPayload.extensions) {\n const extension = paymentPayload.extensions[\"x402x-router-settlement\"] as any;\n if (extension?.info) {\n settlementParams = extension.info;\n }\n }\n \n // Fallback to extra if not in extensions\n if (!settlementParams.settlementRouter && requirements.extra) {\n settlementParams = requirements.extra;\n }\n \n // Validate that required settlement fields are present\n const requiredFields = ['settlementRouter', 'hook', 'hookData'];\n const payToField = 'finalPayTo' in settlementParams ? 'finalPayTo' : 'payTo';\n const missingFields = requiredFields.filter(field => !settlementParams[field]);\n if (!settlementParams[payToField]) {\n missingFields.push(payToField);\n }\n \n if (missingFields.length > 0) {\n return {\n abort: true,\n reason: `Missing settlement parameters: ${missingFields.join(', ')}`,\n };\n }\n \n // All checks passed\n return undefined;\n });\n }\n}\n\n","/**\n * Helper functions for x402x router settlement integration\n * \n * Provides convenient utilities for working with x402 v2 resource servers\n * and router settlement extensions.\n */\n\nimport type { x402ResourceServer } from \"@x402/core/server\";\nimport type { PaymentRequirements, SchemeNetworkFacilitator } from \"@x402/core/types\";\nimport type { FacilitatorConfig } from \"./facilitator-types.js\";\nimport { registerRouterSettlement as registerExtension } from \"./server-extension.js\";\nimport { createRouterSettlementExtension, getRouterSettlementExtensionKey } from \"./extensions.js\";\nimport { getNetworkConfig } from \"./networks.js\";\nimport { generateSalt } from \"./commitment.js\";\nimport type { SettlementExtra } from \"./types.js\";\n\n/**\n * Register router settlement extension with a resource server\n * \n * @param server - x402ResourceServer instance\n * @returns The server instance for chaining\n * \n * @example\n * ```typescript\n * import { x402ResourceServer } from \"@x402/core/server\";\n * import { registerExactEvmScheme } from \"@x402/evm/exact/server/register\";\n * import { registerRouterSettlement } from \"@x402x/extensions\";\n * \n * const server = new x402ResourceServer(facilitatorClient);\n * registerExactEvmScheme(server, {});\n * registerRouterSettlement(server);\n * ```\n */\nexport function registerRouterSettlement(server: x402ResourceServer): x402ResourceServer {\n return registerExtension(server);\n}\n\n/**\n * Create a router settlement facilitator\n * \n * Factory function to create a RouterSettlementFacilitator instance.\n * \n * Note: This requires @x402x/facilitator-sdk to be installed separately.\n * \n * @param config - Facilitator configuration\n * @returns RouterSettlementFacilitator instance\n * \n * @example\n * ```typescript\n * // First install the dependency:\n * // pnpm install @x402x/facilitator-sdk\n * \n * import { createX402xFacilitator } from \"@x402x/extensions\";\n * // Or import directly:\n * // import { createRouterSettlementFacilitator } from \"@x402x/facilitator-sdk\";\n * \n * const facilitator = createX402xFacilitator({\n * privateKey: process.env.FACILITATOR_PRIVATE_KEY,\n * rpcUrls: {\n * \"base-sepolia\": \"https://sepolia.base.org\",\n * },\n * allowedRouters: {\n * \"base-sepolia\": [\"0x817e4f0ee2fbdaac426f1178e149f7dc98873ecb\"],\n * },\n * });\n * ```\n */\nexport async function createX402xFacilitator(\n config: FacilitatorConfig,\n): Promise<SchemeNetworkFacilitator> {\n // Dynamic import to avoid hard dependency\n // Using Function constructor to avoid static analysis during build\n try {\n const importFn = new Function('specifier', 'return import(specifier)');\n const facilitatorModule = await importFn('@x402x/facilitator-sdk') as {\n createRouterSettlementFacilitator: (config: FacilitatorConfig) => SchemeNetworkFacilitator;\n };\n return facilitatorModule.createRouterSettlementFacilitator(config);\n } catch (error) {\n throw new Error(\n \"createX402xFacilitator requires @x402x/facilitator-sdk to be installed. \" +\n \"Please install it using your package manager.\",\n );\n }\n}\n\n/**\n * Options for adding router settlement parameters\n */\nexport interface WithRouterSettlementOptions {\n /** Hook contract address (required) */\n hook: string;\n /** Encoded hook data (required) */\n hookData: string;\n /** Facilitator fee amount in atomic units (required) */\n facilitatorFee: string;\n /** Final recipient address (required) */\n payTo: string;\n /** Unique salt for idempotency (optional, will be auto-generated if not provided) */\n salt?: string;\n /** Asset name for EIP-712 (optional, will use network config default if not provided) */\n name?: string;\n /** Asset version for EIP-712 (optional, will use network config default if not provided) */\n version?: string;\n}\n\n/**\n * Add router settlement parameters to PaymentRequirements\n * \n * Enriches payment requirements with settlement router extra fields needed\n * for atomic settlement through the SettlementRouter contract.\n * \n * @param requirements - Base payment requirements from x402 middleware\n * @param options - Router settlement options\n * @returns Enhanced payment requirements with settlement extra\n * \n * @example\n * ```typescript\n * import { withRouterSettlement, TransferHook } from \"@x402x/extensions\";\n * \n * const baseRequirements = {\n * scheme: \"exact\",\n * network: \"eip155:84532\",\n * asset: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n * amount: \"1000000\", // 1 USDC\n * payTo: merchantAddress,\n * };\n * \n * const requirements = withRouterSettlement(baseRequirements, {\n * hook: TransferHook.getAddress(\"base-sepolia\"),\n * hookData: TransferHook.encode(),\n * facilitatorFee: \"10000\", // 0.01 USDC\n * payTo: merchantAddress,\n * });\n * ```\n */\nexport function withRouterSettlement(\n requirements: Partial<PaymentRequirements>,\n options: WithRouterSettlementOptions,\n): PaymentRequirements {\n // Validate required fields\n if (!requirements.network) {\n throw new Error(\"Network is required in payment requirements\");\n }\n\n if (!requirements.asset) {\n throw new Error(\"Asset is required in payment requirements\");\n }\n\n // Get network configuration\n const networkConfig = getNetworkConfig(requirements.network);\n if (!networkConfig) {\n throw new Error(`Network configuration not found for network: ${requirements.network}`);\n }\n\n // Generate salt if not provided\n const salt = options.salt || generateSalt();\n\n // Build settlement extra with EIP-712 domain info\n const settlementExtra: SettlementExtra = {\n settlementRouter: networkConfig.settlementRouter,\n salt,\n payTo: options.payTo,\n facilitatorFee: options.facilitatorFee,\n hook: options.hook,\n hookData: options.hookData,\n name: options.name || networkConfig.defaultAsset.eip712.name,\n version: options.version || networkConfig.defaultAsset.eip712.version,\n };\n\n // Create extension declaration\n const extensionKey = getRouterSettlementExtensionKey();\n const extensionDeclaration = createRouterSettlementExtension({\n description: \"Router settlement with atomic fee distribution\",\n });\n\n // Merge with existing requirements\n const reqWithExtensions = requirements as any;\n return {\n ...requirements,\n extra: {\n ...(reqWithExtensions.extra || {}),\n ...settlementExtra,\n },\n extensions: {\n ...(reqWithExtensions.extensions || {}),\n [extensionKey]: extensionDeclaration,\n },\n } as PaymentRequirements;\n}\n\n/**\n * Check if payment requirements use router settlement mode\n * \n * @param requirements - Payment requirements to check\n * @returns True if router settlement is enabled\n * \n * @example\n * ```typescript\n * if (isRouterSettlement(requirements)) {\n * console.log(\"Using router settlement mode\");\n * }\n * ```\n */\nexport function isRouterSettlement(requirements: PaymentRequirements): boolean {\n return !!(requirements.extra && \"settlementRouter\" in requirements.extra);\n}\n\n","/**\n * Amount parsing and formatting utilities for x402x default asset (USDC)\n */\n\nimport type { Network } from \"@x402/core/types\";\nimport { processPriceToAtomicAmount, getDefaultAsset } from \"./network-utils.js\";\n\n/**\n * Error class for amount-related validation errors\n */\nexport class AmountError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AmountError\";\n }\n}\n\n/**\n * Parse amount from various formats to atomic units for the default asset (USDC)\n *\n * Supports multiple input formats:\n * - Dollar format: '$1.2' or '$1.20' → '1200000' (1.2 USDC)\n * - Decimal string: '1.2' or '1.20' → '1200000'\n * - Number: 1.2 → '1200000'\n *\n * Uses x402's processPriceToAtomicAmount for parsing. All string/number inputs\n * are treated as USD amounts, not atomic units.\n *\n * @param amount - Amount in various formats (USD, not atomic units)\n * @param network - Network name (required) - used to determine token decimals\n * @returns Amount in atomic units as string\n * @throws AmountError if amount format is invalid\n *\n * @example\n * ```typescript\n * parseDefaultAssetAmount('$1.2', 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount('1.2', 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount(1.2, 'base-sepolia') // '1200000'\n * parseDefaultAssetAmount('100', 'base-sepolia') // '100000000' (100 USDC, not 100 atomic units)\n * ```\n */\nexport function parseDefaultAssetAmount(amount: string | number, network: Network): string {\n // Handle empty/invalid input\n if (amount === null || amount === undefined || amount === \"\") {\n throw new AmountError(\"Amount is required\");\n }\n\n // Use x402's processPriceToAtomicAmount for parsing\n // This handles all string/number inputs as USD amounts\n const result = processPriceToAtomicAmount(amount, network);\n\n if (\"error\" in result) {\n throw new AmountError(`Invalid amount format: ${result.error}`);\n }\n\n return result.amount;\n}\n\n/**\n * Format atomic units to human-readable decimal string for the default asset (USDC)\n *\n * Automatically determines decimals from the network's default asset configuration.\n *\n * @param amount - Amount in atomic units\n * @param network - Network name (required) - used to determine token decimals\n * @returns Human-readable decimal string\n * @throws AmountError if amount is invalid\n *\n * @example\n * ```typescript\n * formatDefaultAssetAmount('1200000', 'base-sepolia') // '1.2'\n * formatDefaultAssetAmount('1000000', 'base-sepolia') // '1'\n * formatDefaultAssetAmount('1', 'base-sepolia') // '0.000001'\n * ```\n */\nexport function formatDefaultAssetAmount(amount: string, network: Network): string {\n const atomicAmount = BigInt(amount);\n if (atomicAmount < 0n) {\n throw new AmountError(\"Amount cannot be negative\");\n }\n\n // Get decimals from network's default asset\n const asset = getDefaultAsset(network);\n const decimals = asset.decimals;\n\n const amountStr = atomicAmount.toString().padStart(decimals + 1, \"0\");\n const integerPart = amountStr.slice(0, -decimals) || \"0\";\n const decimalPart = amountStr.slice(-decimals);\n\n // Remove trailing zeros from decimal part\n const trimmedDecimal = decimalPart.replace(/0+$/, \"\");\n\n if (trimmedDecimal) {\n return `${integerPart}.${trimmedDecimal}`;\n }\n return integerPart;\n}\n","/**\n * ABI definitions for x402x contracts\n */\n\n/**\n * Settlement Router ABI\n *\n * Contains functions used by facilitators for settlement and fee management.\n */\nexport const SETTLEMENT_ROUTER_ABI = [\n {\n type: \"function\",\n name: \"settleAndExecute\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n { name: \"salt\", type: \"bytes32\" },\n { name: \"payTo\", type: \"address\" },\n { name: \"facilitatorFee\", type: \"uint256\" },\n { name: \"hook\", type: \"address\" },\n { name: \"hookData\", type: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"calculateCommitment\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"from\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"salt\", type: \"bytes32\" },\n { name: \"payTo\", type: \"address\" },\n { name: \"facilitatorFee\", type: \"uint256\" },\n { name: \"hook\", type: \"address\" },\n { name: \"hookData\", type: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"calculateContextKey\",\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"pure\",\n },\n {\n type: \"function\",\n name: \"isSettled\",\n inputs: [{ name: \"contextKey\", type: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getPendingFees\",\n inputs: [\n { name: \"facilitator\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"claimFees\",\n inputs: [{ name: \"tokens\", type: \"address[]\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","/**\n * Type definitions for facilitator services\n * \n * These types define the interfaces and configurations used by facilitator\n * implementations that handle payment verification and settlement.\n */\n\nimport type { Network } from \"@x402/core/types\";\n\n/**\n * Ethereum address type\n */\nexport type Address = `0x${string}`;\n\n/**\n * Response from facilitator verification\n */\nexport interface VerifyResponse {\n /** Whether the payment payload is valid */\n isValid: boolean;\n /** Reason for invalidity if isValid is false */\n invalidReason?: string;\n /** Payer address extracted from the payload */\n payer?: string;\n}\n\n/**\n * Response from facilitator settlement\n */\nexport interface SettleResponse {\n /** Whether the settlement was successful */\n success: boolean;\n /** Transaction hash of the settlement */\n transaction: string;\n /** Network the settlement was executed on (CAIP-2 format) */\n network: Network;\n /** Payer address */\n payer?: string;\n /** Error reason if settlement failed */\n errorReason?: string;\n}\n\n/**\n * Configuration for RouterSettlementFacilitator\n */\nexport interface FacilitatorConfig {\n /** Signer address for facilitating settlements (optional, will be derived from privateKey if not provided) */\n signer?: Address;\n /** Private key for local signing (enables sending transactions on standard RPC providers) */\n privateKey?: string;\n /** Allowed SettlementRouter addresses per network */\n allowedRouters?: Record<string, string[]>;\n /** Optional RPC URLs per network */\n rpcUrls?: Record<string, string>;\n /** Gas configuration */\n gasConfig?: {\n maxGasLimit: bigint;\n gasMultiplier: number;\n };\n /** Fee configuration */\n feeConfig?: {\n minFee: string;\n maxFee: string;\n };\n /** Timeouts in milliseconds */\n timeouts?: {\n verify: number;\n settle: number;\n };\n}\n\n/**\n * Parameters for SettlementRouter.settleAndExecute\n */\nexport interface SettlementRouterParams {\n token: Address;\n from: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: string;\n signature: string;\n salt: string;\n payTo: Address;\n facilitatorFee: string;\n hook: Address;\n hookData: string;\n settlementRouter: Address;\n}\n\n/**\n * Error types for facilitator operations\n */\nexport class FacilitatorValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorValidationError\";\n }\n}\n\nexport class SettlementRouterError extends Error {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"SettlementRouterError\";\n }\n}\n\n","/**\n * x402x EVM Client Scheme with Router Settlement\n * \n * This scheme extends the standard EVM exact scheme to support x402x router settlement.\n * The key difference is using a commitment hash (binding all settlement parameters)\n * as the EIP-3009 nonce instead of a random value.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport { getAddress, type Hex } from \"viem\";\nimport { calculateCommitment } from \"../commitment.js\";\nimport type { CommitmentParams } from \"../types.js\";\nimport { ROUTER_SETTLEMENT_KEY } from \"../server-extension.js\";\n\n/**\n * Client EVM signer interface\n * Compatible with viem WalletClient and LocalAccount\n */\nexport type ClientEvmSigner = {\n readonly address: `0x${string}`;\n signTypedData(message: {\n domain: Record<string, unknown>;\n types: Record<string, unknown>;\n primaryType: string;\n message: Record<string, unknown>;\n }): Promise<`0x${string}`>;\n};\n\n/**\n * EIP-3009 TransferWithAuthorization types for EIP-712 signing\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\n/**\n * EVM exact payment payload structure (v2)\n */\ninterface ExactEvmPayloadV2 {\n authorization: {\n from: string;\n to: string;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: Hex;\n };\n signature: `0x${string}`;\n}\n\n/**\n * x402x router settlement extension info structure\n */\ninterface RouterSettlementExtension {\n info: {\n schemaVersion?: number;\n description?: string;\n salt: string; // bytes32 hex\n settlementRouter?: string; // address\n hook?: string; // address\n hookData?: string; // bytes hex\n finalPayTo?: string; // address\n facilitatorFee?: string; // uint256 string\n };\n schema?: Record<string, unknown>;\n}\n\n/**\n * EVM client implementation for the Exact payment scheme with x402x router settlement.\n * \n * This scheme uses a commitment hash as the EIP-3009 nonce to cryptographically bind\n * all settlement parameters (salt, hook, hookData, etc.) to the user's signature,\n * preventing parameter tampering attacks.\n * \n * @example\n * ```typescript\n * import { ExactEvmSchemeWithRouterSettlement } from '@x402x/extensions/client';\n * import { x402Client } from '@x402/core/client';\n * \n * const signer = { address, signTypedData }; // viem WalletClient or LocalAccount\n * const scheme = new ExactEvmSchemeWithRouterSettlement(signer);\n * \n * const client = new x402Client()\n * .register('eip155:84532', scheme);\n * ```\n */\nexport class ExactEvmSchemeWithRouterSettlement implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Per-request router settlement extension (typically sourced from PaymentRequired.extensions).\n *\n * IMPORTANT: We do NOT put this on `paymentRequirements.extra`, because for x402 v2 the\n * server matches paid requests by deep-equality between `paymentPayload.accepted` and the\n * server-side `accepts[]`. Mutating `accepted` will cause \"No matching payment requirements\".\n */\n private routerSettlementFromPaymentRequired?: RouterSettlementExtension;\n\n /**\n * Creates a new ExactEvmSchemeWithRouterSettlement instance.\n *\n * @param signer - The EVM signer for client operations (viem WalletClient or LocalAccount)\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Set router-settlement extension data for the next payment payload creation.\n *\n * Intended to be called from an `x402Client.onBeforePaymentCreation` hook, which has access\n * to `paymentRequired.extensions`.\n */\n setRouterSettlementExtensionFromPaymentRequired(ext: unknown | undefined): void {\n if (!ext) {\n this.routerSettlementFromPaymentRequired = undefined;\n return;\n }\n // We keep this cast narrow and validate at use-time.\n this.routerSettlementFromPaymentRequired = ext as RouterSettlementExtension;\n }\n\n /**\n * Creates a payment payload for the Exact scheme with router settlement.\n * \n * This method:\n * 1. Extracts settlement parameters from PaymentRequired.extensions\n * 2. Calculates a commitment hash binding all parameters\n * 3. Uses the commitment as the EIP-3009 nonce\n * 4. Signs with settlementRouter as the 'to' address\n *\n * @param x402Version - The x402 protocol version (must be 2)\n * @param paymentRequirements - The payment requirements from the server\n * @returns Promise resolving to a payment payload\n * \n * @throws Error if x402Version is not 2\n * @throws Error if x402x-router-settlement extension is missing\n * @throws Error if required settlement parameters are missing\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n if (x402Version !== 2) {\n throw new Error(\n `ExactEvmSchemeWithRouterSettlement only supports x402 version 2, got: ${x402Version}`\n );\n }\n\n // Extract x402x extension.\n // Prefer per-requirement extra (if a server implementation provides it),\n // otherwise use the per-request data injected from PaymentRequired.extensions.\n const routerSettlement =\n (paymentRequirements.extra?.[ROUTER_SETTLEMENT_KEY] as RouterSettlementExtension | undefined) ??\n this.routerSettlementFromPaymentRequired;\n\n if (!routerSettlement?.info) {\n throw new Error(\n \"x402x-router-settlement extension not available for scheme signing. \" +\n \"Ensure the resource server includes the extension in PaymentRequired.extensions and \" +\n \"the client registered x402x via registerX402xScheme() (or injected the handler).\",\n );\n }\n\n const { salt, settlementRouter, hook, hookData, finalPayTo, facilitatorFee } =\n routerSettlement.info;\n\n // Clear after read to avoid leaking between requests\n this.routerSettlementFromPaymentRequired = undefined;\n\n // Validate required parameters\n if (!salt) throw new Error(\"Missing required parameter: salt\");\n if (!settlementRouter) throw new Error(\"Missing required parameter: settlementRouter\");\n if (!hook) throw new Error(\"Missing required parameter: hook\");\n if (hookData === undefined) throw new Error(\"Missing required parameter: hookData\");\n if (!finalPayTo) throw new Error(\"Missing required parameter: finalPayTo\");\n // facilitatorFee is optional - if not provided, use \"0\" (facilitator will calculate actual fee)\n const resolvedFacilitatorFee = facilitatorFee ?? \"0\";\n\n // Parse chain ID from network (e.g., \"eip155:84532\" -> 84532)\n const chainId = parseInt(paymentRequirements.network.split(\":\")[1]);\n if (isNaN(chainId)) {\n throw new Error(`Invalid network format: ${paymentRequirements.network}`);\n }\n\n // Calculate time window\n const now = Math.floor(Date.now() / 1000);\n const validAfter = (now - 600).toString(); // 10 minutes before\n const validBefore = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n // Build commitment parameters\n const commitmentParams: CommitmentParams = {\n chainId,\n hub: settlementRouter,\n asset: paymentRequirements.asset,\n from: this.signer.address,\n value: paymentRequirements.amount,\n validAfter,\n validBefore,\n salt,\n payTo: finalPayTo,\n facilitatorFee: resolvedFacilitatorFee,\n hook,\n hookData,\n };\n\n // Calculate commitment hash - this becomes the nonce\n const nonce = calculateCommitment(commitmentParams) as Hex;\n\n // Build authorization (EIP-3009)\n // CRITICAL: 'to' must be settlementRouter, not payTo\n const authorization: ExactEvmPayloadV2[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(settlementRouter),\n value: paymentRequirements.amount,\n validAfter,\n validBefore,\n nonce,\n };\n\n // Sign the authorization using EIP-712\n const signature = await this.signAuthorization(authorization, paymentRequirements, chainId);\n\n // Build payload\n const payload: Record<string, unknown> = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @param chainId - The chain ID\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV2[\"authorization\"],\n requirements: PaymentRequirements,\n chainId: number,\n ): Promise<`0x${string}`> {\n // Extract EIP-712 domain parameters from extra\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n\n","/**\n * x402x Extension Handler\n * \n * Provides utilities to integrate x402x router settlement with official x402 SDK.\n * \n * The challenge: x402 v2 spec places extensions at root level in PaymentRequired,\n * but x402x scheme needs settlement parameters from PaymentRequirements.extra.\n * \n * Solution: Provide two-layer API:\n * 1. High-level: registerX402xScheme() - one line setup (recommended)\n * 2. Low-level: injectX402xExtensionHandler() - flexible configuration\n */\n\nimport { x402Client } from \"@x402/core/client\";\nimport type { Network } from \"@x402/core/types\";\nimport { ROUTER_SETTLEMENT_KEY } from \"../server-extension\";\nimport { ExactEvmSchemeWithRouterSettlement, type ClientEvmSigner } from \"./exact-evm-scheme\";\n\n/**\n * Injects x402x extension handler into x402Client (Low-level API).\n *\n * IMPORTANT (x402 v2 + x402x multi-network):\n * - Server returns per-option x402x info in `accepts[i].extra[\"x402x-router-settlement\"]`\n * - x402Client only passes `PaymentRequirements` to scheme (no root extensions)\n * - Facilitator v2 reads from `paymentPayload.extensions[\"x402x-router-settlement\"]`\n * \n * Solution: Copy the selected option's x402x info from `selectedRequirements.extra`\n * into `paymentRequired.extensions` so it gets included in `paymentPayload.extensions`.\n * \n * This does NOT mutate `selectedRequirements` (which becomes `paymentPayload.accepted`),\n * so v2 deepEqual matching still works.\n * \n * @param client - x402Client instance to inject handler into\n * @param onRouterSettlementExtension - Callback to receive the per-request extension object\n * @returns The same client instance for chaining\n * \n * @example Low-level API (for advanced users)\n * ```typescript\n * import { x402Client } from '@x402/core/client';\n * import { \n * injectX402xExtensionHandler, \n * ExactEvmSchemeWithRouterSettlement \n * } from '@x402x/extensions';\n * \n * const client = new x402Client();\n * const scheme = new ExactEvmSchemeWithRouterSettlement(signer);\n * injectX402xExtensionHandler(client, (ext) => scheme.setRouterSettlementExtensionFromPaymentRequired(ext))\n * .register('eip155:84532', scheme);\n * ```\n */\nexport function injectX402xExtensionHandler(\n client: x402Client,\n onRouterSettlementExtension?: (extension: unknown | undefined) => void,\n): x402Client {\n return client.onBeforePaymentCreation(async (context) => {\n const { paymentRequired, selectedRequirements } = context;\n \n // Debug: show what we received\n console.log(\"[x402x-handler] onBeforePaymentCreation called\");\n console.log(\"[x402x-handler] selectedRequirements.network:\", selectedRequirements.network);\n console.log(\"[x402x-handler] selectedRequirements.extra keys:\", Object.keys(selectedRequirements.extra || {}));\n \n // Key insight: Per-option x402x info is in selectedRequirements.extra[x402x-router-settlement].\n // We need to copy it into paymentRequired.extensions[x402x-router-settlement] so that:\n // 1. x402Client copies it into paymentPayload.extensions (v2 standard)\n // 2. Facilitator v2 can read it from paymentPayload.extensions\n // 3. We DON'T mutate selectedRequirements (which becomes paymentPayload.accepted)\n \n const perOptionExtension = selectedRequirements.extra?.[ROUTER_SETTLEMENT_KEY];\n \n if (perOptionExtension) {\n // Initialize extensions object if it doesn't exist\n if (!paymentRequired.extensions) {\n (paymentRequired as any).extensions = {};\n }\n \n // Copy the per-option x402x info into root extensions\n // This will be copied into paymentPayload.extensions by x402Client\n (paymentRequired.extensions as any)[ROUTER_SETTLEMENT_KEY] = perOptionExtension;\n \n console.log(\"[x402x-handler] ✅ Copied per-option x402x info into PaymentRequired.extensions\");\n console.log(\"[x402x-handler] Extension info:\", JSON.stringify(perOptionExtension, null, 2));\n } else {\n // Fallback: if no per-option info, use root-level extension (legacy behavior)\n console.warn(\"[x402x-handler] ⚠️ No per-option x402x info found in selectedRequirements.extra\");\n console.warn(\"[x402x-handler] This may cause facilitator errors. Check server-side createSettlementRouteConfig.\");\n }\n\n // Forward extension to callback (for schemes that need direct access)\n if (onRouterSettlementExtension) {\n const extensionToUse = perOptionExtension || paymentRequired.extensions?.[ROUTER_SETTLEMENT_KEY];\n onRouterSettlementExtension(extensionToUse);\n }\n });\n}\n\n/**\n * Register x402x router settlement scheme with automatic extension handling (High-level API).\n * \n * This is the recommended way to set up x402x payments. It combines:\n * 1. Extension handler injection (injectX402xExtensionHandler)\n * 2. Scheme registration (ExactEvmSchemeWithRouterSettlement)\n * \n * Use this for the simplest integration - just provide your signer and network.\n * \n * @param client - x402Client instance\n * @param network - Network identifier in CAIP-2 format (e.g., \"eip155:84532\")\n * @param signer - EVM signer with address and signTypedData method\n * @returns The client instance for chaining\n * \n * @example High-level API (recommended)\n * ```typescript\n * import { x402Client } from '@x402/core/client';\n * import { registerX402xScheme } from '@x402x/extensions';\n * import { useWalletClient } from 'wagmi';\n * \n * const { data: walletClient } = useWalletClient();\n * \n * const client = new x402Client();\n * registerX402xScheme(client, 'eip155:84532', {\n * address: walletClient.account.address,\n * signTypedData: walletClient.signTypedData,\n * });\n * \n * // That's it! Client is ready for x402x payments\n * ```\n * \n * @example Multiple networks\n * ```typescript\n * const client = new x402Client();\n * registerX402xScheme(client, 'eip155:84532', signer); // Base Sepolia\n * registerX402xScheme(client, 'eip155:8453', signer); // Base Mainnet\n * ```\n */\nexport function registerX402xScheme(\n client: x402Client,\n network: Network,\n signer: ClientEvmSigner,\n): x402Client {\n const scheme = new ExactEvmSchemeWithRouterSettlement(signer);\n\n // Inject extension handler: capture root-level extension data (incl. dynamic salt)\n // and pass it into the scheme instance without mutating `accepted`.\n injectX402xExtensionHandler(client, (ext) => {\n // Scope to this specific network to avoid cross-network leakage if user registers multiple.\n // (We don't have direct access to `selectedRequirements` here without mutating accepted,\n // so we keep it simple: this scheme instance is per-network registration.)\n scheme.setRouterSettlementExtensionFromPaymentRequired(ext);\n });\n\n // Register the x402x scheme for this network\n client.register(network, scheme);\n \n return client;\n}\n\n"]}
|