@x402x/client 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,7 +47,7 @@ Client → Facilitator → Smart Contract (Hook)
47
47
  import { parseDefaultAssetAmount } from "@x402x/extensions";
48
48
 
49
49
  const atomicAmount = parseDefaultAssetAmount("1", network); // '1000000'
50
- const client = new X402Client({ wallet, network, facilitatorUrl });
50
+ const client = new x402xClient({ wallet, network, facilitatorUrl });
51
51
  const result = await client.execute({
52
52
  hook: TransferHook.address,
53
53
  amount: atomicAmount, // Must be atomic units
@@ -74,7 +74,7 @@ yarn add @x402x/client @x402x/extensions
74
74
  ### Basic Usage (React + wagmi)
75
75
 
76
76
  ```typescript
77
- import { X402Client } from '@x402x/client';
77
+ import { x402xClient } from '@x402x/client';
78
78
  import { TransferHook, parseDefaultAssetAmount } from '@x402x/extensions';
79
79
  import { useWalletClient } from 'wagmi';
80
80
  import { publicActions } from 'viem';
@@ -87,7 +87,7 @@ function PayButton() {
87
87
  const extendedWallet = wallet.extend(publicActions);
88
88
 
89
89
  // Uses default facilitator at https://facilitator.x402x.dev/
90
- const client = new X402Client({
90
+ const client = new x402xClient({
91
91
  wallet: extendedWallet,
92
92
  network: 'base-sepolia'
93
93
  });
@@ -109,7 +109,7 @@ function PayButton() {
109
109
  }
110
110
  ```
111
111
 
112
- > **Note**: The wallet client must be extended with `publicActions` from viem to support transaction confirmation via `waitForTransactionReceipt`. If you're using the React hooks (`useX402Client`), this is done automatically.
112
+ > **Note**: The wallet client must be extended with `publicActions` from viem to support transaction confirmation via `waitForTransactionReceipt`. If you're using the React hooks (`useX402xClient`), this is done automatically.
113
113
 
114
114
  ---
115
115
 
@@ -142,10 +142,10 @@ const displayAmount = formatDefaultAssetAmount("1000000", "base-sepolia"); // '1
142
142
  ### Example
143
143
 
144
144
  ```typescript
145
- import { X402Client } from "@x402x/client";
145
+ import { x402xClient } from "@x402x/client";
146
146
  import { parseDefaultAssetAmount } from "@x402x/extensions";
147
147
 
148
- const client = new X402Client({ wallet, network: "base-sepolia" });
148
+ const client = new x402xClient({ wallet, network: "base-sepolia" });
149
149
 
150
150
  // ✅ Correct: Convert first, then pass atomic units
151
151
  const atomicAmount = parseDefaultAssetAmount("5", "base-sepolia");
@@ -161,13 +161,13 @@ await client.execute({ amount: "5", payTo: "0x..." }); // Will fail validation
161
161
 
162
162
  ### High-Level API (Recommended)
163
163
 
164
- #### X402Client
164
+ #### x402xClient
165
165
 
166
166
  The main client class that handles the entire settlement flow.
167
167
 
168
168
  ```typescript
169
- class X402Client {
170
- constructor(config: X402ClientConfig);
169
+ class x402xClient {
170
+ constructor(config: x402xClientConfig);
171
171
  execute(params: ExecuteParams): Promise<ExecuteResult>;
172
172
  calculateFee(hook: Address, hookData?: Hex): Promise<FeeCalculationResult>;
173
173
  waitForTransaction(txHash: Hex): Promise<TransactionReceipt>;
@@ -177,16 +177,16 @@ class X402Client {
177
177
  **Example:**
178
178
 
179
179
  ```typescript
180
- import { X402Client } from "@x402x/client";
180
+ import { x402xClient } from "@x402x/client";
181
181
 
182
182
  // Uses default facilitator at https://facilitator.x402x.dev/
183
- const client = new X402Client({
183
+ const client = new x402xClient({
184
184
  wallet: walletClient,
185
185
  network: "base-sepolia",
186
186
  });
187
187
 
188
188
  // Or specify custom facilitator
189
- const client = new X402Client({
189
+ const client = new x402xClient({
190
190
  wallet: walletClient,
191
191
  network: "base-sepolia",
192
192
  facilitatorUrl: "https://custom-facilitator.example.com",
@@ -210,19 +210,19 @@ const result = await client.execute({
210
210
 
211
211
  #### React Hooks
212
212
 
213
- ##### useX402Client
213
+ ##### useX402xClient
214
214
 
215
- Automatically creates an X402Client using wagmi's wallet connection.
215
+ Automatically creates an x402xClient using wagmi's wallet connection.
216
216
 
217
217
  ```typescript
218
- import { useX402Client } from '@x402x/client';
218
+ import { useX402xClient } from '@x402x/client';
219
219
 
220
220
  function MyComponent() {
221
221
  // Uses default facilitator at https://facilitator.x402x.dev/
222
- const client = useX402Client();
222
+ const client = useX402xClient();
223
223
 
224
224
  // Or specify custom facilitator
225
- const client = useX402Client({
225
+ const client = useX402xClient({
226
226
  facilitatorUrl: 'https://custom-facilitator.example.com'
227
227
  });
228
228
 
@@ -301,7 +301,7 @@ Understanding the x402 protocol terminology used in this SDK:
301
301
 
302
302
  **Execute** (high-level API) - Complete end-to-end payment flow including preparation, signing, settlement, and confirmation.
303
303
 
304
- - In @x402x/client: `X402Client.execute()` method
304
+ - In @x402x/client: `x402xClient.execute()` method
305
305
  - Flow: `prepare → sign → settle → wait for confirmation`
306
306
  - Use case: One-line payment execution for most developers
307
307
 
@@ -376,11 +376,11 @@ const result = await settle("https://facilitator.x402x.dev", signed);
376
376
  ### Example 1: Simple Payment
377
377
 
378
378
  ```typescript
379
- import { X402Client } from "@x402x/client";
379
+ import { x402xClient } from "@x402x/client";
380
380
  import { TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
381
381
 
382
382
  // Uses default facilitator at https://facilitator.x402x.dev/
383
- const client = new X402Client({
383
+ const client = new x402xClient({
384
384
  wallet: walletClient,
385
385
  network: "base-sepolia",
386
386
  });
@@ -403,10 +403,10 @@ console.log("Transaction:", result.txHash);
403
403
  TransferHook supports distributing funds to multiple recipients by percentage:
404
404
 
405
405
  ```typescript
406
- import { X402Client } from "@x402x/client";
406
+ import { x402xClient } from "@x402x/client";
407
407
  import { TransferHook, parseDefaultAssetAmount, type Split } from "@x402x/extensions";
408
408
 
409
- const client = new X402Client({
409
+ const client = new x402xClient({
410
410
  wallet: walletClient,
411
411
  network: "base-sepolia",
412
412
  });
@@ -526,7 +526,7 @@ console.log("Transaction:", result.transaction);
526
526
 
527
527
  ```typescript
528
528
  import { ref } from "vue";
529
- import { X402Client } from "@x402x/client";
529
+ import { x402xClient } from "@x402x/client";
530
530
  import { TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
531
531
 
532
532
  export function usePayment() {
@@ -538,7 +538,7 @@ export function usePayment() {
538
538
  error.value = null;
539
539
 
540
540
  try {
541
- const client = new X402Client({
541
+ const client = new x402xClient({
542
542
  wallet: walletClient,
543
543
  network,
544
544
  facilitatorUrl: import.meta.env.VITE_FACILITATOR_URL,
@@ -575,7 +575,7 @@ The SDK provides typed error classes for better error handling:
575
575
 
576
576
  ```typescript
577
577
  import {
578
- X402ClientError,
578
+ x402xClientError,
579
579
  NetworkError,
580
580
  SigningError,
581
581
  FacilitatorError,
@@ -608,7 +608,7 @@ Full TypeScript support with comprehensive type definitions:
608
608
 
609
609
  ```typescript
610
610
  import type {
611
- X402ClientConfig,
611
+ x402xClientConfig,
612
612
  ExecuteParams,
613
613
  ExecuteResult,
614
614
  SettlementData,
package/dist/index.cjs CHANGED
@@ -392,9 +392,9 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
392
392
  }
393
393
 
394
394
  // src/client.ts
395
- var X402Client = class {
395
+ var x402xClient = class {
396
396
  /**
397
- * Create a new X402Client instance
397
+ * Create a new x402xClient instance
398
398
  *
399
399
  * @param config - Client configuration
400
400
  * @throws NetworkError if network is unsupported
@@ -607,7 +607,7 @@ var CHAIN_ID_TO_NETWORK = {
607
607
  97: "bsc-testnet",
608
608
  56: "bsc"
609
609
  };
610
- function useX402Client(config) {
610
+ function useX402xClient(config) {
611
611
  let walletClient;
612
612
  let isConnected;
613
613
  let chainId;
@@ -638,7 +638,7 @@ function useX402Client(config) {
638
638
  }
639
639
  try {
640
640
  const extendedWallet = walletClient.extend(viem.publicActions);
641
- return new X402Client({
641
+ return new x402xClient({
642
642
  wallet: extendedWallet,
643
643
  network,
644
644
  facilitatorUrl: config?.facilitatorUrl,
@@ -647,7 +647,7 @@ function useX402Client(config) {
647
647
  confirmationTimeout: config?.confirmationTimeout
648
648
  });
649
649
  } catch (error) {
650
- console.error("[x402x] Failed to create X402Client:", error);
650
+ console.error("[x402x] Failed to create x402xClient:", error);
651
651
  return null;
652
652
  }
653
653
  }, [
@@ -662,7 +662,7 @@ function useX402Client(config) {
662
662
  ]);
663
663
  }
664
664
  function useExecute(config) {
665
- const client = useX402Client(config);
665
+ const client = useX402xClient(config);
666
666
  const [status, setStatus] = react.useState("idle");
667
667
  const [error, setError] = react.useState(null);
668
668
  const [result, setResult] = react.useState(null);
@@ -723,7 +723,7 @@ exports.NetworkError = NetworkError;
723
723
  exports.SigningError = SigningError;
724
724
  exports.TransactionError = TransactionError;
725
725
  exports.ValidationError = ValidationError;
726
- exports.X402Client = X402Client;
726
+ exports.X402Client = x402xClient;
727
727
  exports.X402ClientError = X402ClientError;
728
728
  exports.calculateTimeWindow = calculateTimeWindow;
729
729
  exports.formatFacilitatorUrl = formatFacilitatorUrl;
@@ -733,6 +733,8 @@ exports.prepareSettlement = prepareSettlement;
733
733
  exports.settle = settle;
734
734
  exports.signAuthorization = signAuthorization;
735
735
  exports.useExecute = useExecute;
736
- exports.useX402Client = useX402Client;
736
+ exports.useX402Client = useX402xClient;
737
+ exports.useX402xClient = useX402xClient;
738
+ exports.x402xClient = x402xClient;
737
739
  //# sourceMappingURL=index.cjs.map
738
740
  //# sourceMappingURL=index.cjs.map
@@ -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","toCanonicalNetworkKey","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;AAC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,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 cryptoObj = (globalThis as any).crypto as Crypto | undefined;\n\n if (!cryptoObj || !cryptoObj.getRandomValues) {\n throw new Error(\"crypto.getRandomValues is not available\");\n }\n\n const randomBytes = cryptoObj.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/extensions\";\nimport { calculateCommitment } from \"@x402x/extensions\";\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: ${\n error instanceof Error ? error.message : \"Unknown\"\n }`,\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 // Use original network name for API compatibility; conversion to canonical format happens during settlement\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, toCanonicalNetworkKey } from \"@x402x/extensions\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * EVM Exact Scheme Authorization structure\n * Standard x402 v2 authorization format for EIP-3009\n */\ninterface ExactEvmAuthorization {\n from: Address;\n to: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: Hex;\n}\n\n/**\n * EVM Exact Scheme Payload structure\n * Standard x402 v2 payload format\n */\ninterface ExactEvmPayload {\n signature: Hex;\n authorization: ExactEvmAuthorization;\n}\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 // Convert network to CAIP-2 format for v2 protocol\n const canonicalNetwork = toCanonicalNetworkKey(signed.settlement.network);\n\n // Calculate total amount (business amount + facilitator fee)\n // This MUST match what was used in commitment calculation\n const totalAmount = (\n BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)\n ).toString();\n\n // Construct standard x402 v2 PaymentPayload\n // Using standard EVM exact scheme payload structure\n const exactEvmPayload: ExactEvmPayload = {\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 const paymentPayload: PaymentPayload = {\n x402Version: 2, // Use v2 protocol\n resource: {\n url: \"https://x402x.dev/serverless\",\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n },\n accepted: {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats\n asset: signed.settlement.asset as Address,\n amount: totalAmount, // Use totalAmount to match commitment calculation\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300,\n extra: {},\n },\n // Standard EVM exact scheme payload\n payload: exactEvmPayload as any, // Type cast required: ExactEvmPayload structure matches v2 protocol\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n // IMPORTANT: Use totalAmount (amount + fee) to match commitment calculation\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts CAIP-2 format\n amount: totalAmount, // Total amount including facilitator fee\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\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 // Call core's settle method with standard x402 v2 payload structure\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/extensions\";\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 { useWalletClient, useAccount, useChainId, WagmiProviderNotFoundError } 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 97: \"bsc-testnet\",\n 56: \"bsc\",\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 &&\n error.message.includes(\"useConfig\") &&\n 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"]}
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/useX402xClient.ts","../src/hooks/useExecute.ts"],"names":["getAddress","isAddress","calculateFacilitatorFee","getNetworkConfig","calculateCommitment","signTypedData","toCanonicalNetworkKey","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,U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,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,GAAQD,kBAAY,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.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 cryptoObj = (globalThis as any).crypto as Crypto | undefined;\n\n if (!cryptoObj || !cryptoObj.getRandomValues) {\n throw new Error(\"crypto.getRandomValues is not available\");\n }\n\n const randomBytes = cryptoObj.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/extensions\";\nimport { calculateCommitment } from \"@x402x/extensions\";\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: ${\n error instanceof Error ? error.message : \"Unknown\"\n }`,\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 // Use original network name for API compatibility; conversion to canonical format happens during settlement\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, toCanonicalNetworkKey } from \"@x402x/extensions\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * EVM Exact Scheme Authorization structure\n * Standard x402 v2 authorization format for EIP-3009\n */\ninterface ExactEvmAuthorization {\n from: Address;\n to: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: Hex;\n}\n\n/**\n * EVM Exact Scheme Payload structure\n * Standard x402 v2 payload format\n */\ninterface ExactEvmPayload {\n signature: Hex;\n authorization: ExactEvmAuthorization;\n}\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 // Convert network to CAIP-2 format for v2 protocol\n const canonicalNetwork = toCanonicalNetworkKey(signed.settlement.network);\n\n // Calculate total amount (business amount + facilitator fee)\n // This MUST match what was used in commitment calculation\n const totalAmount = (\n BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)\n ).toString();\n\n // Construct standard x402 v2 PaymentPayload\n // Using standard EVM exact scheme payload structure\n const exactEvmPayload: ExactEvmPayload = {\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 const paymentPayload: PaymentPayload = {\n x402Version: 2, // Use v2 protocol\n resource: {\n url: \"https://x402x.dev/serverless\",\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n },\n accepted: {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats\n asset: signed.settlement.asset as Address,\n amount: totalAmount, // Use totalAmount to match commitment calculation\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300,\n extra: {},\n },\n // Standard EVM exact scheme payload\n payload: exactEvmPayload as any, // Type cast required: ExactEvmPayload structure matches v2 protocol\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n // IMPORTANT: Use totalAmount (amount + fee) to match commitment calculation\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts CAIP-2 format\n amount: totalAmount, // Total amount including facilitator fee\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\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 // Call core's settle method with standard x402 v2 payload structure\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 * x402xClient - 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/extensions\";\nimport type { x402xClientConfig, 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 x402xClientConfig {\n facilitatorUrl: string;\n timeout: number;\n confirmationTimeout: number;\n}\n\n/**\n * x402xClient - 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 { x402xClient } from '@x402x/client';\n * import { TransferHook } from '@x402x/extensions';\n * import { useWalletClient } from 'wagmi';\n *\n * const { data: wallet } = useWalletClient();\n *\n * // Use default facilitator\n * const client = new x402xClient({\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 x402xClient {\n private config: InternalConfig;\n\n /**\n * Create a new x402xClient 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: x402xClientConfig) {\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 x402xClient instance\n *\n * This hook automatically creates an x402xClient instance using wagmi's\n * wallet client and chain information.\n */\n\nimport { useMemo } from \"react\";\nimport { useWalletClient, useAccount, useChainId, WagmiProviderNotFoundError } from \"wagmi\";\nimport { publicActions } from \"viem\";\nimport { x402xClient } from \"../client.js\";\nimport type { x402xClientConfig } from \"../types.js\";\n\n/**\n * Partial configuration for useX402Client hook\n * (wallet, network, chainId are auto-detected from wagmi)\n */\nexport type UseX402xClientConfig = Partial<Omit<x402xClientConfig, \"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 97: \"bsc-testnet\",\n 56: \"bsc\",\n};\n\n/**\n * React hook for x402xClient\n *\n * Automatically creates an x402xClient 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 x402xClient instance or null if wallet not connected\n *\n * @example\n * ```typescript\n * import { useX402xClient } from '@x402x/client';\n *\n * function MyComponent() {\n * // Use default facilitator\n * const client = useX402xClient();\n *\n * // Or specify custom facilitator\n * const client = useX402xClient({\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 useX402xClient(config?: UseX402xClientConfig): x402xClient | 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 &&\n error.message.includes(\"useConfig\") &&\n 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 x402xClient({\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 x402xClient:\", 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 { useX402xClient, type UseX402xClientConfig } from \"./useX402xClient.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?: UseX402xClientConfig): UseExecuteReturn {\n const client = useX402xClient(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 useX402xClient>,\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
@@ -17,7 +17,7 @@ type ExecuteStatus = "idle" | "preparing" | "signing" | "submitting" | "confirmi
17
17
  /**
18
18
  * X402Client configuration
19
19
  */
20
- interface X402ClientConfig {
20
+ interface x402xClientConfig {
21
21
  /** Wallet client from wagmi/viem */
22
22
  wallet: WalletClient;
23
23
  /** Network name (e.g., 'base-sepolia', 'x-layer-testnet') */
@@ -249,7 +249,7 @@ declare const DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
249
249
  declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
250
250
 
251
251
  /**
252
- * X402Client - High-level client for x402x Serverless Mode
252
+ * x402xClient - High-level client for x402x Serverless Mode
253
253
  *
254
254
  * This client simplifies the entire settlement flow into a single execute() call,
255
255
  * automatically handling:
@@ -261,14 +261,14 @@ declare function prepareSettlement(params: PrepareParams): Promise<SettlementDat
261
261
  *
262
262
  * @example
263
263
  * ```typescript
264
- * import { X402Client } from '@x402x/client';
265
- * import { TransferHook } from '@x402x/core';
264
+ * import { x402xClient } from '@x402x/client';
265
+ * import { TransferHook } from '@x402x/extensions';
266
266
  * import { useWalletClient } from 'wagmi';
267
267
  *
268
268
  * const { data: wallet } = useWalletClient();
269
269
  *
270
270
  * // Use default facilitator
271
- * const client = new X402Client({
271
+ * const client = new x402xClient({
272
272
  * wallet,
273
273
  * network: 'base-sepolia'
274
274
  * });
@@ -287,16 +287,16 @@ declare function prepareSettlement(params: PrepareParams): Promise<SettlementDat
287
287
  * });
288
288
  * ```
289
289
  */
290
- declare class X402Client {
290
+ declare class x402xClient {
291
291
  private config;
292
292
  /**
293
- * Create a new X402Client instance
293
+ * Create a new x402xClient instance
294
294
  *
295
295
  * @param config - Client configuration
296
296
  * @throws NetworkError if network is unsupported
297
297
  * @throws ValidationError if configuration is invalid
298
298
  */
299
- constructor(config: X402ClientConfig);
299
+ constructor(config: x402xClientConfig);
300
300
  /**
301
301
  * Execute a settlement transaction
302
302
  *
@@ -4948,9 +4948,9 @@ declare function calculateTimeWindow(maxTimeoutSeconds?: number): {
4948
4948
  };
4949
4949
 
4950
4950
  /**
4951
- * React hook for creating X402Client instance
4951
+ * React hook for creating x402xClient instance
4952
4952
  *
4953
- * This hook automatically creates an X402Client instance using wagmi's
4953
+ * This hook automatically creates an x402xClient instance using wagmi's
4954
4954
  * wallet client and chain information.
4955
4955
  */
4956
4956
 
@@ -4958,31 +4958,31 @@ declare function calculateTimeWindow(maxTimeoutSeconds?: number): {
4958
4958
  * Partial configuration for useX402Client hook
4959
4959
  * (wallet, network, chainId are auto-detected from wagmi)
4960
4960
  */
4961
- type UseX402ClientConfig = Partial<Omit<X402ClientConfig, "wallet" | "network">> & {
4961
+ type UseX402xClientConfig = Partial<Omit<x402xClientConfig, "wallet" | "network">> & {
4962
4962
  /** Optional: Facilitator URL (default: https://facilitator.x402x.dev/) */
4963
4963
  facilitatorUrl?: string;
4964
4964
  /** Optional: Override network name (auto-detected from chain if not provided) */
4965
4965
  network?: string;
4966
4966
  };
4967
4967
  /**
4968
- * React hook for X402Client
4968
+ * React hook for x402xClient
4969
4969
  *
4970
- * Automatically creates an X402Client instance using the connected wallet
4970
+ * Automatically creates an x402xClient instance using the connected wallet
4971
4971
  * from wagmi. Returns null if wallet is not connected.
4972
4972
  *
4973
4973
  * @param config - Client configuration (facilitatorUrl is optional, defaults to https://facilitator.x402x.dev/)
4974
- * @returns X402Client instance or null if wallet not connected
4974
+ * @returns x402xClient instance or null if wallet not connected
4975
4975
  *
4976
4976
  * @example
4977
4977
  * ```typescript
4978
- * import { useX402Client } from '@x402x/client';
4978
+ * import { useX402xClient } from '@x402x/client';
4979
4979
  *
4980
4980
  * function MyComponent() {
4981
4981
  * // Use default facilitator
4982
- * const client = useX402Client();
4982
+ * const client = useX402xClient();
4983
4983
  *
4984
4984
  * // Or specify custom facilitator
4985
- * const client = useX402Client({
4985
+ * const client = useX402xClient({
4986
4986
  * facilitatorUrl: 'https://custom-facilitator.example.com'
4987
4987
  * });
4988
4988
  *
@@ -5003,7 +5003,7 @@ type UseX402ClientConfig = Partial<Omit<X402ClientConfig, "wallet" | "network">>
5003
5003
  * }
5004
5004
  * ```
5005
5005
  */
5006
- declare function useX402Client(config?: UseX402ClientConfig): X402Client | null;
5006
+ declare function useX402xClient(config?: UseX402xClientConfig): x402xClient | null;
5007
5007
 
5008
5008
  /**
5009
5009
  * React hook for executing settlements
@@ -5077,7 +5077,7 @@ interface UseExecuteReturn {
5077
5077
  * }
5078
5078
  * ```
5079
5079
  */
5080
- declare function useExecute(config?: UseX402ClientConfig): UseExecuteReturn;
5080
+ declare function useExecute(config?: UseX402xClientConfig): UseExecuteReturn;
5081
5081
 
5082
5082
  /**
5083
5083
  * Error classes for x402x client SDK
@@ -5123,4 +5123,4 @@ declare class ValidationError extends X402ClientError {
5123
5123
  constructor(message: string, code?: string);
5124
5124
  }
5125
5125
 
5126
- export { DEFAULT_FACILITATOR_URL, type ExecuteParams, type ExecuteResult, type ExecuteStatus, FacilitatorError, NetworkError, type PrepareParams, type SettleResult, type SettlementData, type SignedAuthorization, SigningError, TransactionError, ValidationError, X402Client, type X402ClientConfig, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402Client };
5126
+ export { DEFAULT_FACILITATOR_URL, type ExecuteParams, type ExecuteResult, type ExecuteStatus, FacilitatorError, NetworkError, type PrepareParams, type SettleResult, type SettlementData, type SignedAuthorization, SigningError, TransactionError, ValidationError, x402xClient as X402Client, type x402xClientConfig as X402ClientConfig, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402xClient as useX402Client, useX402xClient, x402xClient };
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ type ExecuteStatus = "idle" | "preparing" | "signing" | "submitting" | "confirmi
17
17
  /**
18
18
  * X402Client configuration
19
19
  */
20
- interface X402ClientConfig {
20
+ interface x402xClientConfig {
21
21
  /** Wallet client from wagmi/viem */
22
22
  wallet: WalletClient;
23
23
  /** Network name (e.g., 'base-sepolia', 'x-layer-testnet') */
@@ -249,7 +249,7 @@ declare const DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
249
249
  declare function prepareSettlement(params: PrepareParams): Promise<SettlementData>;
250
250
 
251
251
  /**
252
- * X402Client - High-level client for x402x Serverless Mode
252
+ * x402xClient - High-level client for x402x Serverless Mode
253
253
  *
254
254
  * This client simplifies the entire settlement flow into a single execute() call,
255
255
  * automatically handling:
@@ -261,14 +261,14 @@ declare function prepareSettlement(params: PrepareParams): Promise<SettlementDat
261
261
  *
262
262
  * @example
263
263
  * ```typescript
264
- * import { X402Client } from '@x402x/client';
265
- * import { TransferHook } from '@x402x/core';
264
+ * import { x402xClient } from '@x402x/client';
265
+ * import { TransferHook } from '@x402x/extensions';
266
266
  * import { useWalletClient } from 'wagmi';
267
267
  *
268
268
  * const { data: wallet } = useWalletClient();
269
269
  *
270
270
  * // Use default facilitator
271
- * const client = new X402Client({
271
+ * const client = new x402xClient({
272
272
  * wallet,
273
273
  * network: 'base-sepolia'
274
274
  * });
@@ -287,16 +287,16 @@ declare function prepareSettlement(params: PrepareParams): Promise<SettlementDat
287
287
  * });
288
288
  * ```
289
289
  */
290
- declare class X402Client {
290
+ declare class x402xClient {
291
291
  private config;
292
292
  /**
293
- * Create a new X402Client instance
293
+ * Create a new x402xClient instance
294
294
  *
295
295
  * @param config - Client configuration
296
296
  * @throws NetworkError if network is unsupported
297
297
  * @throws ValidationError if configuration is invalid
298
298
  */
299
- constructor(config: X402ClientConfig);
299
+ constructor(config: x402xClientConfig);
300
300
  /**
301
301
  * Execute a settlement transaction
302
302
  *
@@ -4948,9 +4948,9 @@ declare function calculateTimeWindow(maxTimeoutSeconds?: number): {
4948
4948
  };
4949
4949
 
4950
4950
  /**
4951
- * React hook for creating X402Client instance
4951
+ * React hook for creating x402xClient instance
4952
4952
  *
4953
- * This hook automatically creates an X402Client instance using wagmi's
4953
+ * This hook automatically creates an x402xClient instance using wagmi's
4954
4954
  * wallet client and chain information.
4955
4955
  */
4956
4956
 
@@ -4958,31 +4958,31 @@ declare function calculateTimeWindow(maxTimeoutSeconds?: number): {
4958
4958
  * Partial configuration for useX402Client hook
4959
4959
  * (wallet, network, chainId are auto-detected from wagmi)
4960
4960
  */
4961
- type UseX402ClientConfig = Partial<Omit<X402ClientConfig, "wallet" | "network">> & {
4961
+ type UseX402xClientConfig = Partial<Omit<x402xClientConfig, "wallet" | "network">> & {
4962
4962
  /** Optional: Facilitator URL (default: https://facilitator.x402x.dev/) */
4963
4963
  facilitatorUrl?: string;
4964
4964
  /** Optional: Override network name (auto-detected from chain if not provided) */
4965
4965
  network?: string;
4966
4966
  };
4967
4967
  /**
4968
- * React hook for X402Client
4968
+ * React hook for x402xClient
4969
4969
  *
4970
- * Automatically creates an X402Client instance using the connected wallet
4970
+ * Automatically creates an x402xClient instance using the connected wallet
4971
4971
  * from wagmi. Returns null if wallet is not connected.
4972
4972
  *
4973
4973
  * @param config - Client configuration (facilitatorUrl is optional, defaults to https://facilitator.x402x.dev/)
4974
- * @returns X402Client instance or null if wallet not connected
4974
+ * @returns x402xClient instance or null if wallet not connected
4975
4975
  *
4976
4976
  * @example
4977
4977
  * ```typescript
4978
- * import { useX402Client } from '@x402x/client';
4978
+ * import { useX402xClient } from '@x402x/client';
4979
4979
  *
4980
4980
  * function MyComponent() {
4981
4981
  * // Use default facilitator
4982
- * const client = useX402Client();
4982
+ * const client = useX402xClient();
4983
4983
  *
4984
4984
  * // Or specify custom facilitator
4985
- * const client = useX402Client({
4985
+ * const client = useX402xClient({
4986
4986
  * facilitatorUrl: 'https://custom-facilitator.example.com'
4987
4987
  * });
4988
4988
  *
@@ -5003,7 +5003,7 @@ type UseX402ClientConfig = Partial<Omit<X402ClientConfig, "wallet" | "network">>
5003
5003
  * }
5004
5004
  * ```
5005
5005
  */
5006
- declare function useX402Client(config?: UseX402ClientConfig): X402Client | null;
5006
+ declare function useX402xClient(config?: UseX402xClientConfig): x402xClient | null;
5007
5007
 
5008
5008
  /**
5009
5009
  * React hook for executing settlements
@@ -5077,7 +5077,7 @@ interface UseExecuteReturn {
5077
5077
  * }
5078
5078
  * ```
5079
5079
  */
5080
- declare function useExecute(config?: UseX402ClientConfig): UseExecuteReturn;
5080
+ declare function useExecute(config?: UseX402xClientConfig): UseExecuteReturn;
5081
5081
 
5082
5082
  /**
5083
5083
  * Error classes for x402x client SDK
@@ -5123,4 +5123,4 @@ declare class ValidationError extends X402ClientError {
5123
5123
  constructor(message: string, code?: string);
5124
5124
  }
5125
5125
 
5126
- export { DEFAULT_FACILITATOR_URL, type ExecuteParams, type ExecuteResult, type ExecuteStatus, FacilitatorError, NetworkError, type PrepareParams, type SettleResult, type SettlementData, type SignedAuthorization, SigningError, TransactionError, ValidationError, X402Client, type X402ClientConfig, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402Client };
5126
+ export { DEFAULT_FACILITATOR_URL, type ExecuteParams, type ExecuteResult, type ExecuteStatus, FacilitatorError, NetworkError, type PrepareParams, type SettleResult, type SettlementData, type SignedAuthorization, SigningError, TransactionError, ValidationError, x402xClient as X402Client, type x402xClientConfig as X402ClientConfig, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402xClient as useX402Client, useX402xClient, x402xClient };
package/dist/index.js CHANGED
@@ -391,9 +391,9 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
391
391
  }
392
392
 
393
393
  // src/client.ts
394
- var X402Client = class {
394
+ var x402xClient = class {
395
395
  /**
396
- * Create a new X402Client instance
396
+ * Create a new x402xClient instance
397
397
  *
398
398
  * @param config - Client configuration
399
399
  * @throws NetworkError if network is unsupported
@@ -606,7 +606,7 @@ var CHAIN_ID_TO_NETWORK = {
606
606
  97: "bsc-testnet",
607
607
  56: "bsc"
608
608
  };
609
- function useX402Client(config) {
609
+ function useX402xClient(config) {
610
610
  let walletClient;
611
611
  let isConnected;
612
612
  let chainId;
@@ -637,7 +637,7 @@ function useX402Client(config) {
637
637
  }
638
638
  try {
639
639
  const extendedWallet = walletClient.extend(publicActions);
640
- return new X402Client({
640
+ return new x402xClient({
641
641
  wallet: extendedWallet,
642
642
  network,
643
643
  facilitatorUrl: config?.facilitatorUrl,
@@ -646,7 +646,7 @@ function useX402Client(config) {
646
646
  confirmationTimeout: config?.confirmationTimeout
647
647
  });
648
648
  } catch (error) {
649
- console.error("[x402x] Failed to create X402Client:", error);
649
+ console.error("[x402x] Failed to create x402xClient:", error);
650
650
  return null;
651
651
  }
652
652
  }, [
@@ -661,7 +661,7 @@ function useX402Client(config) {
661
661
  ]);
662
662
  }
663
663
  function useExecute(config) {
664
- const client = useX402Client(config);
664
+ const client = useX402xClient(config);
665
665
  const [status, setStatus] = useState("idle");
666
666
  const [error, setError] = useState(null);
667
667
  const [result, setResult] = useState(null);
@@ -704,6 +704,6 @@ function useExecute(config) {
704
704
  };
705
705
  }
706
706
 
707
- export { DEFAULT_FACILITATOR_URL, FacilitatorError, NetworkError, SigningError, TransactionError, ValidationError, X402Client, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402Client };
707
+ export { DEFAULT_FACILITATOR_URL, FacilitatorError, NetworkError, SigningError, TransactionError, ValidationError, x402xClient as X402Client, X402ClientError, calculateTimeWindow, formatFacilitatorUrl, generateSalt, normalizeAddress, prepareSettlement, settle, signAuthorization, useExecute, useX402xClient as useX402Client, useX402xClient, x402xClient };
708
708
  //# sourceMappingURL=index.js.map
709
709
  //# sourceMappingURL=index.js.map
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,IA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A,CAAU,WAAW,CAAA;AACrB,MAAA,QAAA,CAAS,IAAI,CAAA;AACb,MAAA,SAAA,CAAU,IAAI,CAAA;AAEd,MAAA,IAAI;AACF,QAAA,MAAM,aAAA,GAAgB,MAAM,MAAA,CAAO,OAAA,CAAQ,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 cryptoObj = (globalThis as any).crypto as Crypto | undefined;\n\n if (!cryptoObj || !cryptoObj.getRandomValues) {\n throw new Error(\"crypto.getRandomValues is not available\");\n }\n\n const randomBytes = cryptoObj.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/extensions\";\nimport { calculateCommitment } from \"@x402x/extensions\";\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: ${\n error instanceof Error ? error.message : \"Unknown\"\n }`,\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 // Use original network name for API compatibility; conversion to canonical format happens during settlement\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, toCanonicalNetworkKey } from \"@x402x/extensions\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * EVM Exact Scheme Authorization structure\n * Standard x402 v2 authorization format for EIP-3009\n */\ninterface ExactEvmAuthorization {\n from: Address;\n to: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: Hex;\n}\n\n/**\n * EVM Exact Scheme Payload structure\n * Standard x402 v2 payload format\n */\ninterface ExactEvmPayload {\n signature: Hex;\n authorization: ExactEvmAuthorization;\n}\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 // Convert network to CAIP-2 format for v2 protocol\n const canonicalNetwork = toCanonicalNetworkKey(signed.settlement.network);\n\n // Calculate total amount (business amount + facilitator fee)\n // This MUST match what was used in commitment calculation\n const totalAmount = (\n BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)\n ).toString();\n\n // Construct standard x402 v2 PaymentPayload\n // Using standard EVM exact scheme payload structure\n const exactEvmPayload: ExactEvmPayload = {\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 const paymentPayload: PaymentPayload = {\n x402Version: 2, // Use v2 protocol\n resource: {\n url: \"https://x402x.dev/serverless\",\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n },\n accepted: {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats\n asset: signed.settlement.asset as Address,\n amount: totalAmount, // Use totalAmount to match commitment calculation\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300,\n extra: {},\n },\n // Standard EVM exact scheme payload\n payload: exactEvmPayload as any, // Type cast required: ExactEvmPayload structure matches v2 protocol\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n // IMPORTANT: Use totalAmount (amount + fee) to match commitment calculation\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts CAIP-2 format\n amount: totalAmount, // Total amount including facilitator fee\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\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 // Call core's settle method with standard x402 v2 payload structure\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/extensions\";\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 { useWalletClient, useAccount, useChainId, WagmiProviderNotFoundError } 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 97: \"bsc-testnet\",\n 56: \"bsc\",\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 &&\n error.message.includes(\"useConfig\") &&\n 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"]}
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/useX402xClient.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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AAA,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 cryptoObj = (globalThis as any).crypto as Crypto | undefined;\n\n if (!cryptoObj || !cryptoObj.getRandomValues) {\n throw new Error(\"crypto.getRandomValues is not available\");\n }\n\n const randomBytes = cryptoObj.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/extensions\";\nimport { calculateCommitment } from \"@x402x/extensions\";\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: ${\n error instanceof Error ? error.message : \"Unknown\"\n }`,\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 // Use original network name for API compatibility; conversion to canonical format happens during settlement\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, toCanonicalNetworkKey } from \"@x402x/extensions\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * EVM Exact Scheme Authorization structure\n * Standard x402 v2 authorization format for EIP-3009\n */\ninterface ExactEvmAuthorization {\n from: Address;\n to: Address;\n value: string;\n validAfter: string;\n validBefore: string;\n nonce: Hex;\n}\n\n/**\n * EVM Exact Scheme Payload structure\n * Standard x402 v2 payload format\n */\ninterface ExactEvmPayload {\n signature: Hex;\n authorization: ExactEvmAuthorization;\n}\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 // Convert network to CAIP-2 format for v2 protocol\n const canonicalNetwork = toCanonicalNetworkKey(signed.settlement.network);\n\n // Calculate total amount (business amount + facilitator fee)\n // This MUST match what was used in commitment calculation\n const totalAmount = (\n BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)\n ).toString();\n\n // Construct standard x402 v2 PaymentPayload\n // Using standard EVM exact scheme payload structure\n const exactEvmPayload: ExactEvmPayload = {\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 const paymentPayload: PaymentPayload = {\n x402Version: 2, // Use v2 protocol\n resource: {\n url: \"https://x402x.dev/serverless\",\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n },\n accepted: {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats\n asset: signed.settlement.asset as Address,\n amount: totalAmount, // Use totalAmount to match commitment calculation\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300,\n extra: {},\n },\n // Standard EVM exact scheme payload\n payload: exactEvmPayload as any, // Type cast required: ExactEvmPayload structure matches v2 protocol\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n // IMPORTANT: Use totalAmount (amount + fee) to match commitment calculation\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: canonicalNetwork as any, // Type cast required: core_v2 Network type accepts CAIP-2 format\n amount: totalAmount, // Total amount including facilitator fee\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\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 // Call core's settle method with standard x402 v2 payload structure\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 * x402xClient - 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/extensions\";\nimport type { x402xClientConfig, 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 x402xClientConfig {\n facilitatorUrl: string;\n timeout: number;\n confirmationTimeout: number;\n}\n\n/**\n * x402xClient - 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 { x402xClient } from '@x402x/client';\n * import { TransferHook } from '@x402x/extensions';\n * import { useWalletClient } from 'wagmi';\n *\n * const { data: wallet } = useWalletClient();\n *\n * // Use default facilitator\n * const client = new x402xClient({\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 x402xClient {\n private config: InternalConfig;\n\n /**\n * Create a new x402xClient 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: x402xClientConfig) {\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 x402xClient instance\n *\n * This hook automatically creates an x402xClient instance using wagmi's\n * wallet client and chain information.\n */\n\nimport { useMemo } from \"react\";\nimport { useWalletClient, useAccount, useChainId, WagmiProviderNotFoundError } from \"wagmi\";\nimport { publicActions } from \"viem\";\nimport { x402xClient } from \"../client.js\";\nimport type { x402xClientConfig } from \"../types.js\";\n\n/**\n * Partial configuration for useX402Client hook\n * (wallet, network, chainId are auto-detected from wagmi)\n */\nexport type UseX402xClientConfig = Partial<Omit<x402xClientConfig, \"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 97: \"bsc-testnet\",\n 56: \"bsc\",\n};\n\n/**\n * React hook for x402xClient\n *\n * Automatically creates an x402xClient 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 x402xClient instance or null if wallet not connected\n *\n * @example\n * ```typescript\n * import { useX402xClient } from '@x402x/client';\n *\n * function MyComponent() {\n * // Use default facilitator\n * const client = useX402xClient();\n *\n * // Or specify custom facilitator\n * const client = useX402xClient({\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 useX402xClient(config?: UseX402xClientConfig): x402xClient | 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 &&\n error.message.includes(\"useConfig\") &&\n 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 x402xClient({\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 x402xClient:\", 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 { useX402xClient, type UseX402xClientConfig } from \"./useX402xClient.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?: UseX402xClientConfig): UseExecuteReturn {\n const client = useX402xClient(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 useX402xClient>,\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": "2.1.0",
3
+ "version": "2.2.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",