@x402x/client 0.3.0 → 2.1.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
@@ -44,7 +44,7 @@ Client → Facilitator → Smart Contract (Hook)
44
44
  ### After (@x402x/client)
45
45
 
46
46
  ```typescript
47
- import { parseDefaultAssetAmount } from "@x402x/core";
47
+ import { parseDefaultAssetAmount } from "@x402x/extensions";
48
48
 
49
49
  const atomicAmount = parseDefaultAssetAmount("1", network); // '1000000'
50
50
  const client = new X402Client({ wallet, network, facilitatorUrl });
@@ -64,18 +64,18 @@ const result = await client.execute({
64
64
  ### Installation
65
65
 
66
66
  ```bash
67
- npm install @x402x/client @x402x/core
67
+ npm install @x402x/client @x402x/extensions
68
68
  # or
69
- pnpm add @x402x/client @x402x/core
69
+ pnpm add @x402x/client @x402x/extensions
70
70
  # or
71
- yarn add @x402x/client @x402x/core
71
+ yarn add @x402x/client @x402x/extensions
72
72
  ```
73
73
 
74
74
  ### Basic Usage (React + wagmi)
75
75
 
76
76
  ```typescript
77
77
  import { X402Client } from '@x402x/client';
78
- import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';
78
+ import { TransferHook, parseDefaultAssetAmount } from '@x402x/extensions';
79
79
  import { useWalletClient } from 'wagmi';
80
80
  import { publicActions } from 'viem';
81
81
 
@@ -119,10 +119,10 @@ The `amount` parameter in `client.execute()` and `prepareSettlement()` **must be
119
119
 
120
120
  ### Converting USD Amounts to Atomic Units
121
121
 
122
- Use `parseDefaultAssetAmount()` from `@x402x/core` to convert USD amounts:
122
+ Use `parseDefaultAssetAmount()` from `@x402x/extensions` to convert USD amounts:
123
123
 
124
124
  ```typescript
125
- import { parseDefaultAssetAmount, formatDefaultAssetAmount } from "@x402x/core";
125
+ import { parseDefaultAssetAmount, formatDefaultAssetAmount } from "@x402x/extensions";
126
126
 
127
127
  // Convert USD to atomic units
128
128
  const atomicAmount = parseDefaultAssetAmount("1", "base-sepolia"); // '1000000' (1 USDC)
@@ -143,7 +143,7 @@ const displayAmount = formatDefaultAssetAmount("1000000", "base-sepolia"); // '1
143
143
 
144
144
  ```typescript
145
145
  import { X402Client } from "@x402x/client";
146
- import { parseDefaultAssetAmount } from "@x402x/core";
146
+ import { parseDefaultAssetAmount } from "@x402x/extensions";
147
147
 
148
148
  const client = new X402Client({ wallet, network: "base-sepolia" });
149
149
 
@@ -195,7 +195,7 @@ const client = new X402Client({
195
195
  });
196
196
 
197
197
  // Convert USD amount to atomic units
198
- import { parseDefaultAssetAmount } from "@x402x/core";
198
+ import { parseDefaultAssetAmount } from "@x402x/extensions";
199
199
  const atomicAmount = parseDefaultAssetAmount("1", "base-sepolia"); // '1000000'
200
200
 
