uvd-x402-sdk 2.5.0 → 2.10.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 (75) hide show
  1. package/README.md +380 -3
  2. package/dist/adapters/index.d.mts +1 -1
  3. package/dist/adapters/index.d.ts +1 -1
  4. package/dist/adapters/index.js +82 -1
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/adapters/index.mjs +82 -1
  7. package/dist/adapters/index.mjs.map +1 -1
  8. package/dist/backend/index.d.mts +1036 -0
  9. package/dist/backend/index.d.ts +1036 -0
  10. package/dist/backend/index.js +1722 -0
  11. package/dist/backend/index.js.map +1 -0
  12. package/dist/backend/index.mjs +1704 -0
  13. package/dist/backend/index.mjs.map +1 -0
  14. package/dist/{index-BrFeSWKm.d.mts → index-C60c_e5z.d.mts} +13 -4
  15. package/dist/{index-DR2vXt-c.d.mts → index-D-dO_FoP.d.mts} +70 -4
  16. package/dist/{index-DR2vXt-c.d.ts → index-D-dO_FoP.d.ts} +70 -4
  17. package/dist/{index-BYX9BU79.d.ts → index-VIOUicmO.d.ts} +13 -4
  18. package/dist/index.d.mts +3 -3
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +115 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +110 -2
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/providers/algorand/index.d.mts +86 -0
  25. package/dist/providers/algorand/index.d.ts +86 -0
  26. package/dist/providers/algorand/index.js +903 -0
  27. package/dist/providers/algorand/index.js.map +1 -0
  28. package/dist/providers/algorand/index.mjs +898 -0
  29. package/dist/providers/algorand/index.mjs.map +1 -0
  30. package/dist/providers/evm/index.d.mts +1 -1
  31. package/dist/providers/evm/index.d.ts +1 -1
  32. package/dist/providers/evm/index.js +78 -1
  33. package/dist/providers/evm/index.js.map +1 -1
  34. package/dist/providers/evm/index.mjs +78 -1
  35. package/dist/providers/evm/index.mjs.map +1 -1
  36. package/dist/providers/near/index.d.mts +1 -1
  37. package/dist/providers/near/index.d.ts +1 -1
  38. package/dist/providers/near/index.js +78 -1
  39. package/dist/providers/near/index.js.map +1 -1
  40. package/dist/providers/near/index.mjs +78 -1
  41. package/dist/providers/near/index.mjs.map +1 -1
  42. package/dist/providers/solana/index.d.mts +1 -1
  43. package/dist/providers/solana/index.d.ts +1 -1
  44. package/dist/providers/solana/index.js +78 -1
  45. package/dist/providers/solana/index.js.map +1 -1
  46. package/dist/providers/solana/index.mjs +78 -1
  47. package/dist/providers/solana/index.mjs.map +1 -1
  48. package/dist/providers/stellar/index.d.mts +1 -1
  49. package/dist/providers/stellar/index.d.ts +1 -1
  50. package/dist/providers/stellar/index.js +78 -1
  51. package/dist/providers/stellar/index.js.map +1 -1
  52. package/dist/providers/stellar/index.mjs +78 -1
  53. package/dist/providers/stellar/index.mjs.map +1 -1
  54. package/dist/react/index.d.mts +3 -3
  55. package/dist/react/index.d.ts +3 -3
  56. package/dist/react/index.js +82 -1
  57. package/dist/react/index.js.map +1 -1
  58. package/dist/react/index.mjs +82 -1
  59. package/dist/react/index.mjs.map +1 -1
  60. package/dist/utils/index.d.mts +57 -5
  61. package/dist/utils/index.d.ts +57 -5
  62. package/dist/utils/index.js +96 -1
  63. package/dist/utils/index.js.map +1 -1
  64. package/dist/utils/index.mjs +93 -2
  65. package/dist/utils/index.mjs.map +1 -1
  66. package/package.json +24 -3
  67. package/src/adapters/wagmi.ts +4 -0
  68. package/src/backend/index.ts +2131 -0
  69. package/src/chains/index.ts +94 -2
  70. package/src/client/X402Client.ts +4 -0
  71. package/src/index.ts +26 -1
  72. package/src/providers/algorand/index.ts +356 -0
  73. package/src/types/index.ts +78 -3
  74. package/src/utils/index.ts +4 -0
  75. package/src/utils/validation.ts +76 -3
