@bankofai/x402-core 1.0.0-beta.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.
Files changed (72) hide show
  1. package/README.md +294 -0
  2. package/dist/cjs/client/index.d.ts +149 -0
  3. package/dist/cjs/client/index.js +909 -0
  4. package/dist/cjs/client/index.js.map +1 -0
  5. package/dist/cjs/facilitator/index.d.ts +206 -0
  6. package/dist/cjs/facilitator/index.js +431 -0
  7. package/dist/cjs/facilitator/index.js.map +1 -0
  8. package/dist/cjs/http/index.d.ts +50 -0
  9. package/dist/cjs/http/index.js +1452 -0
  10. package/dist/cjs/http/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +3 -0
  12. package/dist/cjs/index.js +31 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/schemas/index.d.ts +891 -0
  15. package/dist/cjs/schemas/index.js +216 -0
  16. package/dist/cjs/schemas/index.js.map +1 -0
  17. package/dist/cjs/server/index.d.ts +79 -0
  18. package/dist/cjs/server/index.js +2568 -0
  19. package/dist/cjs/server/index.js.map +1 -0
  20. package/dist/cjs/types/index.d.ts +1 -0
  21. package/dist/cjs/types/index.js +97 -0
  22. package/dist/cjs/types/index.js.map +1 -0
  23. package/dist/cjs/types/v1/index.d.ts +1 -0
  24. package/dist/cjs/types/v1/index.js +19 -0
  25. package/dist/cjs/types/v1/index.js.map +1 -0
  26. package/dist/cjs/utils/index.d.ts +77 -0
  27. package/dist/cjs/utils/index.js +179 -0
  28. package/dist/cjs/utils/index.js.map +1 -0
  29. package/dist/cjs/x402Client-BgegfQgE.d.ts +1807 -0
  30. package/dist/cjs/x402Client-TQHctrG7.d.ts +1807 -0
  31. package/dist/esm/chunk-ABS7D6VX.mjs +145 -0
  32. package/dist/esm/chunk-ABS7D6VX.mjs.map +1 -0
  33. package/dist/esm/chunk-AGOUMC4P.mjs +68 -0
  34. package/dist/esm/chunk-AGOUMC4P.mjs.map +1 -0
  35. package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
  36. package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
  37. package/dist/esm/chunk-FPXAE3OS.mjs +161 -0
  38. package/dist/esm/chunk-FPXAE3OS.mjs.map +1 -0
  39. package/dist/esm/chunk-IL77TMJL.mjs +1275 -0
  40. package/dist/esm/chunk-IL77TMJL.mjs.map +1 -0
  41. package/dist/esm/chunk-VE37GDG2.mjs +7 -0
  42. package/dist/esm/chunk-VE37GDG2.mjs.map +1 -0
  43. package/dist/esm/client/index.d.mts +149 -0
  44. package/dist/esm/client/index.mjs +504 -0
  45. package/dist/esm/client/index.mjs.map +1 -0
  46. package/dist/esm/facilitator/index.d.mts +206 -0
  47. package/dist/esm/facilitator/index.mjs +399 -0
  48. package/dist/esm/facilitator/index.mjs.map +1 -0
  49. package/dist/esm/http/index.d.mts +50 -0
  50. package/dist/esm/http/index.mjs +35 -0
  51. package/dist/esm/http/index.mjs.map +1 -0
  52. package/dist/esm/index.d.mts +3 -0
  53. package/dist/esm/index.mjs +8 -0
  54. package/dist/esm/index.mjs.map +1 -0
  55. package/dist/esm/schemas/index.d.mts +891 -0
  56. package/dist/esm/schemas/index.mjs +70 -0
  57. package/dist/esm/schemas/index.mjs.map +1 -0
  58. package/dist/esm/server/index.d.mts +79 -0
  59. package/dist/esm/server/index.mjs +1318 -0
  60. package/dist/esm/server/index.mjs.map +1 -0
  61. package/dist/esm/types/index.d.mts +1 -0
  62. package/dist/esm/types/index.mjs +14 -0
  63. package/dist/esm/types/index.mjs.map +1 -0
  64. package/dist/esm/types/v1/index.d.mts +1 -0
  65. package/dist/esm/types/v1/index.mjs +1 -0
  66. package/dist/esm/types/v1/index.mjs.map +1 -0
  67. package/dist/esm/utils/index.d.mts +77 -0
  68. package/dist/esm/utils/index.mjs +28 -0
  69. package/dist/esm/utils/index.mjs.map +1 -0
  70. package/dist/esm/x402Client-BgegfQgE.d.mts +1807 -0
  71. package/dist/esm/x402Client-TQHctrG7.d.mts +1807 -0
  72. package/package.json +142 -0
