moltspay 0.8.14 → 0.9.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.
@@ -0,0 +1,461 @@
1
+ // src/facilitators/interface.ts
2
+ var BaseFacilitator = class {
3
+ supportsNetwork(network) {
4
+ return this.supportedNetworks.includes(network);
5
+ }
6
+ };
7
+
8
+ // src/facilitators/cdp.ts
9
+ import { readFileSync, existsSync } from "fs";
10
+ import * as path from "path";
11
+ var X402_VERSION = 2;
12
+ var CDP_MAINNET_URL = "https://api.cdp.coinbase.com/platform/v2/x402";
13
+ var CDP_TESTNET_URL = "https://www.x402.org/facilitator";
14
+ function loadEnvFile() {
15
+ const envPaths = [
16
+ path.join(process.cwd(), ".env"),
17
+ path.join(process.env.HOME || "", ".moltspay", ".env")
18
+ ];
19
+ for (const envPath of envPaths) {
20
+ if (existsSync(envPath)) {
21
+ try {
22
+ const content = readFileSync(envPath, "utf-8");
23
+ for (const line of content.split("\n")) {
24
+ const trimmed = line.trim();
25
+ if (!trimmed || trimmed.startsWith("#")) continue;
26
+ const eqIndex = trimmed.indexOf("=");
27
+ if (eqIndex === -1) continue;
28
+ const key = trimmed.slice(0, eqIndex).trim();
29
+ let value = trimmed.slice(eqIndex + 1).trim();
30
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
31
+ value = value.slice(1, -1);
32
+ }
33
+ if (!process.env[key]) {
34
+ process.env[key] = value;
35
+ }
36
+ }
37
+ break;
38
+ } catch {
39
+ }
40
+ }
41
+ }
42
+ }
43
+ var CDPFacilitator = class extends BaseFacilitator {
44
+ name = "cdp";
45
+ displayName = "Coinbase CDP";
46
+ supportedNetworks;
47
+ endpoint;
48
+ useMainnet;
49
+ apiKeyId;
50
+ apiKeySecret;
51
+ constructor(config = {}) {
52
+ super();
53
+ loadEnvFile();
54
+ this.useMainnet = config.useMainnet ?? process.env.USE_MAINNET?.toLowerCase() === "true";
55
+ this.apiKeyId = config.apiKeyId || process.env.CDP_API_KEY_ID;
56
+ this.apiKeySecret = config.apiKeySecret || process.env.CDP_API_KEY_SECRET;
57
+ this.endpoint = this.useMainnet ? CDP_MAINNET_URL : CDP_TESTNET_URL;
58
+ this.supportedNetworks = this.useMainnet ? ["eip155:8453"] : ["eip155:8453", "eip155:84532"];
59
+ if (this.useMainnet && (!this.apiKeyId || !this.apiKeySecret)) {
60
+ console.warn("[CDPFacilitator] WARNING: Mainnet mode but missing CDP credentials!");
61
+ console.warn("[CDPFacilitator] Set CDP_API_KEY_ID and CDP_API_KEY_SECRET");
62
+ }
63
+ }
64
+ /**
65
+ * Get auth headers for CDP API requests
66
+ */
67
+ async getAuthHeaders(method, urlPath, body) {
68
+ if (!this.useMainnet) {
69
+ return {};
70
+ }
71
+ if (!this.apiKeyId || !this.apiKeySecret) {
72
+ throw new Error("CDP credentials required for mainnet");
73
+ }
74
+ try {
75
+ const { getAuthHeaders } = await import("@coinbase/cdp-sdk/auth");
76
+ return await getAuthHeaders({
77
+ apiKeyId: this.apiKeyId,
78
+ apiKeySecret: this.apiKeySecret,
79
+ requestMethod: method,
80
+ requestHost: "api.cdp.coinbase.com",
81
+ requestPath: urlPath,
82
+ requestBody: body
83
+ });
84
+ } catch (err) {
85
+ throw new Error(`Failed to generate CDP auth: ${err.message}`);
86
+ }
87
+ }
88
+ /**
89
+ * Health check - verify facilitator is reachable
90
+ */
91
+ async healthCheck() {
92
+ const start = Date.now();
93
+ try {
94
+ const controller = new AbortController();
95
+ const timeout = setTimeout(() => controller.abort(), 5e3);
96
+ const response = await fetch(this.endpoint.replace("/x402", ""), {
97
+ method: "HEAD",
98
+ signal: controller.signal
99
+ }).catch(() => null);
100
+ clearTimeout(timeout);
101
+ const latencyMs = Date.now() - start;
102
+ return {
103
+ healthy: response !== null,
104
+ latencyMs
105
+ };
106
+ } catch (err) {
107
+ return {
108
+ healthy: false,
109
+ error: err.message,
110
+ latencyMs: Date.now() - start
111
+ };
112
+ }
113
+ }
114
+ /**
115
+ * Verify payment signature with facilitator
116
+ */
117
+ async verify(paymentPayload, requirements) {
118
+ try {
119
+ const requestBody = {
120
+ x402Version: X402_VERSION,
121
+ paymentPayload,
122
+ paymentRequirements: requirements
123
+ };
124
+ const headers = {
125
+ "Content-Type": "application/json"
126
+ };
127
+ if (this.useMainnet) {
128
+ const authHeaders = await this.getAuthHeaders(
129
+ "POST",
130
+ "/platform/v2/x402/verify",
131
+ requestBody
132
+ );
133
+ Object.assign(headers, authHeaders);
134
+ }
135
+ const response = await fetch(`${this.endpoint}/verify`, {
136
+ method: "POST",
137
+ headers,
138
+ body: JSON.stringify(requestBody)
139
+ });
140
+ const result = await response.json();
141
+ if (!response.ok || !result.isValid) {
142
+ return {
143
+ valid: false,
144
+ error: result.invalidReason || result.error || "Verification failed",
145
+ details: result
146
+ };
147
+ }
148
+ return { valid: true, details: result };
149
+ } catch (err) {
150
+ return {
151
+ valid: false,
152
+ error: `Facilitator error: ${err.message}`
153
+ };
154
+ }
155
+ }
156
+ /**
157
+ * Settle payment on-chain via facilitator
158
+ */
159
+ async settle(paymentPayload, requirements) {
160
+ try {
161
+ const requestBody = {
162
+ x402Version: X402_VERSION,
163
+ paymentPayload,
164
+ paymentRequirements: requirements
165
+ };
166
+ const headers = {
167
+ "Content-Type": "application/json"
168
+ };
169
+ if (this.useMainnet) {
170
+ const authHeaders = await this.getAuthHeaders(
171
+ "POST",
172
+ "/platform/v2/x402/settle",
173
+ requestBody
174
+ );
175
+ Object.assign(headers, authHeaders);
176
+ }
177
+ const response = await fetch(`${this.endpoint}/settle`, {
178
+ method: "POST",
179
+ headers,
180
+ body: JSON.stringify(requestBody)
181
+ });
182
+ const result = await response.json();
183
+ if (!response.ok || !result.success) {
184
+ return {
185
+ success: false,
186
+ error: result.error || result.errorReason || "Settlement failed"
187
+ };
188
+ }
189
+ return {
190
+ success: true,
191
+ transaction: result.transaction,
192
+ status: result.status || "settled"
193
+ };
194
+ } catch (err) {
195
+ return {
196
+ success: false,
197
+ error: `Settlement error: ${err.message}`
198
+ };
199
+ }
200
+ }
201
+ /**
202
+ * Get CDP fee information
203
+ */
204
+ async getFee() {
205
+ return {
206
+ perTx: 1e-3,
207
+ currency: "USD",
208
+ freeQuota: 1e3
209
+ };
210
+ }
211
+ /**
212
+ * Get configuration summary (for logging)
213
+ */
214
+ getConfigSummary() {
215
+ const mode = this.useMainnet ? "mainnet" : "testnet";
216
+ const hasCredentials = !!(this.apiKeyId && this.apiKeySecret);
217
+ return `CDP Facilitator (${mode}, credentials: ${hasCredentials ? "yes" : "no"})`;
218
+ }
219
+ };
220
+
221
+ // src/facilitators/registry.ts
222
+ var FacilitatorRegistry = class {
223
+ factories = /* @__PURE__ */ new Map();
224
+ instances = /* @__PURE__ */ new Map();
225
+ selection;
226
+ roundRobinIndex = 0;
227
+ constructor(selection) {
228
+ this.registerFactory("cdp", (config) => new CDPFacilitator(config));
229
+ this.selection = selection || { primary: "cdp", strategy: "failover" };
230
+ }
231
+ /**
232
+ * Register a new facilitator factory
233
+ */
234
+ registerFactory(name, factory) {
235
+ this.factories.set(name, factory);
236
+ }
237
+ /**
238
+ * Get or create a facilitator instance
239
+ */
240
+ get(name, config) {
241
+ if (this.instances.has(name)) {
242
+ return this.instances.get(name);
243
+ }
244
+ const factory = this.factories.get(name);
245
+ if (!factory) {
246
+ throw new Error(`Unknown facilitator: ${name}. Available: ${Array.from(this.factories.keys()).join(", ")}`);
247
+ }
248
+ const mergedConfig = {
249
+ ...this.selection.config?.[name],
250
+ ...config
251
+ };
252
+ const instance = factory(mergedConfig);
253
+ this.instances.set(name, instance);
254
+ return instance;
255
+ }
256
+ /**
257
+ * Get all configured facilitator names
258
+ */
259
+ getConfiguredNames() {
260
+ const names = [this.selection.primary];
261
+ if (this.selection.fallback) {
262
+ names.push(...this.selection.fallback);
263
+ }
264
+ return names;
265
+ }
266
+ /**
267
+ * Get list of facilitators based on selection strategy
268
+ */
269
+ async getOrderedFacilitators(network) {
270
+ const names = this.getConfiguredNames();
271
+ const facilitators = [];
272
+ for (const name of names) {
273
+ try {
274
+ const f = this.get(name);
275
+ if (f.supportsNetwork(network)) {
276
+ facilitators.push(f);
277
+ }
278
+ } catch (err) {
279
+ console.warn(`[Registry] Failed to get facilitator ${name}:`, err);
280
+ }
281
+ }
282
+ if (facilitators.length === 0) {
283
+ throw new Error(`No facilitators available for network: ${network}`);
284
+ }
285
+ switch (this.selection.strategy) {
286
+ case "random":
287
+ return this.shuffle(facilitators);
288
+ case "roundrobin":
289
+ this.roundRobinIndex = (this.roundRobinIndex + 1) % facilitators.length;
290
+ return [
291
+ ...facilitators.slice(this.roundRobinIndex),
292
+ ...facilitators.slice(0, this.roundRobinIndex)
293
+ ];
294
+ case "cheapest":
295
+ return this.sortByCheapest(facilitators);
296
+ case "fastest":
297
+ return this.sortByFastest(facilitators);
298
+ case "failover":
299
+ default:
300
+ return facilitators;
301
+ }
302
+ }
303
+ shuffle(array) {
304
+ const result = [...array];
305
+ for (let i = result.length - 1; i > 0; i--) {
306
+ const j = Math.floor(Math.random() * (i + 1));
307
+ [result[i], result[j]] = [result[j], result[i]];
308
+ }
309
+ return result;
310
+ }
311
+ async sortByCheapest(facilitators) {
312
+ const withFees = await Promise.all(
313
+ facilitators.map(async (f) => {
314
+ try {
315
+ const fee = await f.getFee?.();
316
+ return { facilitator: f, perTx: fee?.perTx ?? Infinity };
317
+ } catch {
318
+ return { facilitator: f, perTx: Infinity };
319
+ }
320
+ })
321
+ );
322
+ withFees.sort((a, b) => a.perTx - b.perTx);
323
+ return withFees.map((w) => w.facilitator);
324
+ }
325
+ async sortByFastest(facilitators) {
326
+ const withLatency = await Promise.all(
327
+ facilitators.map(async (f) => {
328
+ try {
329
+ const health = await f.healthCheck();
330
+ return { facilitator: f, latency: health.latencyMs ?? Infinity };
331
+ } catch {
332
+ return { facilitator: f, latency: Infinity };
333
+ }
334
+ })
335
+ );
336
+ withLatency.sort((a, b) => a.latency - b.latency);
337
+ return withLatency.map((w) => w.facilitator);
338
+ }
339
+ /**
340
+ * Verify payment using configured facilitators
341
+ */
342
+ async verify(paymentPayload, requirements) {
343
+ const network = paymentPayload.accepted?.network || paymentPayload.network || requirements.network;
344
+ const facilitators = await this.getOrderedFacilitators(network);
345
+ let lastError;
346
+ for (const f of facilitators) {
347
+ try {
348
+ console.log(`[Registry] Trying ${f.name} for verify...`);
349
+ const result = await f.verify(paymentPayload, requirements);
350
+ if (result.valid) {
351
+ console.log(`[Registry] ${f.name} verify succeeded`);
352
+ return { ...result, facilitator: f.name };
353
+ }
354
+ lastError = result.error;
355
+ console.log(`[Registry] ${f.name} verify failed: ${result.error}`);
356
+ if (this.selection.strategy === "failover" && !this.isTransientError(result.error)) {
357
+ break;
358
+ }
359
+ } catch (err) {
360
+ lastError = err.message;
361
+ console.error(`[Registry] ${f.name} error:`, err.message);
362
+ }
363
+ }
364
+ return {
365
+ valid: false,
366
+ error: lastError || "All facilitators failed",
367
+ facilitator: "none"
368
+ };
369
+ }
370
+ /**
371
+ * Settle payment using configured facilitators
372
+ */
373
+ async settle(paymentPayload, requirements) {
374
+ const network = paymentPayload.accepted?.network || paymentPayload.network || requirements.network;
375
+ const facilitators = await this.getOrderedFacilitators(network);
376
+ let lastError;
377
+ for (const f of facilitators) {
378
+ try {
379
+ console.log(`[Registry] Trying ${f.name} for settle...`);
380
+ const result = await f.settle(paymentPayload, requirements);
381
+ if (result.success) {
382
+ console.log(`[Registry] ${f.name} settle succeeded: ${result.transaction}`);
383
+ return { ...result, facilitator: f.name };
384
+ }
385
+ lastError = result.error;
386
+ console.log(`[Registry] ${f.name} settle failed: ${result.error}`);
387
+ } catch (err) {
388
+ lastError = err.message;
389
+ console.error(`[Registry] ${f.name} error:`, err.message);
390
+ }
391
+ }
392
+ return {
393
+ success: false,
394
+ error: lastError || "All facilitators failed",
395
+ facilitator: "none"
396
+ };
397
+ }
398
+ /**
399
+ * Check health of all configured facilitators
400
+ */
401
+ async healthCheckAll() {
402
+ const results = {};
403
+ for (const name of this.getConfiguredNames()) {
404
+ try {
405
+ const f = this.get(name);
406
+ results[name] = await f.healthCheck();
407
+ } catch (err) {
408
+ results[name] = { healthy: false, error: err.message };
409
+ }
410
+ }
411
+ return results;
412
+ }
413
+ /**
414
+ * Check if an error is transient (network/server issue) vs permanent (bad request)
415
+ */
416
+ isTransientError(error) {
417
+ if (!error) return true;
418
+ const transientPatterns = [
419
+ /timeout/i,
420
+ /network/i,
421
+ /connection/i,
422
+ /ECONNREFUSED/i,
423
+ /ETIMEDOUT/i,
424
+ /503/,
425
+ /502/,
426
+ /500/
427
+ ];
428
+ return transientPatterns.some((p) => p.test(error));
429
+ }
430
+ /**
431
+ * Update selection configuration
432
+ */
433
+ setSelection(selection) {
434
+ this.selection = selection;
435
+ this.instances.clear();
436
+ }
437
+ /**
438
+ * Get current selection configuration
439
+ */
440
+ getSelection() {
441
+ return { ...this.selection };
442
+ }
443
+ };
444
+ var defaultRegistry = null;
445
+ function getDefaultRegistry() {
446
+ if (!defaultRegistry) {
447
+ defaultRegistry = new FacilitatorRegistry();
448
+ }
449
+ return defaultRegistry;
450
+ }
451
+ function createRegistry(selection) {
452
+ return new FacilitatorRegistry(selection);
453
+ }
454
+ export {
455
+ BaseFacilitator,
456
+ CDPFacilitator,
457
+ FacilitatorRegistry,
458
+ createRegistry,
459
+ getDefaultRegistry
460
+ };
461
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/facilitators/interface.ts","../../src/facilitators/cdp.ts","../../src/facilitators/registry.ts"],"sourcesContent":["/**\n * Facilitator Interface\n * \n * A facilitator is a service that handles x402 payment verification and settlement.\n * This abstraction allows MoltsPay to support multiple facilitators.\n * \n * @see https://www.x402.org/ecosystem?category=facilitators\n */\n\n/**\n * x402 Payment Payload (from client)\n */\nexport interface X402PaymentPayload {\n x402Version: number;\n scheme?: string;\n network?: string;\n accepted?: {\n scheme: string;\n network: string;\n asset: string;\n amount: string;\n payTo: string;\n maxTimeoutSeconds: number;\n extra?: Record<string, unknown>;\n };\n payload: unknown;\n}\n\n/**\n * x402 Payment Requirements (server specifies what it accepts)\n */\nexport interface X402PaymentRequirements {\n scheme: string;\n network: string;\n asset: string;\n amount: string;\n payTo: string;\n maxTimeoutSeconds: number;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Result of payment verification\n */\nexport interface VerifyResult {\n valid: boolean;\n error?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Result of payment settlement\n */\nexport interface SettleResult {\n success: boolean;\n transaction?: string;\n error?: string;\n status?: string;\n}\n\n/**\n * Facilitator health check result\n */\nexport interface HealthCheckResult {\n healthy: boolean;\n latencyMs?: number;\n error?: string;\n}\n\n/**\n * Facilitator fee information (for selection strategies)\n */\nexport interface FacilitatorFee {\n perTx: number;\n currency: string;\n freeQuota?: number;\n}\n\n/**\n * Facilitator configuration\n */\nexport interface FacilitatorConfig {\n /** Facilitator endpoint URL */\n endpoint?: string;\n /** API key (if required) */\n apiKey?: string;\n /** API secret (if required) */\n apiSecret?: string;\n /** Additional config specific to facilitator */\n [key: string]: unknown;\n}\n\n/**\n * Facilitator Interface\n * \n * All facilitators must implement this interface.\n */\nexport interface Facilitator {\n /** Unique identifier for this facilitator */\n readonly name: string;\n \n /** Human-readable display name */\n readonly displayName: string;\n \n /** Supported networks (e.g., [\"eip155:8453\", \"eip155:84532\"]) */\n readonly supportedNetworks: string[];\n \n /**\n * Check if facilitator is available and responsive\n */\n healthCheck(): Promise<HealthCheckResult>;\n \n /**\n * Verify a payment signature without executing it\n * \n * @param paymentPayload - The x402 payment payload from client\n * @param requirements - The payment requirements from server\n */\n verify(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<VerifyResult>;\n \n /**\n * Settle a payment on-chain\n * \n * @param paymentPayload - The x402 payment payload from client\n * @param requirements - The payment requirements from server\n */\n settle(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<SettleResult>;\n \n /**\n * Get current fee information (optional, for selection strategies)\n */\n getFee?(): Promise<FacilitatorFee>;\n \n /**\n * Check if this facilitator supports a given network\n */\n supportsNetwork(network: string): boolean;\n}\n\n/**\n * Base class with common functionality\n */\nexport abstract class BaseFacilitator implements Facilitator {\n abstract readonly name: string;\n abstract readonly displayName: string;\n abstract readonly supportedNetworks: string[];\n \n abstract healthCheck(): Promise<HealthCheckResult>;\n abstract verify(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<VerifyResult>;\n abstract settle(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<SettleResult>;\n \n supportsNetwork(network: string): boolean {\n return this.supportedNetworks.includes(network);\n }\n}\n","/**\n * CDP Facilitator\n * \n * Coinbase Developer Platform x402 facilitator implementation.\n * Supports both mainnet (Base) and testnet (Base Sepolia).\n * \n * @see https://docs.cdp.coinbase.com/x402/core-concepts/facilitator\n */\n\nimport { readFileSync, existsSync } from 'fs';\nimport * as path from 'path';\nimport {\n BaseFacilitator,\n X402PaymentPayload,\n X402PaymentRequirements,\n VerifyResult,\n SettleResult,\n HealthCheckResult,\n FacilitatorFee,\n FacilitatorConfig,\n} from './interface.js';\n\n// x402 protocol version\nconst X402_VERSION = 2;\n\n// CDP Facilitator URLs\nconst CDP_MAINNET_URL = 'https://api.cdp.coinbase.com/platform/v2/x402';\nconst CDP_TESTNET_URL = 'https://www.x402.org/facilitator';\n\nexport interface CDPFacilitatorConfig extends FacilitatorConfig {\n /** Use mainnet (true) or testnet (false, default) */\n useMainnet?: boolean;\n /** CDP API Key ID (required for mainnet) */\n apiKeyId?: string;\n /** CDP API Key Secret (required for mainnet) */\n apiKeySecret?: string;\n}\n\n/**\n * Load environment from .env files\n */\nfunction loadEnvFile(): void {\n const envPaths = [\n path.join(process.cwd(), '.env'),\n path.join(process.env.HOME || '', '.moltspay', '.env'),\n ];\n \n for (const envPath of envPaths) {\n if (existsSync(envPath)) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex === -1) continue;\n const key = trimmed.slice(0, eqIndex).trim();\n let value = trimmed.slice(eqIndex + 1).trim();\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n if (!process.env[key]) {\n process.env[key] = value;\n }\n }\n break;\n } catch {\n // Ignore errors\n }\n }\n }\n}\n\n/**\n * CDP (Coinbase Developer Platform) Facilitator\n * \n * Handles payment verification and settlement via Coinbase's x402 facilitator.\n */\nexport class CDPFacilitator extends BaseFacilitator {\n readonly name = 'cdp';\n readonly displayName = 'Coinbase CDP';\n readonly supportedNetworks: string[];\n \n private endpoint: string;\n private useMainnet: boolean;\n private apiKeyId?: string;\n private apiKeySecret?: string;\n \n constructor(config: CDPFacilitatorConfig = {}) {\n super();\n \n // Load env files for credentials\n loadEnvFile();\n \n // Determine mainnet vs testnet\n this.useMainnet = config.useMainnet ?? \n (process.env.USE_MAINNET?.toLowerCase() === 'true');\n \n // Get credentials\n this.apiKeyId = config.apiKeyId || process.env.CDP_API_KEY_ID;\n this.apiKeySecret = config.apiKeySecret || process.env.CDP_API_KEY_SECRET;\n \n // Set endpoint\n this.endpoint = this.useMainnet ? CDP_MAINNET_URL : CDP_TESTNET_URL;\n \n // Set supported networks\n this.supportedNetworks = this.useMainnet \n ? ['eip155:8453'] // Base mainnet only\n : ['eip155:8453', 'eip155:84532']; // Both mainnet and testnet via x402.org\n \n // Warn if mainnet without credentials\n if (this.useMainnet && (!this.apiKeyId || !this.apiKeySecret)) {\n console.warn('[CDPFacilitator] WARNING: Mainnet mode but missing CDP credentials!');\n console.warn('[CDPFacilitator] Set CDP_API_KEY_ID and CDP_API_KEY_SECRET');\n }\n }\n \n /**\n * Get auth headers for CDP API requests\n */\n private async getAuthHeaders(\n method: string,\n urlPath: string,\n body?: unknown\n ): Promise<Record<string, string>> {\n if (!this.useMainnet) {\n // Testnet (x402.org) doesn't require auth\n return {};\n }\n \n if (!this.apiKeyId || !this.apiKeySecret) {\n throw new Error('CDP credentials required for mainnet');\n }\n \n try {\n const { getAuthHeaders } = await import('@coinbase/cdp-sdk/auth');\n \n return await getAuthHeaders({\n apiKeyId: this.apiKeyId,\n apiKeySecret: this.apiKeySecret,\n requestMethod: method,\n requestHost: 'api.cdp.coinbase.com',\n requestPath: urlPath,\n requestBody: body,\n });\n } catch (err: any) {\n throw new Error(`Failed to generate CDP auth: ${err.message}`);\n }\n }\n \n /**\n * Health check - verify facilitator is reachable\n */\n async healthCheck(): Promise<HealthCheckResult> {\n const start = Date.now();\n \n try {\n // For testnet, just check if x402.org responds\n // For mainnet, we could hit a health endpoint or just check DNS\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 5000);\n \n const response = await fetch(this.endpoint.replace('/x402', ''), {\n method: 'HEAD',\n signal: controller.signal,\n }).catch(() => null);\n \n clearTimeout(timeout);\n \n const latencyMs = Date.now() - start;\n \n return {\n healthy: response !== null,\n latencyMs,\n };\n } catch (err: any) {\n return {\n healthy: false,\n error: err.message,\n latencyMs: Date.now() - start,\n };\n }\n }\n \n /**\n * Verify payment signature with facilitator\n */\n async verify(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<VerifyResult> {\n try {\n const requestBody = {\n x402Version: X402_VERSION,\n paymentPayload,\n paymentRequirements: requirements,\n };\n \n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n \n if (this.useMainnet) {\n const authHeaders = await this.getAuthHeaders(\n 'POST',\n '/platform/v2/x402/verify',\n requestBody\n );\n Object.assign(headers, authHeaders);\n }\n \n const response = await fetch(`${this.endpoint}/verify`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n });\n \n const result = await response.json() as any;\n \n if (!response.ok || !result.isValid) {\n return {\n valid: false,\n error: result.invalidReason || result.error || 'Verification failed',\n details: result,\n };\n }\n \n return { valid: true, details: result };\n } catch (err: any) {\n return {\n valid: false,\n error: `Facilitator error: ${err.message}`,\n };\n }\n }\n \n /**\n * Settle payment on-chain via facilitator\n */\n async settle(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<SettleResult> {\n try {\n const requestBody = {\n x402Version: X402_VERSION,\n paymentPayload,\n paymentRequirements: requirements,\n };\n \n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n \n if (this.useMainnet) {\n const authHeaders = await this.getAuthHeaders(\n 'POST',\n '/platform/v2/x402/settle',\n requestBody\n );\n Object.assign(headers, authHeaders);\n }\n \n const response = await fetch(`${this.endpoint}/settle`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n });\n \n const result = await response.json() as any;\n \n if (!response.ok || !result.success) {\n return {\n success: false,\n error: result.error || result.errorReason || 'Settlement failed',\n };\n }\n \n return {\n success: true,\n transaction: result.transaction,\n status: result.status || 'settled',\n };\n } catch (err: any) {\n return {\n success: false,\n error: `Settlement error: ${err.message}`,\n };\n }\n }\n \n /**\n * Get CDP fee information\n */\n async getFee(): Promise<FacilitatorFee> {\n // CDP pricing: 1000 free/month, then $0.001/tx\n return {\n perTx: 0.001,\n currency: 'USD',\n freeQuota: 1000,\n };\n }\n \n /**\n * Get configuration summary (for logging)\n */\n getConfigSummary(): string {\n const mode = this.useMainnet ? 'mainnet' : 'testnet';\n const hasCredentials = !!(this.apiKeyId && this.apiKeySecret);\n return `CDP Facilitator (${mode}, credentials: ${hasCredentials ? 'yes' : 'no'})`;\n }\n}\n","/**\n * Facilitator Registry\n * \n * Central registry for all available facilitators.\n * Supports selection strategies for failover, load balancing, etc.\n */\n\nimport {\n Facilitator,\n FacilitatorConfig,\n X402PaymentPayload,\n X402PaymentRequirements,\n VerifyResult,\n SettleResult,\n HealthCheckResult,\n} from './interface.js';\nimport { CDPFacilitator, CDPFacilitatorConfig } from './cdp.js';\n\n/**\n * Selection strategy for choosing facilitators\n */\nexport type SelectionStrategy = \n | 'failover' // Use primary, switch to fallback on failure\n | 'cheapest' // Use facilitator with lowest fees\n | 'fastest' // Use first responder\n | 'random' // Random selection (load balancing)\n | 'roundrobin'; // Rotate through facilitators\n\n/**\n * Facilitator selection configuration\n */\nexport interface FacilitatorSelection {\n /** Primary facilitator to use */\n primary: string;\n /** Fallback facilitators (in order of preference) */\n fallback?: string[];\n /** Selection strategy */\n strategy?: SelectionStrategy;\n /** Per-facilitator config overrides */\n config?: Record<string, FacilitatorConfig>;\n}\n\n/**\n * Factory function type for creating facilitators\n */\ntype FacilitatorFactory = (config?: FacilitatorConfig) => Facilitator;\n\n/**\n * Facilitator Registry\n * \n * Manages available facilitators and provides selection logic.\n */\nexport class FacilitatorRegistry {\n private factories: Map<string, FacilitatorFactory> = new Map();\n private instances: Map<string, Facilitator> = new Map();\n private selection: FacilitatorSelection;\n private roundRobinIndex = 0;\n \n constructor(selection?: FacilitatorSelection) {\n // Register built-in facilitators\n this.registerFactory('cdp', (config) => new CDPFacilitator(config as CDPFacilitatorConfig));\n \n // Default selection\n this.selection = selection || { primary: 'cdp', strategy: 'failover' };\n }\n \n /**\n * Register a new facilitator factory\n */\n registerFactory(name: string, factory: FacilitatorFactory): void {\n this.factories.set(name, factory);\n }\n \n /**\n * Get or create a facilitator instance\n */\n get(name: string, config?: FacilitatorConfig): Facilitator {\n // Check cache first\n if (this.instances.has(name)) {\n return this.instances.get(name)!;\n }\n \n // Look up factory\n const factory = this.factories.get(name);\n if (!factory) {\n throw new Error(`Unknown facilitator: ${name}. Available: ${Array.from(this.factories.keys()).join(', ')}`);\n }\n \n // Merge config from selection\n const mergedConfig = {\n ...this.selection.config?.[name],\n ...config,\n };\n \n // Create and cache instance\n const instance = factory(mergedConfig);\n this.instances.set(name, instance);\n return instance;\n }\n \n /**\n * Get all configured facilitator names\n */\n getConfiguredNames(): string[] {\n const names = [this.selection.primary];\n if (this.selection.fallback) {\n names.push(...this.selection.fallback);\n }\n return names;\n }\n \n /**\n * Get list of facilitators based on selection strategy\n */\n private async getOrderedFacilitators(network: string): Promise<Facilitator[]> {\n const names = this.getConfiguredNames();\n const facilitators: Facilitator[] = [];\n \n for (const name of names) {\n try {\n const f = this.get(name);\n if (f.supportsNetwork(network)) {\n facilitators.push(f);\n }\n } catch (err) {\n console.warn(`[Registry] Failed to get facilitator ${name}:`, err);\n }\n }\n \n if (facilitators.length === 0) {\n throw new Error(`No facilitators available for network: ${network}`);\n }\n \n // Apply strategy\n switch (this.selection.strategy) {\n case 'random':\n return this.shuffle(facilitators);\n \n case 'roundrobin':\n this.roundRobinIndex = (this.roundRobinIndex + 1) % facilitators.length;\n return [\n ...facilitators.slice(this.roundRobinIndex),\n ...facilitators.slice(0, this.roundRobinIndex),\n ];\n \n case 'cheapest':\n return this.sortByCheapest(facilitators);\n \n case 'fastest':\n return this.sortByFastest(facilitators);\n \n case 'failover':\n default:\n return facilitators;\n }\n }\n \n private shuffle<T>(array: T[]): T[] {\n const result = [...array];\n for (let i = result.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [result[i], result[j]] = [result[j], result[i]];\n }\n return result;\n }\n \n private async sortByCheapest(facilitators: Facilitator[]): Promise<Facilitator[]> {\n const withFees = await Promise.all(\n facilitators.map(async (f) => {\n try {\n const fee = await f.getFee?.();\n return { facilitator: f, perTx: fee?.perTx ?? Infinity };\n } catch {\n return { facilitator: f, perTx: Infinity };\n }\n })\n );\n withFees.sort((a, b) => a.perTx - b.perTx);\n return withFees.map(w => w.facilitator);\n }\n \n private async sortByFastest(facilitators: Facilitator[]): Promise<Facilitator[]> {\n const withLatency = await Promise.all(\n facilitators.map(async (f) => {\n try {\n const health = await f.healthCheck();\n return { facilitator: f, latency: health.latencyMs ?? Infinity };\n } catch {\n return { facilitator: f, latency: Infinity };\n }\n })\n );\n withLatency.sort((a, b) => a.latency - b.latency);\n return withLatency.map(w => w.facilitator);\n }\n \n /**\n * Verify payment using configured facilitators\n */\n async verify(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<VerifyResult & { facilitator: string }> {\n const network = paymentPayload.accepted?.network || paymentPayload.network || requirements.network;\n const facilitators = await this.getOrderedFacilitators(network);\n \n let lastError: string | undefined;\n \n for (const f of facilitators) {\n try {\n console.log(`[Registry] Trying ${f.name} for verify...`);\n const result = await f.verify(paymentPayload, requirements);\n \n if (result.valid) {\n console.log(`[Registry] ${f.name} verify succeeded`);\n return { ...result, facilitator: f.name };\n }\n \n lastError = result.error;\n console.log(`[Registry] ${f.name} verify failed: ${result.error}`);\n \n // For failover strategy, only try next if it's a network/server error\n if (this.selection.strategy === 'failover' && !this.isTransientError(result.error)) {\n // Permanent error (e.g., invalid signature) - don't try others\n break;\n }\n } catch (err: any) {\n lastError = err.message;\n console.error(`[Registry] ${f.name} error:`, err.message);\n }\n }\n \n return {\n valid: false,\n error: lastError || 'All facilitators failed',\n facilitator: 'none',\n };\n }\n \n /**\n * Settle payment using configured facilitators\n */\n async settle(\n paymentPayload: X402PaymentPayload,\n requirements: X402PaymentRequirements\n ): Promise<SettleResult & { facilitator: string }> {\n const network = paymentPayload.accepted?.network || paymentPayload.network || requirements.network;\n const facilitators = await this.getOrderedFacilitators(network);\n \n let lastError: string | undefined;\n \n for (const f of facilitators) {\n try {\n console.log(`[Registry] Trying ${f.name} for settle...`);\n const result = await f.settle(paymentPayload, requirements);\n \n if (result.success) {\n console.log(`[Registry] ${f.name} settle succeeded: ${result.transaction}`);\n return { ...result, facilitator: f.name };\n }\n \n lastError = result.error;\n console.log(`[Registry] ${f.name} settle failed: ${result.error}`);\n } catch (err: any) {\n lastError = err.message;\n console.error(`[Registry] ${f.name} error:`, err.message);\n }\n }\n \n return {\n success: false,\n error: lastError || 'All facilitators failed',\n facilitator: 'none',\n };\n }\n \n /**\n * Check health of all configured facilitators\n */\n async healthCheckAll(): Promise<Record<string, HealthCheckResult>> {\n const results: Record<string, HealthCheckResult> = {};\n \n for (const name of this.getConfiguredNames()) {\n try {\n const f = this.get(name);\n results[name] = await f.healthCheck();\n } catch (err: any) {\n results[name] = { healthy: false, error: err.message };\n }\n }\n \n return results;\n }\n \n /**\n * Check if an error is transient (network/server issue) vs permanent (bad request)\n */\n private isTransientError(error?: string): boolean {\n if (!error) return true;\n const transientPatterns = [\n /timeout/i,\n /network/i,\n /connection/i,\n /ECONNREFUSED/i,\n /ETIMEDOUT/i,\n /503/,\n /502/,\n /500/,\n ];\n return transientPatterns.some(p => p.test(error));\n }\n \n /**\n * Update selection configuration\n */\n setSelection(selection: FacilitatorSelection): void {\n this.selection = selection;\n // Clear cached instances to pick up new config\n this.instances.clear();\n }\n \n /**\n * Get current selection configuration\n */\n getSelection(): FacilitatorSelection {\n return { ...this.selection };\n }\n}\n\n// Default registry instance\nlet defaultRegistry: FacilitatorRegistry | null = null;\n\n/**\n * Get the default facilitator registry\n */\nexport function getDefaultRegistry(): FacilitatorRegistry {\n if (!defaultRegistry) {\n defaultRegistry = new FacilitatorRegistry();\n }\n return defaultRegistry;\n}\n\n/**\n * Create a new registry with custom selection\n */\nexport function createRegistry(selection?: FacilitatorSelection): FacilitatorRegistry {\n return new FacilitatorRegistry(selection);\n}\n"],"mappings":";AAoJO,IAAe,kBAAf,MAAsD;AAAA,EAe3D,gBAAgB,SAA0B;AACxC,WAAO,KAAK,kBAAkB,SAAS,OAAO;AAAA,EAChD;AACF;;;AC7JA,SAAS,cAAc,kBAAkB;AACzC,YAAY,UAAU;AAatB,IAAM,eAAe;AAGrB,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAcxB,SAAS,cAAoB;AAC3B,QAAM,WAAW;AAAA,IACV,UAAK,QAAQ,IAAI,GAAG,MAAM;AAAA,IAC1B,UAAK,QAAQ,IAAI,QAAQ,IAAI,aAAa,MAAM;AAAA,EACvD;AAEA,aAAW,WAAW,UAAU;AAC9B,QAAI,WAAW,OAAO,GAAG;AACvB,UAAI;AACF,cAAM,UAAU,aAAa,SAAS,OAAO;AAC7C,mBAA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A,IAAI,kBAA8C;AAK3C,SAAS,qBAA0C;AACxD,MAAI,CAAC,iBAAiB;AACpB,sBAAkB,IAAI,oBAAoB;AAAA,EAC5C;AACA,SAAO;AACT;AAKO,SAAS,eAAe,WAAuD;AACpF,SAAO,IAAI,oBAAoB,SAAS;AAC1C;","names":[]}
package/dist/index.d.mts CHANGED
@@ -4,4 +4,6 @@ export { CHAINS, ERC20_ABI, getChain, getChainById, listChains } from './chains/
4
4
  export { c as createWallet, g as getWalletAddress, l as loadWallet, w as walletExists } from './createWallet-D53qu7ie.mjs';
5
5
  export { VerifyPaymentParams, VerifyPaymentResult, getTransactionStatus, verifyPayment, waitForTransaction } from './verify/index.mjs';
6
6
  export { CDPWallet, getCDPWalletAddress, initCDPWallet, isCDPAvailable, loadCDPWallet } from './cdp/index.mjs';
7
+ export { B as BaseFacilitator, F as Facilitator, a as FacilitatorConfig, b as FacilitatorFee, c as FacilitatorRegistry, d as FacilitatorSelection, H as HealthCheckResult, S as SelectionStrategy, e as SettleResult, V as VerifyResult, X as X402PaymentPayload, f as X402PaymentRequirements, g as createRegistry, h as getDefaultRegistry } from './registry-OsEO2dOu.mjs';
8
+ export { CDPFacilitator, CDPFacilitatorConfig } from './facilitators/index.mjs';
7
9
  import './index-Dg8n6wdW.mjs';
package/dist/index.d.ts CHANGED
@@ -4,4 +4,6 @@ export { CHAINS, ERC20_ABI, getChain, getChainById, listChains } from './chains/
4
4
  export { c as createWallet, g as getWalletAddress, l as loadWallet, w as walletExists } from './createWallet-D53qu7ie.js';
5
5
  export { VerifyPaymentParams, VerifyPaymentResult, getTransactionStatus, verifyPayment, waitForTransaction } from './verify/index.js';
6
6
  export { CDPWallet, getCDPWalletAddress, initCDPWallet, isCDPAvailable, loadCDPWallet } from './cdp/index.js';
7
+ export { B as BaseFacilitator, F as Facilitator, a as FacilitatorConfig, b as FacilitatorFee, c as FacilitatorRegistry, d as FacilitatorSelection, H as HealthCheckResult, S as SelectionStrategy, e as SettleResult, V as VerifyResult, X as X402PaymentPayload, f as X402PaymentRequirements, g as createRegistry, h as getDefaultRegistry } from './registry-OsEO2dOu.js';
8
+ export { CDPFacilitator, CDPFacilitatorConfig } from './facilitators/index.js';
7
9
  import './index-Dg8n6wdW.js';