@okxweb3/app-x402-core 0.1.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.
Files changed (66) hide show
  1. package/README.md +267 -0
  2. package/dist/cjs/OKXFacilitatorClient-BvyQB1QM.d.ts +59 -0
  3. package/dist/cjs/client/index.d.ts +320 -0
  4. package/dist/cjs/client/index.js +564 -0
  5. package/dist/cjs/client/index.js.map +1 -0
  6. package/dist/cjs/facilitator/index.d.ts +198 -0
  7. package/dist/cjs/facilitator/index.js +533 -0
  8. package/dist/cjs/facilitator/index.js.map +1 -0
  9. package/dist/cjs/http/index.d.ts +51 -0
  10. package/dist/cjs/http/index.js +1226 -0
  11. package/dist/cjs/http/index.js.map +1 -0
  12. package/dist/cjs/index.d.ts +6 -0
  13. package/dist/cjs/index.js +155 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/mechanisms-sojpSwWW.d.ts +763 -0
  16. package/dist/cjs/schemas/index.d.ts +309 -0
  17. package/dist/cjs/schemas/index.js +127 -0
  18. package/dist/cjs/schemas/index.js.map +1 -0
  19. package/dist/cjs/server/index.d.ts +2 -0
  20. package/dist/cjs/server/index.js +1880 -0
  21. package/dist/cjs/server/index.js.map +1 -0
  22. package/dist/cjs/types/index.d.ts +1 -0
  23. package/dist/cjs/types/index.js +97 -0
  24. package/dist/cjs/types/index.js.map +1 -0
  25. package/dist/cjs/utils/index.d.ts +48 -0
  26. package/dist/cjs/utils/index.js +116 -0
  27. package/dist/cjs/utils/index.js.map +1 -0
  28. package/dist/cjs/x402HTTPResourceServer-CcsAkcgI.d.ts +466 -0
  29. package/dist/esm/OKXFacilitatorClient-D5E3LX50.d.mts +59 -0
  30. package/dist/esm/chunk-CAXWAW23.mjs +68 -0
  31. package/dist/esm/chunk-CAXWAW23.mjs.map +1 -0
  32. package/dist/esm/chunk-CS33MEMU.mjs +86 -0
  33. package/dist/esm/chunk-CS33MEMU.mjs.map +1 -0
  34. package/dist/esm/chunk-O3IYMTNT.mjs +118 -0
  35. package/dist/esm/chunk-O3IYMTNT.mjs.map +1 -0
  36. package/dist/esm/chunk-TDLQZ6MP.mjs +86 -0
  37. package/dist/esm/chunk-TDLQZ6MP.mjs.map +1 -0
  38. package/dist/esm/chunk-XBQG2CDV.mjs +1792 -0
  39. package/dist/esm/chunk-XBQG2CDV.mjs.map +1 -0
  40. package/dist/esm/client/index.d.mts +320 -0
  41. package/dist/esm/client/index.mjs +318 -0
  42. package/dist/esm/client/index.mjs.map +1 -0
  43. package/dist/esm/facilitator/index.d.mts +198 -0
  44. package/dist/esm/facilitator/index.mjs +387 -0
  45. package/dist/esm/facilitator/index.mjs.map +1 -0
  46. package/dist/esm/http/index.d.mts +51 -0
  47. package/dist/esm/http/index.mjs +34 -0
  48. package/dist/esm/http/index.mjs.map +1 -0
  49. package/dist/esm/index.d.mts +6 -0
  50. package/dist/esm/index.mjs +9 -0
  51. package/dist/esm/index.mjs.map +1 -0
  52. package/dist/esm/mechanisms-sojpSwWW.d.mts +763 -0
  53. package/dist/esm/schemas/index.d.mts +309 -0
  54. package/dist/esm/schemas/index.mjs +41 -0
  55. package/dist/esm/schemas/index.mjs.map +1 -0
  56. package/dist/esm/server/index.d.mts +2 -0
  57. package/dist/esm/server/index.mjs +28 -0
  58. package/dist/esm/server/index.mjs.map +1 -0
  59. package/dist/esm/types/index.d.mts +1 -0
  60. package/dist/esm/types/index.mjs +13 -0
  61. package/dist/esm/types/index.mjs.map +1 -0
  62. package/dist/esm/utils/index.d.mts +48 -0
  63. package/dist/esm/utils/index.mjs +19 -0
  64. package/dist/esm/utils/index.mjs.map +1 -0
  65. package/dist/esm/x402HTTPResourceServer-DBeutKxq.d.mts +466 -0
  66. package/package.json +121 -0