@@ -0,0 +1,1807 @@
1
+ type PaymentRequirementsV1 = {
2
+ scheme: string;
3
+ network: Network;
4
+ maxAmountRequired: string;
5
+ resource: string;
6
+ description: string;
7
+ mimeType: string;
8
+ outputSchema: Record<string, unknown>;
9
+ payTo: string;
10
+ maxTimeoutSeconds: number;
11
+ asset: string;
12
+ extra: Record<string, unknown>;
13
+ };
14
+ type PaymentRequiredV1 = {
15
+ x402Version: 1;
16
+ error?: string;
17
+ accepts: PaymentRequirementsV1[];
18
+ };
19
+ type PaymentPayloadV1 = {
20
+ x402Version: 1;
21
+ scheme: string;
22
+ network: Network;
23
+ payload: Record<string, unknown>;
24
+ };
25
+ type VerifyRequestV1 = {
26
+ x402Version: number;
27
+ paymentPayload: PaymentPayloadV1;
28
+ paymentRequirements: PaymentRequirementsV1;
29
+ };
30
+ type SettleRequestV1 = {
31
+ x402Version: number;
32
+ paymentPayload: PaymentPayloadV1;
33
+ paymentRequirements: PaymentRequirementsV1;
34
+ };
35
+ type SettleResponseV1 = {
36
+ success: boolean;
37
+ errorReason?: string;
38
+ errorMessage?: string;
39
+ payer?: string;
40
+ transaction: string;
41
+ network: Network;
42
+ };
43
+ type SupportedResponseV1 = {
44
+ kinds: {
45
+ x402Version: number;
46
+ scheme: string;
47
+ network: Network;
48
+ extra?: Record<string, unknown>;
49
+ }[];
50
+ };
51
+
52
+ /**
53
+ * Recursive readonly for hook contexts so accidental in-place mutation is visible at compile time.
54
+ * (Runtime mutation is still possible via other references; see extension enrich validation.)
55
+ */
56
+ type DeepReadonly<T> = T extends (infer U)[] ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
57
+ readonly [K in keyof T]: DeepReadonly<T[K]>;
58
+ } : T;
59
+
60
+ interface FacilitatorConfig {
61
+ url?: string;
62
+ createAuthHeaders?: () => Promise<{
63
+ verify: Record<string, string>;
64
+ settle: Record<string, string>;
65
+ supported: Record<string, string>;
66
+ bazaar?: Record<string, string>;
67
+ }>;
68
+ }
69
+ /**
70
+ * Interface for facilitator clients
71
+ * Can be implemented for HTTP-based or local facilitators
72
+ */
73
+ interface FacilitatorClient {
74
+ /**
75
+ * Verify a payment with the facilitator
76
+ *
77
+ * @param paymentPayload - The payment to verify
78
+ * @param paymentRequirements - The requirements to verify against
79
+ * @returns Verification response
80
+ */
81
+ verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
82
+ /**
83
+ * Settle a payment with the facilitator
84
+ *
85
+ * @param paymentPayload - The payment to settle
86
+ * @param paymentRequirements - The requirements for settlement
87
+ * @returns Settlement response
88
+ */
89
+ settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
90
+ /**
91
+ * Get supported payment kinds and extensions from the facilitator
92
+ *
93
+ * @returns Supported payment kinds and extensions
94
+ */
95
+ getSupported(): Promise<SupportedResponse>;
96
+ }
97
+ /**
98
+ * HTTP-based client for interacting with x402 facilitator services
99
+ * Handles HTTP communication with facilitator endpoints
100
+ */
101
+ declare class HTTPFacilitatorClient implements FacilitatorClient {
102
+ readonly url: string;
103
+ private readonly _createAuthHeaders?;
104
+ /**
105
+ * Creates a new HTTPFacilitatorClient instance.
106
+ *
107
+ * @param config - Configuration options for the facilitator client
108
+ */
109
+ constructor(config?: FacilitatorConfig);
110
+ /**
111
+ * Verify a payment with the facilitator
112
+ *
113
+ * @param paymentPayload - The payment to verify
114
+ * @param paymentRequirements - The requirements to verify against
115
+ * @returns Verification response
116
+ */
117
+ verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
118
+ /**
119
+ * Settle a payment with the facilitator
120
+ *
121
+ * @param paymentPayload - The payment to settle
122
+ * @param paymentRequirements - The requirements for settlement
123
+ * @returns Settlement response
124
+ */
125
+ settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
126
+ /**
127
+ * Get supported payment kinds and extensions from the facilitator.
128
+ * Retries with exponential backoff on 429 rate limit errors.
129
+ *
130
+ * @returns Supported payment kinds and extensions
131
+ */
132
+ getSupported(): Promise<SupportedResponse>;
133
+ /**
134
+ * Creates authentication headers for a specific path.
135
+ *
136
+ * @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
137
+ * @returns An object containing the authentication headers for the specified path
138
+ */
139
+ createAuthHeaders(path: string): Promise<{
140
+ headers: Record<string, string>;
141
+ }>;
142
+ /**
143
+ * Helper to convert objects to JSON-safe format.
144
+ * Handles BigInt and other non-JSON types.
145
+ *
146
+ * @param obj - The object to convert
147
+ * @returns The JSON-safe representation of the object
148
+ */
149
+ private toJsonSafe;
150
+ }
151
+
152
+ /**
153
+ * Configuration for a protected resource
154
+ * Only contains payment-specific configuration, not resource metadata
155
+ */
156
+ interface ResourceConfig {
157
+ scheme: string;
158
+ /**
159
+ * Payment recipient. Use a **vacant** value (`""` or whitespace-only) when an extension must
160
+ * fill `payTo` during `enrichPaymentRequiredResponse`; non-vacant values are **immutable** there
161
+ * so extensions cannot redirect funds to an arbitrary address.
162
+ */
163
+ payTo: string;
164
+ price: Price;
165
+ network: Network;
166
+ maxTimeoutSeconds?: number;
167
+ extra?: Record<string, unknown>;
168
+ }
169
+ /**
170
+ * Context for `enrichPaymentRequiredResponse`. Extensions may merge extension payload via the
171
+ * return value. In-place edits to `paymentRequiredResponse.accepts` are **allowlisted** only
172
+ * (see {@link assertAcceptsAllowlistedAfterExtensionEnrich}): `scheme`, `network`, and
173
+ * `maxTimeoutSeconds` are immutable; `payTo`, `amount`, and `asset` may change only when the
174
+ * baseline value was vacant; `extra` may add keys but must not change or remove baseline keys.
175
+ */
176
+ interface PaymentRequiredContext {
177
+ requirements: PaymentRequirements[];
178
+ resourceInfo: ResourceInfo;
179
+ error?: string;
180
+ paymentRequiredResponse: PaymentRequired;
181
+ transportContext?: unknown;
182
+ }
183
+ /**
184
+ * Verify / settle lifecycle hook context: treat as **read-only** for core protocol fields.
185
+ * Control flow uses **abort** / **recover** return values only, not in-place mutation.
186
+ */
187
+ interface VerifyContext {
188
+ paymentPayload: DeepReadonly<PaymentPayload>;
189
+ requirements: DeepReadonly<PaymentRequirements>;
190
+ declaredExtensions: DeepReadonly<Record<string, unknown>>;
191
+ transportContext?: unknown;
192
+ }
193
+ interface VerifyResultContext extends VerifyContext {
194
+ result: DeepReadonly<VerifyResponse>;
195
+ }
196
+ /**
197
+ * Optional acknowledgement body returned to the caller when an `AfterVerifyHook`
198
+ * requests that the resource handler be skipped for a self-contained operation
199
+ * (e.g. cooperative refund). Travels in-process only — never on the facilitator wire.
200
+ */
201
+ interface SkipHandlerDirective {
202
+ contentType?: string;
203
+ body?: unknown;
204
+ }
205
+ type ResourceVerifyRespone = VerifyResponse & {
206
+ skipHandler?: SkipHandlerDirective;
207
+ };
208
+ interface VerifyFailureContext extends VerifyContext {
209
+ error: Error;
210
+ }
211
+ interface SettleContext {
212
+ paymentPayload: DeepReadonly<PaymentPayload>;
213
+ requirements: DeepReadonly<PaymentRequirements>;
214
+ declaredExtensions: DeepReadonly<Record<string, unknown>>;
215
+ transportContext?: unknown;
216
+ }
217
+ interface SettleResultContext extends SettleContext {
218
+ result: DeepReadonly<SettleResponse>;
219
+ }
220
+ interface SettleFailureContext extends SettleContext {
221
+ error: Error;
222
+ }
223
+ type VerifiedPaymentCancellationReason = "handler_threw" | "handler_failed";
224
+ interface VerifiedPaymentCanceledContext extends SettleContext {
225
+ reason: VerifiedPaymentCancellationReason;
226
+ error?: unknown;
227
+ responseStatus?: number;
228
+ }
229
+ interface VerifiedPaymentCancelOptions {
230
+ reason: VerifiedPaymentCancellationReason;
231
+ error?: unknown;
232
+ responseStatus?: number;
233
+ }
234
+ interface PaymentCancellationDispatcher {
235
+ cancel(options: VerifiedPaymentCancelOptions): Promise<void>;
236
+ }
237
+ type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
238
+ abort: true;
239
+ reason: string;
240
+ message?: string;
241
+ } | {
242
+ skip: true;
243
+ result: VerifyResponse;
244
+ }>;
245
+ type AfterVerifyHook = (context: VerifyResultContext) => Promise<void | {
246
+ skipHandler: true;
247
+ response?: SkipHandlerDirective;
248
+ }>;
249
+ type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
250
+ recovered: true;
251
+ result: VerifyResponse;
252
+ }>;
253
+ type BeforeSettleHook = (context: SettleContext) => Promise<void | {
254
+ abort: true;
255
+ reason: string;
256
+ message?: string;
257
+ } | {
258
+ skip: true;
259
+ result: SettleResponse;
260
+ }>;
261
+ type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
262
+ type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
263
+ recovered: true;
264
+ result: SettleResponse;
265
+ }>;
266
+ type OnVerifiedPaymentCanceledHook = (context: VerifiedPaymentCanceledContext) => Promise<void>;
267
+ /**
268
+ * Optional overrides for settlement parameters.
269
+ * Used to support partial settlement (e.g., upto scheme billing by actual usage).
270
+ *
271
+ * Note: Overriding the amount to a value different from the agreed-upon
272
+ * `PaymentRequirements.amount` is only valid in schemes that explicitly support
273
+ * partial settlement, such as the `upto` scheme. Using this with standard
274
+ * x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.
275
+ */
276
+ type ExtensionValidationResult = {
277
+ valid: true;
278
+ } | {
279
+ valid: false;
280
+ invalidReason: "extension_echo_mismatch";
281
+ extensionKey: string;
282
+ };
283
+ interface SettlementOverrides {
284
+ /**
285
+ * Amount to settle. Supports three formats:
286
+ *
287
+ * - **Raw atomic units** — e.g., `"1000"` settles exactly 1000 atomic units.
288
+ * - **Percent** — e.g., `"50%"` settles 50% of `PaymentRequirements.amount`.
289
+ * Supports up to two decimal places (e.g., `"33.33%"`). The result is floored
290
+ * to the nearest atomic unit.
291
+ * - **Dollar price** — e.g., `"$0.05"` converts a USD-denominated price to
292
+ * atomic units. Decimals are determined from the registered scheme's
293
+ * `getAssetDecimals` method, falling back to 6 (standard for USDC stablecoins).
294
+ * The result is rounded to the nearest atomic unit.
295
+ *
296
+ * The resolved amount must be <= the authorized maximum in `PaymentRequirements`.
297
+ *
298
+ * Note: Setting this to an amount other than `PaymentRequirements.amount` is
299
+ * only valid in schemes that support partial settlement, such as `upto`.
300
+ */
301
+ amount?: string;
302
+ }
303
+ /**
304
+ * Core x402 protocol server for resource protection
305
+ * Transport-agnostic implementation of the x402 payment protocol
306
+ */
307
+ declare class x402ResourceServer {
308
+ private facilitatorClients;
309
+ private registeredServerSchemes;
310
+ private schemeHookAdapters;
311
+ private supportedResponsesMap;
312
+ private facilitatorClientsMap;
313
+ private registeredExtensions;
314
+ private extensionHookAdapters;
315
+ private beforeVerifyHooks;
316
+ private afterVerifyHooks;
317
+ private onVerifyFailureHooks;
318
+ private beforeSettleHooks;
319
+ private afterSettleHooks;
320
+ private onSettleFailureHooks;
321
+ private onVerifiedPaymentCanceledHooks;
322
+ /**
323
+ * Creates a new x402ResourceServer instance.
324
+ *
325
+ * @param facilitatorClients - Optional facilitator client(s) for payment processing
326
+ */
327
+ constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
328
+ /**
329
+ * Register a scheme/network server implementation.
330
+ *
331
+ * @param network - The network identifier
332
+ * @param server - The scheme/network server implementation
333
+ * @returns The x402ResourceServer instance for chaining
334
+ */
335
+ register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
336
+ /**
337
+ * Check if a scheme is registered for a given network.
338
+ *
339
+ * @param network - The network identifier
340
+ * @param scheme - The payment scheme name
341
+ * @returns True if the scheme is registered for the network, false otherwise
342
+ */
343
+ hasRegisteredScheme(network: Network, scheme: string): boolean;
344
+ /**
345
+ * Returns the decimal precision for the asset specified in the given payment requirements.
346
+ * Looks up the registered scheme for the network and delegates to its getAssetDecimals
347
+ * method if available. Falls back to 6 (standard for USDC stablecoins) when the scheme
348
+ * does not implement getAssetDecimals or is not registered.
349
+ *
350
+ * @param requirements - The payment requirements containing scheme, network, and asset
351
+ * @returns The number of decimal places for the asset
352
+ */
353
+ getAssetDecimalsForRequirements(requirements: PaymentRequirements): number;
354
+ /**
355
+ * Registers a resource server extension (enrichment and optional verify/settle hooks).
356
+ * Re-registering the same key overwrites; omitting `hooks` removes adapter handles for that key.
357
+ *
358
+ * @param extension - Extension definition including `key` and optional `hooks`
359
+ * @returns This server instance for chaining
360
+ */
361
+ registerExtension(extension: ResourceServerExtension): this;
362
+ /**
363
+ * Check if an extension is registered.
364
+ *
365
+ * @param key - The extension key
366
+ * @returns True if the extension is registered
367
+ */
368
+ hasExtension(key: string): boolean;
369
+ /**
370
+ * Get all registered extensions.
371
+ *
372
+ * @returns Array of registered extensions
373
+ */
374
+ getExtensions(): ResourceServerExtension[];
375
+ /**
376
+ * Enriches declared extensions using registered extension hooks.
377
+ *
378
+ * @param declaredExtensions - Extensions declared on the route
379
+ * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
380
+ * @returns Enriched extensions map
381
+ */
382
+ enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
383
+ /**
384
+ * Register a hook to execute before payment verification.
385
+ * Can abort verification by returning { abort: true, reason: string }
386
+ *
387
+ * @param hook - The hook function to register
388
+ * @returns The x402ResourceServer instance for chaining
389
+ */
390
+ onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
391
+ /**
392
+ * Register a hook to execute after successful payment verification.
393
+ *
394
+ * @param hook - The hook function to register
395
+ * @returns The x402ResourceServer instance for chaining
396
+ */
397
+ onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
398
+ /**
399
+ * Register a hook to execute when payment verification fails.
400
+ * Can recover from failure by returning { recovered: true, result: VerifyResponse }
401
+ *
402
+ * @param hook - The hook function to register
403
+ * @returns The x402ResourceServer instance for chaining
404
+ */
405
+ onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
406
+ /**
407
+ * Register a hook to execute before payment settlement.
408
+ * Can abort settlement by returning { abort: true, reason: string }
409
+ *
410
+ * @param hook - The hook function to register
411
+ * @returns The x402ResourceServer instance for chaining
412
+ */
413
+ onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
414
+ /**
415
+ * Register a hook to execute after successful payment settlement.
416
+ *
417
+ * @param hook - The hook function to register
418
+ * @returns The x402ResourceServer instance for chaining
419
+ */
420
+ onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
421
+ /**
422
+ * Register a hook to execute when payment settlement fails.
423
+ * Can recover from failure by returning { recovered: true, result: SettleResponse }
424
+ *
425
+ * @param hook - The hook function to register
426
+ * @returns The x402ResourceServer instance for chaining
427
+ */
428
+ onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
429
+ /**
430
+ * Register a hook to execute when verified payment work is canceled before settlement.
431
+ *
432
+ * @param hook - The hook function to register
433
+ * @returns The x402ResourceServer instance for chaining
434
+ */
435
+ onVerifiedPaymentCanceled(hook: OnVerifiedPaymentCanceledHook): x402ResourceServer;
436
+ /**
437
+ * Initialize by fetching supported kinds from all facilitators
438
+ * Creates mappings for supported responses and facilitator clients
439
+ * Earlier facilitators in the array get precedence
440
+ */
441
+ initialize(): Promise<void>;
442
+ /**
443
+ * Get supported kind for a specific version, network, and scheme
444
+ *
445
+ * @param x402Version - The x402 version
446
+ * @param network - The network identifier
447
+ * @param scheme - The payment scheme
448
+ * @returns The supported kind or undefined if not found
449
+ */
450
+ getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
451
+ /**
452
+ * Get facilitator extensions for a specific version, network, and scheme
453
+ *
454
+ * @param x402Version - The x402 version
455
+ * @param network - The network identifier
456
+ * @param scheme - The payment scheme
457
+ * @returns The facilitator extensions or empty array if not found
458
+ */
459
+ getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
460
+ /**
461
+ * Build payment requirements for a protected resource
462
+ *
463
+ * @param resourceConfig - Configuration for the protected resource
464
+ * @returns Array of payment requirements
465
+ */
466
+ buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
467
+ /**
468
+ * Build payment requirements from multiple payment options
469
+ * This method handles resolving dynamic payTo/price functions and builds requirements for each option
470
+ *
471
+ * @param paymentOptions - Array of payment options to convert
472
+ * @param context - HTTP request context for resolving dynamic functions
473
+ * @returns Array of payment requirements (one per option)
474
+ */
475
+ buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
476
+ scheme: string;
477
+ payTo: string | ((context: TContext) => string | Promise<string>);
478
+ price: Price | ((context: TContext) => Price | Promise<Price>);
479
+ network: Network;
480
+ maxTimeoutSeconds?: number;
481
+ extra?: Record<string, unknown>;
482
+ }>, context: TContext): Promise<PaymentRequirements[]>;
483
+ /**
484
+ * Create a payment required response
485
+ *
486
+ * @param requirements - Payment requirements
487
+ * @param resourceInfo - Resource information
488
+ * @param error - Error message
489
+ * @param extensions - Optional declared extensions (for per-key enrichment)
490
+ * @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
491
+ * @param paymentPayload - Optional failed payment payload for response-time scheme enrichment
492
+ * @returns Payment required response object
493
+ */
494
+ createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown, paymentPayload?: PaymentPayload): Promise<PaymentRequired>;
495
+ /**
496
+ * Verifies a payment against requirements, running manual and in-use extension hooks.
497
+ *
498
+ * @param paymentPayload - Signed payment payload from the client
499
+ * @param requirements - Requirements matched to the payload
500
+ * @param declaredExtensions - Optional per-extension declarations for the request
501
+ * @param transportContext - Optional transport-specific context (e.g. HTTP, MCP)
502
+ * @returns Facilitator verify outcome (optionally carrying a `skipHandler` directive),
503
+ * or abort/recovery as driven by hooks
504
+ */
505
+ verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): Promise<ResourceVerifyRespone>;
506
+ /**
507
+ * Create cancellation controls for a verified payment attempt.
508
+ *
509
+ * @param paymentPayload - Signed payment payload from the client
510
+ * @param requirements - Requirements matched to the payload
511
+ * @param declaredExtensions - Optional per-extension declarations for the request
512
+ * @param transportContext - Optional transport-specific context
513
+ * @returns Cancellation controls for the verified payment attempt
514
+ */
515
+ createPaymentCancellationDispatcher(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): PaymentCancellationDispatcher;
516
+ /**
517
+ * Settle a verified payment
518
+ *
519
+ * @param paymentPayload - The payment payload to settle
520
+ * @param requirements - The payment requirements
521
+ * @param declaredExtensions - Optional declared extensions (for per-key enrichment)
522
+ * @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
523
+ * @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
524
+ * @returns Settlement response
525
+ */
526
+ settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown, settlementOverrides?: SettlementOverrides): Promise<SettleResponse>;
527
+ /**
528
+ * Find matching payment requirements for a payment
529
+ *
530
+ * @param availableRequirements - Array of available payment requirements
531
+ * @param paymentPayload - The payment payload
532
+ * @returns Matching payment requirements or undefined
533
+ */
534
+ /**
535
+ * Validates optional client extension echoes against server-advertised extension info.
536
+ * When the client omits extensions entirely, validation passes.
537
+ *
538
+ * @param paymentRequired - Server payment required response used for matching
539
+ * @param paymentPayload - Client payment payload
540
+ * @returns Whether echoed extension info preserves server-advertised values
541
+ */
542
+ validateExtensions(paymentRequired: PaymentRequired, paymentPayload: PaymentPayload): ExtensionValidationResult;
543
+ /**
544
+ * Finds the server-advertised requirement that matches a client payment payload.
545
+ *
546
+ * @param availableRequirements - Payment requirements advertised for the resource.
547
+ * @param paymentPayload - Signed payment payload from the client.
548
+ * @returns The matching requirement, or undefined when none match.
549
+ */
550
+ findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
551
+ /**
552
+ * Logs a warning when a manual or extension adapter lifecycle hook throws.
553
+ *
554
+ * @param phase - Lifecycle phase name (e.g. `beforeVerify`)
555
+ * @param label - Hook source label from {@link getLabeledHooks} (manual index or extension key)
556
+ * @param error - Thrown value or rejection reason
557
+ */
558
+ private warnResourceServerHookFailure;
559
+ /**
560
+ * Logs a warning when a registered extension enrichment hook throws.
561
+ *
562
+ * @param extensionKey - Registered extension identifier
563
+ * @param hookName - Hook method name (e.g. `enrichDeclaration`)
564
+ * @param error - Thrown value or rejection reason
565
+ */
566
+ private warnExtensionHookFailure;
567
+ /**
568
+ * Executes after-verify hooks for facilitator and hook-provided verify results.
569
+ *
570
+ * @param verifyResult - Verify response passed to after-verify hooks.
571
+ * @param context - Verify context shared with before-verify hooks.
572
+ * @param extensionKeysInUse - Declared extension keys for this request.
573
+ * @param matchedScheme - Scheme/network selected for this payment.
574
+ * @param matchedScheme.network - Matched payment network.
575
+ * @param matchedScheme.scheme - Matched payment scheme.
576
+ * @returns Verify response with any in-process skip handler directive.
577
+ */
578
+ private runAfterVerifyHooks;
579
+ /**
580
+ * Runs response enrichment after settlement lifecycle hooks complete.
581
+ *
582
+ * @param settleResult - Mutable settlement result being returned to the caller
583
+ * @param context - Read-only hook context for enrichment callbacks
584
+ * @param declaredExtensions - Extension declarations present on this payment
585
+ * @param matchedScheme - Scheme/network selected for this settlement
586
+ * @param matchedScheme.network - Matched payment network
587
+ * @param matchedScheme.scheme - Matched payment scheme
588
+ */
589
+ private enrichSettlementResponse;
590
+ /**
591
+ * Notify hooks that verified work ended before settlement.
592
+ *
593
+ * @param paymentPayload - Signed payment payload from the client
594
+ * @param requirements - Requirements matched to the payload
595
+ * @param declaredExtensions - Optional per-extension declarations for the request
596
+ * @param options - Cancellation reason and optional diagnostics
597
+ * @param fallbackTransportContext - Optional transport-specific context
598
+ */
599
+ private dispatchVerifiedPaymentCanceled;
600
+ /**
601
+ * Manual hooks first, then the matched scheme adapter, then extension adapters for keys in use.
602
+ * Each entry carries a stable label for logging when a hook throws.
603
+ *
604
+ * @param phase - Hook slot (e.g. `beforeVerify`)
605
+ * @param extensionKeysInUse - Declared extension keys for this request
606
+ * @param matchedScheme - Scheme/network selected for this payment
607
+ * @param matchedScheme.network - Matched payment network
608
+ * @param matchedScheme.scheme - Matched payment scheme
609
+ * @returns Hooks in invocation order with source labels
610
+ */
611
+ private getLabeledHooks;
612
+ /**
613
+ * Get facilitator client for a specific version, network, and scheme
614
+ *
615
+ * @param x402Version - The x402 version
616
+ * @param network - The network identifier
617
+ * @param scheme - The payment scheme
618
+ * @returns The facilitator client or undefined if not found
619
+ */
620
+ private getFacilitatorClient;
621
+ }
622
+
623
+ declare const SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
624
+ /**
625
+ * Framework-agnostic HTTP adapter interface
626
+ * Implementations provide framework-specific HTTP operations
627
+ */
628
+ interface HTTPAdapter {
629
+ getHeader(name: string): string | undefined;
630
+ getMethod(): string;
631
+ getPath(): string;
632
+ getUrl(): string;
633
+ getAcceptHeader(): string;
634
+ getUserAgent(): string;
635
+ /**
636
+ * Get query parameters from the request URL
637
+ *
638
+ * @returns Record of query parameter key-value pairs
639
+ */
640
+ getQueryParams?(): Record<string, string | string[]>;
641
+ /**
642
+ * Get a specific query parameter by name
643
+ *
644
+ * @param name - The query parameter name
645
+ * @returns The query parameter value(s) or undefined
646
+ */
647
+ getQueryParam?(name: string): string | string[] | undefined;
648
+ /**
649
+ * Get the parsed request body
650
+ * Framework adapters should parse JSON/form data appropriately
651
+ *
652
+ * @returns The parsed request body
653
+ */
654
+ getBody?(): unknown;
655
+ }
656
+ /**
657
+ * Paywall configuration for HTML responses
658
+ */
659
+ interface PaywallConfig {
660
+ appName?: string;
661
+ appLogo?: string;
662
+ sessionTokenEndpoint?: string;
663
+ currentUrl?: string;
664
+ testnet?: boolean;
665
+ }
666
+ /**
667
+ * Paywall provider interface for generating HTML
668
+ */
669
+ interface PaywallProvider {
670
+ generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
671
+ }
672
+ /**
673
+ * Dynamic payTo function that receives HTTP request context
674
+ */
675
+ type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
676
+ /**
677
+ * Dynamic price function that receives HTTP request context
678
+ */
679
+ type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
680
+ /**
681
+ * Result of response body callbacks containing content type and body.
682
+ */
683
+ interface HTTPResponseBody {
684
+ /**
685
+ * The content type for the response (e.g., 'application/json', 'text/plain').
686
+ */
687
+ contentType: string;
688
+ /**
689
+ * The response body to include in the 402 response.
690
+ */
691
+ body: unknown;
692
+ }
693
+ /**
694
+ * Dynamic function to generate a custom response for unpaid requests.
695
+ * Receives the HTTP request context and returns the content type and body to include in the 402 response.
696
+ */
697
+ type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
698
+ /**
699
+ * Dynamic function to generate a custom response for settlement failures.
700
+ * Receives the HTTP request context and settle failure result, returns the content type and body.
701
+ */
702
+ type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
703
+ /**
704
+ * A single payment option for a route
705
+ * Represents one way a client can pay for access to the resource
706
+ */
707
+ interface PaymentOption {
708
+ scheme: string;
709
+ payTo: string | DynamicPayTo;
710
+ price: Price | DynamicPrice;
711
+ network: Network;
712
+ maxTimeoutSeconds?: number;
713
+ extra?: Record<string, unknown>;
714
+ }
715
+ /**
716
+ * Route configuration for HTTP endpoints
717
+ *
718
+ * The 'accepts' field defines payment options for the route.
719
+ * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
720
+ */
721
+ interface RouteConfig {
722
+ accepts: PaymentOption | PaymentOption[];
723
+ resource?: string;
724
+ description?: string;
725
+ mimeType?: string;
726
+ serviceName?: string;
727
+ tags?: string[];
728
+ iconUrl?: string;
729
+ customPaywallHtml?: string;
730
+ /**
731
+ * Optional callback to generate a custom response for unpaid API requests.
732
+ * This allows servers to return preview data, error messages, or other content
733
+ * when a request lacks payment.
734
+ *
735
+ * For browser requests (Accept: text/html), the paywall HTML takes precedence.
736
+ * This callback is only used for API clients.
737
+ *
738
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
739
+ *
740
+ * @param context - The HTTP request context
741
+ * @returns An object containing both contentType and body for the 402 response
742
+ */
743
+ unpaidResponseBody?: UnpaidResponseBody;
744
+ /**
745
+ * Optional callback to generate a custom response for settlement failures.
746
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
747
+ *
748
+ * @param context - The HTTP request context
749
+ * @param settleResult - The settlement failure result
750
+ * @returns An object containing both contentType and body for the 402 response
751
+ */
752
+ settlementFailedResponseBody?: SettlementFailedResponseBody;
753
+ extensions?: Record<string, unknown>;
754
+ }
755
+ /**
756
+ * Routes configuration - maps path patterns to route configs
757
+ */
758
+ type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
759
+ /**
760
+ * Check if any routes in the configuration declare bazaar extensions.
761
+ *
762
+ * @param routes - Route configuration
763
+ * @returns True if any route has extensions.bazaar defined
764
+ */
765
+ declare function checkIfBazaarNeeded(routes: RoutesConfig): boolean;
766
+ /**
767
+ * Hook that runs on every request to a protected route, before payment processing.
768
+ * Can grant access without payment, deny the request, or continue to payment flow.
769
+ *
770
+ * @returns
771
+ * - `void` - Continue to payment processing (default behavior)
772
+ * - `{ grantAccess: true }` - Grant access without requiring payment
773
+ * - `{ abort: true; reason: string }` - Deny the request (returns 403)
774
+ */
775
+ type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
776
+ grantAccess: true;
777
+ } | {
778
+ abort: true;
779
+ reason: string;
780
+ }>;
781
+ interface HTTPResourceServerExtensionHooks {
782
+ onProtectedRequest?: (declaration: unknown, context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
783
+ grantAccess: true;
784
+ } | {
785
+ abort: true;
786
+ reason: string;
787
+ }>;
788
+ }
789
+ interface ResourceServerTransportExtensionHooks {
790
+ http?: HTTPResourceServerExtensionHooks;
791
+ }
792
+ /**
793
+ * Compiled route for efficient matching
794
+ */
795
+ interface CompiledRoute {
796
+ verb: string;
797
+ regex: RegExp;
798
+ config: RouteConfig;
799
+ pattern: string;
800
+ }
801
+ /**
802
+ * HTTP request context that encapsulates all request data
803
+ */
804
+ interface HTTPRequestContext {
805
+ adapter: HTTPAdapter;
806
+ path: string;
807
+ method: string;
808
+ paymentHeader?: string;
809
+ routePattern?: string;
810
+ }
811
+ /**
812
+ * HTTP transport context contains both request context and optional response data.
813
+ */
814
+ interface HTTPTransportContext {
815
+ /** The HTTP request context */
816
+ request: HTTPRequestContext;
817
+ /** The response body buffer */
818
+ responseBody?: Buffer;
819
+ /** Response headers set by the route handler (used for settlement overrides) */
820
+ responseHeaders?: Record<string, string>;
821
+ }
822
+ /**
823
+ * HTTP response instructions for the framework middleware
824
+ */
825
+ interface HTTPResponseInstructions {
826
+ status: number;
827
+ headers: Record<string, string>;
828
+ body?: unknown;
829
+ isHtml?: boolean;
830
+ }
831
+ /**
832
+ * Result of processing an HTTP request for payment
833
+ */
834
+ type HTTPProcessResult = {
835
+ type: "no-payment-required";
836
+ } | {
837
+ type: "payment-verified";
838
+ cancellationDispatcher: PaymentCancellationDispatcher;
839
+ paymentPayload: PaymentPayload;
840
+ paymentRequirements: PaymentRequirements;
841
+ declaredExtensions?: Record<string, unknown>;
842
+ } | {
843
+ type: "payment-error";
844
+ response: HTTPResponseInstructions;
845
+ };
846
+ /**
847
+ * Result of processSettlement
848
+ */
849
+ type ProcessSettleSuccessResponse = SettleResponse & {
850
+ success: true;
851
+ headers: Record<string, string>;
852
+ requirements: PaymentRequirements;
853
+ };
854
+ type ProcessSettleFailureResponse = SettleResponse & {
855
+ success: false;
856
+ errorReason: string;
857
+ errorMessage?: string;
858
+ headers: Record<string, string>;
859
+ response: HTTPResponseInstructions;
860
+ };
861
+ type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
862
+ /**
863
+ * Represents a validation error for a specific route's payment configuration.
864
+ */
865
+ interface RouteValidationError {
866
+ /** The route pattern (e.g., "GET /api/weather") */
867
+ routePattern: string;
868
+ /** The payment scheme that failed validation */
869
+ scheme: string;
870
+ /** The network that failed validation */
871
+ network: Network;
872
+ /** The type of validation failure */
873
+ reason: "missing_scheme" | "missing_facilitator";
874
+ /** Human-readable error message */
875
+ message: string;
876
+ }
877
+ /**
878
+ * Error thrown when route configuration validation fails.
879
+ */
880
+ declare class RouteConfigurationError extends Error {
881
+ /** The validation errors that caused this exception */
882
+ readonly errors: RouteValidationError[];
883
+ /**
884
+ * Creates a new RouteConfigurationError with the given validation errors.
885
+ *
886
+ * @param errors - The validation errors that caused this exception.
887
+ */
888
+ constructor(errors: RouteValidationError[]);
889
+ }
890
+ /**
891
+ * HTTP-enhanced x402 resource server
892
+ * Provides framework-agnostic HTTP protocol handling
893
+ */
894
+ declare class x402HTTPResourceServer {
895
+ private ResourceServer;
896
+ private compiledRoutes;
897
+ private routesConfig;
898
+ private paywallProvider?;
899
+ private protectedRequestHooks;
900
+ /**
901
+ * Creates a new x402HTTPResourceServer instance.
902
+ *
903
+ * @param ResourceServer - The core x402ResourceServer instance to use
904
+ * @param routes - Route configuration for payment-protected endpoints
905
+ */
906
+ constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
907
+ /**
908
+ * Get the underlying x402ResourceServer instance.
909
+ *
910
+ * @returns The underlying x402ResourceServer instance
911
+ */
912
+ get server(): x402ResourceServer;
913
+ /**
914
+ * Get the routes configuration.
915
+ *
916
+ * @returns The routes configuration
917
+ */
918
+ get routes(): RoutesConfig;
919
+ /**
920
+ * Initialize the HTTP resource server.
921
+ *
922
+ * This method initializes the underlying resource server (fetching facilitator support)
923
+ * and then validates that all route payment configurations have corresponding
924
+ * registered schemes and facilitator support.
925
+ *
926
+ * @throws RouteConfigurationError if any route's payment options don't have
927
+ * corresponding registered schemes or facilitator support
928
+ *
929
+ * @example
930
+ * ```typescript
931
+ * const httpServer = new x402HTTPResourceServer(server, routes);
932
+ * await httpServer.initialize();
933
+ * ```
934
+ */
935
+ initialize(): Promise<void>;
936
+ /**
937
+ * Register a custom paywall provider for generating HTML
938
+ *
939
+ * @param provider - PaywallProvider instance
940
+ * @returns This service instance for chaining
941
+ */
942
+ registerPaywallProvider(provider: PaywallProvider): this;
943
+ /**
944
+ * Register a hook that runs on every request to a protected route, before payment processing.
945
+ * Hooks are executed in order of registration. The first hook to return a non-void result wins.
946
+ *
947
+ * @param hook - The request hook function
948
+ * @returns The x402HTTPResourceServer instance for chaining
949
+ */
950
+ onProtectedRequest(hook: ProtectedRequestHook): this;
951
+ /**
952
+ * Process HTTP request and return response instructions
953
+ * This is the main entry point for framework middleware
954
+ *
955
+ * @param context - HTTP request context
956
+ * @param paywallConfig - Optional paywall configuration
957
+ * @returns Process result indicating next action for middleware
958
+ */
959
+ processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
960
+ /**
961
+ * Process settlement after successful response
962
+ *
963
+ * @param paymentPayload - The verified payment payload
964
+ * @param requirements - The matching payment requirements
965
+ * @param declaredExtensions - Optional declared extensions (for per-key enrichment)
966
+ * @param transportContext - Optional HTTP transport context
967
+ * @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
968
+ * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
969
+ */
970
+ processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext, settlementOverrides?: SettlementOverrides): Promise<ProcessSettleResultResponse>;
971
+ /**
972
+ * Check if a request requires payment based on route configuration
973
+ *
974
+ * @param context - HTTP request context
975
+ * @returns True if the route requires payment, false otherwise
976
+ */
977
+ requiresPayment(context: HTTPRequestContext): boolean;
978
+ /**
979
+ * Settle a verified payment that requested `skipHandler`, packaging the
980
+ * result as a `payment-error` HTTPProcessResult so framework adapters can
981
+ * write the response without invoking the route handler.
982
+ *
983
+ * - On success: status 200 + PAYMENT-RESPONSE header + configured body.
984
+ * - On failure: the standard 402 settlement-failure response.
985
+ *
986
+ * @param paymentPayload - Verified payment payload.
987
+ * @param requirements - Matched payment requirements.
988
+ * @param declaredExtensions - Optional declared extensions for the route.
989
+ * @param transportContext - Optional HTTP transport context.
990
+ * @param skipHandlerResponse - Optional content type + body to return on success.
991
+ * @returns A `payment-error` HTTPProcessResult carrying the final response.
992
+ */
993
+ private processSkipHandlerSettlement;
994
+ /**
995
+ * Build HTTPResponseInstructions for settlement failure.
996
+ * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
997
+ *
998
+ * @param failure - Settlement failure result with headers
999
+ * @param transportContext - Optional HTTP transport context for the request
1000
+ * @returns HTTP response instructions for the 402 settlement failure response
1001
+ */
1002
+ private buildSettlementFailureResponse;
1003
+ /**
1004
+ * Normalizes a RouteConfig's accepts field into an array of PaymentOptions
1005
+ * Handles both single PaymentOption and array formats
1006
+ *
1007
+ * @param routeConfig - Route configuration
1008
+ * @returns Array of payment options
1009
+ */
1010
+ private normalizePaymentOptions;
1011
+ /**
1012
+ * Manual request hooks run before extension transport hooks for declared extensions.
1013
+ *
1014
+ * @param routeConfig - Route configuration for the matched request
1015
+ * @returns Hooks in invocation order
1016
+ */
1017
+ private getProtectedRequestHooks;
1018
+ /**
1019
+ * Validates that all payment options in routes have corresponding registered schemes
1020
+ * and facilitator support.
1021
+ *
1022
+ * @returns Array of validation errors (empty if all routes are valid)
1023
+ */
1024
+ private validateRouteConfiguration;
1025
+ /**
1026
+ * Get route configuration for a request
1027
+ *
1028
+ * @param path - Request path
1029
+ * @param method - HTTP method
1030
+ * @returns Route configuration and pattern, or undefined if no match
1031
+ */
1032
+ private getRouteConfig;
1033
+ /**
1034
+ * Extract payment from HTTP headers (handles v1 and v2)
1035
+ *
1036
+ * @param adapter - HTTP adapter
1037
+ * @returns Decoded payment payload or null
1038
+ */
1039
+ private extractPayment;
1040
+ /**
1041
+ * Check if request is from a web browser
1042
+ *
1043
+ * @param adapter - HTTP adapter
1044
+ * @returns True if request appears to be from a browser
1045
+ */
1046
+ private isWebBrowser;
1047
+ /**
1048
+ * Create HTTP response instructions from payment required
1049
+ *
1050
+ * @param paymentRequired - Payment requirements
1051
+ * @param isWebBrowser - Whether request is from browser
1052
+ * @param paywallConfig - Paywall configuration
1053
+ * @param customHtml - Custom HTML template
1054
+ * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
1055
+ * @returns Response instructions
1056
+ */
1057
+ private createHTTPResponse;
1058
+ /**
1059
+ * Create HTTP payment required response (v1 puts in body, v2 puts in header)
1060
+ *
1061
+ * @param paymentRequired - Payment required object
1062
+ * @returns Headers and body for the HTTP response
1063
+ */
1064
+ private createHTTPPaymentRequiredResponse;
1065
+ /**
1066
+ * Create settlement response headers
1067
+ *
1068
+ * @param settleResponse - Settlement response
1069
+ * @returns Headers to add to response
1070
+ */
1071
+ private createSettlementHeaders;
1072
+ /**
1073
+ * Parse route pattern into verb and regex
1074
+ *
1075
+ * @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
1076
+ * @returns Parsed pattern with verb and regex
1077
+ */
1078
+ private parseRoutePattern;
1079
+ /**
1080
+ * Normalize path for matching
1081
+ *
1082
+ * @param path - Raw path from request
1083
+ * @returns Normalized path
1084
+ */
1085
+ private normalizePath;
1086
+ /**
1087
+ * Generate paywall HTML for browser requests
1088
+ *
1089
+ * @param paymentRequired - Payment required response
1090
+ * @param paywallConfig - Optional paywall configuration
1091
+ * @param customHtml - Optional custom HTML template
1092
+ * @returns HTML string
1093
+ */
1094
+ private generatePaywallHTML;
1095
+ /**
1096
+ * Extract display amount from payment requirements.
1097
+ * Uses the registered scheme's decimal precision for the asset, falling back to 6.
1098
+ *
1099
+ * @param paymentRequired - The payment required object
1100
+ * @returns The display amount in decimal format
1101
+ */
1102
+ private getDisplayAmount;
1103
+ }
1104
+
1105
+ interface FacilitatorExtension {
1106
+ key: string;
1107
+ }
1108
+ /**
1109
+ * Per-extension verify/settle hooks. Contexts are **read-only** for core protocol fields; use
1110
+ * **abort** / **recover** return values instead of mutating `paymentPayload`, `requirements`, etc.
1111
+ */
1112
+ interface ResourceServerExtensionHooks {
1113
+ onBeforeVerify?: (declaration: unknown, context: VerifyContext) => Promise<void | {
1114
+ abort: true;
1115
+ reason: string;
1116
+ message?: string;
1117
+ } | {
1118
+ skip: true;
1119
+ result: VerifyResponse;
1120
+ }>;
1121
+ onAfterVerify?: (declaration: unknown, context: VerifyResultContext) => Promise<void>;
1122
+ onVerifyFailure?: (declaration: unknown, context: VerifyFailureContext) => Promise<void | {
1123
+ recovered: true;
1124
+ result: VerifyResponse;
1125
+ }>;
1126
+ onBeforeSettle?: (declaration: unknown, context: SettleContext) => Promise<void | {
1127
+ abort: true;
1128
+ reason: string;
1129
+ message?: string;
1130
+ } | {
1131
+ skip: true;
1132
+ result: SettleResponse;
1133
+ }>;
1134
+ onAfterSettle?: (declaration: unknown, context: SettleResultContext) => Promise<void>;
1135
+ onSettleFailure?: (declaration: unknown, context: SettleFailureContext) => Promise<void | {
1136
+ recovered: true;
1137
+ result: SettleResponse;
1138
+ }>;
1139
+ onVerifiedPaymentCanceled?: (declaration: unknown, context: VerifiedPaymentCanceledContext) => Promise<void>;
1140
+ }
1141
+ interface ResourceServerExtension {
1142
+ key: string;
1143
+ enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
1144
+ /**
1145
+ * Return value merges into `extensions[key]`. In-place edits to `accepts` are allowlisted only
1146
+ * (see server `assertAcceptsAllowlistedAfterExtensionEnrich`): vacant `payTo` / `amount` / `asset`
1147
+ * may be filled; locked values and `scheme` / `network` / `maxTimeoutSeconds` / baseline `extra`
1148
+ * entries are immutable.
1149
+ */
1150
+ enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
1151
+ /**
1152
+ * Return value merges into `settleResult.extensions[key]`. Facilitator fields (`success`,
1153
+ * `transaction`, `network`, etc.) must not be changed; only `extensions` is merged from the hook.
1154
+ */
1155
+ enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
1156
+ /** Installed on `registerExtension`; runs only when `declaredExtensions[key]` is defined. */
1157
+ hooks?: ResourceServerExtensionHooks;
1158
+ /** Transport-specific hooks scoped to declared extension keys. */
1159
+ transportHooks?: ResourceServerTransportExtensionHooks;
1160
+ }
1161
+
1162
+ type Network = `${string}:${string}`;
1163
+ type Money = string | number;
1164
+ type AssetAmount = {
1165
+ asset: string;
1166
+ amount: string;
1167
+ extra?: Record<string, unknown>;
1168
+ };
1169
+ type Price = Money | AssetAmount;
1170
+
1171
+ interface ResourceInfo {
1172
+ url: string;
1173
+ description?: string;
1174
+ mimeType?: string;
1175
+ serviceName?: string;
1176
+ tags?: string[];
1177
+ iconUrl?: string;
1178
+ }
1179
+ type PaymentRequirements = {
1180
+ scheme: string;
1181
+ network: Network;
1182
+ asset: string;
1183
+ amount: string;
1184
+ payTo: string;
1185
+ maxTimeoutSeconds: number;
1186
+ extra: Record<string, unknown>;
1187
+ };
1188
+ type PaymentRequired = {
1189
+ x402Version: number;
1190
+ error?: string;
1191
+ resource: ResourceInfo;
1192
+ accepts: PaymentRequirements[];
1193
+ extensions?: Record<string, unknown>;
1194
+ };
1195
+ type PaymentPayload = {
1196
+ x402Version: number;
1197
+ resource?: ResourceInfo;
1198
+ accepted: PaymentRequirements;
1199
+ payload: Record<string, unknown>;
1200
+ extensions?: Record<string, unknown>;
1201
+ };
1202
+
1203
+ type VerifyRequest = {
1204
+ x402Version: number;
1205
+ paymentPayload: PaymentPayload;
1206
+ paymentRequirements: PaymentRequirements;
1207
+ };
1208
+ type VerifyResponse = {
1209
+ isValid: boolean;
1210
+ invalidReason?: string;
1211
+ invalidMessage?: string;
1212
+ payer?: string;
1213
+ extensions?: Record<string, unknown>;
1214
+ extra?: Record<string, unknown>;
1215
+ };
1216
+ type SettleRequest = {
1217
+ x402Version: number;
1218
+ paymentPayload: PaymentPayload;
1219
+ paymentRequirements: PaymentRequirements;
1220
+ };
1221
+ type SettleResponse = {
1222
+ success: boolean;
1223
+ errorReason?: string;
1224
+ errorMessage?: string;
1225
+ payer?: string;
1226
+ transaction: string;
1227
+ network: Network;
1228
+ /** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */
1229
+ amount?: string;
1230
+ extensions?: Record<string, unknown>;
1231
+ extra?: Record<string, unknown>;
1232
+ };
1233
+ type SupportedKind = {
1234
+ x402Version: number;
1235
+ scheme: string;
1236
+ network: Network;
1237
+ extra?: Record<string, unknown>;
1238
+ };
1239
+ type SupportedResponse = {
1240
+ kinds: SupportedKind[];
1241
+ extensions: string[];
1242
+ signers: Record<string, string[]>;
1243
+ };
1244
+ /**
1245
+ * Error thrown when payment verification fails.
1246
+ */
1247
+ declare class VerifyError extends Error {
1248
+ readonly invalidReason?: string;
1249
+ readonly invalidMessage?: string;
1250
+ readonly payer?: string;
1251
+ readonly statusCode: number;
1252
+ /**
1253
+ * Creates a VerifyError from a failed verification response.
1254
+ *
1255
+ * @param statusCode - HTTP status code from the facilitator
1256
+ * @param response - The verify response containing failure details
1257
+ */
1258
+ constructor(statusCode: number, response: VerifyResponse);
1259
+ }
1260
+ /**
1261
+ * Error thrown when payment settlement fails.
1262
+ */
1263
+ declare class SettleError extends Error {
1264
+ readonly errorReason?: string;
1265
+ readonly errorMessage?: string;
1266
+ readonly payer?: string;
1267
+ readonly transaction: string;
1268
+ readonly network: Network;
1269
+ readonly statusCode: number;
1270
+ /**
1271
+ * Creates a SettleError from a failed settlement response.
1272
+ *
1273
+ * @param statusCode - HTTP status code from the facilitator
1274
+ * @param response - The settle response containing error details
1275
+ */
1276
+ constructor(statusCode: number, response: SettleResponse);
1277
+ }
1278
+ /**
1279
+ * Error thrown when a facilitator returns malformed success payload data.
1280
+ */
1281
+ declare class FacilitatorResponseError extends Error {
1282
+ /**
1283
+ * Creates a FacilitatorResponseError for malformed facilitator responses.
1284
+ *
1285
+ * @param message - The boundary error message
1286
+ */
1287
+ constructor(message: string);
1288
+ }
1289
+ /**
1290
+ * Walks an error cause chain to find the first facilitator response error.
1291
+ *
1292
+ * @param error - The thrown value to inspect
1293
+ * @returns The nested facilitator response error, if present
1294
+ */
1295
+ declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
1296
+
1297
+ /**
1298
+ * Money parser function that converts a numeric amount to an AssetAmount
1299
+ * Receives the amount as a decimal number (e.g., 1.50 for $1.50)
1300
+ * Returns null to indicate "cannot handle this amount", causing fallback to next parser
1301
+ * Always returns a Promise for consistency - use async/await
1302
+ *
1303
+ * @param amount - The decimal amount (e.g., 1.50)
1304
+ * @param network - The network identifier for context
1305
+ * @returns AssetAmount or null to try next parser
1306
+ */
1307
+ type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
1308
+ /**
1309
+ * Result of createPaymentPayload - the core payload fields.
1310
+ * Contains the x402 version, scheme-specific payload data, and optional extension data.
1311
+ * Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
1312
+ * with server-declared extensions in the final PaymentPayload.
1313
+ */
1314
+ type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
1315
+ extensions?: Record<string, unknown>;
1316
+ };
1317
+ /**
1318
+ * Context passed to scheme's createPaymentPayload for extensions awareness.
1319
+ * Contains the server-declared extensions from PaymentRequired so the scheme
1320
+ * can check which extensions are advertised and respond accordingly.
1321
+ */
1322
+ interface PaymentPayloadContext {
1323
+ extensions?: Record<string, unknown>;
1324
+ }
1325
+ interface SchemeClientHooks {
1326
+ onBeforePaymentCreation?: BeforePaymentCreationHook;
1327
+ onAfterPaymentCreation?: AfterPaymentCreationHook;
1328
+ onPaymentCreationFailure?: OnPaymentCreationFailureHook;
1329
+ onPaymentResponse?: OnPaymentResponseHook;
1330
+ }
1331
+ interface SchemeNetworkClient {
1332
+ readonly scheme: string;
1333
+ readonly schemeHooks?: SchemeClientHooks;
1334
+ createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
1335
+ }
1336
+ /**
1337
+ * Context passed to SchemeNetworkFacilitator.verify/settle, providing
1338
+ * access to registered facilitator extensions. Mechanism implementations
1339
+ * use this to retrieve extension-provided capabilities (e.g., a batch signer).
1340
+ */
1341
+ interface FacilitatorContext {
1342
+ getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
1343
+ }
1344
+ interface SchemeNetworkFacilitator {
1345
+ readonly scheme: string;
1346
+ /**
1347
+ * CAIP family pattern that this facilitator supports.
1348
+ * Used to group signers by blockchain family in the supported response.
1349
+ *
1350
+ * @example
1351
+ * // EVM facilitators
1352
+ * readonly caipFamily = "eip155:*";
1353
+ *
1354
+ * @example
1355
+ * // SVM facilitators
1356
+ * readonly caipFamily = "solana:*";
1357
+ */
1358
+ readonly caipFamily: string;
1359
+ /**
1360
+ * Get mechanism-specific extra data needed for the supported kinds endpoint.
1361
+ * This method is called when building the facilitator's supported response.
1362
+ *
1363
+ * @param network - The network identifier for context
1364
+ * @returns Extra data object or undefined if no extra data is needed
1365
+ *
1366
+ * @example
1367
+ * // EVM schemes return undefined (no extra data needed)
1368
+ * getExtra(network: Network): undefined {
1369
+ * return undefined;
1370
+ * }
1371
+ *
1372
+ * @example
1373
+ * // SVM schemes return feePayer address
1374
+ * getExtra(network: Network): Record<string, unknown> | undefined {
1375
+ * return { feePayer: this.signer.address };
1376
+ * }
1377
+ */
1378
+ getExtra(network: Network): Record<string, unknown> | undefined;
1379
+ /**
1380
+ * Get signer addresses used by this facilitator for a given network.
1381
+ * These are included in the supported response to help clients understand
1382
+ * which addresses might sign/pay for transactions.
1383
+ *
1384
+ * Supports multiple addresses for load balancing, key rotation, and high availability.
1385
+ *
1386
+ * @param network - The network identifier
1387
+ * @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
1388
+ *
1389
+ * @example
1390
+ * // EVM facilitator
1391
+ * getSigners(network: string): string[] {
1392
+ * return [...this.signer.getAddresses()];
1393
+ * }
1394
+ *
1395
+ * @example
1396
+ * // SVM facilitator
1397
+ * getSigners(network: string): string[] {
1398
+ * return [...this.signer.getAddresses()];
1399
+ * }
1400
+ */
1401
+ getSigners(network: string): string[];
1402
+ verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
1403
+ settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
1404
+ }
1405
+ interface SchemeServerHooks {
1406
+ onBeforeVerify?: BeforeVerifyHook;
1407
+ onAfterVerify?: AfterVerifyHook;
1408
+ onBeforeSettle?: BeforeSettleHook;
1409
+ onAfterSettle?: AfterSettleHook;
1410
+ onVerifyFailure?: OnVerifyFailureHook;
1411
+ onSettleFailure?: OnSettleFailureHook;
1412
+ onVerifiedPaymentCanceled?: OnVerifiedPaymentCanceledHook;
1413
+ }
1414
+ type SchemeEnrichSettlementPayloadHook = (ctx: SettleContext) => Promise<Record<string, unknown> | void>;
1415
+ type SchemeEnrichSettlementResponseHook = (ctx: SettleResultContext) => Promise<Record<string, unknown> | void>;
1416
+ interface SchemePaymentRequiredContext {
1417
+ requirements: PaymentRequirements[];
1418
+ paymentPayload?: DeepReadonly<PaymentPayload>;
1419
+ resourceInfo: ResourceInfo;
1420
+ error?: string;
1421
+ paymentRequiredResponse: PaymentRequired;
1422
+ transportContext?: unknown;
1423
+ }
1424
+ type SchemeEnrichPaymentRequiredResponseHook = (ctx: SchemePaymentRequiredContext) => Promise<PaymentRequirements[] | void>;
1425
+ interface SchemeNetworkServer {
1426
+ readonly scheme: string;
1427
+ readonly schemeHooks?: SchemeServerHooks;
1428
+ enrichPaymentRequiredResponse?: SchemeEnrichPaymentRequiredResponseHook;
1429
+ enrichSettlementPayload?: SchemeEnrichSettlementPayloadHook;
1430
+ enrichSettlementResponse?: SchemeEnrichSettlementResponseHook;
1431
+ /**
1432
+ * Convert a user-friendly price to the scheme's specific amount and asset format
1433
+ * Always returns a Promise for consistency
1434
+ *
1435
+ * @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
1436
+ * @param network - The network identifier for context
1437
+ * @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
1438
+ *
1439
+ * @example
1440
+ * // For EVM networks with USDC:
1441
+ * await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
1442
+ *
1443
+ * // For custom schemes:
1444
+ * await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
1445
+ */
1446
+ parsePrice(price: Price, network: Network): Promise<AssetAmount>;
1447
+ /**
1448
+ * Optional: Return the decimal precision of the asset for a given network.
1449
+ * Used by `resolveSettlementOverrideAmount` to convert dollar-format overrides to atomic units.
1450
+ * Defaults to 6 when not implemented.
1451
+ *
1452
+ * @param asset - The asset address or symbol
1453
+ * @param network - The network identifier
1454
+ * @returns Number of decimal places for the asset
1455
+ */
1456
+ getAssetDecimals?(asset: string, network: Network): number;
1457
+ /**
1458
+ * Build payment requirements for this scheme/network combination
1459
+ *
1460
+ * @param paymentRequirements - Base payment requirements with amount/asset already set
1461
+ * @param supportedKind - The supported kind from facilitator's /supported endpoint
1462
+ * @param supportedKind.x402Version - The x402 version
1463
+ * @param supportedKind.scheme - The payment scheme
1464
+ * @param supportedKind.network - The network identifier
1465
+ * @param supportedKind.extra - Optional extra metadata
1466
+ * @param facilitatorExtensions - Extensions supported by the facilitator
1467
+ * @returns Enhanced payment requirements ready to be sent to clients
1468
+ */
1469
+ enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: SupportedKind, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
1470
+ }
1471
+
1472
+ /**
1473
+ * Client Hook Context Interfaces
1474
+ */
1475
+ interface PaymentCreationContext {
1476
+ paymentRequired: PaymentRequired;
1477
+ selectedRequirements: PaymentRequirements;
1478
+ }
1479
+ interface PaymentCreatedContext extends PaymentCreationContext {
1480
+ paymentPayload: PaymentPayload;
1481
+ }
1482
+ interface PaymentCreationFailureContext extends PaymentCreationContext {
1483
+ error: Error;
1484
+ }
1485
+ /**
1486
+ * Client Hook Type Definitions
1487
+ */
1488
+ type BeforePaymentCreationHook = (context: PaymentCreationContext) => Promise<void | {
1489
+ abort: true;
1490
+ reason: string;
1491
+ }>;
1492
+ type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>;
1493
+ type OnPaymentCreationFailureHook = (context: PaymentCreationFailureContext) => Promise<void | {
1494
+ recovered: true;
1495
+ payload: PaymentPayload;
1496
+ }>;
1497
+ /**
1498
+ * Context provided to payment response hooks after the paid request completes.
1499
+ *
1500
+ * Discriminate by what's present:
1501
+ * - `settleResponse` with `success: true` → settle succeeded
1502
+ * - `settleResponse` with `success: false` → settle failed
1503
+ * - `paymentRequired` (no `settleResponse`) → verify failed
1504
+ * - `error` → transport or parse error
1505
+ */
1506
+ interface PaymentResponseContext {
1507
+ paymentPayload: PaymentPayload;
1508
+ requirements: PaymentRequirements;
1509
+ settleResponse?: SettleResponse;
1510
+ paymentRequired?: PaymentRequired;
1511
+ error?: Error;
1512
+ }
1513
+ /**
1514
+ * Hook fired after a paid request completes.
1515
+ * Return `{ recovered: true }` to signal the transport should retry with a fresh payload.
1516
+ */
1517
+ type OnPaymentResponseHook = (ctx: PaymentResponseContext) => Promise<void | {
1518
+ recovered: true;
1519
+ }>;
1520
+ type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;
1521
+ interface ClientExtensionHooks {
1522
+ onBeforePaymentCreation?: (declaration: unknown, context: PaymentCreationContext) => Promise<void | {
1523
+ abort: true;
1524
+ reason: string;
1525
+ }>;
1526
+ onAfterPaymentCreation?: (declaration: unknown, context: PaymentCreatedContext) => Promise<void>;
1527
+ onPaymentCreationFailure?: (declaration: unknown, context: PaymentCreationFailureContext) => Promise<void | {
1528
+ recovered: true;
1529
+ payload: PaymentPayload;
1530
+ }>;
1531
+ onPaymentResponse?: (declaration: unknown, context: PaymentResponseContext) => Promise<void | {
1532
+ recovered: true;
1533
+ }>;
1534
+ }
1535
+ interface ClientTransportExtensionHooks {
1536
+ [transport: string]: unknown;
1537
+ }
1538
+ /**
1539
+ * Extension that can enrich payment payloads on the client side.
1540
+ *
1541
+ * Client extensions are invoked after the scheme creates the base payment payload
1542
+ * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612
1543
+ * permit signing) to enrich the payload's extensions data.
1544
+ */
1545
+ interface ClientExtension {
1546
+ /**
1547
+ * Unique key identifying this extension (e.g., "eip2612GasSponsoring").
1548
+ * Must match the extension key used in PaymentRequired.extensions.
1549
+ */
1550
+ key: string;
1551
+ /**
1552
+ * Called after payload creation when the extension key is present in
1553
+ * paymentRequired.extensions. Allows the extension to enrich the payload
1554
+ * with extension-specific data (e.g., signing an EIP-2612 permit).
1555
+ *
1556
+ * @param paymentPayload - The payment payload to enrich
1557
+ * @param paymentRequired - The original PaymentRequired response
1558
+ * @returns The enriched payment payload
1559
+ */
1560
+ enrichPaymentPayload?: (paymentPayload: PaymentPayload, paymentRequired: PaymentRequired) => Promise<PaymentPayload>;
1561
+ hooks?: ClientExtensionHooks;
1562
+ transportHooks?: ClientTransportExtensionHooks;
1563
+ }
1564
+ /**
1565
+ * A policy function that filters or transforms payment requirements.
1566
+ * Policies are applied in order before the selector chooses the final option.
1567
+ *
1568
+ * @param x402Version - The x402 protocol version
1569
+ * @param paymentRequirements - Array of payment requirements to filter/transform
1570
+ * @returns Filtered array of payment requirements
1571
+ */
1572
+ type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];
1573
+ /**
1574
+ * Configuration for registering a payment scheme with a specific network
1575
+ */
1576
+ interface SchemeRegistration {
1577
+ /**
1578
+ * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')
1579
+ */
1580
+ network: Network;
1581
+ /**
1582
+ * The scheme client implementation for this network
1583
+ */
1584
+ client: SchemeNetworkClient;
1585
+ /**
1586
+ * The x402 protocol version to use for this scheme
1587
+ *
1588
+ * @default 2
1589
+ */
1590
+ x402Version?: number;
1591
+ }
1592
+ /**
1593
+ * Configuration options for the fetch wrapper
1594
+ */
1595
+ interface x402ClientConfig {
1596
+ /**
1597
+ * Array of scheme registrations defining which payment methods are supported
1598
+ */
1599
+ schemes: SchemeRegistration[];
1600
+ /**
1601
+ * Policies to apply to the client
1602
+ */
1603
+ policies?: PaymentPolicy[];
1604
+ /**
1605
+ * Custom payment requirements selector function
1606
+ * If not provided, uses the default selector (first available option)
1607
+ */
1608
+ paymentRequirementsSelector?: SelectPaymentRequirements;
1609
+ }
1610
+ /**
1611
+ * Core client for managing x402 payment schemes and creating payment payloads.
1612
+ *
1613
+ * Handles registration of payment schemes, policy-based filtering of payment requirements,
1614
+ * and creation of payment payloads based on server requirements.
1615
+ */
1616
+ declare class x402Client {
1617
+ private readonly paymentRequirementsSelector;
1618
+ private readonly registeredClientSchemes;
1619
+ private readonly schemeClientHookAdapters;
1620
+ private readonly policies;
1621
+ private readonly registeredExtensions;
1622
+ private beforePaymentCreationHooks;
1623
+ private afterPaymentCreationHooks;
1624
+ private onPaymentCreationFailureHooks;
1625
+ private paymentResponseHooks;
1626
+ /**
1627
+ * Creates a new x402Client instance.
1628
+ *
1629
+ * @param paymentRequirementsSelector - Function to select payment requirements from available options
1630
+ */
1631
+ constructor(paymentRequirementsSelector?: SelectPaymentRequirements);
1632
+ /**
1633
+ * Creates a new x402Client instance from a configuration object.
1634
+ *
1635
+ * @param config - The client configuration including schemes, policies, and payment requirements selector
1636
+ * @returns A configured x402Client instance
1637
+ */
1638
+ static fromConfig(config: x402ClientConfig): x402Client;
1639
+ /**
1640
+ * Registers a scheme client for the current x402 version.
1641
+ *
1642
+ * @param network - The network to register the client for
1643
+ * @param client - The scheme network client to register
1644
+ * @returns The x402Client instance for chaining
1645
+ */
1646
+ register(network: Network, client: SchemeNetworkClient): x402Client;
1647
+ /**
1648
+ * Registers a scheme client for x402 version 1.
1649
+ *
1650
+ * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
1651
+ * @param client - The scheme network client to register
1652
+ * @returns The x402Client instance for chaining
1653
+ */
1654
+ registerV1(network: string, client: SchemeNetworkClient): x402Client;
1655
+ /**
1656
+ * Registers a policy to filter or transform payment requirements.
1657
+ *
1658
+ * Policies are applied in order after filtering by registered schemes
1659
+ * and before the selector chooses the final payment requirement.
1660
+ *
1661
+ * @param policy - Function to filter/transform payment requirements
1662
+ * @returns The x402Client instance for chaining
1663
+ *
1664
+ * @example
1665
+ * ```typescript
1666
+ * // Prefer cheaper options
1667
+ * client.registerPolicy((version, reqs) =>
1668
+ * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
1669
+ * );
1670
+ *
1671
+ * // Prefer specific networks
1672
+ * client.registerPolicy((version, reqs) =>
1673
+ * reqs.filter(r => r.network.startsWith('eip155:'))
1674
+ * );
1675
+ * ```
1676
+ */
1677
+ registerPolicy(policy: PaymentPolicy): x402Client;
1678
+ /**
1679
+ * Registers a client extension that can enrich payment payloads.
1680
+ *
1681
+ * Extensions are invoked after the scheme creates the base payload and the
1682
+ * payload is wrapped with extensions/resource/accepted data. If the extension's
1683
+ * key is present in `paymentRequired.extensions`, the extension's
1684
+ * `enrichPaymentPayload` hook is called to modify the payload.
1685
+ *
1686
+ * @param extension - The client extension to register
1687
+ * @returns The x402Client instance for chaining
1688
+ */
1689
+ registerExtension(extension: ClientExtension): x402Client;
1690
+ /**
1691
+ * Get all registered client extensions.
1692
+ *
1693
+ * @returns Array of registered extensions
1694
+ */
1695
+ getExtensions(): ClientExtension[];
1696
+ /**
1697
+ * Register a hook to execute before payment payload creation.
1698
+ * Can abort creation by returning { abort: true, reason: string }
1699
+ *
1700
+ * @param hook - The hook function to register
1701
+ * @returns The x402Client instance for chaining
1702
+ */
1703
+ onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client;
1704
+ /**
1705
+ * Register a hook to execute after successful payment payload creation.
1706
+ *
1707
+ * @param hook - The hook function to register
1708
+ * @returns The x402Client instance for chaining
1709
+ */
1710
+ onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client;
1711
+ /**
1712
+ * Register a hook to execute when payment payload creation fails.
1713
+ * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
1714
+ *
1715
+ * @param hook - The hook function to register
1716
+ * @returns The x402Client instance for chaining
1717
+ */
1718
+ onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client;
1719
+ /**
1720
+ * Register a hook to execute after a paid request completes.
1721
+ * Can signal recovery by returning { recovered: true }, causing the transport to retry.
1722
+ *
1723
+ * @param hook - The hook function to register
1724
+ * @returns The x402Client instance for chaining
1725
+ */
1726
+ onPaymentResponse(hook: OnPaymentResponseHook): x402Client;
1727
+ /**
1728
+ * Fires all registered payment response hooks in order.
1729
+ * Returns `{ recovered: true }` if any hook signals recovery (first wins).
1730
+ *
1731
+ * @param ctx - The payment response context
1732
+ * @returns Recovery signal or undefined
1733
+ */
1734
+ handlePaymentResponse(ctx: PaymentResponseContext): Promise<{
1735
+ recovered: true;
1736
+ } | undefined>;
1737
+ /**
1738
+ * Creates a payment payload based on a PaymentRequired response.
1739
+ *
1740
+ * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
1741
+ * response and constructs a complete PaymentPayload with the accepted requirements.
1742
+ *
1743
+ * @param paymentRequired - The PaymentRequired response from the server
1744
+ * @returns Promise resolving to the complete payment payload
1745
+ */
1746
+ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
1747
+ /**
1748
+ * Merges server-declared extensions with client extension echoes.
1749
+ * Client extension data may add fields, but server-declared fields remain intact.
1750
+ *
1751
+ * @param serverExtensions - Extensions declared by the server in the 402 response
1752
+ * @param clientExtensions - Extensions provided by the client or scheme
1753
+ * @returns The merged extensions object, or undefined if both inputs are undefined
1754
+ */
1755
+ private mergeExtensions;
1756
+ /**
1757
+ * Enriches a payment payload by calling registered extension hooks.
1758
+ * For each extension key present in the PaymentRequired response,
1759
+ * invokes the corresponding extension's enrichPaymentPayload callback.
1760
+ *
1761
+ * @param paymentPayload - The payment payload to enrich with extension data
1762
+ * @param paymentRequired - The PaymentRequired response containing extension declarations
1763
+ * @returns The enriched payment payload with extension data applied
1764
+ */
1765
+ private enrichPaymentPayloadWithExtensions;
1766
+ /**
1767
+ * Selects appropriate payment requirements based on registered clients and policies.
1768
+ *
1769
+ * Selection process:
1770
+ * 1. Filter by registered schemes (network + scheme support)
1771
+ * 2. Apply all registered policies in order
1772
+ * 3. Use selector to choose final requirement
1773
+ *
1774
+ * @param x402Version - The x402 protocol version
1775
+ * @param paymentRequirements - Array of available payment requirements
1776
+ * @returns The selected payment requirements
1777
+ */
1778
+ private selectPaymentRequirements;
1779
+ /**
1780
+ * Internal method to register a scheme client.
1781
+ *
1782
+ * @param x402Version - The x402 protocol version
1783
+ * @param network - The network to register the client for
1784
+ * @param client - The scheme network client to register
1785
+ * @returns The x402Client instance for chaining
1786
+ */
1787
+ private _registerScheme;
1788
+ /**
1789
+ * Returns manual hooks followed by the selected scheme hook and declared extension hooks.
1790
+ *
1791
+ * @param phase - Hook slot to collect
1792
+ * @param x402Version - Protocol version for the selected requirement
1793
+ * @param requirements - Selected payment requirement
1794
+ * @param declaredExtensions - Extension declarations that scope extension hooks
1795
+ * @returns Hooks in invocation order
1796
+ */
1797
+ private getLabeledHooks;
1798
+ /**
1799
+ * Maps internal hook phases to extension hook names.
1800
+ *
1801
+ * @param phase - Internal hook phase
1802
+ * @returns Extension hook key for the phase
1803
+ */
1804
+ private getClientExtensionHookKey;
1805
+ }
1806
+
1807
+ export { type SkipHandlerDirective as $, FacilitatorResponseError as A, getFacilitatorResponseError as B, type CompiledRoute as C, type DynamicPayTo as D, x402ResourceServer as E, type FacilitatorExtension as F, type ResourceConfig as G, type HTTPAdapter as H, type PaymentRequiredContext as I, type VerifyContext as J, type VerifyResultContext as K, type VerifyFailureContext as L, type SettleContext as M, type Network as N, type SettleResultContext as O, type PaymentPayload as P, type SettleFailureContext as Q, type RouteConfig as R, type SettleResponse as S, type VerifiedPaymentCanceledContext as T, type UnpaidResponseBody as U, type VerifyResponse as V, type VerifiedPaymentCancellationReason as W, type VerifiedPaymentCancelOptions as X, type PaymentCancellationDispatcher as Y, type SettlementOverrides as Z, type ExtensionValidationResult as _, type PaymentRequirements as a, type ResourceVerifyRespone as a0, type BeforeVerifyHook as a1, type AfterVerifyHook as a2, type OnVerifyFailureHook as a3, type BeforeSettleHook as a4, type AfterSettleHook as a5, type OnSettleFailureHook as a6, type OnVerifiedPaymentCanceledHook as a7, type SchemeEnrichPaymentRequiredResponseHook as a8, type SchemePaymentRequiredContext as a9, type SupportedResponseV1 as aA, type Money as aB, type AssetAmount as aC, type Price as aD, type VerifyRequest as aE, type SettleRequest as aF, type SupportedResponse as aG, type SupportedKind as aH, VerifyError as aI, SettleError as aJ, type ResourceInfo as aK, type SchemeNetworkClient as aL, type SchemeClientHooks as aM, type SchemeNetworkServer as aN, type SchemeServerHooks as aO, type MoneyParser as aP, type PaymentPayloadResult as aQ, type PaymentPayloadContext as aR, type FacilitatorContext as aS, type ResourceServerExtension as aT, type ResourceServerExtensionHooks as aU, type DeepReadonly as aV, type SchemeEnrichSettlementPayloadHook as aa, type SchemeEnrichSettlementResponseHook as ab, SETTLEMENT_OVERRIDES_HEADER as ac, checkIfBazaarNeeded as ad, x402Client as ae, type PaymentCreationContext as af, type PaymentCreatedContext as ag, type PaymentCreationFailureContext as ah, type BeforePaymentCreationHook as ai, type AfterPaymentCreationHook as aj, type OnPaymentCreationFailureHook as ak, type PaymentResponseContext as al, type OnPaymentResponseHook as am, type SelectPaymentRequirements as an, type ClientExtensionHooks as ao, type ClientTransportExtensionHooks as ap, type ClientExtension as aq, type PaymentPolicy as ar, type SchemeRegistration as as, type x402ClientConfig as at, type PaymentRequirementsV1 as au, type PaymentRequiredV1 as av, type PaymentPayloadV1 as aw, type VerifyRequestV1 as ax, type SettleRequestV1 as ay, type SettleResponseV1 as az, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type HTTPRequestContext as d, type HTTPTransportContext as e, type HTTPResponseInstructions as f, type HTTPProcessResult as g, type PaywallConfig as h, type PaywallProvider as i, type PaymentOption as j, type RoutesConfig as k, type DynamicPrice as l, type HTTPResponseBody as m, type SettlementFailedResponseBody as n, type ProcessSettleResultResponse as o, type ProcessSettleSuccessResponse as p, type ProcessSettleFailureResponse as q, type RouteValidationError as r, RouteConfigurationError as s, type ProtectedRequestHook as t, type HTTPResourceServerExtensionHooks as u, type ResourceServerTransportExtensionHooks as v, HTTPFacilitatorClient as w, x402HTTPResourceServer as x, type FacilitatorClient as y, type FacilitatorConfig as z };