@parallel-protocol/x402 0.5.3 → 0.7.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.
@@ -1,491 +0,0 @@
1
- 'use strict';
2
-
3
- var zod = require('zod');
4
- var chains = require('@parallel-protocol/chains');
5
-
6
- // src/errors.ts
7
- var X402_ERROR_CODES = {
8
- FACILITATOR_UNAVAILABLE: "FACILITATOR_UNAVAILABLE",
9
- FACILITATOR_INVALID_RESPONSE: "FACILITATOR_INVALID_RESPONSE",
10
- INVALID_PAYMENT: "INVALID_PAYMENT"
11
- };
12
- var X402ConfigError = class extends Error {
13
- constructor(message, cause) {
14
- super(message);
15
- this.name = "X402ConfigError";
16
- this.cause = cause;
17
- }
18
- };
19
- var X402RuntimeError = class extends Error {
20
- constructor(code) {
21
- super(code);
22
- this.code = code;
23
- this.name = "X402RuntimeError";
24
- }
25
- code;
26
- };
27
-
28
- // src/utils.ts
29
- var EIP155_NETWORKS = {
30
- ethereum: "eip155:1",
31
- base: "eip155:8453",
32
- avalanche: "eip155:43114",
33
- hyperevm: "eip155:999"
34
- };
35
- function parseDecimalAmount(amount, decimals) {
36
- const multiplier = 10n ** BigInt(decimals);
37
- const parts = amount.split(".");
38
- const whole = parts[0] ?? "0";
39
- const fraction = (parts[1] ?? "").padEnd(decimals, "0").slice(0, decimals);
40
- return BigInt(whole) * multiplier + BigInt(fraction || "0");
41
- }
42
- function parsePrice(price, decimals = 18) {
43
- if (typeof price === "bigint") return price;
44
- const match = price.match(/^(\d+(?:\.\d+)?)$/);
45
- if (match?.[1]) return parseDecimalAmount(match[1], decimals);
46
- throw new Error(
47
- `Invalid price format: "${price}". Expected "0.01" or a bigint.`
48
- );
49
- }
50
- function validateAddress(address) {
51
- return /^0x[0-9a-fA-F]{40}$/.test(address);
52
- }
53
- function toEip155Network(network) {
54
- if (network.startsWith("eip155:")) return network;
55
- return EIP155_NETWORKS[network] ?? `eip155:${network}`;
56
- }
57
- function encodeBase64(obj) {
58
- return Buffer.from(JSON.stringify(obj)).toString("base64");
59
- }
60
- function decodeBase64(str) {
61
- return JSON.parse(Buffer.from(str, "base64").toString("utf8"));
62
- }
63
- function matchRoute(path, routes) {
64
- if (routes[path]) return routes[path];
65
- let bestMatch;
66
- let bestLength = 0;
67
- for (const [pattern, config] of Object.entries(routes)) {
68
- if (path.startsWith(`${pattern}/`) && pattern.length > bestLength) {
69
- bestMatch = config;
70
- bestLength = pattern.length;
71
- }
72
- }
73
- return bestMatch;
74
- }
75
- var ethereumAddressSchema = zod.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "Invalid Ethereum address");
76
- var txHashSchema = zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/);
77
- var priceSchema = zod.z.union([
78
- zod.z.bigint().positive("Price must be greater than 0"),
79
- zod.z.string().regex(/^\d+(?:\.\d+)?$/, 'Price must be in format "0.01"').refine((price) => Number(price) > 0, "Price must be greater than 0")
80
- ]);
81
- var facilitatorConfigSchema = zod.z.object({
82
- url: zod.z.string().refine((v) => URL.canParse(v), "Invalid facilitator URL"),
83
- apiKey: zod.z.string().optional()
84
- });
85
- var routeConfigSchema = zod.z.object({
86
- price: priceSchema,
87
- network: zod.z.string().min(1, "Network is required"),
88
- payTo: ethereumAddressSchema,
89
- acceptedTokens: zod.z.array(ethereumAddressSchema).optional(),
90
- description: zod.z.string().optional()
91
- });
92
- var paymentMiddlewareConfigSchema = zod.z.object({
93
- facilitator: facilitatorConfigSchema,
94
- routes: zod.z.record(zod.z.string(), routeConfigSchema).refine((r) => Object.keys(r).length > 0, "At least one route is required")
95
- });
96
- var facilitatorResponseSchema = zod.z.discriminatedUnion("success", [
97
- zod.z.object({
98
- success: zod.z.literal(true),
99
- txHash: txHashSchema,
100
- route: zod.z.string(),
101
- chain: zod.z.string(),
102
- gasSponsored: zod.z.boolean(),
103
- networkId: zod.z.string()
104
- }),
105
- zod.z.object({
106
- success: zod.z.literal(false),
107
- error: zod.z.object({
108
- code: zod.z.string(),
109
- message: zod.z.string(),
110
- hint: zod.z.string().optional()
111
- })
112
- })
113
- ]);
114
- var verifyResponseSchema = zod.z.object({
115
- isValid: zod.z.literal(true)
116
- });
117
- var settleSuccessSchema = zod.z.object({
118
- txHash: txHashSchema,
119
- route: zod.z.string(),
120
- gasSponsored: zod.z.boolean()
121
- });
122
- var settleErrorSchema = zod.z.object({
123
- error: zod.z.string(),
124
- message: zod.z.string()
125
- });
126
- var settleResponseSchema = zod.z.union([
127
- settleSuccessSchema,
128
- settleErrorSchema
129
- ]);
130
-
131
- // src/client.ts
132
- var FACILITATOR_TIMEOUT_MS = 1e4;
133
- var SETTLE_TIMEOUT_MS = 6e4;
134
- function decodePaymentHeader(paymentHeader) {
135
- try {
136
- return decodeBase64(paymentHeader);
137
- } catch {
138
- throw new X402RuntimeError(X402_ERROR_CODES.INVALID_PAYMENT);
139
- }
140
- }
141
- var FacilitatorClient = class {
142
- constructor(config) {
143
- this.config = config;
144
- }
145
- config;
146
- async verify(paymentHeader, paymentRequirements) {
147
- const paymentPayload = decodePaymentHeader(paymentHeader);
148
- let json;
149
- try {
150
- const response = await fetch(`${this.config.url}/x402/verify`, {
151
- method: "POST",
152
- headers: this.buildHeaders(),
153
- body: JSON.stringify({ paymentPayload, paymentRequirements }),
154
- signal: AbortSignal.timeout(FACILITATOR_TIMEOUT_MS)
155
- });
156
- if (!response.ok) {
157
- const errorBody = await response.json().catch(() => null);
158
- const code = errorBody?.error ?? X402_ERROR_CODES.FACILITATOR_UNAVAILABLE;
159
- throw new X402RuntimeError(code);
160
- }
161
- json = await response.json();
162
- } catch (e) {
163
- if (e instanceof X402RuntimeError) throw e;
164
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_UNAVAILABLE);
165
- }
166
- try {
167
- verifyResponseSchema.parse(json);
168
- } catch {
169
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_INVALID_RESPONSE);
170
- }
171
- }
172
- async settle(paymentHeader, paymentRequirements) {
173
- const paymentPayload = decodePaymentHeader(paymentHeader);
174
- let json;
175
- try {
176
- const response = await fetch(`${this.config.url}/x402/settle`, {
177
- method: "POST",
178
- headers: this.buildHeaders(),
179
- body: JSON.stringify({ paymentPayload, paymentRequirements }),
180
- signal: AbortSignal.timeout(SETTLE_TIMEOUT_MS)
181
- });
182
- if (!response.ok) {
183
- const errorBody = await response.json().catch(() => null);
184
- const code = errorBody?.error ?? "SUBMISSION_FAILED";
185
- const message = errorBody?.message ?? "Settlement failed";
186
- return { success: false, error: { code, message } };
187
- }
188
- json = await response.json();
189
- } catch (e) {
190
- if (e instanceof X402RuntimeError) throw e;
191
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_UNAVAILABLE);
192
- }
193
- try {
194
- const parsed = settleResponseSchema.parse(json);
195
- if ("txHash" in parsed) {
196
- return {
197
- success: true,
198
- txHash: parsed.txHash,
199
- route: parsed.route,
200
- chain: paymentRequirements.network,
201
- gasSponsored: parsed.gasSponsored,
202
- networkId: toEip155Network(paymentRequirements.network)
203
- };
204
- }
205
- return {
206
- success: false,
207
- error: { code: parsed.error, message: parsed.message }
208
- };
209
- } catch {
210
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_INVALID_RESPONSE);
211
- }
212
- }
213
- async pay(paymentHeader) {
214
- const headers = this.buildHeaders();
215
- headers["X-PAYMENT"] = paymentHeader;
216
- let json;
217
- try {
218
- const response = await fetch(`${this.config.url}/x402/pay`, {
219
- method: "POST",
220
- headers,
221
- signal: AbortSignal.timeout(FACILITATOR_TIMEOUT_MS)
222
- });
223
- if (!response.ok) {
224
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_UNAVAILABLE);
225
- }
226
- json = await response.json();
227
- } catch (e) {
228
- if (e instanceof X402RuntimeError) throw e;
229
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_UNAVAILABLE);
230
- }
231
- try {
232
- return facilitatorResponseSchema.parse(json);
233
- } catch {
234
- throw new X402RuntimeError(X402_ERROR_CODES.FACILITATOR_INVALID_RESPONSE);
235
- }
236
- }
237
- buildHeaders() {
238
- const headers = {
239
- "Content-Type": "application/json"
240
- };
241
- if (this.config.apiKey) {
242
- headers["X-API-Key"] = this.config.apiKey;
243
- }
244
- return headers;
245
- }
246
- };
247
- var PARALLEL_TOKENS = {
248
- ethereum: {
249
- usdp: "0x9B3a8f7CEC208e247d97dEE13313690977e24459",
250
- susdp: "0xd3a452B305C8285c0Dd7b8537665c734d3D279eF",
251
- usdc: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
252
- frxUSD: "0xCAcd6fd266aF91b8AeD52aCCc382b4e165586E29",
253
- sfrxUSD: "0xcf62F905562626CfcDD2261162a51fd02Fc9c5b6",
254
- USDe: "0x4c9EDD5852cd905f086C759E8383e09bff1E68B3",
255
- sUSDe: "0x9D39A5DE30e57443BfF2A8307A4256c8797A3497"
256
- },
257
- base: {
258
- usdp: "0x76A9A0062ec6712b99B4f63bD2b4270185759dd5",
259
- susdp: "0x472eD57b376fE400259FB28e5C46eB53f0E3e7E7",
260
- usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
261
- USDS: "0x820C137fa70C8691f0e44Dc420a5e53c168921Dc",
262
- sUSDS: "0x5875eEE11Cf8398102FdAd704C9E96607675467a"
263
- },
264
- avalanche: {
265
- usdp: "0x9eE1963f05553eF838604Dd39403be21ceF26AA4",
266
- susdp: "0x9d92c21205383651610f90722131655a5b8ed3e0",
267
- usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
268
- ygamiUSDC: "0x9fD32FD5e32C6B95483d36C5E724C5C5250Ce010"
269
- },
270
- hyperevm: {
271
- usdp: "0xBE65F0F410A72BeC163dC65d46c83699e957D588",
272
- susdp: "0x9B3a8f7CEC208e247d97dEE13313690977e24459",
273
- usdc: "0xb88339cb7199b77e23db6e890353e22632ba630f",
274
- USDe: "0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34",
275
- sUSDe: "0x211Cc4DD073734dA055fbF44a2b4667d5E5fE5d2"
276
- }
277
- };
278
- function getDefaultAcceptedTokens(network) {
279
- const entry = PARALLEL_TOKENS[network];
280
- if (!entry) return void 0;
281
- return [entry.usdp, entry.usdc, entry.susdp];
282
- }
283
- function getTokenDecimals(network, address) {
284
- return chains.getTokenDecimals(network, address);
285
- }
286
-
287
- // src/middleware.ts
288
- function resolveAcceptedTokens(config) {
289
- if (config.acceptedTokens?.length) {
290
- return config.acceptedTokens;
291
- }
292
- const defaults = getDefaultAcceptedTokens(config.network);
293
- if (defaults) return defaults;
294
- throw new X402ConfigError(
295
- `acceptedTokens is required for network "${config.network}" \u2014 no defaults available for this chain`
296
- );
297
- }
298
- function resolveDecimals(config, asset) {
299
- const decimals = config.decimals ?? getTokenDecimals(config.network, asset);
300
- if (decimals === void 0) {
301
- throw new X402ConfigError(
302
- `Unknown decimals for token ${asset} on "${config.network}" \u2014 add it to the @parallel-protocol/chains catalog or set the route's \`decimals\` explicitly`
303
- );
304
- }
305
- return decimals;
306
- }
307
- function buildPaymentRequired(url, config, resolvedTokens) {
308
- const network = toEip155Network(config.network);
309
- const accepts = resolvedTokens.map((asset) => {
310
- const decimals = resolveDecimals(config, asset);
311
- return {
312
- scheme: "exact",
313
- network,
314
- asset,
315
- amount: parsePrice(config.price, decimals).toString(),
316
- payTo: config.payTo,
317
- maxTimeoutSeconds: 300,
318
- extra: { decimals }
319
- };
320
- });
321
- return {
322
- x402Version: 2,
323
- resource: {
324
- url,
325
- description: config.description,
326
- mimeType: "application/json"
327
- },
328
- accepts
329
- };
330
- }
331
- function decodePaymentPayload(header) {
332
- try {
333
- const parsed = JSON.parse(
334
- Buffer.from(header, "base64").toString("utf8")
335
- );
336
- return typeof parsed === "object" && parsed !== null ? parsed : void 0;
337
- } catch {
338
- return void 0;
339
- }
340
- }
341
- function deliveredToken(payload, chainTokens) {
342
- if (payload.method === "depositWithAuthorization" || payload.payload?.depositAuthorization) {
343
- return chainTokens?.susdp;
344
- }
345
- if (payload.method === "redeemWithAuthorization") return chainTokens?.usdp;
346
- if (payload.swapParams?.tokenOut) return payload.swapParams.tokenOut;
347
- if (payload.method === "partialRedeemWithAuthorization") {
348
- return chainTokens?.usdp;
349
- }
350
- return payload.tokenIn ?? chainTokens?.usdp;
351
- }
352
- function resolveDeliveredAsset(header, config, resolvedTokens) {
353
- const payload = decodePaymentPayload(header);
354
- const target = payload ? deliveredToken(
355
- payload,
356
- PARALLEL_TOKENS[config.network]
357
- ) : void 0;
358
- const lower = target?.toLowerCase();
359
- return resolvedTokens.find((token) => token.toLowerCase() === lower) ?? resolvedTokens[0];
360
- }
361
- function buildFacilitatorRequirements(config, asset) {
362
- const decimals = resolveDecimals(config, asset);
363
- return {
364
- maxAmountRequired: parsePrice(config.price, decimals).toString(),
365
- asset,
366
- payTo: config.payTo,
367
- network: config.network
368
- };
369
- }
370
- function paymentRequiredResponse(url, config, resolvedTokens, error) {
371
- const paymentRequired = buildPaymentRequired(url, config, resolvedTokens);
372
- if (error) paymentRequired.error = error;
373
- return {
374
- status: 402,
375
- headers: {
376
- "Content-Type": "application/json",
377
- "payment-required": encodeBase64(paymentRequired),
378
- "access-control-expose-headers": "payment-required"
379
- },
380
- body: paymentRequired
381
- };
382
- }
383
- function createPaymentGate(config) {
384
- try {
385
- paymentMiddlewareConfigSchema.parse(config);
386
- } catch (cause) {
387
- throw new X402ConfigError(
388
- "Invalid paymentMiddleware config \u2014 check your routes, facilitator URL and payTo addresses",
389
- cause
390
- );
391
- }
392
- const client = new FacilitatorClient(config.facilitator);
393
- return async (adapter) => {
394
- if (adapter.getMethod().toUpperCase() === "OPTIONS")
395
- return { type: "pass" };
396
- const routeConfig = matchRoute(adapter.getPath(), config.routes);
397
- if (!routeConfig) return { type: "pass" };
398
- const resolvedTokens = resolveAcceptedTokens(routeConfig);
399
- const paymentHeader = adapter.getHeader("payment-signature") ?? adapter.getHeader("x-payment");
400
- if (!paymentHeader) {
401
- return {
402
- type: "error",
403
- result: paymentRequiredResponse(
404
- adapter.getUrl(),
405
- routeConfig,
406
- resolvedTokens
407
- )
408
- };
409
- }
410
- const requirements = buildFacilitatorRequirements(
411
- routeConfig,
412
- resolveDeliveredAsset(paymentHeader, routeConfig, resolvedTokens)
413
- );
414
- try {
415
- await client.verify(paymentHeader, requirements);
416
- } catch (e) {
417
- const code = e instanceof X402RuntimeError ? e.code : X402_ERROR_CODES.FACILITATOR_UNAVAILABLE;
418
- return {
419
- type: "error",
420
- result: paymentRequiredResponse(
421
- adapter.getUrl(),
422
- routeConfig,
423
- resolvedTokens,
424
- code
425
- )
426
- };
427
- }
428
- return {
429
- type: "verified",
430
- settle: () => client.settle(paymentHeader, requirements)
431
- };
432
- };
433
- }
434
- function createPaymentMiddleware(config) {
435
- const gate = createPaymentGate(config);
436
- return async (adapter) => {
437
- const gateResult = await gate(adapter);
438
- if (gateResult.type === "pass") return { pass: true };
439
- if (gateResult.type === "error") return gateResult.result;
440
- let handlerResult;
441
- try {
442
- handlerResult = await adapter.runHandler();
443
- } catch {
444
- return { pass: true, handlerRan: true };
445
- }
446
- if (handlerResult.status >= 200 && handlerResult.status < 300) {
447
- let settled = false;
448
- try {
449
- const settleResponse = await gateResult.settle();
450
- if (settleResponse.success) {
451
- handlerResult.setResponseHeader(
452
- "payment-response",
453
- encodeBase64(settleResponse)
454
- );
455
- handlerResult.setResponseHeader(
456
- "access-control-expose-headers",
457
- "payment-response"
458
- );
459
- settled = true;
460
- }
461
- } catch {
462
- }
463
- if (!settled) {
464
- handlerResult.discardResponse();
465
- return {
466
- status: 402,
467
- headers: { "Content-Type": "application/json" },
468
- body: {
469
- error: "PAYMENT_SETTLEMENT_FAILED",
470
- message: "Payment could not be confirmed after multiple attempts. Please retry."
471
- }
472
- };
473
- }
474
- }
475
- handlerResult.sendResponse();
476
- return { pass: true, handlerRan: true };
477
- };
478
- }
479
-
480
- exports.FacilitatorClient = FacilitatorClient;
481
- exports.PARALLEL_TOKENS = PARALLEL_TOKENS;
482
- exports.X402ConfigError = X402ConfigError;
483
- exports.X402RuntimeError = X402RuntimeError;
484
- exports.X402_ERROR_CODES = X402_ERROR_CODES;
485
- exports.createPaymentGate = createPaymentGate;
486
- exports.createPaymentMiddleware = createPaymentMiddleware;
487
- exports.encodeBase64 = encodeBase64;
488
- exports.getDefaultAcceptedTokens = getDefaultAcceptedTokens;
489
- exports.parsePrice = parsePrice;
490
- exports.toEip155Network = toEip155Network;
491
- exports.validateAddress = validateAddress;
@@ -1,20 +0,0 @@
1
- 'use strict';
2
-
3
- // src/timeout.ts
4
- var HANDLER_TIMEOUT_MS = 3e4;
5
- var HANDLER_TIMEOUT = /* @__PURE__ */ Symbol("x402:handler-timeout");
6
- async function raceTimeout(promise, ms = HANDLER_TIMEOUT_MS) {
7
- let timer;
8
- const timeout = new Promise((resolve) => {
9
- timer = setTimeout(() => resolve(HANDLER_TIMEOUT), ms);
10
- timer.unref?.();
11
- });
12
- try {
13
- return await Promise.race([promise, timeout]);
14
- } finally {
15
- clearTimeout(timer);
16
- }
17
- }
18
-
19
- exports.HANDLER_TIMEOUT = HANDLER_TIMEOUT;
20
- exports.raceTimeout = raceTimeout;
@@ -1,95 +0,0 @@
1
- import { Address } from 'viem';
2
-
3
- interface FacilitatorConfig {
4
- url: string;
5
- apiKey?: string;
6
- }
7
- interface RouteConfig {
8
- price: string | bigint;
9
- decimals?: number;
10
- network: string;
11
- payTo: Address;
12
- acceptedTokens?: Address[];
13
- description?: string;
14
- }
15
- interface PaymentMiddlewareConfig {
16
- facilitator: FacilitatorConfig;
17
- routes: Record<string, RouteConfig>;
18
- }
19
- interface RunHandlerResult {
20
- status: number;
21
- setResponseHeader(name: string, value: string): void;
22
- sendResponse(): void;
23
- discardResponse(): void;
24
- }
25
- interface HTTPAdapter {
26
- getHeader(name: string): string | undefined;
27
- getMethod(): string;
28
- getPath(): string;
29
- getUrl(): string;
30
- runHandler?(): Promise<RunHandlerResult>;
31
- }
32
- interface ResourceInfo {
33
- url: string;
34
- description?: string;
35
- mimeType?: string;
36
- }
37
- interface PaymentRequirements {
38
- scheme: string;
39
- network: string;
40
- asset: string;
41
- amount: string;
42
- payTo: string;
43
- maxTimeoutSeconds: number;
44
- extra: Record<string, unknown>;
45
- }
46
- interface PaymentRequired {
47
- x402Version: number;
48
- error?: string;
49
- resource: ResourceInfo;
50
- accepts: PaymentRequirements[];
51
- extensions?: Record<string, unknown>;
52
- }
53
- interface FacilitatorPaymentRequirements {
54
- maxAmountRequired: string;
55
- asset: string;
56
- payTo: string;
57
- network: string;
58
- }
59
- interface PaymentConfirmation {
60
- success: true;
61
- txHash: Address;
62
- route: string;
63
- chain: string;
64
- gasSponsored: boolean;
65
- networkId: string;
66
- }
67
- interface PaymentFailure {
68
- success: false;
69
- error: {
70
- code: string;
71
- message: string;
72
- hint?: string;
73
- };
74
- }
75
- type FacilitatorResponse = PaymentConfirmation | PaymentFailure;
76
- interface MiddlewareResult {
77
- status: number;
78
- headers: Record<string, string>;
79
- body: unknown;
80
- }
81
- interface PassResult {
82
- pass: true;
83
- handlerRan?: true;
84
- }
85
- type PaymentGateResult = {
86
- type: "pass";
87
- } | {
88
- type: "error";
89
- result: MiddlewareResult;
90
- } | {
91
- type: "verified";
92
- settle(): Promise<FacilitatorResponse>;
93
- };
94
-
95
- export type { FacilitatorConfig as F, HTTPAdapter as H, MiddlewareResult as M, PaymentMiddlewareConfig as P, RunHandlerResult as R, FacilitatorPaymentRequirements as a, FacilitatorResponse as b, PaymentGateResult as c, PassResult as d, PaymentConfirmation as e, PaymentFailure as f, PaymentRequired as g, PaymentRequirements as h, ResourceInfo as i, RouteConfig as j };
@@ -1,95 +0,0 @@
1
- import { Address } from 'viem';
2
-
3
- interface FacilitatorConfig {
4
- url: string;
5
- apiKey?: string;
6
- }
7
- interface RouteConfig {
8
- price: string | bigint;
9
- decimals?: number;
10
- network: string;
11
- payTo: Address;
12
- acceptedTokens?: Address[];
13
- description?: string;
14
- }
15
- interface PaymentMiddlewareConfig {
16
- facilitator: FacilitatorConfig;
17
- routes: Record<string, RouteConfig>;
18
- }
19
- interface RunHandlerResult {
20
- status: number;
21
- setResponseHeader(name: string, value: string): void;
22
- sendResponse(): void;
23
- discardResponse(): void;
24
- }
25
- interface HTTPAdapter {
26
- getHeader(name: string): string | undefined;
27
- getMethod(): string;
28
- getPath(): string;
29
- getUrl(): string;
30
- runHandler?(): Promise<RunHandlerResult>;
31
- }
32
- interface ResourceInfo {
33
- url: string;
34
- description?: string;
35
- mimeType?: string;
36
- }
37
- interface PaymentRequirements {
38
- scheme: string;
39
- network: string;
40
- asset: string;
41
- amount: string;
42
- payTo: string;
43
- maxTimeoutSeconds: number;
44
- extra: Record<string, unknown>;
45
- }
46
- interface PaymentRequired {
47
- x402Version: number;
48
- error?: string;
49
- resource: ResourceInfo;
50
- accepts: PaymentRequirements[];
51
- extensions?: Record<string, unknown>;
52
- }
53
- interface FacilitatorPaymentRequirements {
54
- maxAmountRequired: string;
55
- asset: string;
56
- payTo: string;
57
- network: string;
58
- }
59
- interface PaymentConfirmation {
60
- success: true;
61
- txHash: Address;
62
- route: string;
63
- chain: string;
64
- gasSponsored: boolean;
65
- networkId: string;
66
- }
67
- interface PaymentFailure {
68
- success: false;
69
- error: {
70
- code: string;
71
- message: string;
72
- hint?: string;
73
- };
74
- }
75
- type FacilitatorResponse = PaymentConfirmation | PaymentFailure;
76
- interface MiddlewareResult {
77
- status: number;
78
- headers: Record<string, string>;
79
- body: unknown;
80
- }
81
- interface PassResult {
82
- pass: true;
83
- handlerRan?: true;
84
- }
85
- type PaymentGateResult = {
86
- type: "pass";
87
- } | {
88
- type: "error";
89
- result: MiddlewareResult;
90
- } | {
91
- type: "verified";
92
- settle(): Promise<FacilitatorResponse>;
93
- };
94
-
95
- export type { FacilitatorConfig as F, HTTPAdapter as H, MiddlewareResult as M, PaymentMiddlewareConfig as P, RunHandlerResult as R, FacilitatorPaymentRequirements as a, FacilitatorResponse as b, PaymentGateResult as c, PassResult as d, PaymentConfirmation as e, PaymentFailure as f, PaymentRequired as g, PaymentRequirements as h, ResourceInfo as i, RouteConfig as j };