@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
@@ -0,0 +1,763 @@
1
+ interface FacilitatorConfig {
2
+ url?: string;
3
+ createAuthHeaders?: () => Promise<{
4
+ verify: Record<string, string>;
5
+ settle: Record<string, string>;
6
+ supported: Record<string, string>;
7
+ }>;
8
+ }
9
+ /**
10
+ * Interface for facilitator clients
11
+ * Can be implemented for HTTP-based or local facilitators
12
+ */
13
+ interface FacilitatorClient {
14
+ /**
15
+ * Verify a payment with the facilitator
16
+ *
17
+ * @param paymentPayload - The payment to verify
18
+ * @param paymentRequirements - The requirements to verify against
19
+ * @returns Verification response
20
+ */
21
+ verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
22
+ /**
23
+ * Settle a payment with the facilitator
24
+ *
25
+ * @param paymentPayload - The payment to settle
26
+ * @param paymentRequirements - The requirements for settlement
27
+ * @returns Settlement response
28
+ */
29
+ settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
30
+ /**
31
+ * Get supported payment kinds and extensions from the facilitator
32
+ *
33
+ * @returns Supported payment kinds and extensions
34
+ */
35
+ getSupported(): Promise<SupportedResponse>;
36
+ /**
37
+ * Query on-chain settlement status by transaction hash.
38
+ * OKX extension: used for timeout recovery polling.
39
+ *
40
+ * @param txHash - The transaction hash to query
41
+ * @returns Settlement status response
42
+ */
43
+ getSettleStatus?(txHash: string): Promise<SettleStatusResponse>;
44
+ }
45
+ /**
46
+ * HTTP-based client for interacting with x402 facilitator services
47
+ * Handles HTTP communication with facilitator endpoints
48
+ */
49
+ declare class HTTPFacilitatorClient implements FacilitatorClient {
50
+ readonly url: string;
51
+ private readonly _createAuthHeaders?;
52
+ /**
53
+ * Creates a new HTTPFacilitatorClient instance.
54
+ *
55
+ * @param config - Configuration options for the facilitator client
56
+ */
57
+ constructor(config?: FacilitatorConfig);
58
+ /**
59
+ * Verify a payment with the facilitator
60
+ *
61
+ * @param paymentPayload - The payment to verify
62
+ * @param paymentRequirements - The requirements to verify against
63
+ * @returns Verification response
64
+ */
65
+ verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
66
+ /**
67
+ * Settle a payment with the facilitator
68
+ *
69
+ * @param paymentPayload - The payment to settle
70
+ * @param paymentRequirements - The requirements for settlement
71
+ * @returns Settlement response
72
+ */
73
+ settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
74
+ /**
75
+ * Get supported payment kinds and extensions from the facilitator.
76
+ * Retries with exponential backoff on 429 rate limit errors.
77
+ *
78
+ * @returns Supported payment kinds and extensions
79
+ */
80
+ getSupported(): Promise<SupportedResponse>;
81
+ /**
82
+ * Query on-chain settlement status by transaction hash.
83
+ *
84
+ * @param txHash - The transaction hash to query
85
+ * @returns Settlement status response
86
+ */
87
+ getSettleStatus(txHash: string): Promise<SettleStatusResponse>;
88
+ /**
89
+ * Creates authentication headers for a specific path.
90
+ *
91
+ * @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
92
+ * @returns An object containing the authentication headers for the specified path
93
+ */
94
+ createAuthHeaders(path: string): Promise<{
95
+ headers: Record<string, string>;
96
+ }>;
97
+ /**
98
+ * Helper to convert objects to JSON-safe format.
99
+ * Handles BigInt and other non-JSON types.
100
+ *
101
+ * @param obj - The object to convert
102
+ * @returns The JSON-safe representation of the object
103
+ */
104
+ private toJsonSafe;
105
+ }
106
+
107
+ /** Default poll interval for settle/status queries (1 second). */
108
+ declare const DEFAULT_POLL_INTERVAL_MS = 1000;
109
+ /** Default poll deadline for settle/status queries (5 seconds). */
110
+ declare const DEFAULT_POLL_DEADLINE_MS = 5000;
111
+ /** Result of polling `GET /settle/status`. */
112
+ type PollResult = "success" | "failed" | "timeout";
113
+ /**
114
+ * Configuration for a protected resource
115
+ * Only contains payment-specific configuration, not resource metadata
116
+ */
117
+ interface ResourceConfig {
118
+ scheme: string;
119
+ payTo: string;
120
+ price: Price;
121
+ network: Network;
122
+ maxTimeoutSeconds?: number;
123
+ extra?: Record<string, unknown>;
124
+ }
125
+ /**
126
+ * Lifecycle Hook Context Interfaces
127
+ */
128
+ interface PaymentRequiredContext {
129
+ requirements: PaymentRequirements[];
130
+ resourceInfo: ResourceInfo;
131
+ error?: string;
132
+ paymentRequiredResponse: PaymentRequired;
133
+ transportContext?: unknown;
134
+ }
135
+ interface VerifyContext {
136
+ paymentPayload: PaymentPayload;
137
+ requirements: PaymentRequirements;
138
+ }
139
+ interface VerifyResultContext extends VerifyContext {
140
+ result: VerifyResponse;
141
+ }
142
+ interface VerifyFailureContext extends VerifyContext {
143
+ error: Error;
144
+ }
145
+ interface SettleContext {
146
+ paymentPayload: PaymentPayload;
147
+ requirements: PaymentRequirements;
148
+ }
149
+ interface SettleResultContext extends SettleContext {
150
+ result: SettleResponse;
151
+ transportContext?: unknown;
152
+ }
153
+ interface SettleFailureContext extends SettleContext {
154
+ error: Error;
155
+ }
156
+ /**
157
+ * Lifecycle Hook Type Definitions
158
+ */
159
+ type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
160
+ abort: true;
161
+ reason: string;
162
+ message?: string;
163
+ }>;
164
+ type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;
165
+ type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
166
+ recovered: true;
167
+ result: VerifyResponse;
168
+ }>;
169
+ type BeforeSettleHook = (context: SettleContext) => Promise<void | {
170
+ abort: true;
171
+ reason: string;
172
+ message?: string;
173
+ }>;
174
+ type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
175
+ type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
176
+ recovered: true;
177
+ result: SettleResponse;
178
+ }>;
179
+ /**
180
+ * Optional overrides for settlement parameters.
181
+ * Used to support partial settlement (e.g., upto scheme billing by actual usage).
182
+ *
183
+ * Note: Overriding the amount to a value different from the agreed-upon
184
+ * `PaymentRequirements.amount` is only valid in schemes that explicitly support
185
+ * partial settlement, such as the `upto` scheme. Using this with standard
186
+ * x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.
187
+ */
188
+ interface SettlementOverrides {
189
+ /**
190
+ * Amount to settle. Supports three formats:
191
+ *
192
+ * - **Raw atomic units** — e.g., `"1000"` settles exactly 1000 atomic units.
193
+ * - **Percent** — e.g., `"50%"` settles 50% of `PaymentRequirements.amount`.
194
+ * Supports up to two decimal places (e.g., `"33.33%"`). The result is floored
195
+ * to the nearest atomic unit.
196
+ * - **Dollar price** — e.g., `"$0.05"` converts a USD-denominated price to
197
+ * atomic units. Uses `PaymentRequirements.extra.decimals` if set; otherwise
198
+ * defaults to 6 (standard for USDC stablecoins). The result is rounded to
199
+ * the nearest atomic unit.
200
+ *
201
+ * The resolved amount must be <= the authorized maximum in `PaymentRequirements`.
202
+ *
203
+ * Note: Setting this to an amount other than `PaymentRequirements.amount` is
204
+ * only valid in schemes that support partial settlement, such as `upto`.
205
+ */
206
+ amount?: string;
207
+ }
208
+ /**
209
+ * Core x402 protocol server for resource protection
210
+ * Transport-agnostic implementation of the x402 payment protocol
211
+ */
212
+ declare class x402ResourceServer {
213
+ private facilitatorClients;
214
+ private registeredServerSchemes;
215
+ private supportedResponsesMap;
216
+ private facilitatorClientsMap;
217
+ private registeredExtensions;
218
+ private beforeVerifyHooks;
219
+ private afterVerifyHooks;
220
+ private onVerifyFailureHooks;
221
+ private beforeSettleHooks;
222
+ private afterSettleHooks;
223
+ private onSettleFailureHooks;
224
+ /**
225
+ * Creates a new x402ResourceServer instance.
226
+ *
227
+ * @param facilitatorClients - Optional facilitator client(s) for payment processing
228
+ */
229
+ constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
230
+ /**
231
+ * Register a scheme/network server implementation.
232
+ *
233
+ * @param network - The network identifier
234
+ * @param server - The scheme/network server implementation
235
+ * @returns The x402ResourceServer instance for chaining
236
+ */
237
+ register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
238
+ /**
239
+ * Check if a scheme is registered for a given network.
240
+ *
241
+ * @param network - The network identifier
242
+ * @param scheme - The payment scheme name
243
+ * @returns True if the scheme is registered for the network, false otherwise
244
+ */
245
+ hasRegisteredScheme(network: Network, scheme: string): boolean;
246
+ /**
247
+ * Registers a resource service extension that can enrich extension declarations.
248
+ *
249
+ * @param extension - The extension to register
250
+ * @returns The x402ResourceServer instance for chaining
251
+ */
252
+ registerExtension(extension: ResourceServerExtension): this;
253
+ /**
254
+ * Check if an extension is registered.
255
+ *
256
+ * @param key - The extension key
257
+ * @returns True if the extension is registered
258
+ */
259
+ hasExtension(key: string): boolean;
260
+ /**
261
+ * Get all registered extensions.
262
+ *
263
+ * @returns Array of registered extensions
264
+ */
265
+ getExtensions(): ResourceServerExtension[];
266
+ /**
267
+ * Enriches declared extensions using registered extension hooks.
268
+ *
269
+ * @param declaredExtensions - Extensions declared on the route
270
+ * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
271
+ * @returns Enriched extensions map
272
+ */
273
+ enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
274
+ /**
275
+ * Register a hook to execute before payment verification.
276
+ * Can abort verification by returning { abort: true, reason: string }
277
+ *
278
+ * @param hook - The hook function to register
279
+ * @returns The x402ResourceServer instance for chaining
280
+ */
281
+ onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
282
+ /**
283
+ * Register a hook to execute after successful payment verification.
284
+ *
285
+ * @param hook - The hook function to register
286
+ * @returns The x402ResourceServer instance for chaining
287
+ */
288
+ onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
289
+ /**
290
+ * Register a hook to execute when payment verification fails.
291
+ * Can recover from failure by returning { recovered: true, result: VerifyResponse }
292
+ *
293
+ * @param hook - The hook function to register
294
+ * @returns The x402ResourceServer instance for chaining
295
+ */
296
+ onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
297
+ /**
298
+ * Register a hook to execute before payment settlement.
299
+ * Can abort settlement by returning { abort: true, reason: string }
300
+ *
301
+ * @param hook - The hook function to register
302
+ * @returns The x402ResourceServer instance for chaining
303
+ */
304
+ onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
305
+ /**
306
+ * Register a hook to execute after successful payment settlement.
307
+ *
308
+ * @param hook - The hook function to register
309
+ * @returns The x402ResourceServer instance for chaining
310
+ */
311
+ onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
312
+ /**
313
+ * Register a hook to execute when payment settlement fails.
314
+ * Can recover from failure by returning { recovered: true, result: SettleResponse }
315
+ *
316
+ * @param hook - The hook function to register
317
+ * @returns The x402ResourceServer instance for chaining
318
+ */
319
+ onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
320
+ /**
321
+ * Initialize by fetching supported kinds from all facilitators
322
+ * Creates mappings for supported responses and facilitator clients
323
+ * Earlier facilitators in the array get precedence
324
+ */
325
+ initialize(): Promise<void>;
326
+ /**
327
+ * Get supported kind for a specific version, network, and scheme
328
+ *
329
+ * @param x402Version - The x402 version
330
+ * @param network - The network identifier
331
+ * @param scheme - The payment scheme
332
+ * @returns The supported kind or undefined if not found
333
+ */
334
+ getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
335
+ /**
336
+ * Get facilitator extensions for a specific version, network, and scheme
337
+ *
338
+ * @param x402Version - The x402 version
339
+ * @param network - The network identifier
340
+ * @param scheme - The payment scheme
341
+ * @returns The facilitator extensions or empty array if not found
342
+ */
343
+ getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
344
+ /**
345
+ * Build payment requirements for a protected resource
346
+ *
347
+ * @param resourceConfig - Configuration for the protected resource
348
+ * @returns Array of payment requirements
349
+ */
350
+ buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
351
+ /**
352
+ * Build payment requirements from multiple payment options
353
+ * This method handles resolving dynamic payTo/price functions and builds requirements for each option
354
+ *
355
+ * @param paymentOptions - Array of payment options to convert
356
+ * @param context - HTTP request context for resolving dynamic functions
357
+ * @returns Array of payment requirements (one per option)
358
+ */
359
+ buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
360
+ scheme: string;
361
+ payTo: string | ((context: TContext) => string | Promise<string>);
362
+ price: Price | ((context: TContext) => Price | Promise<Price>);
363
+ network: Network;
364
+ maxTimeoutSeconds?: number;
365
+ extra?: Record<string, unknown>;
366
+ }>, context: TContext): Promise<PaymentRequirements[]>;
367
+ /**
368
+ * Create a payment required response
369
+ *
370
+ * @param requirements - Payment requirements
371
+ * @param resourceInfo - Resource information
372
+ * @param error - Error message
373
+ * @param extensions - Optional declared extensions (for per-key enrichment)
374
+ * @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
375
+ * @returns Payment required response object
376
+ */
377
+ createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<PaymentRequired>;
378
+ /**
379
+ * Verify a payment against requirements
380
+ *
381
+ * @param paymentPayload - The payment payload to verify
382
+ * @param requirements - The payment requirements
383
+ * @returns Verification response
384
+ */
385
+ verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
386
+ /**
387
+ * Settle a verified payment
388
+ *
389
+ * @param paymentPayload - The payment payload to settle
390
+ * @param requirements - The payment requirements
391
+ * @param declaredExtensions - Optional declared extensions (for per-key enrichment)
392
+ * @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
393
+ * @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
394
+ * @returns Settlement response
395
+ */
396
+ settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown, settlementOverrides?: SettlementOverrides): Promise<SettleResponse>;
397
+ /**
398
+ * Find matching payment requirements for a payment
399
+ *
400
+ * @param availableRequirements - Array of available payment requirements
401
+ * @param paymentPayload - The payment payload
402
+ * @returns Matching payment requirements or undefined
403
+ */
404
+ findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
405
+ /**
406
+ * Process a payment request
407
+ *
408
+ * @param paymentPayload - Optional payment payload if provided
409
+ * @param resourceConfig - Configuration for the protected resource
410
+ * @param resourceInfo - Information about the resource being accessed
411
+ * @param extensions - Optional extensions to include in the response
412
+ * @returns Processing result
413
+ */
414
+ processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>): Promise<{
415
+ success: boolean;
416
+ requiresPayment?: PaymentRequired;
417
+ verificationResult?: VerifyResponse;
418
+ settlementResult?: SettleResponse;
419
+ error?: string;
420
+ }>;
421
+ /**
422
+ * Poll `GET /settle/status` until a terminal state is reached or deadline expires.
423
+ *
424
+ * Used when settle returns `status="timeout"` (exact + syncSettle=true).
425
+ * Mirrors Rust: `X402ResourceServer::poll_settle_status`.
426
+ *
427
+ * @param txHash - Transaction hash to query
428
+ * @param paymentPayload - The payment payload (used to find the correct facilitator client)
429
+ * @param requirements - The payment requirements (used to find the correct facilitator client)
430
+ * @param pollDeadlineMs - Max time to poll in ms (default 5000)
431
+ * @returns Poll result: "success", "failed", or "timeout"
432
+ */
433
+ pollSettleStatus(txHash: string, paymentPayload: PaymentPayload, requirements: PaymentRequirements, pollDeadlineMs?: number): Promise<PollResult>;
434
+ /**
435
+ * Get facilitator client for a specific version, network, and scheme
436
+ *
437
+ * @param x402Version - The x402 version
438
+ * @param network - The network identifier
439
+ * @param scheme - The payment scheme
440
+ * @returns The facilitator client or undefined if not found
441
+ */
442
+ private getFacilitatorClient;
443
+ }
444
+
445
+ /**
446
+ * Base interface for facilitator extensions.
447
+ * Extensions registered with x402Facilitator are stored by key and made
448
+ * available to mechanism implementations via FacilitatorContext.
449
+ *
450
+ * Specific extensions extend this with additional capabilities:
451
+ *
452
+ * @example
453
+ * interface Erc20GasSponsoringExtension extends FacilitatorExtension {
454
+ * batchSigner: SmartWalletBatchSigner;
455
+ * }
456
+ */
457
+ interface FacilitatorExtension {
458
+ key: string;
459
+ }
460
+ interface ResourceServerExtension {
461
+ key: string;
462
+ /**
463
+ * Enrich extension declaration with extension-specific data.
464
+ *
465
+ * @param declaration - Extension declaration from route config
466
+ * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
467
+ * @returns Enriched extension declaration
468
+ */
469
+ enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
470
+ /**
471
+ * Called when generating a 402 PaymentRequired response.
472
+ * Return extension data to add to extensions[key], or undefined to skip.
473
+ *
474
+ * @param declaration - Extension declaration from route config
475
+ * @param context - PaymentRequired context containing response, requirements, and optional transportContext
476
+ * @returns Extension data to add to response.extensions[key]
477
+ */
478
+ enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
479
+ /**
480
+ * Called after successful payment settlement.
481
+ * Return extension data to add to response.extensions[key], or undefined to skip.
482
+ *
483
+ * @param declaration - Extension declaration from route config
484
+ * @param context - Settlement result context containing payment payload, requirements, result and optional transportContext
485
+ * @returns Extension data to add to response.extensions[key]
486
+ */
487
+ enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
488
+ }
489
+
490
+ type Network = `${string}:${string}`;
491
+ type Money = string | number;
492
+ type AssetAmount = {
493
+ asset: string;
494
+ amount: string;
495
+ extra?: Record<string, unknown>;
496
+ };
497
+ type Price = Money | AssetAmount;
498
+
499
+ interface ResourceInfo {
500
+ url: string;
501
+ description?: string;
502
+ mimeType?: string;
503
+ }
504
+ type PaymentRequirements = {
505
+ scheme: string;
506
+ network: Network;
507
+ asset: string;
508
+ amount: string;
509
+ payTo: string;
510
+ maxTimeoutSeconds: number;
511
+ extra: Record<string, unknown>;
512
+ };
513
+ type PaymentRequired = {
514
+ x402Version: number;
515
+ error?: string;
516
+ resource: ResourceInfo;
517
+ accepts: PaymentRequirements[];
518
+ extensions?: Record<string, unknown>;
519
+ };
520
+ type PaymentPayload = {
521
+ x402Version: number;
522
+ resource?: ResourceInfo;
523
+ accepted: PaymentRequirements;
524
+ payload: Record<string, unknown>;
525
+ extensions?: Record<string, unknown>;
526
+ };
527
+
528
+ type VerifyRequest = {
529
+ x402Version: number;
530
+ paymentPayload: PaymentPayload;
531
+ paymentRequirements: PaymentRequirements;
532
+ };
533
+ type VerifyResponse = {
534
+ isValid: boolean;
535
+ invalidReason?: string;
536
+ invalidMessage?: string;
537
+ payer?: string;
538
+ extensions?: Record<string, unknown>;
539
+ };
540
+ type SettleRequest = {
541
+ x402Version: number;
542
+ paymentPayload: PaymentPayload;
543
+ paymentRequirements: PaymentRequirements;
544
+ };
545
+ type SettleResponse = {
546
+ success: boolean;
547
+ /** OKX extension: pending (async, Seller trusts Facilitator), success (immediate), timeout (on-chain timed out) */
548
+ status?: "pending" | "success" | "timeout";
549
+ errorReason?: string;
550
+ errorMessage?: string;
551
+ payer?: string;
552
+ transaction: string;
553
+ network: Network;
554
+ /** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */
555
+ amount?: string;
556
+ extensions?: Record<string, unknown>;
557
+ };
558
+ type SupportedKind = {
559
+ x402Version: number;
560
+ scheme: string;
561
+ network: Network;
562
+ extra?: Record<string, unknown>;
563
+ };
564
+ type SupportedResponse = {
565
+ kinds: SupportedKind[];
566
+ extensions: string[];
567
+ signers: Record<string, string[]>;
568
+ };
569
+ /**
570
+ * Response from `GET /settle/status?txHash=...`.
571
+ * OKX extension: query on-chain settlement status by transaction hash.
572
+ */
573
+ type SettleStatusResponse = {
574
+ success: boolean;
575
+ status?: "pending" | "success" | "failed";
576
+ errorReason?: string;
577
+ errorMessage?: string;
578
+ payer?: string;
579
+ transaction?: string;
580
+ network?: Network;
581
+ };
582
+ /**
583
+ * Error thrown when payment verification fails.
584
+ */
585
+ declare class VerifyError extends Error {
586
+ readonly invalidReason?: string;
587
+ readonly invalidMessage?: string;
588
+ readonly payer?: string;
589
+ readonly statusCode: number;
590
+ /**
591
+ * Creates a VerifyError from a failed verification response.
592
+ *
593
+ * @param statusCode - HTTP status code from the facilitator
594
+ * @param response - The verify response containing error details
595
+ */
596
+ constructor(statusCode: number, response: VerifyResponse);
597
+ }
598
+ /**
599
+ * Error thrown when payment settlement fails.
600
+ */
601
+ declare class SettleError extends Error {
602
+ readonly errorReason?: string;
603
+ readonly errorMessage?: string;
604
+ readonly payer?: string;
605
+ readonly transaction: string;
606
+ readonly network: Network;
607
+ readonly statusCode: number;
608
+ /**
609
+ * Creates a SettleError from a failed settlement response.
610
+ *
611
+ * @param statusCode - HTTP status code from the facilitator
612
+ * @param response - The settle response containing error details
613
+ */
614
+ constructor(statusCode: number, response: SettleResponse);
615
+ }
616
+ /**
617
+ * Error thrown when a facilitator returns malformed success payload data.
618
+ */
619
+ declare class FacilitatorResponseError extends Error {
620
+ /**
621
+ * Creates a FacilitatorResponseError for malformed facilitator responses.
622
+ *
623
+ * @param message - The boundary error message
624
+ */
625
+ constructor(message: string);
626
+ }
627
+ /**
628
+ * Walks an error cause chain to find the first facilitator response error.
629
+ *
630
+ * @param error - The thrown value to inspect
631
+ * @returns The nested facilitator response error, if present
632
+ */
633
+ declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
634
+
635
+ /**
636
+ * Money parser function that converts a numeric amount to an AssetAmount
637
+ * Receives the amount as a decimal number (e.g., 1.50 for $1.50)
638
+ * Returns null to indicate "cannot handle this amount", causing fallback to next parser
639
+ * Always returns a Promise for consistency - use async/await
640
+ *
641
+ * @param amount - The decimal amount (e.g., 1.50)
642
+ * @param network - The network identifier for context
643
+ * @returns AssetAmount or null to try next parser
644
+ */
645
+ type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
646
+ /**
647
+ * Result of createPaymentPayload - the core payload fields.
648
+ * Contains the x402 version, scheme-specific payload data, and optional extension data.
649
+ * Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
650
+ * with server-declared extensions in the final PaymentPayload.
651
+ *
652
+ * acceptedExtraOverrides: OKX extension — key-value pairs to merge into
653
+ * paymentPayload.accepted.extra before sending to the facilitator.
654
+ * Used by aggr_deferred to inject sessionCert into accepted.extra per OKX spec.
655
+ */
656
+ type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
657
+ extensions?: Record<string, unknown>;
658
+ acceptedExtraOverrides?: Record<string, unknown>;
659
+ };
660
+ /**
661
+ * Context passed to scheme's createPaymentPayload for extensions awareness.
662
+ * Contains the server-declared extensions from PaymentRequired so the scheme
663
+ * can check which extensions are advertised and respond accordingly.
664
+ */
665
+ interface PaymentPayloadContext {
666
+ extensions?: Record<string, unknown>;
667
+ }
668
+ interface SchemeNetworkClient {
669
+ readonly scheme: string;
670
+ createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
671
+ }
672
+ /**
673
+ * Context passed to SchemeNetworkFacilitator.verify/settle, providing
674
+ * access to registered facilitator extensions. Mechanism implementations
675
+ * use this to retrieve extension-provided capabilities (e.g., a batch signer).
676
+ */
677
+ interface FacilitatorContext {
678
+ getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
679
+ }
680
+ interface SchemeNetworkFacilitator {
681
+ readonly scheme: string;
682
+ /**
683
+ * CAIP family pattern that this facilitator supports.
684
+ * Used to group signers by blockchain family in the supported response.
685
+ *
686
+ * @example
687
+ * // EVM facilitators
688
+ * readonly caipFamily = "eip155:*";
689
+ */
690
+ readonly caipFamily: string;
691
+ /**
692
+ * Get mechanism-specific extra data needed for the supported kinds endpoint.
693
+ * This method is called when building the facilitator's supported response.
694
+ *
695
+ * @param network - The network identifier for context
696
+ * @returns Extra data object or undefined if no extra data is needed
697
+ *
698
+ * @example
699
+ * // EVM schemes return undefined (no extra data needed)
700
+ * getExtra(network: Network): undefined {
701
+ * return undefined;
702
+ * }
703
+ */
704
+ getExtra(network: Network): Record<string, unknown> | undefined;
705
+ /**
706
+ * Get signer addresses used by this facilitator for a given network.
707
+ * These are included in the supported response to help clients understand
708
+ * which addresses might sign/pay for transactions.
709
+ *
710
+ * Supports multiple addresses for load balancing, key rotation, and high availability.
711
+ *
712
+ * @param network - The network identifier
713
+ * @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
714
+ *
715
+ * @example
716
+ * // EVM facilitator
717
+ * getSigners(network: string): string[] {
718
+ * return [...this.signer.getAddresses()];
719
+ * }
720
+ */
721
+ getSigners(network: string): string[];
722
+ verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
723
+ settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
724
+ }
725
+ interface SchemeNetworkServer {
726
+ readonly scheme: string;
727
+ /**
728
+ * Convert a user-friendly price to the scheme's specific amount and asset format
729
+ * Always returns a Promise for consistency
730
+ *
731
+ * @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
732
+ * @param network - The network identifier for context
733
+ * @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
734
+ *
735
+ * @example
736
+ * // For XLayer with USDT0:
737
+ * await parsePrice("$0.10", "eip155:196") => { amount: "100000", asset: "0x779ded0c9e1022225f8e0630b35a9b54be713736" }
738
+ *
739
+ * // For custom schemes:
740
+ * await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
741
+ */
742
+ parsePrice(price: Price, network: Network): Promise<AssetAmount>;
743
+ /**
744
+ * Build payment requirements for this scheme/network combination
745
+ *
746
+ * @param paymentRequirements - Base payment requirements with amount/asset already set
747
+ * @param supportedKind - The supported kind from facilitator's /supported endpoint
748
+ * @param supportedKind.x402Version - The x402 version
749
+ * @param supportedKind.scheme - The payment scheme
750
+ * @param supportedKind.network - The network identifier
751
+ * @param supportedKind.extra - Optional extra metadata
752
+ * @param facilitatorExtensions - Extensions supported by the facilitator
753
+ * @returns Enhanced payment requirements ready to be sent to clients
754
+ */
755
+ enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
756
+ x402Version: number;
757
+ scheme: string;
758
+ network: Network;
759
+ extra?: Record<string, unknown>;
760
+ }, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
761
+ }
762
+
763
+ export { type AssetAmount as A, VerifyError as B, type VerifyRequest as C, DEFAULT_POLL_DEADLINE_MS as D, type FacilitatorExtension as F, HTTPFacilitatorClient as H, type Money as M, type Network as N, type PaymentPayload as P, type ResourceConfig as R, type SettleResponse as S, type VerifyResponse as V, type PaymentRequirements as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type FacilitatorClient as d, type FacilitatorConfig as e, FacilitatorResponseError as f, getFacilitatorResponseError as g, type SupportedResponse as h, type SettleStatusResponse as i, type SchemeNetworkClient as j, DEFAULT_POLL_INTERVAL_MS as k, type PollResult as l, type SettleResultContext as m, type SettlementOverrides as n, type Price as o, type FacilitatorContext as p, type MoneyParser as q, type PaymentPayloadContext as r, type PaymentPayloadResult as s, type PaymentRequiredContext as t, type ResourceInfo as u, type ResourceServerExtension as v, type SchemeNetworkServer as w, x402ResourceServer as x, SettleError as y, type SettleRequest as z };