@x402x/client 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +21 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -47
- package/dist/index.d.ts +48 -47
- package/dist/index.js +22 -7
- package/dist/index.js.map +1 -1
- package/package.json +16 -16
- package/LICENSE +0 -190
package/dist/index.cjs
CHANGED
|
@@ -141,6 +141,7 @@ function calculateTimeWindow(maxTimeoutSeconds = 300) {
|
|
|
141
141
|
}
|
|
142
142
|
|
|
143
143
|
// src/core/prepare.ts
|
|
144
|
+
var DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
144
145
|
async function queryFacilitatorFee(facilitatorUrl, network, hook, hookData = "0x") {
|
|
145
146
|
try {
|
|
146
147
|
return await core.calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);
|
|
@@ -177,10 +178,11 @@ async function prepareSettlement(params) {
|
|
|
177
178
|
validateAddress(asset, "asset");
|
|
178
179
|
const salt = params.customSalt || generateSalt();
|
|
179
180
|
let facilitatorFee = params.facilitatorFee || "0";
|
|
180
|
-
if (!params.facilitatorFee
|
|
181
|
+
if (!params.facilitatorFee) {
|
|
182
|
+
const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;
|
|
181
183
|
try {
|
|
182
184
|
const feeEstimate = await queryFacilitatorFee(
|
|
183
|
-
|
|
185
|
+
facilitatorUrl,
|
|
184
186
|
params.network,
|
|
185
187
|
params.hook,
|
|
186
188
|
params.hookData
|
|
@@ -374,7 +376,6 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
|
|
|
374
376
|
}
|
|
375
377
|
|
|
376
378
|
// src/client.ts
|
|
377
|
-
var DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
378
379
|
var X402Client = class {
|
|
379
380
|
/**
|
|
380
381
|
* Create a new X402Client instance
|
|
@@ -589,9 +590,23 @@ var CHAIN_ID_TO_NETWORK = {
|
|
|
589
590
|
1952: "x-layer-testnet"
|
|
590
591
|
};
|
|
591
592
|
function useX402Client(config) {
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
593
|
+
let walletClient;
|
|
594
|
+
let isConnected;
|
|
595
|
+
let chainId;
|
|
596
|
+
try {
|
|
597
|
+
const walletClientResult = wagmi.useWalletClient();
|
|
598
|
+
const accountResult = wagmi.useAccount();
|
|
599
|
+
const chainIdResult = wagmi.useChainId();
|
|
600
|
+
walletClient = walletClientResult.data;
|
|
601
|
+
isConnected = accountResult.isConnected;
|
|
602
|
+
chainId = chainIdResult;
|
|
603
|
+
} catch (error) {
|
|
604
|
+
if (error instanceof wagmi.WagmiProviderNotFoundError || error?.name === "WagmiProviderNotFoundError" || error instanceof Error && error.message.includes("useConfig") && error.message.includes("WagmiProvider")) {
|
|
605
|
+
return null;
|
|
606
|
+
}
|
|
607
|
+
console.warn("[x402x] Unable to access wagmi provider:", error);
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
595
610
|
return react.useMemo(() => {
|
|
596
611
|
if (!isConnected || !walletClient) {
|
|
597
612
|
return null;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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","isAddress","calculateFacilitatorFee","getNetworkConfig","calculateCommitment","signTypedData","coreSettle","TransferHook","useWalletClient","useAccount","useChainId","useMemo","publicActions","useState","useCallback","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,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AA,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.cjs","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"]}
|
|
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","isAddress","calculateFacilitatorFee","getNetworkConfig","calculateCommitment","signTypedData","coreSettle","TransferHook","useWalletClient","useAccount","useChainId","WagmiProviderNotFoundError","useMemo","publicActions","useState","useCallback","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,WAAA,CACE,OAAA,EACA,IAAA,EACgB,UAAA,EACA,QAAA,EAChB;AACA,IAAA,KAAA,CAAM,SAAS,IAAI,CAAA;AAHH,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IA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index.cjs","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 * Default facilitator URL\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\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)\n // Use the provided facilitatorUrl or fall back to default\n let facilitatorFee = params.facilitatorFee || \"0\";\n if (!params.facilitatorFee) {\n const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;\n try {\n const feeEstimate = await queryFacilitatorFee(\n 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, DEFAULT_FACILITATOR_URL } 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 * Re-export default facilitator URL for convenience\n */\nexport { DEFAULT_FACILITATOR_URL };\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 {\n useWalletClient,\n useAccount,\n useChainId,\n WagmiProviderNotFoundError,\n} 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 // First, try to get wagmi hooks outside of useMemo to catch provider errors early\n let walletClient: any;\n let isConnected: boolean;\n let chainId: number;\n\n try {\n const walletClientResult = useWalletClient();\n const accountResult = useAccount();\n const chainIdResult = useChainId();\n\n walletClient = walletClientResult.data;\n isConnected = accountResult.isConnected;\n chainId = chainIdResult;\n } catch (error) {\n // If wagmi provider context is missing (e.g., during early render), return null quietly\n if (\n error instanceof WagmiProviderNotFoundError ||\n (error as any)?.name === \"WagmiProviderNotFoundError\" ||\n error instanceof Error && error.message.includes(\"useConfig\") && error.message.includes(\"WagmiProvider\")\n ) {\n return null;\n }\n\n console.warn(\"[x402x] Unable to access wagmi provider:\", error);\n return null;\n }\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/dist/index.d.cts
CHANGED
|
@@ -199,10 +199,56 @@ interface SettleResult {
|
|
|
199
199
|
errorReason?: string;
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
+
/**
|
|
203
|
+
* Prepare settlement data for signing
|
|
204
|
+
*
|
|
205
|
+
* This module handles the preparation of settlement parameters before signing,
|
|
206
|
+
* including generating salt, calculating commitment hash, and fetching facilitator fees.
|
|
207
|
+
*/
|
|
208
|
+
|
|
202
209
|
/**
|
|
203
210
|
* Default facilitator URL
|
|
204
211
|
*/
|
|
205
212
|
declare const DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
213
|
+
/**
|
|
214
|
+
* Prepare settlement data for signing
|
|
215
|
+
*
|
|
216
|
+
* This function:
|
|
217
|
+
* 1. Validates all parameters
|
|
218
|
+
* 2. Loads network configuration
|
|
219
|
+
* 3. Generates salt (if not provided)
|
|
220
|
+
* 4. Queries facilitator fee (if not provided)
|
|
221
|
+
* 5. Calculates time window (if not provided)
|
|
222
|
+
* 6. Calculates commitment hash
|
|
223
|
+
* 7. Returns prepared settlement data
|
|
224
|
+
*
|
|
225
|
+
* @param params - Preparation parameters
|
|
226
|
+
* @returns Prepared settlement data ready for signing
|
|
227
|
+
*
|
|
228
|
+
* @throws NetworkError if network is unsupported
|
|
229
|
+
* @throws ValidationError if parameters are invalid
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* import { prepareSettlement } from '@x402x/client';
|
|
234
|
+
* import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';
|
|
235
|
+
*
|
|
236
|
+
* // Convert USD amount to atomic units first
|
|
237
|
+
* const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'
|
|
238
|
+
*
|
|
239
|
+
* const settlement = await prepareSettlement({
|
|
240
|
+
* wallet: walletClient,
|
|
241
|
+
* network: 'base-sepolia',
|
|
242
|
+
* hook: TransferHook.getAddress('base-sepolia'),
|
|
243
|
+
* hookData: TransferHook.encode(),
|
|
244
|
+
* amount: atomicAmount, // Must be atomic units
|
|
245
|
+
* payTo: '0x...',
|
|
246
|
+
* facilitatorUrl: 'https://facilitator.x402x.dev'
|
|
247
|
+
* });
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
|
|
251
|
+
|
|
206
252
|
/**
|
|
207
253
|
* X402Client - High-level client for x402x Serverless Mode
|
|
208
254
|
*
|
|
@@ -369,6 +415,7 @@ declare class X402Client {
|
|
|
369
415
|
uid: string;
|
|
370
416
|
addChain: (args: viem.AddChainParameters) => Promise<void>;
|
|
371
417
|
deployContract: <const abi extends viem.Abi | readonly unknown[], chainOverride extends viem.Chain | undefined>(args: viem.DeployContractParameters<abi, viem.Chain | undefined, viem.Account | undefined, chainOverride>) => Promise<viem.DeployContractReturnType>;
|
|
418
|
+
fillTransaction: <chainOverride extends viem.Chain | undefined = undefined, accountOverride extends viem.Account | Address | undefined = undefined>(args: viem.FillTransactionParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, accountOverride>) => Promise<viem.FillTransactionReturnType<viem.Chain | undefined, chainOverride>>;
|
|
372
419
|
getAddresses: () => Promise<viem.GetAddressesReturnType>;
|
|
373
420
|
getCallsStatus: (parameters: viem.GetCallsStatusParameters) => Promise<viem.GetCallsStatusReturnType>;
|
|
374
421
|
getCapabilities: <chainId extends number | undefined>(parameters?: viem.GetCapabilitiesParameters<chainId>) => Promise<viem.GetCapabilitiesReturnType<chainId>>;
|
|
@@ -3653,7 +3700,7 @@ declare class X402Client {
|
|
|
3653
3700
|
sendRawTransaction: (args: viem.SendRawTransactionParameters) => Promise<viem.SendRawTransactionReturnType>;
|
|
3654
3701
|
sendRawTransactionSync: (args: viem.SendRawTransactionSyncParameters) => Promise<TransactionReceipt>;
|
|
3655
3702
|
sendTransaction: <const request extends viem.SendTransactionRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<viem.SendTransactionReturnType>;
|
|
3656
|
-
sendTransactionSync: <const request extends viem.SendTransactionSyncRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionSyncParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<
|
|
3703
|
+
sendTransactionSync: <const request extends viem.SendTransactionSyncRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionSyncParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<TransactionReceipt>;
|
|
3657
3704
|
showCallsStatus: (parameters: viem.ShowCallsStatusParameters) => Promise<viem.ShowCallsStatusReturnType>;
|
|
3658
3705
|
signAuthorization: (parameters: viem.SignAuthorizationParameters<viem.Account | undefined>) => Promise<viem.SignAuthorizationReturnType>;
|
|
3659
3706
|
signMessage: (args: viem.SignMessageParameters<viem.Account | undefined>) => Promise<viem.SignMessageReturnType>;
|
|
@@ -4781,52 +4828,6 @@ declare class X402Client {
|
|
|
4781
4828
|
};
|
|
4782
4829
|
}
|
|
4783
4830
|
|
|
4784
|
-
/**
|
|
4785
|
-
* Prepare settlement data for signing
|
|
4786
|
-
*
|
|
4787
|
-
* This module handles the preparation of settlement parameters before signing,
|
|
4788
|
-
* including generating salt, calculating commitment hash, and fetching facilitator fees.
|
|
4789
|
-
*/
|
|
4790
|
-
|
|
4791
|
-
/**
|
|
4792
|
-
* Prepare settlement data for signing
|
|
4793
|
-
*
|
|
4794
|
-
* This function:
|
|
4795
|
-
* 1. Validates all parameters
|
|
4796
|
-
* 2. Loads network configuration
|
|
4797
|
-
* 3. Generates salt (if not provided)
|
|
4798
|
-
* 4. Queries facilitator fee (if not provided)
|
|
4799
|
-
* 5. Calculates time window (if not provided)
|
|
4800
|
-
* 6. Calculates commitment hash
|
|
4801
|
-
* 7. Returns prepared settlement data
|
|
4802
|
-
*
|
|
4803
|
-
* @param params - Preparation parameters
|
|
4804
|
-
* @returns Prepared settlement data ready for signing
|
|
4805
|
-
*
|
|
4806
|
-
* @throws NetworkError if network is unsupported
|
|
4807
|
-
* @throws ValidationError if parameters are invalid
|
|
4808
|
-
*
|
|
4809
|
-
* @example
|
|
4810
|
-
* ```typescript
|
|
4811
|
-
* import { prepareSettlement } from '@x402x/client';
|
|
4812
|
-
* import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';
|
|
4813
|
-
*
|
|
4814
|
-
* // Convert USD amount to atomic units first
|
|
4815
|
-
* const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'
|
|
4816
|
-
*
|
|
4817
|
-
* const settlement = await prepareSettlement({
|
|
4818
|
-
* wallet: walletClient,
|
|
4819
|
-
* network: 'base-sepolia',
|
|
4820
|
-
* hook: TransferHook.getAddress('base-sepolia'),
|
|
4821
|
-
* hookData: TransferHook.encode(),
|
|
4822
|
-
* amount: atomicAmount, // Must be atomic units
|
|
4823
|
-
* payTo: '0x...',
|
|
4824
|
-
* facilitatorUrl: 'https://facilitator.x402x.dev'
|
|
4825
|
-
* });
|
|
4826
|
-
* ```
|
|
4827
|
-
*/
|
|
4828
|
-
declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
|
|
4829
|
-
|
|
4830
4831
|
/**
|
|
4831
4832
|
* Sign EIP-3009 authorization for settlement
|
|
4832
4833
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -199,10 +199,56 @@ interface SettleResult {
|
|
|
199
199
|
errorReason?: string;
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
+
/**
|
|
203
|
+
* Prepare settlement data for signing
|
|
204
|
+
*
|
|
205
|
+
* This module handles the preparation of settlement parameters before signing,
|
|
206
|
+
* including generating salt, calculating commitment hash, and fetching facilitator fees.
|
|
207
|
+
*/
|
|
208
|
+
|
|
202
209
|
/**
|
|
203
210
|
* Default facilitator URL
|
|
204
211
|
*/
|
|
205
212
|
declare const DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
213
|
+
/**
|
|
214
|
+
* Prepare settlement data for signing
|
|
215
|
+
*
|
|
216
|
+
* This function:
|
|
217
|
+
* 1. Validates all parameters
|
|
218
|
+
* 2. Loads network configuration
|
|
219
|
+
* 3. Generates salt (if not provided)
|
|
220
|
+
* 4. Queries facilitator fee (if not provided)
|
|
221
|
+
* 5. Calculates time window (if not provided)
|
|
222
|
+
* 6. Calculates commitment hash
|
|
223
|
+
* 7. Returns prepared settlement data
|
|
224
|
+
*
|
|
225
|
+
* @param params - Preparation parameters
|
|
226
|
+
* @returns Prepared settlement data ready for signing
|
|
227
|
+
*
|
|
228
|
+
* @throws NetworkError if network is unsupported
|
|
229
|
+
* @throws ValidationError if parameters are invalid
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* import { prepareSettlement } from '@x402x/client';
|
|
234
|
+
* import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';
|
|
235
|
+
*
|
|
236
|
+
* // Convert USD amount to atomic units first
|
|
237
|
+
* const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'
|
|
238
|
+
*
|
|
239
|
+
* const settlement = await prepareSettlement({
|
|
240
|
+
* wallet: walletClient,
|
|
241
|
+
* network: 'base-sepolia',
|
|
242
|
+
* hook: TransferHook.getAddress('base-sepolia'),
|
|
243
|
+
* hookData: TransferHook.encode(),
|
|
244
|
+
* amount: atomicAmount, // Must be atomic units
|
|
245
|
+
* payTo: '0x...',
|
|
246
|
+
* facilitatorUrl: 'https://facilitator.x402x.dev'
|
|
247
|
+
* });
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
|
|
251
|
+
|
|
206
252
|
/**
|
|
207
253
|
* X402Client - High-level client for x402x Serverless Mode
|
|
208
254
|
*
|
|
@@ -369,6 +415,7 @@ declare class X402Client {
|
|
|
369
415
|
uid: string;
|
|
370
416
|
addChain: (args: viem.AddChainParameters) => Promise<void>;
|
|
371
417
|
deployContract: <const abi extends viem.Abi | readonly unknown[], chainOverride extends viem.Chain | undefined>(args: viem.DeployContractParameters<abi, viem.Chain | undefined, viem.Account | undefined, chainOverride>) => Promise<viem.DeployContractReturnType>;
|
|
418
|
+
fillTransaction: <chainOverride extends viem.Chain | undefined = undefined, accountOverride extends viem.Account | Address | undefined = undefined>(args: viem.FillTransactionParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, accountOverride>) => Promise<viem.FillTransactionReturnType<viem.Chain | undefined, chainOverride>>;
|
|
372
419
|
getAddresses: () => Promise<viem.GetAddressesReturnType>;
|
|
373
420
|
getCallsStatus: (parameters: viem.GetCallsStatusParameters) => Promise<viem.GetCallsStatusReturnType>;
|
|
374
421
|
getCapabilities: <chainId extends number | undefined>(parameters?: viem.GetCapabilitiesParameters<chainId>) => Promise<viem.GetCapabilitiesReturnType<chainId>>;
|
|
@@ -3653,7 +3700,7 @@ declare class X402Client {
|
|
|
3653
3700
|
sendRawTransaction: (args: viem.SendRawTransactionParameters) => Promise<viem.SendRawTransactionReturnType>;
|
|
3654
3701
|
sendRawTransactionSync: (args: viem.SendRawTransactionSyncParameters) => Promise<TransactionReceipt>;
|
|
3655
3702
|
sendTransaction: <const request extends viem.SendTransactionRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<viem.SendTransactionReturnType>;
|
|
3656
|
-
sendTransactionSync: <const request extends viem.SendTransactionSyncRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionSyncParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<
|
|
3703
|
+
sendTransactionSync: <const request extends viem.SendTransactionSyncRequest<viem.Chain | undefined, chainOverride>, chainOverride extends viem.Chain | undefined = undefined>(args: viem.SendTransactionSyncParameters<viem.Chain | undefined, viem.Account | undefined, chainOverride, request>) => Promise<TransactionReceipt>;
|
|
3657
3704
|
showCallsStatus: (parameters: viem.ShowCallsStatusParameters) => Promise<viem.ShowCallsStatusReturnType>;
|
|
3658
3705
|
signAuthorization: (parameters: viem.SignAuthorizationParameters<viem.Account | undefined>) => Promise<viem.SignAuthorizationReturnType>;
|
|
3659
3706
|
signMessage: (args: viem.SignMessageParameters<viem.Account | undefined>) => Promise<viem.SignMessageReturnType>;
|
|
@@ -4781,52 +4828,6 @@ declare class X402Client {
|
|
|
4781
4828
|
};
|
|
4782
4829
|
}
|
|
4783
4830
|
|
|
4784
|
-
/**
|
|
4785
|
-
* Prepare settlement data for signing
|
|
4786
|
-
*
|
|
4787
|
-
* This module handles the preparation of settlement parameters before signing,
|
|
4788
|
-
* including generating salt, calculating commitment hash, and fetching facilitator fees.
|
|
4789
|
-
*/
|
|
4790
|
-
|
|
4791
|
-
/**
|
|
4792
|
-
* Prepare settlement data for signing
|
|
4793
|
-
*
|
|
4794
|
-
* This function:
|
|
4795
|
-
* 1. Validates all parameters
|
|
4796
|
-
* 2. Loads network configuration
|
|
4797
|
-
* 3. Generates salt (if not provided)
|
|
4798
|
-
* 4. Queries facilitator fee (if not provided)
|
|
4799
|
-
* 5. Calculates time window (if not provided)
|
|
4800
|
-
* 6. Calculates commitment hash
|
|
4801
|
-
* 7. Returns prepared settlement data
|
|
4802
|
-
*
|
|
4803
|
-
* @param params - Preparation parameters
|
|
4804
|
-
* @returns Prepared settlement data ready for signing
|
|
4805
|
-
*
|
|
4806
|
-
* @throws NetworkError if network is unsupported
|
|
4807
|
-
* @throws ValidationError if parameters are invalid
|
|
4808
|
-
*
|
|
4809
|
-
* @example
|
|
4810
|
-
* ```typescript
|
|
4811
|
-
* import { prepareSettlement } from '@x402x/client';
|
|
4812
|
-
* import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';
|
|
4813
|
-
*
|
|
4814
|
-
* // Convert USD amount to atomic units first
|
|
4815
|
-
* const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'
|
|
4816
|
-
*
|
|
4817
|
-
* const settlement = await prepareSettlement({
|
|
4818
|
-
* wallet: walletClient,
|
|
4819
|
-
* network: 'base-sepolia',
|
|
4820
|
-
* hook: TransferHook.getAddress('base-sepolia'),
|
|
4821
|
-
* hookData: TransferHook.encode(),
|
|
4822
|
-
* amount: atomicAmount, // Must be atomic units
|
|
4823
|
-
* payTo: '0x...',
|
|
4824
|
-
* facilitatorUrl: 'https://facilitator.x402x.dev'
|
|
4825
|
-
* });
|
|
4826
|
-
* ```
|
|
4827
|
-
*/
|
|
4828
|
-
declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
|
|
4829
|
-
|
|
4830
4831
|
/**
|
|
4831
4832
|
* Sign EIP-3009 authorization for settlement
|
|
4832
4833
|
*
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ export { AmountError, formatDefaultAssetAmount, parseDefaultAssetAmount } from '
|
|
|
3
3
|
import { getAddress, publicActions, isAddress } from 'viem';
|
|
4
4
|
import { signTypedData } from 'viem/actions';
|
|
5
5
|
import { useMemo, useState, useCallback } from 'react';
|
|
6
|
-
import { useWalletClient, useAccount, useChainId } from 'wagmi';
|
|
6
|
+
import { useWalletClient, useAccount, useChainId, WagmiProviderNotFoundError } from 'wagmi';
|
|
7
7
|
|
|
8
8
|
// src/client.ts
|
|
9
9
|
|
|
@@ -140,6 +140,7 @@ function calculateTimeWindow(maxTimeoutSeconds = 300) {
|
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
// src/core/prepare.ts
|
|
143
|
+
var DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
143
144
|
async function queryFacilitatorFee(facilitatorUrl, network, hook, hookData = "0x") {
|
|
144
145
|
try {
|
|
145
146
|
return await calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);
|
|
@@ -176,10 +177,11 @@ async function prepareSettlement(params) {
|
|
|
176
177
|
validateAddress(asset, "asset");
|
|
177
178
|
const salt = params.customSalt || generateSalt();
|
|
178
179
|
let facilitatorFee = params.facilitatorFee || "0";
|
|
179
|
-
if (!params.facilitatorFee
|
|
180
|
+
if (!params.facilitatorFee) {
|
|
181
|
+
const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;
|
|
180
182
|
try {
|
|
181
183
|
const feeEstimate = await queryFacilitatorFee(
|
|
182
|
-
|
|
184
|
+
facilitatorUrl,
|
|
183
185
|
params.network,
|
|
184
186
|
params.hook,
|
|
185
187
|
params.hookData
|
|
@@ -373,7 +375,6 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
|
|
|
373
375
|
}
|
|
374
376
|
|
|
375
377
|
// src/client.ts
|
|
376
|
-
var DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
|
|
377
378
|
var X402Client = class {
|
|
378
379
|
/**
|
|
379
380
|
* Create a new X402Client instance
|
|
@@ -588,9 +589,23 @@ var CHAIN_ID_TO_NETWORK = {
|
|
|
588
589
|
1952: "x-layer-testnet"
|
|
589
590
|
};
|
|
590
591
|
function useX402Client(config) {
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
592
|
+
let walletClient;
|
|
593
|
+
let isConnected;
|
|
594
|
+
let chainId;
|
|
595
|
+
try {
|
|
596
|
+
const walletClientResult = useWalletClient();
|
|
597
|
+
const accountResult = useAccount();
|
|
598
|
+
const chainIdResult = useChainId();
|
|
599
|
+
walletClient = walletClientResult.data;
|
|
600
|
+
isConnected = accountResult.isConnected;
|
|
601
|
+
chainId = chainIdResult;
|
|
602
|
+
} catch (error) {
|
|
603
|
+
if (error instanceof WagmiProviderNotFoundError || error?.name === "WagmiProviderNotFoundError" || error instanceof Error && error.message.includes("useConfig") && error.message.includes("WagmiProvider")) {
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
console.warn("[x402x] Unable to access wagmi provider:", error);
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
594
609
|
return useMemo(() => {
|
|
595
610
|
if (!isConnected || !walletClient) {
|
|
596
611
|
return null;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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,I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,QAAQ,mBAAmB,CAAA;AACtE,QAAA,SAAA,CAAU,SAAS,CAAA;AACnB,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"]}
|
|
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,WA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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 * Default facilitator URL\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\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)\n // Use the provided facilitatorUrl or fall back to default\n let facilitatorFee = params.facilitatorFee || \"0\";\n if (!params.facilitatorFee) {\n const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;\n try {\n const feeEstimate = await queryFacilitatorFee(\n 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, DEFAULT_FACILITATOR_URL } 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 * Re-export default facilitator URL for convenience\n */\nexport { DEFAULT_FACILITATOR_URL };\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 {\n useWalletClient,\n useAccount,\n useChainId,\n WagmiProviderNotFoundError,\n} 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 // First, try to get wagmi hooks outside of useMemo to catch provider errors early\n let walletClient: any;\n let isConnected: boolean;\n let chainId: number;\n\n try {\n const walletClientResult = useWalletClient();\n const accountResult = useAccount();\n const chainIdResult = useChainId();\n\n walletClient = walletClientResult.data;\n isConnected = accountResult.isConnected;\n chainId = chainIdResult;\n } catch (error) {\n // If wagmi provider context is missing (e.g., during early render), return null quietly\n if (\n error instanceof WagmiProviderNotFoundError ||\n (error as any)?.name === \"WagmiProviderNotFoundError\" ||\n error instanceof Error && error.message.includes(\"useConfig\") && error.message.includes(\"WagmiProvider\")\n ) {\n return null;\n }\n\n console.warn(\"[x402x] Unable to access wagmi provider:\", error);\n return null;\n }\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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x402x/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Client SDK for x402x Serverless Mode - execute on-chain contracts directly via facilitator",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -17,6 +17,17 @@
|
|
|
17
17
|
"dist",
|
|
18
18
|
"README.md"
|
|
19
19
|
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsup",
|
|
22
|
+
"dev": "tsup --watch",
|
|
23
|
+
"test": "vitest run",
|
|
24
|
+
"test:watch": "vitest",
|
|
25
|
+
"test:ui": "vitest --ui",
|
|
26
|
+
"test:coverage": "vitest run --coverage",
|
|
27
|
+
"type-check": "tsc --noEmit",
|
|
28
|
+
"format": "prettier --config ../../.prettierrc --ignore-path ../../.prettierignore --write \"**/*.{ts,tsx,js,jsx,cjs,json,md}\"",
|
|
29
|
+
"format:check": "prettier --config ../../.prettierrc --ignore-path ../../.prettierignore --check \"**/*.{ts,tsx,js,jsx,cjs,json,md}\""
|
|
30
|
+
},
|
|
20
31
|
"keywords": [
|
|
21
32
|
"x402",
|
|
22
33
|
"x402x",
|
|
@@ -31,9 +42,9 @@
|
|
|
31
42
|
"author": "Nuwa Protocol",
|
|
32
43
|
"license": "Apache-2.0",
|
|
33
44
|
"dependencies": {
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
45
|
+
"@x402x/core": "workspace:*",
|
|
46
|
+
"viem": "2.40.3",
|
|
47
|
+
"x402": "npm:@x402x/x402@^0.6.6-patch.3"
|
|
37
48
|
},
|
|
38
49
|
"peerDependencies": {
|
|
39
50
|
"react": "^18.0.0",
|
|
@@ -55,16 +66,5 @@
|
|
|
55
66
|
"tsup": "^8.3.5",
|
|
56
67
|
"typescript": "^5.6.3",
|
|
57
68
|
"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
69
|
}
|
|
70
|
-
}
|
|
70
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,190 +0,0 @@
|
|
|
1
|
-
Apache License
|
|
2
|
-
Version 2.0, January 2004
|
|
3
|
-
http://www.apache.org/licenses/
|
|
4
|
-
|
|
5
|
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
-
|
|
7
|
-
1. Definitions.
|
|
8
|
-
|
|
9
|
-
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
-
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
-
|
|
12
|
-
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
-
the copyright owner that is granting the License.
|
|
14
|
-
|
|
15
|
-
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
-
other entities that control, are controlled by, or are under common
|
|
17
|
-
control with that entity. For the purposes of this definition,
|
|
18
|
-
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
-
direction or management of such entity, whether by contract or
|
|
20
|
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
Copyright 2025 Nuwa Protocol
|
|
179
|
-
|
|
180
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
-
you may not use this file except in compliance with the License.
|
|
182
|
-
You may obtain a copy of the License at
|
|
183
|
-
|
|
184
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
-
|
|
186
|
-
Unless required by applicable law or agreed to in writing, software
|
|
187
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
-
See the License for the specific language governing permissions and
|
|
190
|
-
limitations under the License.
|