@@ -0,0 +1,1036 @@
1
+ import { l as X402Version, m as X402Header } from '../index-D-dO_FoP.js';
2
+
3
+ /**
4
+ * uvd-x402-sdk - Backend Utilities
5
+ *
6
+ * Server-side utilities for building x402 payment APIs.
7
+ * These utilities help backend developers:
8
+ * - Build verify/settle requests for the facilitator
9
+ * - Parse X-PAYMENT headers from incoming requests
10
+ * - Configure CORS for x402 payment flows
11
+ * - Create atomic payment handlers
12
+ * - Discover and register resources via Bazaar Discovery API
13
+ * - Manage escrow payments with refund and dispute resolution
14
+ *
15
+ * @example Basic payment flow
16
+ * ```ts
17
+ * import {
18
+ * parsePaymentHeader,
19
+ * FacilitatorClient,
20
+ * X402_CORS_HEADERS,
21
+ * } from 'uvd-x402-sdk/backend';
22
+ *
23
+ * // Parse payment from request header
24
+ * const payment = parsePaymentHeader(req.headers['x-payment']);
25
+ *
26
+ * // Verify with facilitator
27
+ * const client = new FacilitatorClient();
28
+ * const verifyResult = await client.verify(payment, paymentRequirements);
29
+ *
30
+ * // If valid, provide service then settle
31
+ * const settleResult = await client.settle(payment, paymentRequirements);
32
+ * ```
33
+ *
34
+ * @example Escrow payment with refund support
35
+ * ```ts
36
+ * import { EscrowClient } from 'uvd-x402-sdk/backend';
37
+ *
38
+ * const escrow = new EscrowClient();
39
+ *
40
+ * // Hold payment in escrow
41
+ * const escrowPayment = await escrow.createEscrow({
42
+ * paymentHeader: req.headers['x-payment'],
43
+ * requirements: paymentRequirements,
44
+ * escrowDuration: 86400, // 24 hours
45
+ * });
46
+ *
47
+ * // After service delivered, release to recipient
48
+ * await escrow.release(escrowPayment.id);
49
+ *
50
+ * // Or if service failed, request refund
51
+ * await escrow.requestRefund({
52
+ * escrowId: escrowPayment.id,
53
+ * reason: 'Service not delivered',
54
+ * });
55
+ * ```
56
+ *
57
+ * @example Resource discovery
58
+ * ```ts
59
+ * import { BazaarClient } from 'uvd-x402-sdk/backend';
60
+ *
61
+ * const bazaar = new BazaarClient();
62
+ * const resources = await bazaar.discover({
63
+ * category: 'ai',
64
+ * network: 'base',
65
+ * maxPrice: '0.10',
66
+ * });
67
+ * ```
68
+ */
69
+
70
+ /**
71
+ * Payment requirements sent to the facilitator
72
+ */
73
+ interface PaymentRequirements {
74
+ /** Payment scheme (always "exact") */
75
+ scheme: 'exact';
76
+ /** Network name (v1) or CAIP-2 identifier (v2) */
77
+ network: string;
78
+ /** Maximum amount required in atomic units (e.g., "1000000" for 1 USDC) */
79
+ maxAmountRequired: string;
80
+ /** Resource URL being paid for */
81
+ resource: string;
82
+ /** Description of what's being paid for */
83
+ description: string;
84
+ /** MIME type of the resource */
85
+ mimeType: string;
86
+ /** Recipient address for payment */
87
+ payTo: string;
88
+ /** Maximum timeout in seconds */
89
+ maxTimeoutSeconds: number;
90
+ /** Token contract address */
91
+ asset: string;
92
+ /** Optional output schema for the resource */
93
+ outputSchema?: unknown;
94
+ /** Optional extra data */
95
+ extra?: unknown;
96
+ }
97
+ /**
98
+ * Verify request body for the facilitator /verify endpoint
99
+ */
100
+ interface VerifyRequest {
101
+ x402Version: X402Version;
102
+ paymentPayload: X402Header;
103
+ paymentRequirements: PaymentRequirements;
104
+ }
105
+ /**
106
+ * Settle request body for the facilitator /settle endpoint
107
+ */
108
+ interface SettleRequest {
109
+ x402Version: X402Version;
110
+ paymentPayload: X402Header;
111
+ paymentRequirements: PaymentRequirements;
112
+ }
113
+ /**
114
+ * Verify response from the facilitator
115
+ */
116
+ interface VerifyResponse {
117
+ isValid: boolean;
118
+ invalidReason?: string;
119
+ payer?: string;
120
+ network?: string;
121
+ }
122
+ /**
123
+ * Settle response from the facilitator
124
+ */
125
+ interface SettleResponse {
126
+ success: boolean;
127
+ transactionHash?: string;
128
+ network?: string;
129
+ error?: string;
130
+ }
131
+ /**
132
+ * Options for building payment requirements
133
+ */
134
+ interface PaymentRequirementsOptions {
135
+ /** Amount in human-readable format (e.g., "1.00") */
136
+ amount: string;
137
+ /** Recipient address */
138
+ recipient: string;
139
+ /** Resource URL being protected */
140
+ resource: string;
141
+ /** Chain name (e.g., "base") */
142
+ chainName?: string;
143
+ /** Description of the resource */
144
+ description?: string;
145
+ /** MIME type of the resource */
146
+ mimeType?: string;
147
+ /** Timeout in seconds (default: 300) */
148
+ timeoutSeconds?: number;
149
+ /** x402 version to use */
150
+ x402Version?: X402Version;
151
+ }
152
+ /**
153
+ * Parse X-PAYMENT or PAYMENT-SIGNATURE header value
154
+ *
155
+ * @param headerValue - Base64-encoded header value (or undefined/null)
156
+ * @returns Parsed x402 header object, or null if invalid
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * // Express.js
161
+ * const payment = parsePaymentHeader(req.headers['x-payment']);
162
+ * if (!payment) {
163
+ * return res.status(400).json({ error: 'Invalid payment header' });
164
+ * }
165
+ * ```
166
+ */
167
+ declare function parsePaymentHeader(headerValue: string | undefined | null): X402Header | null;
168
+ /**
169
+ * Extract payment header from request headers object
170
+ *
171
+ * Checks both X-PAYMENT and PAYMENT-SIGNATURE headers.
172
+ *
173
+ * @param headers - Request headers object (case-insensitive)
174
+ * @returns Parsed x402 header object, or null if not found/invalid
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const payment = extractPaymentFromHeaders(req.headers);
179
+ * ```
180
+ */
181
+ declare function extractPaymentFromHeaders(headers: Record<string, string | string[] | undefined>): X402Header | null;
182
+ /**
183
+ * Build payment requirements for the facilitator
184
+ *
185
+ * @param options - Payment requirements options
186
+ * @returns PaymentRequirements object ready for verify/settle
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * const requirements = buildPaymentRequirements({
191
+ * amount: '1.00',
192
+ * recipient: '0x1234...',
193
+ * resource: 'https://api.example.com/premium-data',
194
+ * chainName: 'base',
195
+ * });
196
+ * ```
197
+ */
198
+ declare function buildPaymentRequirements(options: PaymentRequirementsOptions): PaymentRequirements;
199
+ /**
200
+ * Build a verify request for the facilitator /verify endpoint
201
+ *
202
+ * @param paymentHeader - Parsed x402 payment header
203
+ * @param requirements - Payment requirements
204
+ * @returns VerifyRequest body ready for fetch/axios
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * const payment = parsePaymentHeader(req.headers['x-payment']);
209
+ * const verifyBody = buildVerifyRequest(payment, requirements);
210
+ *
211
+ * const response = await fetch('https://facilitator.uvd.xyz/verify', {
212
+ * method: 'POST',
213
+ * headers: { 'Content-Type': 'application/json' },
214
+ * body: JSON.stringify(verifyBody),
215
+ * });
216
+ * ```
217
+ */
218
+ declare function buildVerifyRequest(paymentHeader: X402Header, requirements: PaymentRequirements): VerifyRequest;
219
+ /**
220
+ * Build a settle request for the facilitator /settle endpoint
221
+ *
222
+ * @param paymentHeader - Parsed x402 payment header
223
+ * @param requirements - Payment requirements
224
+ * @returns SettleRequest body ready for fetch/axios
225
+ */
226
+ declare function buildSettleRequest(paymentHeader: X402Header, requirements: PaymentRequirements): SettleRequest;
227
+ /**
228
+ * Recommended CORS headers for x402 payment APIs
229
+ *
230
+ * These headers allow browsers to send payment headers in cross-origin requests.
231
+ */
232
+ declare const X402_CORS_HEADERS: {
233
+ readonly 'Access-Control-Allow-Headers': "Content-Type, X-PAYMENT, PAYMENT-SIGNATURE, Authorization";
234
+ readonly 'Access-Control-Expose-Headers': "X-PAYMENT-RESPONSE, PAYMENT-RESPONSE, PAYMENT-REQUIRED";
235
+ readonly 'Access-Control-Allow-Methods': "GET, POST, OPTIONS";
236
+ };
237
+ /**
238
+ * All x402 custom header names that should be allowed in CORS
239
+ */
240
+ declare const X402_HEADER_NAMES: readonly ["X-PAYMENT", "PAYMENT-SIGNATURE", "X-PAYMENT-RESPONSE", "PAYMENT-RESPONSE", "PAYMENT-REQUIRED"];
241
+ /**
242
+ * Get CORS headers with custom origin
243
+ *
244
+ * @param origin - Allowed origin (use '*' for any, or specific domain)
245
+ * @returns Complete CORS headers object
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * // Express.js middleware
250
+ * app.use((req, res, next) => {
251
+ * const corsHeaders = getCorsHeaders('https://myapp.com');
252
+ * Object.entries(corsHeaders).forEach(([key, value]) => {
253
+ * res.setHeader(key, value);
254
+ * });
255
+ * if (req.method === 'OPTIONS') {
256
+ * return res.status(204).end();
257
+ * }
258
+ * next();
259
+ * });
260
+ * ```
261
+ */
262
+ declare function getCorsHeaders(origin?: string): Record<string, string>;
263
+ /**
264
+ * Options for the FacilitatorClient
265
+ */
266
+ interface FacilitatorClientOptions {
267
+ /** Base URL of the facilitator (default: https://facilitator.ultravioletadao.xyz) */
268
+ baseUrl?: string;
269
+ /** Request timeout in milliseconds (default: 30000) */
270
+ timeout?: number;
271
+ }
272
+ /**
273
+ * Client for interacting with the x402 facilitator API
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const client = new FacilitatorClient();
278
+ *
279
+ * // Verify a payment
280
+ * const verifyResult = await client.verify(paymentHeader, requirements);
281
+ * if (!verifyResult.isValid) {
282
+ * return res.status(402).json({ error: verifyResult.invalidReason });
283
+ * }
284
+ *
285
+ * // Provide the service, then settle
286
+ * const settleResult = await client.settle(paymentHeader, requirements);
287
+ * if (!settleResult.success) {
288
+ * // Handle settlement failure (maybe refund or retry)
289
+ * }
290
+ * ```
291
+ */
292
+ declare class FacilitatorClient {
293
+ private readonly baseUrl;
294
+ private readonly timeout;
295
+ constructor(options?: FacilitatorClientOptions);
296
+ /**
297
+ * Verify a payment with the facilitator
298
+ *
299
+ * Call this before providing the paid resource to validate the payment.
300
+ *
301
+ * @param paymentHeader - Parsed x402 payment header
302
+ * @param requirements - Payment requirements
303
+ * @returns Verification result
304
+ */
305
+ verify(paymentHeader: X402Header, requirements: PaymentRequirements): Promise<VerifyResponse>;
306
+ /**
307
+ * Settle a payment with the facilitator
308
+ *
309
+ * Call this after providing the paid resource to execute the on-chain transfer.
310
+ *
311
+ * @param paymentHeader - Parsed x402 payment header
312
+ * @param requirements - Payment requirements
313
+ * @returns Settlement result with transaction hash
314
+ */
315
+ settle(paymentHeader: X402Header, requirements: PaymentRequirements): Promise<SettleResponse>;
316
+ /**
317
+ * Verify and settle atomically
318
+ *
319
+ * Convenience method that verifies first, then settles if valid.
320
+ * Use this for simple payment flows where you don't need custom logic between verify and settle.
321
+ *
322
+ * @param paymentHeader - Parsed x402 payment header
323
+ * @param requirements - Payment requirements
324
+ * @returns Combined result with verify and settle status
325
+ */
326
+ verifyAndSettle(paymentHeader: X402Header, requirements: PaymentRequirements): Promise<{
327
+ verified: boolean;
328
+ settled: boolean;
329
+ transactionHash?: string;
330
+ error?: string;
331
+ }>;
332
+ /**
333
+ * Check if the facilitator is healthy
334
+ *
335
+ * @returns True if the facilitator is responding
336
+ */
337
+ healthCheck(): Promise<boolean>;
338
+ }
339
+ /**
340
+ * Create a 402 Payment Required response
341
+ *
342
+ * @param requirements - Payment requirements
343
+ * @param options - Additional response options
344
+ * @returns Object with status code, headers, and body for the 402 response
345
+ *
346
+ * @example
347
+ * ```ts
348
+ * // Express.js
349
+ * app.get('/premium-data', (req, res) => {
350
+ * const payment = extractPaymentFromHeaders(req.headers);
351
+ *
352
+ * if (!payment) {
353
+ * const { status, headers, body } = create402Response({
354
+ * amount: '1.00',
355
+ * recipient: '0x...',
356
+ * resource: 'https://api.example.com/premium-data',
357
+ * });
358
+ * return res.status(status).set(headers).json(body);
359
+ * }
360
+ *
361
+ * // Verify and serve...
362
+ * });
363
+ * ```
364
+ */
365
+ declare function create402Response(requirements: PaymentRequirementsOptions, options?: {
366
+ accepts?: Array<{
367
+ network: string;
368
+ asset: string;
369
+ amount: string;
370
+ }>;
371
+ }): {
372
+ status: 402;
373
+ headers: Record<string, string>;
374
+ body: Record<string, unknown>;
375
+ };
376
+ /**
377
+ * Create an Express-compatible middleware for x402 payments
378
+ *
379
+ * @param getRequirements - Function to get payment requirements for a request
380
+ * @param options - Middleware options
381
+ * @returns Express middleware function
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * const paymentMiddleware = createPaymentMiddleware(
386
+ * (req) => ({
387
+ * amount: '1.00',
388
+ * recipient: process.env.PAYMENT_RECIPIENT,
389
+ * resource: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
390
+ * }),
391
+ * { facilitatorUrl: 'https://facilitator.uvd.xyz' }
392
+ * );
393
+ *
394
+ * app.get('/premium/*', paymentMiddleware, (req, res) => {
395
+ * res.json({ premium: 'data' });
396
+ * });
397
+ * ```
398
+ */
399
+ declare function createPaymentMiddleware(getRequirements: (req: {
400
+ headers: Record<string, string | string[] | undefined>;
401
+ }) => PaymentRequirementsOptions, options?: FacilitatorClientOptions): (req: {
402
+ headers: Record<string, string | string[] | undefined>;
403
+ }, res: {
404
+ status: (code: number) => {
405
+ json: (body: unknown) => void;
406
+ set: (headers: Record<string, string>) => {
407
+ json: (body: unknown) => void;
408
+ };
409
+ };
410
+ }, next: () => void) => Promise<void>;
411
+ /**
412
+ * Resource category for discovery
413
+ */
414
+ type BazaarCategory = 'api' | 'data' | 'ai' | 'media' | 'compute' | 'storage' | 'other';
415
+ /**
416
+ * Network/chain filter for discovery
417
+ */
418
+ type BazaarNetwork = 'base' | 'ethereum' | 'polygon' | 'arbitrum' | 'optimism' | 'avalanche' | 'celo' | 'hyperevm' | 'unichain' | 'monad' | 'solana' | 'fogo' | 'stellar' | 'near';
419
+ /**
420
+ * Token/asset filter for discovery
421
+ */
422
+ type BazaarToken = 'USDC' | 'EURC' | 'AUSD' | 'PYUSD' | 'USDT';
423
+ /**
424
+ * Resource registered in the Bazaar
425
+ */
426
+ interface BazaarResource {
427
+ /** Unique resource ID */
428
+ id: string;
429
+ /** Resource URL */
430
+ url: string;
431
+ /** Human-readable name */
432
+ name: string;
433
+ /** Description of the resource */
434
+ description: string;
435
+ /** Category of the resource */
436
+ category: BazaarCategory;
437
+ /** Supported networks for payment */
438
+ networks: BazaarNetwork[];
439
+ /** Supported tokens for payment */
440
+ tokens: BazaarToken[];
441
+ /** Price per request in atomic units */
442
+ pricePerRequest: string;
443
+ /** Price currency (e.g., "USDC") */
444
+ priceCurrency: BazaarToken;
445
+ /** Recipient address for payments */
446
+ payTo: string;
447
+ /** MIME type of the resource */
448
+ mimeType: string;
449
+ /** Optional output schema */
450
+ outputSchema?: unknown;
451
+ /** Resource owner/provider */
452
+ provider?: string;
453
+ /** Resource tags for search */
454
+ tags?: string[];
455
+ /** Whether the resource is active */
456
+ isActive: boolean;
457
+ /** ISO timestamp of creation */
458
+ createdAt: string;
459
+ /** ISO timestamp of last update */
460
+ updatedAt: string;
461
+ }
462
+ /**
463
+ * Options for registering a resource
464
+ */
465
+ interface BazaarRegisterOptions {
466
+ /** Resource URL (must be unique) */
467
+ url: string;
468
+ /** Human-readable name */
469
+ name: string;
470
+ /** Description of the resource */
471
+ description: string;
472
+ /** Category of the resource */
473
+ category: BazaarCategory;
474
+ /** Supported networks for payment */
475
+ networks: BazaarNetwork[];
476
+ /** Supported tokens for payment */
477
+ tokens?: BazaarToken[];
478
+ /** Price per request (e.g., "0.01") */
479
+ price: string;
480
+ /** Price currency (default: USDC) */
481
+ priceCurrency?: BazaarToken;
482
+ /** Recipient address for payments */
483
+ payTo: string;
484
+ /** MIME type of the resource (default: application/json) */
485
+ mimeType?: string;
486
+ /** Optional output schema */
487
+ outputSchema?: unknown;
488
+ /** Resource tags for search */
489
+ tags?: string[];
490
+ }
491
+ /**
492
+ * Options for discovering resources
493
+ */
494
+ interface BazaarDiscoverOptions {
495
+ /** Filter by category */
496
+ category?: BazaarCategory;
497
+ /** Filter by network */
498
+ network?: BazaarNetwork;
499
+ /** Filter by token */
500
+ token?: BazaarToken;
501
+ /** Filter by provider address */
502
+ provider?: string;
503
+ /** Filter by tags (match any) */
504
+ tags?: string[];
505
+ /** Search query (name, description) */
506
+ query?: string;
507
+ /** Maximum price filter (e.g., "0.10") */
508
+ maxPrice?: string;
509
+ /** Page number (1-indexed) */
510
+ page?: number;
511
+ /** Results per page (default: 20, max: 100) */
512
+ limit?: number;
513
+ /** Sort order */
514
+ sortBy?: 'price' | 'createdAt' | 'name';
515
+ /** Sort direction */
516
+ sortOrder?: 'asc' | 'desc';
517
+ }
518
+ /**
519
+ * Paginated discovery response
520
+ */
521
+ interface BazaarDiscoverResponse {
522
+ /** List of resources matching the query */
523
+ resources: BazaarResource[];
524
+ /** Total number of matching resources */
525
+ total: number;
526
+ /** Current page number */
527
+ page: number;
528
+ /** Results per page */
529
+ limit: number;
530
+ /** Total number of pages */
531
+ totalPages: number;
532
+ /** Whether there are more pages */
533
+ hasMore: boolean;
534
+ }
535
+ /**
536
+ * Options for the BazaarClient
537
+ */
538
+ interface BazaarClientOptions {
539
+ /** Base URL of the Bazaar API (default: https://bazaar.ultravioletadao.xyz) */
540
+ baseUrl?: string;
541
+ /** API key for authenticated operations (required for register/update/delete) */
542
+ apiKey?: string;
543
+ /** Request timeout in milliseconds (default: 30000) */
544
+ timeout?: number;
545
+ }
546
+ /**
547
+ * Client for interacting with the x402 Bazaar Discovery API
548
+ *
549
+ * The Bazaar is a discovery service for x402-enabled resources.
550
+ * Providers can register their APIs and consumers can discover them.
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * // Discover resources (no auth required)
555
+ * const bazaar = new BazaarClient();
556
+ * const results = await bazaar.discover({
557
+ * category: 'ai',
558
+ * network: 'base',
559
+ * maxPrice: '0.10',
560
+ * });
561
+ *
562
+ * // Register a resource (requires API key)
563
+ * const authBazaar = new BazaarClient({ apiKey: 'your-api-key' });
564
+ * const resource = await authBazaar.register({
565
+ * url: 'https://api.example.com/v1/chat',
566
+ * name: 'AI Chat API',
567
+ * description: 'Pay-per-message AI chat',
568
+ * category: 'ai',
569
+ * networks: ['base', 'ethereum'],
570
+ * price: '0.01',
571
+ * payTo: '0x...',
572
+ * });
573
+ * ```
574
+ */
575
+ declare class BazaarClient {
576
+ private readonly baseUrl;
577
+ private readonly apiKey?;
578
+ private readonly timeout;
579
+ constructor(options?: BazaarClientOptions);
580
+ /**
581
+ * Discover x402-enabled resources
582
+ *
583
+ * @param options - Discovery filters
584
+ * @returns Paginated list of matching resources
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * // Find AI APIs on Base with USDC under $0.10
589
+ * const results = await bazaar.discover({
590
+ * category: 'ai',
591
+ * network: 'base',
592
+ * token: 'USDC',
593
+ * maxPrice: '0.10',
594
+ * });
595
+ *
596
+ * for (const resource of results.resources) {
597
+ * console.log(`${resource.name}: ${resource.url}`);
598
+ * }
599
+ * ```
600
+ */
601
+ discover(options?: BazaarDiscoverOptions): Promise<BazaarDiscoverResponse>;
602
+ /**
603
+ * Get a specific resource by ID
604
+ *
605
+ * @param resourceId - Resource ID
606
+ * @returns Resource details
607
+ */
608
+ getResource(resourceId: string): Promise<BazaarResource>;
609
+ /**
610
+ * Get a resource by its URL
611
+ *
612
+ * @param resourceUrl - Resource URL
613
+ * @returns Resource details
614
+ */
615
+ getResourceByUrl(resourceUrl: string): Promise<BazaarResource>;
616
+ /**
617
+ * Register a new resource in the Bazaar
618
+ *
619
+ * Requires API key authentication.
620
+ *
621
+ * @param options - Resource registration options
622
+ * @returns Registered resource
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * const resource = await bazaar.register({
627
+ * url: 'https://api.example.com/v1/generate',
628
+ * name: 'Image Generator API',
629
+ * description: 'Generate images with AI',
630
+ * category: 'ai',
631
+ * networks: ['base', 'ethereum', 'polygon'],
632
+ * price: '0.05',
633
+ * payTo: '0x1234...',
634
+ * tags: ['ai', 'image', 'generator'],
635
+ * });
636
+ * ```
637
+ */
638
+ register(options: BazaarRegisterOptions): Promise<BazaarResource>;
639
+ /**
640
+ * Update an existing resource
641
+ *
642
+ * Requires API key authentication. Only the owner can update.
643
+ *
644
+ * @param resourceId - Resource ID to update
645
+ * @param updates - Partial update options
646
+ * @returns Updated resource
647
+ */
648
+ update(resourceId: string, updates: Partial<BazaarRegisterOptions>): Promise<BazaarResource>;
649
+ /**
650
+ * Delete a resource from the Bazaar
651
+ *
652
+ * Requires API key authentication. Only the owner can delete.
653
+ *
654
+ * @param resourceId - Resource ID to delete
655
+ */
656
+ delete(resourceId: string): Promise<void>;
657
+ /**
658
+ * Deactivate a resource (soft delete)
659
+ *
660
+ * Requires API key authentication. Only the owner can deactivate.
661
+ *
662
+ * @param resourceId - Resource ID to deactivate
663
+ * @returns Updated resource with isActive: false
664
+ */
665
+ deactivate(resourceId: string): Promise<BazaarResource>;
666
+ /**
667
+ * Reactivate a deactivated resource
668
+ *
669
+ * Requires API key authentication. Only the owner can reactivate.
670
+ *
671
+ * @param resourceId - Resource ID to reactivate
672
+ * @returns Updated resource with isActive: true
673
+ */
674
+ reactivate(resourceId: string): Promise<BazaarResource>;
675
+ /**
676
+ * List all resources owned by the authenticated user
677
+ *
678
+ * Requires API key authentication.
679
+ *
680
+ * @param options - Pagination options
681
+ * @returns Paginated list of owned resources
682
+ */
683
+ listMyResources(options?: {
684
+ page?: number;
685
+ limit?: number;
686
+ includeInactive?: boolean;
687
+ }): Promise<BazaarDiscoverResponse>;
688
+ /**
689
+ * Get Bazaar API health status
690
+ *
691
+ * @returns True if the Bazaar API is healthy
692
+ */
693
+ healthCheck(): Promise<boolean>;
694
+ /**
695
+ * Get Bazaar statistics
696
+ *
697
+ * @returns Global statistics about the Bazaar
698
+ */
699
+ getStats(): Promise<{
700
+ totalResources: number;
701
+ activeResources: number;
702
+ totalProviders: number;
703
+ categoryCounts: Record<BazaarCategory, number>;
704
+ networkCounts: Record<BazaarNetwork, number>;
705
+ }>;
706
+ }
707
+ /**
708
+ * Escrow payment status
709
+ */
710
+ type EscrowStatus = 'pending' | 'held' | 'released' | 'refunded' | 'disputed' | 'expired';
711
+ /**
712
+ * Refund request status
713
+ */
714
+ type RefundStatus = 'pending' | 'approved' | 'rejected' | 'processed' | 'disputed';
715
+ /**
716
+ * Dispute resolution outcome
717
+ */
718
+ type DisputeOutcome = 'pending' | 'payer_wins' | 'recipient_wins' | 'split';
719
+ /**
720
+ * Escrow payment record
721
+ */
722
+ interface EscrowPayment {
723
+ /** Unique escrow ID */
724
+ id: string;
725
+ /** Original payment header (base64 encoded) */
726
+ paymentHeader: string;
727
+ /** Current status */
728
+ status: EscrowStatus;
729
+ /** Network where payment was made */
730
+ network: string;
731
+ /** Payer address */
732
+ payer: string;
733
+ /** Recipient address */
734
+ recipient: string;
735
+ /** Amount in atomic units */
736
+ amount: string;
737
+ /** Token/asset contract */
738
+ asset: string;
739
+ /** Resource URL being paid for */
740
+ resource: string;
741
+ /** Escrow expiration timestamp (ISO) */
742
+ expiresAt: string;
743
+ /** Release conditions (optional) */
744
+ releaseConditions?: {
745
+ /** Minimum time before release (seconds) */
746
+ minHoldTime?: number;
747
+ /** Required confirmations */
748
+ confirmations?: number;
749
+ /** Custom condition metadata */
750
+ custom?: unknown;
751
+ };
752
+ /** Transaction hash if released/refunded */
753
+ transactionHash?: string;
754
+ /** Creation timestamp (ISO) */
755
+ createdAt: string;
756
+ /** Last update timestamp (ISO) */
757
+ updatedAt: string;
758
+ }
759
+ /**
760
+ * Refund request record
761
+ */
762
+ interface RefundRequest {
763
+ /** Unique refund request ID */
764
+ id: string;
765
+ /** Related escrow ID */
766
+ escrowId: string;
767
+ /** Current status */
768
+ status: RefundStatus;
769
+ /** Reason for refund request */
770
+ reason: string;
771
+ /** Additional evidence/details */
772
+ evidence?: string;
773
+ /** Amount requested (may be partial) */
774
+ amountRequested: string;
775
+ /** Amount approved (if any) */
776
+ amountApproved?: string;
777
+ /** Requester (payer) address */
778
+ requester: string;
779
+ /** Transaction hash if processed */
780
+ transactionHash?: string;
781
+ /** Response from recipient/facilitator */
782
+ response?: {
783
+ status: 'approved' | 'rejected';
784
+ reason?: string;
785
+ respondedAt: string;
786
+ };
787
+ /** Creation timestamp (ISO) */
788
+ createdAt: string;
789
+ /** Last update timestamp (ISO) */
790
+ updatedAt: string;
791
+ }
792
+ /**
793
+ * Dispute record
794
+ */
795
+ interface Dispute {
796
+ /** Unique dispute ID */
797
+ id: string;
798
+ /** Related escrow ID */
799
+ escrowId: string;
800
+ /** Related refund request ID (if any) */
801
+ refundRequestId?: string;
802
+ /** Dispute outcome */
803
+ outcome: DisputeOutcome;
804
+ /** Initiator (payer or recipient) */
805
+ initiator: 'payer' | 'recipient';
806
+ /** Reason for dispute */
807
+ reason: string;
808
+ /** Evidence from payer */
809
+ payerEvidence?: string;
810
+ /** Evidence from recipient */
811
+ recipientEvidence?: string;
812
+ /** Arbitration notes */
813
+ arbitrationNotes?: string;
814
+ /** Amount resolved to payer */
815
+ payerAmount?: string;
816
+ /** Amount resolved to recipient */
817
+ recipientAmount?: string;
818
+ /** Transaction hash(es) for resolution */
819
+ transactionHashes?: string[];
820
+ /** Creation timestamp (ISO) */
821
+ createdAt: string;
822
+ /** Resolution timestamp (ISO) */
823
+ resolvedAt?: string;
824
+ }
825
+ /**
826
+ * Options for creating an escrow payment
827
+ */
828
+ interface CreateEscrowOptions {
829
+ /** Payment header (from client SDK) */
830
+ paymentHeader: string;
831
+ /** Payment requirements */
832
+ requirements: PaymentRequirements;
833
+ /** Escrow duration in seconds (default: 86400 = 24h) */
834
+ escrowDuration?: number;
835
+ /** Release conditions */
836
+ releaseConditions?: {
837
+ minHoldTime?: number;
838
+ confirmations?: number;
839
+ custom?: unknown;
840
+ };
841
+ }
842
+ /**
843
+ * Options for requesting a refund
844
+ */
845
+ interface RequestRefundOptions {
846
+ /** Escrow ID to refund */
847
+ escrowId: string;
848
+ /** Reason for refund */
849
+ reason: string;
850
+ /** Amount to refund (full amount if not specified) */
851
+ amount?: string;
852
+ /** Supporting evidence */
853
+ evidence?: string;
854
+ }
855
+ /**
856
+ * Options for the EscrowClient
857
+ */
858
+ interface EscrowClientOptions {
859
+ /** Base URL of the Escrow API (default: https://escrow.ultravioletadao.xyz) */
860
+ baseUrl?: string;
861
+ /** API key for authenticated operations */
862
+ apiKey?: string;
863
+ /** Request timeout in milliseconds (default: 30000) */
864
+ timeout?: number;
865
+ }
866
+ /**
867
+ * Client for x402 Escrow & Refund operations
868
+ *
869
+ * The Escrow system holds payments until service is verified,
870
+ * enabling refunds and dispute resolution.
871
+ *
872
+ * @example
873
+ * ```ts
874
+ * // Create escrow payment (backend)
875
+ * const escrow = new EscrowClient();
876
+ * const escrowPayment = await escrow.createEscrow({
877
+ * paymentHeader: req.headers['x-payment'],
878
+ * requirements: paymentRequirements,
879
+ * escrowDuration: 86400, // 24 hours
880
+ * });
881
+ *
882
+ * // After service is provided, release the escrow
883
+ * await escrow.release(escrowPayment.id);
884
+ *
885
+ * // If service not provided, payer can request refund
886
+ * await escrow.requestRefund({
887
+ * escrowId: escrowPayment.id,
888
+ * reason: 'Service not delivered within expected timeframe',
889
+ * });
890
+ * ```
891
+ */
892
+ declare class EscrowClient {
893
+ private readonly baseUrl;
894
+ private readonly apiKey?;
895
+ private readonly timeout;
896
+ constructor(options?: EscrowClientOptions);
897
+ private getHeaders;
898
+ /**
899
+ * Create an escrow payment
900
+ *
901
+ * Holds the payment in escrow until released or refunded.
902
+ *
903
+ * @param options - Escrow creation options
904
+ * @returns Created escrow payment
905
+ */
906
+ createEscrow(options: CreateEscrowOptions): Promise<EscrowPayment>;
907
+ /**
908
+ * Get escrow payment by ID
909
+ *
910
+ * @param escrowId - Escrow payment ID
911
+ * @returns Escrow payment details
912
+ */
913
+ getEscrow(escrowId: string): Promise<EscrowPayment>;
914
+ /**
915
+ * Release escrow funds to recipient
916
+ *
917
+ * Call this after service has been successfully provided.
918
+ *
919
+ * @param escrowId - Escrow payment ID
920
+ * @returns Updated escrow payment with transaction hash
921
+ */
922
+ release(escrowId: string): Promise<EscrowPayment>;
923
+ /**
924
+ * Request a refund for an escrow payment
925
+ *
926
+ * Initiates a refund request that must be approved.
927
+ *
928
+ * @param options - Refund request options
929
+ * @returns Created refund request
930
+ */
931
+ requestRefund(options: RequestRefundOptions): Promise<RefundRequest>;
932
+ /**
933
+ * Approve a refund request (for recipients)
934
+ *
935
+ * @param refundId - Refund request ID
936
+ * @param amount - Amount to approve (may be less than requested)
937
+ * @returns Updated refund request
938
+ */
939
+ approveRefund(refundId: string, amount?: string): Promise<RefundRequest>;
940
+ /**
941
+ * Reject a refund request (for recipients)
942
+ *
943
+ * @param refundId - Refund request ID
944
+ * @param reason - Reason for rejection
945
+ * @returns Updated refund request
946
+ */
947
+ rejectRefund(refundId: string, reason: string): Promise<RefundRequest>;
948
+ /**
949
+ * Get refund request by ID
950
+ *
951
+ * @param refundId - Refund request ID
952
+ * @returns Refund request details
953
+ */
954
+ getRefund(refundId: string): Promise<RefundRequest>;
955
+ /**
956
+ * Open a dispute for an escrow payment
957
+ *
958
+ * Initiates arbitration when payer and recipient disagree.
959
+ *
960
+ * @param escrowId - Escrow payment ID
961
+ * @param reason - Reason for dispute
962
+ * @param evidence - Supporting evidence
963
+ * @returns Created dispute
964
+ */
965
+ openDispute(escrowId: string, reason: string, evidence?: string): Promise<Dispute>;
966
+ /**
967
+ * Submit evidence to a dispute
968
+ *
969
+ * @param disputeId - Dispute ID
970
+ * @param evidence - Evidence to submit
971
+ * @returns Updated dispute
972
+ */
973
+ submitEvidence(disputeId: string, evidence: string): Promise<Dispute>;
974
+ /**
975
+ * Get dispute by ID
976
+ *
977
+ * @param disputeId - Dispute ID
978
+ * @returns Dispute details
979
+ */
980
+ getDispute(disputeId: string): Promise<Dispute>;
981
+ /**
982
+ * List escrow payments (with filters)
983
+ *
984
+ * @param options - Filter and pagination options
985
+ * @returns Paginated list of escrow payments
986
+ */
987
+ listEscrows(options?: {
988
+ status?: EscrowStatus;
989
+ payer?: string;
990
+ recipient?: string;
991
+ page?: number;
992
+ limit?: number;
993
+ }): Promise<{
994
+ escrows: EscrowPayment[];
995
+ total: number;
996
+ page: number;
997
+ limit: number;
998
+ hasMore: boolean;
999
+ }>;
1000
+ /**
1001
+ * Check Escrow API health
1002
+ *
1003
+ * @returns True if healthy
1004
+ */
1005
+ healthCheck(): Promise<boolean>;
1006
+ }
1007
+ /**
1008
+ * Check if an escrow can be released
1009
+ *
1010
+ * @param escrow - Escrow payment to check
1011
+ * @returns True if the escrow can be released
1012
+ */
1013
+ declare function canReleaseEscrow(escrow: EscrowPayment): boolean;
1014
+ /**
1015
+ * Check if an escrow can be refunded
1016
+ *
1017
+ * @param escrow - Escrow payment to check
1018
+ * @returns True if the escrow can be refunded
1019
+ */
1020
+ declare function canRefundEscrow(escrow: EscrowPayment): boolean;
1021
+ /**
1022
+ * Check if an escrow is expired
1023
+ *
1024
+ * @param escrow - Escrow payment to check
1025
+ * @returns True if the escrow is expired
1026
+ */
1027
+ declare function isEscrowExpired(escrow: EscrowPayment): boolean;
1028
+ /**
1029
+ * Calculate time remaining until escrow expires
1030
+ *
1031
+ * @param escrow - Escrow payment to check
1032
+ * @returns Milliseconds until expiration (negative if expired)
1033
+ */
1034
+ declare function escrowTimeRemaining(escrow: EscrowPayment): number;
1035
+
1036
+ export { type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, type Dispute, type DisputeOutcome, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type PaymentRequirements, type PaymentRequirementsOptions, type RefundRequest, type RefundStatus, type RequestRefundOptions, type SettleRequest, type SettleResponse, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, isEscrowExpired, parsePaymentHeader };