uvd-x402-sdk 2.104.2 → 2.104.3
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/adapters/index.d.mts +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/index.js +135 -5
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/index.mjs +135 -5
- package/dist/adapters/index.mjs.map +1 -1
- package/dist/backend/index.js.map +1 -1
- package/dist/backend/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +135 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +135 -5
- package/dist/index.mjs.map +1 -1
- package/dist/{ows-BB6Sgj0W.d.ts → ows-CW-g7qGw.d.ts} +9 -2
- package/dist/{ows-DazT4KQH.d.mts → ows-DJu424iz.d.mts} +9 -2
- package/dist/providers/evm/index.js.map +1 -1
- package/dist/providers/evm/index.mjs.map +1 -1
- package/dist/providers/stellar/index.js.map +1 -1
- package/dist/providers/stellar/index.mjs.map +1 -1
- package/dist/providers/sui/index.js.map +1 -1
- package/dist/providers/sui/index.mjs.map +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/adapters/env-key.ts +9 -2
- package/src/adapters/ows.ts +12 -3
- package/src/utils/uint.ts +211 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/chains/index.ts","../../src/types/index.ts","../../src/utils/base64.ts","../../src/utils/x402.ts","../../src/utils/validation.ts","../../src/adapters/wagmi.ts","../../src/utils/uint.ts","../../src/adapters/env-key.ts","../../src/adapters/ows.ts"],"names":["caip2","parseUnits","ethers","isRecord"],"mappings":";;;;;AAmBO,IAAM,uBAAA,GAA0B,yCAAA;AAUhC,IAAM,gBAAA,GAAgD;AAAA,EAC3D,gBAAA,EAAkB;AAAA,IAChB,OAAA,EAAS,CAAA;AAAA,IAAG,UAAA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AAA,CAAG,CAAA;AAAA,MACxF;AAAA,IACF;AACA,IAAA,EAAA,CAAG,SAAA,GAAY,IAAA;AACf,IAAA,OAAO,EAAA;AAAA,EACT;AAAA,EAEA,YAAA,CAAa,QAAgB,IAAA,EAAoB;AAC/C,IAAA,IAAI,MAAA,KAAW,KAAK,QAAA,EAAU;AAC5B,MAAA,MAAM,IAAI,SAAA;AAAA,QACR,CAAA,IAAA,EAAO,IAAI,CAAA,+CAAA,EAAkD,IAAA,CAAK,QAAQ,CAAA,kFAAA,CAAA;AAAA,QAE1E;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,KAAA,CAAS,IAAA,EAAc,GAAA,EAAc,IAAA,GAA8C,gBAAA,EAAqB;AACtG,IAAA,IAAI;AACF,MAAA,OAAO,GAAA,EAAI;AAAA,IACb,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACnE,MAAA,IAAI,IAAA,CAAK,aAAa,OAAA,GAAU,OAAA,CAAQ,MAAM,IAAA,CAAK,WAAW,CAAA,CAAE,IAAA,CAAK,YAAY,CAAA;AACjF,MAAA,MAAM,IAAI,SAAA,CAAU,CAAA,IAAA,EAAO,IAAI,CAAA,SAAA,EAAY,OAAO,IAAI,IAAI,CAAA;AAAA,IAC5D;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * uvd-x402-sdk - Chain Registry\n *\n * Complete configuration for all 29 supported blockchain networks.\n * EVM chains (17): Use ERC-3009 TransferWithAuthorization (includes Scroll, SKALE Base, Robinhood Chain mainnet + testnet, Arc mainnet + testnet)\n * BSC is registered but disabled (Binance-Peg USDC has no ERC-3009), so it is not in those counts.\n * SVM chains (2): Solana and Fogo - Use SPL tokens with partially-signed transactions\n * Stellar (1): Uses Soroban authorization entries\n * NEAR (1): Uses NEP-366 meta-transactions\n * Algorand (2): Uses ASA transfers with atomic transaction groups\n * Sui (2): Uses sponsored transactions (facilitator pays gas)\n * XRPL (2): Native XRP via pre-signed Payment transaction blobs (facilitator pays fee)\n */\n\nimport type { ChainConfig, NetworkType, TokenType, TokenConfig } from '../types';\n\n/**\n * Default facilitator URL for x402 payments\n */\nexport const DEFAULT_FACILITATOR_URL = 'https://facilitator.ultravioletadao.xyz';\n\n/**\n * All supported chains configuration\n *\n * To add a new chain:\n * 1. Add chain config below with all required fields\n * 2. Verify USDC contract supports ERC-3009 (transferWithAuthorization) for EVM chains\n * 3. Test on testnet first before enabling\n */\nexport const SUPPORTED_CHAINS: Record<string, ChainConfig> = {\n 'hedera:mainnet': {\n chainId: 0, chainIdHex: '0x0', name: 'hedera:mainnet',\n displayName: 'Hedera', networkType: 'hedera',\n rpcUrl: 'https://mainnet-public.mirrornode.hedera.com', explorerUrl: 'https://hashscan.io/mainnet',\n nativeCurrency: { name: 'HBAR', symbol: 'HBAR', decimals: 8 },\n usdc: { address: '0.0.456858', decimals: 6, name: 'USDC', version: '' },\n tokens: {\n usdc: { address: '0.0.456858', decimals: 6, name: 'USDC', version: '' },\n },\n x402: { facilitatorUrl: DEFAULT_FACILITATOR_URL, enabled: true },\n },\n 'hedera:testnet': {\n chainId: 0, chainIdHex: '0x0', name: 'hedera:testnet',\n displayName: 'Hedera Testnet', networkType: 'hedera',\n rpcUrl: 'https://testnet.mirrornode.hedera.com', explorerUrl: 'https://hashscan.io/testnet',\n nativeCurrency: { name: 'HBAR', symbol: 'HBAR', decimals: 8 },\n usdc: { address: '0.0.429274', decimals: 6, name: 'USDC', version: '' },\n tokens: {\n usdc: { address: '0.0.429274', decimals: 6, name: 'USDC', version: '' },\n },\n x402: { facilitatorUrl: DEFAULT_FACILITATOR_URL, enabled: true },\n },\n\n // ============================================================================\n // EVM CHAINS (16 enabled + BSC, disabled)\n // ============================================================================\n\n base: {\n chainId: 8453,\n chainIdHex: '0x2105',\n name: 'base',\n displayName: 'Base',\n networkType: 'evm',\n rpcUrl: 'https://mainnet.base.org',\n explorerUrl: 'https://basescan.org',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n eurc: {\n address: '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n avalanche: {\n chainId: 43114,\n chainIdHex: '0xa86a',\n name: 'avalanche',\n displayName: 'Avalanche C-Chain',\n networkType: 'evm',\n rpcUrl: 'https://avalanche-c-chain-rpc.publicnode.com',\n explorerUrl: 'https://snowtrace.io',\n nativeCurrency: {\n name: 'Avalanche',\n symbol: 'AVAX',\n decimals: 18,\n },\n usdc: {\n address: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n // name() on-chain is \"Euro Coin\" here and \"EURC\" on Base: pinned to each\n // contract's DOMAIN_SEPARATOR() by src/eurc-domains.test.ts.\n eurc: {\n address: '0xC891EB4cbdEFf6e073e859e987815Ed1505c2ACD',\n decimals: 6,\n name: 'Euro Coin',\n version: '2',\n usdPegged: false,\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n ethereum: {\n chainId: 1,\n chainIdHex: '0x1',\n name: 'ethereum',\n displayName: 'Ethereum',\n networkType: 'evm',\n rpcUrl: 'https://eth.llamarpc.com',\n explorerUrl: 'https://etherscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n eurc: {\n address: '0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c',\n decimals: 6,\n name: 'Euro Coin',\n version: '2',\n usdPegged: false,\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n pyusd: {\n address: '0x6c3ea9036406852006290770BEdFcAbA0e23A0e8',\n decimals: 6,\n name: 'PayPal USD',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n polygon: {\n chainId: 137,\n chainIdHex: '0x89',\n name: 'polygon',\n displayName: 'Polygon',\n networkType: 'evm',\n rpcUrl: 'https://polygon-rpc.com',\n explorerUrl: 'https://polygonscan.com',\n nativeCurrency: {\n name: 'Polygon',\n symbol: 'POL',\n decimals: 18,\n },\n usdc: {\n address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n arbitrum: {\n chainId: 42161,\n chainIdHex: '0xa4b1',\n name: 'arbitrum',\n displayName: 'Arbitrum One',\n networkType: 'evm',\n rpcUrl: 'https://arb1.arbitrum.io/rpc',\n explorerUrl: 'https://arbiscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n usdt: {\n address: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6,\n name: 'USD₮0',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n optimism: {\n chainId: 10,\n chainIdHex: '0xa',\n name: 'optimism',\n displayName: 'Optimism',\n networkType: 'evm',\n rpcUrl: 'https://mainnet.optimism.io',\n explorerUrl: 'https://optimistic.etherscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n usdt: {\n address: '0x01bff41798a0bcf287b996046ca68b395dbc1071',\n decimals: 6,\n name: 'USD₮0',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n celo: {\n chainId: 42220,\n chainIdHex: '0xa4ec',\n name: 'celo',\n displayName: 'Celo',\n networkType: 'evm',\n rpcUrl: 'https://forno.celo.org',\n explorerUrl: 'https://celoscan.io',\n nativeCurrency: {\n name: 'Celo',\n symbol: 'CELO',\n decimals: 18,\n },\n usdc: {\n address: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6,\n name: 'USDC', // Celo uses \"USDC\" not \"USD Coin\" for EIP-712\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6,\n name: 'USDC', // Celo uses \"USDC\" not \"USD Coin\" for EIP-712\n version: '2',\n },\n usdt: {\n address: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6,\n name: 'Tether USD', // Celo USDT uses \"Tether USD\" for EIP-712\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n hyperevm: {\n chainId: 999,\n chainIdHex: '0x3e7',\n name: 'hyperevm',\n displayName: 'HyperEVM',\n networkType: 'evm',\n rpcUrl: 'https://rpc.hyperliquid.xyz/evm',\n explorerUrl: 'https://hyperevmscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xb88339CB7199b77E23DB6E890353E22632Ba630f',\n decimals: 6,\n name: 'USDC', // HyperEVM uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xb88339CB7199b77E23DB6E890353E22632Ba630f',\n decimals: 6,\n name: 'USDC', // HyperEVM uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n unichain: {\n chainId: 130,\n chainIdHex: '0x82',\n name: 'unichain',\n displayName: 'Unichain',\n networkType: 'evm',\n rpcUrl: 'https://unichain-rpc.publicnode.com',\n explorerUrl: 'https://uniscan.xyz',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x078d782b760474a361dda0af3839290b0ef57ad6',\n decimals: 6,\n name: 'USDC', // Unichain uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x078d782b760474a361dda0af3839290b0ef57ad6',\n decimals: 6,\n name: 'USDC', // Unichain uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n monad: {\n chainId: 143,\n chainIdHex: '0x8f',\n name: 'monad',\n displayName: 'Monad',\n networkType: 'evm',\n rpcUrl: 'https://rpc.monad.xyz',\n explorerUrl: 'https://monad.socialscan.io',\n nativeCurrency: {\n name: 'Monad',\n symbol: 'MON',\n decimals: 18,\n },\n usdc: {\n address: '0x754704bc059f8c67012fed69bc8a327a5aafb603',\n decimals: 6,\n name: 'USDC', // Monad uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x754704bc059f8c67012fed69bc8a327a5aafb603',\n decimals: 6,\n name: 'USDC', // Monad uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n usdt: {\n address: '0xe7cd86e13AC4309349F30B3435a9d337750fC82D',\n decimals: 6,\n name: 'USD\\u20AE0', // USD₮0 (USDT0 omnichain via LayerZero)\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n bsc: {\n chainId: 56,\n chainIdHex: '0x38',\n name: 'bsc',\n displayName: 'BNB Smart Chain',\n networkType: 'evm',\n rpcUrl: 'https://binance.llamarpc.com',\n explorerUrl: 'https://bscscan.com',\n nativeCurrency: {\n name: 'Binance Coin',\n symbol: 'BNB',\n decimals: 18,\n },\n usdc: {\n // Binance-Peg USDC — 18 decimals, NOT the 6 every other chain uses.\n address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n // Disabled on purpose: Binance-Peg USDC does not implement ERC-3009\n // `transferWithAuthorization`, so the exact scheme cannot settle it. The\n // entry exists so the 18-decimal figure is on record — assuming the usual\n // 6 here mis-prices a payment by 12 orders of magnitude.\n enabled: false,\n },\n },\n\n scroll: {\n chainId: 534352,\n chainIdHex: '0x82750',\n name: 'scroll',\n displayName: 'Scroll',\n networkType: 'evm',\n rpcUrl: 'https://rpc.scroll.io',\n explorerUrl: 'https://scrollscan.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'skale-base': {\n chainId: 1187947933,\n chainIdHex: '0x46cea59d',\n name: 'skale-base',\n displayName: 'SKALE Base',\n networkType: 'evm',\n rpcUrl: 'https://skale-base.skalenodes.com/v1/base',\n explorerUrl: 'https://skale-base-explorer.skalenodes.com',\n nativeCurrency: {\n name: 'CREDIT',\n symbol: 'CREDIT',\n decimals: 18,\n },\n usdc: {\n address: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'skale-base-sepolia': {\n chainId: 324705682,\n chainIdHex: '0x135a9d92',\n name: 'skale-base-sepolia',\n displayName: 'SKALE Base Sepolia',\n networkType: 'evm',\n rpcUrl: 'https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha',\n explorerUrl: 'https://base-sepolia-testnet-explorer.skalenodes.com',\n nativeCurrency: {\n name: 'CREDIT',\n symbol: 'CREDIT',\n decimals: 18,\n },\n usdc: {\n address: '0x2e08028E3C4c2356572E096d8EF835cD5C6030bD',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x2e08028E3C4c2356572E096d8EF835cD5C6030bD',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // Robinhood Chain (Arbitrum Orbit L2). NOTE: there is NO USDC on this chain -\n // the settlement stablecoin is Paxos USDG (Global Dollar). The `usdc` field\n // below carries USDG for interface compatibility (same pattern as XRPL's native\n // asset), and `tokens.usdg` is the canonical entry.\n // CRITICAL: USDG's on-chain version() getter REVERTS, so the EIP-712 domain\n // { name: 'Global Dollar', version: '1' } can NEVER be resolved on-chain and\n // MUST come from this config (mirrored into PaymentRequirements.extra by callers).\n robinhood: {\n chainId: 4663,\n chainIdHex: '0x1237',\n name: 'robinhood',\n displayName: 'Robinhood Chain',\n networkType: 'evm',\n rpcUrl: 'https://rpc.mainnet.chain.robinhood.com',\n explorerUrl: 'https://robinhoodchain.blockscout.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168', // Paxos USDG (no USDC on this chain)\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n tokens: {\n usdg: {\n address: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168',\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'robinhood-testnet': {\n chainId: 46630,\n chainIdHex: '0xb626',\n name: 'robinhood-testnet',\n displayName: 'Robinhood Chain Testnet',\n networkType: 'evm',\n rpcUrl: 'https://rpc.testnet.chain.robinhood.com',\n explorerUrl: 'https://explorer.testnet.chain.robinhood.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x7E955252E15c84f5768B83c41a71F9eba181802F', // Paxos USDG testnet (no USDC on this chain)\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n tokens: {\n usdg: {\n address: '0x7E955252E15c84f5768B83c41a71F9eba181802F',\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // Arc testnet (Circle). The stablecoin IS the chain's native asset, so the SAME\n // balance is readable at TWO precisions:\n // - native / gas, via eth_getBalance and EIP-1559 fees: 18 decimals\n // - ERC-20 interface, via balanceOf and transferWithAuthorization: 6 decimals\n // (the ERC-20 view is floor(native / 10^12))\n // An x402 payment is an EIP-3009 authorization against the ERC-20 interface, so\n // its `value` is ALWAYS in the 6 of `tokens.usdc.decimals`. Scaling a price with\n // `nativeCurrency.decimals` instead charges 10^12 times the amount: $0.01 would\n // be signed as 10000000000000000 units, i.e. 10 billion USDC. `nativeCurrency`\n // below is correct where it is actually used -- the wallet_addEthereumChain\n // params -- and must never reach `parseUnits` for a payment.\n // Pinned by src/arc-testnet.test.ts.\n //\n // Mainnet (5042) and testnet (5042002) were verified independently against\n // their official RPCs on 2026-09-16. EURC domains checked on 2026-09-17; funded EURC payments settled on Arc mainnet on\n // 2026-09-22 (x402 v1/v2, docs/networks/arc.md); testnet pending.\n arc: {\n chainId: 5042,\n chainIdHex: '0x13b2',\n name: 'arc',\n displayName: 'Arc',\n networkType: 'evm',\n rpcUrl: 'https://rpc.mainnet.arc.io',\n explorerUrl: 'https://explorer.arc.io',\n nativeCurrency: {\n name: 'USD Coin',\n symbol: 'USDC',\n decimals: 18, // gas precision ONLY -- never the scale of a payment\n },\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6, // ERC-20 interface, which is what an EIP-3009 value is denominated in\n name: 'USDC', // on-chain name(); must match the EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6,\n name: 'USDC',\n version: '2',\n },\n eurc: {\n address: '0xbEf5f6d51CB62b58e6A8f77868681825C6fe21c1',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'arc-testnet': {\n chainId: 5042002,\n chainIdHex: '0x4cef52',\n name: 'arc-testnet',\n displayName: 'Arc Testnet',\n networkType: 'evm',\n rpcUrl: 'https://rpc.testnet.arc.io',\n explorerUrl: 'https://explorer.testnet.arc.io',\n nativeCurrency: {\n name: 'USD Coin',\n symbol: 'USDC',\n decimals: 18, // gas precision ONLY -- never the scale of a payment\n },\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6, // ERC-20 interface, which is what an EIP-3009 value is denominated in\n name: 'USDC', // on-chain name(); must match the EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6,\n name: 'USDC',\n version: '2',\n },\n eurc: {\n address: '0x89B50855Aa3bE2F677cD6303Cec089B5F319D72a',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // SVM CHAINS (2 networks) - Solana Virtual Machine\n // ============================================================================\n\n solana: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'solana',\n displayName: 'Solana',\n networkType: 'svm',\n rpcUrl: 'https://api.mainnet-beta.solana.com',\n explorerUrl: 'https://solscan.io',\n nativeCurrency: {\n name: 'Solana',\n symbol: 'SOL',\n decimals: 9,\n },\n usdc: {\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC SPL token mint\n decimals: 6,\n name: 'USD Coin',\n version: '1',\n },\n tokens: {\n usdc: {\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC SPL token mint\n decimals: 6,\n name: 'USD Coin',\n version: '1',\n },\n ausd: {\n address: 'AUSD1jCcCyPLybk1YnvPWsHQSrZ46dxwoMniN4N2UEB9', // AUSD Token2022 mint\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n fogo: {\n chainId: 0, // Non-EVM (SVM)\n chainIdHex: '0x0',\n name: 'fogo',\n displayName: 'Fogo',\n networkType: 'svm',\n rpcUrl: 'https://rpc.fogo.nightly.app/',\n explorerUrl: 'https://explorer.fogo.nightly.app',\n nativeCurrency: {\n name: 'Fogo',\n symbol: 'FOGO',\n decimals: 9,\n },\n usdc: {\n address: 'uSd2czE61Evaf76RNbq4KPpXnkiL3irdzgLFUMe3NoG', // Fogo USDC mint\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // STELLAR (1 network)\n // ============================================================================\n\n stellar: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'stellar',\n displayName: 'Stellar',\n networkType: 'stellar',\n rpcUrl: 'https://horizon.stellar.org',\n explorerUrl: 'https://stellar.expert/explorer/public',\n nativeCurrency: {\n name: 'Lumens',\n symbol: 'XLM',\n decimals: 7, // Stellar uses 7 decimals (stroops)\n },\n usdc: {\n address: 'CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75', // Soroban Asset Contract\n decimals: 7, // Stellar USDC uses 7 decimals\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // NEAR (1 network) - Uses NEP-366 meta-transactions\n // ============================================================================\n\n near: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'near',\n displayName: 'NEAR Protocol',\n networkType: 'near',\n rpcUrl: 'https://rpc.mainnet.near.org',\n explorerUrl: 'https://nearblocks.io',\n nativeCurrency: {\n name: 'NEAR',\n symbol: 'NEAR',\n decimals: 24, // NEAR uses 24 decimals (yoctoNEAR)\n },\n usdc: {\n address: '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1', // Native Circle USDC\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true, // NEP-366 meta-transactions supported\n },\n },\n\n // ============================================================================\n // ALGORAND (2 networks) - Uses ASA transfers with atomic transaction groups\n // ============================================================================\n\n algorand: {\n chainId: 0, // Non-EVM (Algorand uses genesis hash for network identification)\n chainIdHex: '0x0',\n name: 'algorand',\n displayName: 'Algorand',\n networkType: 'algorand',\n rpcUrl: 'https://mainnet-api.algonode.cloud',\n explorerUrl: 'https://allo.info',\n nativeCurrency: {\n name: 'Algo',\n symbol: 'ALGO',\n decimals: 6, // Algorand uses 6 decimals (microAlgos)\n },\n usdc: {\n address: '31566704', // USDC ASA ID on Algorand mainnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '31566704', // USDC ASA ID on Algorand mainnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'algorand-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'algorand-testnet',\n displayName: 'Algorand Testnet',\n networkType: 'algorand',\n rpcUrl: 'https://testnet-api.algonode.cloud',\n explorerUrl: 'https://testnet.allo.info',\n nativeCurrency: {\n name: 'Algo',\n symbol: 'ALGO',\n decimals: 6,\n },\n usdc: {\n address: '10458941', // USDC ASA ID on Algorand testnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '10458941', // USDC ASA ID on Algorand testnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // SUI (2 networks) - Uses sponsored transactions (facilitator pays gas)\n // ============================================================================\n\n sui: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'sui',\n displayName: 'Sui',\n networkType: 'sui',\n rpcUrl: 'https://fullnode.mainnet.sui.io:443',\n explorerUrl: 'https://suiscan.xyz/mainnet',\n nativeCurrency: {\n name: 'Sui',\n symbol: 'SUI',\n decimals: 9,\n },\n usdc: {\n // USDC coin type on Sui mainnet\n address: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n ausd: {\n // AUSD (Agora USD) coin type on Sui mainnet\n address: '0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD',\n decimals: 6,\n name: 'AUSD',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'sui-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'sui-testnet',\n displayName: 'Sui Testnet',\n networkType: 'sui',\n rpcUrl: 'https://fullnode.testnet.sui.io:443',\n explorerUrl: 'https://suiscan.xyz/testnet',\n nativeCurrency: {\n name: 'Sui',\n symbol: 'SUI',\n decimals: 9,\n },\n usdc: {\n // USDC coin type on Sui testnet\n address: '0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // XRPL (2 networks) - XRP Ledger, native XRP via pre-signed Payment blobs\n // ============================================================================\n\n // Named `xrpl`, which is the only spelling the facilitator puts on the wire\n // (x402-rs/src/network.rs:189). `xrpl-mainnet` still resolves, as an alias.\n xrpl: {\n chainId: 0, // Non-EVM (XRPL uses network id strings, no numeric chain ID)\n chainIdHex: '0x0',\n name: 'xrpl',\n displayName: 'XRP Ledger',\n networkType: 'xrpl',\n rpcUrl: 'https://xrplcluster.com',\n explorerUrl: 'https://livenet.xrpl.org',\n nativeCurrency: {\n name: 'XRP',\n symbol: 'XRP',\n decimals: 6, // XRPL uses 6 decimals (drops); 1 XRP = 1,000,000 drops\n },\n // XRPL settles in native XRP - there is no USDC/token contract.\n // The `usdc` field describes the native asset for interface compatibility.\n // `usdPegged: false` is what stops that compatibility shim from being read\n // as a price: the key says usdc, the value is XRP, and a caller who writes\n // \"10.00\" means ten dollars. See TokenConfig.usdPegged.\n usdc: {\n address: 'XRP', // Native asset - no token contract\n decimals: 6,\n name: 'XRP',\n version: '1',\n usdPegged: false,\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'xrpl-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'xrpl-testnet',\n displayName: 'XRP Ledger Testnet',\n networkType: 'xrpl',\n rpcUrl: 'https://s.altnet.rippletest.net:51234',\n explorerUrl: 'https://testnet.xrpl.org',\n nativeCurrency: {\n name: 'XRP',\n symbol: 'XRP',\n decimals: 6,\n },\n // XRPL settles in native XRP - there is no USDC/token contract.\n usdc: {\n address: 'XRP', // Native asset - no token contract\n decimals: 6,\n name: 'XRP',\n version: '1',\n usdPegged: false,\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n};\n\n/**\n * Alternate spellings that resolve to a registry entry without becoming one.\n *\n * A caller may WRITE these; the SDK never puts one on the wire, and they are\n * not separate networks, so counts and listings stay honest. The facilitator\n * keeps exactly this distinction: its `FromStr` takes `xrpl-mainnet` while\n * everything it publishes says `xrpl`, and the comment there calls that\n * spelling \"right for a lookup and wrong for a wire format\"\n * (`x402-rs/src/network.rs:251,189,719`).\n *\n * Mirrors `_NETWORK_ALIASES` in the Python SDK (`networks/base.py`).\n */\nexport const CHAIN_ALIASES: Record<string, string> = {\n hedera: 'hedera:mainnet',\n 'hedera-testnet': 'hedera:testnet',\n // Execution Market's and Karmakadabra's keys for SKALE Base.\n skale: 'skale-base',\n 'skale-testnet': 'skale-base-sepolia',\n // Renamed in 2.85.0: the facilitator advertises the mainnet as `xrpl`.\n 'xrpl-mainnet': 'xrpl',\n};\n\n/**\n * Default chain for new users\n */\nexport const DEFAULT_CHAIN = 'base';\n\n/**\n * Get chain config by chain ID\n */\nexport function getChainById(chainId: number): ChainConfig | undefined {\n return Object.values(SUPPORTED_CHAINS).find(chain => chain.chainId === chainId);\n}\n\n/**\n * Get chain config by name (case-insensitive)\n */\nexport function getChainByName(name: string): ChainConfig | undefined {\n const key = name.toLowerCase();\n return SUPPORTED_CHAINS[key] ?? SUPPORTED_CHAINS[CHAIN_ALIASES[key] ?? ''];\n}\n\n/**\n * Check if a chain is supported\n */\nexport function isChainSupported(chainIdOrName: number | string): boolean {\n if (typeof chainIdOrName === 'number') {\n return Object.values(SUPPORTED_CHAINS).some(chain => chain.chainId === chainIdOrName);\n }\n return getChainByName(chainIdOrName) !== undefined;\n}\n\n/**\n * Get list of enabled chains\n */\nexport function getEnabledChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(chain => chain.x402.enabled);\n}\n\n/**\n * Get list of chains by network type\n */\nexport function getChainsByNetworkType(networkType: NetworkType): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === networkType && chain.x402.enabled\n );\n}\n\n/**\n * Get all EVM chain IDs (for wallet_switchEthereumChain)\n */\nexport function getEVMChainIds(): number[] {\n return getChainsByNetworkType('evm').map(chain => chain.chainId);\n}\n\n/**\n * Get list of SVM chains (Solana, Fogo)\n */\nexport function getSVMChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'svm' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is SVM-based (Solana Virtual Machine)\n */\nexport function isSVMChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'svm';\n}\n\n/**\n * Get list of Sui chains\n */\nexport function getSuiChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'sui' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is Sui-based\n */\nexport function isSuiChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'sui';\n}\n\n/**\n * Get network type from chain name\n */\nexport function getNetworkType(chainName: string): NetworkType | undefined {\n const chain = getChainByName(chainName);\n return chain?.networkType;\n}\n\n/**\n * Format transaction URL for block explorer\n */\nexport function getExplorerTxUrl(chainName: string, txHash: string): string | null {\n const chain = getChainByName(chainName);\n if (!chain) return null;\n\n switch (chain.networkType) {\n case 'evm':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'svm':\n case 'solana': // @deprecated\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'stellar':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'near':\n return `${chain.explorerUrl}/txns/${txHash}`;\n case 'algorand':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'sui':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'hedera':\n return `${chain.explorerUrl}/transaction/${txHash.replace(/^(0\\.0\\.\\d+)@(\\d+)\\.(\\d+)$/, '$1-$2-$3')}`;\n case 'xrpl':\n return `${chain.explorerUrl}/transactions/${txHash}`;\n default:\n return null;\n }\n}\n\n/**\n * Format address URL for block explorer\n */\nexport function getExplorerAddressUrl(chainName: string, address: string): string | null {\n const chain = getChainByName(chainName);\n if (!chain) return null;\n\n switch (chain.networkType) {\n case 'evm':\n return `${chain.explorerUrl}/address/${address}`;\n case 'svm':\n case 'solana': // @deprecated\n return `${chain.explorerUrl}/account/${address}`;\n case 'stellar':\n return `${chain.explorerUrl}/account/${address}`;\n case 'near':\n return `${chain.explorerUrl}/address/${address}`;\n case 'algorand':\n return `${chain.explorerUrl}/account/${address}`;\n case 'sui':\n return `${chain.explorerUrl}/account/${address}`;\n case 'hedera':\n return `${chain.explorerUrl}/account/${address}`;\n case 'xrpl':\n return `${chain.explorerUrl}/accounts/${address}`;\n default:\n return null;\n }\n}\n\n/**\n * Get list of Algorand chains\n */\nexport function getAlgorandChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'algorand' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is Algorand-based\n */\nexport function isAlgorandChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'algorand';\n}\n\n/**\n * Get list of XRPL chains (XRP Ledger mainnet/testnet)\n */\nexport function getXRPLChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'xrpl' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is XRPL-based (XRP Ledger)\n */\nexport function isXRPLChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'xrpl';\n}\n\n// ============================================================================\n// MULTI-TOKEN SUPPORT FUNCTIONS\n// ============================================================================\n\n/**\n * Get token configuration for a specific chain and token type\n * Falls back to USDC config if token not found (for backward compatibility)\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns Token configuration or undefined if chain not found\n */\nexport function getTokenConfig(\n chainName: string,\n tokenType: TokenType = 'usdc'\n): TokenConfig | undefined {\n const chain = getChainByName(chainName);\n if (!chain) return undefined;\n\n // Try to get from tokens map first (new multi-token support)\n if (chain.tokens && chain.tokens[tokenType]) {\n return chain.tokens[tokenType];\n }\n\n // Fall back to usdc config for backward compatibility\n if (tokenType === 'usdc') {\n return chain.usdc;\n }\n\n return undefined;\n}\n\n/**\n * Whether a price written in dollars can be scaled into this token's base\n * units. Absent `usdPegged` means yes, so every stablecoin keeps its behaviour.\n *\n * @param token - Token configuration, or undefined\n * @returns True when one whole unit of the token is one dollar\n */\nexport function isUsdPegged(token: TokenConfig | undefined): boolean {\n return token?.usdPegged !== false;\n}\n\n/**\n * The sentence for refusing to price a network in dollars.\n *\n * Refusing without saying where to look only moves the dead end one layer up,\n * so this names the asset, states what the old code would have charged, and\n * points at the one place that lists the alternatives. Same shape as the Python\n * SDK's `NetworkConfig.usd_conversion_error()` (`networks/base.py:158`, 0.77.0)\n * so a team hitting this in either language reads the same explanation.\n *\n * @param chainName - Chain the price was written for\n * @param token - The settlement token that carries no dollar peg\n * @returns Message naming the asset and the way out\n */\nexport function usdConversionError(chainName: string, token: TokenConfig): string {\n const symbol = token.name || token.address;\n return (\n `${chainName} settles in ${symbol}, which is not pegged to the dollar, so an ` +\n `amount written in USD cannot be converted with its ${token.decimals} decimals: ` +\n `$1.00 would be charged as 1 ${symbol}. Name a dollar-pegged token this ` +\n `network's facilitator settles (GET /supported lists them; on XRPL that is the ` +\n `Circle USDC issued by rGm7WCVp9gb4jZHWTEtGUr4dd74z2XuWhE) and register it under ` +\n `the chain's \\`tokens\\`, or price the call in ${symbol} units yourself.`\n );\n}\n\n/**\n * Find which token of a chain a contract address belongs to.\n *\n * The signed payload carries the token *address*, but a server that accepts\n * several stablecoins on the same chain needs the symbol, the decimals and the\n * EIP-712 domain to rebuild the payment requirements. This resolves the address\n * back to the registry entry so that metadata can travel with the payment.\n *\n * @param chainName - Chain name (e.g., 'optimism')\n * @param address - Token contract address (case-insensitive on EVM)\n * @returns The token type and its config, or undefined if the address is not in the registry\n */\nexport function getTokenByAddress(\n chainName: string,\n address: string\n): { tokenType: TokenType; config: TokenConfig } | undefined {\n const chain = getChainByName(chainName);\n if (!chain || !address) return undefined;\n\n const wanted = address.startsWith('0x') ? address.toLowerCase() : address;\n const matches = (candidate: string): boolean =>\n (candidate.startsWith('0x') ? candidate.toLowerCase() : candidate) === wanted;\n\n if (chain.tokens) {\n for (const [tokenType, config] of Object.entries(chain.tokens)) {\n if (config && matches(config.address)) {\n return { tokenType: tokenType as TokenType, config };\n }\n }\n }\n\n if (chain.usdc && matches(chain.usdc.address)) {\n return { tokenType: 'usdc', config: chain.usdc };\n }\n\n return undefined;\n}\n\n/**\n * Get list of supported tokens for a chain\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @returns Array of supported token types, or empty array if chain not found\n */\nexport function getSupportedTokens(chainName: string): TokenType[] {\n const chain = getChainByName(chainName);\n if (!chain) return [];\n\n // If tokens map exists, return its keys\n if (chain.tokens) {\n return Object.keys(chain.tokens) as TokenType[];\n }\n\n // Default to just USDC for chains without explicit tokens map\n return ['usdc'];\n}\n\n/**\n * Check if a token is supported on a specific chain\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns true if token is supported on the chain\n */\nexport function isTokenSupported(chainName: string, tokenType: TokenType): boolean {\n const chain = getChainByName(chainName);\n if (!chain) return false;\n\n // Check tokens map\n if (chain.tokens && chain.tokens[tokenType]) {\n return true;\n }\n\n // USDC is always supported (backward compatibility)\n if (tokenType === 'usdc') {\n return true;\n }\n\n return false;\n}\n\n/**\n * Get all chains that support a specific token\n *\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns Array of chain configs that support the token\n */\nexport function getChainsByToken(tokenType: TokenType): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(chain => {\n if (!chain.x402.enabled) return false;\n if (chain.tokens && chain.tokens[tokenType]) return true;\n if (tokenType === 'usdc') return true; // USDC is universal\n return false;\n });\n}\n","/**\n * uvd-x402-sdk - Type Definitions\n *\n * Core TypeScript interfaces for the x402 payment SDK.\n * These types define the contract between the SDK and consuming applications.\n */\n\n// Type-only, so it is erased at compile time and no runtime cycle exists between\n// this module and `policy.ts` (which imports `X402Error` from here as a value).\nimport type { AdvertisedQuote, PolicyApproval, PurchasePolicy } from '../policy';\n\n// ============================================================================\n// CHAIN CONFIGURATION TYPES\n// ============================================================================\n\n/**\n * Network type categorization\n * - 'evm': Ethereum Virtual Machine compatible chains (use EIP-712)\n * - 'svm': Solana Virtual Machine chains (Solana, Fogo) (use SPL tokens)\n * - 'stellar': Stellar network (use Soroban)\n * - 'near': NEAR Protocol (use NEP-366)\n * - 'algorand': Algorand network (use ASA transfers with atomic transactions)\n * - 'sui': Sui blockchain (use sponsored transactions)\n * - 'xrpl': XRP Ledger (use pre-signed Payment transaction blobs)\n *\n * @deprecated 'solana' type is deprecated, use 'svm' instead\n */\nexport type NetworkType = 'evm' | 'svm' | 'solana' | 'stellar' | 'near' | 'algorand' | 'sui' | 'xrpl' | 'hedera';\n\n/**\n * Supported x402 payment schemes\n * - 'exact': Standard one-shot payment (default)\n * - 'escrow': Escrow-based payment with verify/settle/refund\n * - 'commerce': Commerce alias for escrow (marketplace integrations)\n */\nexport type X402Scheme = 'exact' | 'escrow' | 'commerce';\n\n/**\n * Supported stablecoin token types\n * - usdc: USD Coin (Circle) - 6 decimals\n * - eurc: Euro Coin (Circle) - 6 decimals\n * - ausd: Agora USD (Agora Finance) - 6 decimals\n * - pyusd: PayPal USD (PayPal/Paxos) - 6 decimals\n * - usdt: Tether USD (USDT0 omnichain via LayerZero) - 6 decimals\n * - usdg: Global Dollar (Paxos) - 6 decimals; settlement stablecoin on Robinhood Chain\n */\nexport type TokenType = 'usdc' | 'eurc' | 'ausd' | 'pyusd' | 'usdt' | 'usdg' | 'hbar';\n\n/**\n * Token configuration for EIP-712 signing and transfers\n */\nexport interface TokenConfig {\n /** Contract/mint address */\n address: string;\n /** Token decimals (6 for all supported stablecoins) */\n decimals: number;\n /** Token name for EIP-712 domain (e.g., \"USD Coin\" or \"USDC\") */\n name: string;\n /** Token version for EIP-712 domain */\n version: string;\n /**\n * Whether one whole unit of this token IS one dollar.\n *\n * Absent means yes, so every stablecoin entry in the registry keeps the\n * behaviour it had. It is `false` for EURC (euros), native XRP and HBAR.\n *\n * **The distinction is unit, not scale.** `decimals` already handles scale --\n * BSC USDC has 18 of them and prices correctly. But scaling a price by the\n * decimals only turns dollars into base units when one whole unit is one\n * dollar. XRP has six real decimals and is still not a dollar, so\n * `$1.00 -> 10**6` charges **1 XRP**, which is whatever XRP happens to cost.\n * Six decimals of XRP are still XRP.\n *\n * The SDK refuses to price in USD against a token carrying `false` rather\n * than converting at a rate nobody agreed to. Mirrors `NetworkConfig\n * .usd_pegged` in the Python SDK (`networks/base.py:129`, 0.77.0).\n */\n usdPegged?: boolean;\n}\n\n/**\n * USDC token configuration for a specific chain\n * @deprecated Use TokenConfig instead. This is kept for backward compatibility.\n */\nexport interface USDCConfig {\n /** Contract/mint address */\n address: string;\n /** Token decimals (6 for most chains, 7 for Stellar) */\n decimals: number;\n /** Token name for EIP-712 domain (e.g., \"USD Coin\" or \"USDC\") */\n name: string;\n /** Token version for EIP-712 domain */\n version: string;\n /**\n * Whether one whole unit of this token IS one dollar. Absent means yes.\n *\n * See {@link TokenConfig.usdPegged}. It matters here because this field is\n * also where a chain that settles in its own native asset describes that\n * asset -- XRPL keeps native XRP under the key `usdc`, so the key promises a\n * dollar the value does not deliver.\n */\n usdPegged?: boolean;\n}\n\n/**\n * Native currency configuration\n */\nexport interface NativeCurrency {\n name: string;\n symbol: string;\n decimals: number;\n}\n\n/**\n * Complete chain configuration\n */\nexport interface ChainConfig {\n /** Numeric chain ID (0 for non-EVM chains) */\n chainId: number;\n /** Hex-encoded chain ID for wallet_switchEthereumChain */\n chainIdHex: string;\n /** Internal chain identifier (e.g., 'base', 'solana') */\n name: string;\n /** Human-readable display name */\n displayName: string;\n /** Network type for routing */\n networkType: NetworkType;\n /** Primary RPC endpoint URL */\n rpcUrl: string;\n /** Block explorer base URL */\n explorerUrl: string;\n /** Native currency info */\n nativeCurrency: NativeCurrency;\n /** USDC token configuration */\n usdc: USDCConfig;\n /**\n * Multi-token configurations (EVM chains only)\n * Maps token type to its configuration for this chain.\n * Not all tokens are available on all chains.\n */\n tokens?: Partial<Record<TokenType, TokenConfig>>;\n /** x402 facilitator configuration */\n x402: {\n facilitatorUrl: string;\n enabled: boolean;\n };\n}\n\n// ============================================================================\n// WALLET TYPES\n// ============================================================================\n\n/**\n * Current wallet connection state\n */\nexport interface WalletState {\n /** Whether a wallet is currently connected */\n connected: boolean;\n /** Connected wallet address (null if not connected) */\n address: string | null;\n /** Current chain ID (null for non-EVM or disconnected) */\n chainId: number | null;\n /** Current network name */\n network: string | null;\n /** Network type of connected wallet */\n networkType: NetworkType | null;\n /** USDC balance on current chain (null if unknown) */\n balance: string | null;\n}\n\n/**\n * Wallet adapter interface for different wallet types\n */\nexport interface WalletAdapter {\n /** Unique identifier for this wallet type */\n readonly id: string;\n /** Display name */\n readonly name: string;\n /** Network type this adapter supports */\n readonly networkType: NetworkType;\n\n /** Check if this wallet is available/installed */\n isAvailable(): boolean;\n\n /** Connect to the wallet */\n connect(chainName?: string): Promise<string>;\n\n /** Disconnect from the wallet */\n disconnect(): Promise<void>;\n\n /** Switch to a different chain (EVM only) */\n switchChain?(chainName: string): Promise<void>;\n\n /**\n * Sign a payment payload\n * For EVM chains, supports multi-token via paymentInfo.tokenType\n */\n signPayment(paymentInfo: PaymentInfo, chainConfig: ChainConfig): Promise<string>;\n\n /**\n * Check token balance (defaults to USDC for backward compatibility)\n * EVM providers may accept optional tokenType parameter\n */\n getBalance(chainConfig: ChainConfig, tokenType?: TokenType): Promise<string>;\n\n /** Get current address */\n getAddress(): string | null;\n\n /** Get current chain ID (EVM only) */\n getChainId?(): number | null;\n}\n\n/**\n * EIP-712 domain for typed data signing\n */\nexport interface EIP712Domain {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: string;\n}\n\n/**\n * EIP-712 type definitions\n */\nexport interface EIP712Types {\n [typeName: string]: Array<{ name: string; type: string }>;\n}\n\n// ============================================================================\n// PAYMENT TYPES\n// ============================================================================\n\n/**\n * Payment information returned by backend on 402 response\n */\nexport interface PaymentInfo {\n /** Exact v2 offer/resource, required by native Hedera. */\n accepted?: Record<string, unknown>;\n resource?: { url: string; description?: string; mimeType?: string };\n extensions?: Record<string, unknown>;\n /** Default recipient address */\n recipient: string;\n /** Network-specific recipient addresses */\n recipients?: {\n evm?: string;\n solana?: string;\n near?: string;\n stellar?: string;\n algorand?: string;\n sui?: string;\n xrpl?: string;\n hedera?: string;\n };\n /** Facilitator address (for Solana fee payer) */\n facilitator?: string;\n /**\n * Amount in whole units of the settlement asset (e.g., \"10.00\").\n *\n * For dollar-pegged tokens that is dollars; for EURC it is **euros**.\n * On XRPL it is **XRP**, because XRPL settles in its own native asset:\n * the provider converts this to drops (6 decimals) and bills whole XRP\n * (`src/providers/xrpl/index.ts`). This used to be documented as USD, which\n * made the type and its only XRPL consumer disagree about the unit -- and the\n * consumer won, so a \"10.00\" written as ten dollars left as ten XRP. The SDK\n * now refuses to build a dollar price for an asset with no dollar peg rather\n * than let the two readings meet on the wire; see\n * {@link TokenConfig.usdPegged}.\n */\n amount: string;\n /** Token symbol (usually \"USDC\") */\n token?: string;\n /**\n * Token type for multi-token support\n * Defaults to 'usdc' if not specified for backward compatibility\n */\n tokenType?: TokenType;\n /** Network hint from backend */\n network?: string;\n /** Supported chain IDs */\n supportedChains?: number[];\n /**\n * Envelope version the resource asked for, as read off its own 402.\n *\n * This is what makes the client's `x402Version: 'auto'` mean something: the\n * buyer loop reads the version out of the challenge and hands it down here,\n * so the header is built in the shape the server said it accepts. Left\n * undefined by callers who build a payment by hand -- then the client config\n * decides, exactly as before.\n */\n x402Version?: X402Version;\n /**\n * Seconds this EIP-3009 authorization stays settleable\n * (`validBefore = now + validitySeconds`).\n *\n * Set it when the seller settles **async** -- verify, hand over the resource,\n * settle afterwards -- and needs the authorization alive for longer than the\n * default. Left undefined, `X402ClientConfig.validitySeconds` decides, and\n * failing that `DEFAULT_VALIDITY_SECONDS` (300 s, the timeout this SDK's own\n * seller side announces by default). `X402Client.fetch()` fills it from the\n * seller's `maxTimeoutSeconds` when the 402 declares one.\n *\n * Must be a whole number of seconds between 1 and `MAX_VALIDITY_SECONDS`\n * (3600); anything else is refused with `INVALID_CONFIG` before anything is\n * signed. The ceiling is here because this type is shaped like a parsed 402:\n * a caller that hands a seller's response straight to `createPayment` would\n * otherwise let the SELLER decide how long the payer's authorization stays\n * claimable. The facilitator also keeps a 6 s clock-skew grace, so the payer\n * really has `validitySeconds - 6` to sign.\n */\n validitySeconds?: number;\n}\n\n/**\n * One payment option read off a resource's `402`, normalised.\n *\n * The 402 body speaks two dialects -- v1 spells the price `maxAmountRequired`\n * and names the chain `base`, v2 spells it `amount` and names it `eip155:8453`\n * -- and a buyer that only learned one of them silently ignores half the\n * offers. This is the shape after both have been read.\n */\nexport interface X402PaymentOffer {\n /** Network exactly as the 402 wrote it (plain name or CAIP-2). */\n network: string;\n /** SDK chain name the network resolved to, or null when unknown. */\n chainName: string | null;\n /** Token contract address the resource wants paid, when it named one. */\n asset?: string;\n /** Price in the token's own atomic units. */\n amount: string;\n /** Decimals used to read `amount`. */\n decimals: number;\n /** Recipient of the payment. */\n payTo: string;\n /**\n * The seller's `maxTimeoutSeconds`, when its 402 entry declared a finite number.\n *\n * `X402Client.fetch()` signs this window -- clamped to `1..MAX_VALIDITY_SECONDS`\n * -- instead of the client's own, because the seller is the one party that\n * knows how long its settlement takes. Undefined when the entry declared none,\n * or declared something that is not a number.\n */\n maxTimeoutSeconds?: number;\n /** The accept object verbatim -- echoed back for v2. */\n raw: Record<string, unknown>;\n}\n\n/**\n * Options for {@link X402Client.fetch} -- the buyer loop.\n */\nexport interface X402FetchOptions {\n /** HTTP method for both the probe and the paid retry (default `GET`). */\n method?: string;\n /**\n * Hard ceiling in token units (e.g. `'0.05'`). A 402 that asks for more\n * throws instead of signing. Undefined = no ceiling, which means paying\n * whatever an untrusted resource asks: discouraged.\n */\n maxAmount?: string;\n /** Token to pay with (default `usdc`). */\n tokenType?: TokenType;\n /** Override the default cheapest-offer selection. */\n select?: (offers: X402PaymentOffer[]) => X402PaymentOffer | null | undefined;\n /** Passed through to both requests (`headers`, `body`, `signal`, ...). */\n init?: RequestInit;\n /** Injectable `fetch` (tests, or a runtime without a global one). */\n fetchImpl?: typeof globalThis.fetch;\n /**\n * What a catalog listing advertised, when the caller read one.\n *\n * The comparison NEVER decides anything -- a seller repricing inside a policy\n * the operator already authorised is ordinary commerce -- but handing it over\n * gets the divergence reported on the approval instead of having to diff the\n * two by hand. See `PolicyApproval.versusQuote`.\n */\n advertised?: AdvertisedQuote;\n /**\n * Called once the paid retry came back with something other than a 402, i.e.\n * the seller accepted the payment.\n *\n * This is where a caller calls `client.policy.recordSpend(...)`. Evaluating\n * deliberately does not spend: signing can fail and a settlement can be\n * refused, and a cumulative limit that counted attempts would lock a caller\n * out of money it never spent. Nothing here is automatic, so a caller that\n * wants a cumulative limit to mean something has to say so.\n */\n onPaid?: (approval: PolicyApproval) => void;\n}\n\n/**\n * Simple payment request from application\n */\nexport interface PaymentRequest {\n /** Amount in USDC (e.g., \"10.00\") */\n amount: string;\n /** Override recipient address (optional) */\n recipient?: string;\n /** Application-specific metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * x402 payment header names\n *\n * - 'X-PAYMENT': v1 header name (default, most compatible)\n * - 'PAYMENT-SIGNATURE': v2 header name (newer standard)\n *\n * Both headers use the same base64-encoded JSON payload format.\n * The facilitator accepts both headers.\n */\nexport type X402HeaderName = 'X-PAYMENT' | 'PAYMENT-SIGNATURE';\n\n/**\n * Payment headers object containing both v1 and v2 header formats\n */\nexport interface PaymentHeaders {\n /** v1 header: X-PAYMENT */\n 'X-PAYMENT': string;\n /** v2 header: PAYMENT-SIGNATURE (same value, different header name) */\n 'PAYMENT-SIGNATURE': string;\n}\n\n/**\n * Result of a payment operation\n */\nexport interface PaymentResult {\n /** Whether payment was successful */\n success: boolean;\n /** Base64-encoded X-PAYMENT header value */\n paymentHeader: string;\n /**\n * Payment headers object for easy use with fetch/axios\n *\n * @example\n * ```ts\n * // Use v1 header\n * fetch(url, { headers: { 'X-PAYMENT': result.headers['X-PAYMENT'] } });\n *\n * // Use v2 header\n * fetch(url, { headers: { 'PAYMENT-SIGNATURE': result.headers['PAYMENT-SIGNATURE'] } });\n * ```\n */\n headers: PaymentHeaders;\n /** Transaction hash (if available) */\n transactionHash?: string;\n /** Network where payment was made */\n network: string;\n /** Payer address */\n payer?: string;\n /** Error message (if success is false) */\n error?: string;\n}\n\n// ============================================================================\n// PAYLOAD TYPES (Internal)\n// ============================================================================\n\n/**\n * EVM payment payload (ERC-3009 TransferWithAuthorization)\n */\nexport interface EVMPaymentPayload {\n from: string;\n to: string;\n value: string;\n validAfter: number;\n validBefore: number;\n nonce: string;\n v: number;\n r: string;\n s: string;\n chainId: number;\n token: string;\n}\n\n/**\n * Token info for non-USDC stablecoins (e.g., Token2022 like AUSD)\n * Required in payload for facilitator to verify Token2022 transfers correctly.\n */\nexport interface TokenInfo {\n /** Token mint address */\n address: string;\n /** Token symbol (e.g., 'AUSD') */\n symbol: string;\n /** Token decimals (e.g., 6) */\n decimals: number;\n}\n\n/**\n * Solana payment payload (partially-signed transaction)\n */\nexport interface SolanaPaymentPayload {\n /** Base64-encoded serialized transaction */\n transaction: string;\n /**\n * Token info for non-USDC tokens (e.g., Token2022 like AUSD)\n * CRITICAL: Must be included for Token2022 tokens for facilitator verification\n */\n token?: TokenInfo;\n}\n\n/**\n * Stellar payment payload (Soroban authorization)\n */\nexport interface StellarPaymentPayload {\n /** Sender G... public key */\n from: string;\n /** Recipient G... public key */\n to: string;\n /** Amount in stroops (7 decimals) */\n amount: string;\n /** USDC SAC contract address */\n tokenContract: string;\n /** Base64 XDR-encoded SorobanAuthorizationEntry */\n authorizationEntryXdr: string;\n /** Random 64-bit nonce */\n nonce: number;\n /** Ledger when authorization expires */\n signatureExpirationLedger: number;\n}\n\n/**\n * NEAR payment payload (NEP-366 meta-transaction)\n */\nexport interface NEARPaymentPayload {\n /** Base64 Borsh-encoded SignedDelegateAction */\n signedDelegateAction: string;\n network: 'near';\n}\n\n/**\n * Algorand payment payload (atomic transaction group)\n *\n * Follows the GoPlausible x402-avm spec for atomic groups:\n * - Transaction 0: Fee payment (UNSIGNED) - facilitator -> facilitator, covers all fees\n * - Transaction 1: ASA transfer (SIGNED) - client -> merchant\n *\n * The facilitator signs transaction 0 and submits the complete atomic group.\n */\nexport interface AlgorandPaymentPayload {\n /** Index of the payment transaction in the group (always 1) */\n paymentIndex: number;\n /**\n * Array of base64-encoded msgpack transactions forming the atomic group:\n * - [0]: Unsigned fee transaction (facilitator signs)\n * - [1]: Signed ASA transfer (client signed)\n */\n paymentGroup: string[];\n}\n\n/**\n * Sui payment payload (sponsored transaction)\n *\n * Uses Sui sponsored transactions where:\n * - User creates a programmable transaction for USDC transfer\n * - User signs the transaction\n * - Facilitator sponsors (pays gas in SUI) and submits\n *\n * User pays: ZERO SUI\n */\nexport interface SuiPaymentPayload {\n /** Base64-encoded BCS serialized TransactionData */\n transactionBytes: string;\n /** Base64-encoded user signature */\n senderSignature: string;\n /** Sender address (0x + 64 hex chars) */\n from: string;\n /** Recipient address (0x + 64 hex chars) */\n to: string;\n /** Amount in base units (string to handle large numbers) */\n amount: string;\n /** Coin object ID used for the transfer (REQUIRED by facilitator) */\n coinObjectId: string;\n}\n\n/**\n * XRPL payment payload (pre-signed Payment transaction blob)\n *\n * Uses the t54 \"pre-signed Payment blob\" scheme on the XRP Ledger:\n * - The client builds and FULLY signs a Payment transaction off-chain,\n * paying its own XRP network fee.\n * - The single `signedTxBlob` field (hex-encoded fully-signed XRPL tx blob)\n * is sent to the facilitator, which decodes it to re-derive payer/amount/\n * destination and submits it.\n *\n * All payment-level fields (destination, amount, InvoiceID, SourceTag, etc.)\n * come from PaymentRequirements/extra, NOT from this payload.\n *\n * XRP is the native asset (6 decimals / drops). There is no token contract.\n *\n * The JSON field name is EXACTLY `signedTxBlob` (camelCase).\n */\nexport interface XRPLPaymentPayload {\n /** Hex-encoded fully-signed XRPL Payment transaction blob (tx_blob) */\n signedTxBlob: string;\n}\n\n/**\n * Union type for all payment payloads\n */\nexport type PaymentPayload =\n | EVMPaymentPayload\n | SolanaPaymentPayload\n | StellarPaymentPayload\n | NEARPaymentPayload\n | AlgorandPaymentPayload\n | SuiPaymentPayload\n | XRPLPaymentPayload;\n\n// ============================================================================\n// X402 HEADER TYPES (v1 and v2)\n// ============================================================================\n\n/**\n * x402 protocol version\n */\nexport type X402Version = 1 | 2;\n\n/**\n * CAIP-2 chain identifiers for x402 v2\n * @see https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md\n */\nexport const CAIP2_IDENTIFIERS: Record<string, string> = {\n 'hedera:mainnet': 'hedera:mainnet',\n 'hedera:testnet': 'hedera:testnet',\n // EVM chains\n base: 'eip155:8453',\n ethereum: 'eip155:1',\n polygon: 'eip155:137',\n arbitrum: 'eip155:42161',\n optimism: 'eip155:10',\n avalanche: 'eip155:43114',\n celo: 'eip155:42220',\n hyperevm: 'eip155:999',\n unichain: 'eip155:130',\n monad: 'eip155:143',\n bsc: 'eip155:56',\n scroll: 'eip155:534352',\n 'skale-base': 'eip155:1187947933',\n 'skale-base-sepolia': 'eip155:324705682',\n robinhood: 'eip155:4663',\n 'robinhood-testnet': 'eip155:46630',\n arc: 'eip155:5042',\n 'arc-testnet': 'eip155:5042002',\n // SVM chains\n solana: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n fogo: 'svm:fogo',\n // Stellar\n stellar: 'stellar:pubnet',\n // NEAR\n near: 'near:mainnet',\n // Algorand\n algorand: 'algorand:mainnet',\n 'algorand-testnet': 'algorand:testnet',\n // Sui\n sui: 'sui:mainnet',\n 'sui-testnet': 'sui:testnet',\n // XRPL (XRP Ledger)\n xrpl: 'xrpl',\n 'xrpl-testnet': 'xrpl-testnet',\n};\n\n/**\n * Reverse mapping from CAIP-2 to chain name\n */\nexport const CAIP2_TO_CHAIN: Record<string, string> = Object.fromEntries(\n Object.entries(CAIP2_IDENTIFIERS).map(([k, v]) => [v, k])\n);\n\n/**\n * x402 v1 header structure (network as string)\n */\nexport interface X402HeaderV1 {\n x402Version: 1;\n scheme: X402Scheme;\n network: string;\n payload: X402PayloadData;\n}\n\n/**\n * x402 v2 payment option\n */\nexport interface X402PaymentOption {\n network: string; // CAIP-2 format\n asset: string;\n amount: string;\n facilitator?: string;\n}\n\n/**\n * x402 v2 header structure (CAIP-2 network, accepts array)\n */\nexport interface X402HeaderV2 {\n x402Version: 2;\n scheme: X402Scheme;\n network: string; // CAIP-2 format\n payload: X402PayloadData;\n accepts?: X402PaymentOption[];\n}\n\n/**\n * Union type for both v1 and v2 headers\n */\nexport type X402Header = X402HeaderV1 | X402HeaderV2;\n\n/**\n * EVM-specific payload in x402 header\n */\nexport interface X402EVMPayload {\n signature: string;\n authorization: {\n from: string;\n to: string;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: string;\n };\n /**\n * Which token was actually paid.\n *\n * Only present when the payment is created with `includeTokenMetadata`. The\n * signature alone does not say which stablecoin it authorizes — a server that\n * accepts several tokens on the same chain cannot rebuild the payment\n * requirements without this. Omitted by default so existing v1 wire formats\n * stay byte-identical.\n */\n token?: PaymentTokenMetadata;\n}\n\n/**\n * Token identification carried inside an x402 payload.\n *\n * Mirrors what a resource server needs to build `paymentRequirements`: the\n * `asset` it must charge and the `extra` EIP-712 domain the facilitator needs\n * to recover the signature.\n */\nexport interface PaymentTokenMetadata {\n /** Token contract address (the `asset` of the payment requirements) */\n address: string;\n /** Uppercase token symbol, e.g. `USDC`, `EURC`, `USDT` */\n symbol: string;\n /** Token decimals — the amount in the authorization is in these units */\n decimals: number;\n /** EIP-712 domain of the token contract (the `extra` of the requirements) */\n eip712: {\n name: string;\n version: string;\n };\n}\n\n/**\n * Solana-specific payload in x402 header\n */\nexport interface X402SolanaPayload {\n transaction: string;\n}\n\n/**\n * Settlement account payload for Crossmint and other custodial wallets\n * that can only sendTransaction (not signTransaction).\n *\n * In this mode, the client already submitted the transaction on-chain.\n * The facilitator verifies the on-chain tx, then sweeps USDC from the\n * settlement account to the payTo address.\n *\n * Used by: Crossmint smart wallets via @faremeter/wallet-crossmint\n */\nexport interface X402SettlementAccountPayload {\n /** On-chain transaction signature (already submitted) */\n transactionSignature: string;\n /** Base58 secret key for sweeping settlement account (optional) */\n settleSecretKey?: string;\n /** Address to receive rent from closed settlement ATA (optional) */\n settlementRentDestination?: string;\n}\n\n/**\n * Stellar-specific payload in x402 header\n */\nexport interface X402StellarPayload {\n from: string;\n to: string;\n amount: string;\n tokenContract: string;\n authorizationEntryXdr: string;\n nonce: number;\n signatureExpirationLedger: number;\n}\n\n/**\n * NEAR-specific payload in x402 header\n */\nexport interface X402NEARPayload {\n signedDelegateAction: string;\n}\n\n/**\n * Algorand-specific payload in x402 header (atomic group format)\n */\nexport interface X402AlgorandPayload {\n /** Index of the payment transaction in the group (always 1) */\n paymentIndex: number;\n /** Array of base64-encoded msgpack transactions */\n paymentGroup: string[];\n}\n\n/**\n * Sui-specific payload in x402 header (sponsored transaction)\n */\nexport interface X402SuiPayload {\n /** BCS-encoded transaction bytes (base64) */\n transactionBytes: string;\n /** User's signature on the transaction (base64) */\n senderSignature: string;\n /** Sender's Sui address (0x...) */\n from: string;\n /** Recipient's Sui address (0x...) */\n to: string;\n /** Amount in smallest unit (string to avoid precision issues) */\n amount: string;\n /** Coin object ID used for the transfer (REQUIRED by facilitator) */\n coinObjectId: string;\n}\n\n/**\n * XRPL-specific payload in x402 header (t54 pre-signed Payment blob)\n *\n * The JSON field name is EXACTLY `signedTxBlob` (camelCase). The facilitator\n * decodes the blob to re-derive payer/amount/destination; no other fields are\n * carried in the payload.\n */\nexport interface X402XRPLPayload {\n /** Hex-encoded fully-signed XRPL Payment transaction blob (tx_blob) */\n signedTxBlob: string;\n}\n\n/**\n * Union of all x402 payload types\n */\nexport type X402PayloadData =\n | X402EVMPayload\n | X402SolanaPayload\n | X402SettlementAccountPayload\n | X402StellarPayload\n | X402NEARPayload\n | X402AlgorandPayload\n | X402SuiPayload\n | X402XRPLPayload;\n\n// ============================================================================\n// CLIENT CONFIGURATION\n// ============================================================================\n\n/**\n * Multi-payment configuration for supporting multiple networks\n */\nexport interface MultiPaymentConfig {\n /** Networks to support (e.g., ['base', 'solana', 'stellar', 'near']) */\n networks: string[];\n /** Default network if user hasn't selected one */\n defaultNetwork?: string;\n /** Whether to auto-detect user's preferred network based on wallet */\n autoDetect?: boolean;\n}\n\n/**\n * SDK client configuration options\n */\nexport interface X402ClientConfig {\n /** Facilitator URL (default: https://facilitator.ultravioletadao.xyz) */\n facilitatorUrl?: string;\n /** Default chain to connect to */\n defaultChain?: string;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n /** Enable debug logging */\n debug?: boolean;\n /** Custom chain configurations (override defaults) */\n customChains?: Record<string, Partial<ChainConfig>>;\n /** Wallet preference order */\n walletPreference?: string[];\n /** Custom RPC URLs (override defaults) */\n rpcOverrides?: Record<string, string>;\n /**\n * x402 protocol version to use\n * - 1: Classic format with network as string (e.g., \"base\")\n * - 2: CAIP-2 format with accepts array (e.g., \"eip155:8453\")\n * - 'auto': Auto-detect from 402 response (default)\n */\n x402Version?: X402Version | 'auto';\n /** Multi-payment configuration for supporting multiple networks */\n multiPayment?: MultiPaymentConfig;\n /**\n * What this buyer is allowed to sign, decided before it signs.\n *\n * Left undefined, the client holds `PurchasePolicy.permissive()`: this SDK had\n * no budget before 2.89.0 and turning one on silently would refuse payments\n * callers are making today. A policy built with `PurchasePolicy.create()`\n * denies any asset it was not given a ceiling for.\n *\n * @see {@link PurchasePolicy}\n */\n policy?: PurchasePolicy;\n /**\n * Include a `token` block in the payload naming the asset, its decimals and\n * its EIP-712 domain.\n *\n * Needed when the resource accepts more than one stablecoin on the same\n * chain: the signature alone does not say which one was paid, so the server\n * cannot rebuild `paymentRequirements`. Off by default — the emitted header\n * stays byte-identical to previous versions.\n */\n includeTokenMetadata?: boolean;\n /**\n * Seconds every EIP-3009 authorization this client signs stays settleable\n * (`validBefore = now + validitySeconds`).\n *\n * The per-payment {@link PaymentInfo.validitySeconds} overrides it; with\n * neither, `DEFAULT_VALIDITY_SECONDS` (300 s) applies, and `MAX_VALIDITY_SECONDS`\n * (3600 s) is the ceiling for both. Until 2.91.0 this\n * was not configurable at all: the window was 300 s on Base and 60 s on every\n * other EVM network, decided by the payer's SDK, which is exactly the party\n * that does not know how long the seller's settlement takes.\n */\n validitySeconds?: number;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: Required<Pick<X402ClientConfig, 'facilitatorUrl' | 'defaultChain' | 'autoConnect' | 'debug' | 'x402Version'>> = {\n facilitatorUrl: 'https://facilitator.ultravioletadao.xyz',\n defaultChain: 'base',\n autoConnect: false,\n debug: false,\n x402Version: 'auto',\n};\n\n// ============================================================================\n// BALANCE TYPES\n// ============================================================================\n\n/**\n * Balance information for a single network\n */\nexport interface NetworkBalance {\n /** Chain name */\n chainName: string;\n /** Human-readable display name */\n displayName: string;\n /** Formatted balance (e.g., \"15.50\") or null if loading/error */\n balance: string | null;\n /** Whether balance is currently being fetched */\n isLoading: boolean;\n /** Error message if fetch failed */\n error: string | null;\n}\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Events emitted by the SDK client\n */\nexport type X402Event =\n | 'connect'\n | 'disconnect'\n | 'chainChanged'\n | 'accountChanged'\n | 'balanceChanged'\n | 'paymentStarted'\n | 'paymentSigned'\n | 'paymentCompleted'\n | 'paymentFailed';\n\n/**\n * Event data types\n */\nexport interface X402EventData {\n connect: WalletState;\n disconnect: void;\n chainChanged: { chainId: number; chainName: string };\n accountChanged: { address: string };\n balanceChanged: { balance: string };\n paymentStarted: { amount: string; network: string };\n paymentSigned: { paymentHeader: string };\n paymentCompleted: PaymentResult;\n paymentFailed: { error: string; code: X402ErrorCode };\n}\n\n/**\n * Event handler type\n */\nexport type X402EventHandler<E extends X402Event> = (data: X402EventData[E]) => void;\n\n// ============================================================================\n// ERROR TYPES\n// ============================================================================\n\n/**\n * Error codes for categorizing errors\n */\nexport type X402ErrorCode =\n | 'WALLET_NOT_FOUND'\n | 'WALLET_NOT_CONNECTED'\n | 'WALLET_NOT_SUPPORTED'\n | 'WALLET_CONNECTION_FAILED'\n | 'WALLET_CONNECTION_REJECTED'\n | 'WALLET_CONNECTION_TIMEOUT'\n | 'CHAIN_NOT_SUPPORTED'\n | 'CHAIN_SWITCH_REJECTED'\n | 'INSUFFICIENT_BALANCE'\n | 'SIGNATURE_REJECTED'\n | 'PAYMENT_FAILED'\n | 'PAYMENT_TIMEOUT'\n | 'NETWORK_ERROR'\n | 'INVALID_CONFIG'\n | 'INVALID_AMOUNT'\n | 'INVALID_RECIPIENT'\n | 'PAYMENT_EXCEEDS_MAX'\n | 'NO_ACCEPTABLE_PAYMENT'\n /**\n * The buyer's own policy refused the offer before anything was signed. The\n * concrete cause is on `PolicyRefusedError.refusal.code` -- see\n * {@link PurchasePolicy}.\n */\n | 'POLICY_REFUSED'\n | 'UNKNOWN_ERROR';\n\n/**\n * SDK-specific error class\n */\nexport class X402Error extends Error {\n public readonly code: X402ErrorCode;\n public readonly details?: unknown;\n\n constructor(message: string, code: X402ErrorCode, details?: unknown) {\n super(message);\n this.name = 'X402Error';\n this.code = code;\n this.details = details;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, X402Error);\n }\n }\n}\n","/**\n * uvd-x402-sdk - UTF-8 safe base64\n *\n * `btoa()` only accepts code points 0-255. Any character above that throws\n * `InvalidCharacterError`, and the X-PAYMENT payload is not guaranteed to be\n * ASCII: the EIP-712 domain name of USDT on Optimism and Arbitrum is literally\n * `USD₮0` (U+20AE). A header carrying that name crashes a plain `btoa()`.\n *\n * So the JSON is UTF-8 encoded to bytes first, and only then base64'd. Decoding\n * reverses it. For ASCII-only input the output is byte-identical to\n * `btoa(json)`, which is why swapping this in cannot change any existing header.\n *\n * `TextEncoder`/`TextDecoder` are available in every browser the SDK targets and\n * in Node 11+; `btoa`/`atob` are used for the byte<->base64 step because they\n * exist in both environments without pulling in `Buffer`.\n */\n\n/**\n * Encode a string as base64, handling non-ASCII characters correctly.\n *\n * @param value - Any UTF-8 string\n * @returns Base64-encoded value\n */\nexport function encodeBase64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Decode a base64 string produced by {@link encodeBase64Utf8}.\n *\n * @param encoded - Base64-encoded value\n * @returns The original UTF-8 string\n */\nexport function decodeBase64Utf8(encoded: string): string {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * JSON-serialize a value and encode it as UTF-8 safe base64.\n *\n * This is the encoder for every X-PAYMENT header the SDK emits.\n *\n * @param value - Value to serialize\n * @returns Base64-encoded JSON\n */\nexport function encodeBase64Json(value: unknown): string {\n return encodeBase64Utf8(JSON.stringify(value));\n}\n","/**\n * uvd-x402-sdk - x402 Protocol Utilities\n *\n * Utilities for working with x402 v1 and v2 protocols.\n * Handles version detection, payload encoding, and CAIP-2 conversions.\n */\n\nimport type {\n X402Header,\n X402HeaderV1,\n X402HeaderV2,\n X402PayloadData,\n X402PaymentOption,\n X402Version,\n ChainConfig,\n TokenType,\n} from '../types';\nimport { CAIP2_IDENTIFIERS, CAIP2_TO_CHAIN } from '../types';\nimport { getChainByName, getTokenConfig, isUsdPegged } from '../chains';\nimport { decodeBase64Utf8, encodeBase64Json } from './base64';\nimport { toAtomicUnits } from './amount';\n\n/**\n * Detect x402 version from a response header or body\n *\n * @param data - The 402 response data (parsed JSON or header value)\n * @returns The detected version (1 or 2)\n */\nexport function detectX402Version(data: unknown): X402Version {\n if (typeof data === 'string') {\n // A `PAYMENT-REQUIRED` header value is base64 JSON, and the doc above\n // invites one. Returning 1 without decoding misread every v2 challenge as\n // v1 — silently, as a plausible value rather than an error, and the two\n // wire forms are structurally incompatible.\n //\n // This is not hypothetical: measured 2026-08-20, 36 of 36 live Bazaar\n // resources answering 402 carry the challenge in the header, and several\n // put a free content preview in the body, so the header is the only place\n // the version signal exists.\n const trimmed = data.trim();\n if (!trimmed) return 1;\n for (const decode of [\n () => JSON.parse(decodeBase64Utf8(trimmed)),\n () => JSON.parse(trimmed),\n ]) {\n try {\n const parsed = decode();\n if (typeof parsed === 'object' && parsed !== null) {\n return detectX402Version(parsed);\n }\n } catch {\n // not this encoding; try the next\n }\n }\n return 1; // undecodable: fall back to v1, as before\n }\n\n if (typeof data !== 'object' || data === null) {\n return 1; // Default to v1\n }\n\n const obj = data as Record<string, unknown>;\n\n // Check explicit version field\n if (obj.x402Version === 2) {\n return 2;\n }\n\n // Check for v2 indicators. A v1 402 carries `accepts` too (the spec's v1\n // shape, and the v1 402 this SDK builds), so `accepts` does not outvote a\n // declared 1. `X402Client` already takes the version from the field, not\n // from `accepts`.\n if (obj.accepts && Array.isArray(obj.accepts) && obj.x402Version !== 1) {\n return 2;\n }\n\n // `paymentRequirements` is the v1 spelling, so its presence points at v1 --\n // but only when there is no v2 signal, which the checks above already ruled\n // out. Recognised so the value is not treated as an unknown shape.\n if (Array.isArray(obj.paymentRequirements)) {\n return 1;\n }\n\n // Check if network is in CAIP-2 format\n if (typeof obj.network === 'string') {\n if (obj.network.includes(':')) {\n return 2;\n }\n }\n\n return 1;\n}\n\n/**\n * Convert chain name to CAIP-2 identifier\n *\n * @param chainName - Chain name (e.g., 'base', 'solana')\n * @returns CAIP-2 identifier (e.g., 'eip155:8453', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp')\n */\nexport function chainToCAIP2(chainName: string): string {\n // Resolve through the registry FIRST, so an alias answers with the canonical\n // chain's id rather than one built out of the alias. Without this, asking\n // with `xrpl-mainnet` fell past the lookup into the fallback below and\n // manufactured `xrpl:xrpl-mainnet` -- a well-formed CAIP-2 string that no\n // facilitator has ever accepted, and one that PASSES the colon test every v2\n // guard in this SDK uses. A fabricated id is worse than a missing one: the\n // missing one is refused loudly, the fabricated one ships.\n const chain = getChainByName(chainName);\n const caip2 = CAIP2_IDENTIFIERS[(chain?.name ?? chainName).toLowerCase()];\n if (caip2) {\n return caip2;\n }\n\n // Try to construct from chain config\n if (chain) {\n if (chain.networkType === 'evm') {\n return `eip155:${chain.chainId}`;\n }\n // For non-EVM, return the canonical name with the network prefix\n return `${chain.networkType}:${chain.name}`;\n }\n\n return chainName; // Return as-is if unknown\n}\n\n/**\n * Convert CAIP-2 identifier to chain name\n *\n * @param caip2 - CAIP-2 identifier\n * @returns Chain name or null if unknown\n */\nexport function caip2ToChain(caip2: string): string | null {\n // Check direct mapping\n if (CAIP2_TO_CHAIN[caip2]) {\n return CAIP2_TO_CHAIN[caip2];\n }\n\n // Try to extract from EIP-155 format\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (match) {\n const chainId = parseInt(match[1], 10);\n // Find chain by ID\n for (const [name, _config] of Object.entries(CAIP2_IDENTIFIERS)) {\n const chain = getChainByName(name);\n if (chain?.chainId === chainId) {\n return name;\n }\n }\n }\n\n // Try to extract from network:name format\n const parts = caip2.split(':');\n if (parts.length === 2) {\n const networkName = parts[1];\n if (getChainByName(networkName)) {\n return networkName;\n }\n }\n\n return null;\n}\n\n/**\n * Parse network identifier from either v1 or v2 format\n *\n * @param network - Network identifier (v1 string or v2 CAIP-2)\n * @returns Normalized chain name\n */\nexport function parseNetworkIdentifier(network: string): string {\n // If it contains a colon, it's likely CAIP-2\n if (network.includes(':')) {\n return caip2ToChain(network) || network;\n }\n return network.toLowerCase();\n}\n\n/**\n * Encode x402 payload as base64 header value\n *\n * @param header - The x402 header object\n * @returns Base64-encoded string\n */\nexport function encodeX402Header(header: X402Header): string {\n return encodeBase64Json(header);\n}\n\n/**\n * Decode x402 header from base64 string\n *\n * @param encoded - Base64-encoded header value\n * @returns Parsed x402 header\n */\nexport function decodeX402Header(encoded: string): X402Header {\n const json = decodeBase64Utf8(encoded);\n return JSON.parse(json) as X402Header;\n}\n\n/**\n * Create x402 v1 header\n *\n * @param network - Chain name (e.g., 'base')\n * @param payload - Network-specific payload\n * @returns x402 v1 header object\n */\nexport function createX402V1Header(\n network: string,\n payload: X402PayloadData\n): X402HeaderV1 {\n if (getChainByName(network)?.networkType === 'hedera') throw new Error('Native Hedera supports only x402 v2');\n return {\n x402Version: 1,\n scheme: 'exact',\n network,\n payload,\n };\n}\n\n/**\n * Create x402 v2 header\n *\n * @param network - CAIP-2 network identifier\n * @param payload - Network-specific payload\n * @param accepts - Optional array of payment options\n * @returns x402 v2 header object\n */\nexport function createX402V2Header(\n network: string,\n payload: X402PayloadData,\n accepts?: X402PaymentOption[]\n): X402HeaderV2 {\n const header: X402HeaderV2 = {\n x402Version: 2,\n scheme: 'exact',\n network: network.includes(':') ? network : chainToCAIP2(network),\n payload,\n };\n\n if (accepts && accepts.length > 0) {\n header.accepts = accepts;\n }\n\n return header;\n}\n\n/**\n * Create x402 header with automatic version selection\n *\n * @param chainConfig - Chain configuration\n * @param payload - Network-specific payload\n * @param version - Version to use (1, 2, or 'auto')\n * @returns x402 header object\n */\nexport function createX402Header(\n chainConfig: ChainConfig,\n payload: X402PayloadData,\n version: X402Version | 'auto' = 'auto'\n): X402Header {\n // Default to v1 for maximum compatibility\n const effectiveVersion = version === 'auto' ? 1 : version;\n\n if (effectiveVersion === 2) {\n return createX402V2Header(chainConfig.name, payload);\n }\n\n return createX402V1Header(chainConfig.name, payload);\n}\n\n/**\n * Generate payment options array for multi-network support\n *\n * One entry per (chain, token) pair. By default the token is USDC on every\n * chain, which is exactly what this emitted before `tokens` existed.\n *\n * **`tokens` is opt-in on purpose, and the reason is money.** The chain\n * registry knows more stablecoins than USDC (Base also has EURC), and it is\n * tempting to just emit all of them. But this array becomes the `accepts` of a\n * `402`, so every entry is a currency the seller has publicly agreed to be paid\n * in -- at `amount` units of it. Emitting EURC for a seller who priced in\n * dollars would quietly sell at a 1:1 EUR/USD rate nobody agreed to. So the\n * caller names the tokens it actually accepts, and `amount` is read as units of\n * each named token, NOT converted between them.\n *\n * A token a chain does not have is skipped: an option is only emitted for pairs\n * the registry can actually price.\n *\n * @param chainConfigs - Array of chain configurations\n * @param amount - Amount in units of each token (e.g., \"10.00\")\n * @param facilitator - Optional facilitator URL override\n * @param tokens - Tokens to offer per chain (default: `['usdc']`)\n * @returns Array of x402 v2 payment options\n *\n * @example\n * ```ts\n * // Dollars only -- the default, and what every existing caller gets.\n * generatePaymentOptions([base], '5.00');\n *\n * // Dollars or euros, priced separately and both genuinely accepted.\n * generatePaymentOptions([base], '5.00', undefined, ['usdc', 'eurc']);\n * ```\n */\nexport function generatePaymentOptions(\n chainConfigs: ChainConfig[],\n amount: string,\n facilitator?: string,\n tokens: TokenType[] = ['usdc']\n): X402PaymentOption[] {\n const options: X402PaymentOption[] = [];\n\n for (const chain of chainConfigs) {\n if (!chain.x402.enabled) continue;\n\n for (const tokenType of tokens) {\n const token = getTokenConfig(chain.name, tokenType);\n if (!token) continue;\n\n // A token with no dollar peg is skipped for the same reason a missing one\n // is: this array can only carry pairs the registry can actually price.\n // XRPL reaches here because it files native XRP under the key `usdc`, so\n // the loop would otherwise emit \"5 XRP\" for a seller who wrote `'5.00'`\n // and asked for dollars.\n //\n // SKIP, not throw, and that is deliberate. This builds the `accepts` of\n // ONE 402 covering MANY chains -- the usual call is every enabled chain\n // at once -- so throwing would take the whole response down over a single\n // unpriceable pair and cost the seller the chains that were fine.\n // `buildPaymentRequirements` names one chain and therefore throws there.\n // EURC is available only through an explicitly named token: the caller\n // has chosen euros here. The default USDC path still excludes native XRP.\n if (!isUsdPegged(token) && tokenType !== 'eurc') continue;\n\n // Atomic units in THIS token's decimals -- BSC USDC has 18, not 6.\n // Unlike an unpriceable token above, an amount this token cannot hold\n // exactly is the caller's input, not the registry's: it throws.\n const atomicAmount = toAtomicUnits(amount, token.decimals).toString();\n\n options.push({\n network: chainToCAIP2(chain.name),\n asset: token.address,\n amount: atomicAmount,\n facilitator: facilitator || chain.x402.facilitatorUrl,\n });\n }\n }\n\n return options;\n}\n\n/**\n * Check if a network string is in CAIP-2 format\n *\n * @param network - Network identifier\n * @returns True if CAIP-2 format\n */\nexport function isCAIP2Format(network: string): boolean {\n return network.includes(':');\n}\n\n/**\n * Convert between x402 v1 and v2 header formats\n *\n * @param header - Source header\n * @param targetVersion - Target version\n * @returns Converted header\n */\nexport function convertX402Header(\n header: X402Header,\n targetVersion: X402Version\n): X402Header {\n if (header.x402Version === targetVersion) {\n return header;\n }\n\n if (targetVersion === 2) {\n // v1 -> v2\n return {\n x402Version: 2,\n scheme: 'exact',\n network: chainToCAIP2(header.network),\n payload: header.payload,\n };\n } else {\n // v2 -> v1\n const chainName = isCAIP2Format(header.network)\n ? caip2ToChain(header.network) || header.network\n : header.network;\n\n return {\n x402Version: 1,\n scheme: 'exact',\n network: chainName,\n payload: header.payload,\n };\n }\n}\n\n/**\n * Read a 402 payment challenge from wherever the seller put it.\n *\n * x402 allows BOTH transports and sellers pick freely:\n *\n * - base64 JSON in the `PAYMENT-REQUIRED` (or `X-PAYMENT-REQUIRED`) header\n * - JSON in the response body\n *\n * Measured against production on 2026-08-20: of 40 live Bazaar resources,\n * **36 of 36 that answered 402 carried the challenge in the header, and none in\n * the body**. Worse, sellers like Tenjin use the 402 body for a free preview of\n * the paid content — so the body is valid JSON that simply has no `accepts`, and\n * a body-only reader parses it happily and finds nothing.\n *\n * Reads the header first because that is where live sellers put it, and falls\n * back to the body so the sellers who use it keep working.\n *\n * Returns `null` when neither transport carries a challenge — a real \"no terms\n * here\", distinct from a challenge we failed to decode.\n */\nexport function paymentChallengeFrom(\n headers: { get(name: string): string | null } | Record<string, string>,\n body?: unknown,\n): Record<string, unknown> | null {\n const read = (name: string): string | null => {\n if (typeof (headers as { get?: unknown }).get === 'function') {\n return (headers as { get(n: string): string | null }).get(name);\n }\n const rec = headers as Record<string, string>;\n return rec[name] ?? rec[name.toLowerCase()] ?? rec[name.toUpperCase()] ?? null;\n };\n\n const raw = read('payment-required') ?? read('x-payment-required');\n if (raw) {\n const trimmed = raw.trim();\n for (const decode of [\n () => JSON.parse(decodeBase64Utf8(trimmed)),\n () => JSON.parse(trimmed),\n ]) {\n try {\n const parsed = decode();\n if (isChallenge(parsed)) return parsed as Record<string, unknown>;\n } catch {\n // not this encoding; try the next\n }\n }\n }\n\n const parsedBody = typeof body === 'string' ? tryJson(body) : body;\n return isChallenge(parsedBody) ? (parsedBody as Record<string, unknown>) : null;\n}\n\n/**\n * Whether a value actually looks like an x402 challenge.\n *\n * Deliberately stricter than \"is an object\": a 402 body carrying a free preview\n * is valid JSON with no payment terms in it, and treating that as a challenge is\n * how a body-only reader concludes it looked and found nothing wrong.\n */\nfunction isChallenge(v: unknown): boolean {\n if (typeof v !== 'object' || v === null) return false;\n const o = v as Record<string, unknown>;\n // `paymentRequirements` is the v1 spelling of `accepts`. Missing it made a\n // seller using it look like \"no terms here\" — the exact false negative this\n // function exists to prevent. Found in the Python SDK by KarmaKadabra's\n // buyer, which matched both keys in production, 2026-08-20.\n return (\n Array.isArray(o.accepts) ||\n Array.isArray(o.paymentRequirements) ||\n typeof o.payTo === 'string'\n );\n}\n\nfunction tryJson(s: string): unknown {\n try {\n return JSON.parse(s);\n } catch {\n return null;\n }\n}\n","/**\n * uvd-x402-sdk - Validation and Payment Header Utilities\n *\n * Functions for validating payment parameters and creating\n * payment headers for HTTP requests.\n */\n\nimport type { X402HeaderName, PaymentHeaders } from '../types';\nimport { X402Error } from '../types';\n\n/**\n * Regular expression for validating Ethereum addresses\n */\nconst ETH_ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/;\n\n/**\n * Regular expression for validating Solana addresses (base58, 32-44 chars)\n */\nconst SOLANA_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * Regular expression for validating Stellar addresses (G... format)\n */\nconst STELLAR_ADDRESS_REGEX = /^G[A-Z2-7]{55}$/;\n\n/**\n * Regular expression for validating NEAR addresses\n */\nconst NEAR_ADDRESS_REGEX = /^[a-z0-9._-]+$/;\n\n/**\n * Regular expression for validating XRPL classic addresses (r... base58, Ripple alphabet)\n */\nconst XRPL_ADDRESS_REGEX = /^r[1-9A-HJ-NP-Za-km-z]{24,34}$/;\n\n/**\n * Validate that a recipient address is present and valid\n *\n * This function ensures that:\n * 1. The recipient is not null, undefined, or empty\n * 2. The recipient is not just whitespace\n * 3. For EVM, it's a valid checksummed or lowercase 0x address\n *\n * @param recipient - The recipient address to validate\n * @param networkType - Optional network type for format validation\n * @throws X402Error with code 'INVALID_RECIPIENT' if validation fails\n */\nexport function validateRecipient(\n recipient: string | undefined | null,\n networkType?: 'evm' | 'svm' | 'solana' | 'stellar' | 'near' | 'xrpl' | 'hedera'\n): asserts recipient is string {\n // Check for null, undefined, or empty\n if (!recipient) {\n throw new X402Error(\n 'Recipient address is required. The payTo/recipient field cannot be empty. ' +\n 'Please provide a valid recipient address where payments should be sent.',\n 'INVALID_RECIPIENT'\n );\n }\n\n // Check for whitespace-only\n const trimmed = recipient.trim();\n if (trimmed === '') {\n throw new X402Error(\n 'Recipient address cannot be empty or whitespace. ' +\n 'Please provide a valid recipient address.',\n 'INVALID_RECIPIENT'\n );\n }\n\n // Network-specific validation\n if (networkType) {\n switch (networkType) {\n case 'evm':\n if (!ETH_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid EVM recipient address: \"${trimmed}\". ` +\n 'Expected a 40-character hexadecimal address starting with 0x.',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'svm':\n case 'solana':\n if (!SOLANA_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid Solana recipient address: \"${trimmed}\". ` +\n 'Expected a base58-encoded public key (32-44 characters).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'stellar':\n if (!STELLAR_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid Stellar recipient address: \"${trimmed}\". ` +\n 'Expected a G-prefixed public key (56 characters).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'near':\n if (!NEAR_ADDRESS_REGEX.test(trimmed) || trimmed.length > 64) {\n throw new X402Error(\n `Invalid NEAR recipient address: \"${trimmed}\". ` +\n 'Expected a valid NEAR account ID.',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'hedera':\n if (!/^0\\.0\\.[1-9][0-9]*$/.test(trimmed)) {\n throw new X402Error('Hedera recipient must be a native numeric account ID', 'INVALID_RECIPIENT');\n }\n break;\n\n case 'xrpl':\n if (!XRPL_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid XRPL recipient address: \"${trimmed}\". ` +\n 'Expected a classic r-address (base58, Ripple alphabet).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n }\n }\n}\n\n/**\n * Validate payment amount\n *\n * Ensures the amount is a valid positive number string\n *\n * @param amount - The amount string to validate\n * @throws X402Error with code 'INVALID_AMOUNT' if validation fails\n */\nexport function validateAmount(amount: string | undefined | null): asserts amount is string {\n if (!amount) {\n throw new X402Error(\n 'Payment amount is required.',\n 'INVALID_AMOUNT'\n );\n }\n\n const trimmed = amount.trim();\n if (trimmed === '') {\n throw new X402Error(\n 'Payment amount cannot be empty.',\n 'INVALID_AMOUNT'\n );\n }\n\n // Parse as number\n const num = parseFloat(trimmed);\n if (isNaN(num)) {\n throw new X402Error(\n `Invalid payment amount: \"${trimmed}\". Expected a valid number.`,\n 'INVALID_AMOUNT'\n );\n }\n\n if (num <= 0) {\n throw new X402Error(\n `Payment amount must be positive. Got: ${trimmed}`,\n 'INVALID_AMOUNT'\n );\n }\n}\n\n// ============================================================================\n// PAYMENT HEADER UTILITIES\n// ============================================================================\n\n/**\n * Create payment headers object from a base64-encoded payload\n *\n * Returns an object with both X-PAYMENT and PAYMENT-SIGNATURE headers,\n * making it easy to use either header format.\n *\n * @param paymentHeader - Base64-encoded payment payload\n * @returns PaymentHeaders object with both header formats\n *\n * @example\n * ```ts\n * const headers = createPaymentHeaders(paymentHeader);\n *\n * // Use v1 header (most compatible)\n * fetch(url, { headers: { 'X-PAYMENT': headers['X-PAYMENT'] } });\n *\n * // Use v2 header\n * fetch(url, { headers: { 'PAYMENT-SIGNATURE': headers['PAYMENT-SIGNATURE'] } });\n * ```\n */\nexport function createPaymentHeaders(paymentHeader: string): PaymentHeaders {\n return {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n };\n}\n\n/**\n * Get a single payment header by name\n *\n * @param paymentHeader - Base64-encoded payment payload\n * @param headerName - Header name to use ('X-PAYMENT' or 'PAYMENT-SIGNATURE')\n * @returns Object with a single header entry\n *\n * @example\n * ```ts\n * // Use with fetch spread operator\n * fetch(url, {\n * headers: {\n * 'Content-Type': 'application/json',\n * ...getPaymentHeader(result.paymentHeader, 'X-PAYMENT'),\n * },\n * });\n * ```\n */\nexport function getPaymentHeader(\n paymentHeader: string,\n headerName: X402HeaderName = 'X-PAYMENT'\n): Record<X402HeaderName, string> {\n return { [headerName]: paymentHeader } as Record<X402HeaderName, string>;\n}\n\n/**\n * Default x402 payment header name\n *\n * Use 'X-PAYMENT' for maximum compatibility with all facilitators.\n * Use 'PAYMENT-SIGNATURE' for x402 v2 compliance.\n */\nexport const DEFAULT_PAYMENT_HEADER: X402HeaderName = 'X-PAYMENT';\n\n/**\n * All supported x402 payment header names\n */\nexport const PAYMENT_HEADER_NAMES: readonly X402HeaderName[] = [\n 'X-PAYMENT',\n 'PAYMENT-SIGNATURE',\n] as const;\n","/**\n * uvd-x402-sdk - Wagmi/Viem Adapter\n *\n * Provides integration with wagmi/viem for projects using RainbowKit,\n * ConnectKit, or other wagmi-based wallet connection libraries.\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { createPaymentFromWalletClient } from 'uvd-x402-sdk/wagmi';\n *\n * function PayButton() {\n * const { data: walletClient } = useWalletClient();\n *\n * const handlePay = async () => {\n * const paymentHeader = await createPaymentFromWalletClient(walletClient, {\n * recipient: '0x...',\n * amount: '1.00',\n * chainName: 'base',\n * });\n *\n * // Use in your API request\n * await fetch('/api/paid-endpoint', {\n * headers: { 'X-PAYMENT': paymentHeader }\n * });\n * };\n *\n * return <button onClick={handlePay}>Pay $1.00</button>;\n * }\n * ```\n */\n\nimport { getChainByName } from '../chains';\nimport { createX402V1Header, createX402V2Header, encodeX402Header, validateRecipient } from '../utils';\nimport { X402Error } from '../types';\nimport type { PaymentResult, X402Version } from '../types';\n\n/**\n * Viem WalletClient interface (minimal type to avoid viem dependency)\n */\nexport interface WalletClient {\n account: {\n address: `0x${string}`;\n };\n signTypedData: (args: {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: `0x${string}`;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n }) => Promise<`0x${string}`>;\n}\n\n/**\n * Payment options for wagmi adapter\n */\nexport interface WagmiPaymentOptions {\n /** Recipient address */\n recipient: string;\n /** Amount in USDC (e.g., \"1.00\", \"10.50\") */\n amount: string;\n /** Chain name (default: 'base') */\n chainName?: string;\n /** Validity window in seconds (default: 300 = 5 minutes) */\n validitySeconds?: number;\n /**\n * x402 protocol version (default: 1)\n * - 1: Classic format with network as string (e.g., \"base\")\n * - 2: CAIP-2 format (e.g., \"eip155:8453\")\n */\n x402Version?: X402Version;\n}\n\n/**\n * Generate a random 32-byte nonce as hex string\n */\nfunction generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n if (typeof globalThis !== 'undefined' && globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof window !== 'undefined' && window.crypto?.getRandomValues) {\n window.crypto.getRandomValues(bytes);\n } else {\n // Fallback for non-browser environments\n for (let i = 0; i < 32; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return ('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')) as `0x${string}`;\n}\n\n/**\n * Parse amount string to atomic units (BigInt)\n */\nfunction parseUnits(amount: string, decimals: number): bigint {\n const [integer, fraction = ''] = amount.split('.');\n const paddedFraction = fraction.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(integer + paddedFraction);\n}\n\n/**\n * Create an x402 payment header using a wagmi/viem WalletClient\n *\n * This function allows you to use the x402 SDK with wagmi-based wallet\n * connections (RainbowKit, ConnectKit, etc.) instead of the built-in\n * wallet connection.\n *\n * @param walletClient - The WalletClient from wagmi's useWalletClient hook\n * @param options - Payment options (recipient, amount, chainName)\n * @returns Base64-encoded payment header ready for X-PAYMENT HTTP header\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { createPaymentFromWalletClient } from 'uvd-x402-sdk/wagmi';\n *\n * const { data: walletClient } = useWalletClient();\n *\n * const paymentHeader = await createPaymentFromWalletClient(walletClient, {\n * recipient: '0xRecipientAddress',\n * amount: '5.00',\n * chainName: 'base',\n * });\n * ```\n */\nexport async function createPaymentFromWalletClient(\n walletClient: WalletClient | undefined | null,\n options: WagmiPaymentOptions\n): Promise<string> {\n if (!walletClient) {\n throw new X402Error('WalletClient is not available. Make sure wallet is connected.', 'WALLET_NOT_CONNECTED');\n }\n\n const {\n recipient,\n amount,\n chainName = 'base',\n validitySeconds = 300,\n x402Version = 1,\n } = options;\n\n // Validate recipient address - prevents empty/invalid addresses\n validateRecipient(recipient, 'evm');\n\n // Get chain configuration\n const chain = getChainByName(chainName);\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${chainName}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `wagmi adapter only supports EVM chains. For ${chain.networkType}, use the appropriate provider.`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n const from = walletClient.account.address;\n const to = recipient as `0x${string}`;\n const nonce = generateNonce();\n const validAfter = 0;\n const validBefore = Math.floor(Date.now() / 1000) + validitySeconds;\n const value = parseUnits(amount, chain.usdc.decimals);\n\n // EIP-712 domain\n const domain = {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId: chain.chainId,\n verifyingContract: chain.usdc.address as `0x${string}`,\n };\n\n // EIP-712 types for TransferWithAuthorization (ERC-3009)\n const types = {\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 };\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter: BigInt(validAfter),\n validBefore: BigInt(validBefore),\n nonce,\n };\n\n // Sign with viem\n let signature: `0x${string}`;\n try {\n signature = await walletClient.signTypedData({\n domain,\n types,\n primaryType: 'TransferWithAuthorization',\n message,\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || error.message.includes('denied')) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to sign payment: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n // Build the payload data\n // IMPORTANT: validAfter, validBefore, and value must be STRINGS\n const payloadData = {\n signature,\n authorization: {\n from,\n to: recipient,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n },\n };\n\n // Create x402 header with correct version format\n const header = x402Version === 2\n ? createX402V2Header(chainName, payloadData)\n : createX402V1Header(chainName, payloadData);\n\n return encodeX402Header(header);\n}\n\n/**\n * Create payment with full result object (includes metadata)\n *\n * Same as createPaymentFromWalletClient but returns a PaymentResult\n * object with additional metadata.\n *\n * @param walletClient - The WalletClient from wagmi\n * @param options - Payment options\n * @returns PaymentResult with paymentHeader and metadata\n */\nexport async function createPaymentWithResult(\n walletClient: WalletClient | undefined | null,\n options: WagmiPaymentOptions\n): Promise<PaymentResult> {\n const paymentHeader = await createPaymentFromWalletClient(walletClient, options);\n\n return {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: options.chainName || 'base',\n payer: walletClient?.account.address,\n };\n}\n\n/**\n * React hook helper for wagmi integration\n *\n * Returns a function that creates payments using the connected wallet.\n * This is a simple wrapper - for more control, use createPaymentFromWalletClient directly.\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { useX402Wagmi } from 'uvd-x402-sdk/wagmi';\n *\n * function PayButton() {\n * const { data: walletClient } = useWalletClient();\n * const { createPayment, isReady } = useX402Wagmi(walletClient);\n *\n * return (\n * <button\n * disabled={!isReady}\n * onClick={() => createPayment({ recipient: '0x...', amount: '1.00' })}\n * >\n * Pay\n * </button>\n * );\n * }\n * ```\n */\nexport function useX402Wagmi(walletClient: WalletClient | undefined | null) {\n const isReady = !!walletClient;\n\n const createPayment = async (options: WagmiPaymentOptions): Promise<string> => {\n return createPaymentFromWalletClient(walletClient, options);\n };\n\n const createPaymentFull = async (options: WagmiPaymentOptions): Promise<PaymentResult> => {\n return createPaymentWithResult(walletClient, options);\n };\n\n return {\n isReady,\n createPayment,\n createPaymentFull,\n };\n}\n","/**\n * uvd-x402-sdk - Integers that crossed JSON\n *\n * An EIP-712 uint written as a JSON NUMBER hashes the same where it was\n * written and is destroyed where it is read: `JSON.parse` turns every integer\n * above `Number.MAX_SAFE_INTEGER` (2**53 - 1) into the nearest double. A\n * 32-byte `salt` such as `0xab…ab` comes out as 7.76e+76, `BigInt()` of that\n * is a different integer, and the struct signed from it is not the one that\n * was sent: the facilitator answers `bad_signature` and neither end can say\n * why. The pinned lifecycle vector's salt (12345) fits in a double and shows\n * nothing; `release/real-salt` in `scripts/xlang/cross-language-conformance.mjs`\n * is the case that does.\n *\n * The rounding cannot be undone, but it can be seen: an integer above\n * 2**53 - 1 is still above it after rounding. So every integer this SDK reads\n * for a signature or a hash goes through here, and a number that is not a safe\n * integer is refused with an error that names the field. Strings (decimal or\n * 0x-hex) and bigints carry any width exactly and are accepted.\n */\n\nimport { ethers } from 'ethers';\n\nimport { X402Error, type X402ErrorCode } from '../types';\n\n/** Decimal digits, or 0x-hex. No sign, no spaces, no exponent, never empty. */\nconst UINT_STRING = /^(?:[0-9]+|0[xX][0-9a-fA-F]+)$/;\n\n/** An EIP-712 integer type: `uint256`, `int128`, `uint` ... */\nconst INTEGER_TYPE = /^u?int\\d*$/;\n\nfunction shown(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'bigint') return `${value}n`;\n return String(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** The refusal for an integer JSON could not have carried exactly. */\nexport function inexactNumberMessage(field: string, value: number): string {\n return (\n `${field} is the JSON number ${String(value)}, larger in magnitude than ` +\n 'Number.MAX_SAFE_INTEGER (2**53 - 1): JSON.parse has already rounded it, and signing it ' +\n 'would sign a different integer than the one that was written. Send uints as decimal or ' +\n '0x-hex strings (or a bigint)'\n );\n}\n\n/** A number found where an integer is read: rounded on its way in, or not an integer at all. */\nfunction numberRefusal(path: string, value: number, code: X402ErrorCode): X402Error {\n return new X402Error(\n Number.isInteger(value)\n ? inexactNumberMessage(path, value)\n : `${path} must be an integer, got the JSON number ${String(value)}`,\n code\n );\n}\n\n/**\n * An unsigned integer read for a signature or a hash, exactly.\n *\n * Accepts a bigint `>= 0`, a number that is a safe integer `>= 0`, and a\n * string of decimal digits or 0x-hex. Refuses, with `code`, a number above\n * 2**53 - 1 (it was rounded on its way in), a negative, a fraction, and any\n * other string: empty, signed, with spaces or an exponent. `BigInt('')` is\n * `0n`: an empty lifecycle `amount` used to be signed as zero.\n *\n * @param field - Named in the error, e.g. `'paymentInfo.maxAmount'`.\n */\nexport function toUint(\n value: unknown,\n field: string,\n code: X402ErrorCode = 'INVALID_CONFIG'\n): bigint {\n if (typeof value === 'bigint') {\n if (value < 0n) {\n throw new X402Error(`${field} must be a non-negative integer, got ${shown(value)}`, code);\n }\n return value;\n }\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) && value >= 0) return BigInt(value);\n if (Number.isInteger(value) && value > 0) {\n throw new X402Error(inexactNumberMessage(field, value), code);\n }\n throw new X402Error(`${field} must be a non-negative integer, got ${shown(value)}`, code);\n }\n if (typeof value === 'string' && UINT_STRING.test(value)) return BigInt(value);\n throw new X402Error(\n `${field} must be a non-negative integer (decimal or 0x-hex string, bigint, or a number ` +\n `up to 2**53 - 1), got ${shown(value)}`,\n code\n );\n}\n\n/**\n * The first number under `value` that is not a safe integer, with its path.\n * Depth first, arrays and plain objects only; `null` when there is none.\n */\nexport function findInexactNumber(\n value: unknown,\n path: string,\n seen: Set<object> = new Set()\n): { path: string; value: number } | null {\n if (typeof value === 'number') {\n return Number.isSafeInteger(value) ? null : { path, value };\n }\n // Untyped, an object holds the same numbers wherever it is reached, so once\n // is enough, and an object that contains itself (built in code, never\n // parsed) does not recurse for ever.\n if (typeof value !== 'object' || value === null || seen.has(value)) return null;\n seen.add(value);\n const entries: Array<[string, unknown]> = Array.isArray(value)\n ? value.map((item, i): [string, unknown] => [`${path}[${i}]`, item])\n : Object.entries(value).map(([key, item]): [string, unknown] => [`${path}.${key}`, item]);\n for (const [itemPath, item] of entries) {\n const hit = findInexactNumber(item, itemPath, seen);\n if (hit) return hit;\n }\n return null;\n}\n\n/**\n * Refuse `value` if any number under it is not a safe integer: for JSON whose\n * every number is an integer read for a signature (an ERC-3009 payload).\n */\nexport function assertNoInexactNumber(\n value: unknown,\n path: string,\n code: X402ErrorCode = 'INVALID_CONFIG'\n): void {\n const hit = findInexactNumber(value, path);\n if (hit) throw numberRefusal(hit.path, hit.value, code);\n}\n\n/** The root struct ethers signs for `types`, or `primaryType` when ethers cannot say. */\nfunction rootStruct(structs: Record<string, unknown>, primaryType: unknown): string | null {\n try {\n return ethers.TypedDataEncoder.from(\n structs as Record<string, Array<{ name: string; type: string }>>\n ).primaryType;\n } catch {\n return typeof primaryType === 'string' && Array.isArray(structs[primaryType])\n ? primaryType\n : null;\n }\n}\n\nfunction checkTyped(\n type: string,\n value: unknown,\n path: string,\n structs: Record<string, unknown>,\n code: X402ErrorCode,\n ancestors: Set<object> = new Set()\n): void {\n // A value that contains itself, under types that do (ethers refuses those,\n // so it falls back to `primaryType`), would recurse for ever.\n if (typeof value === 'object' && value !== null) {\n if (ancestors.has(value)) return;\n ancestors.add(value);\n }\n try {\n const array = /^(.*)\\[(\\d*)\\]$/.exec(type);\n if (array) {\n if (Array.isArray(value)) {\n value.forEach((item, i) =>\n checkTyped(array[1], item, `${path}[${i}]`, structs, code, ancestors)\n );\n }\n return;\n }\n const struct = structs[type];\n if (Array.isArray(struct)) {\n if (!isRecord(value)) return;\n for (const field of struct as Array<{ name?: unknown; type?: unknown }>) {\n if (typeof field?.name === 'string' && typeof field.type === 'string') {\n checkTyped(\n field.type,\n value[field.name],\n `${path}.${field.name}`,\n structs,\n code,\n ancestors\n );\n }\n }\n return;\n }\n if (INTEGER_TYPE.test(type) && typeof value === 'number' && !Number.isSafeInteger(value)) {\n throw numberRefusal(path, value, code);\n }\n } finally {\n if (typeof value === 'object' && value !== null) ancestors.delete(value);\n }\n}\n\n/**\n * Refuse an EIP-712 document whose integers JSON could not have carried: every\n * `uintN` / `intN` field of `message` by its declared type (nested structs and\n * arrays included), and `domain.chainId`. `message` is walked as the root\n * struct ethers signs for these `types` and, when it names another struct, as\n * `primaryType` too: viem, wagmi and `eth_signTypedData_v4` sign that one.\n * When the types cannot be read at all, any number in `message` that is not a\n * safe integer is refused.\n *\n * Shape errors (no `types`, a field missing) are left to the signer: this\n * only answers whether an integer was rounded on its way in.\n *\n * @param where - Prefix of the field path in the error, e.g. `'typed data'`.\n */\nexport function assertTypedDataIntegersExact(\n doc: unknown,\n where = 'typed data',\n code: X402ErrorCode = 'INVALID_CONFIG'\n): void {\n if (!isRecord(doc)) return;\n const { domain, types, message, primaryType } = doc;\n\n if (isRecord(domain) && typeof domain.chainId === 'number' && !Number.isSafeInteger(domain.chainId)) {\n throw numberRefusal(`${where} domain.chainId`, domain.chainId, code);\n }\n if (!isRecord(message)) return;\n\n const structs = isRecord(types) ? { ...types } : {};\n delete structs['EIP712Domain'];\n const root = rootStruct(structs, primaryType);\n if (root) {\n checkTyped(root, message, `${where} message`, structs, code);\n if (typeof primaryType === 'string' && primaryType !== root && Array.isArray(structs[primaryType])) {\n checkTyped(primaryType, message, `${where} message`, structs, code);\n }\n return;\n }\n assertNoInexactNumber(message, `${where} message`, code);\n}\n\n/**\n * `JSON.parse` of an EIP-712 document, refusing one whose integers did not\n * survive the parse ({@link assertTypedDataIntegersExact}).\n */\nexport function parseTypedDataJson(\n text: string,\n where = 'typed data',\n code: X402ErrorCode = 'INVALID_CONFIG'\n): unknown {\n const doc: unknown = JSON.parse(text);\n assertTypedDataIntegersExact(doc, where, code);\n return doc;\n}\n","/**\n * uvd-x402-sdk - EnvKeyAdapter\n *\n * SigningWalletAdapter implementation using a raw private key.\n * Reads the key from a constructor parameter or the WALLET_PRIVATE_KEY\n * environment variable.\n *\n * Intended for server-side / CLI / agent use cases where the\n * signing key is available in the environment. NEVER use this\n * in browser contexts -- use OWSWalletAdapter instead.\n *\n * @example Using environment variable\n * ```ts\n * // Reads process.env.WALLET_PRIVATE_KEY\n * const wallet = new EnvKeyAdapter();\n * console.log(wallet.getAddress()); // 0x...\n * ```\n *\n * @example Using explicit key\n * ```ts\n * const wallet = new EnvKeyAdapter(process.env.MY_AGENT_KEY!);\n * const auth = await wallet.signEIP3009({\n * to: '0xRecipient',\n * amountUsdc: 0.10,\n * network: 'base',\n * });\n * ```\n */\n\nimport { ethers } from 'ethers';\nimport { getChainByName } from '../chains';\nimport { X402Error } from '../types';\nimport { parseTypedDataJson } from '../utils/uint';\nimport type {\n SigningWalletAdapter,\n EIP3009Params,\n EIP3009Authorization,\n} from '../wallet';\n\n/**\n * EnvKeyAdapter -- SigningWalletAdapter backed by a raw private key.\n */\nexport class EnvKeyAdapter implements SigningWalletAdapter {\n private readonly wallet: ethers.Wallet;\n\n /**\n * Create an EnvKeyAdapter.\n *\n * @param privateKey - Hex-encoded private key (with or without 0x prefix).\n * If omitted, reads from `process.env.WALLET_PRIVATE_KEY`.\n * @throws {X402Error} if no private key is available\n */\n constructor(privateKey?: string) {\n const key = privateKey || (typeof process !== 'undefined' ? process.env.WALLET_PRIVATE_KEY : undefined);\n\n if (!key) {\n throw new X402Error(\n 'No private key provided. Pass it to the constructor or set WALLET_PRIVATE_KEY env var.',\n 'WALLET_NOT_CONNECTED',\n );\n }\n\n this.wallet = new ethers.Wallet(key);\n }\n\n /**\n * Get the checksummed EVM wallet address.\n */\n getAddress(): string {\n return this.wallet.address;\n }\n\n /**\n * Sign a message using EIP-191 personal_sign.\n *\n * @param message - The message string to sign\n * @returns Hex-encoded signature\n */\n async signMessage(message: string): Promise<string> {\n return this.wallet.signMessage(message);\n }\n\n /**\n * Sign EIP-712 typed structured data.\n *\n * @param typedData - JSON string with `domain`, `types`, `primaryType`, and `message` fields\n * @returns Object with signature and v/r/s components\n * @throws {X402Error} `INVALID_CONFIG` when an integer field of `message`\n * (or `domain.chainId`) is a JSON number above 2**53 - 1: `JSON.parse`\n * rounded it, so it is refused instead of signed. Write uints as strings.\n */\n async signTypedData(typedData: string): Promise<{\n signature: string;\n v: number;\n r: string;\n s: string;\n }> {\n const parsed = parseTypedDataJson(typedData) as {\n domain: ethers.TypedDataDomain;\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n };\n\n // ethers v6 signTypedData does not take primaryType -- it infers it\n // from the types object (the type not listed as a field of another type).\n // We pass domain, types (without EIP712Domain), and the message value.\n const { domain, types, message } = parsed;\n\n // Remove EIP712Domain from types if present (ethers handles it via domain)\n const cleanTypes = { ...types };\n delete cleanTypes['EIP712Domain'];\n\n const signature = await this.wallet.signTypedData(domain, cleanTypes, message);\n const sig = ethers.Signature.from(signature);\n\n return {\n signature,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n };\n }\n\n /**\n * Sign a serialized EVM transaction.\n *\n * Uses the raw private key via ethers.Wallet.signTransaction().\n * Used by AdvancedEscrowClient for on-chain operations (release,\n * refund, charge) when constructed with a SigningWalletAdapter.\n *\n * @param unsignedTx - Hex-encoded unsigned transaction (ethers serialized)\n * @returns Hex-encoded signed raw transaction, ready for broadcast\n */\n async signTransaction(unsignedTx: string): Promise<string> {\n const tx = ethers.Transaction.from(unsignedTx);\n return this.wallet.signTransaction(tx);\n }\n\n /**\n * Sign an EIP-3009 ReceiveWithAuthorization for USDC.\n *\n * @param params - EIP-3009 parameters\n * @returns Signed authorization ready for facilitator relay\n */\n async signEIP3009(params: EIP3009Params): Promise<EIP3009Authorization> {\n const chain = getChainByName(params.network);\n if (!chain) {\n throw new X402Error(`Unsupported network: ${params.network}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `EIP-3009 is only supported on EVM chains. ${params.network} is ${chain.networkType}.`,\n 'CHAIN_NOT_SUPPORTED',\n );\n }\n\n const chainId = params.chainId ?? chain.chainId;\n const usdcAddress = params.usdcContract ?? chain.usdc.address;\n const from = this.wallet.address;\n const to = ethers.getAddress(params.to);\n const value = ethers.parseUnits(params.amountUsdc.toString(), chain.usdc.decimals);\n const validAfter = params.validAfter ?? 0;\n const validBefore = params.validBefore ?? Math.floor(Date.now() / 1000) + 300;\n\n // Generate random 32-byte nonce\n const nonce = ethers.hexlify(ethers.randomBytes(32));\n\n // EIP-712 domain (matches USDC contract's domain separator)\n const domain: ethers.TypedDataDomain = {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId,\n verifyingContract: usdcAddress,\n };\n\n // EIP-712 types for TransferWithAuthorization (ERC-3009)\n const types = {\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 };\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter,\n validBefore,\n nonce,\n };\n\n // Sign the EIP-712 typed data\n let signature: string;\n try {\n signature = await this.wallet.signTypedData(domain, types, message);\n } catch (error: unknown) {\n throw new X402Error(\n `Failed to sign EIP-3009 authorization: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error,\n );\n }\n\n const sig = ethers.Signature.from(signature);\n\n return {\n from,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n signature,\n };\n }\n}\n","/**\n * uvd-x402-sdk - OWSWalletAdapter\n *\n * SigningWalletAdapter over an Open Wallet Standard (OWS) vault. OWS keeps the\n * keys encrypted in a local vault and signs inside it; the key never reaches\n * this process.\n *\n * Written against `@open-wallet-standard/core` 1.4.2 (an optional peer\n * dependency: a native Node module, prebuilt for Linux glibc and macOS on x64\n * and arm64). Measured on 1.4.2, not taken from its docs:\n *\n * - Its functions take the wallet by name or id, the chain as CAIP-2\n * (`eip155:8453`), then the passphrase and the vault path, all positional.\n * They return `{ signature, recoveryId }`, the signature as hex without\n * `0x`: `r || s || v`, with v = 27/28 for messages and typed data and 0/1\n * for transactions.\n * - `signTypedData` takes the EIP-712 document as a JSON string and refuses\n * one without `EIP712Domain` in `types` or without `primaryType`. It hashes\n * `EIP712Domain` in the order it is given.\n * - Integers: a decimal string above 2**128 - 1 is refused (\"use hex\n * encoding\"), so is odd-length hex, and a JSON number above 2**64. Out of\n * range it signs ANOTHER value without a word: `2**256` as a uint256 is\n * signed as 0, `256` as a uint8 as 0, `-129` as an int8. It also accepts\n * an address with a bad checksum and bytes without `0x`, where ethers\n * refuses both.\n * - `signTransaction` signs keccak256 of whatever bytes it is given and\n * returns only the signature: the signed transaction is assembled here.\n * - A wrong passphrase is `decryption failed: aead::Error`; no error seen\n * carries the passphrase.\n *\n * So this adapter normalises typed data by the DECLARED EIP-712 type and\n * refuses what ethers refuses before anything is signed, and after signing it\n * recovers every signature with ethers over the digest `EnvKeyAdapter` signs:\n * a signature that does not recover to `getAddress()` is not returned.\n *\n * @example\n * ```ts\n * import * as ows from '@open-wallet-standard/core';\n * import { OWSWalletAdapter } from 'uvd-x402-sdk';\n *\n * const wallet = new OWSWalletAdapter(ows, {\n * wallet: 'agent-treasury', // name or id in the vault\n * passphrase: process.env.OWS_PASSPHRASE,\n * network: 'base',\n * });\n * const auth = await wallet.signEIP3009({\n * to: '0xRecipient',\n * amountUsdc: 0.50,\n * network: 'base',\n * });\n * ```\n */\n\nimport { ethers } from 'ethers';\nimport { getChainByName } from '../chains';\nimport { X402Error } from '../types';\nimport { inexactNumberMessage } from '../utils/uint';\nimport type {\n SigningWalletAdapter,\n EIP3009Params,\n EIP3009Authorization,\n} from '../wallet';\n\n// ============================================================================\n// THE LIBRARY, AS 1.4.2 DECLARES IT\n// ============================================================================\n\n/** What a signing call of `@open-wallet-standard/core` returns. */\nexport interface OWSSignResult {\n /** Hex WITHOUT `0x`. On EVM, 65 bytes: `r || s || v`. */\n signature: string;\n /** The recovery byte again: 27/28 for messages and typed data, 0/1 for transactions. */\n recoveryId?: number;\n}\n\n/** One account of an OWS wallet (one per chain family). */\nexport interface OWSAccountInfo {\n /** CAIP-2 chain id; the EVM account is `eip155:1`. */\n chainId: string;\n address: string;\n derivationPath: string;\n}\n\n/**\n * The functions of `@open-wallet-standard/core` this adapter calls, with the\n * parameters its 1.4.2 `index.d.ts` declares (the same since 1.0.0). Pass the\n * module itself: `import * as ows from '@open-wallet-standard/core'`.\n *\n * Written by hand so that the SDK's types do not need the package installed;\n * `src/adapters/ows.test.ts` compares it with the installed declarations.\n */\nexport interface OWSCore {\n getWallet(\n nameOrId: string,\n vaultPathOpt?: string | null\n ): { id: string; name: string; accounts: OWSAccountInfo[]; createdAt: string };\n signMessage(\n wallet: string,\n chain: string,\n message: string,\n passphrase?: string | null,\n encoding?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n signTypedData(\n wallet: string,\n chain: string,\n typedDataJson: string,\n passphrase?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n signTransaction(\n wallet: string,\n chain: string,\n txHex: string,\n passphrase?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n}\n\nconst OWS_FUNCTIONS = ['getWallet', 'signMessage', 'signTypedData', 'signTransaction'] as const;\n\n/**\n * The wallet object the adapter took before it was written against\n * `@open-wallet-standard/core` 1.4.2.\n *\n * @deprecated This shape is not the `@open-wallet-standard/core` API and\n * never worked with OWS 1.x. It is still exported so that code importing it\n * compiles, but `new OWSWalletAdapter(wallet)` with it throws `INVALID_CONFIG`.\n * Migrate to {@link OWSCore}: pass the module and the wallet,\n * `new OWSWalletAdapter(ows, { wallet: '<name or id>', passphrase })` with\n * `import * as ows from '@open-wallet-standard/core'`.\n */\nexport interface OWSWallet {\n accounts: ReadonlyArray<{\n address: string;\n chains?: ReadonlyArray<string>;\n }>;\n signMessage(params: {\n account: { address: string };\n message: string | Uint8Array;\n }): Promise<{ signature: string }>;\n signTypedData(params: {\n account: { address: string };\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n }): Promise<{ signature: string }>;\n signTransaction(params: {\n account: { address: string };\n transaction: string;\n chainId: string;\n }): Promise<{ signedTransaction: string }>;\n}\n\nconst MIGRATION =\n \"pass the module and the wallet: new OWSWalletAdapter(ows, { wallet: '<name or id>', passphrase }) \" +\n \"with import * as ows from '@open-wallet-standard/core'\";\n\n/** Options of {@link OWSWalletAdapter}. */\nexport interface OWSWalletAdapterOptions {\n /** Name or id of the wallet in the OWS vault. */\n wallet: string;\n /**\n * Vault passphrase, or an OWS API key. Default: `process.env.OWS_PASSPHRASE`.\n * An explicit value, `''` included, wins over the environment.\n */\n passphrase?: string;\n /**\n * EVM network to sign for when the payload names no chain: an SDK name\n * (`'base'`) or CAIP-2 (`'eip155:8453'`). Default `'base'`. Typed data with\n * a `domain.chainId` and transactions with a `chainId` are signed on their\n * own chain. The chain is what an OWS policy decides on; it does not change\n * the bytes signed.\n */\n network?: string;\n /**\n * Vault directory. Default: the OWS default (`~/.ows`). OWS CREATES a\n * directory that does not exist, so a typo here gives an empty vault and\n * \"wallet not found\", not a missing-directory error.\n */\n vaultPath?: string;\n}\n\n// ============================================================================\n// TYPED DATA, AS OWS READS IT\n// ============================================================================\n\ntype TypedField = { name: string; type: string };\ntype TypedTypes = Record<string, TypedField[]>;\n\n/**\n * The EIP-712 domain fields in the order ethers derives `EIP712Domain` in.\n * OWS hashes the order it is given, so it gets this one.\n */\nconst EIP712_DOMAIN_FIELDS: ReadonlyArray<readonly [string, string]> = [\n ['name', 'string'],\n ['version', 'string'],\n ['chainId', 'uint256'],\n ['verifyingContract', 'address'],\n ['salt', 'bytes32'],\n];\n\n/** What ethers' `Transaction.from` reads from an object (6.16), `from` and `hash` aside. */\nconst TRANSACTION_FIELDS = [\n 'type',\n 'to',\n 'nonce',\n 'gasLimit',\n 'gasPrice',\n 'maxPriorityFeePerGas',\n 'maxFeePerGas',\n 'maxFeePerBlobGas',\n 'data',\n 'value',\n 'chainId',\n 'signature',\n 'accessList',\n 'authorizationList',\n 'blobVersionedHashes',\n 'kzg',\n 'blobWrapperVersion',\n 'blobs',\n] as const;\n\n/** Keys of other transaction formats, and the ethers name of the same field. */\nconst ETHERS_NAME_OF: Readonly<Record<string, string>> = { input: 'data', gas: 'gasLimit' };\n\nconst TWO_127 = 1n << 127n;\nconst TWO_128 = 1n << 128n;\nconst TWO_256 = 1n << 256n;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction shown(value: unknown): string {\n if (typeof value === 'bigint') return `${value}n`;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction refuse(message: string): X402Error {\n return new X402Error(`${message}; nothing was signed`, 'INVALID_CONFIG');\n}\n\n/**\n * An integer given as a bigint, a safe-integer number, a decimal string or a\n * 0x-hex string, with an optional leading `-`: what ethers accepts for an\n * EIP-712 integer, minus whitespace and floats.\n */\nfunction toInteger(value: unknown, where: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number' && Number.isSafeInteger(value)) return BigInt(value);\n // An integer past 2**53 - 1 is a value JSON.parse already rounded.\n if (typeof value === 'number' && Number.isInteger(value)) throw refuse(inexactNumberMessage(where, value));\n if (typeof value === 'string' && /^-?(0[xX][0-9a-fA-F]+|[0-9]+)$/.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n throw refuse(\n `${where}: ${shown(value)} is not an integer (a safe-integer number, a decimal string or 0x-hex)`\n );\n}\n\n/**\n * An integer the way OWS 1.4.2 reads it: decimal from -2**127 to 2**128 - 1,\n * even-length hex above, and 256-bit two's complement below (only a type\n * wider than 128 bits gets there).\n */\nfunction integerWire(n: bigint): string {\n if (n >= -TWO_127 && n < TWO_128) return n.toString();\n if (n > 0n) {\n const digits = n.toString(16);\n return `0x${digits.length % 2 ? '0' : ''}${digits}`;\n }\n return `0x${(n + TWO_256).toString(16).padStart(64, '0')}`;\n}\n\n/**\n * `value` of the EIP-712 type `kind` in the form OWS reads from JSON.\n *\n * Normalised by the DECLARED type, not by the JavaScript type of the value:\n * a uint256 comes as a number, a decimal string or 0x-hex (the lifecycle\n * order sends its `salt` as a decimal string above 2**128). Every integer is\n * checked against the range of its type here, before anything is signed.\n * Fields not in the type are left out; they are not part of the digest.\n */\nfunction owsValue(kind: string, value: unknown, types: TypedTypes, where: string): unknown {\n const array = /^(.*)\\[(\\d*)\\]$/.exec(kind);\n if (array) {\n const [, inner, size] = array;\n if (!Array.isArray(value)) throw refuse(`${where}: ${kind} needs an array, got ${shown(value)}`);\n if (size !== '' && value.length !== Number(size)) {\n throw refuse(`${where}: ${kind} needs ${size} items, got ${value.length}`);\n }\n return value.map((item, i) => owsValue(inner, item, types, `${where}[${i}]`));\n }\n\n const struct = types[kind];\n if (struct) {\n if (!isRecord(value)) throw refuse(`${where}: ${kind} needs an object, got ${shown(value)}`);\n const out: Record<string, unknown> = {};\n for (const field of struct) {\n if (value[field.name] === undefined) throw refuse(`${where}: ${kind} lacks ${field.name}`);\n out[field.name] = owsValue(field.type, value[field.name], types, `${where}.${field.name}`);\n }\n return out;\n }\n\n const integer = /^(u?)int(\\d+)$/.exec(kind);\n if (integer) {\n const bits = BigInt(integer[2]);\n const n = toInteger(value, where);\n const [low, high] = integer[1] ? [0n, 1n << bits] : [-(1n << (bits - 1n)), 1n << (bits - 1n)];\n if (n < low || n >= high) {\n throw new X402Error(\n `${where}: ${shown(value)} is out of range for ${kind}; nothing was signed`,\n 'INVALID_AMOUNT'\n );\n }\n return integerWire(n);\n }\n\n if (kind === 'bool') {\n if (typeof value !== 'boolean') throw refuse(`${where}: bool needs true or false, got ${shown(value)}`);\n return value;\n }\n if (kind === 'string') {\n if (typeof value !== 'string') throw refuse(`${where}: string needs a string, got ${shown(value)}`);\n return value;\n }\n if (kind === 'address') {\n try {\n if (typeof value !== 'string') throw new Error();\n return ethers.getAddress(value);\n } catch {\n throw refuse(`${where}: ${shown(value)} is not an address`);\n }\n }\n\n const bytes = /^bytes(\\d*)$/.exec(kind);\n if (bytes) {\n let raw: Uint8Array;\n try {\n if (typeof value !== 'string') throw new Error();\n raw = ethers.getBytes(value);\n } catch {\n throw refuse(`${where}: ${kind} needs 0x-hex, got ${shown(value)}`);\n }\n if (bytes[1] !== '' && raw.length !== Number(bytes[1])) {\n throw refuse(`${where}: ${kind} needs ${bytes[1]} bytes, got ${raw.length}`);\n }\n return ethers.hexlify(raw);\n }\n\n throw refuse(`${where}: unsupported EIP-712 type ${kind}`);\n}\n\ninterface PreparedTypedData {\n /** What OWS signs, as JSON. */\n document: string;\n /** The caller's domain, types (without EIP712Domain) and message: what ethers hashes. */\n domain: ethers.TypedDataDomain;\n types: TypedTypes;\n message: Record<string, unknown>;\n /** CAIP-2 chain of `domain.chainId`, if it names one. */\n chain: string | null;\n}\n\n/**\n * The typed data as the JSON document `signTypedData` of OWS takes.\n *\n * `EIP712Domain` is always derived from the domain's keys, in ethers' order,\n * and one the caller sent is ignored, as `EnvKeyAdapter` ignores it. The\n * root struct is the one ethers picks; a `primaryType` naming another is\n * refused (ethers would sign the root). Domain and message are normalised by\n * their declared types.\n */\nfunction prepareTypedData(input: unknown): PreparedTypedData {\n if (!isRecord(input)) throw refuse('typed data must be an object with domain, types and message');\n const { domain, types, message, primaryType } = input;\n if (!isRecord(domain)) throw refuse('typed data needs a domain object');\n if (!isRecord(types)) throw refuse('typed data needs a types object');\n if (!isRecord(message)) throw refuse('typed data needs a message object');\n\n const structs = { ...(types as TypedTypes) };\n delete structs['EIP712Domain'];\n let root: string;\n try {\n root = ethers.TypedDataEncoder.from(structs).primaryType;\n } catch (error) {\n throw refuse(`typed data types are invalid (${error instanceof Error ? error.message : error})`);\n }\n if (primaryType !== undefined && primaryType !== root) {\n throw refuse(\n `primaryType ${shown(primaryType)} is not ${root}, the root struct ethers signs for these types`\n );\n }\n\n for (const key of Object.keys(domain)) {\n if (!EIP712_DOMAIN_FIELDS.some(([name]) => name === key)) {\n throw refuse(`domain.${key} is not an EIP-712 domain field`);\n }\n }\n // ethers leaves a null domain field out of EIP712Domain; so does this.\n const all: TypedTypes = {\n EIP712Domain: EIP712_DOMAIN_FIELDS.filter(([name]) => domain[name] != null).map(\n ([name, type]) => ({ name, type })\n ),\n ...structs,\n };\n const owsDomain = owsValue('EIP712Domain', domain, all, 'domain') as Record<string, unknown>;\n const owsMessage = owsValue(root, message, all, 'message');\n\n const chainId = domain['chainId'] != null ? toInteger(domain['chainId'], 'domain.chainId') : 0n;\n return {\n document: JSON.stringify({ types: all, primaryType: root, domain: owsDomain, message: owsMessage }),\n domain: domain as ethers.TypedDataDomain,\n types: structs,\n message,\n chain: chainId > 0n ? `eip155:${chainId}` : null,\n };\n}\n\n/** The 65-byte signature of an OWS result, v as 27/28. */\nfunction evmSignature(result: OWSSignResult, what: string): ethers.Signature {\n const hex = String(result?.signature ?? '').replace(/^0x/, '');\n if (!/^[0-9a-fA-F]{130}$/.test(hex)) {\n throw new X402Error(`OWS ${what} returned a signature that is not 65 bytes of hex`, 'PAYMENT_FAILED');\n }\n const bytes = ethers.getBytes(`0x${hex}`);\n const v = bytes[64] < 27 ? bytes[64] + 27 : bytes[64];\n if (v !== 27 && v !== 28) {\n throw new X402Error(`OWS ${what} returned a recovery byte of ${bytes[64]}`, 'PAYMENT_FAILED');\n }\n return ethers.Signature.from({\n r: ethers.hexlify(bytes.subarray(0, 32)),\n s: ethers.hexlify(bytes.subarray(32, 64)),\n v,\n });\n}\n\n/** `eip155:<id>` of an SDK EVM network name or a CAIP-2 `eip155:` id. */\nfunction caip2(network: string): string {\n if (typeof network !== 'string') {\n throw new X402Error(\n `OWSWalletAdapter: options.network must be a string (an SDK network name or eip155:<id>), got ${typeof network}`,\n 'INVALID_CONFIG'\n );\n }\n const caip = /^eip155:([1-9][0-9]*)$/.exec(network);\n if (caip) return network;\n const chain = getChainByName(network);\n if (!chain || chain.networkType !== 'evm') {\n throw new X402Error(\n `OWSWalletAdapter signs for an EVM network; got ${shown(network)}`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n return `eip155:${chain.chainId}`;\n}\n\n// ============================================================================\n// OWS WALLET ADAPTER\n// ============================================================================\n\n/**\n * OWSWalletAdapter -- SigningWalletAdapter over an Open Wallet Standard vault.\n *\n * Every method signs the bytes `EnvKeyAdapter` signs for the same key (the\n * tests import an ephemeral key into a temporary vault and compare), or\n * throws `X402Error` and returns nothing. Refused before signing: an integer\n * out of the range of its EIP-712 type, and whatever ethers refuses to\n * encode. Refused after signing: a signature that does not recover to\n * `getAddress()` with ethers over the digest `EnvKeyAdapter` signs.\n *\n * The passphrase is held in a private field: `JSON.stringify`, `console.log`\n * and `util.inspect` of the adapter do not show it, and error messages are\n * scrubbed of it. Errors do not carry the library's original error object.\n */\nexport class OWSWalletAdapter implements SigningWalletAdapter {\n readonly #ows: OWSCore;\n readonly #wallet: string;\n readonly #passphrase: string | null;\n readonly #vaultPath: string | null;\n readonly #chain: string;\n readonly #address: string;\n\n /**\n * Create an OWSWalletAdapter.\n *\n * @param ows - The `@open-wallet-standard/core` module\n * (`import * as ows from '@open-wallet-standard/core'`), 1.4.2 or later 1.x.\n * @param options - Which wallet, its passphrase, the default network and the vault.\n * @throws {X402Error} `INVALID_CONFIG` if `ows` is not that module or no\n * wallet is named, `CHAIN_NOT_SUPPORTED` if `network` is not EVM,\n * `WALLET_NOT_FOUND` if the vault has no such wallet or it has no EVM account.\n */\n constructor(ows: OWSCore, options: OWSWalletAdapterOptions);\n /**\n * @deprecated The old form, a wallet object with `accounts`\n * ({@link OWSWallet}). It still compiles, but it never worked with OWS 1.x\n * and now throws `INVALID_CONFIG` without signing anything. Pass the module\n * and the wallet: `new OWSWalletAdapter(ows, { wallet, passphrase })`.\n */\n constructor(owsWallet: OWSWallet, accountIndex?: number);\n constructor(ows: OWSCore | OWSWallet, options?: OWSWalletAdapterOptions | number) {\n if (isRecord(ows) && 'accounts' in ows && (options === undefined || typeof options === 'number')) {\n throw new X402Error(\n 'OWSWalletAdapter no longer takes a wallet object with accounts (the deprecated OWSWallet ' +\n `shape, which never worked with @open-wallet-standard/core 1.x); ${MIGRATION}. Nothing was signed.`,\n 'INVALID_CONFIG'\n );\n }\n const missing = OWS_FUNCTIONS.filter(\n (name) => typeof (ows as unknown as Record<string, unknown> | null)?.[name] !== 'function'\n );\n if (missing.length > 0) {\n throw new X402Error(\n `OWSWalletAdapter takes the @open-wallet-standard/core module ` +\n `(import * as ows from '@open-wallet-standard/core'); it lacks ${missing.join(', ')}. ` +\n 'Since the OWS rewrite the adapter no longer takes a wallet object with accounts.',\n 'INVALID_CONFIG'\n );\n }\n const opts = (isRecord(options) ? options : {}) as Partial<OWSWalletAdapterOptions>;\n if (typeof opts.wallet !== 'string' || opts.wallet === '') {\n throw new X402Error('OWSWalletAdapter needs options.wallet: the name or id of a wallet in the vault', 'INVALID_CONFIG');\n }\n\n // The native binding echoes a mistyped argument in its error message, so a\n // passphrase that is not a string is refused here, without showing it.\n if (opts.passphrase != null && typeof opts.passphrase !== 'string') {\n throw new X402Error('OWSWalletAdapter: options.passphrase must be a string', 'INVALID_CONFIG');\n }\n\n this.#ows = ows as OWSCore;\n this.#wallet = opts.wallet;\n this.#passphrase =\n opts.passphrase ??\n (typeof process !== 'undefined' ? process.env?.OWS_PASSPHRASE : undefined) ??\n null;\n this.#vaultPath = opts.vaultPath ?? null;\n this.#chain = caip2(opts.network ?? 'base');\n\n const info = this.#call('getWallet', () => this.#ows.getWallet(this.#wallet, this.#vaultPath), 'WALLET_NOT_FOUND');\n const account = (info?.accounts ?? []).find((a) => String(a.chainId).startsWith('eip155:'));\n if (!account) {\n throw new X402Error(`OWS wallet ${shown(this.#wallet)} has no EVM account`, 'WALLET_NOT_FOUND');\n }\n this.#address = ethers.getAddress(account.address);\n }\n\n /**\n * Get the checksummed EVM wallet address (read from the vault once, when\n * the adapter was created; no passphrase needed).\n */\n getAddress(): string {\n return this.#address;\n }\n\n /**\n * Sign a message using EIP-191 personal_sign (the string as UTF-8, as\n * `EnvKeyAdapter` signs it).\n *\n * @param message - The message string to sign\n * @returns Hex-encoded 65-byte signature, v = 27/28\n */\n async signMessage(message: string): Promise<string> {\n if (typeof message !== 'string') throw refuse(`signMessage takes a string, got ${typeof message}`);\n const result = this.#call('signMessage', () =>\n this.#ows.signMessage(this.#wallet, this.#chain, message, this.#passphrase, 'utf8', null, this.#vaultPath)\n );\n const signature = evmSignature(result, 'signMessage').serialized;\n let signer = '';\n try {\n signer = ethers.verifyMessage(message, signature);\n } catch {\n // not recoverable: refused below\n }\n this.#checkSigner(signer, 'signMessage');\n return signature;\n }\n\n /**\n * Sign EIP-712 typed structured data.\n *\n * @param typedData - JSON string with `domain`, `types`, `message` and\n * optionally `primaryType` (it must then be the root struct)\n * @returns Object with signature and v/r/s components\n * @throws {X402Error} `INVALID_AMOUNT` for an integer out of its type's\n * range and `INVALID_CONFIG` for anything else ethers would not encode,\n * both before signing; `PAYMENT_FAILED` if OWS fails or signs a digest\n * other than the one ethers computes (the signature is not returned).\n */\n async signTypedData(typedData: string): Promise<{\n signature: string;\n v: number;\n r: string;\n s: string;\n }> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(typedData);\n } catch {\n throw refuse('typedData is not a JSON string');\n }\n return this.#signTyped(parsed);\n }\n\n /**\n * Sign an EVM transaction.\n *\n * OWS signs keccak256 of the bytes it is given and returns only the\n * signature, so the transaction is parsed and serialised with ethers here,\n * the way `EnvKeyAdapter` (ethers.Wallet) does it, EIP-155 `v` included.\n *\n * A sender, given as `from` or implied by an existing signature, must be\n * this wallet: it is taken out, as ethers takes it out; any other sender is\n * refused before signing.\n *\n * @param unsignedTx - Hex-encoded transaction (ethers serialized), an\n * `ethers.Transaction`, or a transaction object ethers' `Transaction.from`\n * accepts, plus `from`\n * @returns Hex-encoded signed raw transaction, ready for broadcast\n */\n async signTransaction(unsignedTx: string | ethers.TransactionLike<string>): Promise<string> {\n const tx = this.#unsignedTransaction(unsignedTx);\n const chain = tx.chainId > 0n ? `eip155:${tx.chainId}` : this.#chain;\n const result = this.#call('signTransaction', () =>\n this.#ows.signTransaction(\n this.#wallet,\n chain,\n tx.unsignedSerialized.slice(2),\n this.#passphrase,\n null,\n this.#vaultPath\n )\n );\n tx.signature = evmSignature(result, 'signTransaction');\n const signed = tx.serialized;\n this.#checkSigner(ethers.Transaction.from(signed).from ?? '', 'signTransaction');\n return signed;\n }\n\n /**\n * Sign an EIP-3009 TransferWithAuthorization for USDC: the typed data\n * `EnvKeyAdapter.signEIP3009` builds, signed through {@link signTypedData}\n * (OWS has no EIP-3009 call of its own).\n *\n * @param params - EIP-3009 parameters\n * @returns Signed authorization ready for facilitator relay\n */\n async signEIP3009(params: EIP3009Params): Promise<EIP3009Authorization> {\n const chain = getChainByName(params.network);\n if (!chain) {\n throw new X402Error(`Unsupported network: ${params.network}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `EIP-3009 is only supported on EVM chains. ${params.network} is ${chain.networkType}.`,\n 'CHAIN_NOT_SUPPORTED',\n );\n }\n\n const chainId = params.chainId ?? chain.chainId;\n const usdcAddress = params.usdcContract ?? chain.usdc.address;\n const from = this.#address;\n const to = ethers.getAddress(params.to);\n const value = ethers.parseUnits(params.amountUsdc.toString(), chain.usdc.decimals);\n const validAfter = params.validAfter ?? 0;\n const validBefore = params.validBefore ?? Math.floor(Date.now() / 1000) + 300;\n\n // Generate random 32-byte nonce\n const nonce = ethers.hexlify(ethers.randomBytes(32));\n\n const signed = await this.#signTyped({\n domain: {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId,\n verifyingContract: usdcAddress,\n },\n types: {\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 },\n primaryType: 'TransferWithAuthorization',\n message: { from, to, value, validAfter, validBefore, nonce },\n });\n\n return {\n from,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n v: signed.v,\n r: signed.r,\n s: signed.s,\n signature: signed.signature,\n };\n }\n\n // --------------------------------------------------------------------------\n\n async #signTyped(input: unknown): Promise<{ signature: string; v: number; r: string; s: string }> {\n const typed = prepareTypedData(input);\n const result = this.#call('signTypedData', () =>\n this.#ows.signTypedData(\n this.#wallet,\n typed.chain ?? this.#chain,\n typed.document,\n this.#passphrase,\n null,\n this.#vaultPath\n )\n );\n const sig = evmSignature(result, 'signTypedData');\n let signer: string;\n try {\n signer = ethers.verifyTypedData(typed.domain, typed.types, typed.message, sig);\n } catch (error) {\n throw new X402Error(\n `ethers cannot encode this typed data (${error instanceof Error ? error.message : error}); ` +\n 'the OWS signature is not returned',\n 'INVALID_CONFIG'\n );\n }\n this.#checkSigner(signer, 'signTypedData');\n return { signature: sig.serialized, v: sig.v, r: sig.r, s: sig.s };\n }\n\n #unsignedTransaction(input: string | ethers.TransactionLike<string>): ethers.Transaction {\n const senders: unknown[] = [];\n let tx: ethers.Transaction;\n try {\n if (typeof input === 'string') {\n tx = ethers.Transaction.from(input);\n } else if (typeof input === 'object' && input !== null) {\n // Read field by field, not spread: an ethers.Transaction keeps its\n // fields behind getters, and a spread of it is an empty transaction.\n const source = input as Record<string, unknown>;\n // An ethers.Transaction has no own keys; a plain object may only use\n // the keys ethers reads, so that no field is dropped on the way.\n for (const key of Object.keys(source)) {\n if (key === 'from' || key === 'hash' || (TRANSACTION_FIELDS as readonly string[]).includes(key)) continue;\n const ethersName = ETHERS_NAME_OF[key];\n throw refuse(\n `transaction key ${shown(key)} is not one ethers reads` +\n (ethersName ? `; ethers calls it ${ethersName}` : '')\n );\n }\n if (source.from != null) senders.push(source.from);\n const fields: Record<string, unknown> = {};\n for (const key of TRANSACTION_FIELDS) {\n if (source[key] != null) fields[key] = source[key];\n }\n tx = ethers.Transaction.from(fields);\n } else {\n throw new Error(`got ${typeof input}`);\n }\n } catch (error) {\n if (error instanceof X402Error) throw error;\n throw refuse(\n `not a transaction ethers can read (${error instanceof Error ? error.message : error})`\n );\n }\n if (tx.signature) senders.push(tx.from);\n for (const sender of senders) {\n let address = '';\n try {\n address = ethers.getAddress(sender as string);\n } catch {\n // not an address: refused below\n }\n if (address !== this.#address) {\n throw refuse(`transaction from ${shown(sender)} is not this wallet (${this.#address})`);\n }\n }\n tx.signature = null;\n return tx;\n }\n\n #checkSigner(signer: string, what: string): void {\n if (signer !== this.#address) {\n throw new X402Error(\n `OWS ${what} returned a signature that does not recover to ${this.#address} over the ` +\n 'digest ethers computes (the one EnvKeyAdapter signs); it is not returned',\n 'PAYMENT_FAILED'\n );\n }\n }\n\n /** Run one OWS call; its error becomes an X402Error without the passphrase in it. */\n #call<T>(what: string, run: () => T, code: 'PAYMENT_FAILED' | 'WALLET_NOT_FOUND' = 'PAYMENT_FAILED'): T {\n try {\n return run();\n } catch (error) {\n let message = error instanceof Error ? error.message : String(error);\n if (this.#passphrase) message = message.split(this.#passphrase).join('[redacted]');\n throw new X402Error(`OWS ${what} failed: ${message}`, code);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/chains/index.ts","../../src/types/index.ts","../../src/utils/base64.ts","../../src/utils/x402.ts","../../src/utils/validation.ts","../../src/adapters/wagmi.ts","../../src/utils/uint.ts","../../src/adapters/env-key.ts","../../src/adapters/ows.ts"],"names":["caip2","parseUnits","ethers","isRecord"],"mappings":";;;;;AAmBO,IAAM,uBAAA,GAA0B,yCAAA;AAUhC,IAAM,gBAAA,GAAgD;AAAA,EAC3D,gBAAA,EAAkB;AAAA,IAChB,OAAA,EAAS,CAAA;AAAA,IAAG,UAAA,EAAY,KAAA;AAAA,IAAO,IAAA,EAAM,gBAAA;AAAA,IACrC,WAAA,EAAa,QAAA;AAAA,IAAU,WAAA,EAAa,QAAA;AAAA,IACpC,MAAA,EAAQ,8CAAA;AAAA,IAAgD,WAAA,EAAa,6BAAA;AAAA,IACrE,gBAAgB,EAAE,IAAA,EAAM,QAAQ,MAAA,EAAQ,MAAA,EAAQ,UAAU,CAAA,EAAE;AAAA,IAC5D,IAAA,EAAM,EAAE,OAAA,EAAS,YAAA,EAAc,UAAU,CAAA,EAAG,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,EAAA,EAAG;AAAA,IACtE,MAAA,EAAQ;AAAA,MACN,IAAA,EAAM,EAAE,OAAA,EAAS,YAAA,EAAc,UAAU,CAAA,EAAG,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,EAAA;AAAG,KACxE;AAAA,IACA,IAAA,EAAM,EAAE,cAAA,EAAgB,uBAAA,EAAyB,SAAS,IAAA;AAAK,GACjE;AAAA,EACA,gBAAA,EAAkB;AAAA,IAChB,OAAA,EAAS,CAAA;AAAA,IAAG,UAAA,EAAY,KAAA;AAAA,IAAO,IAAA,EAAM,gBAAA;AAAA,IACrC,WAAA,EAAa,gBAAA;AAAA,IAAkB,WAAA,EAAa,QAAA;AAAA,IAC5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AK,QAAA,EAAU;AAC5B,MAAA,MAAM,IAAI,SAAA;AAAA,QACR,CAAA,IAAA,EAAO,IAAI,CAAA,+CAAA,EAAkD,IAAA,CAAK,QAAQ,CAAA,kFAAA,CAAA;AAAA,QAE1E;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,KAAA,CAAS,IAAA,EAAc,GAAA,EAAc,IAAA,GAA8C,gBAAA,EAAqB;AACtG,IAAA,IAAI;AACF,MAAA,OAAO,GAAA,EAAI;AAAA,IACb,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACnE,MAAA,IAAI,IAAA,CAAK,aAAa,OAAA,GAAU,OAAA,CAAQ,MAAM,IAAA,CAAK,WAAW,CAAA,CAAE,IAAA,CAAK,YAAY,CAAA;AACjF,MAAA,MAAM,IAAI,SAAA,CAAU,CAAA,IAAA,EAAO,IAAI,CAAA,SAAA,EAAY,OAAO,IAAI,IAAI,CAAA;AAAA,IAC5D;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * uvd-x402-sdk - Chain Registry\n *\n * Complete configuration for all 29 supported blockchain networks.\n * EVM chains (17): Use ERC-3009 TransferWithAuthorization (includes Scroll, SKALE Base, Robinhood Chain mainnet + testnet, Arc mainnet + testnet)\n * BSC is registered but disabled (Binance-Peg USDC has no ERC-3009), so it is not in those counts.\n * SVM chains (2): Solana and Fogo - Use SPL tokens with partially-signed transactions\n * Stellar (1): Uses Soroban authorization entries\n * NEAR (1): Uses NEP-366 meta-transactions\n * Algorand (2): Uses ASA transfers with atomic transaction groups\n * Sui (2): Uses sponsored transactions (facilitator pays gas)\n * XRPL (2): Native XRP via pre-signed Payment transaction blobs (facilitator pays fee)\n */\n\nimport type { ChainConfig, NetworkType, TokenType, TokenConfig } from '../types';\n\n/**\n * Default facilitator URL for x402 payments\n */\nexport const DEFAULT_FACILITATOR_URL = 'https://facilitator.ultravioletadao.xyz';\n\n/**\n * All supported chains configuration\n *\n * To add a new chain:\n * 1. Add chain config below with all required fields\n * 2. Verify USDC contract supports ERC-3009 (transferWithAuthorization) for EVM chains\n * 3. Test on testnet first before enabling\n */\nexport const SUPPORTED_CHAINS: Record<string, ChainConfig> = {\n 'hedera:mainnet': {\n chainId: 0, chainIdHex: '0x0', name: 'hedera:mainnet',\n displayName: 'Hedera', networkType: 'hedera',\n rpcUrl: 'https://mainnet-public.mirrornode.hedera.com', explorerUrl: 'https://hashscan.io/mainnet',\n nativeCurrency: { name: 'HBAR', symbol: 'HBAR', decimals: 8 },\n usdc: { address: '0.0.456858', decimals: 6, name: 'USDC', version: '' },\n tokens: {\n usdc: { address: '0.0.456858', decimals: 6, name: 'USDC', version: '' },\n },\n x402: { facilitatorUrl: DEFAULT_FACILITATOR_URL, enabled: true },\n },\n 'hedera:testnet': {\n chainId: 0, chainIdHex: '0x0', name: 'hedera:testnet',\n displayName: 'Hedera Testnet', networkType: 'hedera',\n rpcUrl: 'https://testnet.mirrornode.hedera.com', explorerUrl: 'https://hashscan.io/testnet',\n nativeCurrency: { name: 'HBAR', symbol: 'HBAR', decimals: 8 },\n usdc: { address: '0.0.429274', decimals: 6, name: 'USDC', version: '' },\n tokens: {\n usdc: { address: '0.0.429274', decimals: 6, name: 'USDC', version: '' },\n },\n x402: { facilitatorUrl: DEFAULT_FACILITATOR_URL, enabled: true },\n },\n\n // ============================================================================\n // EVM CHAINS (16 enabled + BSC, disabled)\n // ============================================================================\n\n base: {\n chainId: 8453,\n chainIdHex: '0x2105',\n name: 'base',\n displayName: 'Base',\n networkType: 'evm',\n rpcUrl: 'https://mainnet.base.org',\n explorerUrl: 'https://basescan.org',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n eurc: {\n address: '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n avalanche: {\n chainId: 43114,\n chainIdHex: '0xa86a',\n name: 'avalanche',\n displayName: 'Avalanche C-Chain',\n networkType: 'evm',\n rpcUrl: 'https://avalanche-c-chain-rpc.publicnode.com',\n explorerUrl: 'https://snowtrace.io',\n nativeCurrency: {\n name: 'Avalanche',\n symbol: 'AVAX',\n decimals: 18,\n },\n usdc: {\n address: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n // name() on-chain is \"Euro Coin\" here and \"EURC\" on Base: pinned to each\n // contract's DOMAIN_SEPARATOR() by src/eurc-domains.test.ts.\n eurc: {\n address: '0xC891EB4cbdEFf6e073e859e987815Ed1505c2ACD',\n decimals: 6,\n name: 'Euro Coin',\n version: '2',\n usdPegged: false,\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n ethereum: {\n chainId: 1,\n chainIdHex: '0x1',\n name: 'ethereum',\n displayName: 'Ethereum',\n networkType: 'evm',\n rpcUrl: 'https://eth.llamarpc.com',\n explorerUrl: 'https://etherscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n eurc: {\n address: '0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c',\n decimals: 6,\n name: 'Euro Coin',\n version: '2',\n usdPegged: false,\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n pyusd: {\n address: '0x6c3ea9036406852006290770BEdFcAbA0e23A0e8',\n decimals: 6,\n name: 'PayPal USD',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n polygon: {\n chainId: 137,\n chainIdHex: '0x89',\n name: 'polygon',\n displayName: 'Polygon',\n networkType: 'evm',\n rpcUrl: 'https://polygon-rpc.com',\n explorerUrl: 'https://polygonscan.com',\n nativeCurrency: {\n name: 'Polygon',\n symbol: 'POL',\n decimals: 18,\n },\n usdc: {\n address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n arbitrum: {\n chainId: 42161,\n chainIdHex: '0xa4b1',\n name: 'arbitrum',\n displayName: 'Arbitrum One',\n networkType: 'evm',\n rpcUrl: 'https://arb1.arbitrum.io/rpc',\n explorerUrl: 'https://arbiscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n usdt: {\n address: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6,\n name: 'USD₮0',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n optimism: {\n chainId: 10,\n chainIdHex: '0xa',\n name: 'optimism',\n displayName: 'Optimism',\n networkType: 'evm',\n rpcUrl: 'https://mainnet.optimism.io',\n explorerUrl: 'https://optimistic.etherscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n usdt: {\n address: '0x01bff41798a0bcf287b996046ca68b395dbc1071',\n decimals: 6,\n name: 'USD₮0',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n celo: {\n chainId: 42220,\n chainIdHex: '0xa4ec',\n name: 'celo',\n displayName: 'Celo',\n networkType: 'evm',\n rpcUrl: 'https://forno.celo.org',\n explorerUrl: 'https://celoscan.io',\n nativeCurrency: {\n name: 'Celo',\n symbol: 'CELO',\n decimals: 18,\n },\n usdc: {\n address: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6,\n name: 'USDC', // Celo uses \"USDC\" not \"USD Coin\" for EIP-712\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6,\n name: 'USDC', // Celo uses \"USDC\" not \"USD Coin\" for EIP-712\n version: '2',\n },\n usdt: {\n address: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6,\n name: 'Tether USD', // Celo USDT uses \"Tether USD\" for EIP-712\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n hyperevm: {\n chainId: 999,\n chainIdHex: '0x3e7',\n name: 'hyperevm',\n displayName: 'HyperEVM',\n networkType: 'evm',\n rpcUrl: 'https://rpc.hyperliquid.xyz/evm',\n explorerUrl: 'https://hyperevmscan.io',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0xb88339CB7199b77E23DB6E890353E22632Ba630f',\n decimals: 6,\n name: 'USDC', // HyperEVM uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0xb88339CB7199b77E23DB6E890353E22632Ba630f',\n decimals: 6,\n name: 'USDC', // HyperEVM uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n unichain: {\n chainId: 130,\n chainIdHex: '0x82',\n name: 'unichain',\n displayName: 'Unichain',\n networkType: 'evm',\n rpcUrl: 'https://unichain-rpc.publicnode.com',\n explorerUrl: 'https://uniscan.xyz',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x078d782b760474a361dda0af3839290b0ef57ad6',\n decimals: 6,\n name: 'USDC', // Unichain uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x078d782b760474a361dda0af3839290b0ef57ad6',\n decimals: 6,\n name: 'USDC', // Unichain uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n monad: {\n chainId: 143,\n chainIdHex: '0x8f',\n name: 'monad',\n displayName: 'Monad',\n networkType: 'evm',\n rpcUrl: 'https://rpc.monad.xyz',\n explorerUrl: 'https://monad.socialscan.io',\n nativeCurrency: {\n name: 'Monad',\n symbol: 'MON',\n decimals: 18,\n },\n usdc: {\n address: '0x754704bc059f8c67012fed69bc8a327a5aafb603',\n decimals: 6,\n name: 'USDC', // Monad uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x754704bc059f8c67012fed69bc8a327a5aafb603',\n decimals: 6,\n name: 'USDC', // Monad uses \"USDC\" not \"USD Coin\"\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n usdt: {\n address: '0xe7cd86e13AC4309349F30B3435a9d337750fC82D',\n decimals: 6,\n name: 'USD\\u20AE0', // USD₮0 (USDT0 omnichain via LayerZero)\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n bsc: {\n chainId: 56,\n chainIdHex: '0x38',\n name: 'bsc',\n displayName: 'BNB Smart Chain',\n networkType: 'evm',\n rpcUrl: 'https://binance.llamarpc.com',\n explorerUrl: 'https://bscscan.com',\n nativeCurrency: {\n name: 'Binance Coin',\n symbol: 'BNB',\n decimals: 18,\n },\n usdc: {\n // Binance-Peg USDC — 18 decimals, NOT the 6 every other chain uses.\n address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18,\n name: 'USD Coin',\n version: '2',\n },\n ausd: {\n address: '0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a',\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n // Disabled on purpose: Binance-Peg USDC does not implement ERC-3009\n // `transferWithAuthorization`, so the exact scheme cannot settle it. The\n // entry exists so the 18-decimal figure is on record — assuming the usual\n // 6 here mis-prices a payment by 12 orders of magnitude.\n enabled: false,\n },\n },\n\n scroll: {\n chainId: 534352,\n chainIdHex: '0x82750',\n name: 'scroll',\n displayName: 'Scroll',\n networkType: 'evm',\n rpcUrl: 'https://rpc.scroll.io',\n explorerUrl: 'https://scrollscan.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4',\n decimals: 6,\n name: 'USD Coin',\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'skale-base': {\n chainId: 1187947933,\n chainIdHex: '0x46cea59d',\n name: 'skale-base',\n displayName: 'SKALE Base',\n networkType: 'evm',\n rpcUrl: 'https://skale-base.skalenodes.com/v1/base',\n explorerUrl: 'https://skale-base-explorer.skalenodes.com',\n nativeCurrency: {\n name: 'CREDIT',\n symbol: 'CREDIT',\n decimals: 18,\n },\n usdc: {\n address: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'skale-base-sepolia': {\n chainId: 324705682,\n chainIdHex: '0x135a9d92',\n name: 'skale-base-sepolia',\n displayName: 'SKALE Base Sepolia',\n networkType: 'evm',\n rpcUrl: 'https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha',\n explorerUrl: 'https://base-sepolia-testnet-explorer.skalenodes.com',\n nativeCurrency: {\n name: 'CREDIT',\n symbol: 'CREDIT',\n decimals: 18,\n },\n usdc: {\n address: '0x2e08028E3C4c2356572E096d8EF835cD5C6030bD',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x2e08028E3C4c2356572E096d8EF835cD5C6030bD',\n decimals: 6,\n name: 'Bridged USDC (SKALE Bridge)', // Must match on-chain EIP-712 domain exactly\n version: '2',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // Robinhood Chain (Arbitrum Orbit L2). NOTE: there is NO USDC on this chain -\n // the settlement stablecoin is Paxos USDG (Global Dollar). The `usdc` field\n // below carries USDG for interface compatibility (same pattern as XRPL's native\n // asset), and `tokens.usdg` is the canonical entry.\n // CRITICAL: USDG's on-chain version() getter REVERTS, so the EIP-712 domain\n // { name: 'Global Dollar', version: '1' } can NEVER be resolved on-chain and\n // MUST come from this config (mirrored into PaymentRequirements.extra by callers).\n robinhood: {\n chainId: 4663,\n chainIdHex: '0x1237',\n name: 'robinhood',\n displayName: 'Robinhood Chain',\n networkType: 'evm',\n rpcUrl: 'https://rpc.mainnet.chain.robinhood.com',\n explorerUrl: 'https://robinhoodchain.blockscout.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168', // Paxos USDG (no USDC on this chain)\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n tokens: {\n usdg: {\n address: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168',\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'robinhood-testnet': {\n chainId: 46630,\n chainIdHex: '0xb626',\n name: 'robinhood-testnet',\n displayName: 'Robinhood Chain Testnet',\n networkType: 'evm',\n rpcUrl: 'https://rpc.testnet.chain.robinhood.com',\n explorerUrl: 'https://explorer.testnet.chain.robinhood.com',\n nativeCurrency: {\n name: 'Ethereum',\n symbol: 'ETH',\n decimals: 18,\n },\n usdc: {\n address: '0x7E955252E15c84f5768B83c41a71F9eba181802F', // Paxos USDG testnet (no USDC on this chain)\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n tokens: {\n usdg: {\n address: '0x7E955252E15c84f5768B83c41a71F9eba181802F',\n decimals: 6,\n name: 'Global Dollar', // on-chain version() reverts; domain must be supplied off-chain\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // Arc testnet (Circle). The stablecoin IS the chain's native asset, so the SAME\n // balance is readable at TWO precisions:\n // - native / gas, via eth_getBalance and EIP-1559 fees: 18 decimals\n // - ERC-20 interface, via balanceOf and transferWithAuthorization: 6 decimals\n // (the ERC-20 view is floor(native / 10^12))\n // An x402 payment is an EIP-3009 authorization against the ERC-20 interface, so\n // its `value` is ALWAYS in the 6 of `tokens.usdc.decimals`. Scaling a price with\n // `nativeCurrency.decimals` instead charges 10^12 times the amount: $0.01 would\n // be signed as 10000000000000000 units, i.e. 10 billion USDC. `nativeCurrency`\n // below is correct where it is actually used -- the wallet_addEthereumChain\n // params -- and must never reach `parseUnits` for a payment.\n // Pinned by src/arc-testnet.test.ts.\n //\n // Mainnet (5042) and testnet (5042002) were verified independently against\n // their official RPCs on 2026-09-16. EURC domains checked on 2026-09-17; funded EURC payments settled on Arc mainnet on\n // 2026-09-22 (x402 v1/v2, docs/networks/arc.md); testnet pending.\n arc: {\n chainId: 5042,\n chainIdHex: '0x13b2',\n name: 'arc',\n displayName: 'Arc',\n networkType: 'evm',\n rpcUrl: 'https://rpc.mainnet.arc.io',\n explorerUrl: 'https://explorer.arc.io',\n nativeCurrency: {\n name: 'USD Coin',\n symbol: 'USDC',\n decimals: 18, // gas precision ONLY -- never the scale of a payment\n },\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6, // ERC-20 interface, which is what an EIP-3009 value is denominated in\n name: 'USDC', // on-chain name(); must match the EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6,\n name: 'USDC',\n version: '2',\n },\n eurc: {\n address: '0xbEf5f6d51CB62b58e6A8f77868681825C6fe21c1',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'arc-testnet': {\n chainId: 5042002,\n chainIdHex: '0x4cef52',\n name: 'arc-testnet',\n displayName: 'Arc Testnet',\n networkType: 'evm',\n rpcUrl: 'https://rpc.testnet.arc.io',\n explorerUrl: 'https://explorer.testnet.arc.io',\n nativeCurrency: {\n name: 'USD Coin',\n symbol: 'USDC',\n decimals: 18, // gas precision ONLY -- never the scale of a payment\n },\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6, // ERC-20 interface, which is what an EIP-3009 value is denominated in\n name: 'USDC', // on-chain name(); must match the EIP-712 domain exactly\n version: '2',\n },\n tokens: {\n usdc: {\n address: '0x3600000000000000000000000000000000000000',\n decimals: 6,\n name: 'USDC',\n version: '2',\n },\n eurc: {\n address: '0x89B50855Aa3bE2F677cD6303Cec089B5F319D72a',\n decimals: 6,\n name: 'EURC',\n version: '2',\n usdPegged: false,\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // SVM CHAINS (2 networks) - Solana Virtual Machine\n // ============================================================================\n\n solana: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'solana',\n displayName: 'Solana',\n networkType: 'svm',\n rpcUrl: 'https://api.mainnet-beta.solana.com',\n explorerUrl: 'https://solscan.io',\n nativeCurrency: {\n name: 'Solana',\n symbol: 'SOL',\n decimals: 9,\n },\n usdc: {\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC SPL token mint\n decimals: 6,\n name: 'USD Coin',\n version: '1',\n },\n tokens: {\n usdc: {\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC SPL token mint\n decimals: 6,\n name: 'USD Coin',\n version: '1',\n },\n ausd: {\n address: 'AUSD1jCcCyPLybk1YnvPWsHQSrZ46dxwoMniN4N2UEB9', // AUSD Token2022 mint\n decimals: 6,\n name: 'Agora Dollar',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n fogo: {\n chainId: 0, // Non-EVM (SVM)\n chainIdHex: '0x0',\n name: 'fogo',\n displayName: 'Fogo',\n networkType: 'svm',\n rpcUrl: 'https://rpc.fogo.nightly.app/',\n explorerUrl: 'https://explorer.fogo.nightly.app',\n nativeCurrency: {\n name: 'Fogo',\n symbol: 'FOGO',\n decimals: 9,\n },\n usdc: {\n address: 'uSd2czE61Evaf76RNbq4KPpXnkiL3irdzgLFUMe3NoG', // Fogo USDC mint\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // STELLAR (1 network)\n // ============================================================================\n\n stellar: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'stellar',\n displayName: 'Stellar',\n networkType: 'stellar',\n rpcUrl: 'https://horizon.stellar.org',\n explorerUrl: 'https://stellar.expert/explorer/public',\n nativeCurrency: {\n name: 'Lumens',\n symbol: 'XLM',\n decimals: 7, // Stellar uses 7 decimals (stroops)\n },\n usdc: {\n address: 'CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75', // Soroban Asset Contract\n decimals: 7, // Stellar USDC uses 7 decimals\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // NEAR (1 network) - Uses NEP-366 meta-transactions\n // ============================================================================\n\n near: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'near',\n displayName: 'NEAR Protocol',\n networkType: 'near',\n rpcUrl: 'https://rpc.mainnet.near.org',\n explorerUrl: 'https://nearblocks.io',\n nativeCurrency: {\n name: 'NEAR',\n symbol: 'NEAR',\n decimals: 24, // NEAR uses 24 decimals (yoctoNEAR)\n },\n usdc: {\n address: '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1', // Native Circle USDC\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true, // NEP-366 meta-transactions supported\n },\n },\n\n // ============================================================================\n // ALGORAND (2 networks) - Uses ASA transfers with atomic transaction groups\n // ============================================================================\n\n algorand: {\n chainId: 0, // Non-EVM (Algorand uses genesis hash for network identification)\n chainIdHex: '0x0',\n name: 'algorand',\n displayName: 'Algorand',\n networkType: 'algorand',\n rpcUrl: 'https://mainnet-api.algonode.cloud',\n explorerUrl: 'https://allo.info',\n nativeCurrency: {\n name: 'Algo',\n symbol: 'ALGO',\n decimals: 6, // Algorand uses 6 decimals (microAlgos)\n },\n usdc: {\n address: '31566704', // USDC ASA ID on Algorand mainnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '31566704', // USDC ASA ID on Algorand mainnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'algorand-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'algorand-testnet',\n displayName: 'Algorand Testnet',\n networkType: 'algorand',\n rpcUrl: 'https://testnet-api.algonode.cloud',\n explorerUrl: 'https://testnet.allo.info',\n nativeCurrency: {\n name: 'Algo',\n symbol: 'ALGO',\n decimals: 6,\n },\n usdc: {\n address: '10458941', // USDC ASA ID on Algorand testnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '10458941', // USDC ASA ID on Algorand testnet\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // SUI (2 networks) - Uses sponsored transactions (facilitator pays gas)\n // ============================================================================\n\n sui: {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'sui',\n displayName: 'Sui',\n networkType: 'sui',\n rpcUrl: 'https://fullnode.mainnet.sui.io:443',\n explorerUrl: 'https://suiscan.xyz/mainnet',\n nativeCurrency: {\n name: 'Sui',\n symbol: 'SUI',\n decimals: 9,\n },\n usdc: {\n // USDC coin type on Sui mainnet\n address: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n ausd: {\n // AUSD (Agora USD) coin type on Sui mainnet\n address: '0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD',\n decimals: 6,\n name: 'AUSD',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'sui-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'sui-testnet',\n displayName: 'Sui Testnet',\n networkType: 'sui',\n rpcUrl: 'https://fullnode.testnet.sui.io:443',\n explorerUrl: 'https://suiscan.xyz/testnet',\n nativeCurrency: {\n name: 'Sui',\n symbol: 'SUI',\n decimals: 9,\n },\n usdc: {\n // USDC coin type on Sui testnet\n address: '0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n tokens: {\n usdc: {\n address: '0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC',\n decimals: 6,\n name: 'USDC',\n version: '1',\n },\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n // ============================================================================\n // XRPL (2 networks) - XRP Ledger, native XRP via pre-signed Payment blobs\n // ============================================================================\n\n // Named `xrpl`, which is the only spelling the facilitator puts on the wire\n // (x402-rs/src/network.rs:189). `xrpl-mainnet` still resolves, as an alias.\n xrpl: {\n chainId: 0, // Non-EVM (XRPL uses network id strings, no numeric chain ID)\n chainIdHex: '0x0',\n name: 'xrpl',\n displayName: 'XRP Ledger',\n networkType: 'xrpl',\n rpcUrl: 'https://xrplcluster.com',\n explorerUrl: 'https://livenet.xrpl.org',\n nativeCurrency: {\n name: 'XRP',\n symbol: 'XRP',\n decimals: 6, // XRPL uses 6 decimals (drops); 1 XRP = 1,000,000 drops\n },\n // XRPL settles in native XRP - there is no USDC/token contract.\n // The `usdc` field describes the native asset for interface compatibility.\n // `usdPegged: false` is what stops that compatibility shim from being read\n // as a price: the key says usdc, the value is XRP, and a caller who writes\n // \"10.00\" means ten dollars. See TokenConfig.usdPegged.\n usdc: {\n address: 'XRP', // Native asset - no token contract\n decimals: 6,\n name: 'XRP',\n version: '1',\n usdPegged: false,\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n\n 'xrpl-testnet': {\n chainId: 0, // Non-EVM\n chainIdHex: '0x0',\n name: 'xrpl-testnet',\n displayName: 'XRP Ledger Testnet',\n networkType: 'xrpl',\n rpcUrl: 'https://s.altnet.rippletest.net:51234',\n explorerUrl: 'https://testnet.xrpl.org',\n nativeCurrency: {\n name: 'XRP',\n symbol: 'XRP',\n decimals: 6,\n },\n // XRPL settles in native XRP - there is no USDC/token contract.\n usdc: {\n address: 'XRP', // Native asset - no token contract\n decimals: 6,\n name: 'XRP',\n version: '1',\n usdPegged: false,\n },\n x402: {\n facilitatorUrl: DEFAULT_FACILITATOR_URL,\n enabled: true,\n },\n },\n};\n\n/**\n * Alternate spellings that resolve to a registry entry without becoming one.\n *\n * A caller may WRITE these; the SDK never puts one on the wire, and they are\n * not separate networks, so counts and listings stay honest. The facilitator\n * keeps exactly this distinction: its `FromStr` takes `xrpl-mainnet` while\n * everything it publishes says `xrpl`, and the comment there calls that\n * spelling \"right for a lookup and wrong for a wire format\"\n * (`x402-rs/src/network.rs:251,189,719`).\n *\n * Mirrors `_NETWORK_ALIASES` in the Python SDK (`networks/base.py`).\n */\nexport const CHAIN_ALIASES: Record<string, string> = {\n hedera: 'hedera:mainnet',\n 'hedera-testnet': 'hedera:testnet',\n // Execution Market's and Karmakadabra's keys for SKALE Base.\n skale: 'skale-base',\n 'skale-testnet': 'skale-base-sepolia',\n // Renamed in 2.85.0: the facilitator advertises the mainnet as `xrpl`.\n 'xrpl-mainnet': 'xrpl',\n};\n\n/**\n * Default chain for new users\n */\nexport const DEFAULT_CHAIN = 'base';\n\n/**\n * Get chain config by chain ID\n */\nexport function getChainById(chainId: number): ChainConfig | undefined {\n return Object.values(SUPPORTED_CHAINS).find(chain => chain.chainId === chainId);\n}\n\n/**\n * Get chain config by name (case-insensitive)\n */\nexport function getChainByName(name: string): ChainConfig | undefined {\n const key = name.toLowerCase();\n return SUPPORTED_CHAINS[key] ?? SUPPORTED_CHAINS[CHAIN_ALIASES[key] ?? ''];\n}\n\n/**\n * Check if a chain is supported\n */\nexport function isChainSupported(chainIdOrName: number | string): boolean {\n if (typeof chainIdOrName === 'number') {\n return Object.values(SUPPORTED_CHAINS).some(chain => chain.chainId === chainIdOrName);\n }\n return getChainByName(chainIdOrName) !== undefined;\n}\n\n/**\n * Get list of enabled chains\n */\nexport function getEnabledChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(chain => chain.x402.enabled);\n}\n\n/**\n * Get list of chains by network type\n */\nexport function getChainsByNetworkType(networkType: NetworkType): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === networkType && chain.x402.enabled\n );\n}\n\n/**\n * Get all EVM chain IDs (for wallet_switchEthereumChain)\n */\nexport function getEVMChainIds(): number[] {\n return getChainsByNetworkType('evm').map(chain => chain.chainId);\n}\n\n/**\n * Get list of SVM chains (Solana, Fogo)\n */\nexport function getSVMChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'svm' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is SVM-based (Solana Virtual Machine)\n */\nexport function isSVMChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'svm';\n}\n\n/**\n * Get list of Sui chains\n */\nexport function getSuiChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'sui' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is Sui-based\n */\nexport function isSuiChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'sui';\n}\n\n/**\n * Get network type from chain name\n */\nexport function getNetworkType(chainName: string): NetworkType | undefined {\n const chain = getChainByName(chainName);\n return chain?.networkType;\n}\n\n/**\n * Format transaction URL for block explorer\n */\nexport function getExplorerTxUrl(chainName: string, txHash: string): string | null {\n const chain = getChainByName(chainName);\n if (!chain) return null;\n\n switch (chain.networkType) {\n case 'evm':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'svm':\n case 'solana': // @deprecated\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'stellar':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'near':\n return `${chain.explorerUrl}/txns/${txHash}`;\n case 'algorand':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'sui':\n return `${chain.explorerUrl}/tx/${txHash}`;\n case 'hedera':\n return `${chain.explorerUrl}/transaction/${txHash.replace(/^(0\\.0\\.\\d+)@(\\d+)\\.(\\d+)$/, '$1-$2-$3')}`;\n case 'xrpl':\n return `${chain.explorerUrl}/transactions/${txHash}`;\n default:\n return null;\n }\n}\n\n/**\n * Format address URL for block explorer\n */\nexport function getExplorerAddressUrl(chainName: string, address: string): string | null {\n const chain = getChainByName(chainName);\n if (!chain) return null;\n\n switch (chain.networkType) {\n case 'evm':\n return `${chain.explorerUrl}/address/${address}`;\n case 'svm':\n case 'solana': // @deprecated\n return `${chain.explorerUrl}/account/${address}`;\n case 'stellar':\n return `${chain.explorerUrl}/account/${address}`;\n case 'near':\n return `${chain.explorerUrl}/address/${address}`;\n case 'algorand':\n return `${chain.explorerUrl}/account/${address}`;\n case 'sui':\n return `${chain.explorerUrl}/account/${address}`;\n case 'hedera':\n return `${chain.explorerUrl}/account/${address}`;\n case 'xrpl':\n return `${chain.explorerUrl}/accounts/${address}`;\n default:\n return null;\n }\n}\n\n/**\n * Get list of Algorand chains\n */\nexport function getAlgorandChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'algorand' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is Algorand-based\n */\nexport function isAlgorandChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'algorand';\n}\n\n/**\n * Get list of XRPL chains (XRP Ledger mainnet/testnet)\n */\nexport function getXRPLChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n chain => chain.networkType === 'xrpl' && chain.x402.enabled\n );\n}\n\n/**\n * Check if a chain is XRPL-based (XRP Ledger)\n */\nexport function isXRPLChain(chainName: string): boolean {\n const chain = getChainByName(chainName);\n return chain?.networkType === 'xrpl';\n}\n\n// ============================================================================\n// MULTI-TOKEN SUPPORT FUNCTIONS\n// ============================================================================\n\n/**\n * Get token configuration for a specific chain and token type\n * Falls back to USDC config if token not found (for backward compatibility)\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns Token configuration or undefined if chain not found\n */\nexport function getTokenConfig(\n chainName: string,\n tokenType: TokenType = 'usdc'\n): TokenConfig | undefined {\n const chain = getChainByName(chainName);\n if (!chain) return undefined;\n\n // Try to get from tokens map first (new multi-token support)\n if (chain.tokens && chain.tokens[tokenType]) {\n return chain.tokens[tokenType];\n }\n\n // Fall back to usdc config for backward compatibility\n if (tokenType === 'usdc') {\n return chain.usdc;\n }\n\n return undefined;\n}\n\n/**\n * Whether a price written in dollars can be scaled into this token's base\n * units. Absent `usdPegged` means yes, so every stablecoin keeps its behaviour.\n *\n * @param token - Token configuration, or undefined\n * @returns True when one whole unit of the token is one dollar\n */\nexport function isUsdPegged(token: TokenConfig | undefined): boolean {\n return token?.usdPegged !== false;\n}\n\n/**\n * The sentence for refusing to price a network in dollars.\n *\n * Refusing without saying where to look only moves the dead end one layer up,\n * so this names the asset, states what the old code would have charged, and\n * points at the one place that lists the alternatives. Same shape as the Python\n * SDK's `NetworkConfig.usd_conversion_error()` (`networks/base.py:158`, 0.77.0)\n * so a team hitting this in either language reads the same explanation.\n *\n * @param chainName - Chain the price was written for\n * @param token - The settlement token that carries no dollar peg\n * @returns Message naming the asset and the way out\n */\nexport function usdConversionError(chainName: string, token: TokenConfig): string {\n const symbol = token.name || token.address;\n return (\n `${chainName} settles in ${symbol}, which is not pegged to the dollar, so an ` +\n `amount written in USD cannot be converted with its ${token.decimals} decimals: ` +\n `$1.00 would be charged as 1 ${symbol}. Name a dollar-pegged token this ` +\n `network's facilitator settles (GET /supported lists them; on XRPL that is the ` +\n `Circle USDC issued by rGm7WCVp9gb4jZHWTEtGUr4dd74z2XuWhE) and register it under ` +\n `the chain's \\`tokens\\`, or price the call in ${symbol} units yourself.`\n );\n}\n\n/**\n * Find which token of a chain a contract address belongs to.\n *\n * The signed payload carries the token *address*, but a server that accepts\n * several stablecoins on the same chain needs the symbol, the decimals and the\n * EIP-712 domain to rebuild the payment requirements. This resolves the address\n * back to the registry entry so that metadata can travel with the payment.\n *\n * @param chainName - Chain name (e.g., 'optimism')\n * @param address - Token contract address (case-insensitive on EVM)\n * @returns The token type and its config, or undefined if the address is not in the registry\n */\nexport function getTokenByAddress(\n chainName: string,\n address: string\n): { tokenType: TokenType; config: TokenConfig } | undefined {\n const chain = getChainByName(chainName);\n if (!chain || !address) return undefined;\n\n const wanted = address.startsWith('0x') ? address.toLowerCase() : address;\n const matches = (candidate: string): boolean =>\n (candidate.startsWith('0x') ? candidate.toLowerCase() : candidate) === wanted;\n\n if (chain.tokens) {\n for (const [tokenType, config] of Object.entries(chain.tokens)) {\n if (config && matches(config.address)) {\n return { tokenType: tokenType as TokenType, config };\n }\n }\n }\n\n if (chain.usdc && matches(chain.usdc.address)) {\n return { tokenType: 'usdc', config: chain.usdc };\n }\n\n return undefined;\n}\n\n/**\n * Get list of supported tokens for a chain\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @returns Array of supported token types, or empty array if chain not found\n */\nexport function getSupportedTokens(chainName: string): TokenType[] {\n const chain = getChainByName(chainName);\n if (!chain) return [];\n\n // If tokens map exists, return its keys\n if (chain.tokens) {\n return Object.keys(chain.tokens) as TokenType[];\n }\n\n // Default to just USDC for chains without explicit tokens map\n return ['usdc'];\n}\n\n/**\n * Check if a token is supported on a specific chain\n *\n * @param chainName - Chain name (e.g., 'ethereum', 'base')\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns true if token is supported on the chain\n */\nexport function isTokenSupported(chainName: string, tokenType: TokenType): boolean {\n const chain = getChainByName(chainName);\n if (!chain) return false;\n\n // Check tokens map\n if (chain.tokens && chain.tokens[tokenType]) {\n return true;\n }\n\n // USDC is always supported (backward compatibility)\n if (tokenType === 'usdc') {\n return true;\n }\n\n return false;\n}\n\n/**\n * Get all chains that support a specific token\n *\n * @param tokenType - Token type (e.g., 'usdc', 'eurc', 'pyusd')\n * @returns Array of chain configs that support the token\n */\nexport function getChainsByToken(tokenType: TokenType): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(chain => {\n if (!chain.x402.enabled) return false;\n if (chain.tokens && chain.tokens[tokenType]) return true;\n if (tokenType === 'usdc') return true; // USDC is universal\n return false;\n });\n}\n","/**\n * uvd-x402-sdk - Type Definitions\n *\n * Core TypeScript interfaces for the x402 payment SDK.\n * These types define the contract between the SDK and consuming applications.\n */\n\n// Type-only, so it is erased at compile time and no runtime cycle exists between\n// this module and `policy.ts` (which imports `X402Error` from here as a value).\nimport type { AdvertisedQuote, PolicyApproval, PurchasePolicy } from '../policy';\n\n// ============================================================================\n// CHAIN CONFIGURATION TYPES\n// ============================================================================\n\n/**\n * Network type categorization\n * - 'evm': Ethereum Virtual Machine compatible chains (use EIP-712)\n * - 'svm': Solana Virtual Machine chains (Solana, Fogo) (use SPL tokens)\n * - 'stellar': Stellar network (use Soroban)\n * - 'near': NEAR Protocol (use NEP-366)\n * - 'algorand': Algorand network (use ASA transfers with atomic transactions)\n * - 'sui': Sui blockchain (use sponsored transactions)\n * - 'xrpl': XRP Ledger (use pre-signed Payment transaction blobs)\n *\n * @deprecated 'solana' type is deprecated, use 'svm' instead\n */\nexport type NetworkType = 'evm' | 'svm' | 'solana' | 'stellar' | 'near' | 'algorand' | 'sui' | 'xrpl' | 'hedera';\n\n/**\n * Supported x402 payment schemes\n * - 'exact': Standard one-shot payment (default)\n * - 'escrow': Escrow-based payment with verify/settle/refund\n * - 'commerce': Commerce alias for escrow (marketplace integrations)\n */\nexport type X402Scheme = 'exact' | 'escrow' | 'commerce';\n\n/**\n * Supported stablecoin token types\n * - usdc: USD Coin (Circle) - 6 decimals\n * - eurc: Euro Coin (Circle) - 6 decimals\n * - ausd: Agora USD (Agora Finance) - 6 decimals\n * - pyusd: PayPal USD (PayPal/Paxos) - 6 decimals\n * - usdt: Tether USD (USDT0 omnichain via LayerZero) - 6 decimals\n * - usdg: Global Dollar (Paxos) - 6 decimals; settlement stablecoin on Robinhood Chain\n */\nexport type TokenType = 'usdc' | 'eurc' | 'ausd' | 'pyusd' | 'usdt' | 'usdg' | 'hbar';\n\n/**\n * Token configuration for EIP-712 signing and transfers\n */\nexport interface TokenConfig {\n /** Contract/mint address */\n address: string;\n /** Token decimals (6 for all supported stablecoins) */\n decimals: number;\n /** Token name for EIP-712 domain (e.g., \"USD Coin\" or \"USDC\") */\n name: string;\n /** Token version for EIP-712 domain */\n version: string;\n /**\n * Whether one whole unit of this token IS one dollar.\n *\n * Absent means yes, so every stablecoin entry in the registry keeps the\n * behaviour it had. It is `false` for EURC (euros), native XRP and HBAR.\n *\n * **The distinction is unit, not scale.** `decimals` already handles scale --\n * BSC USDC has 18 of them and prices correctly. But scaling a price by the\n * decimals only turns dollars into base units when one whole unit is one\n * dollar. XRP has six real decimals and is still not a dollar, so\n * `$1.00 -> 10**6` charges **1 XRP**, which is whatever XRP happens to cost.\n * Six decimals of XRP are still XRP.\n *\n * The SDK refuses to price in USD against a token carrying `false` rather\n * than converting at a rate nobody agreed to. Mirrors `NetworkConfig\n * .usd_pegged` in the Python SDK (`networks/base.py:129`, 0.77.0).\n */\n usdPegged?: boolean;\n}\n\n/**\n * USDC token configuration for a specific chain\n * @deprecated Use TokenConfig instead. This is kept for backward compatibility.\n */\nexport interface USDCConfig {\n /** Contract/mint address */\n address: string;\n /** Token decimals (6 for most chains, 7 for Stellar) */\n decimals: number;\n /** Token name for EIP-712 domain (e.g., \"USD Coin\" or \"USDC\") */\n name: string;\n /** Token version for EIP-712 domain */\n version: string;\n /**\n * Whether one whole unit of this token IS one dollar. Absent means yes.\n *\n * See {@link TokenConfig.usdPegged}. It matters here because this field is\n * also where a chain that settles in its own native asset describes that\n * asset -- XRPL keeps native XRP under the key `usdc`, so the key promises a\n * dollar the value does not deliver.\n */\n usdPegged?: boolean;\n}\n\n/**\n * Native currency configuration\n */\nexport interface NativeCurrency {\n name: string;\n symbol: string;\n decimals: number;\n}\n\n/**\n * Complete chain configuration\n */\nexport interface ChainConfig {\n /** Numeric chain ID (0 for non-EVM chains) */\n chainId: number;\n /** Hex-encoded chain ID for wallet_switchEthereumChain */\n chainIdHex: string;\n /** Internal chain identifier (e.g., 'base', 'solana') */\n name: string;\n /** Human-readable display name */\n displayName: string;\n /** Network type for routing */\n networkType: NetworkType;\n /** Primary RPC endpoint URL */\n rpcUrl: string;\n /** Block explorer base URL */\n explorerUrl: string;\n /** Native currency info */\n nativeCurrency: NativeCurrency;\n /** USDC token configuration */\n usdc: USDCConfig;\n /**\n * Multi-token configurations (EVM chains only)\n * Maps token type to its configuration for this chain.\n * Not all tokens are available on all chains.\n */\n tokens?: Partial<Record<TokenType, TokenConfig>>;\n /** x402 facilitator configuration */\n x402: {\n facilitatorUrl: string;\n enabled: boolean;\n };\n}\n\n// ============================================================================\n// WALLET TYPES\n// ============================================================================\n\n/**\n * Current wallet connection state\n */\nexport interface WalletState {\n /** Whether a wallet is currently connected */\n connected: boolean;\n /** Connected wallet address (null if not connected) */\n address: string | null;\n /** Current chain ID (null for non-EVM or disconnected) */\n chainId: number | null;\n /** Current network name */\n network: string | null;\n /** Network type of connected wallet */\n networkType: NetworkType | null;\n /** USDC balance on current chain (null if unknown) */\n balance: string | null;\n}\n\n/**\n * Wallet adapter interface for different wallet types\n */\nexport interface WalletAdapter {\n /** Unique identifier for this wallet type */\n readonly id: string;\n /** Display name */\n readonly name: string;\n /** Network type this adapter supports */\n readonly networkType: NetworkType;\n\n /** Check if this wallet is available/installed */\n isAvailable(): boolean;\n\n /** Connect to the wallet */\n connect(chainName?: string): Promise<string>;\n\n /** Disconnect from the wallet */\n disconnect(): Promise<void>;\n\n /** Switch to a different chain (EVM only) */\n switchChain?(chainName: string): Promise<void>;\n\n /**\n * Sign a payment payload\n * For EVM chains, supports multi-token via paymentInfo.tokenType\n */\n signPayment(paymentInfo: PaymentInfo, chainConfig: ChainConfig): Promise<string>;\n\n /**\n * Check token balance (defaults to USDC for backward compatibility)\n * EVM providers may accept optional tokenType parameter\n */\n getBalance(chainConfig: ChainConfig, tokenType?: TokenType): Promise<string>;\n\n /** Get current address */\n getAddress(): string | null;\n\n /** Get current chain ID (EVM only) */\n getChainId?(): number | null;\n}\n\n/**\n * EIP-712 domain for typed data signing\n */\nexport interface EIP712Domain {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: string;\n}\n\n/**\n * EIP-712 type definitions\n */\nexport interface EIP712Types {\n [typeName: string]: Array<{ name: string; type: string }>;\n}\n\n// ============================================================================\n// PAYMENT TYPES\n// ============================================================================\n\n/**\n * Payment information returned by backend on 402 response\n */\nexport interface PaymentInfo {\n /** Exact v2 offer/resource, required by native Hedera. */\n accepted?: Record<string, unknown>;\n resource?: { url: string; description?: string; mimeType?: string };\n extensions?: Record<string, unknown>;\n /** Default recipient address */\n recipient: string;\n /** Network-specific recipient addresses */\n recipients?: {\n evm?: string;\n solana?: string;\n near?: string;\n stellar?: string;\n algorand?: string;\n sui?: string;\n xrpl?: string;\n hedera?: string;\n };\n /** Facilitator address (for Solana fee payer) */\n facilitator?: string;\n /**\n * Amount in whole units of the settlement asset (e.g., \"10.00\").\n *\n * For dollar-pegged tokens that is dollars; for EURC it is **euros**.\n * On XRPL it is **XRP**, because XRPL settles in its own native asset:\n * the provider converts this to drops (6 decimals) and bills whole XRP\n * (`src/providers/xrpl/index.ts`). This used to be documented as USD, which\n * made the type and its only XRPL consumer disagree about the unit -- and the\n * consumer won, so a \"10.00\" written as ten dollars left as ten XRP. The SDK\n * now refuses to build a dollar price for an asset with no dollar peg rather\n * than let the two readings meet on the wire; see\n * {@link TokenConfig.usdPegged}.\n */\n amount: string;\n /** Token symbol (usually \"USDC\") */\n token?: string;\n /**\n * Token type for multi-token support\n * Defaults to 'usdc' if not specified for backward compatibility\n */\n tokenType?: TokenType;\n /** Network hint from backend */\n network?: string;\n /** Supported chain IDs */\n supportedChains?: number[];\n /**\n * Envelope version the resource asked for, as read off its own 402.\n *\n * This is what makes the client's `x402Version: 'auto'` mean something: the\n * buyer loop reads the version out of the challenge and hands it down here,\n * so the header is built in the shape the server said it accepts. Left\n * undefined by callers who build a payment by hand -- then the client config\n * decides, exactly as before.\n */\n x402Version?: X402Version;\n /**\n * Seconds this EIP-3009 authorization stays settleable\n * (`validBefore = now + validitySeconds`).\n *\n * Set it when the seller settles **async** -- verify, hand over the resource,\n * settle afterwards -- and needs the authorization alive for longer than the\n * default. Left undefined, `X402ClientConfig.validitySeconds` decides, and\n * failing that `DEFAULT_VALIDITY_SECONDS` (300 s, the timeout this SDK's own\n * seller side announces by default). `X402Client.fetch()` fills it from the\n * seller's `maxTimeoutSeconds` when the 402 declares one.\n *\n * Must be a whole number of seconds between 1 and `MAX_VALIDITY_SECONDS`\n * (3600); anything else is refused with `INVALID_CONFIG` before anything is\n * signed. The ceiling is here because this type is shaped like a parsed 402:\n * a caller that hands a seller's response straight to `createPayment` would\n * otherwise let the SELLER decide how long the payer's authorization stays\n * claimable. The facilitator also keeps a 6 s clock-skew grace, so the payer\n * really has `validitySeconds - 6` to sign.\n */\n validitySeconds?: number;\n}\n\n/**\n * One payment option read off a resource's `402`, normalised.\n *\n * The 402 body speaks two dialects -- v1 spells the price `maxAmountRequired`\n * and names the chain `base`, v2 spells it `amount` and names it `eip155:8453`\n * -- and a buyer that only learned one of them silently ignores half the\n * offers. This is the shape after both have been read.\n */\nexport interface X402PaymentOffer {\n /** Network exactly as the 402 wrote it (plain name or CAIP-2). */\n network: string;\n /** SDK chain name the network resolved to, or null when unknown. */\n chainName: string | null;\n /** Token contract address the resource wants paid, when it named one. */\n asset?: string;\n /** Price in the token's own atomic units. */\n amount: string;\n /** Decimals used to read `amount`. */\n decimals: number;\n /** Recipient of the payment. */\n payTo: string;\n /**\n * The seller's `maxTimeoutSeconds`, when its 402 entry declared a finite number.\n *\n * `X402Client.fetch()` signs this window -- clamped to `1..MAX_VALIDITY_SECONDS`\n * -- instead of the client's own, because the seller is the one party that\n * knows how long its settlement takes. Undefined when the entry declared none,\n * or declared something that is not a number.\n */\n maxTimeoutSeconds?: number;\n /** The accept object verbatim -- echoed back for v2. */\n raw: Record<string, unknown>;\n}\n\n/**\n * Options for {@link X402Client.fetch} -- the buyer loop.\n */\nexport interface X402FetchOptions {\n /** HTTP method for both the probe and the paid retry (default `GET`). */\n method?: string;\n /**\n * Hard ceiling in token units (e.g. `'0.05'`). A 402 that asks for more\n * throws instead of signing. Undefined = no ceiling, which means paying\n * whatever an untrusted resource asks: discouraged.\n */\n maxAmount?: string;\n /** Token to pay with (default `usdc`). */\n tokenType?: TokenType;\n /** Override the default cheapest-offer selection. */\n select?: (offers: X402PaymentOffer[]) => X402PaymentOffer | null | undefined;\n /** Passed through to both requests (`headers`, `body`, `signal`, ...). */\n init?: RequestInit;\n /** Injectable `fetch` (tests, or a runtime without a global one). */\n fetchImpl?: typeof globalThis.fetch;\n /**\n * What a catalog listing advertised, when the caller read one.\n *\n * The comparison NEVER decides anything -- a seller repricing inside a policy\n * the operator already authorised is ordinary commerce -- but handing it over\n * gets the divergence reported on the approval instead of having to diff the\n * two by hand. See `PolicyApproval.versusQuote`.\n */\n advertised?: AdvertisedQuote;\n /**\n * Called once the paid retry came back with something other than a 402, i.e.\n * the seller accepted the payment.\n *\n * This is where a caller calls `client.policy.recordSpend(...)`. Evaluating\n * deliberately does not spend: signing can fail and a settlement can be\n * refused, and a cumulative limit that counted attempts would lock a caller\n * out of money it never spent. Nothing here is automatic, so a caller that\n * wants a cumulative limit to mean something has to say so.\n */\n onPaid?: (approval: PolicyApproval) => void;\n}\n\n/**\n * Simple payment request from application\n */\nexport interface PaymentRequest {\n /** Amount in USDC (e.g., \"10.00\") */\n amount: string;\n /** Override recipient address (optional) */\n recipient?: string;\n /** Application-specific metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * x402 payment header names\n *\n * - 'X-PAYMENT': v1 header name (default, most compatible)\n * - 'PAYMENT-SIGNATURE': v2 header name (newer standard)\n *\n * Both headers use the same base64-encoded JSON payload format.\n * The facilitator accepts both headers.\n */\nexport type X402HeaderName = 'X-PAYMENT' | 'PAYMENT-SIGNATURE';\n\n/**\n * Payment headers object containing both v1 and v2 header formats\n */\nexport interface PaymentHeaders {\n /** v1 header: X-PAYMENT */\n 'X-PAYMENT': string;\n /** v2 header: PAYMENT-SIGNATURE (same value, different header name) */\n 'PAYMENT-SIGNATURE': string;\n}\n\n/**\n * Result of a payment operation\n */\nexport interface PaymentResult {\n /** Whether payment was successful */\n success: boolean;\n /** Base64-encoded X-PAYMENT header value */\n paymentHeader: string;\n /**\n * Payment headers object for easy use with fetch/axios\n *\n * @example\n * ```ts\n * // Use v1 header\n * fetch(url, { headers: { 'X-PAYMENT': result.headers['X-PAYMENT'] } });\n *\n * // Use v2 header\n * fetch(url, { headers: { 'PAYMENT-SIGNATURE': result.headers['PAYMENT-SIGNATURE'] } });\n * ```\n */\n headers: PaymentHeaders;\n /** Transaction hash (if available) */\n transactionHash?: string;\n /** Network where payment was made */\n network: string;\n /** Payer address */\n payer?: string;\n /** Error message (if success is false) */\n error?: string;\n}\n\n// ============================================================================\n// PAYLOAD TYPES (Internal)\n// ============================================================================\n\n/**\n * EVM payment payload (ERC-3009 TransferWithAuthorization)\n */\nexport interface EVMPaymentPayload {\n from: string;\n to: string;\n value: string;\n validAfter: number;\n validBefore: number;\n nonce: string;\n v: number;\n r: string;\n s: string;\n chainId: number;\n token: string;\n}\n\n/**\n * Token info for non-USDC stablecoins (e.g., Token2022 like AUSD)\n * Required in payload for facilitator to verify Token2022 transfers correctly.\n */\nexport interface TokenInfo {\n /** Token mint address */\n address: string;\n /** Token symbol (e.g., 'AUSD') */\n symbol: string;\n /** Token decimals (e.g., 6) */\n decimals: number;\n}\n\n/**\n * Solana payment payload (partially-signed transaction)\n */\nexport interface SolanaPaymentPayload {\n /** Base64-encoded serialized transaction */\n transaction: string;\n /**\n * Token info for non-USDC tokens (e.g., Token2022 like AUSD)\n * CRITICAL: Must be included for Token2022 tokens for facilitator verification\n */\n token?: TokenInfo;\n}\n\n/**\n * Stellar payment payload (Soroban authorization)\n */\nexport interface StellarPaymentPayload {\n /** Sender G... public key */\n from: string;\n /** Recipient G... public key */\n to: string;\n /** Amount in stroops (7 decimals) */\n amount: string;\n /** USDC SAC contract address */\n tokenContract: string;\n /** Base64 XDR-encoded SorobanAuthorizationEntry */\n authorizationEntryXdr: string;\n /** Random 64-bit nonce */\n nonce: number;\n /** Ledger when authorization expires */\n signatureExpirationLedger: number;\n}\n\n/**\n * NEAR payment payload (NEP-366 meta-transaction)\n */\nexport interface NEARPaymentPayload {\n /** Base64 Borsh-encoded SignedDelegateAction */\n signedDelegateAction: string;\n network: 'near';\n}\n\n/**\n * Algorand payment payload (atomic transaction group)\n *\n * Follows the GoPlausible x402-avm spec for atomic groups:\n * - Transaction 0: Fee payment (UNSIGNED) - facilitator -> facilitator, covers all fees\n * - Transaction 1: ASA transfer (SIGNED) - client -> merchant\n *\n * The facilitator signs transaction 0 and submits the complete atomic group.\n */\nexport interface AlgorandPaymentPayload {\n /** Index of the payment transaction in the group (always 1) */\n paymentIndex: number;\n /**\n * Array of base64-encoded msgpack transactions forming the atomic group:\n * - [0]: Unsigned fee transaction (facilitator signs)\n * - [1]: Signed ASA transfer (client signed)\n */\n paymentGroup: string[];\n}\n\n/**\n * Sui payment payload (sponsored transaction)\n *\n * Uses Sui sponsored transactions where:\n * - User creates a programmable transaction for USDC transfer\n * - User signs the transaction\n * - Facilitator sponsors (pays gas in SUI) and submits\n *\n * User pays: ZERO SUI\n */\nexport interface SuiPaymentPayload {\n /** Base64-encoded BCS serialized TransactionData */\n transactionBytes: string;\n /** Base64-encoded user signature */\n senderSignature: string;\n /** Sender address (0x + 64 hex chars) */\n from: string;\n /** Recipient address (0x + 64 hex chars) */\n to: string;\n /** Amount in base units (string to handle large numbers) */\n amount: string;\n /** Coin object ID used for the transfer (REQUIRED by facilitator) */\n coinObjectId: string;\n}\n\n/**\n * XRPL payment payload (pre-signed Payment transaction blob)\n *\n * Uses the t54 \"pre-signed Payment blob\" scheme on the XRP Ledger:\n * - The client builds and FULLY signs a Payment transaction off-chain,\n * paying its own XRP network fee.\n * - The single `signedTxBlob` field (hex-encoded fully-signed XRPL tx blob)\n * is sent to the facilitator, which decodes it to re-derive payer/amount/\n * destination and submits it.\n *\n * All payment-level fields (destination, amount, InvoiceID, SourceTag, etc.)\n * come from PaymentRequirements/extra, NOT from this payload.\n *\n * XRP is the native asset (6 decimals / drops). There is no token contract.\n *\n * The JSON field name is EXACTLY `signedTxBlob` (camelCase).\n */\nexport interface XRPLPaymentPayload {\n /** Hex-encoded fully-signed XRPL Payment transaction blob (tx_blob) */\n signedTxBlob: string;\n}\n\n/**\n * Union type for all payment payloads\n */\nexport type PaymentPayload =\n | EVMPaymentPayload\n | SolanaPaymentPayload\n | StellarPaymentPayload\n | NEARPaymentPayload\n | AlgorandPaymentPayload\n | SuiPaymentPayload\n | XRPLPaymentPayload;\n\n// ============================================================================\n// X402 HEADER TYPES (v1 and v2)\n// ============================================================================\n\n/**\n * x402 protocol version\n */\nexport type X402Version = 1 | 2;\n\n/**\n * CAIP-2 chain identifiers for x402 v2\n * @see https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md\n */\nexport const CAIP2_IDENTIFIERS: Record<string, string> = {\n 'hedera:mainnet': 'hedera:mainnet',\n 'hedera:testnet': 'hedera:testnet',\n // EVM chains\n base: 'eip155:8453',\n ethereum: 'eip155:1',\n polygon: 'eip155:137',\n arbitrum: 'eip155:42161',\n optimism: 'eip155:10',\n avalanche: 'eip155:43114',\n celo: 'eip155:42220',\n hyperevm: 'eip155:999',\n unichain: 'eip155:130',\n monad: 'eip155:143',\n bsc: 'eip155:56',\n scroll: 'eip155:534352',\n 'skale-base': 'eip155:1187947933',\n 'skale-base-sepolia': 'eip155:324705682',\n robinhood: 'eip155:4663',\n 'robinhood-testnet': 'eip155:46630',\n arc: 'eip155:5042',\n 'arc-testnet': 'eip155:5042002',\n // SVM chains\n solana: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n fogo: 'svm:fogo',\n // Stellar\n stellar: 'stellar:pubnet',\n // NEAR\n near: 'near:mainnet',\n // Algorand\n algorand: 'algorand:mainnet',\n 'algorand-testnet': 'algorand:testnet',\n // Sui\n sui: 'sui:mainnet',\n 'sui-testnet': 'sui:testnet',\n // XRPL (XRP Ledger)\n xrpl: 'xrpl',\n 'xrpl-testnet': 'xrpl-testnet',\n};\n\n/**\n * Reverse mapping from CAIP-2 to chain name\n */\nexport const CAIP2_TO_CHAIN: Record<string, string> = Object.fromEntries(\n Object.entries(CAIP2_IDENTIFIERS).map(([k, v]) => [v, k])\n);\n\n/**\n * x402 v1 header structure (network as string)\n */\nexport interface X402HeaderV1 {\n x402Version: 1;\n scheme: X402Scheme;\n network: string;\n payload: X402PayloadData;\n}\n\n/**\n * x402 v2 payment option\n */\nexport interface X402PaymentOption {\n network: string; // CAIP-2 format\n asset: string;\n amount: string;\n facilitator?: string;\n}\n\n/**\n * x402 v2 header structure (CAIP-2 network, accepts array)\n */\nexport interface X402HeaderV2 {\n x402Version: 2;\n scheme: X402Scheme;\n network: string; // CAIP-2 format\n payload: X402PayloadData;\n accepts?: X402PaymentOption[];\n}\n\n/**\n * Union type for both v1 and v2 headers\n */\nexport type X402Header = X402HeaderV1 | X402HeaderV2;\n\n/**\n * EVM-specific payload in x402 header\n */\nexport interface X402EVMPayload {\n signature: string;\n authorization: {\n from: string;\n to: string;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: string;\n };\n /**\n * Which token was actually paid.\n *\n * Only present when the payment is created with `includeTokenMetadata`. The\n * signature alone does not say which stablecoin it authorizes — a server that\n * accepts several tokens on the same chain cannot rebuild the payment\n * requirements without this. Omitted by default so existing v1 wire formats\n * stay byte-identical.\n */\n token?: PaymentTokenMetadata;\n}\n\n/**\n * Token identification carried inside an x402 payload.\n *\n * Mirrors what a resource server needs to build `paymentRequirements`: the\n * `asset` it must charge and the `extra` EIP-712 domain the facilitator needs\n * to recover the signature.\n */\nexport interface PaymentTokenMetadata {\n /** Token contract address (the `asset` of the payment requirements) */\n address: string;\n /** Uppercase token symbol, e.g. `USDC`, `EURC`, `USDT` */\n symbol: string;\n /** Token decimals — the amount in the authorization is in these units */\n decimals: number;\n /** EIP-712 domain of the token contract (the `extra` of the requirements) */\n eip712: {\n name: string;\n version: string;\n };\n}\n\n/**\n * Solana-specific payload in x402 header\n */\nexport interface X402SolanaPayload {\n transaction: string;\n}\n\n/**\n * Settlement account payload for Crossmint and other custodial wallets\n * that can only sendTransaction (not signTransaction).\n *\n * In this mode, the client already submitted the transaction on-chain.\n * The facilitator verifies the on-chain tx, then sweeps USDC from the\n * settlement account to the payTo address.\n *\n * Used by: Crossmint smart wallets via @faremeter/wallet-crossmint\n */\nexport interface X402SettlementAccountPayload {\n /** On-chain transaction signature (already submitted) */\n transactionSignature: string;\n /** Base58 secret key for sweeping settlement account (optional) */\n settleSecretKey?: string;\n /** Address to receive rent from closed settlement ATA (optional) */\n settlementRentDestination?: string;\n}\n\n/**\n * Stellar-specific payload in x402 header\n */\nexport interface X402StellarPayload {\n from: string;\n to: string;\n amount: string;\n tokenContract: string;\n authorizationEntryXdr: string;\n nonce: number;\n signatureExpirationLedger: number;\n}\n\n/**\n * NEAR-specific payload in x402 header\n */\nexport interface X402NEARPayload {\n signedDelegateAction: string;\n}\n\n/**\n * Algorand-specific payload in x402 header (atomic group format)\n */\nexport interface X402AlgorandPayload {\n /** Index of the payment transaction in the group (always 1) */\n paymentIndex: number;\n /** Array of base64-encoded msgpack transactions */\n paymentGroup: string[];\n}\n\n/**\n * Sui-specific payload in x402 header (sponsored transaction)\n */\nexport interface X402SuiPayload {\n /** BCS-encoded transaction bytes (base64) */\n transactionBytes: string;\n /** User's signature on the transaction (base64) */\n senderSignature: string;\n /** Sender's Sui address (0x...) */\n from: string;\n /** Recipient's Sui address (0x...) */\n to: string;\n /** Amount in smallest unit (string to avoid precision issues) */\n amount: string;\n /** Coin object ID used for the transfer (REQUIRED by facilitator) */\n coinObjectId: string;\n}\n\n/**\n * XRPL-specific payload in x402 header (t54 pre-signed Payment blob)\n *\n * The JSON field name is EXACTLY `signedTxBlob` (camelCase). The facilitator\n * decodes the blob to re-derive payer/amount/destination; no other fields are\n * carried in the payload.\n */\nexport interface X402XRPLPayload {\n /** Hex-encoded fully-signed XRPL Payment transaction blob (tx_blob) */\n signedTxBlob: string;\n}\n\n/**\n * Union of all x402 payload types\n */\nexport type X402PayloadData =\n | X402EVMPayload\n | X402SolanaPayload\n | X402SettlementAccountPayload\n | X402StellarPayload\n | X402NEARPayload\n | X402AlgorandPayload\n | X402SuiPayload\n | X402XRPLPayload;\n\n// ============================================================================\n// CLIENT CONFIGURATION\n// ============================================================================\n\n/**\n * Multi-payment configuration for supporting multiple networks\n */\nexport interface MultiPaymentConfig {\n /** Networks to support (e.g., ['base', 'solana', 'stellar', 'near']) */\n networks: string[];\n /** Default network if user hasn't selected one */\n defaultNetwork?: string;\n /** Whether to auto-detect user's preferred network based on wallet */\n autoDetect?: boolean;\n}\n\n/**\n * SDK client configuration options\n */\nexport interface X402ClientConfig {\n /** Facilitator URL (default: https://facilitator.ultravioletadao.xyz) */\n facilitatorUrl?: string;\n /** Default chain to connect to */\n defaultChain?: string;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n /** Enable debug logging */\n debug?: boolean;\n /** Custom chain configurations (override defaults) */\n customChains?: Record<string, Partial<ChainConfig>>;\n /** Wallet preference order */\n walletPreference?: string[];\n /** Custom RPC URLs (override defaults) */\n rpcOverrides?: Record<string, string>;\n /**\n * x402 protocol version to use\n * - 1: Classic format with network as string (e.g., \"base\")\n * - 2: CAIP-2 format with accepts array (e.g., \"eip155:8453\")\n * - 'auto': Auto-detect from 402 response (default)\n */\n x402Version?: X402Version | 'auto';\n /** Multi-payment configuration for supporting multiple networks */\n multiPayment?: MultiPaymentConfig;\n /**\n * What this buyer is allowed to sign, decided before it signs.\n *\n * Left undefined, the client holds `PurchasePolicy.permissive()`: this SDK had\n * no budget before 2.89.0 and turning one on silently would refuse payments\n * callers are making today. A policy built with `PurchasePolicy.create()`\n * denies any asset it was not given a ceiling for.\n *\n * @see {@link PurchasePolicy}\n */\n policy?: PurchasePolicy;\n /**\n * Include a `token` block in the payload naming the asset, its decimals and\n * its EIP-712 domain.\n *\n * Needed when the resource accepts more than one stablecoin on the same\n * chain: the signature alone does not say which one was paid, so the server\n * cannot rebuild `paymentRequirements`. Off by default — the emitted header\n * stays byte-identical to previous versions.\n */\n includeTokenMetadata?: boolean;\n /**\n * Seconds every EIP-3009 authorization this client signs stays settleable\n * (`validBefore = now + validitySeconds`).\n *\n * The per-payment {@link PaymentInfo.validitySeconds} overrides it; with\n * neither, `DEFAULT_VALIDITY_SECONDS` (300 s) applies, and `MAX_VALIDITY_SECONDS`\n * (3600 s) is the ceiling for both. Until 2.91.0 this\n * was not configurable at all: the window was 300 s on Base and 60 s on every\n * other EVM network, decided by the payer's SDK, which is exactly the party\n * that does not know how long the seller's settlement takes.\n */\n validitySeconds?: number;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: Required<Pick<X402ClientConfig, 'facilitatorUrl' | 'defaultChain' | 'autoConnect' | 'debug' | 'x402Version'>> = {\n facilitatorUrl: 'https://facilitator.ultravioletadao.xyz',\n defaultChain: 'base',\n autoConnect: false,\n debug: false,\n x402Version: 'auto',\n};\n\n// ============================================================================\n// BALANCE TYPES\n// ============================================================================\n\n/**\n * Balance information for a single network\n */\nexport interface NetworkBalance {\n /** Chain name */\n chainName: string;\n /** Human-readable display name */\n displayName: string;\n /** Formatted balance (e.g., \"15.50\") or null if loading/error */\n balance: string | null;\n /** Whether balance is currently being fetched */\n isLoading: boolean;\n /** Error message if fetch failed */\n error: string | null;\n}\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Events emitted by the SDK client\n */\nexport type X402Event =\n | 'connect'\n | 'disconnect'\n | 'chainChanged'\n | 'accountChanged'\n | 'balanceChanged'\n | 'paymentStarted'\n | 'paymentSigned'\n | 'paymentCompleted'\n | 'paymentFailed';\n\n/**\n * Event data types\n */\nexport interface X402EventData {\n connect: WalletState;\n disconnect: void;\n chainChanged: { chainId: number; chainName: string };\n accountChanged: { address: string };\n balanceChanged: { balance: string };\n paymentStarted: { amount: string; network: string };\n paymentSigned: { paymentHeader: string };\n paymentCompleted: PaymentResult;\n paymentFailed: { error: string; code: X402ErrorCode };\n}\n\n/**\n * Event handler type\n */\nexport type X402EventHandler<E extends X402Event> = (data: X402EventData[E]) => void;\n\n// ============================================================================\n// ERROR TYPES\n// ============================================================================\n\n/**\n * Error codes for categorizing errors\n */\nexport type X402ErrorCode =\n | 'WALLET_NOT_FOUND'\n | 'WALLET_NOT_CONNECTED'\n | 'WALLET_NOT_SUPPORTED'\n | 'WALLET_CONNECTION_FAILED'\n | 'WALLET_CONNECTION_REJECTED'\n | 'WALLET_CONNECTION_TIMEOUT'\n | 'CHAIN_NOT_SUPPORTED'\n | 'CHAIN_SWITCH_REJECTED'\n | 'INSUFFICIENT_BALANCE'\n | 'SIGNATURE_REJECTED'\n | 'PAYMENT_FAILED'\n | 'PAYMENT_TIMEOUT'\n | 'NETWORK_ERROR'\n | 'INVALID_CONFIG'\n | 'INVALID_AMOUNT'\n | 'INVALID_RECIPIENT'\n | 'PAYMENT_EXCEEDS_MAX'\n | 'NO_ACCEPTABLE_PAYMENT'\n /**\n * The buyer's own policy refused the offer before anything was signed. The\n * concrete cause is on `PolicyRefusedError.refusal.code` -- see\n * {@link PurchasePolicy}.\n */\n | 'POLICY_REFUSED'\n | 'UNKNOWN_ERROR';\n\n/**\n * SDK-specific error class\n */\nexport class X402Error extends Error {\n public readonly code: X402ErrorCode;\n public readonly details?: unknown;\n\n constructor(message: string, code: X402ErrorCode, details?: unknown) {\n super(message);\n this.name = 'X402Error';\n this.code = code;\n this.details = details;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, X402Error);\n }\n }\n}\n","/**\n * uvd-x402-sdk - UTF-8 safe base64\n *\n * `btoa()` only accepts code points 0-255. Any character above that throws\n * `InvalidCharacterError`, and the X-PAYMENT payload is not guaranteed to be\n * ASCII: the EIP-712 domain name of USDT on Optimism and Arbitrum is literally\n * `USD₮0` (U+20AE). A header carrying that name crashes a plain `btoa()`.\n *\n * So the JSON is UTF-8 encoded to bytes first, and only then base64'd. Decoding\n * reverses it. For ASCII-only input the output is byte-identical to\n * `btoa(json)`, which is why swapping this in cannot change any existing header.\n *\n * `TextEncoder`/`TextDecoder` are available in every browser the SDK targets and\n * in Node 11+; `btoa`/`atob` are used for the byte<->base64 step because they\n * exist in both environments without pulling in `Buffer`.\n */\n\n/**\n * Encode a string as base64, handling non-ASCII characters correctly.\n *\n * @param value - Any UTF-8 string\n * @returns Base64-encoded value\n */\nexport function encodeBase64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Decode a base64 string produced by {@link encodeBase64Utf8}.\n *\n * @param encoded - Base64-encoded value\n * @returns The original UTF-8 string\n */\nexport function decodeBase64Utf8(encoded: string): string {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * JSON-serialize a value and encode it as UTF-8 safe base64.\n *\n * This is the encoder for every X-PAYMENT header the SDK emits.\n *\n * @param value - Value to serialize\n * @returns Base64-encoded JSON\n */\nexport function encodeBase64Json(value: unknown): string {\n return encodeBase64Utf8(JSON.stringify(value));\n}\n","/**\n * uvd-x402-sdk - x402 Protocol Utilities\n *\n * Utilities for working with x402 v1 and v2 protocols.\n * Handles version detection, payload encoding, and CAIP-2 conversions.\n */\n\nimport type {\n X402Header,\n X402HeaderV1,\n X402HeaderV2,\n X402PayloadData,\n X402PaymentOption,\n X402Version,\n ChainConfig,\n TokenType,\n} from '../types';\nimport { CAIP2_IDENTIFIERS, CAIP2_TO_CHAIN } from '../types';\nimport { getChainByName, getTokenConfig, isUsdPegged } from '../chains';\nimport { decodeBase64Utf8, encodeBase64Json } from './base64';\nimport { toAtomicUnits } from './amount';\n\n/**\n * Detect x402 version from a response header or body\n *\n * @param data - The 402 response data (parsed JSON or header value)\n * @returns The detected version (1 or 2)\n */\nexport function detectX402Version(data: unknown): X402Version {\n if (typeof data === 'string') {\n // A `PAYMENT-REQUIRED` header value is base64 JSON, and the doc above\n // invites one. Returning 1 without decoding misread every v2 challenge as\n // v1 — silently, as a plausible value rather than an error, and the two\n // wire forms are structurally incompatible.\n //\n // This is not hypothetical: measured 2026-08-20, 36 of 36 live Bazaar\n // resources answering 402 carry the challenge in the header, and several\n // put a free content preview in the body, so the header is the only place\n // the version signal exists.\n const trimmed = data.trim();\n if (!trimmed) return 1;\n for (const decode of [\n () => JSON.parse(decodeBase64Utf8(trimmed)),\n () => JSON.parse(trimmed),\n ]) {\n try {\n const parsed = decode();\n if (typeof parsed === 'object' && parsed !== null) {\n return detectX402Version(parsed);\n }\n } catch {\n // not this encoding; try the next\n }\n }\n return 1; // undecodable: fall back to v1, as before\n }\n\n if (typeof data !== 'object' || data === null) {\n return 1; // Default to v1\n }\n\n const obj = data as Record<string, unknown>;\n\n // Check explicit version field\n if (obj.x402Version === 2) {\n return 2;\n }\n\n // Check for v2 indicators. A v1 402 carries `accepts` too (the spec's v1\n // shape, and the v1 402 this SDK builds), so `accepts` does not outvote a\n // declared 1. `X402Client` already takes the version from the field, not\n // from `accepts`.\n if (obj.accepts && Array.isArray(obj.accepts) && obj.x402Version !== 1) {\n return 2;\n }\n\n // `paymentRequirements` is the v1 spelling, so its presence points at v1 --\n // but only when there is no v2 signal, which the checks above already ruled\n // out. Recognised so the value is not treated as an unknown shape.\n if (Array.isArray(obj.paymentRequirements)) {\n return 1;\n }\n\n // Check if network is in CAIP-2 format\n if (typeof obj.network === 'string') {\n if (obj.network.includes(':')) {\n return 2;\n }\n }\n\n return 1;\n}\n\n/**\n * Convert chain name to CAIP-2 identifier\n *\n * @param chainName - Chain name (e.g., 'base', 'solana')\n * @returns CAIP-2 identifier (e.g., 'eip155:8453', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp')\n */\nexport function chainToCAIP2(chainName: string): string {\n // Resolve through the registry FIRST, so an alias answers with the canonical\n // chain's id rather than one built out of the alias. Without this, asking\n // with `xrpl-mainnet` fell past the lookup into the fallback below and\n // manufactured `xrpl:xrpl-mainnet` -- a well-formed CAIP-2 string that no\n // facilitator has ever accepted, and one that PASSES the colon test every v2\n // guard in this SDK uses. A fabricated id is worse than a missing one: the\n // missing one is refused loudly, the fabricated one ships.\n const chain = getChainByName(chainName);\n const caip2 = CAIP2_IDENTIFIERS[(chain?.name ?? chainName).toLowerCase()];\n if (caip2) {\n return caip2;\n }\n\n // Try to construct from chain config\n if (chain) {\n if (chain.networkType === 'evm') {\n return `eip155:${chain.chainId}`;\n }\n // For non-EVM, return the canonical name with the network prefix\n return `${chain.networkType}:${chain.name}`;\n }\n\n return chainName; // Return as-is if unknown\n}\n\n/**\n * Convert CAIP-2 identifier to chain name\n *\n * @param caip2 - CAIP-2 identifier\n * @returns Chain name or null if unknown\n */\nexport function caip2ToChain(caip2: string): string | null {\n // Check direct mapping\n if (CAIP2_TO_CHAIN[caip2]) {\n return CAIP2_TO_CHAIN[caip2];\n }\n\n // Try to extract from EIP-155 format\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (match) {\n const chainId = parseInt(match[1], 10);\n // Find chain by ID\n for (const [name, _config] of Object.entries(CAIP2_IDENTIFIERS)) {\n const chain = getChainByName(name);\n if (chain?.chainId === chainId) {\n return name;\n }\n }\n }\n\n // Try to extract from network:name format\n const parts = caip2.split(':');\n if (parts.length === 2) {\n const networkName = parts[1];\n if (getChainByName(networkName)) {\n return networkName;\n }\n }\n\n return null;\n}\n\n/**\n * Parse network identifier from either v1 or v2 format\n *\n * @param network - Network identifier (v1 string or v2 CAIP-2)\n * @returns Normalized chain name\n */\nexport function parseNetworkIdentifier(network: string): string {\n // If it contains a colon, it's likely CAIP-2\n if (network.includes(':')) {\n return caip2ToChain(network) || network;\n }\n return network.toLowerCase();\n}\n\n/**\n * Encode x402 payload as base64 header value\n *\n * @param header - The x402 header object\n * @returns Base64-encoded string\n */\nexport function encodeX402Header(header: X402Header): string {\n return encodeBase64Json(header);\n}\n\n/**\n * Decode x402 header from base64 string\n *\n * @param encoded - Base64-encoded header value\n * @returns Parsed x402 header\n */\nexport function decodeX402Header(encoded: string): X402Header {\n const json = decodeBase64Utf8(encoded);\n return JSON.parse(json) as X402Header;\n}\n\n/**\n * Create x402 v1 header\n *\n * @param network - Chain name (e.g., 'base')\n * @param payload - Network-specific payload\n * @returns x402 v1 header object\n */\nexport function createX402V1Header(\n network: string,\n payload: X402PayloadData\n): X402HeaderV1 {\n if (getChainByName(network)?.networkType === 'hedera') throw new Error('Native Hedera supports only x402 v2');\n return {\n x402Version: 1,\n scheme: 'exact',\n network,\n payload,\n };\n}\n\n/**\n * Create x402 v2 header\n *\n * @param network - CAIP-2 network identifier\n * @param payload - Network-specific payload\n * @param accepts - Optional array of payment options\n * @returns x402 v2 header object\n */\nexport function createX402V2Header(\n network: string,\n payload: X402PayloadData,\n accepts?: X402PaymentOption[]\n): X402HeaderV2 {\n const header: X402HeaderV2 = {\n x402Version: 2,\n scheme: 'exact',\n network: network.includes(':') ? network : chainToCAIP2(network),\n payload,\n };\n\n if (accepts && accepts.length > 0) {\n header.accepts = accepts;\n }\n\n return header;\n}\n\n/**\n * Create x402 header with automatic version selection\n *\n * @param chainConfig - Chain configuration\n * @param payload - Network-specific payload\n * @param version - Version to use (1, 2, or 'auto')\n * @returns x402 header object\n */\nexport function createX402Header(\n chainConfig: ChainConfig,\n payload: X402PayloadData,\n version: X402Version | 'auto' = 'auto'\n): X402Header {\n // Default to v1 for maximum compatibility\n const effectiveVersion = version === 'auto' ? 1 : version;\n\n if (effectiveVersion === 2) {\n return createX402V2Header(chainConfig.name, payload);\n }\n\n return createX402V1Header(chainConfig.name, payload);\n}\n\n/**\n * Generate payment options array for multi-network support\n *\n * One entry per (chain, token) pair. By default the token is USDC on every\n * chain, which is exactly what this emitted before `tokens` existed.\n *\n * **`tokens` is opt-in on purpose, and the reason is money.** The chain\n * registry knows more stablecoins than USDC (Base also has EURC), and it is\n * tempting to just emit all of them. But this array becomes the `accepts` of a\n * `402`, so every entry is a currency the seller has publicly agreed to be paid\n * in -- at `amount` units of it. Emitting EURC for a seller who priced in\n * dollars would quietly sell at a 1:1 EUR/USD rate nobody agreed to. So the\n * caller names the tokens it actually accepts, and `amount` is read as units of\n * each named token, NOT converted between them.\n *\n * A token a chain does not have is skipped: an option is only emitted for pairs\n * the registry can actually price.\n *\n * @param chainConfigs - Array of chain configurations\n * @param amount - Amount in units of each token (e.g., \"10.00\")\n * @param facilitator - Optional facilitator URL override\n * @param tokens - Tokens to offer per chain (default: `['usdc']`)\n * @returns Array of x402 v2 payment options\n *\n * @example\n * ```ts\n * // Dollars only -- the default, and what every existing caller gets.\n * generatePaymentOptions([base], '5.00');\n *\n * // Dollars or euros, priced separately and both genuinely accepted.\n * generatePaymentOptions([base], '5.00', undefined, ['usdc', 'eurc']);\n * ```\n */\nexport function generatePaymentOptions(\n chainConfigs: ChainConfig[],\n amount: string,\n facilitator?: string,\n tokens: TokenType[] = ['usdc']\n): X402PaymentOption[] {\n const options: X402PaymentOption[] = [];\n\n for (const chain of chainConfigs) {\n if (!chain.x402.enabled) continue;\n\n for (const tokenType of tokens) {\n const token = getTokenConfig(chain.name, tokenType);\n if (!token) continue;\n\n // A token with no dollar peg is skipped for the same reason a missing one\n // is: this array can only carry pairs the registry can actually price.\n // XRPL reaches here because it files native XRP under the key `usdc`, so\n // the loop would otherwise emit \"5 XRP\" for a seller who wrote `'5.00'`\n // and asked for dollars.\n //\n // SKIP, not throw, and that is deliberate. This builds the `accepts` of\n // ONE 402 covering MANY chains -- the usual call is every enabled chain\n // at once -- so throwing would take the whole response down over a single\n // unpriceable pair and cost the seller the chains that were fine.\n // `buildPaymentRequirements` names one chain and therefore throws there.\n // EURC is available only through an explicitly named token: the caller\n // has chosen euros here. The default USDC path still excludes native XRP.\n if (!isUsdPegged(token) && tokenType !== 'eurc') continue;\n\n // Atomic units in THIS token's decimals -- BSC USDC has 18, not 6.\n // Unlike an unpriceable token above, an amount this token cannot hold\n // exactly is the caller's input, not the registry's: it throws.\n const atomicAmount = toAtomicUnits(amount, token.decimals).toString();\n\n options.push({\n network: chainToCAIP2(chain.name),\n asset: token.address,\n amount: atomicAmount,\n facilitator: facilitator || chain.x402.facilitatorUrl,\n });\n }\n }\n\n return options;\n}\n\n/**\n * Check if a network string is in CAIP-2 format\n *\n * @param network - Network identifier\n * @returns True if CAIP-2 format\n */\nexport function isCAIP2Format(network: string): boolean {\n return network.includes(':');\n}\n\n/**\n * Convert between x402 v1 and v2 header formats\n *\n * @param header - Source header\n * @param targetVersion - Target version\n * @returns Converted header\n */\nexport function convertX402Header(\n header: X402Header,\n targetVersion: X402Version\n): X402Header {\n if (header.x402Version === targetVersion) {\n return header;\n }\n\n if (targetVersion === 2) {\n // v1 -> v2\n return {\n x402Version: 2,\n scheme: 'exact',\n network: chainToCAIP2(header.network),\n payload: header.payload,\n };\n } else {\n // v2 -> v1\n const chainName = isCAIP2Format(header.network)\n ? caip2ToChain(header.network) || header.network\n : header.network;\n\n return {\n x402Version: 1,\n scheme: 'exact',\n network: chainName,\n payload: header.payload,\n };\n }\n}\n\n/**\n * Read a 402 payment challenge from wherever the seller put it.\n *\n * x402 allows BOTH transports and sellers pick freely:\n *\n * - base64 JSON in the `PAYMENT-REQUIRED` (or `X-PAYMENT-REQUIRED`) header\n * - JSON in the response body\n *\n * Measured against production on 2026-08-20: of 40 live Bazaar resources,\n * **36 of 36 that answered 402 carried the challenge in the header, and none in\n * the body**. Worse, sellers like Tenjin use the 402 body for a free preview of\n * the paid content — so the body is valid JSON that simply has no `accepts`, and\n * a body-only reader parses it happily and finds nothing.\n *\n * Reads the header first because that is where live sellers put it, and falls\n * back to the body so the sellers who use it keep working.\n *\n * Returns `null` when neither transport carries a challenge — a real \"no terms\n * here\", distinct from a challenge we failed to decode.\n */\nexport function paymentChallengeFrom(\n headers: { get(name: string): string | null } | Record<string, string>,\n body?: unknown,\n): Record<string, unknown> | null {\n const read = (name: string): string | null => {\n if (typeof (headers as { get?: unknown }).get === 'function') {\n return (headers as { get(n: string): string | null }).get(name);\n }\n const rec = headers as Record<string, string>;\n return rec[name] ?? rec[name.toLowerCase()] ?? rec[name.toUpperCase()] ?? null;\n };\n\n const raw = read('payment-required') ?? read('x-payment-required');\n if (raw) {\n const trimmed = raw.trim();\n for (const decode of [\n () => JSON.parse(decodeBase64Utf8(trimmed)),\n () => JSON.parse(trimmed),\n ]) {\n try {\n const parsed = decode();\n if (isChallenge(parsed)) return parsed as Record<string, unknown>;\n } catch {\n // not this encoding; try the next\n }\n }\n }\n\n const parsedBody = typeof body === 'string' ? tryJson(body) : body;\n return isChallenge(parsedBody) ? (parsedBody as Record<string, unknown>) : null;\n}\n\n/**\n * Whether a value actually looks like an x402 challenge.\n *\n * Deliberately stricter than \"is an object\": a 402 body carrying a free preview\n * is valid JSON with no payment terms in it, and treating that as a challenge is\n * how a body-only reader concludes it looked and found nothing wrong.\n */\nfunction isChallenge(v: unknown): boolean {\n if (typeof v !== 'object' || v === null) return false;\n const o = v as Record<string, unknown>;\n // `paymentRequirements` is the v1 spelling of `accepts`. Missing it made a\n // seller using it look like \"no terms here\" — the exact false negative this\n // function exists to prevent. Found in the Python SDK by KarmaKadabra's\n // buyer, which matched both keys in production, 2026-08-20.\n return (\n Array.isArray(o.accepts) ||\n Array.isArray(o.paymentRequirements) ||\n typeof o.payTo === 'string'\n );\n}\n\nfunction tryJson(s: string): unknown {\n try {\n return JSON.parse(s);\n } catch {\n return null;\n }\n}\n","/**\n * uvd-x402-sdk - Validation and Payment Header Utilities\n *\n * Functions for validating payment parameters and creating\n * payment headers for HTTP requests.\n */\n\nimport type { X402HeaderName, PaymentHeaders } from '../types';\nimport { X402Error } from '../types';\n\n/**\n * Regular expression for validating Ethereum addresses\n */\nconst ETH_ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/;\n\n/**\n * Regular expression for validating Solana addresses (base58, 32-44 chars)\n */\nconst SOLANA_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * Regular expression for validating Stellar addresses (G... format)\n */\nconst STELLAR_ADDRESS_REGEX = /^G[A-Z2-7]{55}$/;\n\n/**\n * Regular expression for validating NEAR addresses\n */\nconst NEAR_ADDRESS_REGEX = /^[a-z0-9._-]+$/;\n\n/**\n * Regular expression for validating XRPL classic addresses (r... base58, Ripple alphabet)\n */\nconst XRPL_ADDRESS_REGEX = /^r[1-9A-HJ-NP-Za-km-z]{24,34}$/;\n\n/**\n * Validate that a recipient address is present and valid\n *\n * This function ensures that:\n * 1. The recipient is not null, undefined, or empty\n * 2. The recipient is not just whitespace\n * 3. For EVM, it's a valid checksummed or lowercase 0x address\n *\n * @param recipient - The recipient address to validate\n * @param networkType - Optional network type for format validation\n * @throws X402Error with code 'INVALID_RECIPIENT' if validation fails\n */\nexport function validateRecipient(\n recipient: string | undefined | null,\n networkType?: 'evm' | 'svm' | 'solana' | 'stellar' | 'near' | 'xrpl' | 'hedera'\n): asserts recipient is string {\n // Check for null, undefined, or empty\n if (!recipient) {\n throw new X402Error(\n 'Recipient address is required. The payTo/recipient field cannot be empty. ' +\n 'Please provide a valid recipient address where payments should be sent.',\n 'INVALID_RECIPIENT'\n );\n }\n\n // Check for whitespace-only\n const trimmed = recipient.trim();\n if (trimmed === '') {\n throw new X402Error(\n 'Recipient address cannot be empty or whitespace. ' +\n 'Please provide a valid recipient address.',\n 'INVALID_RECIPIENT'\n );\n }\n\n // Network-specific validation\n if (networkType) {\n switch (networkType) {\n case 'evm':\n if (!ETH_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid EVM recipient address: \"${trimmed}\". ` +\n 'Expected a 40-character hexadecimal address starting with 0x.',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'svm':\n case 'solana':\n if (!SOLANA_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid Solana recipient address: \"${trimmed}\". ` +\n 'Expected a base58-encoded public key (32-44 characters).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'stellar':\n if (!STELLAR_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid Stellar recipient address: \"${trimmed}\". ` +\n 'Expected a G-prefixed public key (56 characters).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'near':\n if (!NEAR_ADDRESS_REGEX.test(trimmed) || trimmed.length > 64) {\n throw new X402Error(\n `Invalid NEAR recipient address: \"${trimmed}\". ` +\n 'Expected a valid NEAR account ID.',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n\n case 'hedera':\n if (!/^0\\.0\\.[1-9][0-9]*$/.test(trimmed)) {\n throw new X402Error('Hedera recipient must be a native numeric account ID', 'INVALID_RECIPIENT');\n }\n break;\n\n case 'xrpl':\n if (!XRPL_ADDRESS_REGEX.test(trimmed)) {\n throw new X402Error(\n `Invalid XRPL recipient address: \"${trimmed}\". ` +\n 'Expected a classic r-address (base58, Ripple alphabet).',\n 'INVALID_RECIPIENT'\n );\n }\n break;\n }\n }\n}\n\n/**\n * Validate payment amount\n *\n * Ensures the amount is a valid positive number string\n *\n * @param amount - The amount string to validate\n * @throws X402Error with code 'INVALID_AMOUNT' if validation fails\n */\nexport function validateAmount(amount: string | undefined | null): asserts amount is string {\n if (!amount) {\n throw new X402Error(\n 'Payment amount is required.',\n 'INVALID_AMOUNT'\n );\n }\n\n const trimmed = amount.trim();\n if (trimmed === '') {\n throw new X402Error(\n 'Payment amount cannot be empty.',\n 'INVALID_AMOUNT'\n );\n }\n\n // Parse as number\n const num = parseFloat(trimmed);\n if (isNaN(num)) {\n throw new X402Error(\n `Invalid payment amount: \"${trimmed}\". Expected a valid number.`,\n 'INVALID_AMOUNT'\n );\n }\n\n if (num <= 0) {\n throw new X402Error(\n `Payment amount must be positive. Got: ${trimmed}`,\n 'INVALID_AMOUNT'\n );\n }\n}\n\n// ============================================================================\n// PAYMENT HEADER UTILITIES\n// ============================================================================\n\n/**\n * Create payment headers object from a base64-encoded payload\n *\n * Returns an object with both X-PAYMENT and PAYMENT-SIGNATURE headers,\n * making it easy to use either header format.\n *\n * @param paymentHeader - Base64-encoded payment payload\n * @returns PaymentHeaders object with both header formats\n *\n * @example\n * ```ts\n * const headers = createPaymentHeaders(paymentHeader);\n *\n * // Use v1 header (most compatible)\n * fetch(url, { headers: { 'X-PAYMENT': headers['X-PAYMENT'] } });\n *\n * // Use v2 header\n * fetch(url, { headers: { 'PAYMENT-SIGNATURE': headers['PAYMENT-SIGNATURE'] } });\n * ```\n */\nexport function createPaymentHeaders(paymentHeader: string): PaymentHeaders {\n return {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n };\n}\n\n/**\n * Get a single payment header by name\n *\n * @param paymentHeader - Base64-encoded payment payload\n * @param headerName - Header name to use ('X-PAYMENT' or 'PAYMENT-SIGNATURE')\n * @returns Object with a single header entry\n *\n * @example\n * ```ts\n * // Use with fetch spread operator\n * fetch(url, {\n * headers: {\n * 'Content-Type': 'application/json',\n * ...getPaymentHeader(result.paymentHeader, 'X-PAYMENT'),\n * },\n * });\n * ```\n */\nexport function getPaymentHeader(\n paymentHeader: string,\n headerName: X402HeaderName = 'X-PAYMENT'\n): Record<X402HeaderName, string> {\n return { [headerName]: paymentHeader } as Record<X402HeaderName, string>;\n}\n\n/**\n * Default x402 payment header name\n *\n * Use 'X-PAYMENT' for maximum compatibility with all facilitators.\n * Use 'PAYMENT-SIGNATURE' for x402 v2 compliance.\n */\nexport const DEFAULT_PAYMENT_HEADER: X402HeaderName = 'X-PAYMENT';\n\n/**\n * All supported x402 payment header names\n */\nexport const PAYMENT_HEADER_NAMES: readonly X402HeaderName[] = [\n 'X-PAYMENT',\n 'PAYMENT-SIGNATURE',\n] as const;\n","/**\n * uvd-x402-sdk - Wagmi/Viem Adapter\n *\n * Provides integration with wagmi/viem for projects using RainbowKit,\n * ConnectKit, or other wagmi-based wallet connection libraries.\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { createPaymentFromWalletClient } from 'uvd-x402-sdk/wagmi';\n *\n * function PayButton() {\n * const { data: walletClient } = useWalletClient();\n *\n * const handlePay = async () => {\n * const paymentHeader = await createPaymentFromWalletClient(walletClient, {\n * recipient: '0x...',\n * amount: '1.00',\n * chainName: 'base',\n * });\n *\n * // Use in your API request\n * await fetch('/api/paid-endpoint', {\n * headers: { 'X-PAYMENT': paymentHeader }\n * });\n * };\n *\n * return <button onClick={handlePay}>Pay $1.00</button>;\n * }\n * ```\n */\n\nimport { getChainByName } from '../chains';\nimport { createX402V1Header, createX402V2Header, encodeX402Header, validateRecipient } from '../utils';\nimport { X402Error } from '../types';\nimport type { PaymentResult, X402Version } from '../types';\n\n/**\n * Viem WalletClient interface (minimal type to avoid viem dependency)\n */\nexport interface WalletClient {\n account: {\n address: `0x${string}`;\n };\n signTypedData: (args: {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: `0x${string}`;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n }) => Promise<`0x${string}`>;\n}\n\n/**\n * Payment options for wagmi adapter\n */\nexport interface WagmiPaymentOptions {\n /** Recipient address */\n recipient: string;\n /** Amount in USDC (e.g., \"1.00\", \"10.50\") */\n amount: string;\n /** Chain name (default: 'base') */\n chainName?: string;\n /** Validity window in seconds (default: 300 = 5 minutes) */\n validitySeconds?: number;\n /**\n * x402 protocol version (default: 1)\n * - 1: Classic format with network as string (e.g., \"base\")\n * - 2: CAIP-2 format (e.g., \"eip155:8453\")\n */\n x402Version?: X402Version;\n}\n\n/**\n * Generate a random 32-byte nonce as hex string\n */\nfunction generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n if (typeof globalThis !== 'undefined' && globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof window !== 'undefined' && window.crypto?.getRandomValues) {\n window.crypto.getRandomValues(bytes);\n } else {\n // Fallback for non-browser environments\n for (let i = 0; i < 32; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return ('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')) as `0x${string}`;\n}\n\n/**\n * Parse amount string to atomic units (BigInt)\n */\nfunction parseUnits(amount: string, decimals: number): bigint {\n const [integer, fraction = ''] = amount.split('.');\n const paddedFraction = fraction.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(integer + paddedFraction);\n}\n\n/**\n * Create an x402 payment header using a wagmi/viem WalletClient\n *\n * This function allows you to use the x402 SDK with wagmi-based wallet\n * connections (RainbowKit, ConnectKit, etc.) instead of the built-in\n * wallet connection.\n *\n * @param walletClient - The WalletClient from wagmi's useWalletClient hook\n * @param options - Payment options (recipient, amount, chainName)\n * @returns Base64-encoded payment header ready for X-PAYMENT HTTP header\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { createPaymentFromWalletClient } from 'uvd-x402-sdk/wagmi';\n *\n * const { data: walletClient } = useWalletClient();\n *\n * const paymentHeader = await createPaymentFromWalletClient(walletClient, {\n * recipient: '0xRecipientAddress',\n * amount: '5.00',\n * chainName: 'base',\n * });\n * ```\n */\nexport async function createPaymentFromWalletClient(\n walletClient: WalletClient | undefined | null,\n options: WagmiPaymentOptions\n): Promise<string> {\n if (!walletClient) {\n throw new X402Error('WalletClient is not available. Make sure wallet is connected.', 'WALLET_NOT_CONNECTED');\n }\n\n const {\n recipient,\n amount,\n chainName = 'base',\n validitySeconds = 300,\n x402Version = 1,\n } = options;\n\n // Validate recipient address - prevents empty/invalid addresses\n validateRecipient(recipient, 'evm');\n\n // Get chain configuration\n const chain = getChainByName(chainName);\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${chainName}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `wagmi adapter only supports EVM chains. For ${chain.networkType}, use the appropriate provider.`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n const from = walletClient.account.address;\n const to = recipient as `0x${string}`;\n const nonce = generateNonce();\n const validAfter = 0;\n const validBefore = Math.floor(Date.now() / 1000) + validitySeconds;\n const value = parseUnits(amount, chain.usdc.decimals);\n\n // EIP-712 domain\n const domain = {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId: chain.chainId,\n verifyingContract: chain.usdc.address as `0x${string}`,\n };\n\n // EIP-712 types for TransferWithAuthorization (ERC-3009)\n const types = {\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 };\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter: BigInt(validAfter),\n validBefore: BigInt(validBefore),\n nonce,\n };\n\n // Sign with viem\n let signature: `0x${string}`;\n try {\n signature = await walletClient.signTypedData({\n domain,\n types,\n primaryType: 'TransferWithAuthorization',\n message,\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || error.message.includes('denied')) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to sign payment: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n // Build the payload data\n // IMPORTANT: validAfter, validBefore, and value must be STRINGS\n const payloadData = {\n signature,\n authorization: {\n from,\n to: recipient,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n },\n };\n\n // Create x402 header with correct version format\n const header = x402Version === 2\n ? createX402V2Header(chainName, payloadData)\n : createX402V1Header(chainName, payloadData);\n\n return encodeX402Header(header);\n}\n\n/**\n * Create payment with full result object (includes metadata)\n *\n * Same as createPaymentFromWalletClient but returns a PaymentResult\n * object with additional metadata.\n *\n * @param walletClient - The WalletClient from wagmi\n * @param options - Payment options\n * @returns PaymentResult with paymentHeader and metadata\n */\nexport async function createPaymentWithResult(\n walletClient: WalletClient | undefined | null,\n options: WagmiPaymentOptions\n): Promise<PaymentResult> {\n const paymentHeader = await createPaymentFromWalletClient(walletClient, options);\n\n return {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: options.chainName || 'base',\n payer: walletClient?.account.address,\n };\n}\n\n/**\n * React hook helper for wagmi integration\n *\n * Returns a function that creates payments using the connected wallet.\n * This is a simple wrapper - for more control, use createPaymentFromWalletClient directly.\n *\n * @example\n * ```tsx\n * import { useWalletClient } from 'wagmi';\n * import { useX402Wagmi } from 'uvd-x402-sdk/wagmi';\n *\n * function PayButton() {\n * const { data: walletClient } = useWalletClient();\n * const { createPayment, isReady } = useX402Wagmi(walletClient);\n *\n * return (\n * <button\n * disabled={!isReady}\n * onClick={() => createPayment({ recipient: '0x...', amount: '1.00' })}\n * >\n * Pay\n * </button>\n * );\n * }\n * ```\n */\nexport function useX402Wagmi(walletClient: WalletClient | undefined | null) {\n const isReady = !!walletClient;\n\n const createPayment = async (options: WagmiPaymentOptions): Promise<string> => {\n return createPaymentFromWalletClient(walletClient, options);\n };\n\n const createPaymentFull = async (options: WagmiPaymentOptions): Promise<PaymentResult> => {\n return createPaymentWithResult(walletClient, options);\n };\n\n return {\n isReady,\n createPayment,\n createPaymentFull,\n };\n}\n","/**\n * uvd-x402-sdk - Integers that crossed JSON\n *\n * An EIP-712 uint written as a JSON NUMBER hashes the same where it was\n * written and is destroyed where it is read: `JSON.parse` turns every integer\n * above `Number.MAX_SAFE_INTEGER` (2**53 - 1) into the nearest double. A\n * 32-byte `salt` such as `0xab…ab` comes out as 7.76e+76, `BigInt()` of that\n * is a different integer, and the struct signed from it is not the one that\n * was sent: the facilitator answers `bad_signature` and neither end can say\n * why. The pinned lifecycle vector's salt (12345) fits in a double and shows\n * nothing; `release/real-salt` in `scripts/xlang/cross-language-conformance.mjs`\n * is the case that does.\n *\n * The rounding cannot be undone, but it can be seen: an integer above\n * 2**53 - 1 is still above it after rounding. So every integer this SDK reads\n * for a signature or a hash goes through here, and a number that is not a safe\n * integer is refused with an error that names the field. Strings (decimal or\n * 0x-hex) and bigints carry any width exactly and are accepted.\n *\n * Where the SDK reads the JSON TEXT itself (a signer handed typed data as a\n * string), a 32-byte salt has nothing to undo: {@link parseJsonExact} reads an\n * integer of 22 to 78 digits as a bigint, digit for digit, as Python's `json`\n * does, and the document is signed with the integer that was written. One a\n * double may have been written as is refused as before: JavaScript writes a\n * rounded number in up to 21 plain digits, and other writers print a rounded\n * double in full, so those digits may not be the ones the producer meant.\n */\n\nimport { ethers } from 'ethers';\n\nimport { X402Error, type X402ErrorCode } from '../types';\n\n/** Decimal digits, or 0x-hex. No sign, no spaces, no exponent, never empty. */\nconst UINT_STRING = /^(?:[0-9]+|0[xX][0-9a-fA-F]+)$/;\n\n/** An EIP-712 integer type: `uint256`, `int128`, `uint` ... */\nconst INTEGER_TYPE = /^u?int\\d*$/;\n\nfunction shown(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'bigint') return `${value}n`;\n return String(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** The refusal for an integer JSON could not have carried exactly. */\nexport function inexactNumberMessage(field: string, value: number): string {\n return (\n `${field} is the JSON number ${String(value)}, larger in magnitude than ` +\n 'Number.MAX_SAFE_INTEGER (2**53 - 1): JSON.parse has already rounded it, and signing it ' +\n 'would sign a different integer than the one that was written. Send uints as decimal or ' +\n '0x-hex strings (or a bigint)'\n );\n}\n\n/** A number found where an integer is read: rounded on its way in, or not an integer at all. */\nfunction numberRefusal(path: string, value: number, code: X402ErrorCode): X402Error {\n return new X402Error(\n Number.isInteger(value)\n ? inexactNumberMessage(path, value)\n : `${path} must be an integer, got the JSON number ${String(value)}`,\n code\n );\n}\n\n/**\n * An unsigned integer read for a signature or a hash, exactly.\n *\n * Accepts a bigint `>= 0`, a number that is a safe integer `>= 0`, and a\n * string of decimal digits or 0x-hex. Refuses, with `code`, a number above\n * 2**53 - 1 (it was rounded on its way in), a negative, a fraction, and any\n * other string: empty, signed, with spaces or an exponent. `BigInt('')` is\n * `0n`: an empty lifecycle `amount` used to be signed as zero.\n *\n * @param field - Named in the error, e.g. `'paymentInfo.maxAmount'`.\n */\nexport function toUint(\n value: unknown,\n field: string,\n code: X402ErrorCode = 'INVALID_CONFIG'\n): bigint {\n if (typeof value === 'bigint') {\n if (value < 0n) {\n throw new X402Error(`${field} must be a non-negative integer, got ${shown(value)}`, code);\n }\n return value;\n }\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) && value >= 0) return BigInt(value);\n if (Number.isInteger(value) && value > 0) {\n throw new X402Error(inexactNumberMessage(field, value), code);\n }\n throw new X402Error(`${field} must be a non-negative integer, got ${shown(value)}`, code);\n }\n if (typeof value === 'string' && UINT_STRING.test(value)) return BigInt(value);\n throw new X402Error(\n `${field} must be a non-negative integer (decimal or 0x-hex string, bigint, or a number ` +\n `up to 2**53 - 1), got ${shown(value)}`,\n code\n );\n}\n\n/**\n * The first number under `value` that is not a safe integer, with its path.\n * Depth first, arrays and plain objects only; `null` when there is none.\n */\nexport function findInexactNumber(\n value: unknown,\n path: string,\n seen: Set<object> = new Set()\n): { path: string; value: number } | null {\n if (typeof value === 'number') {\n return Number.isSafeInteger(value) ? null : { path, value };\n }\n // Untyped, an object holds the same numbers wherever it is reached, so once\n // is enough, and an object that contains itself (built in code, never\n // parsed) does not recurse for ever.\n if (typeof value !== 'object' || value === null || seen.has(value)) return null;\n seen.add(value);\n const entries: Array<[string, unknown]> = Array.isArray(value)\n ? value.map((item, i): [string, unknown] => [`${path}[${i}]`, item])\n : Object.entries(value).map(([key, item]): [string, unknown] => [`${path}.${key}`, item]);\n for (const [itemPath, item] of entries) {\n const hit = findInexactNumber(item, itemPath, seen);\n if (hit) return hit;\n }\n return null;\n}\n\n/**\n * Refuse `value` if any number under it is not a safe integer: for JSON whose\n * every number is an integer read for a signature (an ERC-3009 payload).\n */\nexport function assertNoInexactNumber(\n value: unknown,\n path: string,\n code: X402ErrorCode = 'INVALID_CONFIG'\n): void {\n const hit = findInexactNumber(value, path);\n if (hit) throw numberRefusal(hit.path, hit.value, code);\n}\n\n/** The root struct ethers signs for `types`, or `primaryType` when ethers cannot say. */\nfunction rootStruct(structs: Record<string, unknown>, primaryType: unknown): string | null {\n try {\n return ethers.TypedDataEncoder.from(\n structs as Record<string, Array<{ name: string; type: string }>>\n ).primaryType;\n } catch {\n return typeof primaryType === 'string' && Array.isArray(structs[primaryType])\n ? primaryType\n : null;\n }\n}\n\nfunction checkTyped(\n type: string,\n value: unknown,\n path: string,\n structs: Record<string, unknown>,\n code: X402ErrorCode,\n ancestors: Set<object> = new Set()\n): void {\n // A value that contains itself, under types that do (ethers refuses those,\n // so it falls back to `primaryType`), would recurse for ever.\n if (typeof value === 'object' && value !== null) {\n if (ancestors.has(value)) return;\n ancestors.add(value);\n }\n try {\n const array = /^(.*)\\[(\\d*)\\]$/.exec(type);\n if (array) {\n if (Array.isArray(value)) {\n value.forEach((item, i) =>\n checkTyped(array[1], item, `${path}[${i}]`, structs, code, ancestors)\n );\n }\n return;\n }\n const struct = structs[type];\n if (Array.isArray(struct)) {\n if (!isRecord(value)) return;\n for (const field of struct as Array<{ name?: unknown; type?: unknown }>) {\n if (typeof field?.name === 'string' && typeof field.type === 'string') {\n checkTyped(\n field.type,\n value[field.name],\n `${path}.${field.name}`,\n structs,\n code,\n ancestors\n );\n }\n }\n return;\n }\n if (INTEGER_TYPE.test(type) && typeof value === 'number' && !Number.isSafeInteger(value)) {\n throw numberRefusal(path, value, code);\n }\n } finally {\n if (typeof value === 'object' && value !== null) ancestors.delete(value);\n }\n}\n\n/**\n * Refuse an EIP-712 document whose integers JSON could not have carried: every\n * `uintN` / `intN` field of `message` by its declared type (nested structs and\n * arrays included), and `domain.chainId`. `message` is walked as the root\n * struct ethers signs for these `types` and, when it names another struct, as\n * `primaryType` too: viem, wagmi and `eth_signTypedData_v4` sign that one.\n * When the types cannot be read at all, any number in `message` that is not a\n * safe integer is refused.\n *\n * Shape errors (no `types`, a field missing) are left to the signer: this\n * only answers whether an integer was rounded on its way in.\n *\n * @param where - Prefix of the field path in the error, e.g. `'typed data'`.\n */\nexport function assertTypedDataIntegersExact(\n doc: unknown,\n where = 'typed data',\n code: X402ErrorCode = 'INVALID_CONFIG'\n): void {\n if (!isRecord(doc)) return;\n const { domain, types, message, primaryType } = doc;\n\n if (isRecord(domain) && typeof domain.chainId === 'number' && !Number.isSafeInteger(domain.chainId)) {\n throw numberRefusal(`${where} domain.chainId`, domain.chainId, code);\n }\n if (!isRecord(message)) return;\n\n const structs = isRecord(types) ? { ...types } : {};\n delete structs['EIP712Domain'];\n const root = rootStruct(structs, primaryType);\n if (root) {\n checkTyped(root, message, `${where} message`, structs, code);\n if (typeof primaryType === 'string' && primaryType !== root && Array.isArray(structs[primaryType])) {\n checkTyped(primaryType, message, `${where} message`, structs, code);\n }\n return;\n }\n assertNoInexactNumber(message, `${where} message`, code);\n}\n\n/**\n * Fewest digits of an integer literal read as a bigint. JavaScript writes a\n * number below 1e21 in plain digits, 21 at most, and from 1e21 up with an\n * exponent, so a literal of 22 digits or more never came out of\n * `JSON.stringify`. One of 21 digits or fewer may be a value a JavaScript hop\n * already rounded and wrote back in digits:\n * `JSON.stringify(JSON.parse('1234567890123456789'))` is `1234567890123456800`.\n * Such a literal stays the number `JSON.parse` reads, and an integer field\n * refuses it, as before.\n */\nconst MIN_EXACT_DIGITS = 22;\n\n/**\n * The widest EIP-712 integer, 2**256 - 1, has 78 decimal digits. A longer\n * literal cannot be one, and `BigInt()` of a long run of digits costs time\n * that grows faster than its length, while `JSON.parse` reads it at once.\n */\nconst MAX_EXACT_DIGITS = 78;\n\n/** A double's shortest decimal form has at most 17 significant digits. */\nconst MAX_DOUBLE_DIGITS = 17;\n\n/**\n * Whether an integer literal may be a double written out in full: the exact\n * value of a double (`BigInt(n).toString()`, Python's `int(f)` and `'%.0f'`,\n * Java's `new BigDecimal(d)`), or at most 17 significant digits followed by\n * zeros (`n.toLocaleString()`, `Intl.NumberFormat`, Java's `toPlainString()`,\n * a 15-digit writer). Such a literal may be a value that was rounded to a\n * double before it was written, so it is not read as more exact than one. A\n * random 32-byte salt is neither, but with odds of about 1 in 10**60.\n */\nfunction doubleShaped(literal: string): boolean {\n const significant = literal.replace(/^-/, '').replace(/0+$/, '');\n return significant.length <= MAX_DOUBLE_DIGITS || BigInt(literal) === BigInt(Number(literal));\n}\n\n/** A JSON number (RFC 8259): groups 1 and 2 are the fraction and the exponent. */\nconst JSON_NUMBER = /-?(?:0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?/y;\n\n/** The four characters JSON allows between tokens. */\nconst JSON_SPACE = /[ \\t\\n\\r]*/y;\n\ntype Frame =\n | { kind: 'array'; items: unknown[] }\n | { kind: 'object'; object: Record<string, unknown>; key: string };\n\n/**\n * A data descriptor with no prototype: `Object.defineProperty` reads `get`\n * and `set` through the prototype chain, and `JSON.parse` reads nothing a\n * polluted `Object.prototype` adds.\n */\nfunction dataDescriptor(value: unknown): PropertyDescriptor {\n const descriptor = Object.create(null) as PropertyDescriptor;\n descriptor.value = value;\n descriptor.writable = true;\n descriptor.enumerable = true;\n descriptor.configurable = true;\n return descriptor;\n}\n\n/**\n * `JSON.parse(text)`, except that an integer literal of 22 to 78 digits, with\n * no fraction or exponent, that no double could have been written as comes\n * back as a bigint with the exact value written. Python's `json` reads those\n * digits exactly; `JSON.parse` turns a 32-byte salt (77 digits) into\n * 7.76e+76. 22 is where JavaScript stops writing plain digits\n * ({@link MIN_EXACT_DIGITS}), 78 the width of 2**256 - 1\n * ({@link MAX_EXACT_DIGITS}), and a literal a double may have been written as\n * is left out ({@link doubleShaped}). Any other literal is the number\n * `JSON.parse` reads: one of 21 digits or fewer, longer than 78, shaped like a\n * double, or with a fraction or an exponent (`7.76e+76`).\n *\n * A text with no such literal is returned by `JSON.parse` itself, so for it\n * nothing changes. Otherwise the value is built the way `JSON.parse` builds\n * it: the last of two equal keys wins in the place of the first, `__proto__`\n * is an own key, strings are decoded by `JSON.parse`, and a plain property\n * added to `Object.prototype` is never read into the value (an accessor or a\n * read-only index there makes it throw, never return another value). Anything\n * that is not JSON throws a `SyntaxError`, as `JSON.parse` does, and a value\n * that is not a string is read as `String(value)`, as `JSON.parse` reads it.\n */\nexport function parseJsonExact(input: string): unknown {\n const text = String(input);\n let pos = 0;\n let wide = false;\n\n const fail = (what: string): never => {\n throw new SyntaxError(`${what} in JSON at position ${pos}`);\n };\n const space = (): void => {\n JSON_SPACE.lastIndex = pos;\n // A failed sticky match resets lastIndex to 0: never read it then, or a\n // position past the end would send the parse back to the start.\n if (JSON_SPACE.exec(text)) pos = JSON_SPACE.lastIndex;\n };\n const string = (): string => {\n if (text[pos] !== '\"') fail('Expected a string');\n let end = pos + 1;\n while (end < text.length && text[end] !== '\"') end += text[end] === '\\\\' ? 2 : 1;\n if (end >= text.length) fail('Unterminated string');\n const value = JSON.parse(text.slice(pos, end + 1)) as string;\n pos = end + 1;\n return value;\n };\n const key = (): string => {\n const name = string();\n space();\n if (text[pos] !== ':') fail(\"Expected ':'\");\n pos += 1;\n space();\n return name;\n };\n const scalar = (): unknown => {\n if (text[pos] === '\"') return string();\n for (const [word, value] of [['true', true], ['false', false], ['null', null]] as const) {\n if (text.startsWith(word, pos)) {\n pos += word.length;\n return value;\n }\n }\n JSON_NUMBER.lastIndex = pos;\n const match = JSON_NUMBER.exec(text);\n if (!match) return fail('Unexpected token');\n pos = JSON_NUMBER.lastIndex;\n const literal = match[0];\n const digits = literal.length - (literal.startsWith('-') ? 1 : 0);\n if (\n match[1] === undefined &&\n match[2] === undefined &&\n digits >= MIN_EXACT_DIGITS &&\n digits <= MAX_EXACT_DIGITS &&\n !doubleShaped(literal)\n ) {\n wide = true;\n return BigInt(literal);\n }\n return Number(literal);\n };\n\n // A loop with its own stack, not recursion: JSON.parse reads nesting as\n // deep as the text has, and so does this.\n const stack: Frame[] = [];\n space();\n for (;;) {\n let value: unknown;\n if (text[pos] === '[') {\n pos += 1;\n space();\n if (text[pos] !== ']') {\n stack.push({ kind: 'array', items: [] });\n continue;\n }\n pos += 1;\n value = [];\n } else if (text[pos] === '{') {\n pos += 1;\n space();\n if (text[pos] !== '}') {\n stack.push({ kind: 'object', object: {}, key: key() });\n continue;\n }\n pos += 1;\n value = {};\n } else {\n value = scalar();\n }\n\n // The value is complete: hand it to its container, and close every\n // container that ends right after it.\n for (;;) {\n space();\n const top = stack[stack.length - 1];\n if (top === undefined) {\n if (pos !== text.length) fail('Unexpected non-whitespace character after JSON');\n return wide ? value : JSON.parse(text);\n }\n const close = top.kind === 'array' ? ']' : '}';\n if (top.kind === 'array') {\n top.items.push(value);\n } else {\n Object.defineProperty(top.object, top.key, dataDescriptor(value));\n }\n if (text[pos] === ',') {\n pos += 1;\n space();\n if (top.kind === 'object') top.key = key();\n break;\n }\n if (text[pos] !== close) fail(`Expected ',' or '${close}'`);\n pos += 1;\n stack.pop();\n value = top.kind === 'array' ? top.items : top.object;\n }\n }\n}\n\n/**\n * An EIP-712 document read from JSON text with {@link parseJsonExact}, so an\n * integer of 22 to 78 digits written as a number keeps every digit; then\n * refused if an integer field still holds a number that is not a safe\n * integer: one of up to 21 digits (a JavaScript hop may have rounded it), one\n * a double may have been written as, or one written with an exponent or a\n * fraction ({@link assertTypedDataIntegersExact}).\n */\nexport function parseTypedDataJson(\n text: string,\n where = 'typed data',\n code: X402ErrorCode = 'INVALID_CONFIG'\n): unknown {\n const doc: unknown = parseJsonExact(text);\n assertTypedDataIntegersExact(doc, where, code);\n return doc;\n}\n","/**\n * uvd-x402-sdk - EnvKeyAdapter\n *\n * SigningWalletAdapter implementation using a raw private key.\n * Reads the key from a constructor parameter or the WALLET_PRIVATE_KEY\n * environment variable.\n *\n * Intended for server-side / CLI / agent use cases where the\n * signing key is available in the environment. NEVER use this\n * in browser contexts -- use OWSWalletAdapter instead.\n *\n * @example Using environment variable\n * ```ts\n * // Reads process.env.WALLET_PRIVATE_KEY\n * const wallet = new EnvKeyAdapter();\n * console.log(wallet.getAddress()); // 0x...\n * ```\n *\n * @example Using explicit key\n * ```ts\n * const wallet = new EnvKeyAdapter(process.env.MY_AGENT_KEY!);\n * const auth = await wallet.signEIP3009({\n * to: '0xRecipient',\n * amountUsdc: 0.10,\n * network: 'base',\n * });\n * ```\n */\n\nimport { ethers } from 'ethers';\nimport { getChainByName } from '../chains';\nimport { X402Error } from '../types';\nimport { parseTypedDataJson } from '../utils/uint';\nimport type {\n SigningWalletAdapter,\n EIP3009Params,\n EIP3009Authorization,\n} from '../wallet';\n\n/**\n * EnvKeyAdapter -- SigningWalletAdapter backed by a raw private key.\n */\nexport class EnvKeyAdapter implements SigningWalletAdapter {\n private readonly wallet: ethers.Wallet;\n\n /**\n * Create an EnvKeyAdapter.\n *\n * @param privateKey - Hex-encoded private key (with or without 0x prefix).\n * If omitted, reads from `process.env.WALLET_PRIVATE_KEY`.\n * @throws {X402Error} if no private key is available\n */\n constructor(privateKey?: string) {\n const key = privateKey || (typeof process !== 'undefined' ? process.env.WALLET_PRIVATE_KEY : undefined);\n\n if (!key) {\n throw new X402Error(\n 'No private key provided. Pass it to the constructor or set WALLET_PRIVATE_KEY env var.',\n 'WALLET_NOT_CONNECTED',\n );\n }\n\n this.wallet = new ethers.Wallet(key);\n }\n\n /**\n * Get the checksummed EVM wallet address.\n */\n getAddress(): string {\n return this.wallet.address;\n }\n\n /**\n * Sign a message using EIP-191 personal_sign.\n *\n * @param message - The message string to sign\n * @returns Hex-encoded signature\n */\n async signMessage(message: string): Promise<string> {\n return this.wallet.signMessage(message);\n }\n\n /**\n * Sign EIP-712 typed structured data.\n *\n * An integer of 22 to 78 digits written as a JSON number (a 32-byte salt)\n * is read with every digit, as Python's `json` reads it, not rounded the\n * way `JSON.parse` rounds it.\n *\n * @param typedData - JSON string with `domain`, `types`, `primaryType`, and `message` fields\n * @returns Object with signature and v/r/s components\n * @throws {X402Error} `INVALID_CONFIG` when an integer field of `message`\n * (or `domain.chainId`) is a JSON number above 2**53 - 1 of up to 21\n * digits (a JavaScript hop may have rounded it and written it back in\n * digits) or written with an exponent or a fraction (`7.76e+76`): it is\n * refused instead of signed. Write uints as strings. An integer out of\n * its field's range is refused by ethers (`value out-of-bounds`).\n */\n async signTypedData(typedData: string): Promise<{\n signature: string;\n v: number;\n r: string;\n s: string;\n }> {\n const parsed = parseTypedDataJson(typedData) as {\n domain: ethers.TypedDataDomain;\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n };\n\n // ethers v6 signTypedData does not take primaryType -- it infers it\n // from the types object (the type not listed as a field of another type).\n // We pass domain, types (without EIP712Domain), and the message value.\n const { domain, types, message } = parsed;\n\n // Remove EIP712Domain from types if present (ethers handles it via domain)\n const cleanTypes = { ...types };\n delete cleanTypes['EIP712Domain'];\n\n const signature = await this.wallet.signTypedData(domain, cleanTypes, message);\n const sig = ethers.Signature.from(signature);\n\n return {\n signature,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n };\n }\n\n /**\n * Sign a serialized EVM transaction.\n *\n * Uses the raw private key via ethers.Wallet.signTransaction().\n * Used by AdvancedEscrowClient for on-chain operations (release,\n * refund, charge) when constructed with a SigningWalletAdapter.\n *\n * @param unsignedTx - Hex-encoded unsigned transaction (ethers serialized)\n * @returns Hex-encoded signed raw transaction, ready for broadcast\n */\n async signTransaction(unsignedTx: string): Promise<string> {\n const tx = ethers.Transaction.from(unsignedTx);\n return this.wallet.signTransaction(tx);\n }\n\n /**\n * Sign an EIP-3009 ReceiveWithAuthorization for USDC.\n *\n * @param params - EIP-3009 parameters\n * @returns Signed authorization ready for facilitator relay\n */\n async signEIP3009(params: EIP3009Params): Promise<EIP3009Authorization> {\n const chain = getChainByName(params.network);\n if (!chain) {\n throw new X402Error(`Unsupported network: ${params.network}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `EIP-3009 is only supported on EVM chains. ${params.network} is ${chain.networkType}.`,\n 'CHAIN_NOT_SUPPORTED',\n );\n }\n\n const chainId = params.chainId ?? chain.chainId;\n const usdcAddress = params.usdcContract ?? chain.usdc.address;\n const from = this.wallet.address;\n const to = ethers.getAddress(params.to);\n const value = ethers.parseUnits(params.amountUsdc.toString(), chain.usdc.decimals);\n const validAfter = params.validAfter ?? 0;\n const validBefore = params.validBefore ?? Math.floor(Date.now() / 1000) + 300;\n\n // Generate random 32-byte nonce\n const nonce = ethers.hexlify(ethers.randomBytes(32));\n\n // EIP-712 domain (matches USDC contract's domain separator)\n const domain: ethers.TypedDataDomain = {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId,\n verifyingContract: usdcAddress,\n };\n\n // EIP-712 types for TransferWithAuthorization (ERC-3009)\n const types = {\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 };\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter,\n validBefore,\n nonce,\n };\n\n // Sign the EIP-712 typed data\n let signature: string;\n try {\n signature = await this.wallet.signTypedData(domain, types, message);\n } catch (error: unknown) {\n throw new X402Error(\n `Failed to sign EIP-3009 authorization: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error,\n );\n }\n\n const sig = ethers.Signature.from(signature);\n\n return {\n from,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n signature,\n };\n }\n}\n","/**\n * uvd-x402-sdk - OWSWalletAdapter\n *\n * SigningWalletAdapter over an Open Wallet Standard (OWS) vault. OWS keeps the\n * keys encrypted in a local vault and signs inside it; the key never reaches\n * this process.\n *\n * Written against `@open-wallet-standard/core` 1.4.2 (an optional peer\n * dependency: a native Node module, prebuilt for Linux glibc and macOS on x64\n * and arm64). Measured on 1.4.2, not taken from its docs:\n *\n * - Its functions take the wallet by name or id, the chain as CAIP-2\n * (`eip155:8453`), then the passphrase and the vault path, all positional.\n * They return `{ signature, recoveryId }`, the signature as hex without\n * `0x`: `r || s || v`, with v = 27/28 for messages and typed data and 0/1\n * for transactions.\n * - `signTypedData` takes the EIP-712 document as a JSON string and refuses\n * one without `EIP712Domain` in `types` or without `primaryType`. It hashes\n * `EIP712Domain` in the order it is given.\n * - Integers: a decimal string above 2**128 - 1 is refused (\"use hex\n * encoding\"), so is odd-length hex, and a JSON number above 2**64. Out of\n * range it signs ANOTHER value without a word: `2**256` as a uint256 is\n * signed as 0, `256` as a uint8 as 0, `-129` as an int8. It also accepts\n * an address with a bad checksum and bytes without `0x`, where ethers\n * refuses both.\n * - `signTransaction` signs keccak256 of whatever bytes it is given and\n * returns only the signature: the signed transaction is assembled here.\n * - A wrong passphrase is `decryption failed: aead::Error`; no error seen\n * carries the passphrase.\n *\n * So this adapter normalises typed data by the DECLARED EIP-712 type and\n * refuses what ethers refuses before anything is signed, and after signing it\n * recovers every signature with ethers over the digest `EnvKeyAdapter` signs:\n * a signature that does not recover to `getAddress()` is not returned.\n *\n * @example\n * ```ts\n * import * as ows from '@open-wallet-standard/core';\n * import { OWSWalletAdapter } from 'uvd-x402-sdk';\n *\n * const wallet = new OWSWalletAdapter(ows, {\n * wallet: 'agent-treasury', // name or id in the vault\n * passphrase: process.env.OWS_PASSPHRASE,\n * network: 'base',\n * });\n * const auth = await wallet.signEIP3009({\n * to: '0xRecipient',\n * amountUsdc: 0.50,\n * network: 'base',\n * });\n * ```\n */\n\nimport { ethers } from 'ethers';\nimport { getChainByName } from '../chains';\nimport { X402Error } from '../types';\nimport { inexactNumberMessage, parseJsonExact } from '../utils/uint';\nimport type {\n SigningWalletAdapter,\n EIP3009Params,\n EIP3009Authorization,\n} from '../wallet';\n\n// ============================================================================\n// THE LIBRARY, AS 1.4.2 DECLARES IT\n// ============================================================================\n\n/** What a signing call of `@open-wallet-standard/core` returns. */\nexport interface OWSSignResult {\n /** Hex WITHOUT `0x`. On EVM, 65 bytes: `r || s || v`. */\n signature: string;\n /** The recovery byte again: 27/28 for messages and typed data, 0/1 for transactions. */\n recoveryId?: number;\n}\n\n/** One account of an OWS wallet (one per chain family). */\nexport interface OWSAccountInfo {\n /** CAIP-2 chain id; the EVM account is `eip155:1`. */\n chainId: string;\n address: string;\n derivationPath: string;\n}\n\n/**\n * The functions of `@open-wallet-standard/core` this adapter calls, with the\n * parameters its 1.4.2 `index.d.ts` declares (the same since 1.0.0). Pass the\n * module itself: `import * as ows from '@open-wallet-standard/core'`.\n *\n * Written by hand so that the SDK's types do not need the package installed;\n * `src/adapters/ows.test.ts` compares it with the installed declarations.\n */\nexport interface OWSCore {\n getWallet(\n nameOrId: string,\n vaultPathOpt?: string | null\n ): { id: string; name: string; accounts: OWSAccountInfo[]; createdAt: string };\n signMessage(\n wallet: string,\n chain: string,\n message: string,\n passphrase?: string | null,\n encoding?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n signTypedData(\n wallet: string,\n chain: string,\n typedDataJson: string,\n passphrase?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n signTransaction(\n wallet: string,\n chain: string,\n txHex: string,\n passphrase?: string | null,\n index?: number | null,\n vaultPathOpt?: string | null\n ): OWSSignResult;\n}\n\nconst OWS_FUNCTIONS = ['getWallet', 'signMessage', 'signTypedData', 'signTransaction'] as const;\n\n/**\n * The wallet object the adapter took before it was written against\n * `@open-wallet-standard/core` 1.4.2.\n *\n * @deprecated This shape is not the `@open-wallet-standard/core` API and\n * never worked with OWS 1.x. It is still exported so that code importing it\n * compiles, but `new OWSWalletAdapter(wallet)` with it throws `INVALID_CONFIG`.\n * Migrate to {@link OWSCore}: pass the module and the wallet,\n * `new OWSWalletAdapter(ows, { wallet: '<name or id>', passphrase })` with\n * `import * as ows from '@open-wallet-standard/core'`.\n */\nexport interface OWSWallet {\n accounts: ReadonlyArray<{\n address: string;\n chains?: ReadonlyArray<string>;\n }>;\n signMessage(params: {\n account: { address: string };\n message: string | Uint8Array;\n }): Promise<{ signature: string }>;\n signTypedData(params: {\n account: { address: string };\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n }): Promise<{ signature: string }>;\n signTransaction(params: {\n account: { address: string };\n transaction: string;\n chainId: string;\n }): Promise<{ signedTransaction: string }>;\n}\n\nconst MIGRATION =\n \"pass the module and the wallet: new OWSWalletAdapter(ows, { wallet: '<name or id>', passphrase }) \" +\n \"with import * as ows from '@open-wallet-standard/core'\";\n\n/** Options of {@link OWSWalletAdapter}. */\nexport interface OWSWalletAdapterOptions {\n /** Name or id of the wallet in the OWS vault. */\n wallet: string;\n /**\n * Vault passphrase, or an OWS API key. Default: `process.env.OWS_PASSPHRASE`.\n * An explicit value, `''` included, wins over the environment.\n */\n passphrase?: string;\n /**\n * EVM network to sign for when the payload names no chain: an SDK name\n * (`'base'`) or CAIP-2 (`'eip155:8453'`). Default `'base'`. Typed data with\n * a `domain.chainId` and transactions with a `chainId` are signed on their\n * own chain. The chain is what an OWS policy decides on; it does not change\n * the bytes signed.\n */\n network?: string;\n /**\n * Vault directory. Default: the OWS default (`~/.ows`). OWS CREATES a\n * directory that does not exist, so a typo here gives an empty vault and\n * \"wallet not found\", not a missing-directory error.\n */\n vaultPath?: string;\n}\n\n// ============================================================================\n// TYPED DATA, AS OWS READS IT\n// ============================================================================\n\ntype TypedField = { name: string; type: string };\ntype TypedTypes = Record<string, TypedField[]>;\n\n/**\n * The EIP-712 domain fields in the order ethers derives `EIP712Domain` in.\n * OWS hashes the order it is given, so it gets this one.\n */\nconst EIP712_DOMAIN_FIELDS: ReadonlyArray<readonly [string, string]> = [\n ['name', 'string'],\n ['version', 'string'],\n ['chainId', 'uint256'],\n ['verifyingContract', 'address'],\n ['salt', 'bytes32'],\n];\n\n/** What ethers' `Transaction.from` reads from an object (6.16), `from` and `hash` aside. */\nconst TRANSACTION_FIELDS = [\n 'type',\n 'to',\n 'nonce',\n 'gasLimit',\n 'gasPrice',\n 'maxPriorityFeePerGas',\n 'maxFeePerGas',\n 'maxFeePerBlobGas',\n 'data',\n 'value',\n 'chainId',\n 'signature',\n 'accessList',\n 'authorizationList',\n 'blobVersionedHashes',\n 'kzg',\n 'blobWrapperVersion',\n 'blobs',\n] as const;\n\n/** Keys of other transaction formats, and the ethers name of the same field. */\nconst ETHERS_NAME_OF: Readonly<Record<string, string>> = { input: 'data', gas: 'gasLimit' };\n\nconst TWO_127 = 1n << 127n;\nconst TWO_128 = 1n << 128n;\nconst TWO_256 = 1n << 256n;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction shown(value: unknown): string {\n if (typeof value === 'bigint') return `${value}n`;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction refuse(message: string): X402Error {\n return new X402Error(`${message}; nothing was signed`, 'INVALID_CONFIG');\n}\n\n/**\n * An integer given as a bigint, a safe-integer number, a decimal string or a\n * 0x-hex string, with an optional leading `-`: what ethers accepts for an\n * EIP-712 integer, minus whitespace and floats.\n */\nfunction toInteger(value: unknown, where: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number' && Number.isSafeInteger(value)) return BigInt(value);\n // An integer past 2**53 - 1 is a value JSON.parse already rounded.\n if (typeof value === 'number' && Number.isInteger(value)) throw refuse(inexactNumberMessage(where, value));\n if (typeof value === 'string' && /^-?(0[xX][0-9a-fA-F]+|[0-9]+)$/.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n throw refuse(\n `${where}: ${shown(value)} is not an integer (a safe-integer number, a decimal string or 0x-hex)`\n );\n}\n\n/**\n * An integer the way OWS 1.4.2 reads it: decimal from -2**127 to 2**128 - 1,\n * even-length hex above, and 256-bit two's complement below (only a type\n * wider than 128 bits gets there).\n */\nfunction integerWire(n: bigint): string {\n if (n >= -TWO_127 && n < TWO_128) return n.toString();\n if (n > 0n) {\n const digits = n.toString(16);\n return `0x${digits.length % 2 ? '0' : ''}${digits}`;\n }\n return `0x${(n + TWO_256).toString(16).padStart(64, '0')}`;\n}\n\n/**\n * `value` of the EIP-712 type `kind` in the form OWS reads from JSON.\n *\n * Normalised by the DECLARED type, not by the JavaScript type of the value:\n * a uint256 comes as a number, a decimal string or 0x-hex (the lifecycle\n * order sends its `salt` as a decimal string above 2**128). Every integer is\n * checked against the range of its type here, before anything is signed.\n * Fields not in the type are left out; they are not part of the digest.\n */\nfunction owsValue(kind: string, value: unknown, types: TypedTypes, where: string): unknown {\n const array = /^(.*)\\[(\\d*)\\]$/.exec(kind);\n if (array) {\n const [, inner, size] = array;\n if (!Array.isArray(value)) throw refuse(`${where}: ${kind} needs an array, got ${shown(value)}`);\n if (size !== '' && value.length !== Number(size)) {\n throw refuse(`${where}: ${kind} needs ${size} items, got ${value.length}`);\n }\n return value.map((item, i) => owsValue(inner, item, types, `${where}[${i}]`));\n }\n\n const struct = types[kind];\n if (struct) {\n if (!isRecord(value)) throw refuse(`${where}: ${kind} needs an object, got ${shown(value)}`);\n const out: Record<string, unknown> = {};\n for (const field of struct) {\n if (value[field.name] === undefined) throw refuse(`${where}: ${kind} lacks ${field.name}`);\n out[field.name] = owsValue(field.type, value[field.name], types, `${where}.${field.name}`);\n }\n return out;\n }\n\n const integer = /^(u?)int(\\d+)$/.exec(kind);\n if (integer) {\n const bits = BigInt(integer[2]);\n const n = toInteger(value, where);\n const [low, high] = integer[1] ? [0n, 1n << bits] : [-(1n << (bits - 1n)), 1n << (bits - 1n)];\n if (n < low || n >= high) {\n throw new X402Error(\n `${where}: ${shown(value)} is out of range for ${kind}; nothing was signed`,\n 'INVALID_AMOUNT'\n );\n }\n return integerWire(n);\n }\n\n if (kind === 'bool') {\n if (typeof value !== 'boolean') throw refuse(`${where}: bool needs true or false, got ${shown(value)}`);\n return value;\n }\n if (kind === 'string') {\n if (typeof value !== 'string') throw refuse(`${where}: string needs a string, got ${shown(value)}`);\n return value;\n }\n if (kind === 'address') {\n try {\n if (typeof value !== 'string') throw new Error();\n return ethers.getAddress(value);\n } catch {\n throw refuse(`${where}: ${shown(value)} is not an address`);\n }\n }\n\n const bytes = /^bytes(\\d*)$/.exec(kind);\n if (bytes) {\n let raw: Uint8Array;\n try {\n if (typeof value !== 'string') throw new Error();\n raw = ethers.getBytes(value);\n } catch {\n throw refuse(`${where}: ${kind} needs 0x-hex, got ${shown(value)}`);\n }\n if (bytes[1] !== '' && raw.length !== Number(bytes[1])) {\n throw refuse(`${where}: ${kind} needs ${bytes[1]} bytes, got ${raw.length}`);\n }\n return ethers.hexlify(raw);\n }\n\n throw refuse(`${where}: unsupported EIP-712 type ${kind}`);\n}\n\ninterface PreparedTypedData {\n /** What OWS signs, as JSON. */\n document: string;\n /** The caller's domain, types (without EIP712Domain) and message: what ethers hashes. */\n domain: ethers.TypedDataDomain;\n types: TypedTypes;\n message: Record<string, unknown>;\n /** CAIP-2 chain of `domain.chainId`, if it names one. */\n chain: string | null;\n}\n\n/**\n * The typed data as the JSON document `signTypedData` of OWS takes.\n *\n * `EIP712Domain` is always derived from the domain's keys, in ethers' order,\n * and one the caller sent is ignored, as `EnvKeyAdapter` ignores it. The\n * root struct is the one ethers picks; a `primaryType` naming another is\n * refused (ethers would sign the root). Domain and message are normalised by\n * their declared types.\n */\nfunction prepareTypedData(input: unknown): PreparedTypedData {\n if (!isRecord(input)) throw refuse('typed data must be an object with domain, types and message');\n const { domain, types, message, primaryType } = input;\n if (!isRecord(domain)) throw refuse('typed data needs a domain object');\n if (!isRecord(types)) throw refuse('typed data needs a types object');\n if (!isRecord(message)) throw refuse('typed data needs a message object');\n\n const structs = { ...(types as TypedTypes) };\n delete structs['EIP712Domain'];\n let root: string;\n try {\n root = ethers.TypedDataEncoder.from(structs).primaryType;\n } catch (error) {\n throw refuse(`typed data types are invalid (${error instanceof Error ? error.message : error})`);\n }\n if (primaryType !== undefined && primaryType !== root) {\n throw refuse(\n `primaryType ${shown(primaryType)} is not ${root}, the root struct ethers signs for these types`\n );\n }\n\n for (const key of Object.keys(domain)) {\n if (!EIP712_DOMAIN_FIELDS.some(([name]) => name === key)) {\n throw refuse(`domain.${key} is not an EIP-712 domain field`);\n }\n }\n // ethers leaves a null domain field out of EIP712Domain; so does this.\n const all: TypedTypes = {\n EIP712Domain: EIP712_DOMAIN_FIELDS.filter(([name]) => domain[name] != null).map(\n ([name, type]) => ({ name, type })\n ),\n // Each field as ethers hashes it, name and type: any other key (a wide\n // number in it is a bigint) never reaches OWS or JSON.stringify.\n ...Object.fromEntries(\n Object.entries(structs).map(([struct, fields]) => [\n struct,\n fields.map(({ name, type }) => ({ name, type })),\n ])\n ),\n };\n const owsDomain = owsValue('EIP712Domain', domain, all, 'domain') as Record<string, unknown>;\n const owsMessage = owsValue(root, message, all, 'message');\n\n const chainId = domain['chainId'] != null ? toInteger(domain['chainId'], 'domain.chainId') : 0n;\n return {\n document: JSON.stringify({ types: all, primaryType: root, domain: owsDomain, message: owsMessage }),\n domain: domain as ethers.TypedDataDomain,\n types: structs,\n message,\n chain: chainId > 0n ? `eip155:${chainId}` : null,\n };\n}\n\n/** The 65-byte signature of an OWS result, v as 27/28. */\nfunction evmSignature(result: OWSSignResult, what: string): ethers.Signature {\n const hex = String(result?.signature ?? '').replace(/^0x/, '');\n if (!/^[0-9a-fA-F]{130}$/.test(hex)) {\n throw new X402Error(`OWS ${what} returned a signature that is not 65 bytes of hex`, 'PAYMENT_FAILED');\n }\n const bytes = ethers.getBytes(`0x${hex}`);\n const v = bytes[64] < 27 ? bytes[64] + 27 : bytes[64];\n if (v !== 27 && v !== 28) {\n throw new X402Error(`OWS ${what} returned a recovery byte of ${bytes[64]}`, 'PAYMENT_FAILED');\n }\n return ethers.Signature.from({\n r: ethers.hexlify(bytes.subarray(0, 32)),\n s: ethers.hexlify(bytes.subarray(32, 64)),\n v,\n });\n}\n\n/** `eip155:<id>` of an SDK EVM network name or a CAIP-2 `eip155:` id. */\nfunction caip2(network: string): string {\n if (typeof network !== 'string') {\n throw new X402Error(\n `OWSWalletAdapter: options.network must be a string (an SDK network name or eip155:<id>), got ${typeof network}`,\n 'INVALID_CONFIG'\n );\n }\n const caip = /^eip155:([1-9][0-9]*)$/.exec(network);\n if (caip) return network;\n const chain = getChainByName(network);\n if (!chain || chain.networkType !== 'evm') {\n throw new X402Error(\n `OWSWalletAdapter signs for an EVM network; got ${shown(network)}`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n return `eip155:${chain.chainId}`;\n}\n\n// ============================================================================\n// OWS WALLET ADAPTER\n// ============================================================================\n\n/**\n * OWSWalletAdapter -- SigningWalletAdapter over an Open Wallet Standard vault.\n *\n * Every method signs the bytes `EnvKeyAdapter` signs for the same key (the\n * tests import an ephemeral key into a temporary vault and compare), or\n * throws `X402Error` and returns nothing. Refused before signing: an integer\n * out of the range of its EIP-712 type, and whatever ethers refuses to\n * encode. Refused after signing: a signature that does not recover to\n * `getAddress()` with ethers over the digest `EnvKeyAdapter` signs.\n *\n * The passphrase is held in a private field: `JSON.stringify`, `console.log`\n * and `util.inspect` of the adapter do not show it, and error messages are\n * scrubbed of it. Errors do not carry the library's original error object.\n */\nexport class OWSWalletAdapter implements SigningWalletAdapter {\n readonly #ows: OWSCore;\n readonly #wallet: string;\n readonly #passphrase: string | null;\n readonly #vaultPath: string | null;\n readonly #chain: string;\n readonly #address: string;\n\n /**\n * Create an OWSWalletAdapter.\n *\n * @param ows - The `@open-wallet-standard/core` module\n * (`import * as ows from '@open-wallet-standard/core'`), 1.4.2 or later 1.x.\n * @param options - Which wallet, its passphrase, the default network and the vault.\n * @throws {X402Error} `INVALID_CONFIG` if `ows` is not that module or no\n * wallet is named, `CHAIN_NOT_SUPPORTED` if `network` is not EVM,\n * `WALLET_NOT_FOUND` if the vault has no such wallet or it has no EVM account.\n */\n constructor(ows: OWSCore, options: OWSWalletAdapterOptions);\n /**\n * @deprecated The old form, a wallet object with `accounts`\n * ({@link OWSWallet}). It still compiles, but it never worked with OWS 1.x\n * and now throws `INVALID_CONFIG` without signing anything. Pass the module\n * and the wallet: `new OWSWalletAdapter(ows, { wallet, passphrase })`.\n */\n constructor(owsWallet: OWSWallet, accountIndex?: number);\n constructor(ows: OWSCore | OWSWallet, options?: OWSWalletAdapterOptions | number) {\n if (isRecord(ows) && 'accounts' in ows && (options === undefined || typeof options === 'number')) {\n throw new X402Error(\n 'OWSWalletAdapter no longer takes a wallet object with accounts (the deprecated OWSWallet ' +\n `shape, which never worked with @open-wallet-standard/core 1.x); ${MIGRATION}. Nothing was signed.`,\n 'INVALID_CONFIG'\n );\n }\n const missing = OWS_FUNCTIONS.filter(\n (name) => typeof (ows as unknown as Record<string, unknown> | null)?.[name] !== 'function'\n );\n if (missing.length > 0) {\n throw new X402Error(\n `OWSWalletAdapter takes the @open-wallet-standard/core module ` +\n `(import * as ows from '@open-wallet-standard/core'); it lacks ${missing.join(', ')}. ` +\n 'Since the OWS rewrite the adapter no longer takes a wallet object with accounts.',\n 'INVALID_CONFIG'\n );\n }\n const opts = (isRecord(options) ? options : {}) as Partial<OWSWalletAdapterOptions>;\n if (typeof opts.wallet !== 'string' || opts.wallet === '') {\n throw new X402Error('OWSWalletAdapter needs options.wallet: the name or id of a wallet in the vault', 'INVALID_CONFIG');\n }\n\n // The native binding echoes a mistyped argument in its error message, so a\n // passphrase that is not a string is refused here, without showing it.\n if (opts.passphrase != null && typeof opts.passphrase !== 'string') {\n throw new X402Error('OWSWalletAdapter: options.passphrase must be a string', 'INVALID_CONFIG');\n }\n\n this.#ows = ows as OWSCore;\n this.#wallet = opts.wallet;\n this.#passphrase =\n opts.passphrase ??\n (typeof process !== 'undefined' ? process.env?.OWS_PASSPHRASE : undefined) ??\n null;\n this.#vaultPath = opts.vaultPath ?? null;\n this.#chain = caip2(opts.network ?? 'base');\n\n const info = this.#call('getWallet', () => this.#ows.getWallet(this.#wallet, this.#vaultPath), 'WALLET_NOT_FOUND');\n const account = (info?.accounts ?? []).find((a) => String(a.chainId).startsWith('eip155:'));\n if (!account) {\n throw new X402Error(`OWS wallet ${shown(this.#wallet)} has no EVM account`, 'WALLET_NOT_FOUND');\n }\n this.#address = ethers.getAddress(account.address);\n }\n\n /**\n * Get the checksummed EVM wallet address (read from the vault once, when\n * the adapter was created; no passphrase needed).\n */\n getAddress(): string {\n return this.#address;\n }\n\n /**\n * Sign a message using EIP-191 personal_sign (the string as UTF-8, as\n * `EnvKeyAdapter` signs it).\n *\n * @param message - The message string to sign\n * @returns Hex-encoded 65-byte signature, v = 27/28\n */\n async signMessage(message: string): Promise<string> {\n if (typeof message !== 'string') throw refuse(`signMessage takes a string, got ${typeof message}`);\n const result = this.#call('signMessage', () =>\n this.#ows.signMessage(this.#wallet, this.#chain, message, this.#passphrase, 'utf8', null, this.#vaultPath)\n );\n const signature = evmSignature(result, 'signMessage').serialized;\n let signer = '';\n try {\n signer = ethers.verifyMessage(message, signature);\n } catch {\n // not recoverable: refused below\n }\n this.#checkSigner(signer, 'signMessage');\n return signature;\n }\n\n /**\n * Sign EIP-712 typed structured data.\n *\n * @param typedData - JSON string with `domain`, `types`, `message` and\n * optionally `primaryType` (it must then be the root struct)\n * @returns Object with signature and v/r/s components\n * @throws {X402Error} `INVALID_AMOUNT` for an integer out of its type's\n * range and `INVALID_CONFIG` for anything else ethers would not encode,\n * both before signing; `PAYMENT_FAILED` if OWS fails or signs a digest\n * other than the one ethers computes (the signature is not returned).\n */\n async signTypedData(typedData: string): Promise<{\n signature: string;\n v: number;\n r: string;\n s: string;\n }> {\n let parsed: unknown;\n try {\n // An integer written as a JSON number keeps every digit (a bigint);\n // JSON.parse would round a 32-byte one.\n parsed = parseJsonExact(typedData);\n } catch {\n throw refuse('typedData is not a JSON string');\n }\n return this.#signTyped(parsed);\n }\n\n /**\n * Sign an EVM transaction.\n *\n * OWS signs keccak256 of the bytes it is given and returns only the\n * signature, so the transaction is parsed and serialised with ethers here,\n * the way `EnvKeyAdapter` (ethers.Wallet) does it, EIP-155 `v` included.\n *\n * A sender, given as `from` or implied by an existing signature, must be\n * this wallet: it is taken out, as ethers takes it out; any other sender is\n * refused before signing.\n *\n * @param unsignedTx - Hex-encoded transaction (ethers serialized), an\n * `ethers.Transaction`, or a transaction object ethers' `Transaction.from`\n * accepts, plus `from`\n * @returns Hex-encoded signed raw transaction, ready for broadcast\n */\n async signTransaction(unsignedTx: string | ethers.TransactionLike<string>): Promise<string> {\n const tx = this.#unsignedTransaction(unsignedTx);\n const chain = tx.chainId > 0n ? `eip155:${tx.chainId}` : this.#chain;\n const result = this.#call('signTransaction', () =>\n this.#ows.signTransaction(\n this.#wallet,\n chain,\n tx.unsignedSerialized.slice(2),\n this.#passphrase,\n null,\n this.#vaultPath\n )\n );\n tx.signature = evmSignature(result, 'signTransaction');\n const signed = tx.serialized;\n this.#checkSigner(ethers.Transaction.from(signed).from ?? '', 'signTransaction');\n return signed;\n }\n\n /**\n * Sign an EIP-3009 TransferWithAuthorization for USDC: the typed data\n * `EnvKeyAdapter.signEIP3009` builds, signed through {@link signTypedData}\n * (OWS has no EIP-3009 call of its own).\n *\n * @param params - EIP-3009 parameters\n * @returns Signed authorization ready for facilitator relay\n */\n async signEIP3009(params: EIP3009Params): Promise<EIP3009Authorization> {\n const chain = getChainByName(params.network);\n if (!chain) {\n throw new X402Error(`Unsupported network: ${params.network}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error(\n `EIP-3009 is only supported on EVM chains. ${params.network} is ${chain.networkType}.`,\n 'CHAIN_NOT_SUPPORTED',\n );\n }\n\n const chainId = params.chainId ?? chain.chainId;\n const usdcAddress = params.usdcContract ?? chain.usdc.address;\n const from = this.#address;\n const to = ethers.getAddress(params.to);\n const value = ethers.parseUnits(params.amountUsdc.toString(), chain.usdc.decimals);\n const validAfter = params.validAfter ?? 0;\n const validBefore = params.validBefore ?? Math.floor(Date.now() / 1000) + 300;\n\n // Generate random 32-byte nonce\n const nonce = ethers.hexlify(ethers.randomBytes(32));\n\n const signed = await this.#signTyped({\n domain: {\n name: chain.usdc.name,\n version: chain.usdc.version,\n chainId,\n verifyingContract: usdcAddress,\n },\n types: {\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 },\n primaryType: 'TransferWithAuthorization',\n message: { from, to, value, validAfter, validBefore, nonce },\n });\n\n return {\n from,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n v: signed.v,\n r: signed.r,\n s: signed.s,\n signature: signed.signature,\n };\n }\n\n // --------------------------------------------------------------------------\n\n async #signTyped(input: unknown): Promise<{ signature: string; v: number; r: string; s: string }> {\n const typed = prepareTypedData(input);\n const result = this.#call('signTypedData', () =>\n this.#ows.signTypedData(\n this.#wallet,\n typed.chain ?? this.#chain,\n typed.document,\n this.#passphrase,\n null,\n this.#vaultPath\n )\n );\n const sig = evmSignature(result, 'signTypedData');\n let signer: string;\n try {\n signer = ethers.verifyTypedData(typed.domain, typed.types, typed.message, sig);\n } catch (error) {\n throw new X402Error(\n `ethers cannot encode this typed data (${error instanceof Error ? error.message : error}); ` +\n 'the OWS signature is not returned',\n 'INVALID_CONFIG'\n );\n }\n this.#checkSigner(signer, 'signTypedData');\n return { signature: sig.serialized, v: sig.v, r: sig.r, s: sig.s };\n }\n\n #unsignedTransaction(input: string | ethers.TransactionLike<string>): ethers.Transaction {\n const senders: unknown[] = [];\n let tx: ethers.Transaction;\n try {\n if (typeof input === 'string') {\n tx = ethers.Transaction.from(input);\n } else if (typeof input === 'object' && input !== null) {\n // Read field by field, not spread: an ethers.Transaction keeps its\n // fields behind getters, and a spread of it is an empty transaction.\n const source = input as Record<string, unknown>;\n // An ethers.Transaction has no own keys; a plain object may only use\n // the keys ethers reads, so that no field is dropped on the way.\n for (const key of Object.keys(source)) {\n if (key === 'from' || key === 'hash' || (TRANSACTION_FIELDS as readonly string[]).includes(key)) continue;\n const ethersName = ETHERS_NAME_OF[key];\n throw refuse(\n `transaction key ${shown(key)} is not one ethers reads` +\n (ethersName ? `; ethers calls it ${ethersName}` : '')\n );\n }\n if (source.from != null) senders.push(source.from);\n const fields: Record<string, unknown> = {};\n for (const key of TRANSACTION_FIELDS) {\n if (source[key] != null) fields[key] = source[key];\n }\n tx = ethers.Transaction.from(fields);\n } else {\n throw new Error(`got ${typeof input}`);\n }\n } catch (error) {\n if (error instanceof X402Error) throw error;\n throw refuse(\n `not a transaction ethers can read (${error instanceof Error ? error.message : error})`\n );\n }\n if (tx.signature) senders.push(tx.from);\n for (const sender of senders) {\n let address = '';\n try {\n address = ethers.getAddress(sender as string);\n } catch {\n // not an address: refused below\n }\n if (address !== this.#address) {\n throw refuse(`transaction from ${shown(sender)} is not this wallet (${this.#address})`);\n }\n }\n tx.signature = null;\n return tx;\n }\n\n #checkSigner(signer: string, what: string): void {\n if (signer !== this.#address) {\n throw new X402Error(\n `OWS ${what} returned a signature that does not recover to ${this.#address} over the ` +\n 'digest ethers computes (the one EnvKeyAdapter signs); it is not returned',\n 'PAYMENT_FAILED'\n );\n }\n }\n\n /** Run one OWS call; its error becomes an X402Error without the passphrase in it. */\n #call<T>(what: string, run: () => T, code: 'PAYMENT_FAILED' | 'WALLET_NOT_FOUND' = 'PAYMENT_FAILED'): T {\n try {\n return run();\n } catch (error) {\n let message = error instanceof Error ? error.message : String(error);\n if (this.#passphrase) message = message.split(this.#passphrase).join('[redacted]');\n throw new X402Error(`OWS ${what} failed: ${message}`, code);\n }\n }\n}\n"]}
|