201
201
  const result = await client.execute({
@@ -240,7 +240,7 @@ Provides automatic state management for settlements.
240
240
 
241
241
  ```typescript
242
242
  import { useExecute } from '@x402x/client';
243
- import { parseDefaultAssetAmount } from '@x402x/core';
243
+ import { parseDefaultAssetAmount } from '@x402x/extensions';
244
244
 
245
245
  function PayButton() {
246
246
  // Uses default facilitator at https://facilitator.x402x.dev/
@@ -285,7 +285,7 @@ Understanding the x402 protocol terminology used in this SDK:
285
285
  **Verify** (from x402 protocol) - Validate a payment payload without executing it on-chain. This is useful for pre-validation before actual settlement.
286
286
 
287
287
  - In x402 protocol: `POST /verify` endpoint
288
- - In @x402x/core: `verify()` function
288
+ - In @x402x/extensions: `verify()` function
289
289
  - Use case: Check if payment is valid before committing resources
290
290
 
291
291
  ### settle
@@ -293,7 +293,7 @@ Understanding the x402 protocol terminology used in this SDK:
293
293
  **Settle** (from x402 protocol) - Execute a payment on-chain by submitting it to the blockchain. This is the actual payment execution step.
294
294
 
295
295
  - In x402 protocol: `POST /settle` endpoint
296
- - In @x402x/core: `settle()` function
296
+ - In @x402x/extensions: `settle()` function
297
297
  - In @x402x/client: `settle()` function (convenience wrapper)
298
298
  - Use case: Submit signed payment for blockchain execution
299
299
 
@@ -333,7 +333,7 @@ Prepares settlement data for signing.
333
333
 
334
334
  ```typescript
335
335
  import { prepareSettlement } from "@x402x/client";
336
- import { parseDefaultAssetAmount } from "@x402x/core";
336
+ import { parseDefaultAssetAmount } from "@x402x/extensions";
337
337
 
338
338
  // Convert USD amount to atomic units
339
339
  const atomicAmount = parseDefaultAssetAmount("1", "base-sepolia"); // '1000000'
@@ -377,7 +377,7 @@ const result = await settle("https://facilitator.x402x.dev", signed);
377
377
 
378
378
  ```typescript
379
379
  import { X402Client } from "@x402x/client";
380
- import { TransferHook, parseDefaultAssetAmount } from "@x402x/core";
380
+ import { TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
381
381
 
382
382
  // Uses default facilitator at https://facilitator.x402x.dev/
383
383
  const client = new X402Client({
@@ -404,7 +404,7 @@ TransferHook supports distributing funds to multiple recipients by percentage:
404
404
 
405
405
  ```typescript
406
406
  import { X402Client } from "@x402x/client";
407
- import { TransferHook, parseDefaultAssetAmount, type Split } from "@x402x/core";
407
+ import { TransferHook, parseDefaultAssetAmount, type Split } from "@x402x/extensions";
408
408
 
409
409
  const client = new X402Client({
410
410
  wallet: walletClient,
@@ -449,7 +449,7 @@ console.log("Distributed transfer:", result.txHash);
449
449
 
450
450
  ```typescript
451
451
  import { useExecute } from '@x402x/client';
452
- import { NFTMintHook, parseDefaultAssetAmount } from '@x402x/core';
452
+ import { NFTMintHook, parseDefaultAssetAmount } from '@x402x/extensions';
453
453
 
454
454
  function MintNFT() {
455
455
  // Uses default facilitator
@@ -484,7 +484,7 @@ function MintNFT() {
484
484
 
485
485
  ```typescript
486
486
  import { prepareSettlement, signAuthorization, settle } from "@x402x/client";
487
- import { calculateFacilitatorFee, TransferHook, parseDefaultAssetAmount } from "@x402x/core";
487
+ import { calculateFacilitatorFee, TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
488
488
 
489
489
  // 1. Query minimum fee
490
490
  const hookData = TransferHook.encode([
@@ -527,7 +527,7 @@ console.log("Transaction:", result.transaction);
527
527
  ```typescript
528
528
  import { ref } from "vue";
529
529
  import { X402Client } from "@x402x/client";
530
- import { TransferHook, parseDefaultAssetAmount } from "@x402x/core";
530
+ import { TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
531
531
 
532
532
  export function usePayment() {
533
533
  const status = ref("idle");
@@ -660,7 +660,7 @@ function Component() {
660
660
  ```typescript
661
661
  // 10 lines with @x402x/client (no facilitatorUrl needed!)
662
662
  import { useExecute } from "@x402x/client";
663
- import { TransferHook, parseDefaultAssetAmount } from "@x402x/core";
663
+ import { TransferHook, parseDefaultAssetAmount } from "@x402x/extensions";
664
664
 
665
665
  function Component() {
666
666
  // Uses default facilitator automatically
@@ -683,7 +683,7 @@ function Component() {
683
683
 
684
684
  ## Related Packages
685
685
 
686
- - [@x402x/core](../core) - Core utilities and commitment calculation
686
+ - [@x402x/extensions](../extensions) - Core utilities and network configuration
687
687
  - [@x402x/facilitator](../../facilitator) - Facilitator server implementation
688
688
  - [x402](https://github.com/coinbase/x402) - Base x402 protocol
689
689
 
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var core = require('@x402x/core');
3
+ var extensions = require('@x402x/extensions');
4
4
  var viem = require('viem');
5
5
  var actions = require('viem/actions');
6
6
  var react = require('react');
@@ -56,7 +56,11 @@ var ValidationError = class _ValidationError extends X402ClientError {
56
56
  }
57
57
  };
58
58
  function generateSalt() {
59
- const randomBytes = crypto.getRandomValues(new Uint8Array(32));
59
+ const cryptoObj = globalThis.crypto;
60
+ if (!cryptoObj || !cryptoObj.getRandomValues) {
61
+ throw new Error("crypto.getRandomValues is not available");
62
+ }
63
+ const randomBytes = cryptoObj.getRandomValues(new Uint8Array(32));
60
64
  return `0x${Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
61
65
  }
62
66
  function normalizeAddress(address, name = "address") {
@@ -144,7 +148,7 @@ function calculateTimeWindow(maxTimeoutSeconds = 300) {
144
148
  var DEFAULT_FACILITATOR_URL = "https://facilitator.x402x.dev";
145
149
  async function queryFacilitatorFee(facilitatorUrl, network, hook, hookData = "0x") {
146
150
  try {
147
- return await core.calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);
151
+ return await extensions.calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);
148
152
  } catch (error) {
149
153
  if (error instanceof Error) {
150
154
  throw new FacilitatorError(
@@ -168,7 +172,7 @@ async function prepareSettlement(params) {
168
172
  if (!from) {
169
173
  throw new ValidationError("Wallet client must have an account");
170
174
  }
171
- const networkConfig = params.networkConfig || core.getNetworkConfig(params.network);
175
+ const networkConfig = params.networkConfig || extensions.getNetworkConfig(params.network);
172
176
  if (!networkConfig) {
173
177
  throw new NetworkError(
174
178
  `Network '${params.network}' is not supported. Please provide custom networkConfig.`
@@ -203,7 +207,7 @@ async function prepareSettlement(params) {
203
207
  }
204
208
  const timeWindow = params.validAfter && params.validBefore ? { validAfter: params.validAfter, validBefore: params.validBefore } : calculateTimeWindow(300);
205
209
  const totalAmount = (BigInt(atomicAmount) + BigInt(facilitatorFee)).toString();
206
- const commitment = core.calculateCommitment({
210
+ const commitment = extensions.calculateCommitment({
207
211
  chainId: networkConfig.chainId,
208
212
  hub: networkConfig.settlementRouter,
209
213
  asset,
@@ -311,39 +315,52 @@ async function signAuthorization(wallet, settlement) {
311
315
  }
312
316
  async function settle(facilitatorUrl, signed, timeout = 3e4) {
313
317
  try {
314
- const paymentPayload = {
315
- x402Version: 1,
316
- scheme: "exact",
317
- network: signed.settlement.network,
318
- // Network type compatibility
319
- payload: {
320
- signature: signed.signature,
321
- authorization: {
322
- from: signed.authorization.from,
323
- to: signed.authorization.to,
324
- value: signed.authorization.value,
325
- validAfter: signed.authorization.validAfter,
326
- validBefore: signed.authorization.validBefore,
327
- nonce: signed.authorization.nonce
328
- }
318
+ const canonicalNetwork = extensions.toCanonicalNetworkKey(signed.settlement.network);
319
+ const totalAmount = (BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)).toString();
320
+ const exactEvmPayload = {
321
+ signature: signed.signature,
322
+ authorization: {
323
+ from: signed.authorization.from,
324
+ to: signed.authorization.to,
325
+ value: signed.authorization.value,
326
+ validAfter: signed.authorization.validAfter,
327
+ validBefore: signed.authorization.validBefore,
328
+ nonce: signed.authorization.nonce
329
329
  }
330
330
  };
331
+ const paymentPayload = {
332
+ x402Version: 2,
333
+ // Use v2 protocol
334
+ resource: {
335
+ url: "https://x402x.dev/serverless",
336
+ description: "x402x Serverless Settlement",
337
+ mimeType: "application/json"
338
+ },
339
+ accepted: {
340
+ scheme: "exact",
341
+ network: canonicalNetwork,
342
+ // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats
343
+ asset: signed.settlement.asset,
344
+ amount: totalAmount,
345
+ // Use totalAmount to match commitment calculation
346
+ payTo: signed.settlement.networkConfig.settlementRouter,
347
+ maxTimeoutSeconds: 300,
348
+ extra: {}
349
+ },
350
+ // Standard EVM exact scheme payload
351
+ payload: exactEvmPayload
352
+ // Type cast required: ExactEvmPayload structure matches v2 protocol
353
+ };
331
354
  const paymentRequirements = {
332
355
  scheme: "exact",
333
- network: signed.settlement.network,
334
- // Network type compatibility
335
- maxAmountRequired: signed.settlement.amount,
356
+ network: canonicalNetwork,
357
+ // Type cast required: core_v2 Network type accepts CAIP-2 format
358
+ amount: totalAmount,
359
+ // Total amount including facilitator fee
336
360
  asset: signed.settlement.asset,
337
361
  payTo: signed.settlement.networkConfig.settlementRouter,
338
362
  maxTimeoutSeconds: 300,
339
363
  // 5 minutes
340
- // Required by x402 protocol (even though not used in serverless mode)
341
- // In the future, the x402 v2 will remove the resource field from the payment requirements
342
- // (https://github.com/coinbase/x402/pull/446)
343
- resource: "https://x402x.dev/serverless",
344
- // Placeholder for serverless mode
345
- description: "x402x Serverless Settlement",
346
- mimeType: "application/json",
347
364
  extra: {
348
365
  name: signed.settlement.networkConfig.defaultAsset.eip712.name,
349
366
  version: signed.settlement.networkConfig.defaultAsset.eip712.version,
@@ -355,8 +372,7 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
355
372
  hookData: signed.settlement.hookData
356
373
  }
357
374
  };
358
- paymentPayload.paymentRequirements = paymentRequirements;
359
- const result = await core.settle(facilitatorUrl, paymentPayload, paymentRequirements, timeout);
375
+ const result = await extensions.settle(facilitatorUrl, paymentPayload, paymentRequirements, timeout);
360
376
  return {
361
377
  success: result.success,
362
378
  transaction: result.transaction,
@@ -447,7 +463,7 @@ var X402Client = class {
447
463
  * ```
448
464
  */
449
465
  async execute(params, waitForConfirmation = false) {
450
- const hook = params.hook ? normalizeAddress(params.hook, "hook") : core.TransferHook.getAddress(this.config.network);
466
+ const hook = params.hook ? normalizeAddress(params.hook, "hook") : extensions.TransferHook.getAddress(this.config.network);
451
467
  const payTo = normalizeAddress(params.payTo, "payTo");
452
468
  const hookData = params.hookData || "0x";
453
469
  if (params.hookData) {
@@ -508,7 +524,7 @@ var X402Client = class {
508
524
  const normalizedHook = normalizeAddress(hook, "hook");
509
525
  validateHex(hookData, "hookData");
510
526
  try {
511
- return await core.calculateFacilitatorFee(
527
+ return await extensions.calculateFacilitatorFee(
512
528
  this.config.facilitatorUrl,
513
529
  this.config.network,
514
530
  normalizedHook,
@@ -587,7 +603,9 @@ var CHAIN_ID_TO_NETWORK = {
587
603
  84532: "base-sepolia",
588
604
  8453: "base",
589
605
  196: "x-layer",
590
- 1952: "x-layer-testnet"
606
+ 1952: "x-layer-testnet",
607
+ 97: "bsc-testnet",
608
+ 56: "bsc"
591
609
  };
592
610
  function useX402Client(config) {
593
611
  let walletClient;
@@ -689,15 +707,15 @@ function useExecute(config) {
689
707
 
690
708
  Object.defineProperty(exports, "AmountError", {
691
709
  enumerable: true,
692
- get: function () { return core.AmountError; }
710
+ get: function () { return extensions.AmountError; }
693
711
  });
694
712
  Object.defineProperty(exports, "formatDefaultAssetAmount", {
695
713
  enumerable: true,
696
- get: function () { return core.formatDefaultAssetAmount; }
714
+ get: function () { return extensions.formatDefaultAssetAmount; }
697
715
  });
698
716
  Object.defineProperty(exports, "parseDefaultAssetAmount", {
699
717
  enumerable: true,
700
- get: function () { return core.parseDefaultAssetAmount; }
718
+ get: function () { return extensions.parseDefaultAssetAmount; }
701
719
  });
702
720
  exports.DEFAULT_FACILITATOR_URL = DEFAULT_FACILITATOR_URL;
703
721
  exports.FacilitatorError = FacilitatorError;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/core/utils.ts","../src/core/prepare.ts","../src/core/sign.ts","../src/core/settle.ts","../src/client.ts","../src/hooks/useX402Client.ts","../src/hooks/useExecute.ts"],"names":["getAddress","isAddress","calculateFacilitatorFee","getNetworkConfig","calculateCommitment","signTypedData","coreSettle","TransferHook","useWalletClient","useAccount","useChainId","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,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AAA,CAAU,IAAI,CAAA;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,WAAA,EAAa,CAAC,WAAA,EAAa,SAAA,EAAW,cAAc,YAAY,CAAA,CAAE,SAAS,MAAM,CAAA;AAAA,IACjF,WAAW,MAAA,KAAW,SAAA;AAAA,IACtB,SAAS,MAAA,KAAW;AAAA,GACtB;AACF","file":"index.cjs","sourcesContent":["/**\n * Error classes for x402x client SDK\n */\n\n/**\n * Base error class for all x402x client errors\n */\nexport class X402ClientError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message);\n this.name = \"X402ClientError\";\n Object.setPrototypeOf(this, X402ClientError.prototype);\n }\n}\n\n/**\n * Network-related errors (unsupported network, configuration issues)\n */\nexport class NetworkError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"NetworkError\";\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * Wallet signing errors\n */\nexport class SigningError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"SigningError\";\n Object.setPrototypeOf(this, SigningError.prototype);\n }\n}\n\n/**\n * Facilitator communication errors\n */\nexport class FacilitatorError extends X402ClientError {\n constructor(\n message: string,\n code?: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n ) {\n super(message, code);\n this.name = \"FacilitatorError\";\n Object.setPrototypeOf(this, FacilitatorError.prototype);\n }\n}\n\n/**\n * Transaction execution errors\n */\nexport class TransactionError extends X402ClientError {\n constructor(\n message: string,\n code?: string,\n public readonly txHash?: string,\n ) {\n super(message, code);\n this.name = \"TransactionError\";\n Object.setPrototypeOf(this, TransactionError.prototype);\n }\n}\n\n/**\n * Parameter validation errors\n */\nexport class ValidationError extends X402ClientError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"ValidationError\";\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n","/**\n * Utility functions for x402x client\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { ValidationError } from \"../errors.js\";\n\n/**\n * Generate a random 32-byte salt for settlement idempotency\n *\n * @returns Random 32-byte hex string\n *\n * @example\n * ```typescript\n * const salt = generateSalt();\n * console.log(salt); // \"0x1234...\"\n * ```\n */\nexport function generateSalt(): Hex {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32));\n return `0x${Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}` as Hex;\n}\n\n/**\n * Normalize Ethereum address to EIP-55 checksum format\n *\n * Automatically converts any valid Ethereum address (lowercase, uppercase, or mixed)\n * to the proper checksummed format. This provides a better developer experience\n * by accepting addresses in any case format.\n *\n * @param address - Address to normalize (can be any case)\n * @param name - Parameter name for error messages (optional)\n * @returns Checksummed address in EIP-55 format\n * @throws ValidationError if address is invalid\n *\n * @example\n * ```typescript\n * normalizeAddress('0xabc123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xABC123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xAbC123...') // Returns '0xAbC123...' (already checksummed)\n * ```\n */\nexport function normalizeAddress(address: string, name: string = \"address\"): Address {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to EIP-55 checksum format\n // getAddress() will throw if the address is invalid\n try {\n return getAddress(address);\n } catch (error) {\n throw new ValidationError(\n `${name} is not a valid Ethereum address: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Validate Ethereum address format (legacy, prefer normalizeAddress)\n *\n * @deprecated Use normalizeAddress() instead for better developer experience\n * @param address - Address to validate\n * @param name - Parameter name for error messages\n * @throws ValidationError if address is invalid\n */\nexport function validateAddress(address: string, name: string): void {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!isAddress(address)) {\n throw new ValidationError(`${name} must be a valid Ethereum address`);\n }\n}\n\n/**\n * Validate hex string format\n *\n * @param hex - Hex string to validate\n * @param name - Parameter name for error messages\n * @param expectedLength - Optional expected length (in bytes, not characters)\n * @throws ValidationError if hex is invalid\n */\nexport function validateHex(hex: string, name: string, expectedLength?: number): void {\n if (!hex || typeof hex !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!hex.startsWith(\"0x\")) {\n throw new ValidationError(`${name} must start with 0x`);\n }\n if (!/^0x[0-9a-fA-F]*$/.test(hex)) {\n throw new ValidationError(`${name} must be a valid hex string`);\n }\n if (expectedLength !== undefined) {\n const actualLength = (hex.length - 2) / 2;\n if (actualLength !== expectedLength) {\n throw new ValidationError(\n `${name} must be ${expectedLength} bytes, got ${actualLength} bytes`,\n );\n }\n }\n}\n\n/**\n * Validate amount format - must be atomic units (positive integer string)\n *\n * This function validates that the amount is a valid atomic unit string.\n * For converting USD amounts to atomic units, use parseDefaultAssetAmount from @x402x/core.\n *\n * @param amount - Amount in atomic units (must be a positive integer string)\n * @param name - Parameter name for error messages\n * @throws ValidationError if amount is invalid\n *\n * @example\n * ```typescript\n * validateAmount('1000000', 'amount'); // Valid: atomic units\n * validateAmount('0.1', 'amount'); // Invalid: not atomic units\n * validateAmount('-1', 'amount'); // Invalid: negative\n * ```\n */\nexport function validateAmount(amount: string | number, name: string): void {\n if (amount === null || amount === undefined || amount === \"\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to string if number\n const amountStr = typeof amount === \"number\" ? amount.toString() : amount;\n\n // Must be a non-empty string\n if (typeof amountStr !== \"string\" || amountStr.trim() === \"\") {\n throw new ValidationError(`${name} must be a non-empty string`);\n }\n\n // Must be a valid positive integer (atomic units)\n // Allow leading zeros but must be numeric\n if (!/^\\d+$/.test(amountStr)) {\n throw new ValidationError(\n `${name} must be a positive integer string (atomic units). ` +\n `Use parseDefaultAssetAmount() from @x402x/core to convert USD amounts.`,\n );\n }\n\n // Validate it can be converted to BigInt (no overflow)\n try {\n const atomicAmount = BigInt(amountStr);\n if (atomicAmount < 0n) {\n throw new ValidationError(`${name} cannot be negative`);\n }\n if (atomicAmount === 0n) {\n throw new ValidationError(`${name} cannot be zero`);\n }\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(\n `${name} is not a valid amount: ${error instanceof Error ? error.message : \"Invalid format\"}`,\n );\n }\n}\n\n/**\n * Format facilitator URL (ensure it doesn't end with slash)\n *\n * @param url - Facilitator URL\n * @returns Formatted URL\n */\nexport function formatFacilitatorUrl(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/**\n * Calculate default time window for authorization\n *\n * @param maxTimeoutSeconds - Maximum timeout in seconds\n * @returns Object with validAfter and validBefore timestamps\n */\nexport function calculateTimeWindow(maxTimeoutSeconds: number = 300): {\n validAfter: string;\n validBefore: string;\n} {\n const now = Math.floor(Date.now() / 1000);\n return {\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + maxTimeoutSeconds).toString(),\n };\n}\n","/**\n * Prepare settlement data for signing\n *\n * This module handles the preparation of settlement parameters before signing,\n * including generating salt, calculating commitment hash, and fetching facilitator fees.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getNetworkConfig, calculateFacilitatorFee, type FeeCalculationResult } from \"@x402x/core\";\nimport { calculateCommitment } from \"@x402x/core\";\nimport type { PrepareParams, SettlementData } from \"../types.js\";\nimport { NetworkError, ValidationError, FacilitatorError } from \"../errors.js\";\nimport {\n generateSalt,\n validateAddress,\n validateHex,\n validateAmount,\n calculateTimeWindow,\n} from \"./utils.js\";\n\n/**\n * Default facilitator URL\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\n\n/**\n * Query facilitator fee from facilitator service (internal helper)\n *\n * Uses the /calculate-fee endpoint which provides accurate gas cost estimates\n * with safety margins.\n *\n * @internal\n * @param facilitatorUrl - Facilitator URL\n * @param network - Network name\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result\n *\n * @throws FacilitatorError if request fails\n */\nasync function queryFacilitatorFee(\n facilitatorUrl: string,\n network: string,\n hook: Address,\n hookData: Hex = \"0x\",\n): Promise<FeeCalculationResult> {\n try {\n return await calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to query facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\"Failed to query facilitator fee: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n\n/**\n * Prepare settlement data for signing\n *\n * This function:\n * 1. Validates all parameters\n * 2. Loads network configuration\n * 3. Generates salt (if not provided)\n * 4. Queries facilitator fee (if not provided)\n * 5. Calculates time window (if not provided)\n * 6. Calculates commitment hash\n * 7. Returns prepared settlement data\n *\n * @param params - Preparation parameters\n * @returns Prepared settlement data ready for signing\n *\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if parameters are invalid\n *\n * @example\n * ```typescript\n * import { prepareSettlement } from '@x402x/client';\n * import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units first\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const settlement = await prepareSettlement({\n * wallet: walletClient,\n * network: 'base-sepolia',\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData: TransferHook.encode(),\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...',\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n * ```\n */\nexport async function prepareSettlement(params: PrepareParams): Promise<SettlementData> {\n // 1. Validate parameters\n validateAddress(params.hook, \"hook\");\n validateHex(params.hookData, \"hookData\");\n validateAddress(params.payTo, \"payTo\");\n\n // 2. Validate amount (must be atomic units, no automatic conversion)\n validateAmount(params.amount, \"amount\");\n const atomicAmount = params.amount;\n\n if (params.customSalt) {\n validateHex(params.customSalt, \"customSalt\", 32);\n }\n\n // 2. Get wallet account address\n const from = params.wallet.account?.address;\n if (!from) {\n throw new ValidationError(\"Wallet client must have an account\");\n }\n\n // 3. Load network configuration\n const networkConfig = params.networkConfig || getNetworkConfig(params.network);\n if (!networkConfig) {\n throw new NetworkError(\n `Network '${params.network}' is not supported. Please provide custom networkConfig.`,\n );\n }\n\n // 4. Determine asset address (use provided asset or default asset)\n const asset = params.asset || (networkConfig.defaultAsset.address as Address);\n validateAddress(asset, \"asset\");\n\n // 5. Generate salt (if not provided)\n const salt = params.customSalt || generateSalt();\n\n // 6. Query facilitator fee (if not provided)\n // Use the provided facilitatorUrl or fall back to default\n let facilitatorFee = params.facilitatorFee || \"0\";\n if (!params.facilitatorFee) {\n const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;\n try {\n const feeEstimate = await queryFacilitatorFee(\n facilitatorUrl,\n params.network,\n params.hook,\n params.hookData, // Pass hookData for accurate fee calculation\n );\n\n if (!feeEstimate.hookAllowed) {\n throw new ValidationError(\n `Hook ${params.hook} is not allowed on network ${params.network}.`,\n );\n }\n\n facilitatorFee = feeEstimate.facilitatorFee;\n } catch (error) {\n // If fee query fails, log warning and use 0\n console.warn(\n `[x402x] Failed to query facilitator fee, using 0. This may cause settlement to fail. Error: ${error instanceof Error ? error.message : \"Unknown\"}`,\n );\n facilitatorFee = \"0\";\n }\n }\n\n // 7. Calculate time window (if not provided)\n const timeWindow =\n params.validAfter && params.validBefore\n ? { validAfter: params.validAfter, validBefore: params.validBefore }\n : calculateTimeWindow(300); // 5 minutes default\n\n // 8. Calculate commitment hash\n // IMPORTANT: value must be total amount (business amount + facilitator fee)\n // because the contract's calculateCommitment expects the same value that\n // will be authorized in the EIP-3009 signature\n const totalAmount = (BigInt(atomicAmount) + BigInt(facilitatorFee)).toString();\n const commitment = calculateCommitment({\n chainId: networkConfig.chainId,\n hub: networkConfig.settlementRouter as Address,\n asset: asset,\n from,\n value: totalAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n });\n\n // 9. Return prepared settlement data\n return {\n network: params.network,\n networkConfig,\n asset: asset,\n from,\n amount: atomicAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n commitment: commitment as Hex,\n };\n}\n","/**\n * Sign EIP-3009 authorization for settlement\n *\n * This module handles the signing of EIP-712 typed data for EIP-3009\n * transferWithAuthorization, using the commitment hash as the nonce.\n */\n\nimport type { Address, WalletClient } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { signTypedData } from \"viem/actions\";\nimport type { SettlementData, SignedAuthorization } from \"../types.js\";\nimport { SigningError } from \"../errors.js\";\n\n/**\n * EIP-3009 authorization types for EIP-712 signature\n */\nconst AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Sign EIP-3009 authorization\n *\n * This function signs an EIP-712 typed data message for EIP-3009's\n * transferWithAuthorization function. The commitment hash is used\n * as the nonce to cryptographically bind all settlement parameters.\n *\n * @param wallet - Wallet client from wagmi/viem\n * @param settlement - Prepared settlement data\n * @returns Signed authorization ready to submit\n *\n * @throws SigningError if signing fails or wallet doesn't support signing\n *\n * @example\n * ```typescript\n * import { signAuthorization } from '@x402x/client';\n *\n * const signed = await signAuthorization(walletClient, settlement);\n * console.log('Signature:', signed.signature);\n * ```\n */\nexport async function signAuthorization(\n wallet: WalletClient,\n settlement: SettlementData,\n): Promise<SignedAuthorization> {\n try {\n // Ensure wallet has an account\n if (!wallet.account) {\n throw new SigningError(\"Wallet client must have an account\");\n }\n\n // Build EIP-712 domain\n // Use the asset's EIP-712 domain info from network config\n // Note: For custom assets, the domain info should match the asset contract\n const domain = {\n name: settlement.networkConfig.defaultAsset.eip712.name,\n version: settlement.networkConfig.defaultAsset.eip712.version,\n chainId: settlement.networkConfig.chainId,\n verifyingContract: getAddress(settlement.asset),\n };\n\n // Build EIP-712 message\n // The \"to\" address is the SettlementRouter (not the final recipient)\n // The \"value\" MUST be total amount (business amount + facilitator fee)\n // because the Router needs to deduct the fee before passing to Hook\n const totalAmount = BigInt(settlement.amount) + BigInt(settlement.facilitatorFee);\n const message = {\n from: getAddress(settlement.from),\n to: getAddress(settlement.networkConfig.settlementRouter),\n value: totalAmount,\n validAfter: BigInt(settlement.validAfter),\n validBefore: BigInt(settlement.validBefore),\n nonce: settlement.commitment, // Use commitment as nonce\n };\n\n console.log(\"[x402x/client] EIP-712 Message for signing:\", {\n from: message.from,\n to: message.to,\n value: message.value.toString(),\n validAfter: message.validAfter.toString(),\n validBefore: message.validBefore.toString(),\n nonce: message.nonce,\n });\n\n // Sign typed data\n const signature = await signTypedData(wallet, {\n account: wallet.account,\n domain,\n types: AUTHORIZATION_TYPES,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Build authorization object\n const authorization = {\n from: settlement.from,\n to: settlement.networkConfig.settlementRouter as Address,\n value: totalAmount.toString(), // Use total amount (business + fee)\n validAfter: settlement.validAfter,\n validBefore: settlement.validBefore,\n nonce: settlement.commitment,\n };\n\n return {\n settlement,\n signature,\n authorization,\n };\n } catch (error) {\n if (error instanceof SigningError) {\n throw error;\n }\n\n // Handle common signing errors\n if (error instanceof Error) {\n if (error.message.includes(\"User rejected\")) {\n throw new SigningError(\"User rejected the signing request\", \"USER_REJECTED\");\n }\n if (error.message.includes(\"account\")) {\n throw new SigningError(\"Wallet account not available\", \"NO_ACCOUNT\");\n }\n throw new SigningError(`Failed to sign authorization: ${error.message}`, \"SIGNING_FAILED\");\n }\n\n throw new SigningError(\"Failed to sign authorization: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * Settle payment with facilitator\n *\n * This module handles the settlement of signed payment payloads with the\n * facilitator's /settle endpoint, following the x402 protocol.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { settle as coreSettle } from \"@x402x/core\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * Settle signed authorization with facilitator\n *\n * This function acts as a convenience wrapper that:\n * 1. Constructs the PaymentPayload according to x402 protocol\n * 2. Constructs the PaymentRequirements with settlement extra\n * 3. Calls core's settle() method to POST to facilitator's /settle endpoint\n * 4. Parses and returns the settlement result\n *\n * @param facilitatorUrl - Facilitator URL\n * @param signed - Signed authorization from signAuthorization\n * @param timeout - Optional timeout in milliseconds (default: 30000)\n * @returns Settlement result with transaction hash\n *\n * @throws FacilitatorError if request fails or facilitator returns error\n *\n * @example\n * ```typescript\n * import { settle } from '@x402x/client';\n *\n * const result = await settle(\n * 'https://facilitator.x402x.dev',\n * signed\n * );\n * console.log('TX Hash:', result.transaction);\n * ```\n */\nexport async function settle(\n facilitatorUrl: string,\n signed: SignedAuthorization,\n timeout: number = 30000,\n): Promise<SettleResult> {\n try {\n // Construct PaymentPayload\n const paymentPayload: PaymentPayload = {\n x402Version: 1,\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n payload: {\n signature: signed.signature,\n authorization: {\n from: signed.authorization.from,\n to: signed.authorization.to,\n value: signed.authorization.value,\n validAfter: signed.authorization.validAfter,\n validBefore: signed.authorization.validBefore,\n nonce: signed.authorization.nonce,\n },\n },\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n maxAmountRequired: signed.settlement.amount,\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\n // Required by x402 protocol (even though not used in serverless mode)\n // In the future, the x402 v2 will remove the resource field from the payment requirements\n // (https://github.com/coinbase/x402/pull/446)\n resource: \"https://x402x.dev/serverless\", // Placeholder for serverless mode\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n extra: {\n name: signed.settlement.networkConfig.defaultAsset.eip712.name,\n version: signed.settlement.networkConfig.defaultAsset.eip712.version,\n settlementRouter: signed.settlement.networkConfig.settlementRouter as Address,\n salt: signed.settlement.salt,\n payTo: signed.settlement.payTo,\n facilitatorFee: signed.settlement.facilitatorFee,\n hook: signed.settlement.hook,\n hookData: signed.settlement.hookData,\n },\n };\n\n // Include payment requirements in payload (for stateless facilitator processing)\n paymentPayload.paymentRequirements = paymentRequirements;\n\n // Call core's settle method\n const result = await coreSettle(facilitatorUrl, paymentPayload, paymentRequirements, timeout);\n\n return {\n success: result.success,\n transaction: result.transaction as Hex,\n network: result.network || signed.settlement.network,\n payer: (result.payer || signed.settlement.from) as Address,\n errorReason: result.errorReason,\n };\n } catch (error) {\n if (error instanceof FacilitatorError) {\n throw error;\n }\n\n // Handle errors from core settle\n if (error instanceof Error) {\n throw new FacilitatorError(`Failed to settle payment: ${error.message}`, \"SETTLEMENT_ERROR\");\n }\n\n throw new FacilitatorError(\"Failed to settle payment: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This is the main client class that provides a simple API for executing\n * on-chain contracts via facilitator without needing a resource server.\n */\n\nimport type { Address, Hex, TransactionReceipt } from \"viem\";\nimport { calculateFacilitatorFee, type FeeCalculationResult, TransferHook } from \"@x402x/core\";\nimport type { X402ClientConfig, ExecuteParams, ExecuteResult } from \"./types.js\";\nimport { prepareSettlement, DEFAULT_FACILITATOR_URL } from \"./core/prepare.js\";\nimport { signAuthorization } from \"./core/sign.js\";\nimport { settle } from \"./core/settle.js\";\nimport { ValidationError, FacilitatorError } from \"./errors.js\";\nimport { normalizeAddress, validateHex, validateAmount } from \"./core/utils.js\";\n\n/**\n * Re-export default facilitator URL for convenience\n */\nexport { DEFAULT_FACILITATOR_URL };\n\n/**\n * Internal configuration with required fields\n */\ninterface InternalConfig extends X402ClientConfig {\n facilitatorUrl: string;\n timeout: number;\n confirmationTimeout: number;\n}\n\n/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This client simplifies the entire settlement flow into a single execute() call,\n * automatically handling:\n * - Parameter preparation\n * - Commitment calculation\n * - EIP-712 signing\n * - Facilitator submission\n * - Transaction confirmation\n *\n * @example\n * ```typescript\n * import { X402Client } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n * import { useWalletClient } from 'wagmi';\n *\n * const { data: wallet } = useWalletClient();\n *\n * // Use default facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia'\n * });\n *\n * // Or specify custom facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia',\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * // Simple transfer (hook and hookData are optional)\n * const result = await client.execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * ```\n */\nexport class X402Client {\n private config: InternalConfig;\n\n /**\n * Create a new X402Client instance\n *\n * @param config - Client configuration\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if configuration is invalid\n */\n constructor(config: X402ClientConfig) {\n // Validate configuration\n if (!config.wallet) {\n throw new ValidationError(\"wallet is required\");\n }\n if (!config.network) {\n throw new ValidationError(\"network is required\");\n }\n\n this.config = {\n ...config,\n facilitatorUrl: config.facilitatorUrl || DEFAULT_FACILITATOR_URL,\n timeout: config.timeout || 30000,\n confirmationTimeout: config.confirmationTimeout || 60000,\n };\n }\n\n /**\n * Execute a settlement transaction\n *\n * This is the main method that orchestrates the entire settlement flow:\n * 1. Validates parameters\n * 2. Prepares settlement data (queries fee if needed)\n * 3. Signs EIP-3009 authorization\n * 4. Submits to facilitator\n * 5. Optionally waits for transaction confirmation\n *\n * @param params - Execution parameters\n * @param waitForConfirmation - Whether to wait for transaction confirmation (default: true)\n * @returns Execution result with transaction hash and optional receipt\n *\n * @throws ValidationError if parameters are invalid\n * @throws NetworkError if network is unsupported\n * @throws SigningError if user rejects signing\n * @throws FacilitatorError if facilitator request fails\n * @throws TransactionError if transaction fails\n *\n * @example Simple transfer (uses TransferHook by default)\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const result = await client.execute({\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * console.log('Transaction:', result.txHash);\n * ```\n *\n * @example Custom hook\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * const atomicAmount = parseDefaultAssetAmount('5', 'base-sepolia'); // '5000000'\n *\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * ```\n */\n async execute(\n params: ExecuteParams,\n waitForConfirmation: boolean = false,\n ): Promise<ExecuteResult> {\n // 1. Validate and normalize parameters\n const hook: Address = params.hook\n ? normalizeAddress(params.hook, \"hook\")\n : (TransferHook.getAddress(this.config.network) as Address);\n const payTo = normalizeAddress(params.payTo, \"payTo\");\n const hookData = params.hookData || \"0x\";\n\n if (params.hookData) {\n validateHex(params.hookData, \"hookData\");\n }\n validateAmount(params.amount, \"amount\");\n\n // 2. Prepare settlement with normalized addresses\n const settlement = await prepareSettlement({\n wallet: this.config.wallet,\n network: this.config.network,\n hook,\n hookData,\n asset: params.asset,\n amount: params.amount,\n payTo,\n facilitatorFee: params.facilitatorFee,\n customSalt: params.customSalt,\n validAfter: params.validAfter,\n validBefore: params.validBefore,\n networkConfig: this.config.networkConfig,\n facilitatorUrl: this.config.facilitatorUrl,\n });\n\n // 3. Sign authorization\n const signed = await signAuthorization(this.config.wallet, settlement);\n\n // 4. Settle with facilitator\n const settleResult = await settle(this.config.facilitatorUrl, signed, this.config.timeout);\n\n // 5. Optionally wait for confirmation\n let receipt: TransactionReceipt | undefined;\n if (waitForConfirmation) {\n receipt = await this.waitForTransaction(settleResult.transaction);\n }\n\n return {\n txHash: settleResult.transaction,\n network: settleResult.network,\n payer: settleResult.payer,\n receipt,\n settlement,\n };\n }\n\n /**\n * Calculate facilitator fee for a hook with optional hook data\n *\n * Queries the facilitator for the recommended fee based on current gas prices\n * and hook gas usage. The returned fee includes a safety margin to ensure\n * settlement will succeed.\n *\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result from facilitator\n *\n * @throws FacilitatorError if query fails\n *\n * @example\n * ```typescript\n * const fee = await client.calculateFee('0x...', '0x');\n * console.log('Facilitator fee:', fee.facilitatorFee);\n * console.log('Fee in USD:', fee.facilitatorFeeUSD);\n * console.log('Valid for:', fee.validitySeconds, 'seconds');\n * ```\n */\n async calculateFee(hook: Address, hookData: Hex = \"0x\"): Promise<FeeCalculationResult> {\n const normalizedHook = normalizeAddress(hook, \"hook\");\n validateHex(hookData, \"hookData\");\n\n try {\n return await calculateFacilitatorFee(\n this.config.facilitatorUrl,\n this.config.network,\n normalizedHook,\n hookData,\n );\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to calculate facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\n \"Failed to calculate facilitator fee: Unknown error\",\n \"UNKNOWN_ERROR\",\n );\n }\n }\n\n /**\n * Wait for transaction confirmation\n *\n * @param txHash - Transaction hash to wait for\n * @returns Transaction receipt\n *\n * @throws TransactionError if transaction fails or times out\n *\n * @example\n * ```typescript\n * const receipt = await client.waitForTransaction('0x...');\n * console.log('Status:', receipt.status);\n * ```\n */\n async waitForTransaction(txHash: Hex): Promise<TransactionReceipt> {\n // Check if wallet has waitForTransactionReceipt method\n const publicClient = this.config.wallet as any;\n if (typeof publicClient.waitForTransactionReceipt !== \"function\") {\n throw new Error(\n \"Wallet client does not support waitForTransactionReceipt. \" +\n \"Please use a viem PublicClient or WalletClient with public actions.\",\n );\n }\n\n try {\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: this.config.confirmationTimeout,\n });\n\n if (receipt.status !== \"success\") {\n throw new Error(`Transaction failed with status: ${receipt.status}`);\n }\n\n return receipt;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to confirm transaction: ${error.message}`);\n }\n throw new Error(\"Failed to confirm transaction: Unknown error\");\n }\n }\n\n /**\n * Get the network name\n */\n get network(): string {\n return this.config.network;\n }\n\n /**\n * Get the facilitator URL\n */\n get facilitatorUrl(): string {\n return this.config.facilitatorUrl;\n }\n\n /**\n * Get the wallet client\n */\n get wallet() {\n return this.config.wallet;\n }\n}\n","/**\n * React hook for creating X402Client instance\n *\n * This hook automatically creates an X402Client instance using wagmi's\n * wallet client and chain information.\n */\n\nimport { useMemo } from \"react\";\nimport {\n useWalletClient,\n useAccount,\n useChainId,\n WagmiProviderNotFoundError,\n} from \"wagmi\";\nimport { publicActions } from \"viem\";\nimport { X402Client } from \"../client.js\";\nimport type { X402ClientConfig } from \"../types.js\";\n\n/**\n * Partial configuration for useX402Client hook\n * (wallet, network, chainId are auto-detected from wagmi)\n */\nexport type UseX402ClientConfig = Partial<Omit<X402ClientConfig, \"wallet\" | \"network\">> & {\n /** Optional: Facilitator URL (default: https://facilitator.x402x.dev/) */\n facilitatorUrl?: string;\n /** Optional: Override network name (auto-detected from chain if not provided) */\n network?: string;\n};\n\n/**\n * Map chainId to network name\n */\nconst CHAIN_ID_TO_NETWORK: Record<number, string> = {\n 84532: \"base-sepolia\",\n 8453: \"base\",\n 196: \"x-layer\",\n 1952: \"x-layer-testnet\",\n};\n\n/**\n * React hook for X402Client\n *\n * Automatically creates an X402Client instance using the connected wallet\n * from wagmi. Returns null if wallet is not connected.\n *\n * @param config - Client configuration (facilitatorUrl is optional, defaults to https://facilitator.x402x.dev/)\n * @returns X402Client instance or null if wallet not connected\n *\n * @example\n * ```typescript\n * import { useX402Client } from '@x402x/client';\n *\n * function MyComponent() {\n * // Use default facilitator\n * const client = useX402Client();\n *\n * // Or specify custom facilitator\n * const client = useX402Client({\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * if (!client) {\n * return <div>Please connect your wallet</div>;\n * }\n *\n * const handlePay = async () => {\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * };\n *\n * return <button onClick={handlePay}>Pay</button>;\n * }\n * ```\n */\nexport function useX402Client(config?: UseX402ClientConfig): X402Client | null {\n // First, try to get wagmi hooks outside of useMemo to catch provider errors early\n let walletClient: any;\n let isConnected: boolean;\n let chainId: number;\n\n try {\n const walletClientResult = useWalletClient();\n const accountResult = useAccount();\n const chainIdResult = useChainId();\n\n walletClient = walletClientResult.data;\n isConnected = accountResult.isConnected;\n chainId = chainIdResult;\n } catch (error) {\n // If wagmi provider context is missing (e.g., during early render), return null quietly\n if (\n error instanceof WagmiProviderNotFoundError ||\n (error as any)?.name === \"WagmiProviderNotFoundError\" ||\n error instanceof Error && error.message.includes(\"useConfig\") && error.message.includes(\"WagmiProvider\")\n ) {\n return null;\n }\n\n console.warn(\"[x402x] Unable to access wagmi provider:\", error);\n return null;\n }\n\n return useMemo(() => {\n if (!isConnected || !walletClient) {\n return null;\n }\n\n // Determine network name\n const network = config?.network || CHAIN_ID_TO_NETWORK[chainId];\n if (!network) {\n console.warn(\n `[x402x] Unknown chainId ${chainId}. Please provide network name explicitly in config.`,\n );\n return null;\n }\n\n try {\n // Extend wallet client with public actions (required for waitForTransactionReceipt)\n const extendedWallet = walletClient.extend(publicActions);\n\n return new X402Client({\n wallet: extendedWallet,\n network,\n facilitatorUrl: config?.facilitatorUrl,\n networkConfig: config?.networkConfig,\n timeout: config?.timeout,\n confirmationTimeout: config?.confirmationTimeout,\n });\n } catch (error) {\n console.error(\"[x402x] Failed to create X402Client:\", error);\n return null;\n }\n }, [\n isConnected,\n walletClient,\n chainId,\n config?.network,\n config?.facilitatorUrl,\n config?.networkConfig,\n config?.timeout,\n config?.confirmationTimeout,\n ]);\n}\n","/**\n * React hook for executing settlements\n *\n * This hook provides a simple interface for executing settlements with\n * automatic state management (status, error, result).\n */\n\nimport { useState, useCallback } from \"react\";\nimport { useX402Client, type UseX402ClientConfig } from \"./useX402Client.js\";\nimport type { ExecuteParams, ExecuteResult, ExecuteStatus } from \"../types.js\";\n\n/**\n * Return type for useExecute hook\n */\nexport interface UseExecuteReturn {\n /** Execute a settlement */\n execute: (params: ExecuteParams, waitForConfirmation?: boolean) => Promise<ExecuteResult>;\n /** Current execution status */\n status: ExecuteStatus;\n /** Error if execution failed */\n error: Error | null;\n /** Result if execution succeeded */\n result: ExecuteResult | null;\n /** Reset state */\n reset: () => void;\n /** Whether currently executing */\n isExecuting: boolean;\n /** Whether execution succeeded */\n isSuccess: boolean;\n /** Whether execution failed */\n isError: boolean;\n}\n\n/**\n * React hook for executing settlements\n *\n * Provides a simple interface for executing settlements with automatic\n * state management. Automatically uses the connected wallet from wagmi.\n *\n * @param config - Optional client configuration (if not using global client)\n * @returns Execute function and state\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n *\n * function PayButton() {\n * const { execute, status, error, result } = useExecute({\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n *\n * const handlePay = async () => {\n * try {\n * // Simple transfer (hook and hookData are optional)\n * const result = await execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * console.log('Success:', result.txHash);\n * } catch (err) {\n * console.error('Failed:', err);\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * {status === 'idle' ? 'Pay' : 'Processing...'}\n * </button>\n * {status === 'success' && <div>✅ Success! TX: {result.txHash}</div>}\n * {status === 'error' && <div>❌ Error: {error.message}</div>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecute(config?: UseX402ClientConfig): UseExecuteReturn {\n const client = useX402Client(config);\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n setStatus(\"idle\");\n setError(null);\n setResult(null);\n }, []);\n\n return {\n execute,\n status,\n error,\n result,\n reset,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n\n/**\n * Alternative hook that doesn't require config (uses default client from context)\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n *\n * function PayButton({ facilitatorUrl }: { facilitatorUrl: string }) {\n * const { execute, status, error } = useExecute({ facilitatorUrl });\n *\n * const handlePay = async () => {\n * await execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * recipient: '0x...'\n * });\n * };\n *\n * return (\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * Pay\n * </button>\n * );\n * }\n * ```\n */\nexport function useExecuteWithClient(\n client: ReturnType<typeof useX402Client>,\n): Omit<UseExecuteReturn, \"reset\"> {\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n return {\n execute,\n status,\n error,\n result,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n"]}
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;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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402x 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"]}
package/dist/index.d.cts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { Hex } from '../types/misc.js';
2
2
  import * as viem from 'viem';
3
3
  import { WalletClient, Address, Hex as Hex$1, TransactionReceipt } from 'viem';
4
- import { NetworkConfig, FeeCalculationResult } from '@x402x/core';
5
- export { AmountError, FeeCalculationResult, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/core';
6
- export { PaymentPayload, PaymentRequirements } from 'x402/types';
4
+ import { NetworkConfig, FeeCalculationResult } from '@x402x/extensions';
5
+ export { AmountError, FeeCalculationResult, PaymentPayload as PaymentPayloadV2, PaymentRequirements as PaymentRequirementsV2, SettlementExtra, SettlementExtraCore, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/extensions';
7
6
 
8
7
  type CcipRequestReturnType = Hex;
9
8
 
package/dist/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { Hex } from '../types/misc.js';
2
2
  import * as viem from 'viem';
3
3
  import { WalletClient, Address, Hex as Hex$1, TransactionReceipt } from 'viem';
4
- import { NetworkConfig, FeeCalculationResult } from '@x402x/core';
5
- export { AmountError, FeeCalculationResult, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/core';
6
- export { PaymentPayload, PaymentRequirements } from 'x402/types';
4
+ import { NetworkConfig, FeeCalculationResult } from '@x402x/extensions';
5
+ export { AmountError, FeeCalculationResult, PaymentPayload as PaymentPayloadV2, PaymentRequirements as PaymentRequirementsV2, SettlementExtra, SettlementExtraCore, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/extensions';
7
6
 
8
7
  type CcipRequestReturnType = Hex;
9
8
 
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { getNetworkConfig, calculateCommitment, settle as settle$1, TransferHook, calculateFacilitatorFee } from '@x402x/core';
2
- export { AmountError, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/core';
1
+ import { getNetworkConfig, calculateCommitment, toCanonicalNetworkKey, settle as settle$1, TransferHook, calculateFacilitatorFee } from '@x402x/extensions';
2
+ export { AmountError, formatDefaultAssetAmount, parseDefaultAssetAmount } from '@x402x/extensions';
3
3
  import { getAddress, publicActions, isAddress } from 'viem';
4
4
  import { signTypedData } from 'viem/actions';
5
5
  import { useMemo, useState, useCallback } from 'react';
@@ -55,7 +55,11 @@ var ValidationError = class _ValidationError extends X402ClientError {
55
55
  }
56
56
  };
57
57
  function generateSalt() {
58
- const randomBytes = crypto.getRandomValues(new Uint8Array(32));
58
+ const cryptoObj = globalThis.crypto;
59
+ if (!cryptoObj || !cryptoObj.getRandomValues) {
60
+ throw new Error("crypto.getRandomValues is not available");
61
+ }
62
+ const randomBytes = cryptoObj.getRandomValues(new Uint8Array(32));
59
63
  return `0x${Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
60
64
  }
61
65
  function normalizeAddress(address, name = "address") {
@@ -310,39 +314,52 @@ async function signAuthorization(wallet, settlement) {
310
314
  }
311
315
  async function settle(facilitatorUrl, signed, timeout = 3e4) {
312
316
  try {
313
- const paymentPayload = {
314
- x402Version: 1,
315
- scheme: "exact",
316
- network: signed.settlement.network,
317
- // Network type compatibility
318
- payload: {
319
- signature: signed.signature,
320
- authorization: {
321
- from: signed.authorization.from,
322
- to: signed.authorization.to,
323
- value: signed.authorization.value,
324
- validAfter: signed.authorization.validAfter,
325
- validBefore: signed.authorization.validBefore,
326
- nonce: signed.authorization.nonce
327
- }
317
+ const canonicalNetwork = toCanonicalNetworkKey(signed.settlement.network);
318
+ const totalAmount = (BigInt(signed.settlement.amount) + BigInt(signed.settlement.facilitatorFee)).toString();
319
+ const exactEvmPayload = {
320
+ signature: signed.signature,
321
+ authorization: {
322
+ from: signed.authorization.from,
323
+ to: signed.authorization.to,
324
+ value: signed.authorization.value,
325
+ validAfter: signed.authorization.validAfter,
326
+ validBefore: signed.authorization.validBefore,
327
+ nonce: signed.authorization.nonce
328
328
  }
329
329
  };
330
+ const paymentPayload = {
331
+ x402Version: 2,
332
+ // Use v2 protocol
333
+ resource: {
334
+ url: "https://x402x.dev/serverless",
335
+ description: "x402x Serverless Settlement",
336
+ mimeType: "application/json"
337
+ },
338
+ accepted: {
339
+ scheme: "exact",
340
+ network: canonicalNetwork,
341
+ // Type cast required: core_v2 Network type accepts both CAIP-2 and legacy formats
342
+ asset: signed.settlement.asset,
343
+ amount: totalAmount,
344
+ // Use totalAmount to match commitment calculation
345
+ payTo: signed.settlement.networkConfig.settlementRouter,
346
+ maxTimeoutSeconds: 300,
347
+ extra: {}
348
+ },
349
+ // Standard EVM exact scheme payload
350
+ payload: exactEvmPayload
351
+ // Type cast required: ExactEvmPayload structure matches v2 protocol
352
+ };
330
353
  const paymentRequirements = {
331
354
  scheme: "exact",
332
- network: signed.settlement.network,
333
- // Network type compatibility
334
- maxAmountRequired: signed.settlement.amount,
355
+ network: canonicalNetwork,
356
+ // Type cast required: core_v2 Network type accepts CAIP-2 format
357
+ amount: totalAmount,
358
+ // Total amount including facilitator fee
335
359
  asset: signed.settlement.asset,
336
360
  payTo: signed.settlement.networkConfig.settlementRouter,
337
361
  maxTimeoutSeconds: 300,
338
362
  // 5 minutes
339
- // Required by x402 protocol (even though not used in serverless mode)
340
- // In the future, the x402 v2 will remove the resource field from the payment requirements
341
- // (https://github.com/coinbase/x402/pull/446)
342
- resource: "https://x402x.dev/serverless",
343
- // Placeholder for serverless mode
344
- description: "x402x Serverless Settlement",
345
- mimeType: "application/json",
346
363
  extra: {
347
364
  name: signed.settlement.networkConfig.defaultAsset.eip712.name,
348
365
  version: signed.settlement.networkConfig.defaultAsset.eip712.version,
@@ -354,7 +371,6 @@ async function settle(facilitatorUrl, signed, timeout = 3e4) {
354
371
  hookData: signed.settlement.hookData
355
372
  }
356
373
  };
357
- paymentPayload.paymentRequirements = paymentRequirements;
358
374
  const result = await settle$1(facilitatorUrl, paymentPayload, paymentRequirements, timeout);
359
375
  return {
360
376
  success: result.success,
@@ -586,7 +602,9 @@ var CHAIN_ID_TO_NETWORK = {
586
602
  84532: "base-sepolia",
587
603
  8453: "base",
588
604
  196: "x-layer",
589
- 1952: "x-layer-testnet"
605
+ 1952: "x-layer-testnet",
606
+ 97: "bsc-testnet",
607
+ 56: "bsc"
590
608
  };
591
609
  function useX402Client(config) {
592
610
  let walletClient;
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","cal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AM,uDAAuD,CAAA;AAAA,MACzE;AAEA,MAAA,SAAA,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 randomBytes = crypto.getRandomValues(new Uint8Array(32));\n return `0x${Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}` as Hex;\n}\n\n/**\n * Normalize Ethereum address to EIP-55 checksum format\n *\n * Automatically converts any valid Ethereum address (lowercase, uppercase, or mixed)\n * to the proper checksummed format. This provides a better developer experience\n * by accepting addresses in any case format.\n *\n * @param address - Address to normalize (can be any case)\n * @param name - Parameter name for error messages (optional)\n * @returns Checksummed address in EIP-55 format\n * @throws ValidationError if address is invalid\n *\n * @example\n * ```typescript\n * normalizeAddress('0xabc123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xABC123...') // Returns '0xAbC123...' (checksummed)\n * normalizeAddress('0xAbC123...') // Returns '0xAbC123...' (already checksummed)\n * ```\n */\nexport function normalizeAddress(address: string, name: string = \"address\"): Address {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to EIP-55 checksum format\n // getAddress() will throw if the address is invalid\n try {\n return getAddress(address);\n } catch (error) {\n throw new ValidationError(\n `${name} is not a valid Ethereum address: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Validate Ethereum address format (legacy, prefer normalizeAddress)\n *\n * @deprecated Use normalizeAddress() instead for better developer experience\n * @param address - Address to validate\n * @param name - Parameter name for error messages\n * @throws ValidationError if address is invalid\n */\nexport function validateAddress(address: string, name: string): void {\n if (!address || typeof address !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!isAddress(address)) {\n throw new ValidationError(`${name} must be a valid Ethereum address`);\n }\n}\n\n/**\n * Validate hex string format\n *\n * @param hex - Hex string to validate\n * @param name - Parameter name for error messages\n * @param expectedLength - Optional expected length (in bytes, not characters)\n * @throws ValidationError if hex is invalid\n */\nexport function validateHex(hex: string, name: string, expectedLength?: number): void {\n if (!hex || typeof hex !== \"string\") {\n throw new ValidationError(`${name} is required`);\n }\n if (!hex.startsWith(\"0x\")) {\n throw new ValidationError(`${name} must start with 0x`);\n }\n if (!/^0x[0-9a-fA-F]*$/.test(hex)) {\n throw new ValidationError(`${name} must be a valid hex string`);\n }\n if (expectedLength !== undefined) {\n const actualLength = (hex.length - 2) / 2;\n if (actualLength !== expectedLength) {\n throw new ValidationError(\n `${name} must be ${expectedLength} bytes, got ${actualLength} bytes`,\n );\n }\n }\n}\n\n/**\n * Validate amount format - must be atomic units (positive integer string)\n *\n * This function validates that the amount is a valid atomic unit string.\n * For converting USD amounts to atomic units, use parseDefaultAssetAmount from @x402x/core.\n *\n * @param amount - Amount in atomic units (must be a positive integer string)\n * @param name - Parameter name for error messages\n * @throws ValidationError if amount is invalid\n *\n * @example\n * ```typescript\n * validateAmount('1000000', 'amount'); // Valid: atomic units\n * validateAmount('0.1', 'amount'); // Invalid: not atomic units\n * validateAmount('-1', 'amount'); // Invalid: negative\n * ```\n */\nexport function validateAmount(amount: string | number, name: string): void {\n if (amount === null || amount === undefined || amount === \"\") {\n throw new ValidationError(`${name} is required`);\n }\n\n // Convert to string if number\n const amountStr = typeof amount === \"number\" ? amount.toString() : amount;\n\n // Must be a non-empty string\n if (typeof amountStr !== \"string\" || amountStr.trim() === \"\") {\n throw new ValidationError(`${name} must be a non-empty string`);\n }\n\n // Must be a valid positive integer (atomic units)\n // Allow leading zeros but must be numeric\n if (!/^\\d+$/.test(amountStr)) {\n throw new ValidationError(\n `${name} must be a positive integer string (atomic units). ` +\n `Use parseDefaultAssetAmount() from @x402x/core to convert USD amounts.`,\n );\n }\n\n // Validate it can be converted to BigInt (no overflow)\n try {\n const atomicAmount = BigInt(amountStr);\n if (atomicAmount < 0n) {\n throw new ValidationError(`${name} cannot be negative`);\n }\n if (atomicAmount === 0n) {\n throw new ValidationError(`${name} cannot be zero`);\n }\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(\n `${name} is not a valid amount: ${error instanceof Error ? error.message : \"Invalid format\"}`,\n );\n }\n}\n\n/**\n * Format facilitator URL (ensure it doesn't end with slash)\n *\n * @param url - Facilitator URL\n * @returns Formatted URL\n */\nexport function formatFacilitatorUrl(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/**\n * Calculate default time window for authorization\n *\n * @param maxTimeoutSeconds - Maximum timeout in seconds\n * @returns Object with validAfter and validBefore timestamps\n */\nexport function calculateTimeWindow(maxTimeoutSeconds: number = 300): {\n validAfter: string;\n validBefore: string;\n} {\n const now = Math.floor(Date.now() / 1000);\n return {\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + maxTimeoutSeconds).toString(),\n };\n}\n","/**\n * Prepare settlement data for signing\n *\n * This module handles the preparation of settlement parameters before signing,\n * including generating salt, calculating commitment hash, and fetching facilitator fees.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getNetworkConfig, calculateFacilitatorFee, type FeeCalculationResult } from \"@x402x/core\";\nimport { calculateCommitment } from \"@x402x/core\";\nimport type { PrepareParams, SettlementData } from \"../types.js\";\nimport { NetworkError, ValidationError, FacilitatorError } from \"../errors.js\";\nimport {\n generateSalt,\n validateAddress,\n validateHex,\n validateAmount,\n calculateTimeWindow,\n} from \"./utils.js\";\n\n/**\n * Default facilitator URL\n */\nexport const DEFAULT_FACILITATOR_URL = \"https://facilitator.x402x.dev\";\n\n/**\n * Query facilitator fee from facilitator service (internal helper)\n *\n * Uses the /calculate-fee endpoint which provides accurate gas cost estimates\n * with safety margins.\n *\n * @internal\n * @param facilitatorUrl - Facilitator URL\n * @param network - Network name\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result\n *\n * @throws FacilitatorError if request fails\n */\nasync function queryFacilitatorFee(\n facilitatorUrl: string,\n network: string,\n hook: Address,\n hookData: Hex = \"0x\",\n): Promise<FeeCalculationResult> {\n try {\n return await calculateFacilitatorFee(facilitatorUrl, network, hook, hookData);\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to query facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\"Failed to query facilitator fee: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n\n/**\n * Prepare settlement data for signing\n *\n * This function:\n * 1. Validates all parameters\n * 2. Loads network configuration\n * 3. Generates salt (if not provided)\n * 4. Queries facilitator fee (if not provided)\n * 5. Calculates time window (if not provided)\n * 6. Calculates commitment hash\n * 7. Returns prepared settlement data\n *\n * @param params - Preparation parameters\n * @returns Prepared settlement data ready for signing\n *\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if parameters are invalid\n *\n * @example\n * ```typescript\n * import { prepareSettlement } from '@x402x/client';\n * import { TransferHook, parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units first\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const settlement = await prepareSettlement({\n * wallet: walletClient,\n * network: 'base-sepolia',\n * hook: TransferHook.getAddress('base-sepolia'),\n * hookData: TransferHook.encode(),\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...',\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n * ```\n */\nexport async function prepareSettlement(params: PrepareParams): Promise<SettlementData> {\n // 1. Validate parameters\n validateAddress(params.hook, \"hook\");\n validateHex(params.hookData, \"hookData\");\n validateAddress(params.payTo, \"payTo\");\n\n // 2. Validate amount (must be atomic units, no automatic conversion)\n validateAmount(params.amount, \"amount\");\n const atomicAmount = params.amount;\n\n if (params.customSalt) {\n validateHex(params.customSalt, \"customSalt\", 32);\n }\n\n // 2. Get wallet account address\n const from = params.wallet.account?.address;\n if (!from) {\n throw new ValidationError(\"Wallet client must have an account\");\n }\n\n // 3. Load network configuration\n const networkConfig = params.networkConfig || getNetworkConfig(params.network);\n if (!networkConfig) {\n throw new NetworkError(\n `Network '${params.network}' is not supported. Please provide custom networkConfig.`,\n );\n }\n\n // 4. Determine asset address (use provided asset or default asset)\n const asset = params.asset || (networkConfig.defaultAsset.address as Address);\n validateAddress(asset, \"asset\");\n\n // 5. Generate salt (if not provided)\n const salt = params.customSalt || generateSalt();\n\n // 6. Query facilitator fee (if not provided)\n // Use the provided facilitatorUrl or fall back to default\n let facilitatorFee = params.facilitatorFee || \"0\";\n if (!params.facilitatorFee) {\n const facilitatorUrl = params.facilitatorUrl || DEFAULT_FACILITATOR_URL;\n try {\n const feeEstimate = await queryFacilitatorFee(\n facilitatorUrl,\n params.network,\n params.hook,\n params.hookData, // Pass hookData for accurate fee calculation\n );\n\n if (!feeEstimate.hookAllowed) {\n throw new ValidationError(\n `Hook ${params.hook} is not allowed on network ${params.network}.`,\n );\n }\n\n facilitatorFee = feeEstimate.facilitatorFee;\n } catch (error) {\n // If fee query fails, log warning and use 0\n console.warn(\n `[x402x] Failed to query facilitator fee, using 0. This may cause settlement to fail. Error: ${error instanceof Error ? error.message : \"Unknown\"}`,\n );\n facilitatorFee = \"0\";\n }\n }\n\n // 7. Calculate time window (if not provided)\n const timeWindow =\n params.validAfter && params.validBefore\n ? { validAfter: params.validAfter, validBefore: params.validBefore }\n : calculateTimeWindow(300); // 5 minutes default\n\n // 8. Calculate commitment hash\n // IMPORTANT: value must be total amount (business amount + facilitator fee)\n // because the contract's calculateCommitment expects the same value that\n // will be authorized in the EIP-3009 signature\n const totalAmount = (BigInt(atomicAmount) + BigInt(facilitatorFee)).toString();\n const commitment = calculateCommitment({\n chainId: networkConfig.chainId,\n hub: networkConfig.settlementRouter as Address,\n asset: asset,\n from,\n value: totalAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n });\n\n // 9. Return prepared settlement data\n return {\n network: params.network,\n networkConfig,\n asset: asset,\n from,\n amount: atomicAmount,\n validAfter: timeWindow.validAfter,\n validBefore: timeWindow.validBefore,\n salt,\n payTo: params.payTo,\n facilitatorFee,\n hook: params.hook,\n hookData: params.hookData,\n commitment: commitment as Hex,\n };\n}\n","/**\n * Sign EIP-3009 authorization for settlement\n *\n * This module handles the signing of EIP-712 typed data for EIP-3009\n * transferWithAuthorization, using the commitment hash as the nonce.\n */\n\nimport type { Address, WalletClient } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { signTypedData } from \"viem/actions\";\nimport type { SettlementData, SignedAuthorization } from \"../types.js\";\nimport { SigningError } from \"../errors.js\";\n\n/**\n * EIP-3009 authorization types for EIP-712 signature\n */\nconst AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Sign EIP-3009 authorization\n *\n * This function signs an EIP-712 typed data message for EIP-3009's\n * transferWithAuthorization function. The commitment hash is used\n * as the nonce to cryptographically bind all settlement parameters.\n *\n * @param wallet - Wallet client from wagmi/viem\n * @param settlement - Prepared settlement data\n * @returns Signed authorization ready to submit\n *\n * @throws SigningError if signing fails or wallet doesn't support signing\n *\n * @example\n * ```typescript\n * import { signAuthorization } from '@x402x/client';\n *\n * const signed = await signAuthorization(walletClient, settlement);\n * console.log('Signature:', signed.signature);\n * ```\n */\nexport async function signAuthorization(\n wallet: WalletClient,\n settlement: SettlementData,\n): Promise<SignedAuthorization> {\n try {\n // Ensure wallet has an account\n if (!wallet.account) {\n throw new SigningError(\"Wallet client must have an account\");\n }\n\n // Build EIP-712 domain\n // Use the asset's EIP-712 domain info from network config\n // Note: For custom assets, the domain info should match the asset contract\n const domain = {\n name: settlement.networkConfig.defaultAsset.eip712.name,\n version: settlement.networkConfig.defaultAsset.eip712.version,\n chainId: settlement.networkConfig.chainId,\n verifyingContract: getAddress(settlement.asset),\n };\n\n // Build EIP-712 message\n // The \"to\" address is the SettlementRouter (not the final recipient)\n // The \"value\" MUST be total amount (business amount + facilitator fee)\n // because the Router needs to deduct the fee before passing to Hook\n const totalAmount = BigInt(settlement.amount) + BigInt(settlement.facilitatorFee);\n const message = {\n from: getAddress(settlement.from),\n to: getAddress(settlement.networkConfig.settlementRouter),\n value: totalAmount,\n validAfter: BigInt(settlement.validAfter),\n validBefore: BigInt(settlement.validBefore),\n nonce: settlement.commitment, // Use commitment as nonce\n };\n\n console.log(\"[x402x/client] EIP-712 Message for signing:\", {\n from: message.from,\n to: message.to,\n value: message.value.toString(),\n validAfter: message.validAfter.toString(),\n validBefore: message.validBefore.toString(),\n nonce: message.nonce,\n });\n\n // Sign typed data\n const signature = await signTypedData(wallet, {\n account: wallet.account,\n domain,\n types: AUTHORIZATION_TYPES,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Build authorization object\n const authorization = {\n from: settlement.from,\n to: settlement.networkConfig.settlementRouter as Address,\n value: totalAmount.toString(), // Use total amount (business + fee)\n validAfter: settlement.validAfter,\n validBefore: settlement.validBefore,\n nonce: settlement.commitment,\n };\n\n return {\n settlement,\n signature,\n authorization,\n };\n } catch (error) {\n if (error instanceof SigningError) {\n throw error;\n }\n\n // Handle common signing errors\n if (error instanceof Error) {\n if (error.message.includes(\"User rejected\")) {\n throw new SigningError(\"User rejected the signing request\", \"USER_REJECTED\");\n }\n if (error.message.includes(\"account\")) {\n throw new SigningError(\"Wallet account not available\", \"NO_ACCOUNT\");\n }\n throw new SigningError(`Failed to sign authorization: ${error.message}`, \"SIGNING_FAILED\");\n }\n\n throw new SigningError(\"Failed to sign authorization: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * Settle payment with facilitator\n *\n * This module handles the settlement of signed payment payloads with the\n * facilitator's /settle endpoint, following the x402 protocol.\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { settle as coreSettle } from \"@x402x/core\";\nimport type {\n SignedAuthorization,\n SettleResult,\n PaymentPayload,\n PaymentRequirements,\n} from \"../types.js\";\nimport { FacilitatorError } from \"../errors.js\";\n\n/**\n * Settle signed authorization with facilitator\n *\n * This function acts as a convenience wrapper that:\n * 1. Constructs the PaymentPayload according to x402 protocol\n * 2. Constructs the PaymentRequirements with settlement extra\n * 3. Calls core's settle() method to POST to facilitator's /settle endpoint\n * 4. Parses and returns the settlement result\n *\n * @param facilitatorUrl - Facilitator URL\n * @param signed - Signed authorization from signAuthorization\n * @param timeout - Optional timeout in milliseconds (default: 30000)\n * @returns Settlement result with transaction hash\n *\n * @throws FacilitatorError if request fails or facilitator returns error\n *\n * @example\n * ```typescript\n * import { settle } from '@x402x/client';\n *\n * const result = await settle(\n * 'https://facilitator.x402x.dev',\n * signed\n * );\n * console.log('TX Hash:', result.transaction);\n * ```\n */\nexport async function settle(\n facilitatorUrl: string,\n signed: SignedAuthorization,\n timeout: number = 30000,\n): Promise<SettleResult> {\n try {\n // Construct PaymentPayload\n const paymentPayload: PaymentPayload = {\n x402Version: 1,\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n payload: {\n signature: signed.signature,\n authorization: {\n from: signed.authorization.from,\n to: signed.authorization.to,\n value: signed.authorization.value,\n validAfter: signed.authorization.validAfter,\n validBefore: signed.authorization.validBefore,\n nonce: signed.authorization.nonce,\n },\n },\n };\n\n // Construct PaymentRequirements (for serverless mode verification)\n const paymentRequirements: PaymentRequirements = {\n scheme: \"exact\",\n network: signed.settlement.network as any, // Network type compatibility\n maxAmountRequired: signed.settlement.amount,\n asset: signed.settlement.asset as Address,\n payTo: signed.settlement.networkConfig.settlementRouter as Address,\n maxTimeoutSeconds: 300, // 5 minutes\n // Required by x402 protocol (even though not used in serverless mode)\n // In the future, the x402 v2 will remove the resource field from the payment requirements\n // (https://github.com/coinbase/x402/pull/446)\n resource: \"https://x402x.dev/serverless\", // Placeholder for serverless mode\n description: \"x402x Serverless Settlement\",\n mimeType: \"application/json\",\n extra: {\n name: signed.settlement.networkConfig.defaultAsset.eip712.name,\n version: signed.settlement.networkConfig.defaultAsset.eip712.version,\n settlementRouter: signed.settlement.networkConfig.settlementRouter as Address,\n salt: signed.settlement.salt,\n payTo: signed.settlement.payTo,\n facilitatorFee: signed.settlement.facilitatorFee,\n hook: signed.settlement.hook,\n hookData: signed.settlement.hookData,\n },\n };\n\n // Include payment requirements in payload (for stateless facilitator processing)\n paymentPayload.paymentRequirements = paymentRequirements;\n\n // Call core's settle method\n const result = await coreSettle(facilitatorUrl, paymentPayload, paymentRequirements, timeout);\n\n return {\n success: result.success,\n transaction: result.transaction as Hex,\n network: result.network || signed.settlement.network,\n payer: (result.payer || signed.settlement.from) as Address,\n errorReason: result.errorReason,\n };\n } catch (error) {\n if (error instanceof FacilitatorError) {\n throw error;\n }\n\n // Handle errors from core settle\n if (error instanceof Error) {\n throw new FacilitatorError(`Failed to settle payment: ${error.message}`, \"SETTLEMENT_ERROR\");\n }\n\n throw new FacilitatorError(\"Failed to settle payment: Unknown error\", \"UNKNOWN_ERROR\");\n }\n}\n","/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This is the main client class that provides a simple API for executing\n * on-chain contracts via facilitator without needing a resource server.\n */\n\nimport type { Address, Hex, TransactionReceipt } from \"viem\";\nimport { calculateFacilitatorFee, type FeeCalculationResult, TransferHook } from \"@x402x/core\";\nimport type { X402ClientConfig, ExecuteParams, ExecuteResult } from \"./types.js\";\nimport { prepareSettlement, DEFAULT_FACILITATOR_URL } from \"./core/prepare.js\";\nimport { signAuthorization } from \"./core/sign.js\";\nimport { settle } from \"./core/settle.js\";\nimport { ValidationError, FacilitatorError } from \"./errors.js\";\nimport { normalizeAddress, validateHex, validateAmount } from \"./core/utils.js\";\n\n/**\n * Re-export default facilitator URL for convenience\n */\nexport { DEFAULT_FACILITATOR_URL };\n\n/**\n * Internal configuration with required fields\n */\ninterface InternalConfig extends X402ClientConfig {\n facilitatorUrl: string;\n timeout: number;\n confirmationTimeout: number;\n}\n\n/**\n * X402Client - High-level client for x402x Serverless Mode\n *\n * This client simplifies the entire settlement flow into a single execute() call,\n * automatically handling:\n * - Parameter preparation\n * - Commitment calculation\n * - EIP-712 signing\n * - Facilitator submission\n * - Transaction confirmation\n *\n * @example\n * ```typescript\n * import { X402Client } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n * import { useWalletClient } from 'wagmi';\n *\n * const { data: wallet } = useWalletClient();\n *\n * // Use default facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia'\n * });\n *\n * // Or specify custom facilitator\n * const client = new X402Client({\n * wallet,\n * network: 'base-sepolia',\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * // Simple transfer (hook and hookData are optional)\n * const result = await client.execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * ```\n */\nexport class X402Client {\n private config: InternalConfig;\n\n /**\n * Create a new X402Client instance\n *\n * @param config - Client configuration\n * @throws NetworkError if network is unsupported\n * @throws ValidationError if configuration is invalid\n */\n constructor(config: X402ClientConfig) {\n // Validate configuration\n if (!config.wallet) {\n throw new ValidationError(\"wallet is required\");\n }\n if (!config.network) {\n throw new ValidationError(\"network is required\");\n }\n\n this.config = {\n ...config,\n facilitatorUrl: config.facilitatorUrl || DEFAULT_FACILITATOR_URL,\n timeout: config.timeout || 30000,\n confirmationTimeout: config.confirmationTimeout || 60000,\n };\n }\n\n /**\n * Execute a settlement transaction\n *\n * This is the main method that orchestrates the entire settlement flow:\n * 1. Validates parameters\n * 2. Prepares settlement data (queries fee if needed)\n * 3. Signs EIP-3009 authorization\n * 4. Submits to facilitator\n * 5. Optionally waits for transaction confirmation\n *\n * @param params - Execution parameters\n * @param waitForConfirmation - Whether to wait for transaction confirmation (default: true)\n * @returns Execution result with transaction hash and optional receipt\n *\n * @throws ValidationError if parameters are invalid\n * @throws NetworkError if network is unsupported\n * @throws SigningError if user rejects signing\n * @throws FacilitatorError if facilitator request fails\n * @throws TransactionError if transaction fails\n *\n * @example Simple transfer (uses TransferHook by default)\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * // Convert USD amount to atomic units\n * const atomicAmount = parseDefaultAssetAmount('1', 'base-sepolia'); // '1000000'\n *\n * const result = await client.execute({\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * console.log('Transaction:', result.txHash);\n * ```\n *\n * @example Custom hook\n * ```typescript\n * import { parseDefaultAssetAmount } from '@x402x/core';\n *\n * const atomicAmount = parseDefaultAssetAmount('5', 'base-sepolia'); // '5000000'\n *\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: atomicAmount, // Must be atomic units\n * payTo: '0x...'\n * });\n * ```\n */\n async execute(\n params: ExecuteParams,\n waitForConfirmation: boolean = false,\n ): Promise<ExecuteResult> {\n // 1. Validate and normalize parameters\n const hook: Address = params.hook\n ? normalizeAddress(params.hook, \"hook\")\n : (TransferHook.getAddress(this.config.network) as Address);\n const payTo = normalizeAddress(params.payTo, \"payTo\");\n const hookData = params.hookData || \"0x\";\n\n if (params.hookData) {\n validateHex(params.hookData, \"hookData\");\n }\n validateAmount(params.amount, \"amount\");\n\n // 2. Prepare settlement with normalized addresses\n const settlement = await prepareSettlement({\n wallet: this.config.wallet,\n network: this.config.network,\n hook,\n hookData,\n asset: params.asset,\n amount: params.amount,\n payTo,\n facilitatorFee: params.facilitatorFee,\n customSalt: params.customSalt,\n validAfter: params.validAfter,\n validBefore: params.validBefore,\n networkConfig: this.config.networkConfig,\n facilitatorUrl: this.config.facilitatorUrl,\n });\n\n // 3. Sign authorization\n const signed = await signAuthorization(this.config.wallet, settlement);\n\n // 4. Settle with facilitator\n const settleResult = await settle(this.config.facilitatorUrl, signed, this.config.timeout);\n\n // 5. Optionally wait for confirmation\n let receipt: TransactionReceipt | undefined;\n if (waitForConfirmation) {\n receipt = await this.waitForTransaction(settleResult.transaction);\n }\n\n return {\n txHash: settleResult.transaction,\n network: settleResult.network,\n payer: settleResult.payer,\n receipt,\n settlement,\n };\n }\n\n /**\n * Calculate facilitator fee for a hook with optional hook data\n *\n * Queries the facilitator for the recommended fee based on current gas prices\n * and hook gas usage. The returned fee includes a safety margin to ensure\n * settlement will succeed.\n *\n * @param hook - Hook contract address\n * @param hookData - Optional encoded hook parameters (default: '0x')\n * @returns Fee calculation result from facilitator\n *\n * @throws FacilitatorError if query fails\n *\n * @example\n * ```typescript\n * const fee = await client.calculateFee('0x...', '0x');\n * console.log('Facilitator fee:', fee.facilitatorFee);\n * console.log('Fee in USD:', fee.facilitatorFeeUSD);\n * console.log('Valid for:', fee.validitySeconds, 'seconds');\n * ```\n */\n async calculateFee(hook: Address, hookData: Hex = \"0x\"): Promise<FeeCalculationResult> {\n const normalizedHook = normalizeAddress(hook, \"hook\");\n validateHex(hookData, \"hookData\");\n\n try {\n return await calculateFacilitatorFee(\n this.config.facilitatorUrl,\n this.config.network,\n normalizedHook,\n hookData,\n );\n } catch (error) {\n if (error instanceof Error) {\n throw new FacilitatorError(\n `Failed to calculate facilitator fee: ${error.message}`,\n \"FEE_QUERY_FAILED\",\n );\n }\n throw new FacilitatorError(\n \"Failed to calculate facilitator fee: Unknown error\",\n \"UNKNOWN_ERROR\",\n );\n }\n }\n\n /**\n * Wait for transaction confirmation\n *\n * @param txHash - Transaction hash to wait for\n * @returns Transaction receipt\n *\n * @throws TransactionError if transaction fails or times out\n *\n * @example\n * ```typescript\n * const receipt = await client.waitForTransaction('0x...');\n * console.log('Status:', receipt.status);\n * ```\n */\n async waitForTransaction(txHash: Hex): Promise<TransactionReceipt> {\n // Check if wallet has waitForTransactionReceipt method\n const publicClient = this.config.wallet as any;\n if (typeof publicClient.waitForTransactionReceipt !== \"function\") {\n throw new Error(\n \"Wallet client does not support waitForTransactionReceipt. \" +\n \"Please use a viem PublicClient or WalletClient with public actions.\",\n );\n }\n\n try {\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: this.config.confirmationTimeout,\n });\n\n if (receipt.status !== \"success\") {\n throw new Error(`Transaction failed with status: ${receipt.status}`);\n }\n\n return receipt;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to confirm transaction: ${error.message}`);\n }\n throw new Error(\"Failed to confirm transaction: Unknown error\");\n }\n }\n\n /**\n * Get the network name\n */\n get network(): string {\n return this.config.network;\n }\n\n /**\n * Get the facilitator URL\n */\n get facilitatorUrl(): string {\n return this.config.facilitatorUrl;\n }\n\n /**\n * Get the wallet client\n */\n get wallet() {\n return this.config.wallet;\n }\n}\n","/**\n * React hook for creating X402Client instance\n *\n * This hook automatically creates an X402Client instance using wagmi's\n * wallet client and chain information.\n */\n\nimport { useMemo } from \"react\";\nimport {\n useWalletClient,\n useAccount,\n useChainId,\n WagmiProviderNotFoundError,\n} from \"wagmi\";\nimport { publicActions } from \"viem\";\nimport { X402Client } from \"../client.js\";\nimport type { X402ClientConfig } from \"../types.js\";\n\n/**\n * Partial configuration for useX402Client hook\n * (wallet, network, chainId are auto-detected from wagmi)\n */\nexport type UseX402ClientConfig = Partial<Omit<X402ClientConfig, \"wallet\" | \"network\">> & {\n /** Optional: Facilitator URL (default: https://facilitator.x402x.dev/) */\n facilitatorUrl?: string;\n /** Optional: Override network name (auto-detected from chain if not provided) */\n network?: string;\n};\n\n/**\n * Map chainId to network name\n */\nconst CHAIN_ID_TO_NETWORK: Record<number, string> = {\n 84532: \"base-sepolia\",\n 8453: \"base\",\n 196: \"x-layer\",\n 1952: \"x-layer-testnet\",\n};\n\n/**\n * React hook for X402Client\n *\n * Automatically creates an X402Client instance using the connected wallet\n * from wagmi. Returns null if wallet is not connected.\n *\n * @param config - Client configuration (facilitatorUrl is optional, defaults to https://facilitator.x402x.dev/)\n * @returns X402Client instance or null if wallet not connected\n *\n * @example\n * ```typescript\n * import { useX402Client } from '@x402x/client';\n *\n * function MyComponent() {\n * // Use default facilitator\n * const client = useX402Client();\n *\n * // Or specify custom facilitator\n * const client = useX402Client({\n * facilitatorUrl: 'https://custom-facilitator.example.com'\n * });\n *\n * if (!client) {\n * return <div>Please connect your wallet</div>;\n * }\n *\n * const handlePay = async () => {\n * const result = await client.execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * };\n *\n * return <button onClick={handlePay}>Pay</button>;\n * }\n * ```\n */\nexport function useX402Client(config?: UseX402ClientConfig): X402Client | null {\n // First, try to get wagmi hooks outside of useMemo to catch provider errors early\n let walletClient: any;\n let isConnected: boolean;\n let chainId: number;\n\n try {\n const walletClientResult = useWalletClient();\n const accountResult = useAccount();\n const chainIdResult = useChainId();\n\n walletClient = walletClientResult.data;\n isConnected = accountResult.isConnected;\n chainId = chainIdResult;\n } catch (error) {\n // If wagmi provider context is missing (e.g., during early render), return null quietly\n if (\n error instanceof WagmiProviderNotFoundError ||\n (error as any)?.name === \"WagmiProviderNotFoundError\" ||\n error instanceof Error && error.message.includes(\"useConfig\") && error.message.includes(\"WagmiProvider\")\n ) {\n return null;\n }\n\n console.warn(\"[x402x] Unable to access wagmi provider:\", error);\n return null;\n }\n\n return useMemo(() => {\n if (!isConnected || !walletClient) {\n return null;\n }\n\n // Determine network name\n const network = config?.network || CHAIN_ID_TO_NETWORK[chainId];\n if (!network) {\n console.warn(\n `[x402x] Unknown chainId ${chainId}. Please provide network name explicitly in config.`,\n );\n return null;\n }\n\n try {\n // Extend wallet client with public actions (required for waitForTransactionReceipt)\n const extendedWallet = walletClient.extend(publicActions);\n\n return new X402Client({\n wallet: extendedWallet,\n network,\n facilitatorUrl: config?.facilitatorUrl,\n networkConfig: config?.networkConfig,\n timeout: config?.timeout,\n confirmationTimeout: config?.confirmationTimeout,\n });\n } catch (error) {\n console.error(\"[x402x] Failed to create X402Client:\", error);\n return null;\n }\n }, [\n isConnected,\n walletClient,\n chainId,\n config?.network,\n config?.facilitatorUrl,\n config?.networkConfig,\n config?.timeout,\n config?.confirmationTimeout,\n ]);\n}\n","/**\n * React hook for executing settlements\n *\n * This hook provides a simple interface for executing settlements with\n * automatic state management (status, error, result).\n */\n\nimport { useState, useCallback } from \"react\";\nimport { useX402Client, type UseX402ClientConfig } from \"./useX402Client.js\";\nimport type { ExecuteParams, ExecuteResult, ExecuteStatus } from \"../types.js\";\n\n/**\n * Return type for useExecute hook\n */\nexport interface UseExecuteReturn {\n /** Execute a settlement */\n execute: (params: ExecuteParams, waitForConfirmation?: boolean) => Promise<ExecuteResult>;\n /** Current execution status */\n status: ExecuteStatus;\n /** Error if execution failed */\n error: Error | null;\n /** Result if execution succeeded */\n result: ExecuteResult | null;\n /** Reset state */\n reset: () => void;\n /** Whether currently executing */\n isExecuting: boolean;\n /** Whether execution succeeded */\n isSuccess: boolean;\n /** Whether execution failed */\n isError: boolean;\n}\n\n/**\n * React hook for executing settlements\n *\n * Provides a simple interface for executing settlements with automatic\n * state management. Automatically uses the connected wallet from wagmi.\n *\n * @param config - Optional client configuration (if not using global client)\n * @returns Execute function and state\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n * import { TransferHook } from '@x402x/core';\n *\n * function PayButton() {\n * const { execute, status, error, result } = useExecute({\n * facilitatorUrl: 'https://facilitator.x402x.dev'\n * });\n *\n * const handlePay = async () => {\n * try {\n * // Simple transfer (hook and hookData are optional)\n * const result = await execute({\n * amount: '1000000',\n * payTo: '0x...'\n * });\n * console.log('Success:', result.txHash);\n * } catch (err) {\n * console.error('Failed:', err);\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * {status === 'idle' ? 'Pay' : 'Processing...'}\n * </button>\n * {status === 'success' && <div>✅ Success! TX: {result.txHash}</div>}\n * {status === 'error' && <div>❌ Error: {error.message}</div>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecute(config?: UseX402ClientConfig): UseExecuteReturn {\n const client = useX402Client(config);\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n setStatus(\"idle\");\n setError(null);\n setResult(null);\n }, []);\n\n return {\n execute,\n status,\n error,\n result,\n reset,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n\n/**\n * Alternative hook that doesn't require config (uses default client from context)\n *\n * @example\n * ```typescript\n * import { useExecute } from '@x402x/client';\n *\n * function PayButton({ facilitatorUrl }: { facilitatorUrl: string }) {\n * const { execute, status, error } = useExecute({ facilitatorUrl });\n *\n * const handlePay = async () => {\n * await execute({\n * hook: '0x...',\n * hookData: '0x...',\n * amount: '1000000',\n * recipient: '0x...'\n * });\n * };\n *\n * return (\n * <button onClick={handlePay} disabled={status !== 'idle'}>\n * Pay\n * </button>\n * );\n * }\n * ```\n */\nexport function useExecuteWithClient(\n client: ReturnType<typeof useX402Client>,\n): Omit<UseExecuteReturn, \"reset\"> {\n const [status, setStatus] = useState<ExecuteStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<ExecuteResult | null>(null);\n\n const execute = useCallback(\n async (params: ExecuteParams, waitForConfirmation: boolean = true): Promise<ExecuteResult> => {\n if (!client) {\n throw new Error(\"X402Client not available. Please connect your wallet.\");\n }\n\n setStatus(\"preparing\");\n setError(null);\n setResult(null);\n\n try {\n const executeResult = await client.execute(params, waitForConfirmation);\n setStatus(\"success\");\n setResult(executeResult);\n return executeResult;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(\"Unknown error\");\n setStatus(\"error\");\n setError(error);\n throw error;\n }\n },\n [client],\n );\n\n return {\n execute,\n status,\n error,\n result,\n isExecuting: [\"preparing\", \"signing\", \"submitting\", \"confirming\"].includes(status),\n isSuccess: status === \"success\",\n isError: status === \"error\",\n };\n}\n"]}
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.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d,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x402x/client",
3
- "version": "0.3.0",
3
+ "version": "2.1.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",
@@ -42,9 +42,8 @@
42
42
  "author": "Nuwa Protocol",
43
43
  "license": "Apache-2.0",
44
44
  "dependencies": {
45
- "@x402x/core": "workspace:*",
46
- "viem": "2.40.3",
47
- "x402": "npm:@x402x/x402@^0.6.6-patch.3"
45
+ "@x402x/extensions": "workspace:*",
46
+ "viem": "2.40.3"
48
47
  },
49
48
  "peerDependencies": {
50
49
  "react": "^18.0.0",