@x402x/client 0.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/core/utils.ts","../src/core/prepare.ts","../src/core/sign.ts","../src/core/settle.ts","../src/client.ts","../src/hooks/useX402Client.ts","../src/hooks/useExecute.ts"],"names":["getAddress","coreSettle","calculateFacilitatorFee","error"],"mappings":";;;;;;;;;;AAOO,IAAM,eAAA,GAAN,MAAM,gBAAA,SAAwB,KAAA,CAAM;AAAA,EACzC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,gBAAA,CAAgB,SAAS,CAAA;AAAA,EACvD;AACF;AAKO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,eAAA,CAAgB;AAAA,EAChD,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,SAAS,IAAI,CAAA;AACnB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,EACpD;AACF;AAKO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,eAAA,CAAgB;AAAA,EAChD,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,SAAS,IAAI,CAAA;AACnB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,EACpD;AACF;AAKO,IAAM,gBAAA,GAAN,MAAM,iBAAA,SAAyB,eAAA,CAAgB;AAAA,EACpD,W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QAAA,SAAA,CAAU,aAAa,CAAA;AACvB,QAAA,OAAO,aAAA;AAAA,MACT,SAAS,GAAA,EAAK;AACZ,QAAA,MAAMC,SAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,GAAM,IAAI,MAAM,eAAe,CAAA;AACpE,QAAA,SAAA,CAAU,OAAO,CAAA;AACjB,QAAA,QAAA,CAASA,MAAK,CAAA;AACd,QAAA,MAAMA,MAAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IACA,CAAC,MAAM;AAAA,GACT;AAEA,EAAA,MAAM,KAAA,GAAQ,YAAY,MAAM;AAC9B,IAAA,SAAA,CAAU,MAAM,CAAA;AAChB,IAAA,QAAA,CAAS,IAAI,CAAA;AACb,IAAA,SAAA,CAAU,IAAI,CAAA;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,WAAA,EAAa,CAAC,WAAA,EAAa,SAAA,EAAW,cAAc,YAAY,CAAA,CAAE,SAAS,MAAM,CAAA;AAAA,IACjF,WAAW,MAAA,KAAW,SAAA;AAAA,IACtB,SAAS,MAAA,KAAW;AAAA,GACtB;AACF","file":"index.js","sourcesContent":["/**\n * Error classes for x402x client SDK\n */\n\n/**\n * Base error class for all x402x client errors\n */\nexport class X402ClientError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message);\n this.name = \"X402ClientError\";\n Object.setPrototypeOf(this, X402ClientError.prototype);\n }\n}\n\n/**\n * Network-related errors (unsupported network, configuration issues)\n */\nexport class NetworkError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"NetworkError\";\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * Wallet signing errors\n */\nexport class SigningError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"SigningError\";\n Object.setPrototypeOf(this, SigningError.prototype);\n }\n}\n\n/**\n * Facilitator communication errors\n */\nexport class FacilitatorError extends X402ClientError {\n constructor(\n message: string,\n code?: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n ) {\n super(message, code);\n this.name = \"FacilitatorError\";\n Object.setPrototypeOf(this, FacilitatorError.prototype);\n }\n}\n\n/**\n * Transaction execution errors\n */\nexport class TransactionError extends X402ClientError {\n constructor(\n message: string,\n code?: string,\n public readonly txHash?: string,\n ) {\n super(message, code);\n this.name = \"TransactionError\";\n Object.setPrototypeOf(this, TransactionError.prototype);\n }\n}\n\n/**\n * Parameter validation errors\n */\nexport class ValidationError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"ValidationError\";\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n","/**\n * Utility functions for x402x client\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { ValidationError } from \"../errors.js\";\n\n/**\n * Generate a random 32-byte salt for settlement idempotency\n *\n * @returns Random 32-byte hex string\n *\n * @example\n * ```typescript\n * const salt = generateSalt();\n * console.log(salt); // \"0x1234...\"\n * ```\n */\nexport function generateSalt(): Hex {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32));\n return `0x${Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}` as Hex;\n}\n\n/**\n * Normalize Ethereum address to EIP-55 checksum format\n *\n * Automatically converts any valid Ethereum address (lowercase, uppercase, or mixed)\n * to the proper checksummed format. This provides a better developer experience\n * by accepting addresses in any case format.\n *\n * @param address - Address to normalize (can be any case)\n * @param name - Parameter name for error messages (optional)\n * @returns Checksummed address in EIP-55 format\n * @throws ValidationError if address is invalid\n *\n * @example\n * ```typescript\n * normalizeAddress('0xabc123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xABC123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xAbC123...') // Returns '0xAbC123...' (already checksummed)\n * ```\n */\nexport function normalizeAddress(address: string, name: string = \"address\"): Address {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to EIP-55 checksum format\n // getAddress() will throw if the address is invalid\n try {\n return getAddress(address);\n } catch (error) {\n throw new ValidationError(\n `${name} is not a valid Ethereum address: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Validate Ethereum address format (legacy, prefer normalizeAddress)\n *\n * @deprecated Use normalizeAddress() instead for better developer experience\n * @param address - Address to validate\n * @param name - Parameter name for error messages\n * @throws ValidationError if address is invalid\n */\nexport function validateAddress(address: string, name: string): void {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!isAddress(address)) {\n throw new ValidationError(`${name} must be a valid Ethereum address`);\n }\n}\n\n/**\n * Validate hex string format\n *\n * @param hex - Hex string to validate\n * @param name - Parameter name for error messages\n * @param expectedLength - Optional expected length (in bytes, not characters)\n * @throws ValidationError if hex is invalid\n */\nexport function validateHex(hex: string, name: string, expectedLength?: number): void {\n if (!hex || typeof hex !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!hex.startsWith(\"0x\")) {\n throw new ValidationError(`${name} must start with 0x`);\n }\n if (!/^0x[0-9a-fA-F]*$/.test(hex)) {\n throw new ValidationError(`${name} must be a valid hex string`);\n }\n if (expectedLength !== undefined) {\n const actualLength = (hex.length - 2) / 2;\n if (actualLength !== expectedLength) {\n throw new ValidationError(\n `${name} must be ${expectedLength} bytes, got ${actualLength} bytes`,\n );\n }\n }\n}\n\n/**\n * Validate amount format - must be atomic units (positive integer string)\n *\n * This function validates that the amount is a valid atomic unit string.\n * For converting USD amounts to atomic units, use parseDefaultAssetAmount from @x402x/core.\n *\n * @param amount - Amount in atomic units (must be a positive integer string)\n * @param name - Parameter name for error messages\n * @throws ValidationError if amount is invalid\n *\n * @example\n * ```typescript\n * validateAmount('1000000', 'amount'); // Valid: atomic units\n * validateAmount('0.1', 'amount'); // Invalid: not atomic units\n * validateAmount('-1', 'amount'); // Invalid: negative\n * ```\n */\nexport function validateAmount(amount: string | number, name: string): void {\n if (amount === null || amount === undefined || amount === \"\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to string if number\n const amountStr = typeof amount === \"number\" ? amount.toString() : amount;\n\n // Must be a non-empty string\n if (typeof amountStr !== \"string\" || amountStr.trim() === \"\") {\n throw new ValidationError(`${name} must be a non-empty string`);\n }\n\n // Must be a valid positive integer (atomic units)\n // Allow leading zeros but must be numeric\n if (!/^\\d+$/.test(amountStr)) {\n throw new ValidationError(\n `${name} must be a positive integer string (atomic units). ` +\n `Use parseDefaultAssetAmount() from @x402x/core to convert USD amounts.`,\n );\n }\n\n // Validate it can be converted to BigInt (no overflow)\n try {\n const atomicAmount = BigInt(amountStr);\n if (atomicAmount < 0n) {\n throw new ValidationError(`${name} cannot be negative`);\n }\n if (atomicAmount === 0n) {\n throw new ValidationError(`${name} cannot be zero`);\n }\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(\n `${name} is not a valid amount: ${error instanceof Error ? error.message : \"Invalid format\"}`,\n );\n }\n}\n\n/**\n * Format facilitator URL (ensure it doesn't end with slash)\n *\n * @param url - Facilitator URL\n * @returns Formatted URL\n */\nexport function formatFacilitatorUrl(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/**\n * Calculate default time window for authorization\n *\n * @param maxTimeoutSeconds - Maximum timeout in seconds\n * @returns Object with validAfter and validBefore timestamps\n */\nexport function calculateTimeWindow(maxTimeoutSeconds: number = 300): {\n validAfter: string;\n validBefore: string;\n} {\n const now = Math.floor(Date.now() / 1000);\n return {\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + maxTimeoutSeconds).toString(),\n };\n}\n","/**\n * Prepare settlement data for signing\n *\n * This module handles the preparation of settlement parameters before signing,\n * including generating salt, calculating commitment hash, and fetching facilitator fees.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getNetworkConfig, calculateFacilitatorFee, type FeeCalculationResult } from \"@x402x/core\";\nimport { calculateCommitment } from \"@x402x/core\";\nimport type { PrepareParams, SettlementData } from \"../types.js\";\nimport { NetworkError, ValidationError, FacilitatorError } from \"../errors.js\";\nimport {\n generateSalt,\n validateAddress,\n validateHex,\n validateAmount,\n calculateTimeWindow,\n} from \"./utils.js\";\n\n/**\n * Query facilitator fee from facilitator service (internal helper)\n *\n * Uses the /calculate-fee endpoint which provides accurate gas cost estimates\n * with safety margins.\n *\n * @internal\n * @param facilitatorUrl - Facilitator URL\n * @param network - Network name\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result\n *\n * @throws FacilitatorError if request fails\n */\nasync function queryFacilitatorFee(\n facilitatorUrl: string,\n network: string,\n hook: Address,\n hookData: Hex = \"0x\",\n): Promise<FeeCalculationResult> {\n try {\n return await calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to query facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\"Failed to query facilitator fee: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n\n/**\n * Prepare settlement data for signing\n *\n * This function:\n * 1. Validates all parameters\n * 2. Loads network configuration\n * 3. Generates salt (if not provided)\n * 4. Queries facilitator fee (if not provided)\n * 5. Calculates time window (if not provided)\n * 6. Calculates commitment hash\n * 7. Returns prepared settlement data\n *\n * @param params - Preparation parameters\n * @returns Prepared settlement data ready for signing\n *\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if parameters are invalid\n *\n * @example\n * ```typescript\n * import { prepareSettlement } from '@x402x/client';\n * import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units first\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const settlement = await prepareSettlement({\n * wallet: walletClient,\n * network: 'base-sepolia',\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData: TransferHook.encode(),\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...',\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n * ```\n */\nexport async function prepareSettlement(params: PrepareParams): Promise<SettlementData> {\n // 1. Validate parameters\n validateAddress(params.hook, \"hook\");\n validateHex(params.hookData, \"hookData\");\n validateAddress(params.payTo, \"payTo\");\n\n // 2. Validate amount (must be atomic units, no automatic conversion)\n validateAmount(params.amount, \"amount\");\n const atomicAmount = params.amount;\n\n if (params.customSalt) {\n validateHex(params.customSalt, \"customSalt\", 32);\n }\n\n // 2. Get wallet account address\n const from = params.wallet.account?.address;\n if (!from) {\n throw new ValidationError(\"Wallet client must have an account\");\n }\n\n // 3. Load network configuration\n const networkConfig = params.networkConfig || getNetworkConfig(params.network);\n if (!networkConfig) {\n throw new NetworkError(\n `Network '${params.network}' is not supported. Please provide custom networkConfig.`,\n );\n }\n\n // 4. Determine asset address (use provided asset or default asset)\n const asset = params.asset || (networkConfig.defaultAsset.address as Address);\n validateAddress(asset, \"asset\");\n\n // 5. Generate salt (if not provided)\n const salt = params.customSalt || generateSalt();\n\n // 6. Query facilitator fee (if not provided and facilitatorUrl is available)\n let facilitatorFee = params.facilitatorFee || \"0\";\n if (!params.facilitatorFee && params.facilitatorUrl) {\n try {\n const feeEstimate = await queryFacilitatorFee(\n params.facilitatorUrl,\n params.network,\n params.hook,\n params.hookData, // Pass hookData for accurate fee calculation\n );\n\n if (!feeEstimate.hookAllowed) {\n throw new ValidationError(\n `Hook ${params.hook} is not allowed on network ${params.network}.`,\n );\n }\n\n facilitatorFee = feeEstimate.facilitatorFee;\n } catch (error) {\n // If fee query fails, log warning and use 0\n console.warn(\n `[x402x] Failed to query facilitator fee, using 0. This may cause settlement to fail. Error: ${error instanceof Error ? error.message : \"Unknown\"}`,\n );\n facilitatorFee = \"0\";\n }\n }\n\n // 7. Calculate time window (if not provided)\n const timeWindow =\n params.validAfter && params.validBefore\n ? { validAfter: params.validAfter, validBefore: params.validBefore }\n : calculateTimeWindow(300); // 5 minutes default\n\n // 8. Calculate commitment hash\n // IMPORTANT: value must be total amount (business amount + facilitator fee)\n // because the contract's calculateCommitment expects the same value that\n // will be authorized in the EIP-3009 signature\n const totalAmount = (BigInt(atomicAmount) + BigInt(facilitatorFee)).toString();\n const commitment = calculateCommitment({\n chainId: networkConfig.chainId,\n hub: networkConfig.settlementRouter as Address,\n asset: asset,\n from,\n value: totalAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n });\n\n // 9. Return prepared settlement data\n return {\n network: params.network,\n networkConfig,\n asset: asset,\n from,\n amount: atomicAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n commitment: commitment as Hex,\n };\n}\n","/**\n * Sign EIP-3009 authorization for settlement\n *\n * This module handles the signing of EIP-712 typed data for EIP-3009\n * transferWithAuthorization, using the commitment hash as the nonce.\n */\n\nimport type { Address, WalletClient } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { signTypedData } from \"viem/actions\";\nimport type { SettlementData, SignedAuthorization } from \"../types.js\";\nimport { SigningError } from \"../errors.js\";\n\n/**\n * EIP-3009 authorization types for EIP-712 signature\n */\nconst AUTHORIZATION_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} as const;\n\n/**\n * Sign EIP-3009 authorization\n *\n * This function signs an EIP-712 typed data message for EIP-3009's\n * transferWithAuthorization function. The commitment hash is used\n * as the nonce to cryptographically bind all settlement parameters.\n *\n * @param wallet - Wallet client from wagmi/viem\n * @param settlement - Prepared settlement data\n * @returns Signed authorization ready to submit\n *\n * @throws SigningError if signing fails or wallet doesn't support signing\n *\n * @example\n * ```typescript\n * import { signAuthorization } from '@x402x/client';\n *\n * const signed = await signAuthorization(walletClient, settlement);\n * console.log('Signature:', signed.signature);\n * ```\n */\nexport async function signAuthorization(\n wallet: WalletClient,\n settlement: SettlementData,\n): Promise<SignedAuthorization> {\n try {\n // Ensure wallet has an account\n if (!wallet.account) {\n throw new SigningError(\"Wallet client must have an account\");\n }\n\n // Build EIP-712 domain\n // Use the asset's EIP-712 domain info from network config\n // Note: For custom assets, the domain info should match the asset contract\n const domain = {\n name: settlement.networkConfig.defaultAsset.eip712.name,\n version: settlement.networkConfig.defaultAsset.eip712.version,\n chainId: settlement.networkConfig.chainId,\n verifyingContract: getAddress(settlement.asset),\n };\n\n // Build EIP-712 message\n // The \"to\" address is the SettlementRouter (not the final recipient)\n // The \"value\" MUST be total amount (business amount + facilitator fee)\n // because the Router needs to deduct the fee before passing to Hook\n const totalAmount = BigInt(settlement.amount) + BigInt(settlement.facilitatorFee);\n const message = {\n from: getAddress(settlement.from),\n to: getAddress(settlement.networkConfig.settlementRouter),\n value: totalAmount,\n validAfter: BigInt(settlement.validAfter),\n validBefore: BigInt(settlement.validBefore),\n nonce: settlement.commitment, // Use commitment as nonce\n };\n\n console.log(\"[x402x/client] EIP-712 Message for signing:\", {\n from: message.from,\n to: message.to,\n value: message.value.toString(),\n validAfter: message.validAfter.toString(),\n validBefore: message.validBefore.toString(),\n nonce: message.nonce,\n });\n\n // Sign typed data\n const signature = await signTypedData(wallet, {\n account: wallet.account,\n domain,\n types: AUTHORIZATION_TYPES,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Build authorization object\n const authorization = {\n from: settlement.from,\n to: settlement.networkConfig.settlementRouter as Address,\n value: totalAmount.toString(), // Use total amount (business + fee)\n validAfter: settlement.validAfter,\n validBefore: settlement.validBefore,\n nonce: settlement.commitment,\n };\n\n return {\n settlement,\n signature,\n authorization,\n };\n } catch (error) {\n if (error instanceof SigningError) {\n throw error;\n }\n\n // Handle common signing errors\n if (error instanceof Error) {\n if (error.message.includes(\"User rejected\")) {\n throw new SigningError(\"User rejected the signing request\", \"USER_REJECTED\");\n }\n if (error.message.includes(\"account\")) {\n throw new SigningError(\"Wallet account not available\", \"NO_ACCOUNT\");\n }\n throw new SigningError(`Failed to sign authorization: ${error.message}`, \"SIGNING_FAILED\");\n }\n\n throw new SigningError(\"Failed to sign authorization: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * Settle payment with facilitator\n *\n * This module handles the settlement of signed payment payloads with the\n * facilitator's /settle endpoint, following the x402 protocol.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { settle as coreSettle } from \"@x402x/core\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * Settle signed authorization with facilitator\n *\n * This function acts as a convenience wrapper that:\n * 1. Constructs the PaymentPayload according to x402 protocol\n * 2. Constructs the PaymentRequirements with settlement extra\n * 3. Calls core's settle() method to POST to facilitator's /settle endpoint\n * 4. Parses and returns the settlement result\n *\n * @param facilitatorUrl - Facilitator URL\n * @param signed - Signed authorization from signAuthorization\n * @param timeout - Optional timeout in milliseconds (default: 30000)\n * @returns Settlement result with transaction hash\n *\n * @throws FacilitatorError if request fails or facilitator returns error\n *\n * @example\n * ```typescript\n * import { settle } from '@x402x/client';\n *\n * const result = await settle(\n * 'https://facilitator.x402x.dev',\n * signed\n * );\n * console.log('TX Hash:', result.transaction);\n * ```\n */\nexport async function settle(\n facilitatorUrl: string,\n signed: SignedAuthorization,\n timeout: number = 30000,\n): Promise<SettleResult> {\n try {\n // Construct PaymentPayload\n const paymentPayload: PaymentPayload = {\n x402Version: 1,\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n payload: {\n signature: signed.signature,\n authorization: {\n from: signed.authorization.from,\n to: signed.authorization.to,\n value: signed.authorization.value,\n validAfter: signed.authorization.validAfter,\n validBefore: signed.authorization.validBefore,\n nonce: signed.authorization.nonce,\n },\n },\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n maxAmountRequired: signed.settlement.amount,\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\n // Required by x402 protocol (even though not used in serverless mode)\n // In the future, the x402 v2 will remove the resource field from the payment requirements\n // (https://github.com/coinbase/x402/pull/446)\n resource: \"https://x402x.dev/serverless\", // Placeholder for serverless mode\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n extra: {\n name: signed.settlement.networkConfig.defaultAsset.eip712.name,\n version: signed.settlement.networkConfig.defaultAsset.eip712.version,\n settlementRouter: signed.settlement.networkConfig.settlementRouter as Address,\n salt: signed.settlement.salt,\n payTo: signed.settlement.payTo,\n facilitatorFee: signed.settlement.facilitatorFee,\n hook: signed.settlement.hook,\n hookData: signed.settlement.hookData,\n },\n };\n\n // Include payment requirements in payload (for stateless facilitator processing)\n paymentPayload.paymentRequirements = paymentRequirements;\n\n // Call core's settle method\n const result = await coreSettle(facilitatorUrl, paymentPayload, paymentRequirements, timeout);\n\n return {\n success: result.success,\n transaction: result.transaction as Hex,\n network: result.network || signed.settlement.network,\n payer: (result.payer || signed.settlement.from) as Address,\n errorReason: result.errorReason,\n };\n } catch (error) {\n if (error instanceof FacilitatorError) {\n throw error;\n }\n\n // Handle errors from core settle\n if (error instanceof Error) {\n throw new FacilitatorError(`Failed to settle payment: ${error.message}`, \"SETTLEMENT_ERROR\");\n }\n\n throw new FacilitatorError(\"Failed to settle payment: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This is the main client class that provides a simple API for executing\n * on-chain contracts via facilitator without needing a resource server.\n */\n\nimport type { Address, Hex, TransactionReceipt } from \"viem\";\nimport { calculateFacilitatorFee, type FeeCalculationResult, TransferHook } from \"@x402x/core\";\nimport type { X402ClientConfig, ExecuteParams, ExecuteResult } from \"./types.js\";\nimport { prepareSettlement } from \"./core/prepare.js\";\nimport { signAuthorization } from \"./core/sign.js\";\nimport { settle } from \"./core/settle.js\";\nimport { ValidationError, FacilitatorError } from \"./errors.js\";\nimport { normalizeAddress, validateHex, validateAmount } from \"./core/utils.js\";\n\n/**\n * Default facilitator URL\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\n\n/**\n * Internal configuration with required fields\n */\ninterface InternalConfig extends X402ClientConfig {\n facilitatorUrl: string;\n timeout: number;\n confirmationTimeout: number;\n}\n\n/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This client simplifies the entire settlement flow into a single execute() call,\n * automatically handling:\n * - Parameter preparation\n * - Commitment calculation\n * - EIP-712 signing\n * - Facilitator submission\n * - Transaction confirmation\n *\n * @example\n * ```typescript\n * import { X402Client } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n * import { useWalletClient } from 'wagmi';\n *\n * const { data: wallet } = useWalletClient();\n *\n * // Use default facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia'\n * });\n *\n * // Or specify custom facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia',\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * // Simple transfer (hook and hookData are optional)\n * const result = await client.execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * ```\n */\nexport class X402Client {\n private config: InternalConfig;\n\n /**\n * Create a new X402Client instance\n *\n * @param config - Client configuration\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if configuration is invalid\n */\n constructor(config: X402ClientConfig) {\n // Validate configuration\n if (!config.wallet) {\n throw new ValidationError(\"wallet is required\");\n }\n if (!config.network) {\n throw new ValidationError(\"network is required\");\n }\n\n this.config = {\n ...config,\n facilitatorUrl: config.facilitatorUrl || DEFAULT_FACILITATOR_URL,\n timeout: config.timeout || 30000,\n confirmationTimeout: config.confirmationTimeout || 60000,\n };\n }\n\n /**\n * Execute a settlement transaction\n *\n * This is the main method that orchestrates the entire settlement flow:\n * 1. Validates parameters\n * 2. Prepares settlement data (queries fee if needed)\n * 3. Signs EIP-3009 authorization\n * 4. Submits to facilitator\n * 5. Optionally waits for transaction confirmation\n *\n * @param params - Execution parameters\n * @param waitForConfirmation - Whether to wait for transaction confirmation (default: true)\n * @returns Execution result with transaction hash and optional receipt\n *\n * @throws ValidationError if parameters are invalid\n * @throws NetworkError if network is unsupported\n * @throws SigningError if user rejects signing\n * @throws FacilitatorError if facilitator request fails\n * @throws TransactionError if transaction fails\n *\n * @example Simple transfer (uses TransferHook by default)\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const result = await client.execute({\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * console.log('Transaction:', result.txHash);\n * ```\n *\n * @example Custom hook\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * const atomicAmount = parseDefaultAssetAmount('5', 'base-sepolia'); // '5000000'\n *\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * ```\n */\n async execute(\n params: ExecuteParams,\n waitForConfirmation: boolean = false,\n ): Promise<ExecuteResult> {\n // 1. Validate and normalize parameters\n const hook: Address = params.hook\n ? normalizeAddress(params.hook, \"hook\")\n : (TransferHook.getAddress(this.config.network) as Address);\n const payTo = normalizeAddress(params.payTo, \"payTo\");\n const hookData = params.hookData || \"0x\";\n\n if (params.hookData) {\n validateHex(params.hookData, \"hookData\");\n }\n validateAmount(params.amount, \"amount\");\n\n // 2. Prepare settlement with normalized addresses\n const settlement = await prepareSettlement({\n wallet: this.config.wallet,\n network: this.config.network,\n hook,\n hookData,\n asset: params.asset,\n amount: params.amount,\n payTo,\n facilitatorFee: params.facilitatorFee,\n customSalt: params.customSalt,\n validAfter: params.validAfter,\n validBefore: params.validBefore,\n networkConfig: this.config.networkConfig,\n facilitatorUrl: this.config.facilitatorUrl,\n });\n\n // 3. Sign authorization\n const signed = await signAuthorization(this.config.wallet, settlement);\n\n // 4. Settle with facilitator\n const settleResult = await settle(this.config.facilitatorUrl, signed, this.config.timeout);\n\n // 5. Optionally wait for confirmation\n let receipt: TransactionReceipt | undefined;\n if (waitForConfirmation) {\n receipt = await this.waitForTransaction(settleResult.transaction);\n }\n\n return {\n txHash: settleResult.transaction,\n network: settleResult.network,\n payer: settleResult.payer,\n receipt,\n settlement,\n };\n }\n\n /**\n * Calculate facilitator fee for a hook with optional hook data\n *\n * Queries the facilitator for the recommended fee based on current gas prices\n * and hook gas usage. The returned fee includes a safety margin to ensure\n * settlement will succeed.\n *\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result from facilitator\n *\n * @throws FacilitatorError if query fails\n *\n * @example\n * ```typescript\n * const fee = await client.calculateFee('0x...', '0x');\n * console.log('Facilitator fee:', fee.facilitatorFee);\n * console.log('Fee in USD:', fee.facilitatorFeeUSD);\n * console.log('Valid for:', fee.validitySeconds, 'seconds');\n * ```\n */\n async calculateFee(hook: Address, hookData: Hex = \"0x\"): Promise<FeeCalculationResult> {\n const normalizedHook = normalizeAddress(hook, \"hook\");\n validateHex(hookData, \"hookData\");\n\n try {\n return await calculateFacilitatorFee(\n this.config.facilitatorUrl,\n this.config.network,\n normalizedHook,\n hookData,\n );\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to calculate facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\n \"Failed to calculate facilitator fee: Unknown error\",\n \"UNKNOWN_ERROR\",\n );\n }\n }\n\n /**\n * Wait for transaction confirmation\n *\n * @param txHash - Transaction hash to wait for\n * @returns Transaction receipt\n *\n * @throws TransactionError if transaction fails or times out\n *\n * @example\n * ```typescript\n * const receipt = await client.waitForTransaction('0x...');\n * console.log('Status:', receipt.status);\n * ```\n */\n async waitForTransaction(txHash: Hex): Promise<TransactionReceipt> {\n // Check if wallet has waitForTransactionReceipt method\n const publicClient = this.config.wallet as any;\n if (typeof publicClient.waitForTransactionReceipt !== \"function\") {\n throw new Error(\n \"Wallet client does not support waitForTransactionReceipt. \" +\n \"Please use a viem PublicClient or WalletClient with public actions.\",\n );\n }\n\n try {\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: this.config.confirmationTimeout,\n });\n\n if (receipt.status !== \"success\") {\n throw new Error(`Transaction failed with status: ${receipt.status}`);\n }\n\n return receipt;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to confirm transaction: ${error.message}`);\n }\n throw new Error(\"Failed to confirm transaction: Unknown error\");\n }\n }\n\n /**\n * Get the network name\n */\n get network(): string {\n return this.config.network;\n }\n\n /**\n * Get the facilitator URL\n */\n get facilitatorUrl(): string {\n return this.config.facilitatorUrl;\n }\n\n /**\n * Get the wallet client\n */\n get wallet() {\n return this.config.wallet;\n }\n}\n","/**\n * React hook for creating X402Client instance\n *\n * This hook automatically creates an X402Client instance using wagmi's\n * wallet client and chain information.\n */\n\nimport { useMemo } from \"react\";\nimport { useWalletClient, useAccount, useChainId } from \"wagmi\";\nimport { publicActions } from \"viem\";\nimport { X402Client } from \"../client.js\";\nimport type { X402ClientConfig } from \"../types.js\";\n\n/**\n * Partial configuration for useX402Client hook\n * (wallet, network, chainId are auto-detected from wagmi)\n */\nexport type UseX402ClientConfig = Partial<Omit<X402ClientConfig, \"wallet\" | \"network\">> & {\n /** Optional: Facilitator URL (default: https://facilitator.x402x.dev/) */\n facilitatorUrl?: string;\n /** Optional: Override network name (auto-detected from chain if not provided) */\n network?: string;\n};\n\n/**\n * Map chainId to network name\n */\nconst CHAIN_ID_TO_NETWORK: Record<number, string> = {\n 84532: \"base-sepolia\",\n 8453: \"base\",\n 196: \"x-layer\",\n 1952: \"x-layer-testnet\",\n};\n\n/**\n * React hook for X402Client\n *\n * Automatically creates an X402Client instance using the connected wallet\n * from wagmi. Returns null if wallet is not connected.\n *\n * @param config - Client configuration (facilitatorUrl is optional, defaults to https://facilitator.x402x.dev/)\n * @returns X402Client instance or null if wallet not connected\n *\n * @example\n * ```typescript\n * import { useX402Client } from '@x402x/client';\n *\n * function MyComponent() {\n * // Use default facilitator\n * const client = useX402Client();\n *\n * // Or specify custom facilitator\n * const client = useX402Client({\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * if (!client) {\n * return <div>Please connect your wallet</div>;\n * }\n *\n * const handlePay = async () => {\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * };\n *\n * return <button onClick={handlePay}>Pay</button>;\n * }\n * ```\n */\nexport function useX402Client(config?: UseX402ClientConfig): X402Client | null {\n const { data: walletClient } = useWalletClient();\n const { isConnected } = useAccount();\n const chainId = useChainId();\n\n return useMemo(() => {\n if (!isConnected || !walletClient) {\n return null;\n }\n\n // Determine network name\n const network = config?.network || CHAIN_ID_TO_NETWORK[chainId];\n if (!network) {\n console.warn(\n `[x402x] Unknown chainId ${chainId}. Please provide network name explicitly in config.`,\n );\n return null;\n }\n\n try {\n // Extend wallet client with public actions (required for waitForTransactionReceipt)\n const extendedWallet = walletClient.extend(publicActions);\n\n return new X402Client({\n wallet: extendedWallet,\n network,\n facilitatorUrl: config?.facilitatorUrl,\n networkConfig: config?.networkConfig,\n timeout: config?.timeout,\n confirmationTimeout: config?.confirmationTimeout,\n });\n } catch (error) {\n console.error(\"[x402x] Failed to create X402Client:\", error);\n return null;\n }\n }, [\n isConnected,\n walletClient,\n chainId,\n config?.network,\n config?.facilitatorUrl,\n config?.networkConfig,\n config?.timeout,\n config?.confirmationTimeout,\n ]);\n}\n","/**\n * React hook for executing settlements\n *\n * This hook provides a simple interface for executing settlements with\n * automatic state management (status, error, result).\n */\n\nimport { useState, useCallback } from \"react\";\nimport { useX402Client, type UseX402ClientConfig } from \"./useX402Client.js\";\nimport type { ExecuteParams, ExecuteResult, ExecuteStatus } from \"../types.js\";\n\n/**\n * Return type for useExecute hook\n */\nexport interface UseExecuteReturn {\n /** Execute a settlement */\n execute: (params: ExecuteParams, waitForConfirmation?: boolean) => Promise<ExecuteResult>;\n /** Current execution status */\n status: ExecuteStatus;\n /** Error if execution failed */\n error: Error | null;\n /** Result if execution succeeded */\n result: ExecuteResult | null;\n /** Reset state */\n reset: () => void;\n /** Whether currently executing */\n isExecuting: boolean;\n /** Whether execution succeeded */\n isSuccess: boolean;\n /** Whether execution failed */\n isError: boolean;\n}\n\n/**\n * React hook for executing settlements\n *\n * Provides a simple interface for executing settlements with automatic\n * state management. Automatically uses the connected wallet from wagmi.\n *\n * @param config - Optional client configuration (if not using global client)\n * @returns Execute function and state\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n *\n * function PayButton() {\n * const { execute, status, error, result } = useExecute({\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n *\n * const handlePay = async () => {\n * try {\n * // Simple transfer (hook and hookData are optional)\n * const result = await execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * console.log('Success:', result.txHash);\n * } catch (err) {\n * console.error('Failed:', err);\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * {status === 'idle' ? 'Pay' : 'Processing...'}\n * </button>\n * {status === 'success' && <div>✅ Success! TX: {result.txHash}</div>}\n * {status === 'error' && <div>❌ Error: {error.message}</div>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecute(config?: UseX402ClientConfig): UseExecuteReturn {\n const client = useX402Client(config);\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n setStatus(\"idle\");\n setError(null);\n setResult(null);\n }, []);\n\n return {\n execute,\n status,\n error,\n result,\n reset,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n\n/**\n * Alternative hook that doesn't require config (uses default client from context)\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n *\n * function PayButton({ facilitatorUrl }: { facilitatorUrl: string }) {\n * const { execute, status, error } = useExecute({ facilitatorUrl });\n *\n * const handlePay = async () => {\n * await execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * recipient: '0x...'\n * });\n * };\n *\n * return (\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * Pay\n * </button>\n * );\n * }\n * ```\n */\nexport function useExecuteWithClient(\n client: ReturnType<typeof useX402Client>,\n): Omit<UseExecuteReturn, \"reset\"> {\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n return {\n execute,\n status,\n error,\n result,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@x402x/client",
3
+ "version": "0.2.0",
4
+ "description": "Client SDK for x402x Serverless Mode - execute on-chain contracts directly via facilitator",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "keywords": [
21
+ "x402",
22
+ "x402x",
23
+ "serverless",
24
+ "payment",
25
+ "blockchain",
26
+ "ethereum",
27
+ "web3",
28
+ "usdc",
29
+ "settlement"
30
+ ],
31
+ "author": "Nuwa Protocol",
32
+ "license": "Apache-2.0",
33
+ "dependencies": {
34
+ "viem": "^2.21.26",
35
+ "x402": "npm:@x402x/x402@0.6.6-patch.2",
36
+ "@x402x/core": "0.2.0"
37
+ },
38
+ "peerDependencies": {
39
+ "react": "^18.0.0",
40
+ "wagmi": "^2.15.6"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "react": {
44
+ "optional": true
45
+ },
46
+ "wagmi": {
47
+ "optional": true
48
+ }
49
+ },
50
+ "devDependencies": {
51
+ "@types/react": "^18.3.12",
52
+ "@vitest/coverage-v8": "1.6.1",
53
+ "@vitest/ui": "^1.6.0",
54
+ "prettier": "3.5.2",
55
+ "tsup": "^8.3.5",
56
+ "typescript": "^5.6.3",
57
+ "vitest": "^1.6.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup",
61
+ "dev": "tsup --watch",
62
+ "test": "vitest run",
63
+ "test:watch": "vitest",
64
+ "test:ui": "vitest --ui",
65
+ "test:coverage": "vitest run --coverage",
66
+ "type-check": "tsc --noEmit",
67
+ "format": "prettier --config ../../.prettierrc --ignore-path ../../.prettierignore --write \"**/*.{ts,tsx,js,jsx,cjs,json,md}\"",
68
+ "format:check": "prettier --config ../../.prettierrc --ignore-path ../../.prettierignore --check \"**/*.{ts,tsx,js,jsx,cjs,json,md}\""
69
+ }
70
+ }