@x402/axios 0.0.1 → 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
@@ -1 +1,197 @@
1
- # @x402/axios
1
+ # x402-axios
2
+
3
+ A utility package that extends Axios to automatically handle 402 Payment Required responses using the x402 payment protocol v2. This package enables seamless integration of payment functionality into your applications when making HTTP requests.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm install @x402/axios
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import axios from "axios";
15
+ import { wrapAxiosWithPaymentFromConfig } from "@x402/axios";
16
+ import { ExactEvmScheme } from "@x402/evm";
17
+ import { privateKeyToAccount } from "viem/accounts";
18
+
19
+ // Create an account
20
+ const account = privateKeyToAccount("0xYourPrivateKey");
21
+
22
+ // Wrap the axios instance with payment handling
23
+ const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
24
+ schemes: [
25
+ {
26
+ network: "eip155:8453", // Base Sepolia
27
+ client: new ExactEvmScheme(account),
28
+ },
29
+ ],
30
+ });
31
+
32
+ // Make a request that may require payment
33
+ const response = await api.get("https://api.example.com/paid-endpoint");
34
+
35
+ const data = response.data;
36
+ ```
37
+
38
+ ## API
39
+
40
+ ### `wrapAxiosWithPayment(axiosInstance, client)`
41
+
42
+ Wraps an Axios instance to handle 402 Payment Required responses automatically.
43
+
44
+ #### Parameters
45
+
46
+ - `axiosInstance`: The Axios instance to wrap (typically from `axios.create()`)
47
+ - `client`: An x402Client instance with registered payment schemes
48
+
49
+ ### `wrapAxiosWithPaymentFromConfig(axiosInstance, config)`
50
+
51
+ Convenience wrapper that creates an x402Client from a configuration object.
52
+
53
+ #### Parameters
54
+
55
+ - `axiosInstance`: The Axios instance to wrap (typically from `axios.create()`)
56
+ - `config`: Configuration object with the following properties:
57
+ - `schemes`: Array of scheme registrations, each containing:
58
+ - `network`: Network identifier (e.g., 'eip155:8453', 'solana:mainnet', 'eip155:*' for wildcards)
59
+ - `client`: The scheme client implementation (e.g., `ExactEvmScheme`, `ExactSvmScheme`)
60
+ - `x402Version`: Optional protocol version (defaults to 2, set to 1 for legacy support)
61
+ - `paymentRequirementsSelector`: Optional function to select payment requirements from multiple options
62
+
63
+ #### Returns
64
+
65
+ A wrapped Axios instance that automatically handles 402 responses by:
66
+ 1. Making the initial request
67
+ 2. If a 402 response is received, parsing the payment requirements
68
+ 3. Creating a payment header using the configured scheme client
69
+ 4. Retrying the request with the payment header
70
+
71
+ ## Examples
72
+
73
+ ### Basic Usage with EVM
74
+
75
+ ```typescript
76
+ import { config } from "dotenv";
77
+ import axios from "axios";
78
+ import { wrapAxiosWithPaymentFromConfig, decodePaymentResponseHeader } from "@x402/axios";
79
+ import { privateKeyToAccount } from "viem/accounts";
80
+ import { ExactEvmScheme } from "@x402/evm";
81
+
82
+ config();
83
+
84
+ const { EVM_PRIVATE_KEY, API_URL } = process.env;
85
+
86
+ const account = privateKeyToAccount(EVM_PRIVATE_KEY as `0x${string}`);
87
+
88
+ const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
89
+ schemes: [
90
+ {
91
+ network: "eip155:*", // Support all EVM chains
92
+ client: new ExactEvmScheme(account),
93
+ },
94
+ ],
95
+ });
96
+
97
+ // Make a request to a paid API endpoint
98
+ api.get(API_URL)
99
+ .then(response => {
100
+ const data = response.data;
101
+
102
+ // Optionally decode the payment response header
103
+ const paymentResponse = response.headers["payment-response"];
104
+ if (paymentResponse) {
105
+ const decoded = decodePaymentResponseHeader(paymentResponse);
106
+ console.log("Payment details:", decoded);
107
+ }
108
+
109
+ console.log("Response data:", data);
110
+ })
111
+ .catch(error => {
112
+ console.error(error);
113
+ });
114
+ ```
115
+
116
+ ### Using Builder Pattern
117
+
118
+ For more control, you can use the builder pattern to register multiple schemes:
119
+
120
+ ```typescript
121
+ import axios from "axios";
122
+ import { wrapAxiosWithPayment, x402Client } from "@x402/axios";
123
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
124
+ import { ExactSvmScheme } from "@x402/svm/exact/client";
125
+ import { privateKeyToAccount } from "viem/accounts";
126
+ import { createKeyPairSignerFromBytes } from "@solana/kit";
127
+ import { base58 } from "@scure/base";
128
+
129
+ // Create signers
130
+ const evmSigner = privateKeyToAccount("0xYourPrivateKey");
131
+ const svmSigner = await createKeyPairSignerFromBytes(base58.decode("YourSvmPrivateKey"));
132
+
133
+ // Build client with multiple schemes
134
+ const client = new x402Client()
135
+ .register("eip155:*", new ExactEvmScheme(evmSigner))
136
+ .register("solana:*", new ExactSvmScheme(svmSigner));
137
+
138
+ // Wrap axios with the client
139
+ const api = wrapAxiosWithPayment(axios.create(), client);
140
+ ```
141
+
142
+ ### Multi-Chain Support
143
+
144
+ ```typescript
145
+ import axios from "axios";
146
+ import { wrapAxiosWithPaymentFromConfig } from "@x402/axios";
147
+ import { ExactEvmScheme } from "@x402/evm";
148
+ import { ExactSvmScheme } from "@x402/svm";
149
+
150
+ const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
151
+ schemes: [
152
+ // EVM chains
153
+ {
154
+ network: "eip155:8453", // Base Sepolia
155
+ client: new ExactEvmScheme(evmAccount),
156
+ },
157
+ // SVM chains
158
+ {
159
+ network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", // Solana devnet
160
+ client: new ExactSvmScheme(svmSigner),
161
+ },
162
+ ],
163
+ });
164
+ ```
165
+
166
+ ### Custom Payment Requirements Selector
167
+
168
+ ```typescript
169
+ import axios from "axios";
170
+ import { wrapAxiosWithPaymentFromConfig, type SelectPaymentRequirements } from "@x402/axios";
171
+ import { ExactEvmScheme } from "@x402/evm";
172
+
173
+ // Custom selector that prefers the cheapest option
174
+ const selectCheapestOption: SelectPaymentRequirements = (version, accepts) => {
175
+ if (!accepts || accepts.length === 0) {
176
+ throw new Error("No payment options available");
177
+ }
178
+
179
+ // Sort by value and return the cheapest
180
+ const sorted = [...accepts].sort((a, b) =>
181
+ BigInt(a.value) - BigInt(b.value)
182
+ );
183
+
184
+ return sorted[0];
185
+ };
186
+
187
+ const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
188
+ schemes: [
189
+ {
190
+ network: "eip155:8453",
191
+ client: new ExactEvmScheme(account),
192
+ },
193
+ ],
194
+ paymentRequirementsSelector: selectCheapestOption,
195
+ });
196
+ ```
197
+
@@ -0,0 +1,71 @@
1
+ import { x402Client, x402ClientConfig } from '@x402/core/client';
2
+ export { PaymentPolicy, SchemeRegistration, SelectPaymentRequirements, x402Client, x402ClientConfig, x402HTTPClient } from '@x402/core/client';
3
+ import { AxiosInstance } from 'axios';
4
+ export { decodePaymentResponseHeader } from '@x402/core/http';
5
+ export { Network, PaymentPayload, PaymentRequired, PaymentRequirements, SchemeNetworkClient } from '@x402/core/types';
6
+
7
+ /**
8
+ * Wraps an Axios instance with x402 payment handling.
9
+ *
10
+ * This function adds an interceptor to automatically handle 402 Payment Required responses
11
+ * by creating and sending payment headers. It will:
12
+ * 1. Intercept 402 responses
13
+ * 2. Parse the payment requirements
14
+ * 3. Create a payment header using the configured x402HTTPClient
15
+ * 4. Retry the request with the payment header
16
+ *
17
+ * @param axiosInstance - The Axios instance to wrap
18
+ * @param client - Configured x402Client instance for handling payments
19
+ * @returns The wrapped Axios instance that handles 402 responses automatically
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import axios from 'axios';
24
+ * import { wrapAxiosWithPayment, x402Client } from '@x402/axios';
25
+ * import { ExactEvmScheme } from '@x402/evm';
26
+ * import { privateKeyToAccount } from 'viem/accounts';
27
+ *
28
+ * const account = privateKeyToAccount('0x...');
29
+ * const client = new x402Client()
30
+ * .register('eip155:*', new ExactEvmScheme(account));
31
+ *
32
+ * const api = wrapAxiosWithPayment(axios.create(), client);
33
+ *
34
+ * // Make a request that may require payment
35
+ * const response = await api.get('https://api.example.com/paid-endpoint');
36
+ * ```
37
+ *
38
+ * @throws {Error} If no schemes are provided
39
+ * @throws {Error} If the request configuration is missing
40
+ * @throws {Error} If a payment has already been attempted for this request
41
+ * @throws {Error} If there's an error creating the payment header
42
+ */
43
+ declare function wrapAxiosWithPayment(axiosInstance: AxiosInstance, client: x402Client): AxiosInstance;
44
+ /**
45
+ * Wraps an Axios instance with x402 payment handling using a configuration object.
46
+ *
47
+ * @param axiosInstance - The Axios instance to wrap
48
+ * @param config - Configuration options including scheme registrations and selectors
49
+ * @returns The wrapped Axios instance that handles 402 responses automatically
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * import axios from 'axios';
54
+ * import { wrapAxiosWithPaymentFromConfig } from '@x402/axios';
55
+ * import { ExactEvmScheme } from '@x402/evm';
56
+ * import { privateKeyToAccount } from 'viem/accounts';
57
+ *
58
+ * const account = privateKeyToAccount('0x...');
59
+ *
60
+ * const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
61
+ * schemes: [
62
+ * { network: 'eip155:*', client: new ExactEvmScheme(account) }
63
+ * ]
64
+ * });
65
+ *
66
+ * const response = await api.get('https://api.example.com/paid-endpoint');
67
+ * ```
68
+ */
69
+ declare function wrapAxiosWithPaymentFromConfig(axiosInstance: AxiosInstance, config: x402ClientConfig): AxiosInstance;
70
+
71
+ export { wrapAxiosWithPayment, wrapAxiosWithPaymentFromConfig };
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ decodePaymentResponseHeader: () => import_http.decodePaymentResponseHeader,
24
+ wrapAxiosWithPayment: () => wrapAxiosWithPayment,
25
+ wrapAxiosWithPaymentFromConfig: () => wrapAxiosWithPaymentFromConfig,
26
+ x402Client: () => import_client2.x402Client,
27
+ x402HTTPClient: () => import_client2.x402HTTPClient
28
+ });
29
+ module.exports = __toCommonJS(src_exports);
30
+ var import_client = require("@x402/core/client");
31
+ var import_client2 = require("@x402/core/client");
32
+ var import_http = require("@x402/core/http");
33
+ function wrapAxiosWithPayment(axiosInstance, client) {
34
+ const httpClient = new import_client.x402HTTPClient(client);
35
+ axiosInstance.interceptors.response.use(
36
+ (response) => response,
37
+ async (error) => {
38
+ if (!error.response || error.response.status !== 402) {
39
+ return Promise.reject(error);
40
+ }
41
+ const originalConfig = error.config;
42
+ if (!originalConfig || !originalConfig.headers) {
43
+ return Promise.reject(new Error("Missing axios request configuration"));
44
+ }
45
+ if (originalConfig.__is402Retry) {
46
+ return Promise.reject(error);
47
+ }
48
+ try {
49
+ let paymentRequired;
50
+ try {
51
+ const response = error.response;
52
+ const getHeader = (name) => {
53
+ const value = response.headers[name] ?? response.headers[name.toLowerCase()];
54
+ return typeof value === "string" ? value : void 0;
55
+ };
56
+ const body = response.data;
57
+ paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);
58
+ } catch (parseError) {
59
+ return Promise.reject(
60
+ new Error(
61
+ `Failed to parse payment requirements: ${parseError instanceof Error ? parseError.message : "Unknown error"}`
62
+ )
63
+ );
64
+ }
65
+ let paymentPayload;
66
+ try {
67
+ paymentPayload = await client.createPaymentPayload(paymentRequired);
68
+ } catch (paymentError) {
69
+ return Promise.reject(
70
+ new Error(
71
+ `Failed to create payment payload: ${paymentError instanceof Error ? paymentError.message : "Unknown error"}`
72
+ )
73
+ );
74
+ }
75
+ const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
76
+ originalConfig.__is402Retry = true;
77
+ Object.entries(paymentHeaders).forEach(([key, value]) => {
78
+ originalConfig.headers.set(key, value);
79
+ });
80
+ originalConfig.headers.set(
81
+ "Access-Control-Expose-Headers",
82
+ "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
83
+ );
84
+ const secondResponse = await axiosInstance.request(originalConfig);
85
+ return secondResponse;
86
+ } catch (retryError) {
87
+ return Promise.reject(retryError);
88
+ }
89
+ }
90
+ );
91
+ return axiosInstance;
92
+ }
93
+ function wrapAxiosWithPaymentFromConfig(axiosInstance, config) {
94
+ const client = import_client.x402Client.fromConfig(config);
95
+ return wrapAxiosWithPayment(axiosInstance, client);
96
+ }
97
+ // Annotate the CommonJS export names for ESM import in node:
98
+ 0 && (module.exports = {
99
+ decodePaymentResponseHeader,
100
+ wrapAxiosWithPayment,
101
+ wrapAxiosWithPaymentFromConfig,
102
+ x402Client,
103
+ x402HTTPClient
104
+ });
105
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import { x402Client, x402ClientConfig, x402HTTPClient } from \"@x402/core/client\";\nimport { type PaymentRequired } from \"@x402/core/types\";\nimport type { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from \"axios\";\n\n/**\n * Wraps an Axios instance with x402 payment handling.\n *\n * This function adds an interceptor to automatically handle 402 Payment Required responses\n * by creating and sending payment headers. It will:\n * 1. Intercept 402 responses\n * 2. Parse the payment requirements\n * 3. Create a payment header using the configured x402HTTPClient\n * 4. Retry the request with the payment header\n *\n * @param axiosInstance - The Axios instance to wrap\n * @param client - Configured x402Client instance for handling payments\n * @returns The wrapped Axios instance that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import axios from 'axios';\n * import { wrapAxiosWithPayment, x402Client } from '@x402/axios';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { privateKeyToAccount } from 'viem/accounts';\n *\n * const account = privateKeyToAccount('0x...');\n * const client = new x402Client()\n * .register('eip155:*', new ExactEvmScheme(account));\n *\n * const api = wrapAxiosWithPayment(axios.create(), client);\n *\n * // Make a request that may require payment\n * const response = await api.get('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If no schemes are provided\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 wrapAxiosWithPayment(\n axiosInstance: AxiosInstance,\n client: x402Client,\n): AxiosInstance {\n const httpClient = new x402HTTPClient(client);\n\n axiosInstance.interceptors.response.use(\n response => response,\n async (error: AxiosError) => {\n if (!error.response || error.response.status !== 402) {\n return Promise.reject(error);\n }\n\n const originalConfig = error.config;\n if (!originalConfig || !originalConfig.headers) {\n return Promise.reject(new Error(\"Missing axios request configuration\"));\n }\n\n // Check if this is already a retry to prevent infinite loops\n if (\n (originalConfig as InternalAxiosRequestConfig & { __is402Retry?: boolean }).__is402Retry\n ) {\n return Promise.reject(error);\n }\n\n try {\n // Parse payment requirements from response\n let paymentRequired: PaymentRequired;\n try {\n const response = error.response!; // Already validated above\n\n // Create getHeader function for case-insensitive header lookup\n const getHeader = (name: string) => {\n const value = response.headers[name] ?? response.headers[name.toLowerCase()];\n return typeof value === \"string\" ? value : undefined;\n };\n\n // Try to get from headers first (v2), then from body (v1)\n const body = response.data as PaymentRequired | undefined;\n\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n } catch (parseError) {\n return Promise.reject(\n new Error(\n `Failed to parse payment requirements: ${parseError instanceof Error ? parseError.message : \"Unknown error\"}`,\n ),\n );\n }\n\n // Create payment payload\n let paymentPayload;\n try {\n paymentPayload = await client.createPaymentPayload(paymentRequired);\n } catch (paymentError) {\n return Promise.reject(\n new Error(\n `Failed to create payment payload: ${paymentError instanceof Error ? paymentError.message : \"Unknown error\"}`,\n ),\n );\n }\n\n // Encode payment header\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);\n\n // Mark this as a retry\n (originalConfig as InternalAxiosRequestConfig & { __is402Retry?: boolean }).__is402Retry =\n true;\n\n // Add payment headers to the request\n Object.entries(paymentHeaders).forEach(([key, value]) => {\n originalConfig.headers.set(key, value);\n });\n\n // Add CORS header to expose payment response\n originalConfig.headers.set(\n \"Access-Control-Expose-Headers\",\n \"PAYMENT-RESPONSE,X-PAYMENT-RESPONSE\",\n );\n\n // Retry the request with payment\n const secondResponse = await axiosInstance.request(originalConfig);\n return secondResponse;\n } catch (retryError) {\n return Promise.reject(retryError);\n }\n },\n );\n\n return axiosInstance;\n}\n\n/**\n * Wraps an Axios instance with x402 payment handling using a configuration object.\n *\n * @param axiosInstance - The Axios instance to wrap\n * @param config - Configuration options including scheme registrations and selectors\n * @returns The wrapped Axios instance that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import axios from 'axios';\n * import { wrapAxiosWithPaymentFromConfig } from '@x402/axios';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { privateKeyToAccount } from 'viem/accounts';\n *\n * const account = privateKeyToAccount('0x...');\n *\n * const api = wrapAxiosWithPaymentFromConfig(axios.create(), {\n * schemes: [\n * { network: 'eip155:*', client: new ExactEvmScheme(account) }\n * ]\n * });\n *\n * const response = await api.get('https://api.example.com/paid-endpoint');\n * ```\n */\nexport function wrapAxiosWithPaymentFromConfig(\n axiosInstance: AxiosInstance,\n config: x402ClientConfig,\n): AxiosInstance {\n const client = x402Client.fromConfig(config);\n return wrapAxiosWithPayment(axiosInstance, client);\n}\n\n// Re-export types and utilities for convenience\nexport { x402Client, x402HTTPClient } from \"@x402/core/client\";\nexport type {\n PaymentPolicy,\n SchemeRegistration,\n SelectPaymentRequirements,\n x402ClientConfig,\n} from \"@x402/core/client\";\nexport { decodePaymentResponseHeader } from \"@x402/core/http\";\nexport type {\n Network,\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAA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,cAAc;AAG7E,QAAC,eAA2E,eAC1E;AAGF,eAAO,QAAQ,cAAc,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACvD,yBAAe,QAAQ,IAAI,KAAK,KAAK;AAAA,QACvC,CAAC;AAGD,uBAAe,QAAQ;AAAA,UACrB;AAAA,UACA;AAAA,QACF;AAGA,cAAM,iBAAiB,MAAM,cAAc,QAAQ,cAAc;AACjE,eAAO;AAAA,MACT,SAAS,YAAY;AACnB,eAAO,QAAQ,OAAO,UAAU;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AA2BO,SAAS,+BACd,eACA,QACe;AACf,QAAM,SAAS,yBAAW,WAAW,MAAM;AAC3C,SAAO,qBAAqB,eAAe,MAAM;AACnD;","names":["import_client"]}
@@ -0,0 +1,71 @@
1
+ import { x402Client, x402ClientConfig } from '@x402/core/client';
2
+ export { PaymentPolicy, SchemeRegistration, SelectPaymentRequirements, x402Client, x402ClientConfig, x402HTTPClient } from '@x402/core/client';
3
+ import { AxiosInstance } from 'axios';
4
+ export { decodePaymentResponseHeader } from '@x402/core/http';
5
+ export { Network, PaymentPayload, PaymentRequired, PaymentRequirements, SchemeNetworkClient } from '@x402/core/types';
6
+
7
+ /**
8
+ * Wraps an Axios instance with x402 payment handling.
9
+ *
10
+ * This function adds an interceptor to automatically handle 402 Payment Required responses
11
+ * by creating and sending payment headers. It will:
12
+ * 1. Intercept 402 responses
13
+ * 2. Parse the payment requirements
14
+ * 3. Create a payment header using the configured x402HTTPClient
15
+ * 4. Retry the request with the payment header
16
+ *
17
+ * @param axiosInstance - The Axios instance to wrap
18
+ * @param client - Configured x402Client instance for handling payments
19
+ * @returns The wrapped Axios instance that handles 402 responses automatically
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import axios from 'axios';
24
+ * import { wrapAxiosWithPayment, x402Client } from '@x402/axios';
25
+ * import { ExactEvmScheme } from '@x402/evm';
26
+ * import { privateKeyToAccount } from 'viem/accounts';
27
+ *
28
+ * const account = privateKeyToAccount('0x...');
29
+ * const client = new x402Client()
30
+ * .register('eip155:*', new ExactEvmScheme(account));
31
+ *
32
+ * const api = wrapAxiosWithPayment(axios.create(), client);
33
+ *
34
+ * // Make a request that may require payment
35
+ * const response = await api.get('https://api.example.com/paid-endpoint');
36
+ * ```
37
+ *
38
+ * @throws {Error} If no schemes are provided
39
+ * @throws {Error} If the request configuration is missing
40
+ * @throws {Error} If a payment has already been attempted for this request
41
+ * @throws {Error} If there's an error creating the payment header
42
+ */
43
+ declare function wrapAxiosWithPayment(axiosInstance: AxiosInstance, client: x402Client): AxiosInstance;
44
+ /**
45
+ * Wraps an Axios instance with x402 payment handling using a configuration object.
46
+ *
47
+ * @param axiosInstance - The Axios instance to wrap
48
+ * @param config - Configuration options including scheme registrations and selectors
49
+ * @returns The wrapped Axios instance that handles 402 responses automatically
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * import axios from 'axios';
54
+ * import { wrapAxiosWithPaymentFromConfig } from '@x402/axios';
55
+ * import { ExactEvmScheme } from '@x402/evm';
56
+ * import { privateKeyToAccount } from 'viem/accounts';
57
+ *
58
+ * const account = privateKeyToAccount('0x...');
59
+ *
60
+ * const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
61
+ * schemes: [
62
+ * { network: 'eip155:*', client: new ExactEvmScheme(account) }
63
+ * ]
64
+ * });
65
+ *
66
+ * const response = await api.get('https://api.example.com/paid-endpoint');
67
+ * ```
68
+ */
69
+ declare function wrapAxiosWithPaymentFromConfig(axiosInstance: AxiosInstance, config: x402ClientConfig): AxiosInstance;
70
+
71
+ export { wrapAxiosWithPayment, wrapAxiosWithPaymentFromConfig };
@@ -0,0 +1,76 @@
1
+ // src/index.ts
2
+ import { x402Client, x402HTTPClient } from "@x402/core/client";
3
+ import { x402Client as x402Client2, x402HTTPClient as x402HTTPClient2 } from "@x402/core/client";
4
+ import { decodePaymentResponseHeader } from "@x402/core/http";
5
+ function wrapAxiosWithPayment(axiosInstance, client) {
6
+ const httpClient = new x402HTTPClient(client);
7
+ axiosInstance.interceptors.response.use(
8
+ (response) => response,
9
+ async (error) => {
10
+ if (!error.response || error.response.status !== 402) {
11
+ return Promise.reject(error);
12
+ }
13
+ const originalConfig = error.config;
14
+ if (!originalConfig || !originalConfig.headers) {
15
+ return Promise.reject(new Error("Missing axios request configuration"));
16
+ }
17
+ if (originalConfig.__is402Retry) {
18
+ return Promise.reject(error);
19
+ }
20
+ try {
21
+ let paymentRequired;
22
+ try {
23
+ const response = error.response;
24
+ const getHeader = (name) => {
25
+ const value = response.headers[name] ?? response.headers[name.toLowerCase()];
26
+ return typeof value === "string" ? value : void 0;
27
+ };
28
+ const body = response.data;
29
+ paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);
30
+ } catch (parseError) {
31
+ return Promise.reject(
32
+ new Error(
33
+ `Failed to parse payment requirements: ${parseError instanceof Error ? parseError.message : "Unknown error"}`
34
+ )
35
+ );
36
+ }
37
+ let paymentPayload;
38
+ try {
39
+ paymentPayload = await client.createPaymentPayload(paymentRequired);
40
+ } catch (paymentError) {
41
+ return Promise.reject(
42
+ new Error(
43
+ `Failed to create payment payload: ${paymentError instanceof Error ? paymentError.message : "Unknown error"}`
44
+ )
45
+ );
46
+ }
47
+ const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
48
+ originalConfig.__is402Retry = true;
49
+ Object.entries(paymentHeaders).forEach(([key, value]) => {
50
+ originalConfig.headers.set(key, value);
51
+ });
52
+ originalConfig.headers.set(
53
+ "Access-Control-Expose-Headers",
54
+ "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
55
+ );
56
+ const secondResponse = await axiosInstance.request(originalConfig);
57
+ return secondResponse;
58
+ } catch (retryError) {
59
+ return Promise.reject(retryError);
60
+ }
61
+ }
62
+ );
63
+ return axiosInstance;
64
+ }
65
+ function wrapAxiosWithPaymentFromConfig(axiosInstance, config) {
66
+ const client = x402Client.fromConfig(config);
67
+ return wrapAxiosWithPayment(axiosInstance, client);
68
+ }
69
+ export {
70
+ decodePaymentResponseHeader,
71
+ wrapAxiosWithPayment,
72
+ wrapAxiosWithPaymentFromConfig,
73
+ x402Client2 as x402Client,
74
+ x402HTTPClient2 as x402HTTPClient
75
+ };
76
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["import { x402Client, x402ClientConfig, x402HTTPClient } from \"@x402/core/client\";\nimport { type PaymentRequired } from \"@x402/core/types\";\nimport type { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from \"axios\";\n\n/**\n * Wraps an Axios instance with x402 payment handling.\n *\n * This function adds an interceptor to automatically handle 402 Payment Required responses\n * by creating and sending payment headers. It will:\n * 1. Intercept 402 responses\n * 2. Parse the payment requirements\n * 3. Create a payment header using the configured x402HTTPClient\n * 4. Retry the request with the payment header\n *\n * @param axiosInstance - The Axios instance to wrap\n * @param client - Configured x402Client instance for handling payments\n * @returns The wrapped Axios instance that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import axios from 'axios';\n * import { wrapAxiosWithPayment, x402Client } from '@x402/axios';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { privateKeyToAccount } from 'viem/accounts';\n *\n * const account = privateKeyToAccount('0x...');\n * const client = new x402Client()\n * .register('eip155:*', new ExactEvmScheme(account));\n *\n * const api = wrapAxiosWithPayment(axios.create(), client);\n *\n * // Make a request that may require payment\n * const response = await api.get('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If no schemes are provided\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 wrapAxiosWithPayment(\n axiosInstance: AxiosInstance,\n client: x402Client,\n): AxiosInstance {\n const httpClient = new x402HTTPClient(client);\n\n axiosInstance.interceptors.response.use(\n response => response,\n async (error: AxiosError) => {\n if (!error.response || error.response.status !== 402) {\n return Promise.reject(error);\n }\n\n const originalConfig = error.config;\n if (!originalConfig || !originalConfig.headers) {\n return Promise.reject(new Error(\"Missing axios request configuration\"));\n }\n\n // Check if this is already a retry to prevent infinite loops\n if (\n (originalConfig as InternalAxiosRequestConfig & { __is402Retry?: boolean }).__is402Retry\n ) {\n return Promise.reject(error);\n }\n\n try {\n // Parse payment requirements from response\n let paymentRequired: PaymentRequired;\n try {\n const response = error.response!; // Already validated above\n\n // Create getHeader function for case-insensitive header lookup\n const getHeader = (name: string) => {\n const value = response.headers[name] ?? response.headers[name.toLowerCase()];\n return typeof value === \"string\" ? value : undefined;\n };\n\n // Try to get from headers first (v2), then from body (v1)\n const body = response.data as PaymentRequired | undefined;\n\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n } catch (parseError) {\n return Promise.reject(\n new Error(\n `Failed to parse payment requirements: ${parseError instanceof Error ? parseError.message : \"Unknown error\"}`,\n ),\n );\n }\n\n // Create payment payload\n let paymentPayload;\n try {\n paymentPayload = await client.createPaymentPayload(paymentRequired);\n } catch (paymentError) {\n return Promise.reject(\n new Error(\n `Failed to create payment payload: ${paymentError instanceof Error ? paymentError.message : \"Unknown error\"}`,\n ),\n );\n }\n\n // Encode payment header\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);\n\n // Mark this as a retry\n (originalConfig as InternalAxiosRequestConfig & { __is402Retry?: boolean }).__is402Retry =\n true;\n\n // Add payment headers to the request\n Object.entries(paymentHeaders).forEach(([key, value]) => {\n originalConfig.headers.set(key, value);\n });\n\n // Add CORS header to expose payment response\n originalConfig.headers.set(\n \"Access-Control-Expose-Headers\",\n \"PAYMENT-RESPONSE,X-PAYMENT-RESPONSE\",\n );\n\n // Retry the request with payment\n const secondResponse = await axiosInstance.request(originalConfig);\n return secondResponse;\n } catch (retryError) {\n return Promise.reject(retryError);\n }\n },\n );\n\n return axiosInstance;\n}\n\n/**\n * Wraps an Axios instance with x402 payment handling using a configuration object.\n *\n * @param axiosInstance - The Axios instance to wrap\n * @param config - Configuration options including scheme registrations and selectors\n * @returns The wrapped Axios instance that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import axios from 'axios';\n * import { wrapAxiosWithPaymentFromConfig } from '@x402/axios';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { privateKeyToAccount } from 'viem/accounts';\n *\n * const account = privateKeyToAccount('0x...');\n *\n * const api = wrapAxiosWithPaymentFromConfig(axios.create(), {\n * schemes: [\n * { network: 'eip155:*', client: new ExactEvmScheme(account) }\n * ]\n * });\n *\n * const response = await api.get('https://api.example.com/paid-endpoint');\n * ```\n */\nexport function wrapAxiosWithPaymentFromConfig(\n axiosInstance: AxiosInstance,\n config: x402ClientConfig,\n): AxiosInstance {\n const client = x402Client.fromConfig(config);\n return wrapAxiosWithPayment(axiosInstance, client);\n}\n\n// Re-export types and utilities for convenience\nexport { x402Client, x402HTTPClient } from \"@x402/core/client\";\nexport type {\n PaymentPolicy,\n SchemeRegistration,\n SelectPaymentRequirements,\n x402ClientConfig,\n} from \"@x402/core/client\";\nexport { decodePaymentResponseHeader } from \"@x402/core/http\";\nexport type {\n Network,\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\n"],"mappings":";AAAA,SAAS,YAA8B,sBAAsB;AAqK7D,SAAS,cAAAA,aAAY,kBAAAC,uBAAsB;AAO3C,SAAS,mCAAmC;AApIrC,SAAS,qBACd,eACA,QACe;AACf,QAAM,aAAa,IAAI,eAAe,MAAM;AAE5C,gBAAc,aAAa,SAAS;AAAA,IAClC,cAAY;AAAA,IACZ,OAAO,UAAsB;AAC3B,UAAI,CAAC,MAAM,YAAY,MAAM,SAAS,WAAW,KAAK;AACpD,eAAO,QAAQ,OAAO,KAAK;AAAA,MAC7B;AAEA,YAAM,iBAAiB,MAAM;AAC7B,UAAI,CAAC,kBAAkB,CAAC,eAAe,SAAS;AAC9C,eAAO,QAAQ,OAAO,IAAI,MAAM,qCAAqC,CAAC;AAAA,MACxE;AAGA,UACG,eAA2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402HTTPClient"]}
package/package.json CHANGED
@@ -1,12 +1,60 @@
1
1
  {
2
2
  "name": "@x402/axios",
3
- "version": "0.0.1",
4
- "description": "The Axios interceptor package for the x402 payment protocol",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "author": "Coinbase Inc.",
3
+ "version": "2.1.0",
4
+ "main": "./dist/cjs/index.js",
5
+ "module": "./dist/esm/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "keywords": [],
10
8
  "license": "Apache-2.0",
11
- "repository": "https://github.com/coinbase/x402"
9
+ "author": "Coinbase Inc.",
10
+ "repository": "https://github.com/coinbase/x402",
11
+ "description": "x402 Payment Protocol",
12
+ "devDependencies": {
13
+ "@eslint/js": "^9.24.0",
14
+ "@types/node": "^22.13.4",
15
+ "@typescript-eslint/eslint-plugin": "^8.29.1",
16
+ "@typescript-eslint/parser": "^8.29.1",
17
+ "eslint": "^9.24.0",
18
+ "eslint-plugin-import": "^2.31.0",
19
+ "eslint-plugin-jsdoc": "^50.6.9",
20
+ "eslint-plugin-prettier": "^5.2.6",
21
+ "prettier": "3.5.2",
22
+ "tsup": "^8.4.0",
23
+ "tsx": "^4.19.2",
24
+ "typescript": "^5.7.3",
25
+ "vite-tsconfig-paths": "^5.1.4",
26
+ "vitest": "^3.0.5",
27
+ "vite": "^6.2.6"
28
+ },
29
+ "dependencies": {
30
+ "axios": "^1.7.9",
31
+ "zod": "^3.24.2",
32
+ "@x402/core": "^2.1.0"
33
+ },
34
+ "exports": {
35
+ ".": {
36
+ "import": {
37
+ "types": "./dist/esm/index.d.mts",
38
+ "default": "./dist/esm/index.mjs"
39
+ },
40
+ "require": {
41
+ "types": "./dist/cjs/index.d.ts",
42
+ "default": "./dist/cjs/index.js"
43
+ }
44
+ }
45
+ },
46
+ "files": [
47
+ "dist"
48
+ ],
49
+ "scripts": {
50
+ "start": "tsx --env-file=.env index.ts",
51
+ "test": "vitest run",
52
+ "test:watch": "vitest",
53
+ "build": "tsup",
54
+ "watch": "tsc --watch",
55
+ "format": "prettier -c .prettierrc --write \"**/*.{ts,js,cjs,json,md}\"",
56
+ "format:check": "prettier -c .prettierrc --check \"**/*.{ts,js,cjs,json,md}\"",
57
+ "lint": "eslint . --ext .ts --fix",
58
+ "lint:check": "eslint . --ext .ts"
59
+ }
12
60
  }
package/index.js DELETED
@@ -1,3 +0,0 @@
1
- // Placeholder for @x402/axios
2
- module.exports = {};
3
-