@wtflabs/x402-fetch 0.0.1-beta.0 → 0.0.1-beta.2

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.
@@ -1,8 +1,8 @@
1
- import { Signer, MultiNetworkSigner, X402Config } from 'x402/types';
2
- export { ConnectedClient, EvmChainConfig, MultiNetworkSigner, Signer, X402Config, createConnectedClient, createSigner, withChain } from 'x402/types';
3
- import { PaymentRequirementsSelector } from 'x402/client';
4
- export { PaymentRequirementsSelector } from 'x402/client';
5
- export { decodeXPaymentResponse } from 'x402/shared';
1
+ import { Signer, MultiNetworkSigner, X402Config } from '@wtflabs/x402/types';
2
+ export { ConnectedClient, EvmChainConfig, MultiNetworkSigner, Signer, X402Config, createConnectedClient, createSigner, withChain } from '@wtflabs/x402/types';
3
+ import { PaymentRequirementsSelector } from '@wtflabs/x402/client';
4
+ export { PaymentRequirementsSelector } from '@wtflabs/x402/client';
5
+ export { decodeXPaymentResponse } from '@wtflabs/x402/shared';
6
6
  export { Chain, Hex } from 'viem';
7
7
 
8
8
  /**
package/dist/cjs/index.js CHANGED
@@ -27,11 +27,11 @@ __export(src_exports, {
27
27
  wrapFetchWithPayment: () => wrapFetchWithPayment
28
28
  });
29
29
  module.exports = __toCommonJS(src_exports);
30
- var import_types = require("x402/types");
31
- var import_client = require("x402/client");
32
- var import_schemes = require("x402/schemes");
33
- var import_shared = require("x402/shared");
34
- var import_types2 = require("x402/types");
30
+ var import_types = require("@wtflabs/x402/types");
31
+ var import_client = require("@wtflabs/x402/client");
32
+ var import_schemes = require("@wtflabs/x402/schemes");
33
+ var import_shared = require("@wtflabs/x402/shared");
34
+ var import_types2 = require("@wtflabs/x402/types");
35
35
  function wrapFetchWithPayment(fetch, walletClient, maxValue = BigInt(0.1 * 10 ** 6), paymentRequirementsSelector = import_client.selectPaymentRequirements, config) {
36
36
  return async (input, init) => {
37
37
  var _a;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import {\n ChainIdToNetwork,\n PaymentRequirementsSchema,\n Signer,\n evm,\n MultiNetworkSigner,\n isMultiNetworkSigner,\n isSvmSignerWallet,\n Network,\n X402Config,\n} from \"x402/types\";\nimport {\n createPaymentHeader,\n PaymentRequirementsSelector,\n selectPaymentRequirements,\n} from \"x402/client\";\nimport { exact } from \"x402/schemes\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending a payment header. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Verify the payment amount is within the allowed maximum\n * 4. Create a payment header using the provided wallet client\n * 5. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param walletClient - The wallet client used to sign payment messages\n * @param maxValue - The maximum allowed payment amount in base units (defaults to 0.1 USDC)\n * @param paymentRequirementsSelector - A function that selects the payment requirements from the response\n * @param config - Optional configuration for X402 operations (e.g., custom RPC URLs)\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * const wallet = new SignerWallet(...);\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n *\n * // With custom RPC configuration\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet, undefined, undefined, {\n * svmConfig: { rpcUrl: \"http://localhost:8899\" }\n * });\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If the payment amount exceeds the maximum allowed value\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n walletClient: Signer | MultiNetworkSigner,\n maxValue: bigint = BigInt(0.1 * 10 ** 6), // Default to 0.10 USDC\n paymentRequirementsSelector: PaymentRequirementsSelector = selectPaymentRequirements,\n config?: X402Config,\n) {\n return async (input: RequestInfo, init?: RequestInit) => {\n const response = await fetch(input, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const { x402Version, accepts } = (await response.json()) as {\n x402Version: number;\n accepts: unknown[];\n };\n const parsedPaymentRequirements = accepts.map(x => PaymentRequirementsSchema.parse(x));\n\n const network = isMultiNetworkSigner(walletClient)\n ? undefined\n : evm.isSignerWallet(walletClient as typeof evm.EvmSigner)\n ? ChainIdToNetwork[(walletClient as typeof evm.EvmSigner).chain?.id]\n : isSvmSignerWallet(walletClient)\n ? ([\"solana\", \"solana-devnet\"] as Network[])\n : undefined;\n\n const selectedPaymentRequirements = paymentRequirementsSelector(\n parsedPaymentRequirements,\n network,\n \"exact\",\n );\n\n if (BigInt(selectedPaymentRequirements.maxAmountRequired) > maxValue) {\n throw new Error(\"Payment amount exceeds maximum allowed\");\n }\n\n // 获取支付类型,默认为 eip3009\n const paymentType = selectedPaymentRequirements.paymentType || \"eip3009\";\n\n // 根据支付类型创建支付头\n let paymentHeader: string;\n\n // 仅对 EVM 网络支持 permit 和 permit2\n const isEvmNetwork = network && ![\"solana\", \"solana-devnet\"].includes(network[0]);\n\n if (paymentType === \"permit\" && isEvmNetwork) {\n // 使用 EIP-2612 Permit\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"permit2\" && isEvmNetwork) {\n // 使用 Permit2\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit2 authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit2.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"eip3009\" || !paymentType) {\n // 默认使用 EIP-3009(统一的 createPaymentHeader)\n paymentHeader = await createPaymentHeader(\n walletClient,\n x402Version,\n selectedPaymentRequirements,\n config,\n );\n } else {\n throw new Error(`Unsupported payment type: ${paymentType}`);\n }\n\n if (!init) {\n throw new Error(\"Missing fetch request configuration\");\n }\n\n if ((init as { __is402Retry?: boolean }).__is402Retry) {\n throw new Error(\"Payment already attempted\");\n }\n\n const newInit = {\n ...init,\n headers: {\n ...(init.headers || {}),\n \"X-PAYMENT\": paymentHeader,\n \"Access-Control-Expose-Headers\": \"X-PAYMENT-RESPONSE\",\n },\n __is402Retry: true,\n };\n\n const secondResponse = await fetch(input, newInit);\n return secondResponse;\n };\n}\n\nexport { decodeXPaymentResponse } from \"x402/shared\";\nexport {\n createSigner,\n createConnectedClient,\n withChain,\n type Signer,\n type ConnectedClient,\n type MultiNetworkSigner,\n type X402Config,\n type EvmChainConfig\n} from \"x402/types\";\nexport { type PaymentRequirementsSelector } from \"x402/client\";\nexport type { Hex, Chain } from \"viem\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAUO;AACP,oBAIO;AACP,qBAAsB;AA6ItB,oBAAuC;AACvC,IAAAA,gBASO;AAhHA,SAAS,qBACd,OACA,cACA,WAAmB,OAAO,MAAM,MAAM,CAAC,GACvC,8BAA2D,yCAC3D,QACA;AACA,SAAO,OAAO,OAAoB,SAAuB;AA9D3D;AA+DI,UAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AAExC,QAAI,SAAS,WAAW,KAAK;AAC3B,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,aAAa,QAAQ,IAAK,MAAM,SAAS,KAAK;AAItD,UAAM,4BAA4B,QAAQ,IAAI,OAAK,uCAA0B,MAAM,CAAC,CAAC;AAErF,UAAM,cAAU,mCAAqB,YAAY,IAC7C,SACA,iBAAI,eAAe,YAAoC,IACrD,+BAAkB,kBAAsC,UAAtC,mBAA6C,EAAE,QACjE,gCAAkB,YAAY,IAC3B,CAAC,UAAU,eAAe,IAC3B;AAER,UA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OAAO;AACjD,WAAO;AAAA,EACT;AACF;","names":["import_types"]}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import {\n ChainIdToNetwork,\n PaymentRequirementsSchema,\n Signer,\n evm,\n MultiNetworkSigner,\n isMultiNetworkSigner,\n isSvmSignerWallet,\n Network,\n X402Config,\n} from \"@wtflabs/x402/types\";\nimport {\n createPaymentHeader,\n PaymentRequirementsSelector,\n selectPaymentRequirements,\n} from \"@wtflabs/x402/client\";\nimport { exact } from \"@wtflabs/x402/schemes\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending a payment header. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Verify the payment amount is within the allowed maximum\n * 4. Create a payment header using the provided wallet client\n * 5. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param walletClient - The wallet client used to sign payment messages\n * @param maxValue - The maximum allowed payment amount in base units (defaults to 0.1 USDC)\n * @param paymentRequirementsSelector - A function that selects the payment requirements from the response\n * @param config - Optional configuration for X402 operations (e.g., custom RPC URLs)\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * const wallet = new SignerWallet(...);\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n *\n * // With custom RPC configuration\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet, undefined, undefined, {\n * svmConfig: { rpcUrl: \"http://localhost:8899\" }\n * });\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If the payment amount exceeds the maximum allowed value\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n walletClient: Signer | MultiNetworkSigner,\n maxValue: bigint = BigInt(0.1 * 10 ** 6), // Default to 0.10 USDC\n paymentRequirementsSelector: PaymentRequirementsSelector = selectPaymentRequirements,\n config?: X402Config,\n) {\n return async (input: RequestInfo, init?: RequestInit) => {\n const response = await fetch(input, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const { x402Version, accepts } = (await response.json()) as {\n x402Version: number;\n accepts: unknown[];\n };\n const parsedPaymentRequirements = accepts.map(x => PaymentRequirementsSchema.parse(x));\n\n const network = isMultiNetworkSigner(walletClient)\n ? undefined\n : evm.isSignerWallet(walletClient as typeof evm.EvmSigner)\n ? ChainIdToNetwork[(walletClient as typeof evm.EvmSigner).chain?.id]\n : isSvmSignerWallet(walletClient)\n ? ([\"solana\", \"solana-devnet\"] as Network[])\n : undefined;\n\n const selectedPaymentRequirements = paymentRequirementsSelector(\n parsedPaymentRequirements,\n network,\n \"exact\",\n );\n\n if (BigInt(selectedPaymentRequirements.maxAmountRequired) > maxValue) {\n throw new Error(\"Payment amount exceeds maximum allowed\");\n }\n\n // 获取支付类型,默认为 eip3009\n const paymentType = selectedPaymentRequirements.paymentType || \"eip3009\";\n\n // 根据支付类型创建支付头\n let paymentHeader: string;\n\n // 仅对 EVM 网络支持 permit 和 permit2\n const isEvmNetwork = network && ![\"solana\", \"solana-devnet\"].includes(network[0]);\n\n if (paymentType === \"permit\" && isEvmNetwork) {\n // 使用 EIP-2612 Permit\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"permit2\" && isEvmNetwork) {\n // 使用 Permit2\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit2 authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit2.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"eip3009\" || !paymentType) {\n // 默认使用 EIP-3009(统一的 createPaymentHeader)\n paymentHeader = await createPaymentHeader(\n walletClient,\n x402Version,\n selectedPaymentRequirements,\n config,\n );\n } else {\n throw new Error(`Unsupported payment type: ${paymentType}`);\n }\n\n if (!init) {\n throw new Error(\"Missing fetch request configuration\");\n }\n\n if ((init as { __is402Retry?: boolean }).__is402Retry) {\n throw new Error(\"Payment already attempted\");\n }\n\n const newInit = {\n ...init,\n headers: {\n ...(init.headers || {}),\n \"X-PAYMENT\": paymentHeader,\n \"Access-Control-Expose-Headers\": \"X-PAYMENT-RESPONSE\",\n },\n __is402Retry: true,\n };\n\n const secondResponse = await fetch(input, newInit);\n return secondResponse;\n };\n}\n\nexport { decodeXPaymentResponse } from \"@wtflabs/x402/shared\";\nexport {\n createSigner,\n createConnectedClient,\n withChain,\n type Signer,\n type ConnectedClient,\n type MultiNetworkSigner,\n type X402Config,\n type EvmChainConfig\n} from \"@wtflabs/x402/types\";\nexport { type PaymentRequirementsSelector } from \"@wtflabs/x402/client\";\nexport type { Hex, Chain } from \"viem\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAUO;AACP,oBAIO;AACP,qBAAsB;AA6ItB,oBAAuC;AACvC,IAAAA,gBASO;AAhHA,SAAS,qBACd,OACA,cACA,WAAmB,OAAO,MAAM,MAAM,CAAC,GACvC,8BAA2D,yCAC3D,QACA;AACA,SAAO,OAAO,OAAoB,SAAuB;AA9D3D;AA+DI,UAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AAExC,QAAI,SAAS,WAAW,KAAK;AAC3B,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,aAAa,QAAQ,IAAK,MAAM,SAAS,KAAK;AAItD,UAAM,4BAA4B,QAAQ,IAAI,OAAK,uCAA0B,MAAM,CAAC,CAAC;AAErF,UAAM,cAAU,mCAAqB,YAAY,IAC7C,SAC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AAW,CAAC;AAAA,QACrB,aAAa;AAAA,QACb,iCAAiC;AAAA,MACnC;AAAA,MACA,cAAc;AAAA,IAChB;AAEA,UAAM,iBAAiB,MAAM,MAAM,OAAO,OAAO;AACjD,WAAO;AAAA,EACT;AACF;","names":["import_types"]}
@@ -1,8 +1,8 @@
1
- import { Signer, MultiNetworkSigner, X402Config } from 'x402/types';
2
- export { ConnectedClient, EvmChainConfig, MultiNetworkSigner, Signer, X402Config, createConnectedClient, createSigner, withChain } from 'x402/types';
3
- import { PaymentRequirementsSelector } from 'x402/client';
4
- export { PaymentRequirementsSelector } from 'x402/client';
5
- export { decodeXPaymentResponse } from 'x402/shared';
1
+ import { Signer, MultiNetworkSigner, X402Config } from '@wtflabs/x402/types';
2
+ export { ConnectedClient, EvmChainConfig, MultiNetworkSigner, Signer, X402Config, createConnectedClient, createSigner, withChain } from '@wtflabs/x402/types';
3
+ import { PaymentRequirementsSelector } from '@wtflabs/x402/client';
4
+ export { PaymentRequirementsSelector } from '@wtflabs/x402/client';
5
+ export { decodeXPaymentResponse } from '@wtflabs/x402/shared';
6
6
  export { Chain, Hex } from 'viem';
7
7
 
8
8
  /**
@@ -5,18 +5,18 @@ import {
5
5
  evm,
6
6
  isMultiNetworkSigner,
7
7
  isSvmSignerWallet
8
- } from "x402/types";
8
+ } from "@wtflabs/x402/types";
9
9
  import {
10
10
  createPaymentHeader,
11
11
  selectPaymentRequirements
12
- } from "x402/client";
13
- import { exact } from "x402/schemes";
14
- import { decodeXPaymentResponse } from "x402/shared";
12
+ } from "@wtflabs/x402/client";
13
+ import { exact } from "@wtflabs/x402/schemes";
14
+ import { decodeXPaymentResponse } from "@wtflabs/x402/shared";
15
15
  import {
16
16
  createSigner,
17
17
  createConnectedClient,
18
18
  withChain
19
- } from "x402/types";
19
+ } from "@wtflabs/x402/types";
20
20
  function wrapFetchWithPayment(fetch, walletClient, maxValue = BigInt(0.1 * 10 ** 6), paymentRequirementsSelector = selectPaymentRequirements, config) {
21
21
  return async (input, init) => {
22
22
  var _a;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import {\n ChainIdToNetwork,\n PaymentRequirementsSchema,\n Signer,\n evm,\n MultiNetworkSigner,\n isMultiNetworkSigner,\n isSvmSignerWallet,\n Network,\n X402Config,\n} from \"x402/types\";\nimport {\n createPaymentHeader,\n PaymentRequirementsSelector,\n selectPaymentRequirements,\n} from \"x402/client\";\nimport { exact } from \"x402/schemes\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending a payment header. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Verify the payment amount is within the allowed maximum\n * 4. Create a payment header using the provided wallet client\n * 5. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param walletClient - The wallet client used to sign payment messages\n * @param maxValue - The maximum allowed payment amount in base units (defaults to 0.1 USDC)\n * @param paymentRequirementsSelector - A function that selects the payment requirements from the response\n * @param config - Optional configuration for X402 operations (e.g., custom RPC URLs)\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * const wallet = new SignerWallet(...);\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n *\n * // With custom RPC configuration\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet, undefined, undefined, {\n * svmConfig: { rpcUrl: \"http://localhost:8899\" }\n * });\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If the payment amount exceeds the maximum allowed value\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n walletClient: Signer | MultiNetworkSigner,\n maxValue: bigint = BigInt(0.1 * 10 ** 6), // Default to 0.10 USDC\n paymentRequirementsSelector: PaymentRequirementsSelector = selectPaymentRequirements,\n config?: X402Config,\n) {\n return async (input: RequestInfo, init?: RequestInit) => {\n const response = await fetch(input, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const { x402Version, accepts } = (await response.json()) as {\n x402Version: number;\n accepts: unknown[];\n };\n const parsedPaymentRequirements = accepts.map(x => PaymentRequirementsSchema.parse(x));\n\n const network = isMultiNetworkSigner(walletClient)\n ? undefined\n : evm.isSignerWallet(walletClient as typeof evm.EvmSigner)\n ? ChainIdToNetwork[(walletClient as typeof evm.EvmSigner).chain?.id]\n : isSvmSignerWallet(walletClient)\n ? ([\"solana\", \"solana-devnet\"] as Network[])\n : undefined;\n\n const selectedPaymentRequirements = paymentRequirementsSelector(\n parsedPaymentRequirements,\n network,\n \"exact\",\n );\n\n if (BigInt(selectedPaymentRequirements.maxAmountRequired) > maxValue) {\n throw new Error(\"Payment amount exceeds maximum allowed\");\n }\n\n // 获取支付类型,默认为 eip3009\n const paymentType = selectedPaymentRequirements.paymentType || \"eip3009\";\n\n // 根据支付类型创建支付头\n let paymentHeader: string;\n\n // 仅对 EVM 网络支持 permit 和 permit2\n const isEvmNetwork = network && ![\"solana\", \"solana-devnet\"].includes(network[0]);\n\n if (paymentType === \"permit\" && isEvmNetwork) {\n // 使用 EIP-2612 Permit\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"permit2\" && isEvmNetwork) {\n // 使用 Permit2\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit2 authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit2.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"eip3009\" || !paymentType) {\n // 默认使用 EIP-3009(统一的 createPaymentHeader)\n paymentHeader = await createPaymentHeader(\n walletClient,\n x402Version,\n selectedPaymentRequirements,\n config,\n );\n } else {\n throw new Error(`Unsupported payment type: ${paymentType}`);\n }\n\n if (!init) {\n throw new Error(\"Missing fetch request configuration\");\n }\n\n if ((init as { __is402Retry?: boolean }).__is402Retry) {\n throw new Error(\"Payment already attempted\");\n }\n\n const newInit = {\n ...init,\n headers: {\n ...(init.headers || {}),\n \"X-PAYMENT\": paymentHeader,\n \"Access-Control-Expose-Headers\": \"X-PAYMENT-RESPONSE\",\n },\n __is402Retry: true,\n };\n\n const secondResponse = await fetch(input, newInit);\n return secondResponse;\n };\n}\n\nexport { decodeXPaymentResponse } from \"x402/shared\";\nexport {\n createSigner,\n createConnectedClient,\n withChain,\n type Signer,\n type ConnectedClient,\n type MultiNetworkSigner,\n type X402Config,\n type EvmChainConfig\n} from \"x402/types\";\nexport { type PaymentRequirementsSelector } from \"x402/client\";\nexport type { Hex, Chain } from \"viem\";\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,aAAa;AA6ItB,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AAhHA,SAAS,qBACd,OACA,cACA,WAAmB,OAAO,MAAM,MAAM,CAAC,GACvC,8BAA2D,2BAC3D,QACA;AACA,SAAO,OAAO,OAAoB,SAAuB;AA9D3D;AA+DI,UAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AAExC,QAAI,SAAS,WAAW,KAAK;AAC3B,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,aAAa,QAAQ,IAAK,MAAM,SAAS,KAAK;AAItD,UAAM,4BAA4B,QAAQ,IAAI,OAAK,0BAA0B,MAAM,CAAC,CAAC;AAErF,UAAM,UAAU,qBAAqB,YAAY,IAC7C,SACA,IAAI,e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,QACrB,aAAa;AAAA,QACb,iCAAiC;AAAA,MACnC;AAAA,MACA,cAAc;AAAA,IAChB;AAEA,UAAM,iBAAiB,MAAM,MAAM,OAAO,OAAO;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import {\n ChainIdToNetwork,\n PaymentRequirementsSchema,\n Signer,\n evm,\n MultiNetworkSigner,\n isMultiNetworkSigner,\n isSvmSignerWallet,\n Network,\n X402Config,\n} from \"@wtflabs/x402/types\";\nimport {\n createPaymentHeader,\n PaymentRequirementsSelector,\n selectPaymentRequirements,\n} from \"@wtflabs/x402/client\";\nimport { exact } from \"@wtflabs/x402/schemes\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending a payment header. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Verify the payment amount is within the allowed maximum\n * 4. Create a payment header using the provided wallet client\n * 5. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param walletClient - The wallet client used to sign payment messages\n * @param maxValue - The maximum allowed payment amount in base units (defaults to 0.1 USDC)\n * @param paymentRequirementsSelector - A function that selects the payment requirements from the response\n * @param config - Optional configuration for X402 operations (e.g., custom RPC URLs)\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * const wallet = new SignerWallet(...);\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n *\n * // With custom RPC configuration\n * const fetchWithPay = wrapFetchWithPayment(fetch, wallet, undefined, undefined, {\n * svmConfig: { rpcUrl: \"http://localhost:8899\" }\n * });\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If the payment amount exceeds the maximum allowed value\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n walletClient: Signer | MultiNetworkSigner,\n maxValue: bigint = BigInt(0.1 * 10 ** 6), // Default to 0.10 USDC\n paymentRequirementsSelector: PaymentRequirementsSelector = selectPaymentRequirements,\n config?: X402Config,\n) {\n return async (input: RequestInfo, init?: RequestInit) => {\n const response = await fetch(input, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const { x402Version, accepts } = (await response.json()) as {\n x402Version: number;\n accepts: unknown[];\n };\n const parsedPaymentRequirements = accepts.map(x => PaymentRequirementsSchema.parse(x));\n\n const network = isMultiNetworkSigner(walletClient)\n ? undefined\n : evm.isSignerWallet(walletClient as typeof evm.EvmSigner)\n ? ChainIdToNetwork[(walletClient as typeof evm.EvmSigner).chain?.id]\n : isSvmSignerWallet(walletClient)\n ? ([\"solana\", \"solana-devnet\"] as Network[])\n : undefined;\n\n const selectedPaymentRequirements = paymentRequirementsSelector(\n parsedPaymentRequirements,\n network,\n \"exact\",\n );\n\n if (BigInt(selectedPaymentRequirements.maxAmountRequired) > maxValue) {\n throw new Error(\"Payment amount exceeds maximum allowed\");\n }\n\n // 获取支付类型,默认为 eip3009\n const paymentType = selectedPaymentRequirements.paymentType || \"eip3009\";\n\n // 根据支付类型创建支付头\n let paymentHeader: string;\n\n // 仅对 EVM 网络支持 permit 和 permit2\n const isEvmNetwork = network && ![\"solana\", \"solana-devnet\"].includes(network[0]);\n\n if (paymentType === \"permit\" && isEvmNetwork) {\n // 使用 EIP-2612 Permit\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"permit2\" && isEvmNetwork) {\n // 使用 Permit2\n if (!evm.isSignerWallet(walletClient as typeof evm.EvmSigner)) {\n throw new Error(\"Permit2 authorization requires an EVM signer wallet\");\n }\n paymentHeader = await exact.evm.permit2.createPaymentHeader(\n walletClient as typeof evm.EvmSigner,\n x402Version,\n selectedPaymentRequirements,\n );\n } else if (paymentType === \"eip3009\" || !paymentType) {\n // 默认使用 EIP-3009(统一的 createPaymentHeader)\n paymentHeader = await createPaymentHeader(\n walletClient,\n x402Version,\n selectedPaymentRequirements,\n config,\n );\n } else {\n throw new Error(`Unsupported payment type: ${paymentType}`);\n }\n\n if (!init) {\n throw new Error(\"Missing fetch request configuration\");\n }\n\n if ((init as { __is402Retry?: boolean }).__is402Retry) {\n throw new Error(\"Payment already attempted\");\n }\n\n const newInit = {\n ...init,\n headers: {\n ...(init.headers || {}),\n \"X-PAYMENT\": paymentHeader,\n \"Access-Control-Expose-Headers\": \"X-PAYMENT-RESPONSE\",\n },\n __is402Retry: true,\n };\n\n const secondResponse = await fetch(input, newInit);\n return secondResponse;\n };\n}\n\nexport { decodeXPaymentResponse } from \"@wtflabs/x402/shared\";\nexport {\n createSigner,\n createConnectedClient,\n withChain,\n type Signer,\n type ConnectedClient,\n type MultiNetworkSigner,\n type X402Config,\n type EvmChainConfig\n} from \"@wtflabs/x402/types\";\nexport { type PaymentRequirementsSelector } from \"@wtflabs/x402/client\";\nexport type { Hex, Chain } from \"viem\";\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,aAAa;AA6ItB,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AAhHA,SAAS,qBACd,OACA,cACA,WAAmB,OAAO,MAAM,MAAM,CAAC,GACvC,8BAA2D,2BAC3D,QACA;AACA,SAAO,OAAO,OAAoB,SAAuB;AA9D3D;AA+DI,UAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AAExC,QAAI,SAAS,WAAW,KAAK;AAC3B,aAAO;AAAA,IACT;AAEA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IACvD;AAEA,QAAK,KAAoC,cAAc;AACrD,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AAEA,UAAM,UAAU;AAAA,MACd,GAAG;AAAA,MACH,SAAS;AAAA,QACP,GAAI,KAAK,WAAW,CAAC;AAAA,QACrB,aAAa;AAAA,QACb,iCAAiC;AAAA,MACnC;AAAA,MACA,cAAc;AAAA,IAChB;AAEA,UAAM,iBAAiB,MAAM,MAAM,OAAO,OAAO;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtflabs/x402-fetch",
3
- "version": "0.0.1-beta.0",
3
+ "version": "0.0.1-beta.2",
4
4
  "main": "./dist/cjs/index.js",
5
5
  "module": "./dist/esm/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -40,7 +40,7 @@
40
40
  "dependencies": {
41
41
  "viem": "^2.21.26",
42
42
  "zod": "^3.24.2",
43
- "x402": "workspace:^"
43
+ "@wtflabs/x402": "workspace:^"
44
44
  },
45
45
  "exports": {
46
46
  ".": {