uvd-x402-sdk 2.89.0 → 2.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/index.ts","../../src/chains/index.ts","../../src/utils/base64.ts","../../src/utils/x402.ts","../../src/utils/token-metadata.ts","../../src/utils/validation.ts","../../src/utils/personal-sign.ts","../../src/utils/index.ts","../../src/providers/solana/index.ts","../../src/client/X402Client.ts","../../src/policy.ts","../../src/react/index.tsx","../../src/react/NetworkPicker.tsx","../../src/react/PaymentMethodPicker.tsx"],"names":["publicKeyString","ethers","SVMProvider","useMemo","useRef","useCallback","jsxs","jsx","useState","createContext","useEffect","useContext"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IA4kBa,iBAAA,EAuCA,gBA8PA,cAAA,EAuGA,SAAA;AAx9Bb,IAAA,UAAA,GAAA,KAAA,CAAA;AAAA,EAAA,oBAAA,GAAA;AA4kBO,IAAM,iBAAA,GAA4C;AAAA;AAAA,MAEvD,IAAA,EAAM,aAAA;AAAA,MACN,QAAA,EAAU,UAAA;AAAA,MACV,OAAA,EAAS,YAAA;AAAA,MACT,QAAA,EAAU,cAAA;AAAA,MACV,QAAA,EAAU,WAAA;AAAA,MACV,SAAA,EAAW,cAAA;AAAA,MACX,IAAA,EAAM,cAAA;AAAA,MACN,QAAA,EAAU,YAAA;AAAA,MACV,QAAA,EAAU,YAAA;AAAA,MACV,KAAA,EAAO,YAAA;AAAA,MACP,GAAA,EAAK,WAAA;AAAA,MACL,MAAA,EAAQ,eAAA;AAAA,MACR,YAAA,EAAc,mBAAA;AAAA,MACd,oBAAA,EAAsB,kBAAA;AAAA,MACtB,SAAA,EAAW,aAAA;AAAA,MACX,mBAAA,EAAqB,cAAA;AAAA;AAAA,MAErB,MAAA,EAAQ,yCAAA;AAAA,MACR,IAAA,EAAM,UAAA;AAAA;AAAA,MAE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EAAiB;AAAA,EACnB,CAAA,EAAG,CAAC,gBAAgB,CAAC,CAAA;AAGrB,EAAA,MAAM,qBAAA,GAAwBP,cAAQ,MAAM;AAC1C,IAAA,IAAI,UAAA,GAAa,CAAA;AACjB,IAAA,IAAI,QAAA,GAA0B,IAAA;AAE9B,IAAA,QAAA,CAAS,OAAA,CAAQ,CAAC,EAAA,EAAI,SAAA,KAAc;AAClC,MAAA,IAAI,EAAA,CAAG,OAAA,KAAY,IAAA,IAAQ,CAAC,GAAG,KAAA,EAAO;AACpC,QAAA,MAAM,GAAA,GAAM,UAAA,CAAW,EAAA,CAAG,OAAO,CAAA;AACjC,QAAA,IAAI,MAAM,UAAA,EAAY;AACpB,UAAA,UAAA,GAAa,GAAA;AACb,UAAA,QAAA,GAAW,SAAA;AAAA,QACb;AAAA,MACF;AAAA,IACF,CAAC,CAAA;AAED,IAAA,OAAO,QAAA;AAAA,EACT,CAAA,EAAG,CAAC,QAAQ,CAAC,CAAA;AAEb,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA,EAAS,gBAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\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';\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';\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 exactly one thing today: the native\n * XRP that XRPL settles in.\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 /** 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 };\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 every dollar-pegged token that is dollars, which is all of them but\n * one. On XRPL it is **XRP**, because XRPL settles in its own native asset:\n * the provider spends this through `xrpToDrops` 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\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 /** 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 // 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 // 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\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 - Chain Registry\n *\n * Complete configuration for all 25 supported blockchain networks.\n * EVM chains (15): Use ERC-3009 TransferWithAuthorization (includes Scroll, SKALE Base, Robinhood Chain mainnet + testnet)\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 // ============================================================================\n // EVM CHAINS (15 networks)\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 },\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 eurc: {\n address: '0xC891EB4cbdEFf6e073e859e987815Ed1505c2ACD',\n decimals: 6,\n name: 'EURC',\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 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 },\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 // ============================================================================\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:199`).\n */\nexport const CHAIN_ALIASES: Record<string, string> = {\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 '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 '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 - 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';\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\n if (obj.accepts && Array.isArray(obj.accepts)) {\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 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 if (!isUsdPegged(token)) continue;\n\n // Atomic units in THIS token's decimals -- BSC USDC has 18, not 6.\n const atomicAmount = Math.floor(\n parseFloat(amount) * Math.pow(10, token.decimals)\n ).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 - Token metadata for payment payloads\n *\n * An EIP-3009 authorization is signed against a token contract, but the encoded\n * payload only carries the signature and the transfer fields. The token itself\n * is implicit — the server is expected to already know which asset it asked\n * for.\n *\n * That holds when a resource accepts exactly one token per chain. It breaks as\n * soon as it accepts several: a EURC payment and a USDC payment on Base produce\n * indistinguishable payloads, and the server cannot build the\n * `paymentRequirements` (`asset` + `extra`) the facilitator needs to settle.\n *\n * So the payment can opt into carrying the token with it.\n */\n\nimport { getTokenByAddress } from '../chains';\nimport type { PaymentTokenMetadata } from '../types';\n\n/**\n * Build the token metadata block for a payload, resolving the address against\n * the chain registry.\n *\n * @param chainName - Chain the payment was signed for\n * @param address - Token contract address from the signed payload\n * @returns Metadata block, or undefined if the address is not in the registry\n */\nexport function buildTokenMetadata(\n chainName: string,\n address: string\n): PaymentTokenMetadata | undefined {\n const match = getTokenByAddress(chainName, address);\n if (!match) return undefined;\n\n return {\n address: match.config.address,\n symbol: match.tokenType.toUpperCase(),\n decimals: match.config.decimals,\n eip712: {\n name: match.config.name,\n version: match.config.version,\n },\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'\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 '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 - EIP-191 personal_sign helpers\n *\n * Generic recover/verify for an EIP-191 `personal_sign` over an arbitrary\n * string message — the shape a wallet produces for `eth_sign`/`personal_sign`\n * and `cast wallet sign <message>`.\n *\n * This is deliberately NOT the ERC-8128 machinery (`verifyRequest`), which\n * verifies an RFC 9421 SIGNED HTTP REQUEST (method;url;headers;content-digest).\n * A challenge/response flow — a service hands out a nonce string, the wallet\n * signs that string, the service recovers the signer — is a different, simpler\n * case that the ERC-8128 path does not cover. Consumers doing wallet-ownership\n * challenges (e.g. MeshRelay's IRC `VERIFY`/`VERIFY-SIG`) needed this and were\n * each reaching for `ethers.verifyMessage` directly; this centralizes it.\n */\n\nimport { ethers } from 'ethers';\n\n/**\n * Recover the address that produced an EIP-191 `personal_sign` over `message`.\n *\n * @param message - the exact string that was signed\n * @param signature - the 0x-prefixed signature\n * @returns the checksummed recovered address\n * @throws if the signature is malformed (propagates ethers' error)\n */\nexport function recoverPersonalSignAddress(message: string, signature: string): string {\n return ethers.verifyMessage(message, signature);\n}\n\n/**\n * Whether `signature` over `message` was produced by `expected`.\n *\n * Compares case-insensitively (recovered addresses are checksummed, linked\n * wallets are often stored lower-cased) and never throws: a malformed\n * signature is a failed verification, not an exception to handle at every\n * call site.\n *\n * @returns true iff the recovered signer equals `expected`\n */\nexport function verifyPersonalSign(params: {\n message: string;\n signature: string;\n expected: string;\n}): boolean {\n const { message, signature, expected } = params;\n if (!expected) return false;\n try {\n const recovered = recoverPersonalSignAddress(message, signature);\n return recovered.toLowerCase() === expected.toLowerCase();\n } catch {\n return false;\n }\n}\n","/**\n * uvd-x402-sdk - Utilities\n *\n * Re-exports all utility functions.\n */\n\nexport {\n detectX402Version,\n paymentChallengeFrom,\n chainToCAIP2,\n caip2ToChain,\n parseNetworkIdentifier,\n encodeX402Header,\n decodeX402Header,\n createX402V1Header,\n createX402V2Header,\n createX402Header,\n generatePaymentOptions,\n isCAIP2Format,\n convertX402Header,\n} from './x402';\n\nexport { buildTokenMetadata } from './token-metadata';\n\nexport {\n encodeBase64Utf8,\n decodeBase64Utf8,\n encodeBase64Json,\n} from './base64';\n\nexport {\n validateRecipient,\n validateAmount,\n createPaymentHeaders,\n getPaymentHeader,\n DEFAULT_PAYMENT_HEADER,\n PAYMENT_HEADER_NAMES,\n} from './validation';\n\nexport {\n recoverPersonalSignAddress,\n verifyPersonalSign,\n} from './personal-sign';\n","/**\n * uvd-x402-sdk - SVM Provider (Solana Virtual Machine)\n *\n * Provides wallet connection and payment creation for SVM-based chains via Phantom.\n * Supports: Solana, Fogo\n * Uses partially-signed transactions where the facilitator is the fee payer.\n *\n * @example Solana\n * ```ts\n * import { SVMProvider } from 'uvd-x402-sdk/solana';\n * import { getChainByName } from 'uvd-x402-sdk';\n *\n * const svm = new SVMProvider();\n *\n * // Connect\n * const address = await svm.connect();\n *\n * // Create Solana payment\n * const chainConfig = getChainByName('solana')!;\n * const paymentPayload = await svm.signPayment(paymentInfo, chainConfig);\n * const header = svm.encodePaymentHeader(paymentPayload, chainConfig);\n * ```\n *\n * @example Fogo\n * ```ts\n * import { SVMProvider } from 'uvd-x402-sdk/solana';\n * import { getChainByName } from 'uvd-x402-sdk';\n *\n * const svm = new SVMProvider();\n *\n * // Connect (same wallet works for all SVM chains)\n * const address = await svm.connect();\n *\n * // Create Fogo payment\n * const chainConfig = getChainByName('fogo')!;\n * const paymentPayload = await svm.signPayment(paymentInfo, chainConfig);\n * const header = svm.encodePaymentHeader(paymentPayload, chainConfig);\n * ```\n */\n\nimport type {\n ChainConfig,\n PaymentInfo,\n SolanaPaymentPayload,\n TokenInfo,\n WalletAdapter,\n X402Version,\n} from '../../types';\nimport { X402Error } from '../../types';\nimport { getChainByName } from '../../chains';\nimport { chainToCAIP2, encodeBase64Json } from '../../utils';\n\n/**\n * Browser-compatible base64 encoding for Uint8Array\n * Avoids Node.js Buffer dependency for browser bundlers\n */\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\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// Lazy import Solana dependencies to avoid bundling when not used\nlet Connection: typeof import('@solana/web3.js').Connection;\nlet PublicKey: typeof import('@solana/web3.js').PublicKey;\nlet TransactionMessage: typeof import('@solana/web3.js').TransactionMessage;\nlet VersionedTransaction: typeof import('@solana/web3.js').VersionedTransaction;\nlet ComputeBudgetProgram: typeof import('@solana/web3.js').ComputeBudgetProgram;\nlet getAssociatedTokenAddress: typeof import('@solana/spl-token').getAssociatedTokenAddress;\nlet createTransferCheckedInstruction: typeof import('@solana/spl-token').createTransferCheckedInstruction;\nlet createAssociatedTokenAccountIdempotentInstruction: typeof import('@solana/spl-token').createAssociatedTokenAccountIdempotentInstruction;\nlet TOKEN_PROGRAM_ID: typeof import('@solana/spl-token').TOKEN_PROGRAM_ID;\n\nasync function loadSolanaDeps() {\n if (!Connection) {\n const web3 = await import('@solana/web3.js');\n const splToken = await import('@solana/spl-token');\n Connection = web3.Connection;\n PublicKey = web3.PublicKey;\n TransactionMessage = web3.TransactionMessage;\n VersionedTransaction = web3.VersionedTransaction;\n ComputeBudgetProgram = web3.ComputeBudgetProgram;\n getAssociatedTokenAddress = splToken.getAssociatedTokenAddress;\n createTransferCheckedInstruction = splToken.createTransferCheckedInstruction;\n createAssociatedTokenAccountIdempotentInstruction = splToken.createAssociatedTokenAccountIdempotentInstruction;\n TOKEN_PROGRAM_ID = splToken.TOKEN_PROGRAM_ID;\n }\n}\n\n/**\n * Phantom wallet provider interface\n */\ninterface PhantomProvider {\n isPhantom?: boolean;\n isConnected?: boolean;\n publicKey?: { toBase58(): string };\n connect(): Promise<{ publicKey: { toBase58(): string } }>;\n disconnect(): Promise<void>;\n signTransaction<T>(transaction: T): Promise<T>;\n}\n\n/**\n * SVMProvider - Wallet adapter for SVM chains (Solana, Fogo) via Phantom\n *\n * @alias SolanaProvider for backward compatibility\n */\nexport class SVMProvider implements WalletAdapter {\n readonly id = 'phantom';\n readonly name = 'Phantom';\n readonly networkType = 'svm' as const;\n\n private provider: PhantomProvider | null = null;\n private publicKey: InstanceType<typeof PublicKey> | null = null;\n private connections: Map<string, InstanceType<typeof Connection>> = new Map();\n private address: string | null = null;\n\n /**\n * Check if Phantom wallet is available\n */\n isAvailable(): boolean {\n if (typeof window === 'undefined') return false;\n return !!(\n (window as Window & { phantom?: { solana?: PhantomProvider } }).phantom?.solana?.isPhantom ||\n (window as Window & { solana?: PhantomProvider }).solana?.isPhantom\n );\n }\n\n /**\n * Connect to Phantom wallet\n */\n async connect(): Promise<string> {\n await loadSolanaDeps();\n\n // Get Phantom provider\n this.provider = await this.getPhantomProvider();\n if (!this.provider) {\n throw new X402Error(\n 'Phantom wallet not installed. Please install from phantom.app',\n 'WALLET_NOT_FOUND'\n );\n }\n\n try {\n // Check if already connected\n if (this.provider.publicKey && this.provider.isConnected) {\n const publicKeyString = this.provider.publicKey.toBase58();\n this.publicKey = new PublicKey(publicKeyString);\n this.address = publicKeyString;\n await this.initConnection();\n return publicKeyString;\n }\n\n // Connect\n const resp = await this.provider.connect();\n const publicKeyString = resp.publicKey.toBase58();\n\n this.publicKey = new PublicKey(publicKeyString);\n this.address = publicKeyString;\n\n await this.initConnection();\n\n return publicKeyString;\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || (error as { code?: number }).code === 4001) {\n throw new X402Error('Connection rejected by user', 'WALLET_CONNECTION_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to connect Phantom: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'UNKNOWN_ERROR',\n error\n );\n }\n }\n\n /**\n * Disconnect from Phantom\n */\n async disconnect(): Promise<void> {\n if (this.provider) {\n try {\n await this.provider.disconnect();\n } catch {\n // Ignore disconnect errors\n }\n }\n this.provider = null;\n this.publicKey = null;\n this.connections.clear();\n this.address = null;\n }\n\n /**\n * Get current address\n */\n getAddress(): string | null {\n return this.address;\n }\n\n /**\n * Get USDC balance\n */\n async getBalance(chainConfig: ChainConfig): Promise<string> {\n await loadSolanaDeps();\n\n if (!this.address) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n await this.initConnection(chainConfig);\n const connection = this.connections.get(chainConfig.name);\n if (!connection) {\n throw new X402Error('Failed to connect to Solana RPC', 'NETWORK_ERROR');\n }\n\n try {\n const response = await fetch(chainConfig.rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [\n this.address,\n { mint: chainConfig.usdc.address },\n { encoding: 'jsonParsed' },\n ],\n }),\n });\n\n const data = await response.json();\n\n if (!data.result?.value?.length) {\n return '0.00';\n }\n\n const tokenAccountInfo = data.result.value[0].account.data.parsed.info;\n const balance = Number(tokenAccountInfo.tokenAmount.amount) / Math.pow(10, tokenAccountInfo.tokenAmount.decimals);\n\n return balance.toFixed(2);\n } catch {\n return '0.00';\n }\n }\n\n /**\n * Create SVM payment (partially-signed transaction)\n *\n * Works for both Solana and Fogo chains.\n *\n * Transaction structure required by facilitator:\n * 1. SetComputeUnitLimit\n * 2. SetComputeUnitPrice\n * 3. (Optional) CreateAssociatedTokenAccount if recipient ATA doesn't exist\n * 4. TransferChecked (USDC transfer)\n *\n * Fee payer: Facilitator (not user)\n * User pays: ZERO SOL/FOGO\n */\n async signPayment(paymentInfo: PaymentInfo, chainConfig: ChainConfig): Promise<string> {\n await loadSolanaDeps();\n\n if (!this.provider || !this.publicKey || !this.address) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const connection = await this.getConnection(chainConfig);\n if (!connection) {\n throw new X402Error(`Failed to connect to ${chainConfig.displayName} RPC`, 'NETWORK_ERROR');\n }\n\n // Get recipient and facilitator addresses\n const recipient = paymentInfo.recipients?.solana || paymentInfo.recipient;\n const facilitatorAddress = paymentInfo.facilitator;\n\n if (!facilitatorAddress) {\n throw new X402Error('Facilitator address not provided', 'INVALID_CONFIG');\n }\n\n const recipientPubkey = new PublicKey(recipient);\n const facilitatorPubkey = new PublicKey(facilitatorAddress);\n const usdcMint = new PublicKey(chainConfig.usdc.address);\n\n // Parse amount (6 decimals for USDC)\n const amount = Math.floor(parseFloat(paymentInfo.amount) * 1_000_000);\n\n // Get token accounts\n const fromTokenAccount = await getAssociatedTokenAddress(\n usdcMint,\n this.publicKey,\n true,\n TOKEN_PROGRAM_ID\n );\n\n const toTokenAccount = await getAssociatedTokenAddress(\n usdcMint,\n recipientPubkey,\n true,\n TOKEN_PROGRAM_ID\n );\n\n // Check if recipient ATA exists\n const toTokenAccountInfo = await connection.getAccountInfo(toTokenAccount);\n const needsATACreation = toTokenAccountInfo === null;\n\n // Get recent blockhash\n const { blockhash } = await connection.getLatestBlockhash('finalized');\n\n // Build instructions in exact order required by facilitator\n const instructions = [];\n\n // Instruction 0: SetComputeUnitLimit\n instructions.push(\n ComputeBudgetProgram.setComputeUnitLimit({\n units: needsATACreation ? 50_000 : 20_000,\n })\n );\n\n // Instruction 1: SetComputeUnitPrice\n // Use 100k microlamports/CU for fast landing on mainnet\n // Lower values (like 1) cause transactions to be deprioritized and time out\n instructions.push(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: 100_000,\n })\n );\n\n // Instruction 2 (optional): CreateAssociatedTokenAccountIdempotent\n // User pays for ATA creation (not facilitator - security check in x402-rs)\n if (needsATACreation) {\n instructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n this.publicKey, // User pays for ATA creation\n toTokenAccount,\n recipientPubkey,\n usdcMint,\n TOKEN_PROGRAM_ID\n )\n );\n }\n\n // Instruction 2/3: TransferChecked\n instructions.push(\n createTransferCheckedInstruction(\n fromTokenAccount,\n usdcMint,\n toTokenAccount,\n this.publicKey,\n amount,\n 6,\n [],\n TOKEN_PROGRAM_ID\n )\n );\n\n // Build VersionedTransaction with facilitator as fee payer\n const messageV0 = new TransactionMessage({\n payerKey: facilitatorPubkey,\n recentBlockhash: blockhash,\n instructions,\n }).compileToV0Message();\n\n const transaction = new VersionedTransaction(messageV0);\n\n // User signs (partial signature - facilitator will co-sign)\n // IMPORTANT: Phantom may modify the transaction (add memo instruction).\n // We send the FULL signed transaction to the facilitator, which will use it\n // exactly as signed (not reconstruct it). This ensures signature validity.\n let signedTransaction: InstanceType<typeof VersionedTransaction>;\n try {\n signedTransaction = await this.provider.signTransaction(transaction);\n } catch (error: unknown) {\n if (error instanceof Error && error.message.includes('User rejected')) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\n }\n throw new X402Error(\n `Failed to sign transaction: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n // Serialize the FULL signed transaction (including any wallet modifications)\n // The facilitator will use this exact transaction, adding only its signature\n const serialized = signedTransaction.serialize();\n\n const payload: SolanaPaymentPayload = {\n transaction: uint8ArrayToBase64(serialized),\n };\n\n return JSON.stringify(payload);\n }\n\n /**\n * Encode SVM payment as X-PAYMENT header\n *\n * @param paymentPayload - JSON-encoded payment payload from signPayment()\n * @param chainConfig - Chain configuration (optional, defaults to 'solana')\n * @param version - x402 protocol version (1 or 2, defaults to 1)\n * @returns Base64-encoded X-PAYMENT header value\n */\n encodePaymentHeader(\n paymentPayload: string,\n chainConfig?: ChainConfig,\n version: X402Version = 1\n ): string {\n const payload = JSON.parse(paymentPayload) as SolanaPaymentPayload;\n\n // Use chain name from config, or default to 'solana' for backward compatibility\n const networkName = chainConfig?.name || 'solana';\n\n // Build the payload data - preserve token info for Token2022 (AUSD, etc.)\n const payloadData: { transaction: string; token?: TokenInfo } = {\n transaction: payload.transaction,\n };\n\n // CRITICAL: Preserve token info for non-USDC tokens (Token2022 like AUSD)\n // Without this, the facilitator cannot verify Token2022 transfers correctly\n if (payload.token) {\n payloadData.token = payload.token;\n }\n\n // Format in x402 standard format (v1 or v2)\n const x402Payload = version === 2\n ? {\n x402Version: 2 as const,\n scheme: 'exact' as const,\n network: chainToCAIP2(networkName), // CAIP-2 format for v2\n payload: payloadData,\n }\n : {\n x402Version: 1 as const,\n scheme: 'exact' as const,\n network: networkName, // Plain chain name for v1\n payload: payloadData,\n };\n\n return encodeBase64Json(x402Payload);\n }\n\n // Private helpers\n\n private async getPhantomProvider(): Promise<PhantomProvider | null> {\n if (typeof window === 'undefined') return null;\n\n // Try window.phantom.solana first\n const win = window as Window & {\n phantom?: { solana?: PhantomProvider };\n solana?: PhantomProvider;\n };\n\n if (win.phantom?.solana?.isPhantom) {\n return win.phantom.solana;\n }\n\n // Fallback to window.solana\n if (win.solana?.isPhantom) {\n return win.solana;\n }\n\n // Wait a bit for Phantom to inject itself\n for (let i = 0; i < 5; i++) {\n await new Promise(resolve => setTimeout(resolve, 100));\n if (win.phantom?.solana?.isPhantom) {\n return win.phantom.solana;\n }\n if (win.solana?.isPhantom) {\n return win.solana;\n }\n }\n\n return null;\n }\n\n /**\n * Get or create a connection for a specific chain\n *\n * IMPORTANT: Caches by RPC URL, not chain name. This allows consumers to\n * override the RPC URL (e.g., use Helius instead of public RPC) and get\n * a fresh connection with their custom RPC.\n */\n private async getConnection(chainConfig?: ChainConfig): Promise<InstanceType<typeof Connection>> {\n await loadSolanaDeps();\n\n const config = chainConfig || getChainByName('solana');\n if (!config) {\n throw new X402Error('Chain config not found', 'CHAIN_NOT_SUPPORTED');\n }\n\n // Cache by RPC URL, not chain name - allows custom RPC overrides\n const cacheKey = config.rpcUrl;\n\n // Check if we already have a connection for this RPC\n if (this.connections.has(cacheKey)) {\n return this.connections.get(cacheKey)!;\n }\n\n // Create new connection for this RPC\n const connection = new Connection(config.rpcUrl, 'confirmed');\n this.connections.set(cacheKey, connection);\n\n return connection;\n }\n\n /**\n * @deprecated Use getConnection instead\n */\n private async initConnection(chainConfig?: ChainConfig): Promise<void> {\n await this.getConnection(chainConfig);\n }\n}\n\n/**\n * @deprecated Use SVMProvider instead\n */\nexport class SolanaProvider extends SVMProvider {\n constructor() {\n super();\n console.warn('SolanaProvider is deprecated. Use SVMProvider instead.');\n }\n}\n\n// Default export\nexport default SVMProvider;\n","/**\n * uvd-x402-sdk - Main Client\n *\n * The X402Client is the primary entry point for the SDK.\n * It manages wallet connections, chain switching, and payment creation.\n */\n\nimport { ethers } from 'ethers';\nimport type {\n ChainConfig,\n NetworkType,\n PaymentInfo,\n PaymentResult,\n WalletState,\n X402ClientConfig,\n X402Event,\n X402EventData,\n X402EventHandler,\n EVMPaymentPayload,\n TokenType,\n X402EVMPayload,\n X402Version,\n X402PaymentOffer,\n X402FetchOptions,\n WalletAdapter,\n} from '../types';\nimport { X402Error, DEFAULT_CONFIG } from '../types';\nimport {\n PurchasePolicy,\n PolicyRefusedError,\n decideOnChallenge,\n noReadableOffer,\n canonicalRecipient,\n} from '../policy';\nimport type { PolicyApproval, ReadChallenge } from '../policy';\nimport {\n SUPPORTED_CHAINS,\n getChainByName,\n getChainById,\n getEnabledChains,\n getTokenConfig,\n} from '../chains';\nimport {\n validateRecipient,\n chainToCAIP2,\n caip2ToChain,\n encodeBase64Json,\n buildTokenMetadata,\n} from '../utils';\n\n/**\n * The x402 scheme vocabulary, shared by all three implementations.\n *\n * The same five the Rust facilitator's closed `Scheme` enum holds and the same\n * five the Python SDK keys `KNOWN_SCHEMES` on. A scheme outside this set is one\n * no implementation in the stack can name, so an entry carrying one is unreadable\n * and is counted by the name the seller used.\n *\n * Kept as a set of known NAMES rather than of payable ones because the two are\n * different questions, and conflating them is what rule 7 is about: naming what a\n * seller offered is how a caller learns to go find a facilitator that implements\n * it. See {@link CLIENT_PAYABLE_SCHEMES} for the other question.\n */\nexport const KNOWN_SCHEMES: ReadonlySet<string> = new Set([\n 'exact',\n 'upto',\n 'escrow',\n 'commerce',\n 'fhe-transfer',\n]);\n\n/**\n * Of those, the ones the BUYER path in this client can actually sign.\n *\n * One entry, and that is the point: the payload builder stamps\n * `scheme: 'exact'` into everything it produces, so `exact` is the only thing\n * this client can honestly present. `escrow` and `commerce` are implemented on\n * the SELLER side (`src/backend`) and in the pre-auth builder, and `upto` and\n * `fhe-transfer` are not implemented here at all.\n *\n * # Why this is a SECOND set and not a narrower first one\n *\n * `parse402` used to accept any entry carrying an amount, a payee and a network,\n * so a well-formed offer asking for a scheme this build cannot present was read\n * as payable and then **signed as `exact`** -- a payment offered to the seller\n * under a scheme it never asked for. Recognising a scheme is not being able to\n * pay it. Collapsing these two sets into one re-opens exactly that hole: widen\n * this one to the five known names and a well-formed `escrow` offer gets signed\n * as `exact` again.\n *\n * Both cases end the same way for the caller -- the entry is excluded and counted\n * by its scheme name -- and `no-readable-offer` says \"no offer in this challenge\n * is one this build **can pay**\", which is the frame both of them sit in.\n */\nexport const CLIENT_PAYABLE_SCHEMES: ReadonlySet<string> = new Set(['exact']);\n\n/**\n * X402Client - Main SDK client for x402 payments\n *\n * @example\n * ```ts\n * import { X402Client } from 'uvd-x402-sdk';\n *\n * const client = new X402Client({ defaultChain: 'base' });\n *\n * // Connect wallet\n * await client.connect('base');\n *\n * // Create payment\n * const result = await client.createPayment({\n * recipient: '0x...',\n * amount: '10.00',\n * });\n *\n * // Use result.paymentHeader in your API request\n * ```\n */\nexport class X402Client {\n // Configuration\n private readonly config: Required<Pick<X402ClientConfig, 'facilitatorUrl' | 'defaultChain' | 'autoConnect' | 'debug'>> & X402ClientConfig;\n\n // Wallet state\n private provider: ethers.BrowserProvider | ethers.JsonRpcProvider | null = null;\n private signer: ethers.Signer | null = null;\n private connectedAddress: string | null = null;\n private currentChainId: number | null = null;\n private currentNetwork: NetworkType | null = null;\n private currentChainName: string | null = null;\n /**\n * Non-EVM wallet, when one is connected. EVM keeps using `provider`/`signer`\n * because those are ethers-typed; every other network type talks through the\n * {@link WalletAdapter} contract instead.\n */\n private walletAdapter: WalletAdapter | null = null;\n\n // Event emitter\n private eventHandlers: Map<X402Event, Set<X402EventHandler<X402Event>>> = new Map();\n\n /**\n * What this buyer is allowed to sign, evaluated against the offer in hand\n * before anything is signed.\n *\n * `permissive()` when the caller supplied none, and that asymmetry is\n * deliberate: this SDK had no budget before 2.89.0, so switching one on\n * silently would refuse payments consumers are making today, while whoever\n * sits down to WRITE a policy gets the deny-by-default one.\n */\n private readonly purchasePolicy: PurchasePolicy;\n\n constructor(config: X402ClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n // Apply custom RPC overrides\n if (config.rpcOverrides) {\n for (const [chainName, rpcUrl] of Object.entries(config.rpcOverrides)) {\n if (SUPPORTED_CHAINS[chainName]) {\n SUPPORTED_CHAINS[chainName].rpcUrl = rpcUrl;\n }\n }\n }\n\n // Apply custom chain configurations\n if (config.customChains) {\n for (const [chainName, chainConfig] of Object.entries(config.customChains)) {\n if (SUPPORTED_CHAINS[chainName]) {\n Object.assign(SUPPORTED_CHAINS[chainName], chainConfig);\n }\n }\n }\n\n this.purchasePolicy = config.policy ?? PurchasePolicy.permissive();\n\n this.log('X402Client initialized', { config: this.config });\n }\n\n /**\n * The policy in force, for a caller that wants to record a settled payment\n * against it with {@link PurchasePolicy.recordSpend}.\n *\n * Nothing on the payment path ever widens it.\n */\n get policy(): PurchasePolicy {\n return this.purchasePolicy;\n }\n\n // ============================================================================\n // PUBLIC API - Wallet Connection\n // ============================================================================\n\n /**\n * Connect to a wallet on the specified chain\n */\n async connect(chainName?: string): Promise<string> {\n const targetChain = chainName || this.config.defaultChain;\n const chain = getChainByName(targetChain);\n\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (!chain.x402.enabled) {\n throw new X402Error(`Chain ${targetChain} is not enabled for x402 payments`, 'CHAIN_NOT_SUPPORTED');\n }\n\n this.log(`Connecting wallet on ${chain.displayName}...`);\n\n // Route to appropriate connection method based on network type\n switch (chain.networkType) {\n case 'evm':\n return this.connectEVMWallet(chain);\n case 'svm':\n // The registry says 'svm' for Solana and Fogo; this used to read\n // `case 'solana'`, which no chain has ever carried, so every SVM\n // caller fell through to `default:`. `NetworkType` allows both\n // spellings, so the compiler never caught it.\n return this.connectSVMWallet(chain);\n case 'stellar':\n throw new X402Error(\n 'Stellar support requires importing from \"uvd-x402-sdk/stellar\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n case 'near':\n throw new X402Error(\n 'NEAR support requires importing from \"uvd-x402-sdk/near\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n case 'xrpl':\n throw new X402Error(\n 'XRPL support requires importing from \"uvd-x402-sdk/xrpl\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n default:\n throw new X402Error(`Unknown network type for chain ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n }\n\n /**\n * Connect using a private key (Node.js / server-side, no browser wallet needed)\n */\n async connectWithPrivateKey(privateKey: string, chainName?: string): Promise<string> {\n const targetChain = chainName || this.config.defaultChain;\n const chain = getChainByName(targetChain);\n\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (!chain.x402.enabled) {\n throw new X402Error(`Chain ${targetChain} is not enabled for x402 payments`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error('connectWithPrivateKey is only supported for EVM chains', 'CHAIN_NOT_SUPPORTED');\n }\n\n this.log(`Connecting with private key on ${chain.displayName}...`);\n\n const rpcProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n const wallet = new ethers.Wallet(privateKey, rpcProvider);\n\n this.provider = rpcProvider;\n this.signer = wallet;\n this.connectedAddress = wallet.address;\n this.currentChainId = chain.chainId;\n this.currentNetwork = 'evm';\n this.currentChainName = chain.name;\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('Private key wallet connected', { address: this.connectedAddress, chain: chain.name });\n\n return this.connectedAddress;\n }\n\n /**\n * Disconnect the current wallet\n */\n async disconnect(): Promise<void> {\n if (this.walletAdapter) {\n try {\n await this.walletAdapter.disconnect();\n } catch {\n // A wallet that is already gone must not block local teardown.\n }\n this.walletAdapter = null;\n }\n this.provider = null;\n this.signer = null;\n this.connectedAddress = null;\n this.currentChainId = null;\n this.currentNetwork = null;\n this.currentChainName = null;\n\n this.emit('disconnect', undefined);\n this.log('Wallet disconnected');\n }\n\n /**\n * Switch to a different chain (EVM only)\n */\n async switchChain(chainName: string): Promise<void> {\n const chain = getChainByName(chainName);\n\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 'switchChain is only supported for EVM networks. Reconnect with connect() for other networks.',\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n if (!this.provider) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n // Private key connections cannot use wallet_switchEthereumChain — re-create provider\n if (this.provider instanceof ethers.JsonRpcProvider && this.signer instanceof ethers.Wallet) {\n const rpcProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n const wallet = new ethers.Wallet(this.signer.privateKey, rpcProvider);\n this.provider = rpcProvider;\n this.signer = wallet;\n this.currentChainId = chain.chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId: chain.chainId, chainName: chain.name });\n this.log('Switched chain (private key mode)', { chain: chain.name });\n return;\n }\n\n await this.switchEVMChain(chain);\n }\n\n // ============================================================================\n // PUBLIC API - Payment Creation\n // ============================================================================\n\n /**\n * Create a payment authorization\n *\n * @param paymentInfo - Payment information from 402 response\n * @returns Payment result with encoded X-PAYMENT header\n */\n async createPayment(paymentInfo: PaymentInfo): Promise<PaymentResult> {\n if (!this.connectedAddress) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n if (!this.currentChainName) {\n throw new X402Error('Chain not set', 'CHAIN_NOT_SUPPORTED');\n }\n\n const chain = getChainByName(this.currentChainName);\n if (!chain) {\n throw new X402Error(`Chain ${this.currentChainName} not found`, 'CHAIN_NOT_SUPPORTED');\n }\n\n this.emit('paymentStarted', { amount: paymentInfo.amount, network: chain.name });\n this.log('Creating payment...', { paymentInfo, chain: chain.name });\n\n try {\n // Route to appropriate payment method\n switch (chain.networkType) {\n case 'evm':\n return await this.createEVMPayment(paymentInfo, chain);\n default:\n if (this.walletAdapter?.networkType === chain.networkType) {\n return await this.createAdapterPayment(paymentInfo, chain);\n }\n throw new X402Error(\n `Payment creation for ${chain.networkType} requires the appropriate provider`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n } catch (error) {\n const x402Error = error instanceof X402Error\n ? error\n : new X402Error(\n error instanceof Error ? error.message : 'Unknown error',\n 'PAYMENT_FAILED',\n error\n );\n\n this.emit('paymentFailed', { error: x402Error.message, code: x402Error.code });\n throw x402Error;\n }\n }\n\n\n // ============================================================================\n // PUBLIC API - Buyer loop\n // ============================================================================\n\n /**\n * Fetch a resource, paying its `402 Payment Required` challenge if it has one.\n *\n * The BUYER side of x402, and the half this client was missing: it could sign\n * a payment ({@link createPayment}) but never ask for one, so every consumer\n * hand-rolled the same loop -- probe, read `accepts`, pick, sign, retry --\n * and each one picked its own answer to \"how much is too much\".\n *\n * Safe by default: `maxAmount` is a hard ceiling. A 402 that asks for more\n * throws `PAYMENT_EXCEEDS_MAX` instead of quietly signing it. A response that\n * is not a 402 -- a first-try 200 included -- comes back untouched; this pays\n * only when payment is what was asked for.\n *\n * @param url - Resource URL.\n * @param options - See {@link X402FetchOptions}.\n * @returns The paid response after a 402, or the original response.\n *\n * @example\n * ```ts\n * await client.connectWithPrivateKey(key, 'base');\n * const res = await client.fetch('https://api.example.com/data', {\n * maxAmount: '0.05',\n * });\n * const data = await res.json();\n * ```\n */\n async fetch(url: string, options: X402FetchOptions = {}): Promise<Response> {\n if (!this.connectedAddress) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const method = options.method || 'GET';\n const doFetch = options.fetchImpl || globalThis.fetch;\n if (typeof doFetch !== 'function') {\n throw new X402Error(\n 'No fetch implementation available; pass options.fetchImpl',\n 'NETWORK_ERROR'\n );\n }\n\n const probe = await doFetch(url, { ...options.init, method });\n if (probe.status !== 402) {\n return probe;\n }\n\n let body: unknown;\n try {\n body = await probe.json();\n } catch (error) {\n throw new X402Error(\n `402 response body is not JSON: ${error instanceof Error ? error.message : 'unknown'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n const tokenType: TokenType = options.tokenType || 'usdc';\n const challenge = this.parse402(body, tokenType);\n const { version, offers } = challenge;\n if (offers.length === 0) {\n // Step 1 of the policy contract, and two different facts that used to be\n // one error. A seller that sent offers none of which this build can read is\n // asking for a scheme we do not implement; saying so names what it wanted,\n // where \"no usable payment options\" sends the caller hunting a bug in its\n // own code. A seller that sent none at all is the other fact, and keeps the\n // error it always had.\n const unreadableCount = challenge.unreadableCount ?? challenge.unreadable.length;\n if (unreadableCount > 0) {\n throw new PolicyRefusedError(noReadableOffer(challenge.unreadable));\n }\n throw new X402Error(\n '402 response offered no usable payment options',\n 'NO_ACCEPTABLE_PAYMENT'\n );\n }\n\n // The ceiling is deliberately NOT applied while selecting: if even the\n // cheapest offer is over budget the caller wants to be told the price, not\n // handed a vague \"nothing acceptable\".\n const chosen = options.select\n ? options.select(offers)\n : X402Client.cheapestOffer(offers);\n if (!chosen) {\n throw new X402Error(\n 'No payment option selected for the 402 challenge',\n 'NO_ACCEPTABLE_PAYMENT'\n );\n }\n\n if (options.maxAmount !== undefined) {\n const ceiling = ethers.parseUnits(options.maxAmount, chosen.decimals);\n if (BigInt(chosen.amount) > ceiling) {\n throw new X402Error(\n `Payment of ${ethers.formatUnits(chosen.amount, chosen.decimals)} exceeds ` +\n `maxAmount ${options.maxAmount} for ${url}`,\n 'PAYMENT_EXCEEDS_MAX',\n {\n amount: chosen.amount,\n decimals: chosen.decimals,\n maxAmount: options.maxAmount,\n }\n );\n }\n }\n\n // The policy, evaluated against THIS offer, before anything is signed. An\n // offer that diverges from a listing but sits inside an authorised policy\n // proceeds -- stopping to ask would turn every ordinary reprice into a halt --\n // and one that does not is refused with a concrete cause. The policy is never\n // widened to fit the offer, and there is no confirmation hook in this path.\n //\n // The whole challenge goes in, never just the offer: `validUntil` lives in\n // the challenge's `extensions`, and a call that takes the parts is how it gets\n // dropped.\n const decision = decideOnChallenge(this.purchasePolicy, challenge, chosen, {\n now: Math.floor(Date.now() / 1000),\n quote: options.advertised,\n });\n if (!decision.ok) {\n this.log('policy refused this offer', { cause: decision.refusal.code });\n this.emit('paymentFailed', {\n error: decision.refusal.message,\n code: 'POLICY_REFUSED',\n });\n throw new PolicyRefusedError(decision.refusal);\n }\n const approval: PolicyApproval = decision.approval;\n this.log('policy approved this offer', {\n versusQuote: approval.versusQuote.code,\n amount: String(approval.amount),\n });\n\n if (!chosen.chainName) {\n throw new X402Error(\n `402 asked for payment on unknown network '${chosen.network}'`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n // The policy just approved the offer's OWN asset, but `createPayment` signs\n // for whatever token `tokenType` resolves to on this chain -- and reads the\n // price at that token's decimals. With USDC on both sides they coincide,\n // which is why this never showed. They do not have to: a seller pricing in a\n // token that is not the configured one would get an approval for asset A and\n // a signature for asset B, at B's decimals, and the caller would believe a\n // budget it never actually enforced.\n //\n // Refused rather than silently re-pointed: which token to pay with is the\n // caller's decision, and guessing it from the seller's 402 is how a wallet\n // ends up signing for a token nobody chose.\n const configuredToken = getTokenConfig(chosen.chainName, tokenType);\n if (\n chosen.asset &&\n configuredToken &&\n canonicalRecipient(configuredToken.address) !== canonicalRecipient(chosen.asset)\n ) {\n throw new X402Error(\n `402 wants ${chosen.asset} on ${chosen.chainName}, but this client signs ` +\n `${configuredToken.address} (tokenType '${tokenType}'). Pass the tokenType ` +\n 'that matches the offer; signing the configured token would pay a ' +\n 'different asset than the one that was approved.',\n 'NO_ACCEPTABLE_PAYMENT',\n {\n offered: chosen.asset,\n wouldSign: configuredToken.address,\n tokenType,\n network: chosen.chainName,\n }\n );\n }\n\n if (chosen.chainName !== this.currentChainName) {\n await this.switchChain(chosen.chainName);\n }\n\n const payment = await this.createPayment({\n recipient: chosen.payTo,\n amount: ethers.formatUnits(chosen.amount, chosen.decimals),\n tokenType,\n network: chosen.chainName,\n x402Version: version,\n });\n\n // v1 servers read `X-PAYMENT`; v2 ones read `PAYMENT-SIGNATURE`. Both carry\n // the identical base64 payload, so sending both on a v2 retry costs nothing\n // and spares the caller from guessing which name the resource implemented.\n const paidHeaders: Record<string, string> = {\n ...X402Client.headersToRecord(options.init?.headers),\n 'X-PAYMENT': payment.paymentHeader,\n };\n if (version === 2) {\n paidHeaders['PAYMENT-SIGNATURE'] = payment.paymentHeader;\n }\n\n const paid = await doFetch(url, { ...options.init, method, headers: paidHeaders });\n\n // Approving did not spend: signing can fail and a settlement can be refused,\n // and a cumulative limit that counted attempts would lock a caller out of\n // money it never spent. A retry that came back as anything but another 402 is\n // the seller accepting the payment, which is the moment a caller records it --\n // by its own hand, in `onPaid`, never automatically here.\n if (paid.status !== 402) {\n options.onPaid?.(approval);\n }\n return paid;\n }\n\n /**\n * Normalise a 402 body into its envelope version, its payment offers, the ones\n * it could not read, and the challenge's `extensions`.\n *\n * Reads both spec shapes -- `{x402Version, accepts: [...]}` and the non-spec\n * one where a lone requirement sits at the top level -- and both dialects of\n * the price field (`maxAmountRequired` in v1, `amount` in v2).\n *\n * **`accepts` is a list, so one unreadable entry does not sink the list.** A\n * seller offering `exact` alongside a scheme this build does not implement used\n * to be unpayable in the Rust crate, and the buyer never learned there was a\n * perfectly payable offer right there. The readable ones are kept and the\n * others are counted by scheme name, so a refusal can say what the seller\n * offered instead of \"could not parse\". Discovering the service keeps working\n * even when buying it automatically does not.\n *\n * Returns the WHOLE challenge on purpose: handing `offers` alone downstream is\n * what dropped the seller's `validUntil` on the floor in Rust for a full commit\n * with every unit test green.\n */\n private parse402(\n body: unknown,\n tokenType: TokenType\n ): ReadChallenge & { version: X402Version } {\n const doc = (body ?? {}) as Record<string, unknown>;\n const version: X402Version = Number(doc.x402Version) === 2 ? 2 : 1;\n\n const rawAccepts = Array.isArray(doc.accepts)\n ? doc.accepts\n : doc.payTo\n ? [doc]\n : [];\n\n const offers: X402PaymentOffer[] = [];\n const unreadable: string[] = [];\n let unreadableCount = 0;\n\n /** Count an entry this build cannot pay, by scheme name when it has one. */\n const cannotRead = (accept: Record<string, unknown> | null) => {\n unreadableCount += 1;\n const scheme = accept?.scheme;\n if (typeof scheme === 'string' && scheme) unreadable.push(scheme);\n };\n\n for (const entry of rawAccepts) {\n if (!entry || typeof entry !== 'object') {\n cannotRead(null);\n continue;\n }\n const accept = entry as Record<string, unknown>;\n\n // The scheme first, so a well-formed offer in a scheme we cannot pay is\n // counted by the NAME the seller used -- the informative half of rule 7 --\n // instead of being reported for whichever field it also happened to omit.\n //\n // An ABSENT scheme is unreadable, not `exact`. Rust requires the field, so a\n // challenge without it fails to deserialise there, and a buyer that guessed\n // `exact` would sign under a scheme the seller never actually named -- which\n // is the same hole as signing a named one we cannot present, minus the\n // evidence. It is counted (`unreadableCount`) without a name, because it has\n // none to report.\n //\n // Note this is deliberately ASYMMETRIC with the seller side of this SDK,\n // where a missing scheme reads as `exact` (\"the default, not an override\",\n // `src/backend/index.ts`). A seller is lenient about what it accepts; a\n // buyer is strict about what it signs.\n const declaredScheme = accept.scheme;\n if (\n typeof declaredScheme !== 'string' ||\n !declaredScheme ||\n !KNOWN_SCHEMES.has(declaredScheme) ||\n !CLIENT_PAYABLE_SCHEMES.has(declaredScheme)\n ) {\n cannotRead(accept);\n continue;\n }\n\n const amount = accept.amount ?? accept.maxAmountRequired;\n const payTo = accept.payTo;\n const network = accept.network;\n if (amount === undefined || amount === null) {\n cannotRead(accept);\n continue;\n }\n if (typeof payTo !== 'string' || !payTo) {\n cannotRead(accept);\n continue;\n }\n if (typeof network !== 'string' || !network) {\n cannotRead(accept);\n continue;\n }\n\n const chainName = getChainByName(network) ? network : caip2ToChain(network);\n\n offers.push({\n network,\n chainName,\n asset: typeof accept.asset === 'string' ? accept.asset : undefined,\n amount: String(amount),\n decimals: X402Client.offerDecimals(chainName, tokenType),\n payTo,\n raw: accept,\n });\n }\n\n const extensions =\n doc.extensions && typeof doc.extensions === 'object' && !Array.isArray(doc.extensions)\n ? (doc.extensions as Record<string, unknown>)\n : undefined;\n\n return { version, offers, unreadable, unreadableCount, extensions };\n }\n\n /**\n * Decimals to read an offer's atomic `amount` with.\n *\n * Not cosmetic: BSC USDC has 18 and everyone else's has 6, so reading every\n * price at 6 makes one chain look 10^12 times cheaper than it is and the\n * cheapest offer gets chosen wrong. Falls back to 6 only when the chain is\n * unknown -- and an unknown chain cannot be paid anyway.\n */\n private static offerDecimals(chainName: string | null, tokenType: TokenType): number {\n if (!chainName) return 6;\n const token = getTokenConfig(chainName, tokenType);\n if (token) return token.decimals;\n return getChainByName(chainName)?.usdc.decimals ?? 6;\n }\n\n /** Cheapest offer, compared across chains at a common scale. */\n private static cheapestOffer(offers: X402PaymentOffer[]): X402PaymentOffer {\n return offers.reduce((best, offer) =>\n X402Client.scaled(offer) < X402Client.scaled(best) ? offer : best\n );\n }\n\n /** An offer's price scaled to 18 decimals, so BigInt comparison is exact. */\n private static scaled(offer: X402PaymentOffer): bigint {\n const exponent = 18 - offer.decimals;\n const value = BigInt(offer.amount);\n return exponent >= 0\n ? value * 10n ** BigInt(exponent)\n : value / 10n ** BigInt(-exponent);\n }\n\n /** Flatten whatever `HeadersInit` shape the caller passed into a record. */\n private static headersToRecord(init?: HeadersInit): Record<string, string> {\n if (!init) return {};\n if (Array.isArray(init)) return Object.fromEntries(init);\n const maybeHeaders = init as Headers;\n if (typeof maybeHeaders.forEach === 'function') {\n const out: Record<string, string> = {};\n maybeHeaders.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n }\n return { ...(init as Record<string, string>) };\n }\n\n /**\n * Check USDC balance on current chain\n */\n async getBalance(): Promise<string> {\n if (!this.connectedAddress || !this.currentChainName) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const chain = getChainByName(this.currentChainName);\n if (!chain) {\n throw new X402Error(`Chain ${this.currentChainName} not found`, 'CHAIN_NOT_SUPPORTED');\n }\n\n switch (chain.networkType) {\n case 'evm':\n return this.getEVMBalance(chain);\n default:\n if (this.walletAdapter?.networkType === chain.networkType) {\n return this.walletAdapter.getBalance(chain);\n }\n throw new X402Error(\n `Balance check for ${chain.networkType} requires the appropriate provider`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n }\n\n // ============================================================================\n // PUBLIC API - Getters\n // ============================================================================\n\n /**\n * Get current wallet state\n */\n getState(): WalletState {\n return {\n connected: this.connectedAddress !== null,\n address: this.connectedAddress,\n chainId: this.currentChainId,\n network: this.currentChainName,\n networkType: this.currentNetwork,\n balance: null, // Call getBalance() separately\n };\n }\n\n /**\n * Get connected wallet address\n */\n getAddress(): string | null {\n return this.connectedAddress;\n }\n\n /**\n * Get current chain ID\n */\n getChainId(): number | null {\n return this.currentChainId;\n }\n\n /**\n * Get current chain name\n */\n getChainName(): string | null {\n return this.currentChainName;\n }\n\n /**\n * Get current chain display name\n */\n getChainDisplayName(): string | null {\n if (!this.currentChainName) return null;\n const chain = getChainByName(this.currentChainName);\n return chain?.displayName ?? null;\n }\n\n /**\n * Check if wallet is connected\n */\n isConnected(): boolean {\n return this.connectedAddress !== null;\n }\n\n /**\n * Get list of enabled chains\n */\n getEnabledChains(): ChainConfig[] {\n return getEnabledChains();\n }\n\n /**\n * Get chain config by name\n */\n getChain(name: string): ChainConfig | undefined {\n return getChainByName(name);\n }\n\n // ============================================================================\n // PUBLIC API - Events\n // ============================================================================\n\n /**\n * Subscribe to an event\n */\n on<E extends X402Event>(event: E, handler: X402EventHandler<E>): () => void {\n if (!this.eventHandlers.has(event)) {\n this.eventHandlers.set(event, new Set());\n }\n this.eventHandlers.get(event)!.add(handler as X402EventHandler<X402Event>);\n\n // Return unsubscribe function\n return () => this.off(event, handler);\n }\n\n /**\n * Unsubscribe from an event\n */\n off<E extends X402Event>(event: E, handler: X402EventHandler<E>): void {\n this.eventHandlers.get(event)?.delete(handler as X402EventHandler<X402Event>);\n }\n\n // ============================================================================\n // PRIVATE - EVM Wallet Connection\n // ============================================================================\n\n /**\n * Connect an SVM chain (Solana, Fogo) through the Phantom-backed provider.\n *\n * The provider is imported lazily: `@solana/web3.js` and `@solana/spl-token`\n * are OPTIONAL peer dependencies, so an EVM-only consumer must never pay for\n * them at module load. They are resolved only once someone actually asks for\n * an SVM chain.\n */\n private async connectSVMWallet(chain: ChainConfig): Promise<string> {\n const { SVMProvider } = await import('../providers/solana');\n const adapter = new SVMProvider();\n\n // SVMProvider.connect() takes no chain: one Phantom session serves every\n // SVM chain, and the chain is passed per call via chainConfig.\n const address = await adapter.connect();\n\n this.walletAdapter = adapter;\n this.provider = null;\n this.signer = null;\n this.connectedAddress = address;\n this.currentChainId = chain.chainId;\n this.currentNetwork = chain.networkType;\n this.currentChainName = chain.name;\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('SVM wallet connected', { address, chain: chain.name });\n\n return address;\n }\n\n private async connectEVMWallet(chain: ChainConfig): Promise<string> {\n // Check for injected provider\n if (typeof window === 'undefined' || !window.ethereum) {\n throw new X402Error(\n 'No Ethereum wallet found. Please install MetaMask or another EVM wallet.',\n 'WALLET_NOT_FOUND'\n );\n }\n\n try {\n this.provider = new ethers.BrowserProvider(window.ethereum);\n\n // Request account access\n await this.provider.send('eth_requestAccounts', []);\n\n // Switch to target chain\n await this.switchEVMChain(chain);\n\n // Get signer and address\n this.signer = await this.provider.getSigner();\n this.connectedAddress = await this.signer.getAddress();\n this.currentChainId = chain.chainId;\n this.currentNetwork = 'evm';\n this.currentChainName = chain.name;\n\n // Setup event listeners\n this.setupEVMEventListeners();\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('EVM wallet connected', { address: this.connectedAddress, chain: chain.name });\n\n return this.connectedAddress;\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || (error as { code?: number }).code === 4001) {\n throw new X402Error('Connection rejected by user', 'WALLET_CONNECTION_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to connect wallet: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'UNKNOWN_ERROR',\n error\n );\n }\n }\n\n private async switchEVMChain(chain: ChainConfig): Promise<void> {\n if (!this.provider) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n try {\n await this.provider.send('wallet_switchEthereumChain', [{ chainId: chain.chainIdHex }]);\n } catch (switchError: unknown) {\n // Chain not added - try to add it\n if ((switchError as { code?: number }).code === 4902) {\n try {\n await this.provider.send('wallet_addEthereumChain', [\n {\n chainId: chain.chainIdHex,\n chainName: chain.displayName,\n nativeCurrency: chain.nativeCurrency,\n rpcUrls: [chain.rpcUrl],\n blockExplorerUrls: [chain.explorerUrl],\n },\n ]);\n } catch (addError) {\n throw new X402Error(\n `Failed to add ${chain.displayName} network`,\n 'CHAIN_SWITCH_REJECTED',\n addError\n );\n }\n } else if ((switchError as { code?: number }).code === 4001) {\n throw new X402Error('Network switch rejected by user', 'CHAIN_SWITCH_REJECTED');\n } else {\n throw new X402Error(\n `Failed to switch to ${chain.displayName}`,\n 'CHAIN_SWITCH_REJECTED',\n switchError\n );\n }\n }\n\n this.currentChainId = chain.chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId: chain.chainId, chainName: chain.name });\n }\n\n private setupEVMEventListeners(): void {\n if (typeof window === 'undefined' || !window.ethereum) return;\n\n window.ethereum.on?.('accountsChanged', ((...args: unknown[]) => {\n const accounts = args[0] as string[];\n if (accounts.length === 0) {\n this.disconnect();\n } else if (accounts[0] !== this.connectedAddress) {\n this.connectedAddress = accounts[0];\n this.emit('accountChanged', { address: accounts[0] });\n }\n }) as (...args: unknown[]) => void);\n\n window.ethereum.on?.('chainChanged', ((...args: unknown[]) => {\n const chainIdHex = args[0] as string;\n const chainId = parseInt(chainIdHex, 16);\n const chain = getChainById(chainId);\n if (chain) {\n this.currentChainId = chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId, chainName: chain.name });\n }\n }) as (...args: unknown[]) => void);\n }\n\n // ============================================================================\n // PRIVATE - EVM Payment Creation\n // ============================================================================\n\n private async createEVMPayment(paymentInfo: PaymentInfo, chain: ChainConfig): Promise<PaymentResult> {\n if (!this.signer) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n // Get recipient address for EVM\n const recipient = this.getRecipientForNetwork(paymentInfo, 'evm');\n\n // Validate recipient address - prevents empty/invalid addresses\n validateRecipient(recipient, 'evm');\n\n // Which stablecoin to charge. Defaults to USDC so existing callers are\n // unaffected; anything else is resolved from the chain's token registry.\n const tokenType: TokenType = paymentInfo.tokenType || 'usdc';\n const token = getTokenConfig(chain.name, tokenType);\n if (!token) {\n throw new X402Error(\n `Token ${tokenType} not supported on ${chain.name}`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n // Generate random nonce\n const nonceBytes = new Uint8Array(32);\n if (typeof window !== 'undefined' && window.crypto) {\n window.crypto.getRandomValues(nonceBytes);\n } else {\n for (let i = 0; i < 32; i++) {\n nonceBytes[i] = Math.floor(Math.random() * 256);\n }\n }\n const nonce = ethers.hexlify(nonceBytes);\n\n // Set validity window (5 minutes for congested networks, 1 minute otherwise)\n const validAfter = 0;\n const validityWindowSeconds = chain.name === 'base' ? 300 : 60;\n const validBefore = Math.floor(Date.now() / 1000) + validityWindowSeconds;\n\n // EIP-712 domain of the token being charged\n const domain = {\n name: token.name,\n version: token.version,\n chainId: chain.chainId,\n verifyingContract: token.address,\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 // Parse amount in the token's own decimals\n const value = ethers.parseUnits(paymentInfo.amount, token.decimals);\n const from = await this.signer.getAddress();\n const to = ethers.getAddress(recipient);\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter,\n validBefore,\n nonce,\n };\n\n this.log('Signing EIP-712 message...', { domain, message });\n\n // Sign the EIP-712 message\n let signature: string;\n try {\n signature = await this.signer.signTypedData(domain, types, message);\n } catch (error: unknown) {\n if (error instanceof Error && (error.message.includes('User rejected') || (error as { code?: number }).code === 4001)) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\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 const sig = ethers.Signature.from(signature);\n\n // Construct payload\n const payload: EVMPaymentPayload = {\n from,\n to,\n value: value.toString(),\n validAfter,\n validBefore,\n nonce,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n chainId: chain.chainId,\n token: token.address,\n };\n\n // Encode as X-PAYMENT header. The 402 wins over the config when it spoke:\n // `x402Version: 'auto'` means \"whatever the resource asked for\".\n const paymentHeader = this.encodeEVMPaymentHeader(\n payload,\n chain,\n paymentInfo.x402Version\n );\n\n this.emit('paymentSigned', { paymentHeader });\n\n const result: PaymentResult = {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: chain.name,\n payer: from,\n };\n\n this.emit('paymentCompleted', result);\n this.log('Payment created successfully', { network: chain.name, from });\n\n return result;\n }\n\n /**\n * Build a payment through a non-EVM {@link WalletAdapter}.\n *\n * The adapter signs and returns its own payload; encoding that payload into\n * the X-PAYMENT header is network-specific, so it stays with the provider\n * that produced it. Version resolution matches the EVM path exactly: a hint\n * read off the resource's own 402 wins over the client config.\n */\n private async createAdapterPayment(\n paymentInfo: PaymentInfo,\n chain: ChainConfig\n ): Promise<PaymentResult> {\n const adapter = this.walletAdapter;\n if (!adapter) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const encode = (adapter as { encodePaymentHeader?: (p: string, c: ChainConfig, v: X402Version) => string })\n .encodePaymentHeader;\n if (typeof encode !== 'function') {\n throw new X402Error(\n `The ${adapter.name} adapter cannot encode an X-PAYMENT header`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n const signed = await adapter.signPayment(paymentInfo, chain);\n const version = paymentInfo.x402Version ?? (this.config.x402Version === 2 ? 2 : 1);\n const paymentHeader = encode.call(adapter, signed, chain, version);\n\n this.emit('paymentSigned', { paymentHeader });\n\n const result: PaymentResult = {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: chain.name,\n payer: adapter.getAddress() ?? undefined,\n };\n\n this.emit('paymentCompleted', result);\n this.log('Payment created successfully', { network: chain.name, adapter: adapter.name });\n\n return result;\n }\n\n private encodeEVMPaymentHeader(\n payload: EVMPaymentPayload,\n chain: ChainConfig,\n versionHint?: X402Version\n ): string {\n // Reconstruct full signature from v, r, s\n const fullSignature = payload.r + payload.s.slice(2) + payload.v.toString(16).padStart(2, '0');\n\n // Determine version to use. A hint read off the resource's own 402 wins;\n // with no hint we fall back to the config (default v1 for compatibility).\n const version = versionHint ?? (this.config.x402Version === 2 ? 2 : 1);\n\n // Build the payload data\n const payloadData: X402EVMPayload = {\n signature: fullSignature,\n authorization: {\n from: payload.from,\n to: payload.to,\n value: payload.value,\n validAfter: payload.validAfter.toString(),\n validBefore: payload.validBefore.toString(),\n nonce: payload.nonce,\n },\n };\n\n if (this.config.includeTokenMetadata) {\n const token = buildTokenMetadata(chain.name, payload.token);\n if (!token) {\n throw new X402Error(\n `Token ${payload.token} is not in the registry for ${chain.name}; cannot build token metadata`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n payloadData.token = token;\n }\n\n // Format in x402 standard format (v1 or v2)\n const x402Payload = version === 2\n ? {\n x402Version: 2 as const,\n scheme: 'exact' as const,\n network: chainToCAIP2(chain.name), // CAIP-2 format for v2\n payload: payloadData,\n }\n : {\n x402Version: 1 as const,\n scheme: 'exact' as const,\n network: chain.name, // Plain chain name for v1\n payload: payloadData,\n };\n\n // Base64 encode (UTF-8 safe: token domain names like `USD₮0` are not ASCII)\n return encodeBase64Json(x402Payload);\n }\n\n // ============================================================================\n // PRIVATE - EVM Balance Check\n // ============================================================================\n\n private async getEVMBalance(chain: ChainConfig): Promise<string> {\n // Use public RPC for balance check (more reliable than wallet provider)\n const publicProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n\n const usdcAbi = ['function balanceOf(address owner) view returns (uint256)'];\n const usdcContract = new ethers.Contract(chain.usdc.address, usdcAbi, publicProvider);\n\n try {\n const balance = await usdcContract.balanceOf(this.connectedAddress);\n const formatted = ethers.formatUnits(balance, chain.usdc.decimals);\n return parseFloat(formatted).toFixed(2);\n } catch {\n return '0.00';\n }\n }\n\n // ============================================================================\n // PRIVATE - Utilities\n // ============================================================================\n\n private getRecipientForNetwork(paymentInfo: PaymentInfo, network: NetworkType): string {\n // Map SVM to solana for recipient lookup\n const lookupNetwork = network === 'svm' ? 'solana' : network;\n const recipients = paymentInfo.recipients as Record<string, string> | undefined;\n if (recipients?.[lookupNetwork]) {\n return recipients[lookupNetwork];\n }\n return paymentInfo.recipient;\n }\n\n private emit<E extends X402Event>(event: E, data: X402EventData[E]): void {\n this.eventHandlers.get(event)?.forEach(handler => {\n try {\n handler(data);\n } catch (error) {\n console.error(`Error in ${event} handler:`, error);\n }\n });\n }\n\n private log(message: string, data?: unknown): void {\n if (this.config.debug) {\n console.log(`[X402Client] ${message}`, data ?? '');\n }\n }\n}\n\n// Type augmentation for window.ethereum\ndeclare global {\n interface Window {\n ethereum?: {\n request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;\n on?: (event: string, handler: (...args: unknown[]) => void) => void;\n removeListener?: (event: string, handler: (...args: unknown[]) => void) => void;\n };\n }\n}\n","/**\n * uvd-x402-sdk - What this buyer is allowed to sign, decided before it signs.\n *\n * # The rule this module exists to enforce\n *\n * A catalog listing is a claim somebody else made about their own price. The\n * `402` that comes back from the actual request is the offer. They can differ,\n * legitimately: a seller may have repriced, and the listing may be a copy of a\n * copy. So the buying decision cannot be made against the listing. It has to be\n * made against **the offer in hand**, every time, before anything is signed.\n *\n * Two things follow, and both are load-bearing:\n *\n * - **A divergence from the listing is not, by itself, a refusal.** If the offer\n * costs more than the catalog said but still sits inside a policy the operator\n * already authorised, the payment proceeds. Stopping to ask would turn every\n * ordinary reprice into a halt, and an agent that halts on ordinary commerce\n * is an agent nobody can leave running. There is no human-confirmation hook in\n * this path.\n * - **A policy is never widened to fit an offer.** Not by a byte, not once, not\n * \"because the seller says so\". There is deliberately no method on this type\n * that raises a limit from inside an evaluation. If the offer exceeds what was\n * authorised the answer is a refusal with a concrete cause, and the caller\n * decides whether to authorise more.\n *\n * # Order of evaluation\n *\n * Fixed, and part of the contract, because the FIRST failing check is the one\n * reported and a caller branches on it:\n *\n * 1. Was any offer readable at all? -> `no-readable-offer`\n * 2. Has it expired? -> `offer-expired`\n * 3. Is the recipient one we are willing to pay? -> `recipient-not-permitted`\n * 4. Was its asset budgeted at all? -> `asset-not-budgeted`\n * 5. Does it exceed the per-payment limit for that asset? -> `per-payment-limit`\n * 6. Does it exceed what remains of the cumulative limit? -> `cumulative-limit`\n *\n * The comparison against the listing is made LAST and refuses nothing: it is\n * evidence for the caller, never a gate.\n *\n * This is the same contract the Rust facilitator's `x402-reqwest` crate\n * implements (`PurchasePolicy`, release 2.25.0), written down once so a buyer in\n * either language refuses the same payments for the same stated reasons.\n *\n * @module\n */\n\nimport { X402Error } from './types';\nimport type { X402PaymentOffer } from './types';\n\n// ============================================================================\n// The offer-validity extension\n// ============================================================================\n\n/**\n * Extension key under which a seller declares how long its offer stands.\n *\n * Defined once, here, and read by nobody else's constant: a seller and a buyer\n * naming different keys have nothing to say to each other. The version is IN\n * the key because the offer-and-receipt transport can still change, and a value\n * read from an unversioned key could never be compared with anything later. A\n * key we do not recognise is ignored, which means \"no declared expiry\" -- a\n * different thing from \"expired\".\n */\nexport const OFFER_VALIDITY_EXTENSION = 'offer-receipt/1';\n\n/**\n * Read `validUntil` (Unix seconds) out of a 402 challenge's `extensions`.\n *\n * Shape: `extensions[\"offer-receipt/1\"].info.validUntil`. The `{info, schema}`\n * envelope is the one every merged x402 extension uses; reading the number from\n * anywhere else would be reading a field nobody agreed to publish.\n *\n * Anything unreadable is `undefined`, **never zero**: \"the seller said\n * something we could not read\" must not become \"this offer expired in 1970\".\n * A string, a float, a negative, a number past `Number.MAX_SAFE_INTEGER` -- all\n * unreadable, all absent.\n */\nexport function offerValidUntil(\n extensions: Record<string, unknown> | undefined | null\n): number | undefined {\n if (!extensions || typeof extensions !== 'object') return undefined;\n const entry = (extensions as Record<string, unknown>)[OFFER_VALIDITY_EXTENSION];\n if (!entry || typeof entry !== 'object') return undefined;\n const info = (entry as Record<string, unknown>).info;\n if (!info || typeof info !== 'object') return undefined;\n const value = (info as Record<string, unknown>).validUntil;\n if (typeof value !== 'number') return undefined;\n if (!Number.isSafeInteger(value) || value < 0) return undefined;\n return value;\n}\n\n// ============================================================================\n// Addresses\n// ============================================================================\n\n/**\n * Canonical form of a recipient or token address, for comparison.\n *\n * # Why this is not `toLowerCase()`\n *\n * It was, in the Rust crate, and that is only correct for one family. EVM\n * addresses are hex and arrive both checksummed and lowercase, so folding case\n * is right and necessary. **Base58 is case-sensitive** -- Solana and XRPL\n * addresses use both cases as distinct symbols -- so lowercasing one does not\n * produce the same address spelled differently, it produces a string that is not\n * an address.\n *\n * An allowlist written in the seller's own spelling would then never match, and\n * every payment to a legitimate Solana payee would be refused with\n * `recipient-not-permitted`. Worse in the other direction: two distinct base58\n * addresses can fold to the same lowercase string, so an allowlist could admit\n * an address nobody put on it.\n *\n * So: hex is folded, everything else is compared exactly.\n */\nexport function canonicalRecipient(address: string): string {\n const trimmed = address.trim();\n const rest =\n trimmed.startsWith('0x') || trimmed.startsWith('0X') ? trimmed.slice(2) : null;\n const isHex = rest !== null && rest.length > 0 && /^[0-9a-fA-F]+$/.test(rest);\n return isHex ? trimmed.toLowerCase() : trimmed;\n}\n\n// ============================================================================\n// Assets\n// ============================================================================\n\n/**\n * A token on a network -- the unit a budget is denominated in.\n *\n * Both halves are required. The same USDC contract address on two networks is\n * two different assets, and a budget for one is not a budget for the other: the\n * EVM signer takes its EIP-712 domain from the seller's own `extra`, so it will\n * sign for whatever token and network the seller names.\n */\nexport interface PolicyAsset {\n /**\n * SDK chain name (`'base'`) when the 402's network resolved to one, otherwise\n * the network string exactly as the 402 wrote it.\n *\n * Resolving first is what lets one written policy cover both 402 dialects:\n * a v1 challenge says `base` and a v2 one says `eip155:8453`, and a budget\n * keyed on the raw string would silently miss half of a seller's offers.\n */\n network: string;\n /** Token contract address. Compared canonicalised, never raw. */\n address: string;\n}\n\n/**\n * Stable map key for an asset. Not part of the wire format; comparison only.\n *\n * The network is folded to lowercase because SDK chain names and CAIP-2 strings\n * are lowercase by convention, so `'Base'` and `'base'` are the same network\n * written two ways -- never two networks. Leaving the case in fails closed\n * (`asset-not-budgeted`, so no wrong payment), but it trips the operator over a\n * capital letter and the refusal would point at the budget instead of the typo.\n * The address keeps its by-family treatment: see {@link canonicalRecipient}.\n */\nexport function assetKey(asset: PolicyAsset): string {\n return `${asset.network.trim().toLowerCase()}|${canonicalRecipient(asset.address)}`;\n}\n\n/** Human form, for a refusal message. */\nfunction assetLabel(asset: PolicyAsset): string {\n return asset.address ? `${asset.address} on ${asset.network}` : `(no asset declared) on ${asset.network}`;\n}\n\n/**\n * The asset an offer is priced in.\n *\n * An offer that declares no `asset` yields an empty address, which no budget can\n * ever hold -- {@link PurchasePolicy.perPayment} rejects an empty address -- so\n * such an offer is refused with `asset-not-budgeted` unless unlisted assets were\n * explicitly permitted. That is the safe direction: an unnamed token is a token\n * nobody budgeted for.\n */\nexport function offerAsset(offer: X402PaymentOffer): PolicyAsset {\n return {\n network: offer.chainName ?? offer.network,\n address: typeof offer.asset === 'string' ? offer.asset : '',\n };\n}\n\n// ============================================================================\n// Refusals\n// ============================================================================\n\n/**\n * Closed vocabulary of reasons a payment was not signed, in kebab-case, so an\n * SDK in another language branches on it without parsing English.\n *\n * There is no `other`: a refusal a caller cannot interpret is a refusal it will\n * paper over.\n */\nexport type PolicyRefusalCode =\n | 'no-readable-offer'\n | 'offer-expired'\n | 'recipient-not-permitted'\n | 'asset-not-budgeted'\n | 'per-payment-limit'\n | 'cumulative-limit';\n\n/**\n * Why a payment was not signed. Every variant carries the numbers that caused\n * it, so a caller can log the decision without re-deriving it.\n */\nexport type PolicyRefusal =\n | {\n code: 'no-readable-offer';\n /** Scheme names the seller offered, for the ones this build cannot read. */\n offered: string[];\n message: string;\n }\n | { code: 'offer-expired'; validUntil: number; now: number; message: string }\n | { code: 'recipient-not-permitted'; payTo: string; message: string }\n | { code: 'asset-not-budgeted'; asset: PolicyAsset; message: string }\n | {\n code: 'per-payment-limit';\n requested: bigint;\n allowed: bigint;\n asset: PolicyAsset;\n message: string;\n }\n | {\n code: 'cumulative-limit';\n requested: bigint;\n spent: bigint;\n wouldTotal: bigint;\n allowed: bigint;\n asset: PolicyAsset;\n message: string;\n };\n\n/**\n * A 402 whose offers this build could not read, turned into a refusal that says\n * so.\n *\n * The point is the message. A caller that learns the seller offered\n * `batch-settlement` knows to look for a facilitator that implements it, where\n * \"could not parse the response\" would have sent it looking for a bug in its own\n * code. Discovering the service keeps working even though buying it\n * automatically does not.\n */\nexport function noReadableOffer(offered: string[]): PolicyRefusal {\n return {\n code: 'no-readable-offer',\n offered,\n message:\n 'no offer in this challenge is one this build can pay; offered: ' +\n JSON.stringify(offered),\n };\n}\n\n/**\n * Error thrown on the real payment path when the policy refuses.\n *\n * Extends {@link X402Error}, so a consumer already catching `X402Error` keeps\n * catching this; the typed cause is on {@link PolicyRefusedError.refusal} and\n * its stable code on `refusal.code`.\n */\nexport class PolicyRefusedError extends X402Error {\n public readonly refusal: PolicyRefusal;\n\n constructor(refusal: PolicyRefusal) {\n super(`payment refused by policy: ${refusal.message}`, 'POLICY_REFUSED', refusal);\n this.name = 'PolicyRefusedError';\n this.refusal = refusal;\n }\n\n /** Stable kebab code of the refusal, for branching. */\n get policyCode(): PolicyRefusalCode {\n return this.refusal.code;\n }\n}\n\n// ============================================================================\n// The listing, and how the offer compares to it\n// ============================================================================\n\n/**\n * What a catalog listing advertised, for comparison against the real offer.\n *\n * Optional throughout. A buyer that never read a listing simply evaluates the\n * offer against its policy, which is the same decision with one fewer input.\n */\nexport interface AdvertisedQuote {\n asset: PolicyAsset;\n /** Price in the token's own atomic units. */\n amount: bigint;\n}\n\n/** How the offer in hand compares to what the catalog advertised. */\nexport type QuoteComparison =\n | { code: 'not-compared' }\n | { code: 'matches' }\n | { code: 'amount-differs'; advertised: bigint; offered: bigint }\n /**\n * A different asset entirely. The same number in another currency is not the\n * same price, so there is nothing to compare -- and no number is compared.\n */\n | { code: 'different-asset'; advertised: PolicyAsset; offered: PolicyAsset };\n\n/** A payment this policy permits, and what it noticed on the way. */\nexport interface PolicyApproval {\n asset: PolicyAsset;\n /** Price in the token's own atomic units. */\n amount: bigint;\n /**\n * How the offer compared to the listing, when there was one. Carried so a\n * caller can log or surface it; it never changed the decision.\n */\n versusQuote: QuoteComparison;\n}\n\n/** The outcome of an evaluation. Explicit, so no caller needs a `try`. */\nexport type PolicyDecision =\n | { ok: true; approval: PolicyApproval }\n | { ok: false; refusal: PolicyRefusal };\n\n/** Inputs to {@link PurchasePolicy.evaluate} besides the offer itself. */\nexport interface EvaluateOptions {\n /**\n * Unix seconds. Passed rather than read so the decision is testable at an\n * exact instant: money decisions that depend on a hidden clock cannot be\n * pinned.\n */\n now: number;\n /** `validUntil` the seller declared, if any. See {@link offerValidUntil}. */\n validUntil?: number;\n /** What the catalog advertised, if the caller read a listing. */\n quote?: AdvertisedQuote;\n}\n\n// ============================================================================\n// The policy\n// ============================================================================\n\n/**\n * The spending rules a caller authorised in advance.\n *\n * Every builder returns a new policy that **shares the running total**: two\n * copies of one policy spend from the same purse, which is what makes a\n * cumulative limit mean anything when a client is copied per request.\n *\n * @example\n * ```ts\n * const USDC_BASE = { network: 'base', address: '0x8335...2913' };\n * const policy = PurchasePolicy.create()\n * .perPayment(USDC_BASE, 50_000n) // 0.05 USDC, atomic units\n * .cumulative(USDC_BASE, 1_000_000n) // 1 USDC total, for this policy's life\n * .onlyPay(['0xe4dc...e545']);\n *\n * const client = new X402Client({ defaultChain: 'base', policy });\n * ```\n */\nexport class PurchasePolicy {\n private readonly perPaymentLimits: Map<string, bigint>;\n private readonly cumulativeLimits: Map<string, bigint>;\n /** Shared by reference across every copy: one purse, many holders. */\n private readonly spentTotals: Map<string, bigint>;\n private readonly recipients: Set<string> | null;\n private readonly assetsByKey: Map<string, PolicyAsset>;\n private readonly unlistedAssetsAllowed: boolean;\n\n private constructor(\n perPaymentLimits: Map<string, bigint>,\n cumulativeLimits: Map<string, bigint>,\n spentTotals: Map<string, bigint>,\n recipients: Set<string> | null,\n assetsByKey: Map<string, PolicyAsset>,\n unlistedAssetsAllowed: boolean\n ) {\n this.perPaymentLimits = perPaymentLimits;\n this.cumulativeLimits = cumulativeLimits;\n this.spentTotals = spentTotals;\n this.recipients = recipients;\n this.assetsByKey = assetsByKey;\n this.unlistedAssetsAllowed = unlistedAssetsAllowed;\n }\n\n /**\n * A policy that pays nothing until it is told what it may pay.\n *\n * # Why the default is deny\n *\n * The limits are a map keyed by asset, and a map answers \"no entry\" for every\n * asset nobody thought of. Permitting on a missing entry means a budget in\n * USDC is **no budget at all** for any other token: a seller offering the same\n * resource priced in something unlisted walks straight past the ceiling, and\n * the wallet will sign it, because the EVM signer takes the EIP-712 domain\n * from the seller's own `extra` and will happily sign for a token and a\n * network it has never heard of.\n *\n * So an asset with no stated ceiling is refused. A caller that genuinely wants\n * to pay anything says so once, by name, with\n * {@link PurchasePolicy.allowUnlistedAssets}, and that sentence is then in\n * their code where a reader can find it.\n */\n static create(): PurchasePolicy {\n return new PurchasePolicy(new Map(), new Map(), new Map(), null, new Map(), false);\n }\n\n /**\n * A policy that permits an asset it was never told about.\n *\n * This is what {@link X402Client} holds when the caller supplied no policy,\n * and it exists for exactly one reason: this SDK had no budget before 2.89.0,\n * and turning one on silently would refuse payments that callers are making\n * today. Named rather than defaulted, so choosing it is visible. The asymmetry\n * is deliberate -- whoever sits down to WRITE a policy deserves the safe\n * default.\n */\n static permissive(): PurchasePolicy {\n return new PurchasePolicy(new Map(), new Map(), new Map(), null, new Map(), true);\n }\n\n /** Permit assets with no configured ceiling. */\n allowUnlistedAssets(): PurchasePolicy {\n return this.with({ unlistedAssetsAllowed: true });\n }\n\n /**\n * Refuse assets with no configured ceiling. The default; here so the intent\n * can be written down at a call site that wants it explicit.\n */\n denyUnlistedAssets(): PurchasePolicy {\n return this.with({ unlistedAssetsAllowed: false });\n }\n\n /** Most this policy will pay in ONE payment of `asset`, in atomic units. */\n perPayment(asset: PolicyAsset, amount: bigint): PurchasePolicy {\n const key = this.register(asset);\n const perPaymentLimits = new Map(this.perPaymentLimits);\n perPaymentLimits.set(key, requireCeiling(amount, 'perPayment'));\n return this.with({ perPaymentLimits });\n }\n\n /**\n * Most this policy will pay in `asset` in TOTAL, across every payment it\n * approves for as long as it lives.\n */\n cumulative(asset: PolicyAsset, amount: bigint): PurchasePolicy {\n const key = this.register(asset);\n const cumulativeLimits = new Map(this.cumulativeLimits);\n cumulativeLimits.set(key, requireCeiling(amount, 'cumulative'));\n return this.with({ cumulativeLimits });\n }\n\n /**\n * Restrict payment to a set of recipients.\n *\n * Addresses are canonicalised **by family**, not by lowercasing the string:\n * see {@link canonicalRecipient}.\n */\n onlyPay(recipients: Iterable<string>): PurchasePolicy {\n const set = new Set<string>();\n for (const r of recipients) set.add(canonicalRecipient(r));\n return this.with({ recipients: set });\n }\n\n /**\n * Total recorded so far for `asset`, in atomic units.\n *\n * A total that is not a sane bigint means something corrupted the purse.\n * Reporting zero would silently restore the caller's whole budget, so this\n * reports the CEILING instead: for money, the safe direction is to refuse,\n * never to permit.\n */\n spent(asset: PolicyAsset): bigint {\n const key = assetKey(asset);\n const value = this.spentTotals.get(key);\n if (value === undefined) return 0n;\n if (typeof value !== 'bigint' || value < 0n) {\n return this.cumulativeLimits.get(key) ?? 0n;\n }\n return value;\n }\n\n /**\n * Record that a payment actually happened.\n *\n * Separate from {@link PurchasePolicy.evaluate} on purpose. Signing can still\n * fail and a settlement can still be refused; a cumulative limit that counted\n * attempts rather than payments would lock a caller out of money it never\n * spent. Call this when a payment settled.\n *\n * A negative amount is ignored: handing budget back is not something a\n * settlement can do, and treating it as one would be a way to widen a policy\n * from outside.\n */\n recordSpend(asset: PolicyAsset, amount: bigint): void {\n if (typeof amount !== 'bigint' || amount <= 0n) return;\n const key = assetKey(asset);\n if (!this.assetsByKey.has(key)) this.assetsByKey.set(key, asset);\n const current = this.spent(asset);\n this.spentTotals.set(key, current + amount);\n }\n\n /**\n * Whether this policy pays an asset it holds no ceiling for. Read-only: there\n * is no setter that flips it from inside an evaluation.\n */\n get permitsUnlistedAssets(): boolean {\n return this.unlistedAssetsAllowed;\n }\n\n /**\n * Decide whether this offer may be signed. Steps 2 through 6 of the contract;\n * step 1 (`no-readable-offer`) is decided on the challenge, before an offer\n * exists to evaluate -- see {@link decideOnChallenge}.\n *\n * **Approving does not record the spend.** See\n * {@link PurchasePolicy.recordSpend}.\n */\n evaluate(offer: X402PaymentOffer, options: EvaluateOptions): PolicyDecision {\n const { now, validUntil, quote } = options;\n\n // 2. Expiry. Before anything about money: terms that have lapsed are not\n // terms, whatever they say. `validUntil === now` still stands -- it is the\n // last instant the offer is up.\n if (validUntil !== undefined && now > validUntil) {\n return {\n ok: false,\n refusal: {\n code: 'offer-expired',\n validUntil,\n now,\n message:\n `this offer expired at ${validUntil} (now ${now}); ` +\n 'ask the seller for new terms',\n },\n };\n }\n\n // 3. Recipient.\n if (this.recipients !== null) {\n const payTo = canonicalRecipient(offer.payTo);\n if (!this.recipients.has(payTo)) {\n return {\n ok: false,\n refusal: {\n code: 'recipient-not-permitted',\n payTo: offer.payTo,\n message: `this policy does not pay ${offer.payTo}`,\n },\n };\n }\n }\n\n const asset = offerAsset(offer);\n const key = assetKey(asset);\n const requested = readAmount(offer.amount);\n\n // 4. An asset nobody budgeted for. Checked BEFORE the ceilings, because the\n // ceilings are a map and a map has no opinion about a key it does not\n // hold -- which is precisely how an unlisted token would sail past a\n // budget that looks complete. And the caller has to be told \"budget that\n // asset\", not \"raise a ceiling that does not exist\".\n if (\n !this.unlistedAssetsAllowed &&\n !this.perPaymentLimits.has(key) &&\n !this.cumulativeLimits.has(key)\n ) {\n return {\n ok: false,\n refusal: {\n code: 'asset-not-budgeted',\n asset,\n message:\n `this policy has no budget for ${assetLabel(asset)}; ` +\n 'it pays only what it was told it may pay',\n },\n };\n }\n\n // 5. Per-payment ceiling.\n const perPaymentAllowed = this.perPaymentLimits.get(key);\n if (perPaymentAllowed !== undefined && requested > perPaymentAllowed) {\n return {\n ok: false,\n refusal: {\n code: 'per-payment-limit',\n requested,\n allowed: perPaymentAllowed,\n asset,\n message:\n `offer of ${requested} exceeds the per-payment limit of ` +\n `${perPaymentAllowed} for ${assetLabel(asset)}`,\n },\n };\n }\n\n // 6. Cumulative ceiling.\n const cumulativeAllowed = this.cumulativeLimits.get(key);\n if (cumulativeAllowed !== undefined) {\n const spent = this.spent(asset);\n const wouldTotal = spent + requested;\n if (wouldTotal > cumulativeAllowed) {\n return {\n ok: false,\n refusal: {\n code: 'cumulative-limit',\n requested,\n spent,\n wouldTotal,\n allowed: cumulativeAllowed,\n asset,\n message:\n `offer of ${requested} would take spend to ${wouldTotal}, past the ` +\n `cumulative limit of ${cumulativeAllowed} for ${assetLabel(asset)} ` +\n `(already spent ${spent})`,\n },\n };\n }\n }\n\n // The comparison against the listing is made LAST and refuses nothing. It is\n // evidence for the caller, not a gate: a seller repricing inside a policy the\n // operator already authorised is ordinary commerce.\n return {\n ok: true,\n approval: { asset, amount: requested, versusQuote: compareToQuote(asset, requested, quote) },\n };\n }\n\n /** Copy sharing the same purse. Cloning is what a per-request client does. */\n clone(): PurchasePolicy {\n return this.with({});\n }\n\n /**\n * Rebuild with some fields replaced, **always sharing `spentTotals`**. This is\n * the one place that decides copies share a purse, so it is the one place to\n * read when asking whether they do.\n */\n private with(changes: {\n perPaymentLimits?: Map<string, bigint>;\n cumulativeLimits?: Map<string, bigint>;\n recipients?: Set<string> | null;\n unlistedAssetsAllowed?: boolean;\n }): PurchasePolicy {\n return new PurchasePolicy(\n changes.perPaymentLimits ?? this.perPaymentLimits,\n changes.cumulativeLimits ?? this.cumulativeLimits,\n this.spentTotals,\n changes.recipients !== undefined ? changes.recipients : this.recipients,\n this.assetsByKey,\n changes.unlistedAssetsAllowed ?? this.unlistedAssetsAllowed\n );\n }\n\n /** Remember an asset's written form and reject one no budget could match. */\n private register(asset: PolicyAsset): string {\n if (!asset || typeof asset.address !== 'string' || asset.address.trim() === '') {\n throw new X402Error(\n 'A budget needs a token address; an asset with none can never match an offer',\n 'INVALID_CONFIG',\n { asset }\n );\n }\n if (typeof asset.network !== 'string' || asset.network.trim() === '') {\n throw new X402Error(\n 'A budget needs a network; the same address on two networks is two assets',\n 'INVALID_CONFIG',\n { asset }\n );\n }\n const key = assetKey(asset);\n this.assetsByKey.set(key, asset);\n return key;\n }\n}\n\n/** A ceiling has to be a non-negative bigint; anything else is a config bug. */\nfunction requireCeiling(amount: bigint, field: string): bigint {\n if (typeof amount !== 'bigint' || amount < 0n) {\n throw new X402Error(\n `${field} must be a non-negative bigint in atomic units`,\n 'INVALID_AMOUNT',\n { amount: String(amount) }\n );\n }\n return amount;\n}\n\n/**\n * An offer's price as a bigint.\n *\n * Arithmetic is bigint throughout, never `number`: atomic units of an 18-decimal\n * token pass `Number.MAX_SAFE_INTEGER` at 0.01 of a token, and a ceiling\n * compared as a float is a ceiling that rounds.\n *\n * An amount that is not a non-negative integer is read as the largest value we\n * can represent for the comparison, so it fails every ceiling rather than\n * passing as zero: a price we cannot read is not a price we may pay.\n */\nfunction readAmount(amount: string): bigint {\n const text = String(amount).trim();\n if (!/^\\d+$/.test(text)) return UNREADABLE_AMOUNT;\n return BigInt(text);\n}\n\n/**\n * Stand-in for a price we could not read. Absurdly large on purpose: it exceeds\n * every ceiling a caller would write, so an unreadable amount is refused by the\n * limit checks instead of sliding through as zero.\n */\nconst UNREADABLE_AMOUNT = (1n << 256n) - 1n;\n\nfunction compareToQuote(\n asset: PolicyAsset,\n requested: bigint,\n quote: AdvertisedQuote | undefined\n): QuoteComparison {\n if (!quote) return { code: 'not-compared' };\n if (assetKey(quote.asset) !== assetKey(asset)) {\n // Rule 4: a different asset is not the same price. No numbers are compared.\n return { code: 'different-asset', advertised: quote.asset, offered: asset };\n }\n if (quote.amount !== requested) {\n return { code: 'amount-differs', advertised: quote.amount, offered: requested };\n }\n return { code: 'matches' };\n}\n\n// ============================================================================\n// The whole decision, in one place\n// ============================================================================\n\n/** A 402 challenge as the buyer read it, whole. */\nexport interface ReadChallenge {\n /** Offers this build could read. */\n offers: X402PaymentOffer[];\n /**\n * Scheme names of the entries it could not. Rule 7: an `accepts` with one\n * unreadable entry KEEPS the readable ones and counts the others by scheme\n * name, so a refusal can say what the seller offered.\n */\n unreadable: string[];\n /**\n * How many entries were unreadable, which is not the same as how many could be\n * NAMED: an entry too broken to even carry a `scheme` still proves the seller\n * sent offers. Without it, a challenge whose only entry was nameless garbage\n * would read as \"the seller sent nothing\" -- a different fact, and the wrong\n * one to report. Defaults to `unreadable.length`.\n */\n unreadableCount?: number;\n /** The challenge's top-level `extensions`, where `validUntil` lives. */\n extensions?: Record<string, unknown>;\n}\n\n/** Inputs to {@link decideOnChallenge} besides the challenge. */\nexport interface DecideOptions {\n /** Unix seconds. Passed, never read, so the decision can be pinned in a test. */\n now: number;\n /** What the catalog advertised, if the caller read a listing. */\n quote?: AdvertisedQuote;\n}\n\n/**\n * The whole buying decision: all six steps, in the fixed order, against the\n * offer in hand.\n *\n * Takes the challenge WHOLE, deliberately. Passing `offers` alone is what\n * dropped the seller's `validUntil` on the floor in the Rust crate for a full\n * commit with every unit test green, and a signature that takes the parts\n * invites doing it again.\n *\n * Callable without a network stack on purpose: a decision that can only be\n * exercised by driving a real HTTP client is a decision nobody tests.\n *\n * @param offer - The offer already selected out of `challenge.offers`. Selection\n * is the caller's (cheapest, or its own `select`); this decides whether the\n * selected one may be paid.\n */\nexport function decideOnChallenge(\n policy: PurchasePolicy,\n challenge: ReadChallenge,\n offer: X402PaymentOffer | null,\n options: DecideOptions\n): PolicyDecision {\n // 1. Was any offer readable at all? A challenge that carried offers, none of\n // which this build can read, is not \"no matching payment method\": it is a\n // seller asking for a scheme we do not implement, and saying so names what\n // they wanted.\n const unreadableCount = challenge.unreadableCount ?? challenge.unreadable.length;\n if (challenge.offers.length === 0 && unreadableCount > 0) {\n return { ok: false, refusal: noReadableOffer(challenge.unreadable) };\n }\n if (!offer) {\n // Nothing selected out of a challenge that had readable offers, or a seller\n // that sent no offers at all. Either way there is no offer in hand to judge,\n // and the refusal names what the seller offered -- an empty list when it\n // offered nothing.\n return { ok: false, refusal: noReadableOffer(challenge.unreadable) };\n }\n return policy.evaluate(offer, {\n now: options.now,\n validUntil: offerValidUntil(challenge.extensions),\n quote: options.quote,\n });\n}\n","/**\n * uvd-x402-sdk - React Hooks\n *\n * Provides React hooks for easy integration with x402 payments.\n *\n * @example\n * ```tsx\n * import { X402Provider, useX402, useBalance, usePayment } from 'uvd-x402-sdk/react';\n *\n * function App() {\n * return (\n * <X402Provider config={{ defaultChain: 'base' }}>\n * <PaymentButton amount=\"10.00\" recipient=\"0x...\" />\n * </X402Provider>\n * );\n * }\n *\n * function PaymentButton({ amount, recipient }) {\n * const { connect, isConnected, address } = useX402();\n * const { balance, isLoading: balanceLoading } = useBalance();\n * const { pay, isPaying } = usePayment();\n *\n * if (!isConnected) {\n * return <button onClick={() => connect('base')}>Connect Wallet</button>;\n * }\n *\n * return (\n * <button\n * onClick={() => pay({ amount, recipient })}\n * disabled={isPaying}\n * >\n * Pay ${amount} USDC\n * </button>\n * );\n * }\n * ```\n */\n\nimport { createContext, useContext, useCallback, useState, useEffect, useMemo, type ReactNode } from 'react';\nimport { X402Client } from '../client';\nimport type {\n X402ClientConfig,\n WalletState,\n PaymentInfo,\n PaymentResult,\n ChainConfig,\n NetworkBalance,\n} from '../types';\nimport { getEnabledChains, getChainByName } from '../chains';\n\n// ============================================================================\n// CONTEXT\n// ============================================================================\n\ninterface X402ContextValue {\n client: X402Client;\n state: WalletState;\n connect: (chainName?: string) => Promise<string>;\n disconnect: () => Promise<void>;\n switchChain: (chainName: string) => Promise<void>;\n getBalance: () => Promise<string>;\n}\n\nconst X402Context = createContext<X402ContextValue | null>(null);\n\n// ============================================================================\n// PROVIDER\n// ============================================================================\n\ninterface X402ProviderProps {\n children: ReactNode;\n config?: X402ClientConfig;\n}\n\n/**\n * X402Provider - Context provider for x402 SDK\n *\n * Wrap your app with this provider to use the x402 hooks.\n */\nexport function X402Provider({ children, config }: X402ProviderProps) {\n const [client] = useState(() => new X402Client(config));\n const [state, setState] = useState<WalletState>(() => client.getState());\n\n useEffect(() => {\n // Subscribe to events\n const unsubConnect = client.on('connect', (newState) => {\n setState(newState);\n });\n\n const unsubDisconnect = client.on('disconnect', () => {\n setState(client.getState());\n });\n\n const unsubChainChanged = client.on('chainChanged', () => {\n setState(client.getState());\n });\n\n const unsubAccountChanged = client.on('accountChanged', () => {\n setState(client.getState());\n });\n\n return () => {\n unsubConnect();\n unsubDisconnect();\n unsubChainChanged();\n unsubAccountChanged();\n };\n }, [client]);\n\n const connect = useCallback(\n async (chainName?: string) => {\n const address = await client.connect(chainName);\n setState(client.getState());\n return address;\n },\n [client]\n );\n\n const disconnect = useCallback(async () => {\n await client.disconnect();\n setState(client.getState());\n }, [client]);\n\n const switchChain = useCallback(\n async (chainName: string) => {\n await client.switchChain(chainName);\n setState(client.getState());\n },\n [client]\n );\n\n const getBalance = useCallback(() => client.getBalance(), [client]);\n\n const value = useMemo(\n () => ({\n client,\n state,\n connect,\n disconnect,\n switchChain,\n getBalance,\n }),\n [client, state, connect, disconnect, switchChain, getBalance]\n );\n\n return <X402Context.Provider value={value}>{children}</X402Context.Provider>;\n}\n\n// ============================================================================\n// HOOKS\n// ============================================================================\n\n/**\n * useX402 - Main hook for x402 functionality\n *\n * Returns wallet state and connection methods.\n */\nexport function useX402() {\n const context = useContext(X402Context);\n if (!context) {\n throw new Error('useX402 must be used within an X402Provider');\n }\n\n const { client, state, connect, disconnect, switchChain, getBalance } = context;\n\n return {\n // State\n isConnected: state.connected,\n address: state.address,\n chainId: state.chainId,\n network: state.network,\n networkType: state.networkType,\n\n // Methods\n connect,\n disconnect,\n switchChain,\n getBalance,\n\n // Client access for advanced usage\n client,\n };\n}\n\n/**\n * useBalance - Hook for USDC balance management\n */\nexport function useBalance() {\n const { client, isConnected, network } = useX402();\n const [balance, setBalance] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const fetchBalance = useCallback(async () => {\n if (!isConnected) {\n setBalance(null);\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const bal = await client.getBalance();\n setBalance(bal);\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Failed to fetch balance');\n setBalance(null);\n } finally {\n setIsLoading(false);\n }\n }, [client, isConnected]);\n\n // Auto-fetch on connection/network change\n useEffect(() => {\n fetchBalance();\n }, [fetchBalance, network]);\n\n return {\n balance,\n isLoading,\n error,\n refetch: fetchBalance,\n };\n}\n\n/**\n * usePayment - Hook for creating payments\n */\nexport function usePayment() {\n const { client, isConnected } = useX402();\n const [isPaying, setIsPaying] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [lastResult, setLastResult] = useState<PaymentResult | null>(null);\n\n const pay = useCallback(\n async (paymentInfo: PaymentInfo): Promise<PaymentResult> => {\n if (!isConnected) {\n throw new Error('Wallet not connected');\n }\n\n setIsPaying(true);\n setError(null);\n\n try {\n const result = await client.createPayment(paymentInfo);\n setLastResult(result);\n return result;\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Payment failed';\n setError(message);\n throw err;\n } finally {\n setIsPaying(false);\n }\n },\n [client, isConnected]\n );\n\n const reset = useCallback(() => {\n setError(null);\n setLastResult(null);\n }, []);\n\n return {\n pay,\n isPaying,\n error,\n lastResult,\n reset,\n };\n}\n\n/**\n * useChains - Hook for chain information\n */\nexport function useChains() {\n const { network: currentNetwork } = useX402();\n\n const chains = useMemo(() => getEnabledChains(), []);\n\n const currentChain = useMemo(\n () => (currentNetwork ? getChainByName(currentNetwork) : null),\n [currentNetwork]\n );\n\n const evmChains = useMemo(\n () => chains.filter((c) => c.networkType === 'evm'),\n [chains]\n );\n\n const nonEvmChains = useMemo(\n () => chains.filter((c) => c.networkType !== 'evm'),\n [chains]\n );\n\n return {\n chains,\n currentChain,\n evmChains,\n nonEvmChains,\n getChain: getChainByName,\n };\n}\n\n/**\n * useNetworkBalances - Hook for fetching balances across all networks\n */\nexport function useNetworkBalances() {\n const { address, isConnected, networkType } = useX402();\n const [balances, setBalances] = useState<Map<string, NetworkBalance>>(new Map());\n const [isLoading, setIsLoading] = useState(false);\n\n const fetchAllBalances = useCallback(async () => {\n if (!isConnected || !address) {\n setBalances(new Map());\n return;\n }\n\n setIsLoading(true);\n const chains = getEnabledChains();\n\n // Filter to compatible chains\n const compatibleChains = chains.filter((chain) => {\n // EVM address starts with 0x\n if (address.startsWith('0x')) {\n return chain.networkType === 'evm';\n }\n // Otherwise match by network type\n return chain.networkType === networkType;\n });\n\n const newBalances = new Map<string, NetworkBalance>();\n\n // Initialize loading states\n compatibleChains.forEach((chain) => {\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: null,\n isLoading: true,\n error: null,\n });\n });\n setBalances(new Map(newBalances));\n\n // Fetch in parallel\n await Promise.allSettled(\n compatibleChains.map(async (chain) => {\n try {\n const provider = new (await import('ethers')).JsonRpcProvider(chain.rpcUrl);\n const usdcAbi = ['function balanceOf(address) view returns (uint256)'];\n const contract = new (await import('ethers')).Contract(\n chain.usdc.address,\n usdcAbi,\n provider\n );\n const balance = await contract.balanceOf(address);\n const formatted = parseFloat(\n (await import('ethers')).formatUnits(balance, chain.usdc.decimals)\n ).toFixed(2);\n\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: formatted,\n isLoading: false,\n error: null,\n });\n } catch (err) {\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: null,\n isLoading: false,\n error: err instanceof Error ? err.message : 'Failed',\n });\n }\n setBalances(new Map(newBalances));\n })\n );\n\n setIsLoading(false);\n }, [address, isConnected, networkType]);\n\n useEffect(() => {\n fetchAllBalances();\n }, [fetchAllBalances]);\n\n // Find network with highest balance\n const highestBalanceNetwork = useMemo(() => {\n let maxBalance = 0;\n let maxChain: string | null = null;\n\n balances.forEach((nb, chainName) => {\n if (nb.balance !== null && !nb.error) {\n const bal = parseFloat(nb.balance);\n if (bal > maxBalance) {\n maxBalance = bal;\n maxChain = chainName;\n }\n }\n });\n\n return maxChain;\n }, [balances]);\n\n return {\n balances,\n isLoading,\n refetch: fetchAllBalances,\n highestBalanceNetwork,\n };\n}\n\n// Re-export types for convenience\nexport type { WalletState, PaymentInfo, PaymentResult, ChainConfig, NetworkBalance };\n\n// ============================================================================\n// COMPONENTS\n// ============================================================================\n\nexport { NetworkPicker, buildNetworkOptions, resolveChain, SIGNABLE_IN_BROWSER, FAMILY_LABEL } from './NetworkPicker';\nexport type { NetworkPickerProps, NetworkOption } from './NetworkPicker';\n\nexport { PaymentMethodPicker } from './PaymentMethodPicker';\nexport type { PaymentMethodPickerProps, PaymentAccept } from './PaymentMethodPicker';\n","/**\n * NetworkPicker - the shared network selector for the whole stack.\n *\n * WHY IT IS SEPARATE FROM PaymentMethodPicker\n * The first version of this work bundled \"pick a network\" and \"pay\" into one\n * component. Dogfooding it into meshrelay broke that idea in the first minute:\n * its selector is a controlled input (`value` / `onChange`) sitting next to a\n * pay button that owns the payment. Sites that already have a payment flow need\n * the selector alone. So: this component selects, `PaymentMethodPicker` wraps it\n * and adds the paying.\n *\n * The props are deliberately shaped like meshrelay's `NetworkSelector`, which is\n * the one that got the interaction right, so adopting it is an import swap\n * rather than a rewrite.\n *\n * TWO RULES, EACH PAID FOR IN A PRODUCTION BUG\n *\n * 1. No chain table lives here. Networks come from `getEnabledChains()`, the\n * single source, which already carries all 21 mainnet networks the\n * facilitator settles. describe.net deleted its own 14-network table for\n * this reason.\n * 2. A network with no local config does NOT break the list. It renders with its\n * raw id. With 21 networks and counting, that is a requirement, not manners.\n *\n * WHY IT IMPORTS `../chains` AND NOT `useChains()`\n * Going through the `./index` barrel pulls `X402Client` and with it `ethers`.\n * `getEnabledChains()` is a data table with no crypto in it, so the picker keeps\n * the same single source without the weight, and `react/picker` can exist as an\n * entrypoint that ships 30.8 kB instead of 64.5 kB. A picker must not make a\n * page pay for a signing stack it may never use.\n *\n * Accessibility follows meshrelay: `role=\"radiogroup\"`, live `aria-checked`, and\n * arrow keys that move and select, per the WAI-ARIA radiogroup pattern.\n */\n\nimport { useCallback, useMemo, useRef, type KeyboardEvent, type ReactNode } from 'react';\n\nimport { getEnabledChains } from '../chains';\nimport type { ChainConfig, NetworkType } from '../types';\n\n/**\n * Wallet families a browser can sign for today. The rest are listed but\n * disabled: the facilitator settles them, the browser bridge is not there yet.\n * Backlog items 1 and 2 in `docs/carrusel-de-pago-compartido.md`.\n */\nexport const SIGNABLE_IN_BROWSER: readonly NetworkType[] = ['evm', 'svm', 'solana'];\n\nexport const FAMILY_LABEL: Record<string, string> = {\n evm: 'EVM',\n svm: 'Solana VM',\n solana: 'Solana VM',\n stellar: 'Stellar',\n near: 'NEAR',\n algorand: 'Algorand',\n sui: 'Sui',\n xrpl: 'XRP Ledger',\n};\n\nexport interface NetworkOption {\n /** Network id, as the caller and the facilitator name it. */\n id: string;\n /** Local config, or null when this build does not know the network. */\n chain: ChainConfig | null;\n /** What to show. Falls back to the raw id. */\n label: string;\n family: string;\n selectable: boolean;\n /** Why it cannot be picked. Shown to the user, never swallowed. */\n disabledReason?: string;\n}\n\nexport interface NetworkPickerProps {\n /** Currently selected network. Controlled component. */\n value: string | null;\n /** Called when the user picks a different network. */\n onChange: (next: string) => void;\n /**\n * Networks to offer. Omit to offer every x402-enabled chain the SDK knows.\n * Pass the ids from a 402 `accepts` array to mirror what the resource takes.\n */\n networks?: readonly string[];\n /** Narrow by wallet family. */\n families?: readonly NetworkType[];\n /** When true, all options are non-interactive (e.g. mid-payment). */\n disabled?: boolean;\n /** Heading above the selector. */\n label?: string;\n /** Hint below the selector. */\n hint?: string;\n /** Hide the heading entirely. */\n hideLabel?: boolean;\n /** Group options under a family heading. Useful past a handful of networks. */\n groupByFamily?: boolean;\n layout?: 'carousel' | 'segmented' | 'list';\n className?: string;\n /**\n * Per-option decoration. Exists so adopting this component is not a visual\n * regression: meshrelay carries a logo, a short label and a tagline per\n * network that `ChainConfig` does not have, and it should not have to give\n * them up to stop maintaining its own selector. Everything returned is\n * optional and falls back to what the SDK knows.\n */\n decorate?: (option: NetworkOption) => {\n icon?: ReactNode;\n label?: ReactNode;\n shortLabel?: ReactNode;\n title?: string;\n };\n /**\n * Your class names, merged onto the built-in ones. A component that ships in\n * an SDK has no business imposing a look: meshrelay already has a CSS module\n * for this selector and adopting the shared logic should not cost it the\n * styling. Built-in `uvd-x402-picker__*` classes stay on, so a site can also\n * target those instead.\n */\n classNames?: Partial<\n Record<\n | 'root'\n | 'label'\n | 'group'\n | 'family'\n | 'familyLabel'\n | 'option'\n | 'optionSelected'\n | 'optionDisabled'\n | 'icon'\n | 'name'\n | 'nameShort'\n | 'reason'\n | 'hint',\n string\n >\n >;\n}\n\n/** Join the built-in class with the caller's, dropping empties. */\nfunction cx(...parts: Array<string | false | undefined | null>): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/** Match a network id to local chain config, tolerating aliases. */\nexport function resolveChain(\n id: string,\n chains: readonly ChainConfig[],\n aliases: readonly string[] = []\n): ChainConfig | null {\n const names = [id, ...aliases].map((n) => String(n).toLowerCase());\n return (\n chains.find((c) => names.includes(c.name.toLowerCase())) ??\n chains.find((c) => names.some((n) => n === `eip155:${c.chainId}`)) ??\n null\n );\n}\n\nexport function describeWhyDisabled(\n chain: ChainConfig | null,\n family: string,\n signable: boolean\n): string | undefined {\n if (!chain) return 'Not configured in this build';\n if (chain.x402.enabled === false) return 'Disabled for x402';\n if (!signable) return `No browser wallet bridge for ${FAMILY_LABEL[family] ?? family} yet`;\n return undefined;\n}\n\n/** Build the option list. Exported so PaymentMethodPicker reuses the same rules. */\nexport function buildNetworkOptions(\n ids: readonly string[],\n chains: readonly ChainConfig[],\n families?: readonly NetworkType[]\n): NetworkOption[] {\n const all = ids.map((id): NetworkOption => {\n const chain = resolveChain(id, chains);\n const family = chain?.networkType ?? 'unknown';\n const signable = SIGNABLE_IN_BROWSER.includes(family as NetworkType);\n return {\n id,\n chain,\n label: chain?.displayName ?? id,\n family,\n selectable: signable && chain !== null && chain.x402.enabled !== false,\n disabledReason: describeWhyDisabled(chain, family, signable),\n };\n });\n return families ? all.filter((o) => families.includes(o.family as NetworkType)) : all;\n}\n\nexport function NetworkPicker({\n value,\n onChange,\n networks,\n families,\n disabled = false,\n label = 'Payment network',\n hint,\n hideLabel = false,\n groupByFamily = false,\n layout = 'carousel',\n className,\n decorate,\n classNames: cls = {},\n}: NetworkPickerProps) {\n const chains = useMemo(() => getEnabledChains(), []);\n const buttonRefs = useRef<Record<string, HTMLButtonElement | null>>({});\n\n const options = useMemo(() => {\n const ids =\n networks ?? chains.filter((c) => c.x402.enabled !== false).map((c) => c.name);\n return buildNetworkOptions(ids, chains, families);\n }, [networks, chains, families]);\n\n const selectable = useMemo(\n () => (disabled ? [] : options.filter((o) => o.selectable)),\n [options, disabled]\n );\n\n const onKeyDown = useCallback(\n (event: KeyboardEvent<HTMLButtonElement>, id: string) => {\n const keys = ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'];\n if (!keys.includes(event.key) || selectable.length === 0) return;\n event.preventDefault();\n const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : -1;\n const at = selectable.findIndex((o) => o.id === id);\n const next = selectable[(at + step + selectable.length) % selectable.length];\n if (!next) return;\n onChange(next.id);\n buttonRefs.current[next.id]?.focus();\n },\n [selectable, onChange]\n );\n\n const renderOption = (option: NetworkOption) => {\n const isSelected = value === option.id;\n const usable = option.selectable && !disabled;\n const isFirstFallback = value === null && selectable[0]?.id === option.id;\n const extra = decorate?.(option);\n return (\n <button\n key={option.id}\n ref={(el) => {\n buttonRefs.current[option.id] = el;\n }}\n type=\"button\"\n role=\"radio\"\n aria-checked={isSelected}\n aria-disabled={!usable}\n disabled={!usable}\n title={extra?.title ?? option.disabledReason}\n tabIndex={isSelected || isFirstFallback ? 0 : -1}\n onClick={() => usable && onChange(option.id)}\n onKeyDown={(event) => onKeyDown(event, option.id)}\n className={cx(\n 'uvd-x402-picker__option',\n cls.option,\n isSelected && 'is-selected',\n isSelected && cls.optionSelected,\n !usable && cls.optionDisabled\n )}\n >\n {extra?.icon}\n <span className={cx('uvd-x402-picker__name', cls.name)}>\n {extra?.label ?? option.label}\n </span>\n {extra?.shortLabel && (\n <span className={cx('uvd-x402-picker__name-short', cls.nameShort)}>\n {extra.shortLabel}\n </span>\n )}\n {option.disabledReason && (\n <span className={cx('uvd-x402-picker__reason', cls.reason)}>\n {option.disabledReason}\n </span>\n )}\n </button>\n );\n };\n\n const grouped = useMemo(() => {\n if (!groupByFamily) return null;\n const map = new Map<string, NetworkOption[]>();\n for (const option of options) {\n const list = map.get(option.family) ?? [];\n list.push(option);\n map.set(option.family, list);\n }\n return [...map.entries()];\n }, [options, groupByFamily]);\n\n return (\n <div\n className={cx(\n 'uvd-x402-picker',\n `uvd-x402-picker--${layout}`,\n cls.root,\n className\n )}\n >\n {!hideLabel && (\n <h3 className={cx('uvd-x402-picker__label', cls.label)}>{label}</h3>\n )}\n\n <div\n role=\"radiogroup\"\n aria-label={label}\n className={cx('uvd-x402-picker__group', cls.group)}\n >\n {grouped\n ? grouped.map(([family, entries]) => (\n <section key={family} className={cx('uvd-x402-picker__family', cls.family)}>\n <h4 className={cx('uvd-x402-picker__family-label', cls.familyLabel)}>\n {FAMILY_LABEL[family] ?? family}\n </h4>\n {entries.map(renderOption)}\n </section>\n ))\n : options.map(renderOption)}\n </div>\n\n {hint && <p className={cx('uvd-x402-picker__hint', cls.hint)}>{hint}</p>}\n </div>\n );\n}\n","/**\n * PaymentMethodPicker - network selection plus payment, in one component.\n *\n * This is `NetworkPicker` with the paying attached. Sites that already own their\n * payment flow (meshrelay, for one) should use `NetworkPicker` directly and keep\n * their button; sites starting from nothing get the whole thing here.\n *\n * WHY THIS EXISTS\n * Three repos grew their own picker (describe.net `dn-pay.js`, 402milly\n * `ChainSelector`, meshrelay `NetworkSelector`): 3,718 lines solving the same\n * problem three times, none covering the 21 mainnet networks the facilitator\n * settles. Design notes and backlog: `docs/carrusel-de-pago-compartido.md`.\n *\n * THE RULE THAT MATTERS MOST HERE\n * `accepts` is passed through VERBATIM, by reference. Never rebuilt, cloned or\n * reordered. Rebuilding that object field by field is how a valid payment ends\n * up rejected (see the note in describe.net `dn-pay.js:485`). The other rules\n * about chain tables and `wallet_addEthereumChain` live in `NetworkPicker`.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\n\nimport { useX402, usePayment } from './index';\nimport { NetworkPicker } from './NetworkPicker';\nimport type { NetworkType, PaymentInfo, PaymentResult } from '../types';\n\n/** One entry of the `accepts` array of a 402 response. */\nexport interface PaymentAccept {\n scheme: string;\n network: string;\n networkAliases?: string[];\n extra?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface PaymentMethodPickerProps {\n /** The `accepts` array from the 402 response, untouched. */\n accepts: readonly PaymentAccept[];\n /** Recipients and amount, handed to `pay()` as-is. */\n payment: PaymentInfo;\n onPaid?: (result: PaymentResult) => void;\n onError?: (error: Error) => void;\n /** Restrict to some families. Omit to offer everything the resource accepts. */\n families?: readonly NetworkType[];\n layout?: 'carousel' | 'segmented' | 'list';\n label?: string;\n hint?: string;\n payLabel?: string;\n className?: string;\n}\n\nexport function PaymentMethodPicker({\n accepts,\n payment,\n onPaid,\n onError,\n families,\n layout = 'carousel',\n label = 'Payment network',\n hint,\n payLabel = 'Pay',\n className,\n}: PaymentMethodPickerProps) {\n const { isConnected, connect, switchChain, network } = useX402();\n const { pay, isPaying } = usePayment();\n const [selected, setSelected] = useState<string | null>(null);\n\n // Ids only. The accept objects themselves are never copied. Rule 1.\n const networks = useMemo(() => accepts.map((a) => a.network), [accepts]);\n\n const confirm = useCallback(async () => {\n const accept = accepts.find((a) => a.network === selected);\n if (!accept) return;\n try {\n if (!isConnected) await connect(accept.network);\n // Ask to switch. Never wallet_addEthereumChain.\n if (network && network !== accept.network) await switchChain(accept.network);\n // `payment` and `accept` both travel verbatim, by reference.\n const result = await pay({ ...payment, accept } as PaymentInfo);\n onPaid?.(result);\n } catch (error) {\n onError?.(error instanceof Error ? error : new Error(String(error)));\n }\n }, [accepts, selected, isConnected, connect, network, switchChain, pay, payment, onPaid, onError]);\n\n return (\n <div className={['uvd-x402-pay', className].filter(Boolean).join(' ')}>\n <NetworkPicker\n value={selected}\n onChange={setSelected}\n networks={networks}\n families={families}\n disabled={isPaying}\n label={label}\n hint={hint}\n groupByFamily={networks.length > 6}\n layout={layout}\n />\n\n <button\n type=\"button\"\n disabled={!selected || isPaying}\n onClick={confirm}\n className=\"uvd-x402-pay__confirm\"\n >\n {isPaying ? 'Paying...' : payLabel}\n </button>\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/index.ts","../../src/chains/index.ts","../../src/utils/base64.ts","../../src/utils/x402.ts","../../src/utils/token-metadata.ts","../../src/utils/validation.ts","../../src/utils/personal-sign.ts","../../src/utils/index.ts","../../src/providers/solana/index.ts","../../src/client/X402Client.ts","../../src/policy.ts","../../src/react/index.tsx","../../src/react/NetworkPicker.tsx","../../src/react/PaymentMethodPicker.tsx"],"names":["publicKeyString","ethers","SVMProvider","useMemo","useRef","useCallback","jsxs","jsx","useState","createContext","useEffect","useContext"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IA4kBa,iBAAA,EAuCA,gBA8PA,cAAA,EAuGA,SAAA;AAx9Bb,IAAA,UAAA,GAAA,KAAA,CAAA;AAAA,EAAA,oBAAA,GAAA;AA4kBO,IAAM,iBAAA,GAA4C;AAAA;AAAA,MAEvD,IAAA,EAAM,aAAA;AAAA,MACN,QAAA,EAAU,UAAA;AAAA,MACV,OAAA,EAAS,YAAA;AAAA,MACT,QAAA,EAAU,cAAA;AAAA,MACV,QAAA,EAAU,WAAA;AAAA,MACV,SAAA,EAAW,cAAA;AAAA,MACX,IAAA,EAAM,cAAA;AAAA,MACN,QAAA,EAAU,YAAA;AAAA,MACV,QAAA,EAAU,YAAA;AAAA,MACV,KAAA,EAAO,YAAA;AAAA,MACP,GAAA,EAAK,WAAA;AAAA,MACL,MAAA,EAAQ,eAAA;AAAA,MACR,YAAA,EAAc,mBAAA;AAAA,MACd,oBAAA,EAAsB,kBAAA;AAAA,MACtB,SAAA,EAAW,aAAA;AAAA,MACX,mBAAA,EAAqB,cAAA;AAAA;AAAA,MAErB,MAAA,EAAQ,yCAAA;AAAA,MACR,IAAA,EAAM,UAAA;AAAA;AAAA,MAEN,OAAA,EAAS,gBAAA;AAAA;AAAA,MAET,IAAA,EAAM,cAAA;AAAA;AAAA,MAEN,QAAA,EAAU,kBAAA;AAAA,MACV,kBAAA,EAAoB,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1C,IAAA,IAAI,UAAA,GAAa,CAAA;AACjB,IAAA,IAAI,QAAA,GAA0B,IAAA;AAE9B,IAAA,QAAA,CAAS,OAAA,CAAQ,CAAC,EAAA,EAAI,SAAA,KAAc;AAClC,MAAA,IAAI,EAAA,CAAG,OAAA,KAAY,IAAA,IAAQ,CAAC,GAAG,KAAA,EAAO;AACpC,QAAA,MAAM,GAAA,GAAM,UAAA,CAAW,EAAA,CAAG,OAAO,CAAA;AACjC,QAAA,IAAI,MAAM,UAAA,EAAY;AACpB,UAAA,UAAA,GAAa,GAAA;AACb,UAAA,QAAA,GAAW,SAAA;AAAA,QACb;AAAA,MACF;AAAA,IACF,CAAC,CAAA;AAED,IAAA,OAAO,QAAA;AAAA,EACT,CAAA,EAAG,CAAC,QAAQ,CAAC,CAAA;AAEb,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA,EAAS,gBAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\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';\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';\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 exactly one thing today: the native\n * XRP that XRPL settles in.\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 /** 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 };\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 every dollar-pegged token that is dollars, which is all of them but\n * one. On XRPL it is **XRP**, because XRPL settles in its own native asset:\n * the provider spends this through `xrpToDrops` 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\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 /** 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 // 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 // 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\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 - Chain Registry\n *\n * Complete configuration for all 25 supported blockchain networks.\n * EVM chains (15): Use ERC-3009 TransferWithAuthorization (includes Scroll, SKALE Base, Robinhood Chain mainnet + testnet)\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 // ============================================================================\n // EVM CHAINS (15 networks)\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 },\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 eurc: {\n address: '0xC891EB4cbdEFf6e073e859e987815Ed1505c2ACD',\n decimals: 6,\n name: 'EURC',\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 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 },\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 // ============================================================================\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:199`).\n */\nexport const CHAIN_ALIASES: Record<string, string> = {\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 '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 '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 - 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';\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\n if (obj.accepts && Array.isArray(obj.accepts)) {\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 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 if (!isUsdPegged(token)) continue;\n\n // Atomic units in THIS token's decimals -- BSC USDC has 18, not 6.\n const atomicAmount = Math.floor(\n parseFloat(amount) * Math.pow(10, token.decimals)\n ).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 - Token metadata for payment payloads\n *\n * An EIP-3009 authorization is signed against a token contract, but the encoded\n * payload only carries the signature and the transfer fields. The token itself\n * is implicit — the server is expected to already know which asset it asked\n * for.\n *\n * That holds when a resource accepts exactly one token per chain. It breaks as\n * soon as it accepts several: a EURC payment and a USDC payment on Base produce\n * indistinguishable payloads, and the server cannot build the\n * `paymentRequirements` (`asset` + `extra`) the facilitator needs to settle.\n *\n * So the payment can opt into carrying the token with it.\n */\n\nimport { getTokenByAddress } from '../chains';\nimport type { PaymentTokenMetadata } from '../types';\n\n/**\n * Build the token metadata block for a payload, resolving the address against\n * the chain registry.\n *\n * @param chainName - Chain the payment was signed for\n * @param address - Token contract address from the signed payload\n * @returns Metadata block, or undefined if the address is not in the registry\n */\nexport function buildTokenMetadata(\n chainName: string,\n address: string\n): PaymentTokenMetadata | undefined {\n const match = getTokenByAddress(chainName, address);\n if (!match) return undefined;\n\n return {\n address: match.config.address,\n symbol: match.tokenType.toUpperCase(),\n decimals: match.config.decimals,\n eip712: {\n name: match.config.name,\n version: match.config.version,\n },\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'\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 '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 - EIP-191 personal_sign helpers\n *\n * Generic recover/verify for an EIP-191 `personal_sign` over an arbitrary\n * string message — the shape a wallet produces for `eth_sign`/`personal_sign`\n * and `cast wallet sign <message>`.\n *\n * This is deliberately NOT the ERC-8128 machinery (`verifyRequest`), which\n * verifies an RFC 9421 SIGNED HTTP REQUEST (method;url;headers;content-digest).\n * A challenge/response flow — a service hands out a nonce string, the wallet\n * signs that string, the service recovers the signer — is a different, simpler\n * case that the ERC-8128 path does not cover. Consumers doing wallet-ownership\n * challenges (e.g. MeshRelay's IRC `VERIFY`/`VERIFY-SIG`) needed this and were\n * each reaching for `ethers.verifyMessage` directly; this centralizes it.\n */\n\nimport { ethers } from 'ethers';\n\n/**\n * Recover the address that produced an EIP-191 `personal_sign` over `message`.\n *\n * @param message - the exact string that was signed\n * @param signature - the 0x-prefixed signature\n * @returns the checksummed recovered address\n * @throws if the signature is malformed (propagates ethers' error)\n */\nexport function recoverPersonalSignAddress(message: string, signature: string): string {\n return ethers.verifyMessage(message, signature);\n}\n\n/**\n * Whether `signature` over `message` was produced by `expected`.\n *\n * Compares case-insensitively (recovered addresses are checksummed, linked\n * wallets are often stored lower-cased) and never throws: a malformed\n * signature is a failed verification, not an exception to handle at every\n * call site.\n *\n * @returns true iff the recovered signer equals `expected`\n */\nexport function verifyPersonalSign(params: {\n message: string;\n signature: string;\n expected: string;\n}): boolean {\n const { message, signature, expected } = params;\n if (!expected) return false;\n try {\n const recovered = recoverPersonalSignAddress(message, signature);\n return recovered.toLowerCase() === expected.toLowerCase();\n } catch {\n return false;\n }\n}\n","/**\n * uvd-x402-sdk - Utilities\n *\n * Re-exports all utility functions.\n */\n\nexport {\n detectX402Version,\n paymentChallengeFrom,\n chainToCAIP2,\n caip2ToChain,\n parseNetworkIdentifier,\n encodeX402Header,\n decodeX402Header,\n createX402V1Header,\n createX402V2Header,\n createX402Header,\n generatePaymentOptions,\n isCAIP2Format,\n convertX402Header,\n} from './x402';\n\nexport { buildTokenMetadata } from './token-metadata';\n\nexport {\n encodeBase64Utf8,\n decodeBase64Utf8,\n encodeBase64Json,\n} from './base64';\n\nexport {\n validateRecipient,\n validateAmount,\n createPaymentHeaders,\n getPaymentHeader,\n DEFAULT_PAYMENT_HEADER,\n PAYMENT_HEADER_NAMES,\n} from './validation';\n\nexport {\n recoverPersonalSignAddress,\n verifyPersonalSign,\n} from './personal-sign';\n","/**\n * uvd-x402-sdk - SVM Provider (Solana Virtual Machine)\n *\n * Provides wallet connection and payment creation for SVM-based chains via Phantom.\n * Supports: Solana, Fogo\n * Uses partially-signed transactions where the facilitator is the fee payer.\n *\n * @example Solana\n * ```ts\n * import { SVMProvider } from 'uvd-x402-sdk/solana';\n * import { getChainByName } from 'uvd-x402-sdk';\n *\n * const svm = new SVMProvider();\n *\n * // Connect\n * const address = await svm.connect();\n *\n * // Create Solana payment\n * const chainConfig = getChainByName('solana')!;\n * const paymentPayload = await svm.signPayment(paymentInfo, chainConfig);\n * const header = svm.encodePaymentHeader(paymentPayload, chainConfig);\n * ```\n *\n * @example Fogo\n * ```ts\n * import { SVMProvider } from 'uvd-x402-sdk/solana';\n * import { getChainByName } from 'uvd-x402-sdk';\n *\n * const svm = new SVMProvider();\n *\n * // Connect (same wallet works for all SVM chains)\n * const address = await svm.connect();\n *\n * // Create Fogo payment\n * const chainConfig = getChainByName('fogo')!;\n * const paymentPayload = await svm.signPayment(paymentInfo, chainConfig);\n * const header = svm.encodePaymentHeader(paymentPayload, chainConfig);\n * ```\n */\n\nimport type {\n ChainConfig,\n PaymentInfo,\n SolanaPaymentPayload,\n TokenInfo,\n WalletAdapter,\n X402Version,\n} from '../../types';\nimport { X402Error } from '../../types';\nimport { getChainByName } from '../../chains';\nimport { chainToCAIP2, encodeBase64Json } from '../../utils';\n\n/**\n * Browser-compatible base64 encoding for Uint8Array\n * Avoids Node.js Buffer dependency for browser bundlers\n */\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\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// Lazy import Solana dependencies to avoid bundling when not used\nlet Connection: typeof import('@solana/web3.js').Connection;\nlet PublicKey: typeof import('@solana/web3.js').PublicKey;\nlet TransactionMessage: typeof import('@solana/web3.js').TransactionMessage;\nlet VersionedTransaction: typeof import('@solana/web3.js').VersionedTransaction;\nlet ComputeBudgetProgram: typeof import('@solana/web3.js').ComputeBudgetProgram;\nlet getAssociatedTokenAddress: typeof import('@solana/spl-token').getAssociatedTokenAddress;\nlet createTransferCheckedInstruction: typeof import('@solana/spl-token').createTransferCheckedInstruction;\nlet createAssociatedTokenAccountIdempotentInstruction: typeof import('@solana/spl-token').createAssociatedTokenAccountIdempotentInstruction;\nlet TOKEN_PROGRAM_ID: typeof import('@solana/spl-token').TOKEN_PROGRAM_ID;\n\nasync function loadSolanaDeps() {\n if (!Connection) {\n const web3 = await import('@solana/web3.js');\n const splToken = await import('@solana/spl-token');\n Connection = web3.Connection;\n PublicKey = web3.PublicKey;\n TransactionMessage = web3.TransactionMessage;\n VersionedTransaction = web3.VersionedTransaction;\n ComputeBudgetProgram = web3.ComputeBudgetProgram;\n getAssociatedTokenAddress = splToken.getAssociatedTokenAddress;\n createTransferCheckedInstruction = splToken.createTransferCheckedInstruction;\n createAssociatedTokenAccountIdempotentInstruction = splToken.createAssociatedTokenAccountIdempotentInstruction;\n TOKEN_PROGRAM_ID = splToken.TOKEN_PROGRAM_ID;\n }\n}\n\n/**\n * Phantom wallet provider interface\n */\ninterface PhantomProvider {\n isPhantom?: boolean;\n isConnected?: boolean;\n publicKey?: { toBase58(): string };\n connect(): Promise<{ publicKey: { toBase58(): string } }>;\n disconnect(): Promise<void>;\n signTransaction<T>(transaction: T): Promise<T>;\n}\n\n/**\n * SVMProvider - Wallet adapter for SVM chains (Solana, Fogo) via Phantom\n *\n * @alias SolanaProvider for backward compatibility\n */\nexport class SVMProvider implements WalletAdapter {\n readonly id = 'phantom';\n readonly name = 'Phantom';\n readonly networkType = 'svm' as const;\n\n private provider: PhantomProvider | null = null;\n private publicKey: InstanceType<typeof PublicKey> | null = null;\n private connections: Map<string, InstanceType<typeof Connection>> = new Map();\n private address: string | null = null;\n\n /**\n * Check if Phantom wallet is available\n */\n isAvailable(): boolean {\n if (typeof window === 'undefined') return false;\n return !!(\n (window as Window & { phantom?: { solana?: PhantomProvider } }).phantom?.solana?.isPhantom ||\n (window as Window & { solana?: PhantomProvider }).solana?.isPhantom\n );\n }\n\n /**\n * Connect to Phantom wallet\n */\n async connect(): Promise<string> {\n await loadSolanaDeps();\n\n // Get Phantom provider\n this.provider = await this.getPhantomProvider();\n if (!this.provider) {\n throw new X402Error(\n 'Phantom wallet not installed. Please install from phantom.app',\n 'WALLET_NOT_FOUND'\n );\n }\n\n try {\n // Check if already connected\n if (this.provider.publicKey && this.provider.isConnected) {\n const publicKeyString = this.provider.publicKey.toBase58();\n this.publicKey = new PublicKey(publicKeyString);\n this.address = publicKeyString;\n await this.initConnection();\n return publicKeyString;\n }\n\n // Connect\n const resp = await this.provider.connect();\n const publicKeyString = resp.publicKey.toBase58();\n\n this.publicKey = new PublicKey(publicKeyString);\n this.address = publicKeyString;\n\n await this.initConnection();\n\n return publicKeyString;\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || (error as { code?: number }).code === 4001) {\n throw new X402Error('Connection rejected by user', 'WALLET_CONNECTION_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to connect Phantom: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'UNKNOWN_ERROR',\n error\n );\n }\n }\n\n /**\n * Disconnect from Phantom\n */\n async disconnect(): Promise<void> {\n if (this.provider) {\n try {\n await this.provider.disconnect();\n } catch {\n // Ignore disconnect errors\n }\n }\n this.provider = null;\n this.publicKey = null;\n this.connections.clear();\n this.address = null;\n }\n\n /**\n * Get current address\n */\n getAddress(): string | null {\n return this.address;\n }\n\n /**\n * Get USDC balance\n */\n async getBalance(chainConfig: ChainConfig): Promise<string> {\n await loadSolanaDeps();\n\n if (!this.address) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n await this.initConnection(chainConfig);\n const connection = this.connections.get(chainConfig.name);\n if (!connection) {\n throw new X402Error('Failed to connect to Solana RPC', 'NETWORK_ERROR');\n }\n\n try {\n const response = await fetch(chainConfig.rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [\n this.address,\n { mint: chainConfig.usdc.address },\n { encoding: 'jsonParsed' },\n ],\n }),\n });\n\n const data = await response.json();\n\n if (!data.result?.value?.length) {\n return '0.00';\n }\n\n const tokenAccountInfo = data.result.value[0].account.data.parsed.info;\n const balance = Number(tokenAccountInfo.tokenAmount.amount) / Math.pow(10, tokenAccountInfo.tokenAmount.decimals);\n\n return balance.toFixed(2);\n } catch {\n return '0.00';\n }\n }\n\n /**\n * Create SVM payment (partially-signed transaction)\n *\n * Works for both Solana and Fogo chains.\n *\n * Transaction structure required by facilitator:\n * 1. SetComputeUnitLimit\n * 2. SetComputeUnitPrice\n * 3. (Optional) CreateAssociatedTokenAccount if recipient ATA doesn't exist\n * 4. TransferChecked (USDC transfer)\n *\n * Fee payer: Facilitator (not user)\n * User pays: ZERO SOL/FOGO\n */\n async signPayment(paymentInfo: PaymentInfo, chainConfig: ChainConfig): Promise<string> {\n await loadSolanaDeps();\n\n if (!this.provider || !this.publicKey || !this.address) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const connection = await this.getConnection(chainConfig);\n if (!connection) {\n throw new X402Error(`Failed to connect to ${chainConfig.displayName} RPC`, 'NETWORK_ERROR');\n }\n\n // Get recipient and facilitator addresses\n const recipient = paymentInfo.recipients?.solana || paymentInfo.recipient;\n const facilitatorAddress = paymentInfo.facilitator;\n\n if (!facilitatorAddress) {\n throw new X402Error('Facilitator address not provided', 'INVALID_CONFIG');\n }\n\n const recipientPubkey = new PublicKey(recipient);\n const facilitatorPubkey = new PublicKey(facilitatorAddress);\n const usdcMint = new PublicKey(chainConfig.usdc.address);\n\n // Parse amount (6 decimals for USDC)\n const amount = Math.floor(parseFloat(paymentInfo.amount) * 1_000_000);\n\n // Get token accounts\n const fromTokenAccount = await getAssociatedTokenAddress(\n usdcMint,\n this.publicKey,\n true,\n TOKEN_PROGRAM_ID\n );\n\n const toTokenAccount = await getAssociatedTokenAddress(\n usdcMint,\n recipientPubkey,\n true,\n TOKEN_PROGRAM_ID\n );\n\n // Check if recipient ATA exists\n const toTokenAccountInfo = await connection.getAccountInfo(toTokenAccount);\n const needsATACreation = toTokenAccountInfo === null;\n\n // Get recent blockhash\n const { blockhash } = await connection.getLatestBlockhash('finalized');\n\n // Build instructions in exact order required by facilitator\n const instructions = [];\n\n // Instruction 0: SetComputeUnitLimit\n instructions.push(\n ComputeBudgetProgram.setComputeUnitLimit({\n units: needsATACreation ? 50_000 : 20_000,\n })\n );\n\n // Instruction 1: SetComputeUnitPrice\n // Use 100k microlamports/CU for fast landing on mainnet\n // Lower values (like 1) cause transactions to be deprioritized and time out\n instructions.push(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: 100_000,\n })\n );\n\n // Instruction 2 (optional): CreateAssociatedTokenAccountIdempotent\n // User pays for ATA creation (not facilitator - security check in x402-rs)\n if (needsATACreation) {\n instructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n this.publicKey, // User pays for ATA creation\n toTokenAccount,\n recipientPubkey,\n usdcMint,\n TOKEN_PROGRAM_ID\n )\n );\n }\n\n // Instruction 2/3: TransferChecked\n instructions.push(\n createTransferCheckedInstruction(\n fromTokenAccount,\n usdcMint,\n toTokenAccount,\n this.publicKey,\n amount,\n 6,\n [],\n TOKEN_PROGRAM_ID\n )\n );\n\n // Build VersionedTransaction with facilitator as fee payer\n const messageV0 = new TransactionMessage({\n payerKey: facilitatorPubkey,\n recentBlockhash: blockhash,\n instructions,\n }).compileToV0Message();\n\n const transaction = new VersionedTransaction(messageV0);\n\n // User signs (partial signature - facilitator will co-sign)\n // IMPORTANT: Phantom may modify the transaction (add memo instruction).\n // We send the FULL signed transaction to the facilitator, which will use it\n // exactly as signed (not reconstruct it). This ensures signature validity.\n let signedTransaction: InstanceType<typeof VersionedTransaction>;\n try {\n signedTransaction = await this.provider.signTransaction(transaction);\n } catch (error: unknown) {\n if (error instanceof Error && error.message.includes('User rejected')) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\n }\n throw new X402Error(\n `Failed to sign transaction: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n // Serialize the FULL signed transaction (including any wallet modifications)\n // The facilitator will use this exact transaction, adding only its signature\n const serialized = signedTransaction.serialize();\n\n const payload: SolanaPaymentPayload = {\n transaction: uint8ArrayToBase64(serialized),\n };\n\n return JSON.stringify(payload);\n }\n\n /**\n * Encode SVM payment as X-PAYMENT header\n *\n * @param paymentPayload - JSON-encoded payment payload from signPayment()\n * @param chainConfig - Chain configuration (optional, defaults to 'solana')\n * @param version - x402 protocol version (1 or 2, defaults to 1)\n * @returns Base64-encoded X-PAYMENT header value\n */\n encodePaymentHeader(\n paymentPayload: string,\n chainConfig?: ChainConfig,\n version: X402Version = 1\n ): string {\n const payload = JSON.parse(paymentPayload) as SolanaPaymentPayload;\n\n // Use chain name from config, or default to 'solana' for backward compatibility\n const networkName = chainConfig?.name || 'solana';\n\n // Build the payload data - preserve token info for Token2022 (AUSD, etc.)\n const payloadData: { transaction: string; token?: TokenInfo } = {\n transaction: payload.transaction,\n };\n\n // CRITICAL: Preserve token info for non-USDC tokens (Token2022 like AUSD)\n // Without this, the facilitator cannot verify Token2022 transfers correctly\n if (payload.token) {\n payloadData.token = payload.token;\n }\n\n // Format in x402 standard format (v1 or v2)\n const x402Payload = version === 2\n ? {\n x402Version: 2 as const,\n scheme: 'exact' as const,\n network: chainToCAIP2(networkName), // CAIP-2 format for v2\n payload: payloadData,\n }\n : {\n x402Version: 1 as const,\n scheme: 'exact' as const,\n network: networkName, // Plain chain name for v1\n payload: payloadData,\n };\n\n return encodeBase64Json(x402Payload);\n }\n\n // Private helpers\n\n private async getPhantomProvider(): Promise<PhantomProvider | null> {\n if (typeof window === 'undefined') return null;\n\n // Try window.phantom.solana first\n const win = window as Window & {\n phantom?: { solana?: PhantomProvider };\n solana?: PhantomProvider;\n };\n\n if (win.phantom?.solana?.isPhantom) {\n return win.phantom.solana;\n }\n\n // Fallback to window.solana\n if (win.solana?.isPhantom) {\n return win.solana;\n }\n\n // Wait a bit for Phantom to inject itself\n for (let i = 0; i < 5; i++) {\n await new Promise(resolve => setTimeout(resolve, 100));\n if (win.phantom?.solana?.isPhantom) {\n return win.phantom.solana;\n }\n if (win.solana?.isPhantom) {\n return win.solana;\n }\n }\n\n return null;\n }\n\n /**\n * Get or create a connection for a specific chain\n *\n * IMPORTANT: Caches by RPC URL, not chain name. This allows consumers to\n * override the RPC URL (e.g., use Helius instead of public RPC) and get\n * a fresh connection with their custom RPC.\n */\n private async getConnection(chainConfig?: ChainConfig): Promise<InstanceType<typeof Connection>> {\n await loadSolanaDeps();\n\n const config = chainConfig || getChainByName('solana');\n if (!config) {\n throw new X402Error('Chain config not found', 'CHAIN_NOT_SUPPORTED');\n }\n\n // Cache by RPC URL, not chain name - allows custom RPC overrides\n const cacheKey = config.rpcUrl;\n\n // Check if we already have a connection for this RPC\n if (this.connections.has(cacheKey)) {\n return this.connections.get(cacheKey)!;\n }\n\n // Create new connection for this RPC\n const connection = new Connection(config.rpcUrl, 'confirmed');\n this.connections.set(cacheKey, connection);\n\n return connection;\n }\n\n /**\n * @deprecated Use getConnection instead\n */\n private async initConnection(chainConfig?: ChainConfig): Promise<void> {\n await this.getConnection(chainConfig);\n }\n}\n\n/**\n * @deprecated Use SVMProvider instead\n */\nexport class SolanaProvider extends SVMProvider {\n constructor() {\n super();\n console.warn('SolanaProvider is deprecated. Use SVMProvider instead.');\n }\n}\n\n// Default export\nexport default SVMProvider;\n","/**\n * uvd-x402-sdk - Main Client\n *\n * The X402Client is the primary entry point for the SDK.\n * It manages wallet connections, chain switching, and payment creation.\n */\n\nimport { ethers } from 'ethers';\nimport type {\n ChainConfig,\n NetworkType,\n PaymentInfo,\n PaymentResult,\n WalletState,\n X402ClientConfig,\n X402Event,\n X402EventData,\n X402EventHandler,\n EVMPaymentPayload,\n TokenType,\n X402EVMPayload,\n X402Version,\n X402PaymentOffer,\n X402FetchOptions,\n WalletAdapter,\n} from '../types';\nimport { X402Error, DEFAULT_CONFIG } from '../types';\nimport {\n PurchasePolicy,\n PolicyRefusedError,\n decideOnChallenge,\n noReadableOffer,\n canonicalRecipient,\n} from '../policy';\nimport type { PolicyApproval, ReadChallenge } from '../policy';\nimport {\n SUPPORTED_CHAINS,\n getChainByName,\n getChainById,\n getEnabledChains,\n getTokenConfig,\n} from '../chains';\nimport {\n validateRecipient,\n chainToCAIP2,\n caip2ToChain,\n encodeBase64Json,\n buildTokenMetadata,\n} from '../utils';\n\n/**\n * The x402 scheme vocabulary, shared by all three implementations.\n *\n * The same five the Rust facilitator's closed `Scheme` enum holds and the same\n * five the Python SDK keys `KNOWN_SCHEMES` on. A scheme outside this set is one\n * no implementation in the stack can name, so an entry carrying one is unreadable\n * and is counted by the name the seller used.\n *\n * Kept as a set of known NAMES rather than of payable ones because the two are\n * different questions, and conflating them is what rule 7 is about: naming what a\n * seller offered is how a caller learns to go find a facilitator that implements\n * it. See {@link CLIENT_PAYABLE_SCHEMES} for the other question.\n */\nexport const KNOWN_SCHEMES: ReadonlySet<string> = new Set([\n 'exact',\n 'upto',\n 'escrow',\n 'commerce',\n 'fhe-transfer',\n]);\n\n/**\n * Of those, the ones the BUYER path in this client can actually sign.\n *\n * One entry, and that is the point: the payload builder stamps\n * `scheme: 'exact'` into everything it produces, so `exact` is the only thing\n * this client can honestly present. `escrow` and `commerce` are implemented on\n * the SELLER side (`src/backend`) and in the pre-auth builder, and `upto` and\n * `fhe-transfer` are not implemented here at all.\n *\n * # Why this is a SECOND set and not a narrower first one\n *\n * `parse402` used to accept any entry carrying an amount, a payee and a network,\n * so a well-formed offer asking for a scheme this build cannot present was read\n * as payable and then **signed as `exact`** -- a payment offered to the seller\n * under a scheme it never asked for. Recognising a scheme is not being able to\n * pay it. Collapsing these two sets into one re-opens exactly that hole: widen\n * this one to the five known names and a well-formed `escrow` offer gets signed\n * as `exact` again.\n *\n * Both cases end the same way for the caller -- the entry is excluded and counted\n * by its scheme name -- and `no-readable-offer` says \"no offer in this challenge\n * is one this build **can pay**\", which is the frame both of them sit in.\n */\nexport const CLIENT_PAYABLE_SCHEMES: ReadonlySet<string> = new Set(['exact']);\n\n/**\n * X402Client - Main SDK client for x402 payments\n *\n * @example\n * ```ts\n * import { X402Client } from 'uvd-x402-sdk';\n *\n * const client = new X402Client({ defaultChain: 'base' });\n *\n * // Connect wallet\n * await client.connect('base');\n *\n * // Create payment\n * const result = await client.createPayment({\n * recipient: '0x...',\n * amount: '10.00',\n * });\n *\n * // Use result.paymentHeader in your API request\n * ```\n */\nexport class X402Client {\n // Configuration\n private readonly config: Required<Pick<X402ClientConfig, 'facilitatorUrl' | 'defaultChain' | 'autoConnect' | 'debug'>> & X402ClientConfig;\n\n // Wallet state\n private provider: ethers.BrowserProvider | ethers.JsonRpcProvider | null = null;\n private signer: ethers.Signer | null = null;\n private connectedAddress: string | null = null;\n private currentChainId: number | null = null;\n private currentNetwork: NetworkType | null = null;\n private currentChainName: string | null = null;\n /**\n * Non-EVM wallet, when one is connected. EVM keeps using `provider`/`signer`\n * because those are ethers-typed; every other network type talks through the\n * {@link WalletAdapter} contract instead.\n */\n private walletAdapter: WalletAdapter | null = null;\n\n // Event emitter\n private eventHandlers: Map<X402Event, Set<X402EventHandler<X402Event>>> = new Map();\n\n /**\n * What this buyer is allowed to sign, evaluated against the offer in hand\n * before anything is signed.\n *\n * `permissive()` when the caller supplied none, and that asymmetry is\n * deliberate: this SDK had no budget before 2.89.0, so switching one on\n * silently would refuse payments consumers are making today, while whoever\n * sits down to WRITE a policy gets the deny-by-default one.\n */\n private readonly purchasePolicy: PurchasePolicy;\n\n constructor(config: X402ClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n // Apply custom RPC overrides\n if (config.rpcOverrides) {\n for (const [chainName, rpcUrl] of Object.entries(config.rpcOverrides)) {\n if (SUPPORTED_CHAINS[chainName]) {\n SUPPORTED_CHAINS[chainName].rpcUrl = rpcUrl;\n }\n }\n }\n\n // Apply custom chain configurations\n if (config.customChains) {\n for (const [chainName, chainConfig] of Object.entries(config.customChains)) {\n if (SUPPORTED_CHAINS[chainName]) {\n Object.assign(SUPPORTED_CHAINS[chainName], chainConfig);\n }\n }\n }\n\n this.purchasePolicy = config.policy ?? PurchasePolicy.permissive();\n\n this.log('X402Client initialized', { config: this.config });\n }\n\n /**\n * The policy in force, for a caller that wants to record a settled payment\n * against it with {@link PurchasePolicy.recordSpend}.\n *\n * Nothing on the payment path ever widens it.\n */\n get policy(): PurchasePolicy {\n return this.purchasePolicy;\n }\n\n // ============================================================================\n // PUBLIC API - Wallet Connection\n // ============================================================================\n\n /**\n * Connect to a wallet on the specified chain\n */\n async connect(chainName?: string): Promise<string> {\n const targetChain = chainName || this.config.defaultChain;\n const chain = getChainByName(targetChain);\n\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (!chain.x402.enabled) {\n throw new X402Error(`Chain ${targetChain} is not enabled for x402 payments`, 'CHAIN_NOT_SUPPORTED');\n }\n\n this.log(`Connecting wallet on ${chain.displayName}...`);\n\n // Route to appropriate connection method based on network type\n switch (chain.networkType) {\n case 'evm':\n return this.connectEVMWallet(chain);\n case 'svm':\n // The registry says 'svm' for Solana and Fogo; this used to read\n // `case 'solana'`, which no chain has ever carried, so every SVM\n // caller fell through to `default:`. `NetworkType` allows both\n // spellings, so the compiler never caught it.\n return this.connectSVMWallet(chain);\n case 'stellar':\n throw new X402Error(\n 'Stellar support requires importing from \"uvd-x402-sdk/stellar\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n case 'near':\n throw new X402Error(\n 'NEAR support requires importing from \"uvd-x402-sdk/near\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n case 'xrpl':\n throw new X402Error(\n 'XRPL support requires importing from \"uvd-x402-sdk/xrpl\"',\n 'CHAIN_NOT_SUPPORTED'\n );\n default:\n throw new X402Error(`Unknown network type for chain ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n }\n\n /**\n * Connect using a private key (Node.js / server-side, no browser wallet needed)\n */\n async connectWithPrivateKey(privateKey: string, chainName?: string): Promise<string> {\n const targetChain = chainName || this.config.defaultChain;\n const chain = getChainByName(targetChain);\n\n if (!chain) {\n throw new X402Error(`Unsupported chain: ${targetChain}`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (!chain.x402.enabled) {\n throw new X402Error(`Chain ${targetChain} is not enabled for x402 payments`, 'CHAIN_NOT_SUPPORTED');\n }\n\n if (chain.networkType !== 'evm') {\n throw new X402Error('connectWithPrivateKey is only supported for EVM chains', 'CHAIN_NOT_SUPPORTED');\n }\n\n this.log(`Connecting with private key on ${chain.displayName}...`);\n\n const rpcProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n const wallet = new ethers.Wallet(privateKey, rpcProvider);\n\n this.provider = rpcProvider;\n this.signer = wallet;\n this.connectedAddress = wallet.address;\n this.currentChainId = chain.chainId;\n this.currentNetwork = 'evm';\n this.currentChainName = chain.name;\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('Private key wallet connected', { address: this.connectedAddress, chain: chain.name });\n\n return this.connectedAddress;\n }\n\n /**\n * Disconnect the current wallet\n */\n async disconnect(): Promise<void> {\n if (this.walletAdapter) {\n try {\n await this.walletAdapter.disconnect();\n } catch {\n // A wallet that is already gone must not block local teardown.\n }\n this.walletAdapter = null;\n }\n this.provider = null;\n this.signer = null;\n this.connectedAddress = null;\n this.currentChainId = null;\n this.currentNetwork = null;\n this.currentChainName = null;\n\n this.emit('disconnect', undefined);\n this.log('Wallet disconnected');\n }\n\n /**\n * Switch to a different chain (EVM only)\n */\n async switchChain(chainName: string): Promise<void> {\n const chain = getChainByName(chainName);\n\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 'switchChain is only supported for EVM networks. Reconnect with connect() for other networks.',\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n if (!this.provider) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n // Private key connections cannot use wallet_switchEthereumChain — re-create provider\n if (this.provider instanceof ethers.JsonRpcProvider && this.signer instanceof ethers.Wallet) {\n const rpcProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n const wallet = new ethers.Wallet(this.signer.privateKey, rpcProvider);\n this.provider = rpcProvider;\n this.signer = wallet;\n this.currentChainId = chain.chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId: chain.chainId, chainName: chain.name });\n this.log('Switched chain (private key mode)', { chain: chain.name });\n return;\n }\n\n await this.switchEVMChain(chain);\n }\n\n // ============================================================================\n // PUBLIC API - Payment Creation\n // ============================================================================\n\n /**\n * Create a payment authorization\n *\n * @param paymentInfo - Payment information from 402 response\n * @returns Payment result with encoded X-PAYMENT header\n */\n async createPayment(paymentInfo: PaymentInfo): Promise<PaymentResult> {\n if (!this.connectedAddress) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n if (!this.currentChainName) {\n throw new X402Error('Chain not set', 'CHAIN_NOT_SUPPORTED');\n }\n\n const chain = getChainByName(this.currentChainName);\n if (!chain) {\n throw new X402Error(`Chain ${this.currentChainName} not found`, 'CHAIN_NOT_SUPPORTED');\n }\n\n this.emit('paymentStarted', { amount: paymentInfo.amount, network: chain.name });\n this.log('Creating payment...', { paymentInfo, chain: chain.name });\n\n try {\n // Route to appropriate payment method\n switch (chain.networkType) {\n case 'evm':\n return await this.createEVMPayment(paymentInfo, chain);\n default:\n if (this.walletAdapter?.networkType === chain.networkType) {\n return await this.createAdapterPayment(paymentInfo, chain);\n }\n throw new X402Error(\n `Payment creation for ${chain.networkType} requires the appropriate provider`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n } catch (error) {\n const x402Error = error instanceof X402Error\n ? error\n : new X402Error(\n error instanceof Error ? error.message : 'Unknown error',\n 'PAYMENT_FAILED',\n error\n );\n\n this.emit('paymentFailed', { error: x402Error.message, code: x402Error.code });\n throw x402Error;\n }\n }\n\n\n // ============================================================================\n // PUBLIC API - Buyer loop\n // ============================================================================\n\n /**\n * Fetch a resource, paying its `402 Payment Required` challenge if it has one.\n *\n * The BUYER side of x402, and the half this client was missing: it could sign\n * a payment ({@link createPayment}) but never ask for one, so every consumer\n * hand-rolled the same loop -- probe, read `accepts`, pick, sign, retry --\n * and each one picked its own answer to \"how much is too much\".\n *\n * Safe by default: `maxAmount` is a hard ceiling. A 402 that asks for more\n * throws `PAYMENT_EXCEEDS_MAX` instead of quietly signing it. A response that\n * is not a 402 -- a first-try 200 included -- comes back untouched; this pays\n * only when payment is what was asked for.\n *\n * @param url - Resource URL.\n * @param options - See {@link X402FetchOptions}.\n * @returns The paid response after a 402, or the original response.\n *\n * @example\n * ```ts\n * await client.connectWithPrivateKey(key, 'base');\n * const res = await client.fetch('https://api.example.com/data', {\n * maxAmount: '0.05',\n * });\n * const data = await res.json();\n * ```\n */\n async fetch(url: string, options: X402FetchOptions = {}): Promise<Response> {\n if (!this.connectedAddress) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const method = options.method || 'GET';\n const doFetch = options.fetchImpl || globalThis.fetch;\n if (typeof doFetch !== 'function') {\n throw new X402Error(\n 'No fetch implementation available; pass options.fetchImpl',\n 'NETWORK_ERROR'\n );\n }\n\n const probe = await doFetch(url, { ...options.init, method });\n if (probe.status !== 402) {\n return probe;\n }\n\n let body: unknown;\n try {\n body = await probe.json();\n } catch (error) {\n throw new X402Error(\n `402 response body is not JSON: ${error instanceof Error ? error.message : 'unknown'}`,\n 'PAYMENT_FAILED',\n error\n );\n }\n\n const tokenType: TokenType = options.tokenType || 'usdc';\n const challenge = this.parse402(body, tokenType);\n const { version, offers } = challenge;\n if (offers.length === 0) {\n // Step 1 of the policy contract, and two different facts that used to be\n // one error. A seller that sent offers none of which this build can read is\n // asking for a scheme we do not implement; saying so names what it wanted,\n // where \"no usable payment options\" sends the caller hunting a bug in its\n // own code. A seller that sent none at all is the other fact, and keeps the\n // error it always had.\n const unreadableCount = challenge.unreadableCount ?? challenge.unreadable.length;\n if (unreadableCount > 0) {\n throw new PolicyRefusedError(noReadableOffer(challenge.unreadable));\n }\n throw new X402Error(\n '402 response offered no usable payment options',\n 'NO_ACCEPTABLE_PAYMENT'\n );\n }\n\n // The ceiling is deliberately NOT applied while selecting: if even the\n // cheapest offer is over budget the caller wants to be told the price, not\n // handed a vague \"nothing acceptable\".\n const chosen = options.select\n ? options.select(offers)\n : X402Client.cheapestOffer(offers);\n if (!chosen) {\n throw new X402Error(\n 'No payment option selected for the 402 challenge',\n 'NO_ACCEPTABLE_PAYMENT'\n );\n }\n\n if (options.maxAmount !== undefined) {\n const ceiling = ethers.parseUnits(options.maxAmount, chosen.decimals);\n if (BigInt(chosen.amount) > ceiling) {\n throw new X402Error(\n `Payment of ${ethers.formatUnits(chosen.amount, chosen.decimals)} exceeds ` +\n `maxAmount ${options.maxAmount} for ${url}`,\n 'PAYMENT_EXCEEDS_MAX',\n {\n amount: chosen.amount,\n decimals: chosen.decimals,\n maxAmount: options.maxAmount,\n }\n );\n }\n }\n\n // The policy, evaluated against THIS offer, before anything is signed. An\n // offer that diverges from a listing but sits inside an authorised policy\n // proceeds -- stopping to ask would turn every ordinary reprice into a halt --\n // and one that does not is refused with a concrete cause. The policy is never\n // widened to fit the offer, and there is no confirmation hook in this path.\n //\n // The whole challenge goes in, never just the offer: `validUntil` lives in\n // the challenge's `extensions`, and a call that takes the parts is how it gets\n // dropped.\n const decision = decideOnChallenge(this.purchasePolicy, challenge, chosen, {\n now: Math.floor(Date.now() / 1000),\n quote: options.advertised,\n });\n if (!decision.ok) {\n this.log('policy refused this offer', { cause: decision.refusal.code });\n this.emit('paymentFailed', {\n error: decision.refusal.message,\n code: 'POLICY_REFUSED',\n });\n throw new PolicyRefusedError(decision.refusal);\n }\n const approval: PolicyApproval = decision.approval;\n this.log('policy approved this offer', {\n versusQuote: approval.versusQuote.code,\n amount: String(approval.amount),\n });\n\n if (!chosen.chainName) {\n throw new X402Error(\n `402 asked for payment on unknown network '${chosen.network}'`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n // The policy just approved the offer's OWN asset, but `createPayment` signs\n // for whatever token `tokenType` resolves to on this chain -- and reads the\n // price at that token's decimals. With USDC on both sides they coincide,\n // which is why this never showed. They do not have to: a seller pricing in a\n // token that is not the configured one would get an approval for asset A and\n // a signature for asset B, at B's decimals, and the caller would believe a\n // budget it never actually enforced.\n //\n // Refused rather than silently re-pointed: which token to pay with is the\n // caller's decision, and guessing it from the seller's 402 is how a wallet\n // ends up signing for a token nobody chose.\n const configuredToken = getTokenConfig(chosen.chainName, tokenType);\n if (\n chosen.asset &&\n configuredToken &&\n canonicalRecipient(configuredToken.address) !== canonicalRecipient(chosen.asset)\n ) {\n throw new X402Error(\n `402 wants ${chosen.asset} on ${chosen.chainName}, but this client signs ` +\n `${configuredToken.address} (tokenType '${tokenType}'). Pass the tokenType ` +\n 'that matches the offer; signing the configured token would pay a ' +\n 'different asset than the one that was approved.',\n 'NO_ACCEPTABLE_PAYMENT',\n {\n offered: chosen.asset,\n wouldSign: configuredToken.address,\n tokenType,\n network: chosen.chainName,\n }\n );\n }\n\n if (chosen.chainName !== this.currentChainName) {\n await this.switchChain(chosen.chainName);\n }\n\n const payment = await this.createPayment({\n recipient: chosen.payTo,\n amount: ethers.formatUnits(chosen.amount, chosen.decimals),\n tokenType,\n network: chosen.chainName,\n x402Version: version,\n });\n\n // v1 servers read `X-PAYMENT`; v2 ones read `PAYMENT-SIGNATURE`. Both carry\n // the identical base64 payload, so sending both on a v2 retry costs nothing\n // and spares the caller from guessing which name the resource implemented.\n const paidHeaders: Record<string, string> = {\n ...X402Client.headersToRecord(options.init?.headers),\n 'X-PAYMENT': payment.paymentHeader,\n };\n if (version === 2) {\n paidHeaders['PAYMENT-SIGNATURE'] = payment.paymentHeader;\n }\n\n const paid = await doFetch(url, { ...options.init, method, headers: paidHeaders });\n\n // Approving did not spend: signing can fail and a settlement can be refused,\n // and a cumulative limit that counted attempts would lock a caller out of\n // money it never spent. A retry that came back as anything but another 402 is\n // the seller accepting the payment, which is the moment a caller records it --\n // by its own hand, in `onPaid`, never automatically here.\n if (paid.status !== 402) {\n options.onPaid?.(approval);\n }\n return paid;\n }\n\n /**\n * Normalise a 402 body into its envelope version, its payment offers, the ones\n * it could not read, and the challenge's `extensions`.\n *\n * Reads both spec shapes -- `{x402Version, accepts: [...]}` and the non-spec\n * one where a lone requirement sits at the top level -- and both dialects of\n * the price field (`maxAmountRequired` in v1, `amount` in v2).\n *\n * **`accepts` is a list, so one unreadable entry does not sink the list.** A\n * seller offering `exact` alongside a scheme this build does not implement used\n * to be unpayable in the Rust crate, and the buyer never learned there was a\n * perfectly payable offer right there. The readable ones are kept and the\n * others are counted by scheme name, so a refusal can say what the seller\n * offered instead of \"could not parse\". Discovering the service keeps working\n * even when buying it automatically does not.\n *\n * Returns the WHOLE challenge on purpose: handing `offers` alone downstream is\n * what dropped the seller's `validUntil` on the floor in Rust for a full commit\n * with every unit test green.\n */\n private parse402(\n body: unknown,\n tokenType: TokenType\n ): ReadChallenge & { version: X402Version } {\n const doc = (body ?? {}) as Record<string, unknown>;\n const version: X402Version = Number(doc.x402Version) === 2 ? 2 : 1;\n\n const rawAccepts = Array.isArray(doc.accepts)\n ? doc.accepts\n : doc.payTo\n ? [doc]\n : [];\n\n const offers: X402PaymentOffer[] = [];\n const unreadable: string[] = [];\n let unreadableCount = 0;\n\n /** Count an entry this build cannot pay, by scheme name when it has one. */\n const cannotRead = (accept: Record<string, unknown> | null) => {\n unreadableCount += 1;\n const scheme = accept?.scheme;\n if (typeof scheme === 'string' && scheme) unreadable.push(scheme);\n };\n\n for (const entry of rawAccepts) {\n if (!entry || typeof entry !== 'object') {\n cannotRead(null);\n continue;\n }\n const accept = entry as Record<string, unknown>;\n\n // The scheme first, so a well-formed offer in a scheme we cannot pay is\n // counted by the NAME the seller used -- the informative half of rule 7 --\n // instead of being reported for whichever field it also happened to omit.\n //\n // An ABSENT scheme is unreadable, not `exact`. Rust requires the field, so a\n // challenge without it fails to deserialise there, and a buyer that guessed\n // `exact` would sign under a scheme the seller never actually named -- which\n // is the same hole as signing a named one we cannot present, minus the\n // evidence. It is counted (`unreadableCount`) without a name, because it has\n // none to report.\n //\n // Note this is deliberately ASYMMETRIC with the seller side of this SDK,\n // where a missing scheme reads as `exact` (\"the default, not an override\",\n // `src/backend/index.ts`). A seller is lenient about what it accepts; a\n // buyer is strict about what it signs.\n const declaredScheme = accept.scheme;\n if (\n typeof declaredScheme !== 'string' ||\n !declaredScheme ||\n !KNOWN_SCHEMES.has(declaredScheme) ||\n !CLIENT_PAYABLE_SCHEMES.has(declaredScheme)\n ) {\n cannotRead(accept);\n continue;\n }\n\n const amount = accept.amount ?? accept.maxAmountRequired;\n const payTo = accept.payTo;\n const network = accept.network;\n if (amount === undefined || amount === null) {\n cannotRead(accept);\n continue;\n }\n if (typeof payTo !== 'string' || !payTo) {\n cannotRead(accept);\n continue;\n }\n if (typeof network !== 'string' || !network) {\n cannotRead(accept);\n continue;\n }\n\n const chainName = getChainByName(network) ? network : caip2ToChain(network);\n\n offers.push({\n network,\n chainName,\n asset: typeof accept.asset === 'string' ? accept.asset : undefined,\n amount: String(amount),\n decimals: X402Client.offerDecimals(chainName, tokenType),\n payTo,\n raw: accept,\n });\n }\n\n const extensions =\n doc.extensions && typeof doc.extensions === 'object' && !Array.isArray(doc.extensions)\n ? (doc.extensions as Record<string, unknown>)\n : undefined;\n\n return { version, offers, unreadable, unreadableCount, extensions };\n }\n\n /**\n * Decimals to read an offer's atomic `amount` with.\n *\n * Not cosmetic: BSC USDC has 18 and everyone else's has 6, so reading every\n * price at 6 makes one chain look 10^12 times cheaper than it is and the\n * cheapest offer gets chosen wrong. Falls back to 6 only when the chain is\n * unknown -- and an unknown chain cannot be paid anyway.\n */\n private static offerDecimals(chainName: string | null, tokenType: TokenType): number {\n if (!chainName) return 6;\n const token = getTokenConfig(chainName, tokenType);\n if (token) return token.decimals;\n return getChainByName(chainName)?.usdc.decimals ?? 6;\n }\n\n /** Cheapest offer, compared across chains at a common scale. */\n private static cheapestOffer(offers: X402PaymentOffer[]): X402PaymentOffer {\n return offers.reduce((best, offer) =>\n X402Client.scaled(offer) < X402Client.scaled(best) ? offer : best\n );\n }\n\n /** An offer's price scaled to 18 decimals, so BigInt comparison is exact. */\n private static scaled(offer: X402PaymentOffer): bigint {\n const exponent = 18 - offer.decimals;\n const value = BigInt(offer.amount);\n return exponent >= 0\n ? value * 10n ** BigInt(exponent)\n : value / 10n ** BigInt(-exponent);\n }\n\n /** Flatten whatever `HeadersInit` shape the caller passed into a record. */\n private static headersToRecord(init?: HeadersInit): Record<string, string> {\n if (!init) return {};\n if (Array.isArray(init)) return Object.fromEntries(init);\n const maybeHeaders = init as Headers;\n if (typeof maybeHeaders.forEach === 'function') {\n const out: Record<string, string> = {};\n maybeHeaders.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n }\n return { ...(init as Record<string, string>) };\n }\n\n /**\n * Check USDC balance on current chain\n */\n async getBalance(): Promise<string> {\n if (!this.connectedAddress || !this.currentChainName) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const chain = getChainByName(this.currentChainName);\n if (!chain) {\n throw new X402Error(`Chain ${this.currentChainName} not found`, 'CHAIN_NOT_SUPPORTED');\n }\n\n switch (chain.networkType) {\n case 'evm':\n return this.getEVMBalance(chain);\n default:\n if (this.walletAdapter?.networkType === chain.networkType) {\n return this.walletAdapter.getBalance(chain);\n }\n throw new X402Error(\n `Balance check for ${chain.networkType} requires the appropriate provider`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n }\n\n // ============================================================================\n // PUBLIC API - Getters\n // ============================================================================\n\n /**\n * Get current wallet state\n */\n getState(): WalletState {\n return {\n connected: this.connectedAddress !== null,\n address: this.connectedAddress,\n chainId: this.currentChainId,\n network: this.currentChainName,\n networkType: this.currentNetwork,\n balance: null, // Call getBalance() separately\n };\n }\n\n /**\n * Get connected wallet address\n */\n getAddress(): string | null {\n return this.connectedAddress;\n }\n\n /**\n * Get current chain ID\n */\n getChainId(): number | null {\n return this.currentChainId;\n }\n\n /**\n * Get current chain name\n */\n getChainName(): string | null {\n return this.currentChainName;\n }\n\n /**\n * Get current chain display name\n */\n getChainDisplayName(): string | null {\n if (!this.currentChainName) return null;\n const chain = getChainByName(this.currentChainName);\n return chain?.displayName ?? null;\n }\n\n /**\n * Check if wallet is connected\n */\n isConnected(): boolean {\n return this.connectedAddress !== null;\n }\n\n /**\n * Get list of enabled chains\n */\n getEnabledChains(): ChainConfig[] {\n return getEnabledChains();\n }\n\n /**\n * Get chain config by name\n */\n getChain(name: string): ChainConfig | undefined {\n return getChainByName(name);\n }\n\n // ============================================================================\n // PUBLIC API - Events\n // ============================================================================\n\n /**\n * Subscribe to an event\n */\n on<E extends X402Event>(event: E, handler: X402EventHandler<E>): () => void {\n if (!this.eventHandlers.has(event)) {\n this.eventHandlers.set(event, new Set());\n }\n this.eventHandlers.get(event)!.add(handler as X402EventHandler<X402Event>);\n\n // Return unsubscribe function\n return () => this.off(event, handler);\n }\n\n /**\n * Unsubscribe from an event\n */\n off<E extends X402Event>(event: E, handler: X402EventHandler<E>): void {\n this.eventHandlers.get(event)?.delete(handler as X402EventHandler<X402Event>);\n }\n\n // ============================================================================\n // PRIVATE - EVM Wallet Connection\n // ============================================================================\n\n /**\n * Connect an SVM chain (Solana, Fogo) through the Phantom-backed provider.\n *\n * The provider is imported lazily: `@solana/web3.js` and `@solana/spl-token`\n * are OPTIONAL peer dependencies, so an EVM-only consumer must never pay for\n * them at module load. They are resolved only once someone actually asks for\n * an SVM chain.\n */\n private async connectSVMWallet(chain: ChainConfig): Promise<string> {\n const { SVMProvider } = await import('../providers/solana');\n const adapter = new SVMProvider();\n\n // SVMProvider.connect() takes no chain: one Phantom session serves every\n // SVM chain, and the chain is passed per call via chainConfig.\n const address = await adapter.connect();\n\n this.walletAdapter = adapter;\n this.provider = null;\n this.signer = null;\n this.connectedAddress = address;\n this.currentChainId = chain.chainId;\n this.currentNetwork = chain.networkType;\n this.currentChainName = chain.name;\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('SVM wallet connected', { address, chain: chain.name });\n\n return address;\n }\n\n private async connectEVMWallet(chain: ChainConfig): Promise<string> {\n // Check for injected provider\n if (typeof window === 'undefined' || !window.ethereum) {\n throw new X402Error(\n 'No Ethereum wallet found. Please install MetaMask or another EVM wallet.',\n 'WALLET_NOT_FOUND'\n );\n }\n\n try {\n this.provider = new ethers.BrowserProvider(window.ethereum);\n\n // Request account access\n await this.provider.send('eth_requestAccounts', []);\n\n // Switch to target chain\n await this.switchEVMChain(chain);\n\n // Get signer and address\n this.signer = await this.provider.getSigner();\n this.connectedAddress = await this.signer.getAddress();\n this.currentChainId = chain.chainId;\n this.currentNetwork = 'evm';\n this.currentChainName = chain.name;\n\n // Setup event listeners\n this.setupEVMEventListeners();\n\n const state = this.getState();\n this.emit('connect', state);\n this.log('EVM wallet connected', { address: this.connectedAddress, chain: chain.name });\n\n return this.connectedAddress;\n } catch (error: unknown) {\n if (error instanceof Error) {\n if (error.message.includes('User rejected') || (error as { code?: number }).code === 4001) {\n throw new X402Error('Connection rejected by user', 'WALLET_CONNECTION_REJECTED');\n }\n }\n throw new X402Error(\n `Failed to connect wallet: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'UNKNOWN_ERROR',\n error\n );\n }\n }\n\n private async switchEVMChain(chain: ChainConfig): Promise<void> {\n if (!this.provider) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n try {\n await this.provider.send('wallet_switchEthereumChain', [{ chainId: chain.chainIdHex }]);\n } catch (switchError: unknown) {\n // Chain not added - try to add it\n if ((switchError as { code?: number }).code === 4902) {\n try {\n await this.provider.send('wallet_addEthereumChain', [\n {\n chainId: chain.chainIdHex,\n chainName: chain.displayName,\n nativeCurrency: chain.nativeCurrency,\n rpcUrls: [chain.rpcUrl],\n blockExplorerUrls: [chain.explorerUrl],\n },\n ]);\n } catch (addError) {\n throw new X402Error(\n `Failed to add ${chain.displayName} network`,\n 'CHAIN_SWITCH_REJECTED',\n addError\n );\n }\n } else if ((switchError as { code?: number }).code === 4001) {\n throw new X402Error('Network switch rejected by user', 'CHAIN_SWITCH_REJECTED');\n } else {\n throw new X402Error(\n `Failed to switch to ${chain.displayName}`,\n 'CHAIN_SWITCH_REJECTED',\n switchError\n );\n }\n }\n\n this.currentChainId = chain.chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId: chain.chainId, chainName: chain.name });\n }\n\n private setupEVMEventListeners(): void {\n if (typeof window === 'undefined' || !window.ethereum) return;\n\n window.ethereum.on?.('accountsChanged', ((...args: unknown[]) => {\n const accounts = args[0] as string[];\n if (accounts.length === 0) {\n this.disconnect();\n } else if (accounts[0] !== this.connectedAddress) {\n this.connectedAddress = accounts[0];\n this.emit('accountChanged', { address: accounts[0] });\n }\n }) as (...args: unknown[]) => void);\n\n window.ethereum.on?.('chainChanged', ((...args: unknown[]) => {\n const chainIdHex = args[0] as string;\n const chainId = parseInt(chainIdHex, 16);\n const chain = getChainById(chainId);\n if (chain) {\n this.currentChainId = chainId;\n this.currentChainName = chain.name;\n this.emit('chainChanged', { chainId, chainName: chain.name });\n }\n }) as (...args: unknown[]) => void);\n }\n\n // ============================================================================\n // PRIVATE - EVM Payment Creation\n // ============================================================================\n\n private async createEVMPayment(paymentInfo: PaymentInfo, chain: ChainConfig): Promise<PaymentResult> {\n if (!this.signer) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n // Get recipient address for EVM\n const recipient = this.getRecipientForNetwork(paymentInfo, 'evm');\n\n // Validate recipient address - prevents empty/invalid addresses\n validateRecipient(recipient, 'evm');\n\n // Which stablecoin to charge. Defaults to USDC so existing callers are\n // unaffected; anything else is resolved from the chain's token registry.\n const tokenType: TokenType = paymentInfo.tokenType || 'usdc';\n const token = getTokenConfig(chain.name, tokenType);\n if (!token) {\n throw new X402Error(\n `Token ${tokenType} not supported on ${chain.name}`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n // Generate random nonce\n const nonceBytes = new Uint8Array(32);\n if (typeof window !== 'undefined' && window.crypto) {\n window.crypto.getRandomValues(nonceBytes);\n } else {\n for (let i = 0; i < 32; i++) {\n nonceBytes[i] = Math.floor(Math.random() * 256);\n }\n }\n const nonce = ethers.hexlify(nonceBytes);\n\n // Set validity window (5 minutes for congested networks, 1 minute otherwise)\n const validAfter = 0;\n const validityWindowSeconds = chain.name === 'base' ? 300 : 60;\n const validBefore = Math.floor(Date.now() / 1000) + validityWindowSeconds;\n\n // EIP-712 domain of the token being charged\n const domain = {\n name: token.name,\n version: token.version,\n chainId: chain.chainId,\n verifyingContract: token.address,\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 // Parse amount in the token's own decimals\n const value = ethers.parseUnits(paymentInfo.amount, token.decimals);\n const from = await this.signer.getAddress();\n const to = ethers.getAddress(recipient);\n\n // Message to sign\n const message = {\n from,\n to,\n value,\n validAfter,\n validBefore,\n nonce,\n };\n\n this.log('Signing EIP-712 message...', { domain, message });\n\n // Sign the EIP-712 message\n let signature: string;\n try {\n signature = await this.signer.signTypedData(domain, types, message);\n } catch (error: unknown) {\n if (error instanceof Error && (error.message.includes('User rejected') || (error as { code?: number }).code === 4001)) {\n throw new X402Error('Signature rejected by user', 'SIGNATURE_REJECTED');\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 const sig = ethers.Signature.from(signature);\n\n // Construct payload\n const payload: EVMPaymentPayload = {\n from,\n to,\n value: value.toString(),\n validAfter,\n validBefore,\n nonce,\n v: sig.v,\n r: sig.r,\n s: sig.s,\n chainId: chain.chainId,\n token: token.address,\n };\n\n // Encode as X-PAYMENT header. The 402 wins over the config when it spoke:\n // `x402Version: 'auto'` means \"whatever the resource asked for\".\n const paymentHeader = this.encodeEVMPaymentHeader(\n payload,\n chain,\n paymentInfo.x402Version\n );\n\n this.emit('paymentSigned', { paymentHeader });\n\n const result: PaymentResult = {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: chain.name,\n payer: from,\n };\n\n this.emit('paymentCompleted', result);\n this.log('Payment created successfully', { network: chain.name, from });\n\n return result;\n }\n\n /**\n * Build a payment through a non-EVM {@link WalletAdapter}.\n *\n * The adapter signs and returns its own payload; encoding that payload into\n * the X-PAYMENT header is network-specific, so it stays with the provider\n * that produced it. Version resolution matches the EVM path exactly: a hint\n * read off the resource's own 402 wins over the client config.\n */\n private async createAdapterPayment(\n paymentInfo: PaymentInfo,\n chain: ChainConfig\n ): Promise<PaymentResult> {\n const adapter = this.walletAdapter;\n if (!adapter) {\n throw new X402Error('Wallet not connected', 'WALLET_NOT_CONNECTED');\n }\n\n const encode = (adapter as { encodePaymentHeader?: (p: string, c: ChainConfig, v: X402Version) => string })\n .encodePaymentHeader;\n if (typeof encode !== 'function') {\n throw new X402Error(\n `The ${adapter.name} adapter cannot encode an X-PAYMENT header`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n\n const signed = await adapter.signPayment(paymentInfo, chain);\n const version = paymentInfo.x402Version ?? (this.config.x402Version === 2 ? 2 : 1);\n const paymentHeader = encode.call(adapter, signed, chain, version);\n\n this.emit('paymentSigned', { paymentHeader });\n\n const result: PaymentResult = {\n success: true,\n paymentHeader,\n headers: {\n 'X-PAYMENT': paymentHeader,\n 'PAYMENT-SIGNATURE': paymentHeader,\n },\n network: chain.name,\n payer: adapter.getAddress() ?? undefined,\n };\n\n this.emit('paymentCompleted', result);\n this.log('Payment created successfully', { network: chain.name, adapter: adapter.name });\n\n return result;\n }\n\n private encodeEVMPaymentHeader(\n payload: EVMPaymentPayload,\n chain: ChainConfig,\n versionHint?: X402Version\n ): string {\n // Reconstruct full signature from v, r, s\n const fullSignature = payload.r + payload.s.slice(2) + payload.v.toString(16).padStart(2, '0');\n\n // Determine version to use. A hint read off the resource's own 402 wins;\n // with no hint we fall back to the config (default v1 for compatibility).\n const version = versionHint ?? (this.config.x402Version === 2 ? 2 : 1);\n\n // Build the payload data\n const payloadData: X402EVMPayload = {\n signature: fullSignature,\n authorization: {\n from: payload.from,\n to: payload.to,\n value: payload.value,\n validAfter: payload.validAfter.toString(),\n validBefore: payload.validBefore.toString(),\n nonce: payload.nonce,\n },\n };\n\n if (this.config.includeTokenMetadata) {\n const token = buildTokenMetadata(chain.name, payload.token);\n if (!token) {\n throw new X402Error(\n `Token ${payload.token} is not in the registry for ${chain.name}; cannot build token metadata`,\n 'CHAIN_NOT_SUPPORTED'\n );\n }\n payloadData.token = token;\n }\n\n // Format in x402 standard format (v1 or v2)\n const x402Payload = version === 2\n ? {\n x402Version: 2 as const,\n scheme: 'exact' as const,\n network: chainToCAIP2(chain.name), // CAIP-2 format for v2\n payload: payloadData,\n }\n : {\n x402Version: 1 as const,\n scheme: 'exact' as const,\n network: chain.name, // Plain chain name for v1\n payload: payloadData,\n };\n\n // Base64 encode (UTF-8 safe: token domain names like `USD₮0` are not ASCII)\n return encodeBase64Json(x402Payload);\n }\n\n // ============================================================================\n // PRIVATE - EVM Balance Check\n // ============================================================================\n\n private async getEVMBalance(chain: ChainConfig): Promise<string> {\n // Use public RPC for balance check (more reliable than wallet provider)\n const publicProvider = new ethers.JsonRpcProvider(chain.rpcUrl);\n\n const usdcAbi = ['function balanceOf(address owner) view returns (uint256)'];\n const usdcContract = new ethers.Contract(chain.usdc.address, usdcAbi, publicProvider);\n\n try {\n const balance = await usdcContract.balanceOf(this.connectedAddress);\n const formatted = ethers.formatUnits(balance, chain.usdc.decimals);\n return parseFloat(formatted).toFixed(2);\n } catch {\n return '0.00';\n }\n }\n\n // ============================================================================\n // PRIVATE - Utilities\n // ============================================================================\n\n private getRecipientForNetwork(paymentInfo: PaymentInfo, network: NetworkType): string {\n // Map SVM to solana for recipient lookup\n const lookupNetwork = network === 'svm' ? 'solana' : network;\n const recipients = paymentInfo.recipients as Record<string, string> | undefined;\n if (recipients?.[lookupNetwork]) {\n return recipients[lookupNetwork];\n }\n return paymentInfo.recipient;\n }\n\n private emit<E extends X402Event>(event: E, data: X402EventData[E]): void {\n this.eventHandlers.get(event)?.forEach(handler => {\n try {\n handler(data);\n } catch (error) {\n console.error(`Error in ${event} handler:`, error);\n }\n });\n }\n\n private log(message: string, data?: unknown): void {\n if (this.config.debug) {\n console.log(`[X402Client] ${message}`, data ?? '');\n }\n }\n}\n\n// Type augmentation for window.ethereum\ndeclare global {\n interface Window {\n ethereum?: {\n request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;\n on?: (event: string, handler: (...args: unknown[]) => void) => void;\n removeListener?: (event: string, handler: (...args: unknown[]) => void) => void;\n };\n }\n}\n","/**\n * uvd-x402-sdk - What this buyer is allowed to sign, decided before it signs.\n *\n * # The rule this module exists to enforce\n *\n * A catalog listing is a claim somebody else made about their own price. The\n * `402` that comes back from the actual request is the offer. They can differ,\n * legitimately: a seller may have repriced, and the listing may be a copy of a\n * copy. So the buying decision cannot be made against the listing. It has to be\n * made against **the offer in hand**, every time, before anything is signed.\n *\n * Two things follow, and both are load-bearing:\n *\n * - **A divergence from the listing is not, by itself, a refusal.** If the offer\n * costs more than the catalog said but still sits inside a policy the operator\n * already authorised, the payment proceeds. Stopping to ask would turn every\n * ordinary reprice into a halt, and an agent that halts on ordinary commerce\n * is an agent nobody can leave running. There is no human-confirmation hook in\n * this path.\n * - **A policy is never widened to fit an offer.** Not by a byte, not once, not\n * \"because the seller says so\". There is deliberately no method on this type\n * that raises a limit from inside an evaluation. If the offer exceeds what was\n * authorised the answer is a refusal with a concrete cause, and the caller\n * decides whether to authorise more.\n *\n * # Order of evaluation\n *\n * Fixed, and part of the contract, because the FIRST failing check is the one\n * reported and a caller branches on it:\n *\n * 1. Was any offer readable at all? -> `no-readable-offer`\n * 2. Has it expired? -> `offer-expired`\n * 3. Is the recipient one we are willing to pay? -> `recipient-not-permitted`\n * 4. Was its asset budgeted at all? -> `asset-not-budgeted`\n * 5. Does it exceed the per-payment limit for that asset? -> `per-payment-limit`\n * 6. Does it exceed what remains of the cumulative limit? -> `cumulative-limit`\n *\n * The comparison against the listing is made LAST and refuses nothing: it is\n * evidence for the caller, never a gate.\n *\n * This is the same contract the Rust facilitator's `x402-reqwest` crate\n * implements (`PurchasePolicy`, release 2.25.0), written down once so a buyer in\n * either language refuses the same payments for the same stated reasons.\n *\n * @module\n */\n\nimport { X402Error } from './types';\nimport type { X402PaymentOffer } from './types';\n\n// ============================================================================\n// The offer-validity extension\n// ============================================================================\n\n/**\n * Extension key under which a seller declares how long its offer stands.\n *\n * Defined once, here, and read by nobody else's constant: a seller and a buyer\n * naming different keys have nothing to say to each other. The version is IN\n * the key because the offer-and-receipt transport can still change, and a value\n * read from an unversioned key could never be compared with anything later. A\n * key we do not recognise is ignored, which means \"no declared expiry\" -- a\n * different thing from \"expired\".\n */\nexport const OFFER_VALIDITY_EXTENSION = 'offer-receipt/1';\n\n/**\n * Read `validUntil` (Unix seconds) out of a 402 challenge's `extensions`.\n *\n * Shape: `extensions[\"offer-receipt/1\"].info.validUntil`. The `{info, schema}`\n * envelope is the one every merged x402 extension uses; reading the number from\n * anywhere else would be reading a field nobody agreed to publish.\n *\n * Anything unreadable is `undefined`, **never zero**: \"the seller said\n * something we could not read\" must not become \"this offer expired in 1970\".\n * A string, a float, a negative, a number past `Number.MAX_SAFE_INTEGER` -- all\n * unreadable, all absent.\n */\nexport function offerValidUntil(\n extensions: Record<string, unknown> | undefined | null\n): number | undefined {\n if (!extensions || typeof extensions !== 'object') return undefined;\n const entry = (extensions as Record<string, unknown>)[OFFER_VALIDITY_EXTENSION];\n if (!entry || typeof entry !== 'object') return undefined;\n const info = (entry as Record<string, unknown>).info;\n if (!info || typeof info !== 'object') return undefined;\n const value = (info as Record<string, unknown>).validUntil;\n if (typeof value !== 'number') return undefined;\n if (!Number.isSafeInteger(value) || value < 0) return undefined;\n return value;\n}\n\n// ============================================================================\n// Addresses\n// ============================================================================\n\n/**\n * Canonical form of a recipient or token address, for comparison.\n *\n * # Why this is not `toLowerCase()`\n *\n * It was, in the Rust crate, and that is only correct for one family. EVM\n * addresses are hex and arrive both checksummed and lowercase, so folding case\n * is right and necessary. **Base58 is case-sensitive** -- Solana and XRPL\n * addresses use both cases as distinct symbols -- so lowercasing one does not\n * produce the same address spelled differently, it produces a string that is not\n * an address.\n *\n * An allowlist written in the seller's own spelling would then never match, and\n * every payment to a legitimate Solana payee would be refused with\n * `recipient-not-permitted`. Worse in the other direction: two distinct base58\n * addresses can fold to the same lowercase string, so an allowlist could admit\n * an address nobody put on it.\n *\n * So: hex is folded, everything else is compared exactly.\n */\nexport function canonicalRecipient(address: string): string {\n const trimmed = address.trim();\n const rest =\n trimmed.startsWith('0x') || trimmed.startsWith('0X') ? trimmed.slice(2) : null;\n const isHex = rest !== null && rest.length > 0 && /^[0-9a-fA-F]+$/.test(rest);\n return isHex ? trimmed.toLowerCase() : trimmed;\n}\n\n// ============================================================================\n// Assets\n// ============================================================================\n\n/**\n * A token on a network -- the unit a budget is denominated in.\n *\n * Both halves are required. The same USDC contract address on two networks is\n * two different assets, and a budget for one is not a budget for the other: the\n * EVM signer takes its EIP-712 domain from the seller's own `extra`, so it will\n * sign for whatever token and network the seller names.\n */\nexport interface PolicyAsset {\n /**\n * SDK chain name (`'base'`) when the 402's network resolved to one, otherwise\n * the network string exactly as the 402 wrote it.\n *\n * Resolving first is what lets one written policy cover both 402 dialects:\n * a v1 challenge says `base` and a v2 one says `eip155:8453`, and a budget\n * keyed on the raw string would silently miss half of a seller's offers.\n */\n network: string;\n /** Token contract address. Compared canonicalised, never raw. */\n address: string;\n}\n\n/**\n * Stable map key for an asset. Not part of the wire format; comparison only.\n *\n * The network is folded to lowercase because SDK chain names and CAIP-2 strings\n * are lowercase by convention, so `'Base'` and `'base'` are the same network\n * written two ways -- never two networks. Leaving the case in fails closed\n * (`asset-not-budgeted`, so no wrong payment), but it trips the operator over a\n * capital letter and the refusal would point at the budget instead of the typo.\n * The address keeps its by-family treatment: see {@link canonicalRecipient}.\n */\nexport function assetKey(asset: PolicyAsset): string {\n return `${asset.network.trim().toLowerCase()}|${canonicalRecipient(asset.address)}`;\n}\n\n/** Human form, for a refusal message. */\nfunction assetLabel(asset: PolicyAsset): string {\n return asset.address ? `${asset.address} on ${asset.network}` : `(no asset declared) on ${asset.network}`;\n}\n\n/**\n * The asset an offer is priced in.\n *\n * An offer that declares no `asset` yields an empty address, which no budget can\n * ever hold -- {@link PurchasePolicy.perPayment} rejects an empty address -- so\n * such an offer is refused with `asset-not-budgeted` unless unlisted assets were\n * explicitly permitted. That is the safe direction: an unnamed token is a token\n * nobody budgeted for.\n */\nexport function offerAsset(offer: X402PaymentOffer): PolicyAsset {\n return {\n network: offer.chainName ?? offer.network,\n address: typeof offer.asset === 'string' ? offer.asset : '',\n };\n}\n\n// ============================================================================\n// Refusals\n// ============================================================================\n\n/**\n * Closed vocabulary of reasons a payment was not signed, in kebab-case, so an\n * SDK in another language branches on it without parsing English.\n *\n * There is no `other`: a refusal a caller cannot interpret is a refusal it will\n * paper over.\n */\nexport type PolicyRefusalCode =\n | 'no-readable-offer'\n | 'offer-expired'\n | 'recipient-not-permitted'\n | 'asset-not-budgeted'\n | 'per-payment-limit'\n | 'cumulative-limit';\n\n/**\n * Why a payment was not signed. Every variant carries the numbers that caused\n * it, so a caller can log the decision without re-deriving it.\n */\nexport type PolicyRefusal =\n | {\n code: 'no-readable-offer';\n /** Scheme names the seller offered, for the ones this build cannot read. */\n offered: string[];\n message: string;\n }\n | { code: 'offer-expired'; validUntil: number; now: number; message: string }\n | { code: 'recipient-not-permitted'; payTo: string; message: string }\n | { code: 'asset-not-budgeted'; asset: PolicyAsset; message: string }\n | {\n code: 'per-payment-limit';\n requested: bigint;\n allowed: bigint;\n asset: PolicyAsset;\n message: string;\n }\n | {\n code: 'cumulative-limit';\n requested: bigint;\n spent: bigint;\n wouldTotal: bigint;\n allowed: bigint;\n asset: PolicyAsset;\n message: string;\n };\n\n/**\n * A 402 whose offers this build could not read, turned into a refusal that says\n * so.\n *\n * The point is the message. A caller that learns the seller offered\n * `batch-settlement` knows to look for a facilitator that implements it, where\n * \"could not parse the response\" would have sent it looking for a bug in its own\n * code. Discovering the service keeps working even though buying it\n * automatically does not.\n */\nexport function noReadableOffer(offered: string[]): PolicyRefusal {\n return {\n code: 'no-readable-offer',\n offered,\n message:\n 'no offer in this challenge is one this build can pay; offered: ' +\n JSON.stringify(offered),\n };\n}\n\n/**\n * Error thrown on the real payment path when the policy refuses.\n *\n * Extends {@link X402Error}, so a consumer already catching `X402Error` keeps\n * catching this; the typed cause is on {@link PolicyRefusedError.refusal} and\n * its stable code on `refusal.code`.\n */\nexport class PolicyRefusedError extends X402Error {\n public readonly refusal: PolicyRefusal;\n\n constructor(refusal: PolicyRefusal) {\n super(`payment refused by policy: ${refusal.message}`, 'POLICY_REFUSED', refusal);\n this.name = 'PolicyRefusedError';\n this.refusal = refusal;\n }\n\n /** Stable kebab code of the refusal, for branching. */\n get policyCode(): PolicyRefusalCode {\n return this.refusal.code;\n }\n}\n\n// ============================================================================\n// The listing, and how the offer compares to it\n// ============================================================================\n\n/**\n * What a catalog listing advertised, for comparison against the real offer.\n *\n * Optional throughout. A buyer that never read a listing simply evaluates the\n * offer against its policy, which is the same decision with one fewer input.\n */\nexport interface AdvertisedQuote {\n asset: PolicyAsset;\n /** Price in the token's own atomic units. */\n amount: bigint;\n}\n\n/** How the offer in hand compares to what the catalog advertised. */\nexport type QuoteComparison =\n | { code: 'not-compared' }\n | { code: 'matches' }\n | { code: 'amount-differs'; advertised: bigint; offered: bigint }\n /**\n * A different asset entirely. The same number in another currency is not the\n * same price, so there is nothing to compare -- and no number is compared.\n */\n | { code: 'different-asset'; advertised: PolicyAsset; offered: PolicyAsset };\n\n/** A payment this policy permits, and what it noticed on the way. */\nexport interface PolicyApproval {\n asset: PolicyAsset;\n /** Price in the token's own atomic units. */\n amount: bigint;\n /**\n * How the offer compared to the listing, when there was one. Carried so a\n * caller can log or surface it; it never changed the decision.\n */\n versusQuote: QuoteComparison;\n}\n\n/** The outcome of an evaluation. Explicit, so no caller needs a `try`. */\nexport type PolicyDecision =\n | { ok: true; approval: PolicyApproval }\n | { ok: false; refusal: PolicyRefusal };\n\n/** Inputs to {@link PurchasePolicy.evaluate} besides the offer itself. */\nexport interface EvaluateOptions {\n /**\n * Unix seconds. Passed rather than read so the decision is testable at an\n * exact instant: money decisions that depend on a hidden clock cannot be\n * pinned.\n */\n now: number;\n /** `validUntil` the seller declared, if any. See {@link offerValidUntil}. */\n validUntil?: number;\n /** What the catalog advertised, if the caller read a listing. */\n quote?: AdvertisedQuote;\n}\n\n// ============================================================================\n// The policy\n// ============================================================================\n\n/**\n * The spending rules a caller authorised in advance.\n *\n * Every builder returns a new policy that **shares the running total**: two\n * copies of one policy spend from the same purse, which is what makes a\n * cumulative limit mean anything when a client is copied per request.\n *\n * @example\n * ```ts\n * const USDC_BASE = { network: 'base', address: '0x8335...2913' };\n * const policy = PurchasePolicy.create()\n * .perPayment(USDC_BASE, 50_000n) // 0.05 USDC, atomic units\n * .cumulative(USDC_BASE, 1_000_000n) // 1 USDC total, for this policy's life\n * .onlyPay(['0xe4dc...e545']);\n *\n * const client = new X402Client({ defaultChain: 'base', policy });\n * ```\n */\nexport class PurchasePolicy {\n private readonly perPaymentLimits: Map<string, bigint>;\n private readonly cumulativeLimits: Map<string, bigint>;\n /** Shared by reference across every copy: one purse, many holders. */\n private readonly spentTotals: Map<string, bigint>;\n private readonly recipients: Set<string> | null;\n private readonly assetsByKey: Map<string, PolicyAsset>;\n private readonly unlistedAssetsAllowed: boolean;\n\n private constructor(\n perPaymentLimits: Map<string, bigint>,\n cumulativeLimits: Map<string, bigint>,\n spentTotals: Map<string, bigint>,\n recipients: Set<string> | null,\n assetsByKey: Map<string, PolicyAsset>,\n unlistedAssetsAllowed: boolean\n ) {\n this.perPaymentLimits = perPaymentLimits;\n this.cumulativeLimits = cumulativeLimits;\n this.spentTotals = spentTotals;\n this.recipients = recipients;\n this.assetsByKey = assetsByKey;\n this.unlistedAssetsAllowed = unlistedAssetsAllowed;\n }\n\n /**\n * A policy that pays nothing until it is told what it may pay.\n *\n * # Why the default is deny\n *\n * The limits are a map keyed by asset, and a map answers \"no entry\" for every\n * asset nobody thought of. Permitting on a missing entry means a budget in\n * USDC is **no budget at all** for any other token: a seller offering the same\n * resource priced in something unlisted walks straight past the ceiling, and\n * the wallet will sign it, because the EVM signer takes the EIP-712 domain\n * from the seller's own `extra` and will happily sign for a token and a\n * network it has never heard of.\n *\n * So an asset with no stated ceiling is refused. A caller that genuinely wants\n * to pay anything says so once, by name, with\n * {@link PurchasePolicy.allowUnlistedAssets}, and that sentence is then in\n * their code where a reader can find it.\n */\n static create(): PurchasePolicy {\n return new PurchasePolicy(new Map(), new Map(), new Map(), null, new Map(), false);\n }\n\n /**\n * A policy that permits an asset it was never told about.\n *\n * This is what {@link X402Client} holds when the caller supplied no policy,\n * and it exists for exactly one reason: this SDK had no budget before 2.89.0,\n * and turning one on silently would refuse payments that callers are making\n * today. Named rather than defaulted, so choosing it is visible. The asymmetry\n * is deliberate -- whoever sits down to WRITE a policy deserves the safe\n * default.\n */\n static permissive(): PurchasePolicy {\n return new PurchasePolicy(new Map(), new Map(), new Map(), null, new Map(), true);\n }\n\n /** Permit assets with no configured ceiling. */\n allowUnlistedAssets(): PurchasePolicy {\n return this.with({ unlistedAssetsAllowed: true });\n }\n\n /**\n * Refuse assets with no configured ceiling. The default; here so the intent\n * can be written down at a call site that wants it explicit.\n */\n denyUnlistedAssets(): PurchasePolicy {\n return this.with({ unlistedAssetsAllowed: false });\n }\n\n /** Most this policy will pay in ONE payment of `asset`, in atomic units. */\n perPayment(asset: PolicyAsset, amount: bigint): PurchasePolicy {\n const key = this.register(asset);\n const perPaymentLimits = new Map(this.perPaymentLimits);\n perPaymentLimits.set(key, requireCeiling(amount, 'perPayment'));\n return this.with({ perPaymentLimits });\n }\n\n /**\n * Most this policy will pay in `asset` in TOTAL, across every payment it\n * approves for as long as it lives.\n */\n cumulative(asset: PolicyAsset, amount: bigint): PurchasePolicy {\n const key = this.register(asset);\n const cumulativeLimits = new Map(this.cumulativeLimits);\n cumulativeLimits.set(key, requireCeiling(amount, 'cumulative'));\n return this.with({ cumulativeLimits });\n }\n\n /**\n * Restrict payment to a set of recipients.\n *\n * Addresses are canonicalised **by family**, not by lowercasing the string:\n * see {@link canonicalRecipient}.\n */\n onlyPay(recipients: Iterable<string>): PurchasePolicy {\n const set = new Set<string>();\n for (const r of recipients) set.add(canonicalRecipient(r));\n return this.with({ recipients: set });\n }\n\n /**\n * Total recorded so far for `asset`, in atomic units.\n *\n * A total that is not a sane bigint means something corrupted the purse.\n * Reporting zero would silently restore the caller's whole budget, so this\n * reports the CEILING instead: for money, the safe direction is to refuse,\n * never to permit.\n */\n spent(asset: PolicyAsset): bigint {\n const key = assetKey(asset);\n const value = this.spentTotals.get(key);\n if (value === undefined) return 0n;\n if (typeof value !== 'bigint' || value < 0n) {\n return this.cumulativeLimits.get(key) ?? 0n;\n }\n return value;\n }\n\n /**\n * Record that a payment actually happened.\n *\n * Separate from {@link PurchasePolicy.evaluate} on purpose. Signing can still\n * fail and a settlement can still be refused; a cumulative limit that counted\n * attempts rather than payments would lock a caller out of money it never\n * spent. Call this when a payment settled.\n *\n * A negative amount is ignored: handing budget back is not something a\n * settlement can do, and treating it as one would be a way to widen a policy\n * from outside.\n */\n recordSpend(asset: PolicyAsset, amount: bigint): void {\n if (typeof amount !== 'bigint' || amount <= 0n) return;\n const key = assetKey(asset);\n if (!this.assetsByKey.has(key)) this.assetsByKey.set(key, asset);\n const current = this.spent(asset);\n this.spentTotals.set(key, current + amount);\n }\n\n /**\n * Whether this policy pays an asset it holds no ceiling for. Read-only: there\n * is no setter that flips it from inside an evaluation.\n */\n get permitsUnlistedAssets(): boolean {\n return this.unlistedAssetsAllowed;\n }\n\n /**\n * Decide whether this offer may be signed. Steps 2 through 6 of the contract;\n * step 1 (`no-readable-offer`) is decided on the challenge, before an offer\n * exists to evaluate -- see {@link decideOnChallenge}.\n *\n * **Approving does not record the spend.** See\n * {@link PurchasePolicy.recordSpend}.\n */\n evaluate(offer: X402PaymentOffer, options: EvaluateOptions): PolicyDecision {\n const { now, validUntil, quote } = options;\n\n // 2. Expiry. Before anything about money: terms that have lapsed are not\n // terms, whatever they say. `validUntil === now` still stands -- it is the\n // last instant the offer is up.\n if (validUntil !== undefined && now > validUntil) {\n return {\n ok: false,\n refusal: {\n code: 'offer-expired',\n validUntil,\n now,\n message:\n `this offer expired at ${validUntil} (now ${now}); ` +\n 'ask the seller for new terms',\n },\n };\n }\n\n // 3. Recipient.\n if (this.recipients !== null) {\n const payTo = canonicalRecipient(offer.payTo);\n if (!this.recipients.has(payTo)) {\n return {\n ok: false,\n refusal: {\n code: 'recipient-not-permitted',\n payTo: offer.payTo,\n message: `this policy does not pay ${offer.payTo}`,\n },\n };\n }\n }\n\n const asset = offerAsset(offer);\n const key = assetKey(asset);\n const requested = readAmount(offer.amount);\n\n // 4. An asset nobody budgeted for. Checked BEFORE the ceilings, because the\n // ceilings are a map and a map has no opinion about a key it does not\n // hold -- which is precisely how an unlisted token would sail past a\n // budget that looks complete. And the caller has to be told \"budget that\n // asset\", not \"raise a ceiling that does not exist\".\n if (\n !this.unlistedAssetsAllowed &&\n !this.perPaymentLimits.has(key) &&\n !this.cumulativeLimits.has(key)\n ) {\n return {\n ok: false,\n refusal: {\n code: 'asset-not-budgeted',\n asset,\n message:\n `this policy has no budget for ${assetLabel(asset)}; ` +\n 'it pays only what it was told it may pay',\n },\n };\n }\n\n // 5. Per-payment ceiling.\n const perPaymentAllowed = this.perPaymentLimits.get(key);\n if (perPaymentAllowed !== undefined && requested > perPaymentAllowed) {\n return {\n ok: false,\n refusal: {\n code: 'per-payment-limit',\n requested,\n allowed: perPaymentAllowed,\n asset,\n message:\n `offer of ${requested} exceeds the per-payment limit of ` +\n `${perPaymentAllowed} for ${assetLabel(asset)}`,\n },\n };\n }\n\n // 6. Cumulative ceiling.\n const cumulativeAllowed = this.cumulativeLimits.get(key);\n if (cumulativeAllowed !== undefined) {\n const spent = this.spent(asset);\n const wouldTotal = spent + requested;\n if (wouldTotal > cumulativeAllowed) {\n return {\n ok: false,\n refusal: {\n code: 'cumulative-limit',\n requested,\n spent,\n wouldTotal,\n allowed: cumulativeAllowed,\n asset,\n message:\n `offer of ${requested} would take spend to ${wouldTotal}, past the ` +\n `cumulative limit of ${cumulativeAllowed} for ${assetLabel(asset)} ` +\n `(already spent ${spent})`,\n },\n };\n }\n }\n\n // The comparison against the listing is made LAST and refuses nothing. It is\n // evidence for the caller, not a gate: a seller repricing inside a policy the\n // operator already authorised is ordinary commerce.\n return {\n ok: true,\n approval: { asset, amount: requested, versusQuote: compareToQuote(asset, requested, quote) },\n };\n }\n\n /** Copy sharing the same purse. Cloning is what a per-request client does. */\n clone(): PurchasePolicy {\n return this.with({});\n }\n\n /**\n * Rebuild with some fields replaced, **always sharing `spentTotals`**. This is\n * the one place that decides copies share a purse, so it is the one place to\n * read when asking whether they do.\n */\n private with(changes: {\n perPaymentLimits?: Map<string, bigint>;\n cumulativeLimits?: Map<string, bigint>;\n recipients?: Set<string> | null;\n unlistedAssetsAllowed?: boolean;\n }): PurchasePolicy {\n return new PurchasePolicy(\n changes.perPaymentLimits ?? this.perPaymentLimits,\n changes.cumulativeLimits ?? this.cumulativeLimits,\n this.spentTotals,\n changes.recipients !== undefined ? changes.recipients : this.recipients,\n this.assetsByKey,\n changes.unlistedAssetsAllowed ?? this.unlistedAssetsAllowed\n );\n }\n\n /** Remember an asset's written form and reject one no budget could match. */\n private register(asset: PolicyAsset): string {\n if (!asset || typeof asset.address !== 'string' || asset.address.trim() === '') {\n throw new X402Error(\n 'A budget needs a token address; an asset with none can never match an offer',\n 'INVALID_CONFIG',\n { asset }\n );\n }\n if (typeof asset.network !== 'string' || asset.network.trim() === '') {\n throw new X402Error(\n 'A budget needs a network; the same address on two networks is two assets',\n 'INVALID_CONFIG',\n { asset }\n );\n }\n const key = assetKey(asset);\n this.assetsByKey.set(key, asset);\n return key;\n }\n}\n\n/** A ceiling has to be a non-negative bigint; anything else is a config bug. */\nfunction requireCeiling(amount: bigint, field: string): bigint {\n if (typeof amount !== 'bigint' || amount < 0n) {\n throw new X402Error(\n `${field} must be a non-negative bigint in atomic units`,\n 'INVALID_AMOUNT',\n { amount: String(amount) }\n );\n }\n return amount;\n}\n\n/**\n * An offer's price as a bigint.\n *\n * Arithmetic is bigint throughout, never `number`: atomic units of an 18-decimal\n * token pass `Number.MAX_SAFE_INTEGER` at 0.01 of a token, and a ceiling\n * compared as a float is a ceiling that rounds.\n *\n * An amount that is not a non-negative integer is read as the largest value we\n * can represent for the comparison, so it fails every ceiling rather than\n * passing as zero: a price we cannot read is not a price we may pay.\n */\nfunction readAmount(amount: string): bigint {\n const text = String(amount).trim();\n if (!/^\\d+$/.test(text)) return UNREADABLE_AMOUNT;\n return BigInt(text);\n}\n\n/**\n * Stand-in for a price we could not read. Absurdly large on purpose: it exceeds\n * every ceiling a caller would write, so an unreadable amount is refused by the\n * limit checks instead of sliding through as zero.\n */\nconst UNREADABLE_AMOUNT = (1n << 256n) - 1n;\n\nfunction compareToQuote(\n asset: PolicyAsset,\n requested: bigint,\n quote: AdvertisedQuote | undefined\n): QuoteComparison {\n if (!quote) return { code: 'not-compared' };\n if (assetKey(quote.asset) !== assetKey(asset)) {\n // Rule 4: a different asset is not the same price. No numbers are compared.\n return { code: 'different-asset', advertised: quote.asset, offered: asset };\n }\n if (quote.amount !== requested) {\n return { code: 'amount-differs', advertised: quote.amount, offered: requested };\n }\n return { code: 'matches' };\n}\n\n// ============================================================================\n// The whole decision, in one place\n// ============================================================================\n\n/** A 402 challenge as the buyer read it, whole. */\nexport interface ReadChallenge {\n /** Offers this build could read. */\n offers: X402PaymentOffer[];\n /**\n * Scheme names of the entries it could not. Rule 7: an `accepts` with one\n * unreadable entry KEEPS the readable ones and counts the others by scheme\n * name, so a refusal can say what the seller offered.\n */\n unreadable: string[];\n /**\n * How many entries were unreadable, which is not the same as how many could be\n * NAMED: an entry too broken to even carry a `scheme` still proves the seller\n * sent offers. Without it, a challenge whose only entry was nameless garbage\n * would read as \"the seller sent nothing\" -- a different fact, and the wrong\n * one to report. Defaults to `unreadable.length`.\n */\n unreadableCount?: number;\n /** The challenge's top-level `extensions`, where `validUntil` lives. */\n extensions?: Record<string, unknown>;\n}\n\n/** Inputs to {@link decideOnChallenge} besides the challenge. */\nexport interface DecideOptions {\n /** Unix seconds. Passed, never read, so the decision can be pinned in a test. */\n now: number;\n /** What the catalog advertised, if the caller read a listing. */\n quote?: AdvertisedQuote;\n}\n\n/**\n * The whole buying decision: all six steps, in the fixed order, against the\n * offer in hand.\n *\n * Takes the challenge WHOLE, deliberately. Passing `offers` alone is what\n * dropped the seller's `validUntil` on the floor in the Rust crate for a full\n * commit with every unit test green, and a signature that takes the parts\n * invites doing it again.\n *\n * Callable without a network stack on purpose: a decision that can only be\n * exercised by driving a real HTTP client is a decision nobody tests.\n *\n * @param offer - The offer already selected out of `challenge.offers`. Selection\n * is the caller's (cheapest, or its own `select`); this decides whether the\n * selected one may be paid.\n */\nexport function decideOnChallenge(\n policy: PurchasePolicy,\n challenge: ReadChallenge,\n offer: X402PaymentOffer | null,\n options: DecideOptions\n): PolicyDecision {\n // 1. Was any offer readable at all? A challenge that carried offers, none of\n // which this build can read, is not \"no matching payment method\": it is a\n // seller asking for a scheme we do not implement, and saying so names what\n // they wanted.\n const unreadableCount = challenge.unreadableCount ?? challenge.unreadable.length;\n if (challenge.offers.length === 0 && unreadableCount > 0) {\n return { ok: false, refusal: noReadableOffer(challenge.unreadable) };\n }\n if (!offer) {\n // Nothing selected out of a challenge that had readable offers, or a seller\n // that sent no offers at all. Either way there is no offer in hand to judge,\n // and the refusal names what the seller offered -- an empty list when it\n // offered nothing.\n return { ok: false, refusal: noReadableOffer(challenge.unreadable) };\n }\n return policy.evaluate(offer, {\n now: options.now,\n validUntil: offerValidUntil(challenge.extensions),\n quote: options.quote,\n });\n}\n","/**\n * uvd-x402-sdk - React Hooks\n *\n * Provides React hooks for easy integration with x402 payments.\n *\n * @example\n * ```tsx\n * import { X402Provider, useX402, useBalance, usePayment } from 'uvd-x402-sdk/react';\n *\n * function App() {\n * return (\n * <X402Provider config={{ defaultChain: 'base' }}>\n * <PaymentButton amount=\"10.00\" recipient=\"0x...\" />\n * </X402Provider>\n * );\n * }\n *\n * function PaymentButton({ amount, recipient }) {\n * const { connect, isConnected, address } = useX402();\n * const { balance, isLoading: balanceLoading } = useBalance();\n * const { pay, isPaying } = usePayment();\n *\n * if (!isConnected) {\n * return <button onClick={() => connect('base')}>Connect Wallet</button>;\n * }\n *\n * return (\n * <button\n * onClick={() => pay({ amount, recipient })}\n * disabled={isPaying}\n * >\n * Pay ${amount} USDC\n * </button>\n * );\n * }\n * ```\n */\n\nimport { createContext, useContext, useCallback, useState, useEffect, useMemo, type ReactNode } from 'react';\nimport { X402Client } from '../client';\nimport type {\n X402ClientConfig,\n WalletState,\n PaymentInfo,\n PaymentResult,\n ChainConfig,\n NetworkBalance,\n} from '../types';\nimport { getEnabledChains, getChainByName } from '../chains';\n\n// ============================================================================\n// CONTEXT\n// ============================================================================\n\ninterface X402ContextValue {\n client: X402Client;\n state: WalletState;\n connect: (chainName?: string) => Promise<string>;\n disconnect: () => Promise<void>;\n switchChain: (chainName: string) => Promise<void>;\n getBalance: () => Promise<string>;\n}\n\nconst X402Context = createContext<X402ContextValue | null>(null);\n\n// ============================================================================\n// PROVIDER\n// ============================================================================\n\ninterface X402ProviderProps {\n children: ReactNode;\n config?: X402ClientConfig;\n}\n\n/**\n * X402Provider - Context provider for x402 SDK\n *\n * Wrap your app with this provider to use the x402 hooks.\n */\nexport function X402Provider({ children, config }: X402ProviderProps) {\n const [client] = useState(() => new X402Client(config));\n const [state, setState] = useState<WalletState>(() => client.getState());\n\n useEffect(() => {\n // Subscribe to events\n const unsubConnect = client.on('connect', (newState) => {\n setState(newState);\n });\n\n const unsubDisconnect = client.on('disconnect', () => {\n setState(client.getState());\n });\n\n const unsubChainChanged = client.on('chainChanged', () => {\n setState(client.getState());\n });\n\n const unsubAccountChanged = client.on('accountChanged', () => {\n setState(client.getState());\n });\n\n return () => {\n unsubConnect();\n unsubDisconnect();\n unsubChainChanged();\n unsubAccountChanged();\n };\n }, [client]);\n\n const connect = useCallback(\n async (chainName?: string) => {\n const address = await client.connect(chainName);\n setState(client.getState());\n return address;\n },\n [client]\n );\n\n const disconnect = useCallback(async () => {\n await client.disconnect();\n setState(client.getState());\n }, [client]);\n\n const switchChain = useCallback(\n async (chainName: string) => {\n await client.switchChain(chainName);\n setState(client.getState());\n },\n [client]\n );\n\n const getBalance = useCallback(() => client.getBalance(), [client]);\n\n const value = useMemo(\n () => ({\n client,\n state,\n connect,\n disconnect,\n switchChain,\n getBalance,\n }),\n [client, state, connect, disconnect, switchChain, getBalance]\n );\n\n return <X402Context.Provider value={value}>{children}</X402Context.Provider>;\n}\n\n// ============================================================================\n// HOOKS\n// ============================================================================\n\n/**\n * useX402 - Main hook for x402 functionality\n *\n * Returns wallet state and connection methods.\n */\nexport function useX402() {\n const context = useContext(X402Context);\n if (!context) {\n throw new Error('useX402 must be used within an X402Provider');\n }\n\n const { client, state, connect, disconnect, switchChain, getBalance } = context;\n\n return {\n // State\n isConnected: state.connected,\n address: state.address,\n chainId: state.chainId,\n network: state.network,\n networkType: state.networkType,\n\n // Methods\n connect,\n disconnect,\n switchChain,\n getBalance,\n\n // Client access for advanced usage\n client,\n };\n}\n\n/**\n * useBalance - Hook for USDC balance management\n */\nexport function useBalance() {\n const { client, isConnected, network } = useX402();\n const [balance, setBalance] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const fetchBalance = useCallback(async () => {\n if (!isConnected) {\n setBalance(null);\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const bal = await client.getBalance();\n setBalance(bal);\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Failed to fetch balance');\n setBalance(null);\n } finally {\n setIsLoading(false);\n }\n }, [client, isConnected]);\n\n // Auto-fetch on connection/network change\n useEffect(() => {\n fetchBalance();\n }, [fetchBalance, network]);\n\n return {\n balance,\n isLoading,\n error,\n refetch: fetchBalance,\n };\n}\n\n/**\n * usePayment - Hook for creating payments\n */\nexport function usePayment() {\n const { client } = useX402();\n const [isPaying, setIsPaying] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [lastResult, setLastResult] = useState<PaymentResult | null>(null);\n\n const pay = useCallback(\n async (paymentInfo: PaymentInfo): Promise<PaymentResult> => {\n // The client is the source of truth. `isConnected` from the context is the snapshot of\n // the render that created this callback, so a `connect()` awaited in the same click\n // handler is not visible here yet: the first click after connecting threw\n // \"Wallet not connected\" and only the second one opened the wallet (seen with Rabby,\n // 2026-09-09).\n if (!client.getState().connected) {\n throw new Error('Wallet not connected');\n }\n\n setIsPaying(true);\n setError(null);\n\n try {\n const result = await client.createPayment(paymentInfo);\n setLastResult(result);\n return result;\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Payment failed';\n setError(message);\n throw err;\n } finally {\n setIsPaying(false);\n }\n },\n [client]\n );\n\n const reset = useCallback(() => {\n setError(null);\n setLastResult(null);\n }, []);\n\n return {\n pay,\n isPaying,\n error,\n lastResult,\n reset,\n };\n}\n\n/**\n * useChains - Hook for chain information\n */\nexport function useChains() {\n const { network: currentNetwork } = useX402();\n\n const chains = useMemo(() => getEnabledChains(), []);\n\n const currentChain = useMemo(\n () => (currentNetwork ? getChainByName(currentNetwork) : null),\n [currentNetwork]\n );\n\n const evmChains = useMemo(\n () => chains.filter((c) => c.networkType === 'evm'),\n [chains]\n );\n\n const nonEvmChains = useMemo(\n () => chains.filter((c) => c.networkType !== 'evm'),\n [chains]\n );\n\n return {\n chains,\n currentChain,\n evmChains,\n nonEvmChains,\n getChain: getChainByName,\n };\n}\n\n/**\n * useNetworkBalances - Hook for fetching balances across all networks\n */\nexport function useNetworkBalances() {\n const { address, isConnected, networkType } = useX402();\n const [balances, setBalances] = useState<Map<string, NetworkBalance>>(new Map());\n const [isLoading, setIsLoading] = useState(false);\n\n const fetchAllBalances = useCallback(async () => {\n if (!isConnected || !address) {\n setBalances(new Map());\n return;\n }\n\n setIsLoading(true);\n const chains = getEnabledChains();\n\n // Filter to compatible chains\n const compatibleChains = chains.filter((chain) => {\n // EVM address starts with 0x\n if (address.startsWith('0x')) {\n return chain.networkType === 'evm';\n }\n // Otherwise match by network type\n return chain.networkType === networkType;\n });\n\n const newBalances = new Map<string, NetworkBalance>();\n\n // Initialize loading states\n compatibleChains.forEach((chain) => {\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: null,\n isLoading: true,\n error: null,\n });\n });\n setBalances(new Map(newBalances));\n\n // Fetch in parallel\n await Promise.allSettled(\n compatibleChains.map(async (chain) => {\n try {\n const provider = new (await import('ethers')).JsonRpcProvider(chain.rpcUrl);\n const usdcAbi = ['function balanceOf(address) view returns (uint256)'];\n const contract = new (await import('ethers')).Contract(\n chain.usdc.address,\n usdcAbi,\n provider\n );\n const balance = await contract.balanceOf(address);\n const formatted = parseFloat(\n (await import('ethers')).formatUnits(balance, chain.usdc.decimals)\n ).toFixed(2);\n\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: formatted,\n isLoading: false,\n error: null,\n });\n } catch (err) {\n newBalances.set(chain.name, {\n chainName: chain.name,\n displayName: chain.displayName,\n balance: null,\n isLoading: false,\n error: err instanceof Error ? err.message : 'Failed',\n });\n }\n setBalances(new Map(newBalances));\n })\n );\n\n setIsLoading(false);\n }, [address, isConnected, networkType]);\n\n useEffect(() => {\n fetchAllBalances();\n }, [fetchAllBalances]);\n\n // Find network with highest balance\n const highestBalanceNetwork = useMemo(() => {\n let maxBalance = 0;\n let maxChain: string | null = null;\n\n balances.forEach((nb, chainName) => {\n if (nb.balance !== null && !nb.error) {\n const bal = parseFloat(nb.balance);\n if (bal > maxBalance) {\n maxBalance = bal;\n maxChain = chainName;\n }\n }\n });\n\n return maxChain;\n }, [balances]);\n\n return {\n balances,\n isLoading,\n refetch: fetchAllBalances,\n highestBalanceNetwork,\n };\n}\n\n// Re-export types for convenience\nexport type { WalletState, PaymentInfo, PaymentResult, ChainConfig, NetworkBalance };\n\n// ============================================================================\n// COMPONENTS\n// ============================================================================\n\nexport { NetworkPicker, buildNetworkOptions, resolveChain, SIGNABLE_IN_BROWSER, FAMILY_LABEL } from './NetworkPicker';\nexport type { NetworkPickerProps, NetworkOption } from './NetworkPicker';\n\nexport { PaymentMethodPicker } from './PaymentMethodPicker';\nexport type { PaymentMethodPickerProps, PaymentAccept } from './PaymentMethodPicker';\n","/**\n * NetworkPicker - the shared network selector for the whole stack.\n *\n * WHY IT IS SEPARATE FROM PaymentMethodPicker\n * The first version of this work bundled \"pick a network\" and \"pay\" into one\n * component. Dogfooding it into meshrelay broke that idea in the first minute:\n * its selector is a controlled input (`value` / `onChange`) sitting next to a\n * pay button that owns the payment. Sites that already have a payment flow need\n * the selector alone. So: this component selects, `PaymentMethodPicker` wraps it\n * and adds the paying.\n *\n * The props are deliberately shaped like meshrelay's `NetworkSelector`, which is\n * the one that got the interaction right, so adopting it is an import swap\n * rather than a rewrite.\n *\n * TWO RULES, EACH PAID FOR IN A PRODUCTION BUG\n *\n * 1. No chain table lives here. Networks come from `getEnabledChains()`, the\n * single source, which already carries all 21 mainnet networks the\n * facilitator settles. describe.net deleted its own 14-network table for\n * this reason.\n * 2. A network with no local config does NOT break the list. It renders with its\n * raw id. With 21 networks and counting, that is a requirement, not manners.\n *\n * WHY IT IMPORTS `../chains` AND NOT `useChains()`\n * Going through the `./index` barrel pulls `X402Client` and with it `ethers`.\n * `getEnabledChains()` is a data table with no crypto in it, so the picker keeps\n * the same single source without the weight, and `react/picker` can exist as an\n * entrypoint that ships 30.8 kB instead of 64.5 kB. A picker must not make a\n * page pay for a signing stack it may never use.\n *\n * Accessibility follows meshrelay: `role=\"radiogroup\"`, live `aria-checked`, and\n * arrow keys that move and select, per the WAI-ARIA radiogroup pattern.\n */\n\nimport { useCallback, useMemo, useRef, type KeyboardEvent, type ReactNode } from 'react';\n\nimport { getEnabledChains } from '../chains';\nimport type { ChainConfig, NetworkType } from '../types';\n\n/**\n * Wallet families a browser can sign for today. The rest are listed but\n * disabled: the facilitator settles them, the browser bridge is not there yet.\n * Backlog items 1 and 2 in `docs/carrusel-de-pago-compartido.md`.\n */\nexport const SIGNABLE_IN_BROWSER: readonly NetworkType[] = ['evm', 'svm', 'solana'];\n\nexport const FAMILY_LABEL: Record<string, string> = {\n evm: 'EVM',\n svm: 'Solana VM',\n solana: 'Solana VM',\n stellar: 'Stellar',\n near: 'NEAR',\n algorand: 'Algorand',\n sui: 'Sui',\n xrpl: 'XRP Ledger',\n};\n\nexport interface NetworkOption {\n /** Network id, as the caller and the facilitator name it. */\n id: string;\n /** Local config, or null when this build does not know the network. */\n chain: ChainConfig | null;\n /** What to show. Falls back to the raw id. */\n label: string;\n family: string;\n selectable: boolean;\n /** Why it cannot be picked. Shown to the user, never swallowed. */\n disabledReason?: string;\n}\n\nexport interface NetworkPickerProps {\n /** Currently selected network. Controlled component. */\n value: string | null;\n /** Called when the user picks a different network. */\n onChange: (next: string) => void;\n /**\n * Networks to offer. Omit to offer every x402-enabled chain the SDK knows.\n * Pass the ids from a 402 `accepts` array to mirror what the resource takes.\n */\n networks?: readonly string[];\n /** Narrow by wallet family. */\n families?: readonly NetworkType[];\n /** When true, all options are non-interactive (e.g. mid-payment). */\n disabled?: boolean;\n /** Heading above the selector. */\n label?: string;\n /** Hint below the selector. */\n hint?: string;\n /** Hide the heading entirely. */\n hideLabel?: boolean;\n /** Group options under a family heading. Useful past a handful of networks. */\n groupByFamily?: boolean;\n layout?: 'carousel' | 'segmented' | 'list';\n className?: string;\n /**\n * Per-option decoration. Exists so adopting this component is not a visual\n * regression: meshrelay carries a logo, a short label and a tagline per\n * network that `ChainConfig` does not have, and it should not have to give\n * them up to stop maintaining its own selector. Everything returned is\n * optional and falls back to what the SDK knows.\n */\n decorate?: (option: NetworkOption) => {\n icon?: ReactNode;\n label?: ReactNode;\n shortLabel?: ReactNode;\n title?: string;\n };\n /**\n * Your class names, merged onto the built-in ones. A component that ships in\n * an SDK has no business imposing a look: meshrelay already has a CSS module\n * for this selector and adopting the shared logic should not cost it the\n * styling. Built-in `uvd-x402-picker__*` classes stay on, so a site can also\n * target those instead.\n */\n classNames?: Partial<\n Record<\n | 'root'\n | 'label'\n | 'group'\n | 'family'\n | 'familyLabel'\n | 'option'\n | 'optionSelected'\n | 'optionDisabled'\n | 'icon'\n | 'name'\n | 'nameShort'\n | 'reason'\n | 'hint',\n string\n >\n >;\n}\n\n/** Join the built-in class with the caller's, dropping empties. */\nfunction cx(...parts: Array<string | false | undefined | null>): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/** Match a network id to local chain config, tolerating aliases. */\nexport function resolveChain(\n id: string,\n chains: readonly ChainConfig[],\n aliases: readonly string[] = []\n): ChainConfig | null {\n const names = [id, ...aliases].map((n) => String(n).toLowerCase());\n return (\n chains.find((c) => names.includes(c.name.toLowerCase())) ??\n chains.find((c) => names.some((n) => n === `eip155:${c.chainId}`)) ??\n null\n );\n}\n\nexport function describeWhyDisabled(\n chain: ChainConfig | null,\n family: string,\n signable: boolean\n): string | undefined {\n if (!chain) return 'Not configured in this build';\n if (chain.x402.enabled === false) return 'Disabled for x402';\n if (!signable) return `No browser wallet bridge for ${FAMILY_LABEL[family] ?? family} yet`;\n return undefined;\n}\n\n/** Build the option list. Exported so PaymentMethodPicker reuses the same rules. */\nexport function buildNetworkOptions(\n ids: readonly string[],\n chains: readonly ChainConfig[],\n families?: readonly NetworkType[]\n): NetworkOption[] {\n const all = ids.map((id): NetworkOption => {\n const chain = resolveChain(id, chains);\n const family = chain?.networkType ?? 'unknown';\n const signable = SIGNABLE_IN_BROWSER.includes(family as NetworkType);\n return {\n id,\n chain,\n label: chain?.displayName ?? id,\n family,\n selectable: signable && chain !== null && chain.x402.enabled !== false,\n disabledReason: describeWhyDisabled(chain, family, signable),\n };\n });\n return families ? all.filter((o) => families.includes(o.family as NetworkType)) : all;\n}\n\nexport function NetworkPicker({\n value,\n onChange,\n networks,\n families,\n disabled = false,\n label = 'Payment network',\n hint,\n hideLabel = false,\n groupByFamily = false,\n layout = 'carousel',\n className,\n decorate,\n classNames: cls = {},\n}: NetworkPickerProps) {\n const chains = useMemo(() => getEnabledChains(), []);\n const buttonRefs = useRef<Record<string, HTMLButtonElement | null>>({});\n\n const options = useMemo(() => {\n const ids =\n networks ?? chains.filter((c) => c.x402.enabled !== false).map((c) => c.name);\n return buildNetworkOptions(ids, chains, families);\n }, [networks, chains, families]);\n\n const selectable = useMemo(\n () => (disabled ? [] : options.filter((o) => o.selectable)),\n [options, disabled]\n );\n\n const onKeyDown = useCallback(\n (event: KeyboardEvent<HTMLButtonElement>, id: string) => {\n const keys = ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'];\n if (!keys.includes(event.key) || selectable.length === 0) return;\n event.preventDefault();\n const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : -1;\n const at = selectable.findIndex((o) => o.id === id);\n const next = selectable[(at + step + selectable.length) % selectable.length];\n if (!next) return;\n onChange(next.id);\n buttonRefs.current[next.id]?.focus();\n },\n [selectable, onChange]\n );\n\n const renderOption = (option: NetworkOption) => {\n const isSelected = value === option.id;\n const usable = option.selectable && !disabled;\n const isFirstFallback = value === null && selectable[0]?.id === option.id;\n const extra = decorate?.(option);\n return (\n <button\n key={option.id}\n ref={(el) => {\n buttonRefs.current[option.id] = el;\n }}\n type=\"button\"\n role=\"radio\"\n aria-checked={isSelected}\n aria-disabled={!usable}\n disabled={!usable}\n title={extra?.title ?? option.disabledReason}\n tabIndex={isSelected || isFirstFallback ? 0 : -1}\n onClick={() => usable && onChange(option.id)}\n onKeyDown={(event) => onKeyDown(event, option.id)}\n className={cx(\n 'uvd-x402-picker__option',\n cls.option,\n isSelected && 'is-selected',\n isSelected && cls.optionSelected,\n !usable && cls.optionDisabled\n )}\n >\n {extra?.icon}\n <span className={cx('uvd-x402-picker__name', cls.name)}>\n {extra?.label ?? option.label}\n </span>\n {extra?.shortLabel && (\n <span className={cx('uvd-x402-picker__name-short', cls.nameShort)}>\n {extra.shortLabel}\n </span>\n )}\n {option.disabledReason && (\n <span className={cx('uvd-x402-picker__reason', cls.reason)}>\n {option.disabledReason}\n </span>\n )}\n </button>\n );\n };\n\n const grouped = useMemo(() => {\n if (!groupByFamily) return null;\n const map = new Map<string, NetworkOption[]>();\n for (const option of options) {\n const list = map.get(option.family) ?? [];\n list.push(option);\n map.set(option.family, list);\n }\n return [...map.entries()];\n }, [options, groupByFamily]);\n\n return (\n <div\n className={cx(\n 'uvd-x402-picker',\n `uvd-x402-picker--${layout}`,\n cls.root,\n className\n )}\n >\n {!hideLabel && (\n <h3 className={cx('uvd-x402-picker__label', cls.label)}>{label}</h3>\n )}\n\n <div\n role=\"radiogroup\"\n aria-label={label}\n className={cx('uvd-x402-picker__group', cls.group)}\n >\n {grouped\n ? grouped.map(([family, entries]) => (\n <section key={family} className={cx('uvd-x402-picker__family', cls.family)}>\n <h4 className={cx('uvd-x402-picker__family-label', cls.familyLabel)}>\n {FAMILY_LABEL[family] ?? family}\n </h4>\n {entries.map(renderOption)}\n </section>\n ))\n : options.map(renderOption)}\n </div>\n\n {hint && <p className={cx('uvd-x402-picker__hint', cls.hint)}>{hint}</p>}\n </div>\n );\n}\n","/**\n * PaymentMethodPicker - network selection plus payment, in one component.\n *\n * This is `NetworkPicker` with the paying attached. Sites that already own their\n * payment flow (meshrelay, for one) should use `NetworkPicker` directly and keep\n * their button; sites starting from nothing get the whole thing here.\n *\n * WHY THIS EXISTS\n * Three repos grew their own picker (describe.net `dn-pay.js`, 402milly\n * `ChainSelector`, meshrelay `NetworkSelector`): 3,718 lines solving the same\n * problem three times, none covering the 21 mainnet networks the facilitator\n * settles. Design notes and backlog: `docs/carrusel-de-pago-compartido.md`.\n *\n * THE RULE THAT MATTERS MOST HERE\n * `accepts` is passed through VERBATIM, by reference. Never rebuilt, cloned or\n * reordered. Rebuilding that object field by field is how a valid payment ends\n * up rejected (see the note in describe.net `dn-pay.js:485`). The other rules\n * about chain tables and `wallet_addEthereumChain` live in `NetworkPicker`.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\n\nimport { useX402, usePayment } from './index';\nimport { NetworkPicker } from './NetworkPicker';\nimport type { NetworkType, PaymentInfo, PaymentResult } from '../types';\n\n/** One entry of the `accepts` array of a 402 response. */\nexport interface PaymentAccept {\n scheme: string;\n network: string;\n networkAliases?: string[];\n extra?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface PaymentMethodPickerProps {\n /** The `accepts` array from the 402 response, untouched. */\n accepts: readonly PaymentAccept[];\n /** Recipients and amount, handed to `pay()` as-is. */\n payment: PaymentInfo;\n onPaid?: (result: PaymentResult) => void;\n onError?: (error: Error) => void;\n /** Restrict to some families. Omit to offer everything the resource accepts. */\n families?: readonly NetworkType[];\n layout?: 'carousel' | 'segmented' | 'list';\n label?: string;\n hint?: string;\n payLabel?: string;\n className?: string;\n}\n\nexport function PaymentMethodPicker({\n accepts,\n payment,\n onPaid,\n onError,\n families,\n layout = 'carousel',\n label = 'Payment network',\n hint,\n payLabel = 'Pay',\n className,\n}: PaymentMethodPickerProps) {\n const { isConnected, connect, switchChain, network } = useX402();\n const { pay, isPaying } = usePayment();\n const [selected, setSelected] = useState<string | null>(null);\n\n // Ids only. The accept objects themselves are never copied. Rule 1.\n const networks = useMemo(() => accepts.map((a) => a.network), [accepts]);\n\n const confirm = useCallback(async () => {\n const accept = accepts.find((a) => a.network === selected);\n if (!accept) return;\n try {\n if (!isConnected) await connect(accept.network);\n // Ask to switch. Never wallet_addEthereumChain.\n if (network && network !== accept.network) await switchChain(accept.network);\n // `payment` and `accept` both travel verbatim, by reference.\n const result = await pay({ ...payment, accept } as PaymentInfo);\n onPaid?.(result);\n } catch (error) {\n onError?.(error instanceof Error ? error : new Error(String(error)));\n }\n }, [accepts, selected, isConnected, connect, network, switchChain, pay, payment, onPaid, onError]);\n\n return (\n <div className={['uvd-x402-pay', className].filter(Boolean).join(' ')}>\n <NetworkPicker\n value={selected}\n onChange={setSelected}\n networks={networks}\n families={families}\n disabled={isPaying}\n label={label}\n hint={hint}\n groupByFamily={networks.length > 6}\n layout={layout}\n />\n\n <button\n type=\"button\"\n disabled={!selected || isPaying}\n onClick={confirm}\n className=\"uvd-x402-pay__confirm\"\n >\n {isPaying ? 'Paying...' : payLabel}\n </button>\n </div>\n );\n}\n"]}
|