package/README.md ADDED
@@ -0,0 +1,267 @@
1
+ # @okxweb3/app-x402-core
2
+
3
+ Core implementation of the x402 payment protocol for TypeScript/JavaScript applications. Provides transport-agnostic client, server, and facilitator components for EVM-based payment flows.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm install @okxweb3/app-x402-core
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### Client Usage
14
+
15
+ ```typescript
16
+ import { x402Client } from '@okxweb3/app-x402-core/client';
17
+ import { x402HTTPClient } from '@okxweb3/app-x402-core/http';
18
+ import { ExactEvmScheme } from '@okxweb3/app-x402-evm/exact/client';
19
+
20
+ // Create core client and register EVM payment scheme
21
+ const coreClient = new x402Client()
22
+ .register('eip155:*', new ExactEvmScheme(evmSigner));
23
+
24
+ // Wrap with HTTP client for header encoding/decoding
25
+ const client = new x402HTTPClient(coreClient);
26
+
27
+ // Make a request
28
+ const response = await fetch('https://api.example.com/protected');
29
+
30
+ if (response.status === 402) {
31
+ // Extract payment requirements from response
32
+ const paymentRequired = client.getPaymentRequiredResponse(
33
+ (name) => response.headers.get(name),
34
+ await response.json()
35
+ );
36
+
37
+ // Create and send payment
38
+ const paymentPayload = await client.createPaymentPayload(paymentRequired);
39
+
40
+ const paidResponse = await fetch('https://api.example.com/protected', {
41
+ headers: client.encodePaymentSignatureHeader(paymentPayload),
42
+ });
43
+
44
+ // Get settlement confirmation
45
+ const settlement = client.getPaymentSettleResponse(
46
+ (name) => paidResponse.headers.get(name)
47
+ );
48
+ console.log('Transaction:', settlement.transaction);
49
+ }
50
+ ```
51
+
52
+ ### Server Usage
53
+
54
+ ```typescript
55
+ import { x402ResourceServer } from '@okxweb3/app-x402-core/server';
56
+ import { x402HTTPResourceServer } from '@okxweb3/app-x402-core/http';
57
+ import { OKXFacilitatorClient } from '@okxweb3/app-x402-core';
58
+ import { ExactEvmScheme } from '@okxweb3/app-x402-evm/exact/server';
59
+
60
+ // Connect to OKX facilitator
61
+ const facilitatorClient = new OKXFacilitatorClient({
62
+ apiKey: 'YOUR_API_KEY',
63
+ secretKey: 'YOUR_SECRET_KEY',
64
+ passphrase: 'YOUR_PASSPHRASE',
65
+ });
66
+
67
+ // Create resource server with EVM payment scheme
68
+ const resourceServer = new x402ResourceServer(facilitatorClient)
69
+ .register('eip155:*', new ExactEvmScheme());
70
+
71
+ // Initialize (fetches supported kinds from facilitator)
72
+ await resourceServer.initialize();
73
+
74
+ // Configure routes with payment requirements
75
+ const routes = {
76
+ 'GET /api/data': {
77
+ accepts: {
78
+ scheme: 'exact',
79
+ network: 'eip155:196',
80
+ payTo: '0xYourAddress',
81
+ price: '$0.01',
82
+ },
83
+ description: 'Premium data access',
84
+ mimeType: 'application/json',
85
+ },
86
+ };
87
+
88
+ // Create HTTP server wrapper
89
+ const httpServer = new x402HTTPResourceServer(resourceServer, routes);
90
+ ```
91
+
92
+ ## OKXFacilitatorClient
93
+
94
+ The `OKXFacilitatorClient` connects to the OKX facilitator service using HMAC-SHA256 authentication.
95
+
96
+ ```typescript
97
+ import { OKXFacilitatorClient } from '@okxweb3/app-x402-core';
98
+ import type { OKXConfig } from '@okxweb3/app-x402-core';
99
+
100
+ const config: OKXConfig = {
101
+ apiKey: 'YOUR_API_KEY',
102
+ secretKey: 'YOUR_SECRET_KEY',
103
+ passphrase: 'YOUR_PASSPHRASE',
104
+ baseUrl: 'https://www.okx.com', // optional, defaults to https://www.okx.com
105
+ syncSettle: false, // optional, when true the facilitator waits for on-chain confirmation
106
+ };
107
+
108
+ const client = new OKXFacilitatorClient(config);
109
+ ```
110
+
111
+ ## Route Configuration
112
+
113
+ Routes use the `accepts` field to define payment options:
114
+
115
+ ```typescript
116
+ const routes = {
117
+ // Single payment option
118
+ 'GET /api/data': {
119
+ accepts: {
120
+ scheme: 'exact',
121
+ network: 'eip155:196',
122
+ payTo: '0xAddress',
123
+ price: '$0.01',
124
+ },
125
+ description: 'Data endpoint',
126
+ mimeType: 'application/json',
127
+ },
128
+
129
+ // XLayer payment option
130
+ 'POST /api/*': {
131
+ accepts: [
132
+ {
133
+ scheme: 'exact',
134
+ network: 'eip155:196',
135
+ payTo: '0xAddress',
136
+ price: '$0.05',
137
+ },
138
+ ],
139
+ },
140
+ };
141
+ ```
142
+
143
+ ## Client Configuration
144
+
145
+ Use `fromConfig()` for declarative setup:
146
+
147
+ ```typescript
148
+ const client = x402Client.fromConfig({
149
+ schemes: [
150
+ { network: 'eip155:196', client: new ExactEvmScheme(evmSigner) },
151
+ ],
152
+ policies: [
153
+ // Filter by max price
154
+ (version, reqs) => reqs.filter(r => BigInt(r.amount) < BigInt('1000000')),
155
+ ],
156
+ });
157
+ ```
158
+
159
+ ## Lifecycle Hooks
160
+
161
+ ### Client Hooks
162
+
163
+ ```typescript
164
+ client
165
+ .onBeforePaymentCreation(async (ctx) => {
166
+ console.log('Creating payment for:', ctx.selectedRequirements.network);
167
+ // Return { abort: true, reason: '...' } to cancel
168
+ })
169
+ .onAfterPaymentCreation(async (ctx) => {
170
+ console.log('Payment created:', ctx.paymentPayload);
171
+ })
172
+ .onPaymentCreationFailure(async (ctx) => {
173
+ console.error('Payment failed:', ctx.error);
174
+ // Return { recovered: true, payload: ... } to recover
175
+ });
176
+ ```
177
+
178
+ ### Server Hooks
179
+
180
+ ```typescript
181
+ resourceServer
182
+ .onBeforeVerify(async (ctx) => { /* ... */ })
183
+ .onAfterVerify(async (ctx) => { /* ... */ })
184
+ .onBeforeSettle(async (ctx) => { /* ... */ })
185
+ .onAfterSettle(async (ctx) => { /* ... */ });
186
+ ```
187
+
188
+ ### Facilitator Hooks
189
+
190
+ ```typescript
191
+ facilitator
192
+ .onBeforeVerify(async (ctx) => { console.log('Before verify', ctx); })
193
+ .onAfterVerify(async (ctx) => { console.log('After verify', ctx); })
194
+ .onVerifyFailure(async (ctx) => { console.log('Verify failure', ctx); })
195
+ .onBeforeSettle(async (ctx) => { console.log('Before settle', ctx); })
196
+ .onAfterSettle(async (ctx) => { console.log('After settle', ctx); })
197
+ .onSettleFailure(async (ctx) => { console.log('Settle failure', ctx); });
198
+ ```
199
+
200
+ ## HTTP Headers
201
+
202
+ | Header | Description |
203
+ |--------|-------------|
204
+ | `PAYMENT-SIGNATURE` | Base64-encoded payment payload |
205
+ | `PAYMENT-REQUIRED` | Base64-encoded payment requirements |
206
+ | `PAYMENT-RESPONSE` | Base64-encoded settlement response |
207
+
208
+ ## Network Pattern Matching
209
+
210
+ Register handlers for EVM network families using wildcards:
211
+
212
+ ```typescript
213
+ // All EVM networks
214
+ server.register('eip155:*', new ExactEvmScheme());
215
+
216
+ // Specific network takes precedence
217
+ server.register('eip155:196', new ExactEvmScheme());
218
+ ```
219
+
220
+ ## Types
221
+
222
+ ```typescript
223
+ type Network = `${string}:${string}`; // e.g., "eip155:196"
224
+
225
+ type PaymentRequirements = {
226
+ scheme: string;
227
+ network: Network;
228
+ asset: string;
229
+ amount: string;
230
+ payTo: string;
231
+ maxTimeoutSeconds: number;
232
+ extra: Record<string, unknown>;
233
+ };
234
+
235
+ type PaymentPayload = {
236
+ x402Version: number;
237
+ resource: ResourceInfo;
238
+ accepted: PaymentRequirements;
239
+ payload: Record<string, unknown>;
240
+ extensions?: Record<string, unknown>;
241
+ };
242
+
243
+ type PaymentRequired = {
244
+ x402Version: number;
245
+ error?: string;
246
+ resource: ResourceInfo;
247
+ accepts: PaymentRequirements[];
248
+ extensions?: Record<string, unknown>;
249
+ };
250
+ ```
251
+
252
+ ## Subpath Exports
253
+
254
+ | Path | Description |
255
+ |------|-------------|
256
+ | `@okxweb3/app-x402-core` | Main entry: `x402Version`, `OKXFacilitatorClient`, `OKXConfig` |
257
+ | `@okxweb3/app-x402-core/client` | Client: `x402Client`, `x402HTTPClient` |
258
+ | `@okxweb3/app-x402-core/server` | Server: `x402ResourceServer`, `x402HTTPResourceServer`, `HTTPFacilitatorClient` |
259
+ | `@okxweb3/app-x402-core/facilitator` | Facilitator: `x402Facilitator`, `OKXFacilitatorClient` |
260
+ | `@okxweb3/app-x402-core/http` | HTTP utilities: encoding/decoding helpers, `x402HTTPResourceServer`, `x402HTTPClient` |
261
+ | `@okxweb3/app-x402-core/types` | Shared type definitions |
262
+ | `@okxweb3/app-x402-core/schemas` | Zod validation schemas |
263
+ | `@okxweb3/app-x402-core/utils` | Utility functions |
264
+
265
+ ## License
266
+
267
+ Apache-2.0
@@ -0,0 +1,59 @@
1
+ import { d as FacilitatorClient, h as SupportedResponse, P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, i as SettleStatusResponse } from './mechanisms-sojpSwWW.js';
2
+
3
+ interface OKXConfig {
4
+ apiKey: string;
5
+ secretKey: string;
6
+ passphrase: string;
7
+ baseUrl?: string;
8
+ /**
9
+ * OKX exact-scheme extension: when true, the settle call tells the facilitator to
10
+ * wait for on-chain confirmation before responding (syncSettle=true in request body).
11
+ * The facilitator then returns status="success" directly (no polling needed).
12
+ * When false (default), the facilitator responds with status="pending" immediately.
13
+ */
14
+ syncSettle?: boolean;
15
+ }
16
+ /**
17
+ * OKX facilitator client implementing the FacilitatorClient interface.
18
+ * Uses HMAC-SHA256 signing per OKX REST API authentication spec.
19
+ */
20
+ declare class OKXFacilitatorClient implements FacilitatorClient {
21
+ private config;
22
+ /**
23
+ *
24
+ * @param config
25
+ */
26
+ constructor(config: OKXConfig);
27
+ /**
28
+ *
29
+ * @param method
30
+ * @param path
31
+ * @param body
32
+ */
33
+ private createHeaders;
34
+ /**
35
+ *
36
+ */
37
+ getSupported(): Promise<SupportedResponse>;
38
+ /**
39
+ *
40
+ * @param payload
41
+ * @param requirements
42
+ */
43
+ verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
44
+ /**
45
+ *
46
+ * @param payload
47
+ * @param requirements
48
+ */
49
+ settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
50
+ /**
51
+ * Query on-chain settlement status by transaction hash.
52
+ *
53
+ * @param txHash - The transaction hash to query
54
+ * @returns Settlement status response
55
+ */
56
+ getSettleStatus(txHash: string): Promise<SettleStatusResponse>;
57
+ }
58
+
59
+ export { type OKXConfig as O, OKXFacilitatorClient as a };
@@ -0,0 +1,320 @@
1
+ import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, j as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-sojpSwWW.js';
2
+
3
+ /**
4
+ * Client Hook Context Interfaces
5
+ */
6
+ interface PaymentCreationContext {
7
+ paymentRequired: PaymentRequired;
8
+ selectedRequirements: PaymentRequirements;
9
+ }
10
+ interface PaymentCreatedContext extends PaymentCreationContext {
11
+ paymentPayload: PaymentPayload;
12
+ }
13
+ interface PaymentCreationFailureContext extends PaymentCreationContext {
14
+ error: Error;
15
+ }
16
+ /**
17
+ * Client Hook Type Definitions
18
+ */
19
+ type BeforePaymentCreationHook = (context: PaymentCreationContext) => Promise<void | {
20
+ abort: true;
21
+ reason: string;
22
+ }>;
23
+ type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>;
24
+ type OnPaymentCreationFailureHook = (context: PaymentCreationFailureContext) => Promise<void | {
25
+ recovered: true;
26
+ payload: PaymentPayload;
27
+ }>;
28
+ type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;
29
+ /**
30
+ * Extension that can enrich payment payloads on the client side.
31
+ *
32
+ * Client extensions are invoked after the scheme creates the base payment payload
33
+ * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612
34
+ * permit signing) to enrich the payload's extensions data.
35
+ */
36
+ interface ClientExtension {
37
+ /**
38
+ * Unique key identifying this extension (e.g., "eip2612GasSponsoring").
39
+ * Must match the extension key used in PaymentRequired.extensions.
40
+ */
41
+ key: string;
42
+ /**
43
+ * Called after payload creation when the extension key is present in
44
+ * paymentRequired.extensions. Allows the extension to enrich the payload
45
+ * with extension-specific data (e.g., signing an EIP-2612 permit).
46
+ *
47
+ * @param paymentPayload - The payment payload to enrich
48
+ * @param paymentRequired - The original PaymentRequired response
49
+ * @returns The enriched payment payload
50
+ */
51
+ enrichPaymentPayload?: (paymentPayload: PaymentPayload, paymentRequired: PaymentRequired) => Promise<PaymentPayload>;
52
+ }
53
+ /**
54
+ * A policy function that filters or transforms payment requirements.
55
+ * Policies are applied in order before the selector chooses the final option.
56
+ *
57
+ * @param x402Version - The x402 protocol version
58
+ * @param paymentRequirements - Array of payment requirements to filter/transform
59
+ * @returns Filtered array of payment requirements
60
+ */
61
+ type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];
62
+ /**
63
+ * Configuration for registering a payment scheme with a specific network
64
+ */
65
+ interface SchemeRegistration {
66
+ /**
67
+ * The network identifier (e.g., 'eip155:196', 'eip155:196')
68
+ */
69
+ network: Network;
70
+ /**
71
+ * The scheme client implementation for this network
72
+ */
73
+ client: SchemeNetworkClient;
74
+ /**
75
+ * The x402 protocol version to use for this scheme
76
+ *
77
+ * @default 2
78
+ */
79
+ x402Version?: number;
80
+ }
81
+ /**
82
+ * Configuration options for the fetch wrapper
83
+ */
84
+ interface x402ClientConfig {
85
+ /**
86
+ * Array of scheme registrations defining which payment methods are supported
87
+ */
88
+ schemes: SchemeRegistration[];
89
+ /**
90
+ * Policies to apply to the client
91
+ */
92
+ policies?: PaymentPolicy[];
93
+ /**
94
+ * Custom payment requirements selector function
95
+ * If not provided, uses the default selector (first available option)
96
+ */
97
+ paymentRequirementsSelector?: SelectPaymentRequirements;
98
+ }
99
+ /**
100
+ * Core client for managing x402 payment schemes and creating payment payloads.
101
+ *
102
+ * Handles registration of payment schemes, policy-based filtering of payment requirements,
103
+ * and creation of payment payloads based on server requirements.
104
+ */
105
+ declare class x402Client {
106
+ private readonly paymentRequirementsSelector;
107
+ private readonly registeredClientSchemes;
108
+ private readonly policies;
109
+ private readonly registeredExtensions;
110
+ private beforePaymentCreationHooks;
111
+ private afterPaymentCreationHooks;
112
+ private onPaymentCreationFailureHooks;
113
+ /**
114
+ * Creates a new x402Client instance.
115
+ *
116
+ * @param paymentRequirementsSelector - Function to select payment requirements from available options
117
+ */
118
+ constructor(paymentRequirementsSelector?: SelectPaymentRequirements);
119
+ /**
120
+ * Creates a new x402Client instance from a configuration object.
121
+ *
122
+ * @param config - The client configuration including schemes, policies, and payment requirements selector
123
+ * @returns A configured x402Client instance
124
+ */
125
+ static fromConfig(config: x402ClientConfig): x402Client;
126
+ /**
127
+ * Registers a scheme client for the current x402 version.
128
+ *
129
+ * @param network - The network to register the client for
130
+ * @param client - The scheme network client to register
131
+ * @returns The x402Client instance for chaining
132
+ */
133
+ register(network: Network, client: SchemeNetworkClient): x402Client;
134
+ /**
135
+ * Registers a policy to filter or transform payment requirements.
136
+ *
137
+ * Policies are applied in order after filtering by registered schemes
138
+ * and before the selector chooses the final payment requirement.
139
+ *
140
+ * @param policy - Function to filter/transform payment requirements
141
+ * @returns The x402Client instance for chaining
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * // Prefer cheaper options
146
+ * client.registerPolicy((version, reqs) =>
147
+ * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
148
+ * );
149
+ *
150
+ * // Prefer specific networks
151
+ * client.registerPolicy((version, reqs) =>
152
+ * reqs.filter(r => r.network.startsWith('eip155:'))
153
+ * );
154
+ * ```
155
+ */
156
+ registerPolicy(policy: PaymentPolicy): x402Client;
157
+ /**
158
+ * Registers a client extension that can enrich payment payloads.
159
+ *
160
+ * Extensions are invoked after the scheme creates the base payload and the
161
+ * payload is wrapped with extensions/resource/accepted data. If the extension's
162
+ * key is present in `paymentRequired.extensions`, the extension's
163
+ * `enrichPaymentPayload` hook is called to modify the payload.
164
+ *
165
+ * @param extension - The client extension to register
166
+ * @returns The x402Client instance for chaining
167
+ */
168
+ registerExtension(extension: ClientExtension): x402Client;
169
+ /**
170
+ * Register a hook to execute before payment payload creation.
171
+ * Can abort creation by returning { abort: true, reason: string }
172
+ *
173
+ * @param hook - The hook function to register
174
+ * @returns The x402Client instance for chaining
175
+ */
176
+ onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client;
177
+ /**
178
+ * Register a hook to execute after successful payment payload creation.
179
+ *
180
+ * @param hook - The hook function to register
181
+ * @returns The x402Client instance for chaining
182
+ */
183
+ onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client;
184
+ /**
185
+ * Register a hook to execute when payment payload creation fails.
186
+ * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
187
+ *
188
+ * @param hook - The hook function to register
189
+ * @returns The x402Client instance for chaining
190
+ */
191
+ onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client;
192
+ /**
193
+ * Creates a payment payload based on a PaymentRequired response.
194
+ *
195
+ * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
196
+ * response and constructs a complete PaymentPayload with the accepted requirements.
197
+ *
198
+ * @param paymentRequired - The PaymentRequired response from the server
199
+ * @returns Promise resolving to the complete payment payload
200
+ */
201
+ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
202
+ /**
203
+ * Merges server-declared extensions with scheme-provided extensions.
204
+ * Scheme extensions overlay on top of server extensions at each key,
205
+ * preserving server-provided schema while overlaying scheme-provided info.
206
+ *
207
+ * @param serverExtensions - Extensions declared by the server in the 402 response
208
+ * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)
209
+ * @returns The merged extensions object, or undefined if both inputs are undefined
210
+ */
211
+ private mergeExtensions;
212
+ /**
213
+ * Enriches a payment payload by calling registered extension hooks.
214
+ * For each extension key present in the PaymentRequired response,
215
+ * invokes the corresponding extension's enrichPaymentPayload callback.
216
+ *
217
+ * @param paymentPayload - The payment payload to enrich with extension data
218
+ * @param paymentRequired - The PaymentRequired response containing extension declarations
219
+ * @returns The enriched payment payload with extension data applied
220
+ */
221
+ private enrichPaymentPayloadWithExtensions;
222
+ /**
223
+ * Selects appropriate payment requirements based on registered clients and policies.
224
+ *
225
+ * Selection process:
226
+ * 1. Filter by registered schemes (network + scheme support)
227
+ * 2. Apply all registered policies in order
228
+ * 3. Use selector to choose final requirement
229
+ *
230
+ * @param x402Version - The x402 protocol version
231
+ * @param paymentRequirements - Array of available payment requirements
232
+ * @returns The selected payment requirements
233
+ */
234
+ private selectPaymentRequirements;
235
+ /**
236
+ * Internal method to register a scheme client.
237
+ *
238
+ * @param x402Version - The x402 protocol version
239
+ * @param network - The network to register the client for
240
+ * @param client - The scheme network client to register
241
+ * @returns The x402Client instance for chaining
242
+ */
243
+ private _registerScheme;
244
+ }
245
+
246
+ /**
247
+ * Context provided to onPaymentRequired hooks.
248
+ */
249
+ interface PaymentRequiredContext {
250
+ paymentRequired: PaymentRequired;
251
+ }
252
+ /**
253
+ * Hook called when a 402 response is received, before payment processing.
254
+ * Return headers to try before payment, or void to proceed directly to payment.
255
+ */
256
+ type PaymentRequiredHook = (context: PaymentRequiredContext) => Promise<{
257
+ headers: Record<string, string>;
258
+ } | void>;
259
+ /**
260
+ * HTTP-specific client for handling x402 payment protocol over HTTP.
261
+ *
262
+ * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality
263
+ * for payment headers and responses while maintaining the builder pattern.
264
+ */
265
+ declare class x402HTTPClient {
266
+ private readonly client;
267
+ private paymentRequiredHooks;
268
+ /**
269
+ * Creates a new x402HTTPClient instance.
270
+ *
271
+ * @param client - The underlying x402Client for payment logic
272
+ */
273
+ constructor(client: x402Client);
274
+ /**
275
+ * Register a hook to handle 402 responses before payment.
276
+ * Hooks run in order; first to return headers wins.
277
+ *
278
+ * @param hook - The hook function to register
279
+ * @returns This instance for chaining
280
+ */
281
+ onPaymentRequired(hook: PaymentRequiredHook): this;
282
+ /**
283
+ * Run hooks and return headers if any hook provides them.
284
+ *
285
+ * @param paymentRequired - The payment required response from the server
286
+ * @returns Headers to use for retry, or null to proceed to payment
287
+ */
288
+ handlePaymentRequired(paymentRequired: PaymentRequired): Promise<Record<string, string> | null>;
289
+ /**
290
+ * Encodes a payment payload into appropriate HTTP headers based on version.
291
+ *
292
+ * @param paymentPayload - The payment payload to encode
293
+ * @returns HTTP headers containing the encoded payment signature
294
+ */
295
+ encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string>;
296
+ /**
297
+ * Extracts payment required information from HTTP response.
298
+ *
299
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
300
+ * @returns The payment required object
301
+ */
302
+ getPaymentRequiredResponse(getHeader: (name: string) => string | null | undefined): PaymentRequired;
303
+ /**
304
+ * Extracts payment settlement response from HTTP headers.
305
+ *
306
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
307
+ * @returns The settlement response object
308
+ */
309
+ getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse;
310
+ /**
311
+ * Creates a payment payload for the given payment requirements.
312
+ * Delegates to the underlying x402Client.
313
+ *
314
+ * @param paymentRequired - The payment required response from the server
315
+ * @returns Promise resolving to the payment payload
316
+ */
317
+ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
318
+ }
319
+
320
+ export { type AfterPaymentCreationHook, type BeforePaymentCreationHook, type ClientExtension, type OnPaymentCreationFailureHook, type PaymentCreatedContext, type PaymentCreationContext, type PaymentCreationFailureContext, type PaymentPolicy, type PaymentRequiredContext, type PaymentRequiredHook, type SchemeRegistration, type SelectPaymentRequirements, x402Client, type x402ClientConfig, x402HTTPClient };