@routedock/routedock 0.1.2 → 0.3.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +532 -4
  3. package/dist/MppSessionHandler-1EL8QBAn.d.cts +215 -0
  4. package/dist/MppSessionHandler-Bq4S-JTE.d.ts +215 -0
  5. package/dist/ProviderRegistry-CA_TdREG.d.ts +142 -0
  6. package/dist/ProviderRegistry-D-0rqK0N.d.cts +142 -0
  7. package/dist/RouteDockClient-Bh86bVly.d.ts +469 -0
  8. package/dist/RouteDockClient-go9aopfF.d.cts +469 -0
  9. package/dist/SessionReconciler-Bw-PoBVl.d.ts +134 -0
  10. package/dist/SessionReconciler-Cz2nuOlJ.d.cts +134 -0
  11. package/dist/SessionStore-B4-Hi4H8.d.cts +143 -0
  12. package/dist/SessionStore-BaYiegP0.d.ts +143 -0
  13. package/dist/client.cjs +2746 -217
  14. package/dist/client.d.cts +51 -81
  15. package/dist/client.d.ts +51 -81
  16. package/dist/client.js +2690 -218
  17. package/dist/index.cjs +3634 -420
  18. package/dist/index.d.cts +12 -3
  19. package/dist/index.d.ts +12 -3
  20. package/dist/index.js +3569 -419
  21. package/dist/logger-D8_Q2ytp.d.cts +467 -0
  22. package/dist/logger-D8_Q2ytp.d.ts +467 -0
  23. package/dist/provider/fastify.cjs +1099 -0
  24. package/dist/provider/fastify.d.cts +40 -0
  25. package/dist/provider/fastify.d.ts +40 -0
  26. package/dist/provider/fastify.js +1097 -0
  27. package/dist/provider/hono.cjs +1152 -0
  28. package/dist/provider/hono.d.cts +101 -0
  29. package/dist/provider/hono.d.ts +101 -0
  30. package/dist/provider/hono.js +1142 -0
  31. package/dist/provider.cjs +1105 -147
  32. package/dist/provider.d.cts +38 -27
  33. package/dist/provider.d.ts +38 -27
  34. package/dist/provider.js +1079 -148
  35. package/dist/react.cjs +2931 -0
  36. package/dist/react.d.cts +107 -0
  37. package/dist/react.d.ts +107 -0
  38. package/dist/react.js +2924 -0
  39. package/dist/routedockMiddleware-57gUaEMf.d.ts +64 -0
  40. package/dist/routedockMiddleware-DlyLrxp7.d.cts +64 -0
  41. package/dist/schema.cjs +404 -0
  42. package/dist/schema.d.cts +3 -0
  43. package/dist/schema.d.ts +3 -0
  44. package/dist/schema.js +399 -0
  45. package/dist/sign-AKH67sft.d.cts +53 -0
  46. package/dist/sign-BEq-OsSq.d.ts +53 -0
  47. package/dist/testing.cjs +59 -0
  48. package/dist/testing.d.cts +114 -0
  49. package/dist/testing.d.ts +114 -0
  50. package/dist/testing.js +56 -0
  51. package/package.json +143 -23
  52. package/PUBLISH_CHECKLIST.md +0 -70
  53. package/dist/SessionStore-CCVO0PHM.d.cts +0 -152
  54. package/dist/SessionStore-CCVO0PHM.d.ts +0 -152
  55. package/dist/routedockMiddleware-B7WTB3LT.d.cts +0 -53
  56. package/dist/routedockMiddleware-DRgdrycG.d.ts +0 -53
  57. package/src/client/ModeRouter.ts +0 -104
  58. package/src/client/MppChargeClient.ts +0 -44
  59. package/src/client/MppSessionClient.ts +0 -144
  60. package/src/client/RouteDockClient.ts +0 -124
  61. package/src/client/index.ts +0 -8
  62. package/src/client/x402Client.ts +0 -84
  63. package/src/index.ts +0 -9
  64. package/src/provider/MppChargeHandler.ts +0 -90
  65. package/src/provider/MppSessionHandler.ts +0 -157
  66. package/src/provider/index.ts +0 -7
  67. package/src/provider/routedockMiddleware.ts +0 -154
  68. package/src/provider/x402Handler.ts +0 -164
  69. package/src/schemas/routedock.schema.json +0 -159
  70. package/src/store/SessionStore.ts +0 -90
  71. package/src/tests/smoke.test.ts +0 -228
  72. package/src/types.ts +0 -165
  73. package/tsconfig.json +0 -14
  74. package/tsup.config.ts +0 -15
package/dist/client.cjs CHANGED
@@ -1,57 +1,331 @@
1
1
  'use strict';
2
2
 
3
+ var nulthSdk = require('@routedock/nulth-sdk');
3
4
  var stellarSdk = require('@stellar/stellar-sdk');
4
- var Ajv = require('ajv');
5
+ var jsonSchema = require('@cfworker/json-schema');
6
+ var crypto = require('crypto');
5
7
  var stellar = require('@x402/stellar');
6
8
  var client = require('@x402/stellar/exact/client');
7
9
  var client$1 = require('@x402/core/client');
8
10
  var http = require('@x402/core/http');
9
11
  var client$3 = require('@stellar/mpp/charge/client');
10
12
  var client$2 = require('mppx/client');
13
+ var mpp = require('@stellar/mpp');
11
14
  var client$4 = require('@stellar/mpp/channel/client');
15
+ var mppx = require('mppx');
16
+ var fs = require('fs/promises');
17
+ var path = require('path');
12
18
 
13
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
20
 
15
- var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
21
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
22
+ var path__default = /*#__PURE__*/_interopDefault(path);
16
23
 
17
- // src/types.ts
24
+ // src/errors.ts
18
25
  var RouteDockError = class extends Error {
19
- constructor(message) {
20
- super(message);
26
+ code;
27
+ retryable;
28
+ retryAfterMs;
29
+ constructor(message, code, retryable, options = {}) {
30
+ super(message, { cause: options.cause });
21
31
  this.name = "RouteDockError";
32
+ this.code = code;
33
+ this.retryable = retryable;
34
+ if (options.retryAfterMs !== void 0) {
35
+ this.retryAfterMs = options.retryAfterMs;
36
+ }
22
37
  }
23
38
  };
24
39
  var RouteDockManifestError = class extends RouteDockError {
25
- constructor(message) {
26
- super(message);
40
+ constructor(message, options = {}) {
41
+ super(message, "MANIFEST", false, options);
27
42
  this.name = "RouteDockManifestError";
28
43
  }
29
44
  };
45
+ var RouteDockManifestTimeoutError = class extends RouteDockError {
46
+ constructor(message, options = {}) {
47
+ super(message, "MANIFEST_TIMEOUT", true, options);
48
+ this.name = "RouteDockManifestTimeoutError";
49
+ }
50
+ };
51
+ var RouteDockManifestSunsetError = class extends RouteDockError {
52
+ constructor(message, options = {}) {
53
+ super(message, "MANIFEST_SUNSET", false, options);
54
+ this.name = "RouteDockManifestSunsetError";
55
+ }
56
+ };
30
57
  var RouteDockNoSupportedModeError = class extends RouteDockError {
31
- constructor(message) {
32
- super(message);
58
+ constructor(message, options = {}) {
59
+ super(message, "NO_SUPPORTED_MODE", false, options);
33
60
  this.name = "RouteDockNoSupportedModeError";
34
61
  }
35
62
  };
36
- var RouteDockSessionError = class extends RouteDockError {
37
- constructor(message) {
38
- super(message);
39
- this.name = "RouteDockSessionError";
63
+ var RouteDockClientVersionError = class extends RouteDockError {
64
+ constructor(message, options = {}) {
65
+ super(message, "CLIENT_VERSION_TOO_OLD", false, options);
66
+ this.name = "RouteDockClientVersionError";
67
+ }
68
+ };
69
+ var RouteDockTrustlineError = class extends RouteDockError {
70
+ asset;
71
+ issuer;
72
+ remediation;
73
+ constructor(asset, issuer, remediation, options = {}) {
74
+ super(
75
+ `Missing trustline for ${asset} (issuer: ${issuer}). ${remediation}`,
76
+ "TRUSTLINE",
77
+ false,
78
+ options
79
+ );
80
+ this.name = "RouteDockTrustlineError";
81
+ this.asset = asset;
82
+ this.issuer = issuer;
83
+ this.remediation = remediation;
84
+ }
85
+ };
86
+ var RouteDockFacilitatorError = class extends RouteDockError {
87
+ status;
88
+ constructor(message, status, options = {}) {
89
+ super(message, "FACILITATOR", true, options);
90
+ this.name = "RouteDockFacilitatorError";
91
+ this.status = status;
92
+ }
93
+ };
94
+ var RouteDockNetworkError = class extends RouteDockError {
95
+ constructor(message, options = {}) {
96
+ super(message, "NETWORK", true, options);
97
+ this.name = "RouteDockNetworkError";
98
+ }
99
+ };
100
+ var RouteDockSignatureError = class extends RouteDockError {
101
+ constructor(message, options = {}) {
102
+ super(message, "SIGNATURE", false, options);
103
+ this.name = "RouteDockSignatureError";
104
+ }
105
+ };
106
+ var RouteDockVoucherMonotonicityError = class extends RouteDockError {
107
+ constructor(message, options = {}) {
108
+ super(message, "VOUCHER_MONOTONICITY", false, options);
109
+ this.name = "RouteDockVoucherMonotonicityError";
40
110
  }
41
111
  };
42
- var RouteDockPolicyRejectedError = class extends RouteDockError {
112
+ var RouteDockPolicyRejectError = class extends RouteDockError {
43
113
  reason;
44
- constructor(reason) {
45
- super(`Payment rejected by policy: ${reason}`);
46
- this.name = "RouteDockPolicyRejectedError";
114
+ constructor(reason, options = {}) {
115
+ super(`Payment rejected by policy: ${reason}`, "POLICY_REJECT", false, options);
116
+ this.name = "RouteDockPolicyRejectError";
47
117
  this.reason = reason;
48
118
  }
49
119
  };
120
+ var RouteDockChannelStateError = class extends RouteDockError {
121
+ constructor(message, options = {}) {
122
+ super(message, "CHANNEL_STATE", false, options);
123
+ this.name = "RouteDockChannelStateError";
124
+ }
125
+ };
126
+ var RouteDockDisputeError = class extends RouteDockError {
127
+ constructor(message, options = {}) {
128
+ super(message, "DISPUTE", false, options);
129
+ this.name = "RouteDockDisputeError";
130
+ }
131
+ };
132
+ var RouteDockRefundWindowError = class extends RouteDockError {
133
+ constructor(message, options = {}) {
134
+ super(message, "REFUND_WINDOW", false, options);
135
+ this.name = "RouteDockRefundWindowError";
136
+ }
137
+ };
138
+ var RouteDockPolicyRejectedError = RouteDockPolicyRejectError;
139
+ var RouteDockSessionError = RouteDockVoucherMonotonicityError;
140
+ function parseRetryAfterMs(response) {
141
+ const header = response.headers.get("Retry-After");
142
+ if (!header) return void 0;
143
+ const seconds = Number(header);
144
+ if (!Number.isNaN(seconds) && seconds >= 0) {
145
+ return seconds * 1e3;
146
+ }
147
+ const date = Date.parse(header);
148
+ if (!Number.isNaN(date)) {
149
+ return Math.max(0, date - Date.now());
150
+ }
151
+ return void 0;
152
+ }
153
+ function httpStatusToError(message, status, response) {
154
+ const retryAfterMs = response ? parseRetryAfterMs(response) : void 0;
155
+ const opts = retryAfterMs !== void 0 ? { retryAfterMs } : {};
156
+ if (status === 429 || status === 503 || status >= 500 && status < 600) {
157
+ return new RouteDockFacilitatorError(message, status, opts);
158
+ }
159
+ if (status >= 400) {
160
+ return new RouteDockManifestError(message, opts);
161
+ }
162
+ return new RouteDockNetworkError(message, opts);
163
+ }
164
+ function wrapFetchError(err, context) {
165
+ if (err instanceof RouteDockError) return err;
166
+ return new RouteDockNetworkError(`${context}: ${String(err)}`, { cause: err });
167
+ }
168
+ function wrapMppError(err, context) {
169
+ if (err instanceof RouteDockError) return err;
170
+ if (err instanceof TypeError || err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) {
171
+ return new RouteDockNetworkError(`${context}: ${String(err)}`, { cause: err });
172
+ }
173
+ return new RouteDockSignatureError(`${context}: ${String(err)}`, { cause: err });
174
+ }
175
+
176
+ // src/types.ts
177
+ var DEFAULT_MAX_SESSION_DURATION_MS = 36e5;
178
+
179
+ // src/internal/logger.ts
180
+ function createConsoleLogger() {
181
+ return (level, message, fields) => {
182
+ const values = fields ? Object.values(fields) : [];
183
+ if (values.length > 0) {
184
+ console[level](message, ...values);
185
+ } else {
186
+ console[level](message);
187
+ }
188
+ };
189
+ }
190
+ var consoleLogger = createConsoleLogger();
191
+ var noopLogger = () => {
192
+ };
193
+ function resolveLogger(logger, fallback = consoleLogger) {
194
+ return logger ?? fallback;
195
+ }
196
+
197
+ // src/internal/retry.ts
198
+ var DEFAULT_RETRY_POLICY = {
199
+ maxAttempts: 4,
200
+ baseDelayMs: 250,
201
+ maxDelayMs: 3e4
202
+ };
203
+ function backoffDelayMs(attempt, baseDelayMs, maxDelayMs = DEFAULT_RETRY_POLICY.maxDelayMs) {
204
+ const cappedDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
205
+ return Math.floor(Math.random() * (cappedDelay + 1));
206
+ }
207
+ function sleep(ms) {
208
+ return new Promise((resolve) => setTimeout(resolve, ms));
209
+ }
210
+ async function withRetry(fn, policy = {}) {
211
+ const { maxAttempts, baseDelayMs, maxDelayMs, onRetry, logger } = {
212
+ ...DEFAULT_RETRY_POLICY,
213
+ ...policy
214
+ };
215
+ const log = resolveLogger(logger);
216
+ let lastError;
217
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
218
+ try {
219
+ return await fn();
220
+ } catch (err) {
221
+ if (!(err instanceof RouteDockError)) {
222
+ throw err;
223
+ }
224
+ lastError = err;
225
+ if (!err.retryable || attempt >= maxAttempts - 1) {
226
+ throw err;
227
+ }
228
+ const delay = err.retryAfterMs !== void 0 ? err.retryAfterMs : backoffDelayMs(attempt, baseDelayMs, maxDelayMs);
229
+ if (onRetry) {
230
+ try {
231
+ await onRetry(attempt, err, delay);
232
+ } catch (cbErr) {
233
+ log("error", "[withRetry] onRetry callback threw:", { error: cbErr });
234
+ }
235
+ }
236
+ await sleep(delay);
237
+ }
238
+ }
239
+ throw lastError ?? new RouteDockError("Retry exhausted", "NETWORK", false);
240
+ }
241
+ var USDC_ISSUERS = {
242
+ testnet: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
243
+ mainnet: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN"
244
+ };
245
+ var usdcToUnits = nulthSdk.usdcToStroops;
246
+
247
+ // src/internal/assetUtils.ts
248
+ function normalizeManifestAssets(manifest) {
249
+ if (manifest.assets && manifest.assets.length > 0) {
250
+ return manifest.assets;
251
+ }
252
+ if (manifest.asset && manifest.asset_contract) {
253
+ return [
254
+ {
255
+ asset: manifest.asset,
256
+ asset_contract: manifest.asset_contract
257
+ }
258
+ ];
259
+ }
260
+ throw new RouteDockManifestError(
261
+ "Manifest must define either assets[] or root asset/asset_contract fields"
262
+ );
263
+ }
264
+ function getEligibleAssets(manifest, mode, endpoint) {
265
+ const assets = normalizeManifestAssets(manifest);
266
+ return assets.filter((asset) => {
267
+ if (asset.modes && !asset.modes.includes(mode)) {
268
+ return false;
269
+ }
270
+ if (endpoint && asset.endpoints && asset.endpoints.length > 0) {
271
+ const trimmedEndpoint = endpoint.replace(/^\//, "");
272
+ if (asset.endpoints.includes(endpoint) || asset.endpoints.includes(trimmedEndpoint)) {
273
+ return true;
274
+ }
275
+ if (manifest.endpoints) {
276
+ let pathname = endpoint;
277
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
278
+ try {
279
+ pathname = new URL(endpoint).pathname;
280
+ } catch {
281
+ }
282
+ }
283
+ const trimmedPathname = pathname.replace(/^\//, "");
284
+ const matchesEndpoint = Object.entries(manifest.endpoints).some(([key, desc]) => {
285
+ const pathMatches = desc.path === pathname || desc.path === endpoint || desc.path.replace(/\/+$/, "") === pathname.replace(/\/+$/, "") || desc.path.replace(/^\//, "") === trimmedPathname;
286
+ const keyMatches = key === endpoint || key === trimmedEndpoint;
287
+ if (pathMatches || keyMatches) {
288
+ return asset.endpoints.includes(key) || asset.endpoints.includes(desc.path) || asset.endpoints.includes(desc.path.replace(/^\//, ""));
289
+ }
290
+ return false;
291
+ });
292
+ if (!matchesEndpoint) {
293
+ return false;
294
+ }
295
+ } else {
296
+ return false;
297
+ }
298
+ }
299
+ return true;
300
+ });
301
+ }
302
+ function resolveAssetContract(manifest, mode, endpoint, explicitContract) {
303
+ if (manifest.assets && manifest.assets.length > 0) {
304
+ return selectAsset(manifest, mode, endpoint).asset_contract;
305
+ }
306
+ return explicitContract ?? selectAsset(manifest, mode, endpoint).asset_contract;
307
+ }
308
+ function selectAsset(manifest, mode, endpoint) {
309
+ const eligible = getEligibleAssets(manifest, mode, endpoint);
310
+ if (eligible.length === 0) {
311
+ const endpointMsg = endpoint ? ` for endpoint '${endpoint}'` : "";
312
+ throw new RouteDockManifestError(
313
+ `No eligible assets found for mode '${mode}'${endpointMsg}`
314
+ );
315
+ }
316
+ return eligible[0];
317
+ }
318
+ function isAssetEligible(manifest, assetIdentifier, mode, endpoint) {
319
+ const eligible = getEligibleAssets(manifest, mode, endpoint);
320
+ return eligible.some(
321
+ (asset) => asset.asset === assetIdentifier || asset.asset_contract === assetIdentifier
322
+ );
323
+ }
50
324
 
51
325
  // src/schemas/routedock.schema.json
52
326
  var routedock_schema_default = {
53
327
  $schema: "http://json-schema.org/draft-07/schema#",
54
- $id: "https://routedock.dev/schemas/routedock.schema.json",
328
+ $id: "https://routedock.xyz/schemas/routedock.schema.json",
55
329
  title: "RouteDock Manifest",
56
330
  description: "Discovery manifest served at /.well-known/routedock.json on every RouteDock provider endpoint",
57
331
  type: "object",
@@ -72,8 +346,26 @@ var routedock_schema_default = {
72
346
  properties: {
73
347
  routedock: {
74
348
  type: "string",
75
- const: "1.0",
76
- description: "Manifest schema version. Always '1.0' for this version."
349
+ pattern: "^[0-9]+\\.[0-9]+$",
350
+ description: "Manifest schema version, e.g. '1.0', '1.1', '2.0'."
351
+ },
352
+ min_client_version: {
353
+ type: "string",
354
+ pattern: "^[0-9]+\\.[0-9]+$",
355
+ description: "Minimum SDK client version (major.minor) required to use this manifest. Clients below this version must refuse to pay."
356
+ },
357
+ deprecated_modes: {
358
+ type: "array",
359
+ items: {
360
+ $ref: "#/definitions/PaymentMode"
361
+ },
362
+ uniqueItems: true,
363
+ description: "Payment modes still listed in 'modes' for backwards compatibility but deprecated for new integrations."
364
+ },
365
+ sunset_at: {
366
+ type: "string",
367
+ format: "date-time",
368
+ description: "ISO 8601 timestamp after which this manifest version is no longer supported by the provider."
77
369
  },
78
370
  name: {
79
371
  type: "string",
@@ -109,6 +401,14 @@ var routedock_schema_default = {
109
401
  type: "string",
110
402
  description: "Stellar Asset Contract (SAC) address for the payment asset"
111
403
  },
404
+ assets: {
405
+ type: "array",
406
+ minItems: 1,
407
+ items: {
408
+ $ref: "#/definitions/AssetConfig"
409
+ },
410
+ description: "Payment assets accepted by this provider. Each asset can be scoped to specific modes and endpoints. When present, assets[0] must match the root-level asset and asset_contract."
411
+ },
112
412
  payee: {
113
413
  type: "string",
114
414
  description: "Stellar address (G...) that receives payments"
@@ -126,18 +426,25 @@ var routedock_schema_default = {
126
426
  },
127
427
  "mpp-session": {
128
428
  $ref: "#/definitions/SessionPricingConfig"
429
+ },
430
+ "mpp-session-ws": {
431
+ $ref: "#/definitions/SessionPricingConfig",
432
+ description: "WebSocket transport variant of mpp-session: channel opened and first voucher negotiated over HTTP, then the connection upgrades to WebSocket for push-based streaming."
129
433
  }
130
434
  },
131
435
  minProperties: 1
132
436
  },
133
437
  endpoints: {
134
438
  type: "object",
135
- description: "Map of endpoint name to HTTP method + path (e.g. { 'price': 'GET /price' })",
439
+ description: "Map of endpoint name to endpoint descriptors",
136
440
  additionalProperties: {
137
- type: "string"
441
+ $ref: "#/definitions/EndpointDescriptor"
138
442
  },
139
443
  minProperties: 1
140
444
  },
445
+ sla: {
446
+ $ref: "#/definitions/SLAConfig"
447
+ },
141
448
  tags: {
142
449
  type: "array",
143
450
  items: {
@@ -147,14 +454,125 @@ var routedock_schema_default = {
147
454
  },
148
455
  uniqueItems: true,
149
456
  description: "Capability tags indexed with trigram search in the provider registry"
457
+ },
458
+ vault: {
459
+ $ref: "#/definitions/VaultMode"
460
+ },
461
+ nulth_account: {
462
+ type: "string",
463
+ description: "Optional Nulth smart account address associated with this provider"
464
+ },
465
+ capabilities: {
466
+ type: "object",
467
+ description: "Optional protocol features this provider supports",
468
+ properties: {
469
+ streaming: {
470
+ type: "array",
471
+ items: {
472
+ type: "string",
473
+ enum: ["sse", "websocket"]
474
+ },
475
+ description: "Supported streaming transports"
476
+ },
477
+ webhooks: {
478
+ type: "boolean",
479
+ description: "Whether webhook callbacks are supported"
480
+ },
481
+ idempotency_keys: {
482
+ type: "boolean",
483
+ description: "Whether idempotency keys are supported"
484
+ },
485
+ content_types: {
486
+ type: "array",
487
+ items: {
488
+ type: "string"
489
+ },
490
+ description: "Supported content types for request/response"
491
+ }
492
+ },
493
+ additionalProperties: false
494
+ },
495
+ regions: {
496
+ type: "array",
497
+ items: {
498
+ type: "string",
499
+ minLength: 2,
500
+ maxLength: 10
501
+ },
502
+ uniqueItems: true,
503
+ description: "IATA airport codes or UN/LOCODE identifiers for regions where this provider has infrastructure (e.g. ['IAD', 'AMS']). Used by agents to select the nearest provider."
504
+ },
505
+ latency_hints: {
506
+ type: "object",
507
+ additionalProperties: {
508
+ type: "number",
509
+ minimum: 0
510
+ },
511
+ description: "Provider-declared p50 latency in milliseconds per region code. Keys must be a subset of 'regions'. Example: { 'IAD': 14, 'AMS': 22 }."
512
+ },
513
+ signature: {
514
+ type: "string",
515
+ description: "Base64 Ed25519 signature (payee keypair) over the SHA-256 hash of this manifest with the signature field omitted. Clients must verify before trusting any routing field."
516
+ },
517
+ signature_version: {
518
+ type: "string",
519
+ const: "2",
520
+ description: "Manifest signature format. Version 2 recursively includes every nested manifest field in the signed digest."
521
+ },
522
+ categories: {
523
+ type: "array",
524
+ items: {
525
+ type: "string",
526
+ minLength: 1,
527
+ maxLength: 128
528
+ },
529
+ uniqueItems: true,
530
+ description: "Optional hierarchical categories from a published taxonomy (e.g. data/price/crypto)"
150
531
  }
151
532
  },
152
533
  definitions: {
534
+ VaultMode: {
535
+ type: "string",
536
+ enum: ["local-key", "agent-vault", "nulth"],
537
+ description: "Agent vault / custody mode for payments from this provider"
538
+ },
153
539
  PaymentMode: {
154
540
  type: "string",
155
- enum: ["x402", "mpp-charge", "mpp-session"],
541
+ enum: ["x402", "mpp-charge", "mpp-session", "mpp-session-ws"],
156
542
  description: "A supported RouteDock payment mode"
157
543
  },
544
+ AssetConfig: {
545
+ type: "object",
546
+ description: "Payment asset configuration with optional mode and endpoint scoping",
547
+ required: ["asset", "asset_contract"],
548
+ additionalProperties: false,
549
+ properties: {
550
+ asset: {
551
+ type: "string",
552
+ description: "Asset ticker symbol (e.g. 'USDC' or 'XLM')"
553
+ },
554
+ asset_contract: {
555
+ type: "string",
556
+ description: "Stellar Asset Contract (SAC) address for the payment asset"
557
+ },
558
+ modes: {
559
+ type: "array",
560
+ items: {
561
+ $ref: "#/definitions/PaymentMode"
562
+ },
563
+ uniqueItems: true,
564
+ description: "Optional: restrict this asset to specific payment modes. If omitted, available for all modes."
565
+ },
566
+ endpoints: {
567
+ type: "array",
568
+ items: {
569
+ type: "string"
570
+ },
571
+ uniqueItems: true,
572
+ description: "Optional: restrict this asset to specific endpoints (by name). If omitted, available for all endpoints."
573
+ }
574
+ }
575
+ },
158
576
  PricingConfig: {
159
577
  type: "object",
160
578
  description: "Per-request pricing for x402 or mpp-charge modes",
@@ -173,13 +591,17 @@ var routedock_schema_default = {
173
591
  facilitator: {
174
592
  type: "string",
175
593
  description: "x402 facilitator URL (required for x402 mode). OpenZeppelin Channels endpoint."
594
+ },
595
+ payee: {
596
+ type: "string",
597
+ description: "Optional per-mode payee override (Stellar G... address). Directs settlements for this mode to a separate account for treasury separation. Falls back to the top-level 'payee' when omitted."
176
598
  }
177
599
  }
178
600
  },
179
601
  SessionPricingConfig: {
180
602
  type: "object",
181
603
  description: "Per-voucher pricing for mpp-session (one-way-channel) mode",
182
- required: ["rate", "per", "channel_contract", "min_deposit", "refund_waiting_period_ledgers"],
604
+ required: ["rate", "per", "channel_factory", "min_deposit", "refund_waiting_period_ledgers"],
183
605
  additionalProperties: false,
184
606
  properties: {
185
607
  rate: {
@@ -191,9 +613,9 @@ var routedock_schema_default = {
191
613
  const: "voucher",
192
614
  description: "Billing unit \u2014 always 'voucher' for session mode"
193
615
  },
194
- channel_contract: {
616
+ channel_factory: {
195
617
  type: "string",
196
- description: "Soroban contract address (C...) for the one-way-channel contract"
618
+ description: "Stable Soroban factory address (C...) used to deploy a per-session channel"
197
619
  },
198
620
  min_deposit: {
199
621
  type: "string",
@@ -205,138 +627,706 @@ var routedock_schema_default = {
205
627
  description: "Ledgers the server has to settle before the funder can reclaim. Default: 17280 (~24h). Do not reduce in production."
206
628
  }
207
629
  }
630
+ },
631
+ SLAConfig: {
632
+ type: "object",
633
+ description: "Service Level Agreement for the provider",
634
+ required: ["uptime_30d_percent", "p95_latency_ms"],
635
+ additionalProperties: false,
636
+ properties: {
637
+ uptime_30d_percent: {
638
+ type: "number",
639
+ description: "Uptime percentage over the last 30 days"
640
+ },
641
+ p95_latency_ms: {
642
+ type: "number",
643
+ description: "P95 latency in milliseconds"
644
+ },
645
+ maintenance_windows: {
646
+ type: "array",
647
+ items: {
648
+ type: "object",
649
+ required: ["cron", "duration_minutes"],
650
+ additionalProperties: false,
651
+ properties: {
652
+ cron: {
653
+ type: "string",
654
+ description: "Cron expression for the maintenance window"
655
+ },
656
+ duration_minutes: {
657
+ type: "number",
658
+ description: "Duration of the maintenance window in minutes"
659
+ }
660
+ }
661
+ }
662
+ }
663
+ }
664
+ },
665
+ EndpointDescriptor: {
666
+ type: "object",
667
+ description: "Descriptor for a provider endpoint",
668
+ required: ["method", "path"],
669
+ additionalProperties: false,
670
+ properties: {
671
+ method: {
672
+ type: "string",
673
+ description: "HTTP method for the endpoint"
674
+ },
675
+ path: {
676
+ type: "string",
677
+ description: "Path for the endpoint"
678
+ },
679
+ deprecated: {
680
+ type: "boolean",
681
+ description: "Whether this endpoint is retained only for backwards compatibility"
682
+ },
683
+ sunset_at: {
684
+ type: "string",
685
+ format: "date-time",
686
+ description: "ISO 8601 timestamp after which callers should stop using this endpoint"
687
+ },
688
+ headers: {
689
+ type: "object",
690
+ additionalProperties: {
691
+ type: "string"
692
+ },
693
+ description: "Expected request headers"
694
+ },
695
+ request_schema: {
696
+ description: "JSON schema for the request body"
697
+ },
698
+ response_schema: {
699
+ description: "JSON schema for the response body"
700
+ },
701
+ rate_limit: {
702
+ type: "object",
703
+ required: ["requests", "window_seconds"],
704
+ additionalProperties: false,
705
+ properties: {
706
+ requests: {
707
+ type: "number"
708
+ },
709
+ window_seconds: {
710
+ type: "number"
711
+ }
712
+ }
713
+ }
714
+ }
208
715
  }
209
716
  }
210
717
  };
211
718
 
212
- // src/client/ModeRouter.ts
213
- var ajv = new Ajv__default.default();
214
- var validateManifest = ajv.compile(routedock_schema_default);
215
- var CACHE_TTL_MS = 6e4;
216
- var manifestCache = /* @__PURE__ */ new Map();
217
- async function fetchManifest(baseUrl) {
218
- const cached = manifestCache.get(baseUrl);
219
- if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
220
- return cached.manifest;
719
+ // package.json
720
+ var package_default = {
721
+ version: "0.3.0"};
722
+ var MANIFEST_SIGNATURE_VERSION = "2";
723
+ function canonicalize(value) {
724
+ if (Array.isArray(value)) {
725
+ return value.map(canonicalize);
221
726
  }
222
- const url = baseUrl.replace(/\/$/, "") + "/.well-known/routedock.json";
223
- let raw;
727
+ if (value !== null && typeof value === "object") {
728
+ return Object.fromEntries(
729
+ Object.keys(value).sort().map((key) => [key, canonicalize(value[key])])
730
+ );
731
+ }
732
+ return value;
733
+ }
734
+ function manifestDigest(manifest) {
735
+ const { signature: _omit, ...rest } = manifest;
736
+ const canonical = JSON.stringify(canonicalize(rest));
737
+ return crypto.createHash("sha256").update(canonical, "utf8").digest();
738
+ }
739
+ function verifyManifestSignature(manifest, expectedPayee) {
740
+ if (!manifest.signature) {
741
+ throw new RouteDockSignatureError(
742
+ "Manifest is missing a signature field \u2014 cannot verify payee authenticity"
743
+ );
744
+ }
745
+ if (manifest.signature_version !== MANIFEST_SIGNATURE_VERSION) {
746
+ throw new RouteDockSignatureError(
747
+ `Manifest signature version must be ${MANIFEST_SIGNATURE_VERSION}; legacy signatures are not safe because nested fields were excluded from their digest`
748
+ );
749
+ }
750
+ if (expectedPayee !== void 0 && manifest.payee !== expectedPayee) {
751
+ throw new RouteDockSignatureError(
752
+ `Manifest payee ${manifest.payee} does not match expected payee ${expectedPayee}`
753
+ );
754
+ }
755
+ const keypair = stellarSdk.Keypair.fromPublicKey(manifest.payee);
756
+ const digest = manifestDigest(manifest);
757
+ let sigBytes;
224
758
  try {
225
- const resp = await fetch(url);
226
- if (!resp.ok) {
227
- throw new RouteDockManifestError(`Manifest fetch failed: HTTP ${resp.status} from ${url}`);
228
- }
229
- raw = await resp.json();
230
- } catch (err) {
231
- if (err instanceof RouteDockManifestError) throw err;
232
- throw new RouteDockManifestError(`Manifest fetch error: ${String(err)}`);
759
+ sigBytes = Buffer.from(manifest.signature, "base64");
760
+ } catch {
761
+ throw new RouteDockSignatureError("Manifest signature is not valid base64");
233
762
  }
234
- if (!validateManifest(raw)) {
235
- const msgs = ajv.errorsText(validateManifest.errors);
236
- throw new RouteDockManifestError(`Invalid manifest at ${url}: ${msgs}`);
763
+ let valid = false;
764
+ try {
765
+ valid = keypair.verify(digest, sigBytes);
766
+ } catch {
767
+ throw new RouteDockSignatureError(
768
+ `Manifest signature verification failed for payee ${manifest.payee}`
769
+ );
237
770
  }
238
- const manifest = raw;
239
- manifestCache.set(baseUrl, { manifest, fetchedAt: Date.now() });
240
- return manifest;
241
- }
242
- function selectMode(manifest, options = {}) {
243
- const modes = manifest.modes;
244
- if (options.forceMode) {
245
- if (!modes.includes(options.forceMode)) {
246
- throw new RouteDockNoSupportedModeError(
247
- `Provider does not support forced mode: ${options.forceMode} (available: ${modes.join(", ")})`
248
- );
249
- }
250
- console.log(`[RouteDock] ${manifest.name} \u2192 ${options.forceMode} (forced)`);
251
- return options.forceMode;
771
+ if (!valid) {
772
+ throw new RouteDockSignatureError(
773
+ `Manifest signature verification failed for payee ${manifest.payee}`
774
+ );
252
775
  }
253
- if ((options.sustained || options.session) && modes.includes("mpp-session")) {
254
- const mode = "mpp-session";
255
- console.log(`[RouteDock] ${manifest.name} \u2192 ${mode}`);
256
- return mode;
776
+ }
777
+
778
+ // src/client/ModeRouter.ts
779
+ var validator = new jsonSchema.Validator(routedock_schema_default, "7");
780
+ var SDK_VERSION = package_default.version;
781
+ function parseMajorMinor(version) {
782
+ const parts = version.split(".");
783
+ return [Number.parseInt(parts[0] ?? "0", 10), Number.parseInt(parts[1] ?? "0", 10)];
784
+ }
785
+ function isVersionBelow(a, b) {
786
+ const [aMajor, aMinor] = parseMajorMinor(a);
787
+ const [bMajor, bMinor] = parseMajorMinor(b);
788
+ return aMajor < bMajor || aMajor === bMajor && aMinor < bMinor;
789
+ }
790
+ function assertClientVersionSupported(manifest, baseUrl) {
791
+ const minVersion = manifest.min_client_version;
792
+ if (minVersion && isVersionBelow(SDK_VERSION, minVersion)) {
793
+ throw new RouteDockClientVersionError(
794
+ `SDK version ${SDK_VERSION} is below the minimum required version ${minVersion} for provider at ${baseUrl}. Please upgrade the SDK.`
795
+ );
257
796
  }
258
- if (modes.includes("mpp-charge")) {
259
- const mode = "mpp-charge";
260
- console.log(`[RouteDock] ${manifest.name} \u2192 ${mode}`);
261
- return mode;
797
+ }
798
+ function assertManifestActive(manifest, baseUrl) {
799
+ const sunsetAt = manifest.sunset_at;
800
+ if (!sunsetAt) return;
801
+ const sunsetTime = Date.parse(sunsetAt);
802
+ if (!Number.isFinite(sunsetTime)) {
803
+ throw new RouteDockManifestError(
804
+ `Manifest at ${baseUrl} contains an invalid sunset_at timestamp: ${sunsetAt}`
805
+ );
262
806
  }
263
- if (modes.includes("x402")) {
264
- const mode = "x402";
265
- console.log(`[RouteDock] ${manifest.name} \u2192 ${mode}`);
266
- return mode;
807
+ if (sunsetTime <= Date.now()) {
808
+ throw new RouteDockManifestSunsetError(
809
+ `Manifest for provider at ${baseUrl} sunset at ${sunsetAt} and can no longer be used`
810
+ );
267
811
  }
268
- throw new RouteDockNoSupportedModeError(
269
- `No supported payment mode found in manifest (modes: ${modes.join(", ")})`
270
- );
271
812
  }
272
- var CAIP2 = {
273
- testnet: "stellar:testnet",
274
- mainnet: "stellar:pubnet"
275
- };
276
- var X402Client = class {
277
- constructor(secretKey, network) {
278
- this.secretKey = secretKey;
279
- this.network = network;
280
- const caip2 = CAIP2[network];
281
- const signer = stellar.createEd25519Signer(secretKey, caip2);
282
- const scheme = new client.ExactStellarScheme(signer);
283
- const core = new client$1.x402Client();
284
- core.register(caip2, scheme);
285
- this.httpClient = new client$1.x402HTTPClient(core);
813
+ function assertEndpointActive(manifest, url, logger) {
814
+ const pathname = new URL(url).pathname;
815
+ const matches = Object.entries(manifest.endpoints).filter(
816
+ ([, descriptor]) => descriptor.path === pathname
817
+ );
818
+ if (matches.length === 0) return;
819
+ const now = Date.now();
820
+ const allSunset = matches.every(([, descriptor]) => {
821
+ const sunsetAt = descriptor.sunset_at;
822
+ return typeof sunsetAt === "string" && Date.parse(sunsetAt) <= now;
823
+ });
824
+ if (allSunset) {
825
+ const [key, descriptor] = matches[0];
826
+ throw new RouteDockManifestSunsetError(
827
+ `Endpoint '${key}' (${pathname}) sunset at ${descriptor.sunset_at} and can no longer be used`
828
+ );
286
829
  }
287
- secretKey;
288
- network;
289
- httpClient;
290
- async pay(url, manifest) {
291
- const pricing = manifest.pricing.x402;
292
- if (!pricing) {
293
- throw new RouteDockManifestError("manifest.pricing.x402 missing");
830
+ const deprecated = matches.find(([, descriptor]) => descriptor.deprecated === true);
831
+ if (deprecated && logger) {
832
+ const [key, descriptor] = deprecated;
833
+ const sunsetSuffix = descriptor.sunset_at ? `; sunset_at ${descriptor.sunset_at}` : "";
834
+ logger(
835
+ "warn",
836
+ `[RouteDock] WARNING: ${manifest.name} \u2192 ${pathname}; endpoint '${key}' is deprecated${sunsetSuffix}`
837
+ );
838
+ }
839
+ }
840
+ function assertManifestValid(manifest, baseUrl) {
841
+ const context = baseUrl ? ` at ${baseUrl}` : "";
842
+ if (manifest.latency_hints !== void 0) {
843
+ if (!Array.isArray(manifest.regions) || manifest.regions.length === 0) {
844
+ throw new RouteDockManifestError(
845
+ `Invalid manifest${context}: latency_hints defined without declaring regions`
846
+ );
294
847
  }
295
- if (!pricing.facilitator) {
296
- throw new RouteDockManifestError("manifest.pricing.x402.facilitator missing");
848
+ const regionSet = new Set(manifest.regions);
849
+ for (const region of Object.keys(manifest.latency_hints)) {
850
+ if (!regionSet.has(region)) {
851
+ throw new RouteDockManifestError(
852
+ `Invalid manifest${context}: latency_hints key '${region}' is not declared in regions (${manifest.regions.join(", ")})`
853
+ );
854
+ }
297
855
  }
298
- const init = await fetch(url, { headers: { "X-Preferred-Mode": "x402" } });
299
- if (init.status !== 402) {
300
- const data2 = await init.json();
301
- return { data: data2, txHash: null, mode: "x402", amount: pricing.amount, timestamp: Date.now() };
856
+ }
857
+ if (manifest.assets !== void 0) {
858
+ if (!Array.isArray(manifest.assets) || manifest.assets.length === 0) {
859
+ throw new RouteDockManifestError(
860
+ `Invalid manifest${context}: assets must be a non-empty array when defined`
861
+ );
302
862
  }
303
- const reqHeader = init.headers.get("X-Payment-Requirements");
304
- if (!reqHeader) {
305
- throw new RouteDockManifestError("402 response missing X-Payment-Requirements header");
863
+ for (let i = 0; i < manifest.assets.length; i++) {
864
+ const a = manifest.assets[i];
865
+ if (!a || typeof a.asset !== "string" || typeof a.asset_contract !== "string") {
866
+ throw new RouteDockManifestError(
867
+ `Invalid manifest${context}: assets[${i}] must define asset and asset_contract strings`
868
+ );
869
+ }
306
870
  }
307
- const paymentRequired = http.decodePaymentRequiredHeader(reqHeader);
308
- const paymentPayload = await this.httpClient.createPaymentPayload(paymentRequired);
309
- const paymentHeaders = this.httpClient.encodePaymentSignatureHeader(paymentPayload);
310
- const settled = await fetch(url, { headers: paymentHeaders });
311
- if (!settled.ok) {
312
- throw new RouteDockManifestError(`x402 payment failed: HTTP ${settled.status}`);
871
+ const first = manifest.assets[0];
872
+ if (first.asset !== manifest.asset || first.asset_contract !== manifest.asset_contract) {
873
+ throw new RouteDockManifestError(
874
+ `Invalid manifest${context}: assets[0] (${first.asset}:${first.asset_contract}) must match root asset fields (${manifest.asset}:${manifest.asset_contract})`
875
+ );
313
876
  }
314
- let txHash = null;
315
- const responseHeader = settled.headers.get("X-Payment-Response");
316
- if (responseHeader) {
317
- try {
318
- const settleResponse = http.decodePaymentResponseHeader(responseHeader);
877
+ }
878
+ }
879
+ var CACHE_TTL_MS = 6e4;
880
+ var DEFAULT_MANIFEST_CACHE_MAX_SIZE = 512;
881
+ var DEFAULT_MANIFEST_TIMEOUT_MS = 5e3;
882
+ var LruCache = class {
883
+ constructor(maxSize) {
884
+ this.maxSize = maxSize;
885
+ }
886
+ maxSize;
887
+ map = /* @__PURE__ */ new Map();
888
+ get(key) {
889
+ if (!this.map.has(key)) return void 0;
890
+ const value = this.map.get(key);
891
+ this.map.delete(key);
892
+ this.map.set(key, value);
893
+ return value;
894
+ }
895
+ set(key, value) {
896
+ if (this.map.has(key)) {
897
+ this.map.delete(key);
898
+ } else if (this.map.size >= this.maxSize) {
899
+ const oldestKey = this.map.keys().next().value;
900
+ if (oldestKey !== void 0) {
901
+ this.map.delete(oldestKey);
902
+ }
903
+ }
904
+ this.map.set(key, value);
905
+ }
906
+ setMaxSize(maxSize) {
907
+ this.maxSize = maxSize;
908
+ while (this.map.size > this.maxSize) {
909
+ const oldestKey = this.map.keys().next().value;
910
+ if (oldestKey === void 0) break;
911
+ this.map.delete(oldestKey);
912
+ }
913
+ }
914
+ delete(key) {
915
+ this.map.delete(key);
916
+ }
917
+ };
918
+ var manifestCache = new LruCache(DEFAULT_MANIFEST_CACHE_MAX_SIZE);
919
+ function configureManifestCache(maxSize) {
920
+ if (!Number.isInteger(maxSize) || maxSize <= 0) {
921
+ throw new RouteDockManifestError("Invalid manifest cache size: " + maxSize);
922
+ }
923
+ manifestCache.setMaxSize(maxSize);
924
+ }
925
+ function invalidateManifest(baseUrl) {
926
+ manifestCache.delete(baseUrl);
927
+ }
928
+ function ttlFromHeaders(headers, now) {
929
+ const cacheControl = headers.get("cache-control");
930
+ if (cacheControl) {
931
+ const directives = cacheControl.split(",").map((directive) => directive.trim().toLowerCase());
932
+ if (directives.includes("no-store") || directives.includes("no-cache")) {
933
+ return 0;
934
+ }
935
+ const maxAge = /max-age=(\d+)/i.exec(cacheControl);
936
+ if (maxAge) {
937
+ return Number.parseInt(maxAge[1], 10) * 1e3;
938
+ }
939
+ }
940
+ const expires = headers.get("expires");
941
+ if (expires) {
942
+ const expiresTime = Date.parse(expires);
943
+ if (Number.isFinite(expiresTime)) {
944
+ return expiresTime - now;
945
+ }
946
+ }
947
+ return CACHE_TTL_MS;
948
+ }
949
+ async function fetchManifest(baseUrl, retryPolicy, manifestTimeoutMs = DEFAULT_MANIFEST_TIMEOUT_MS, expectedPayee) {
950
+ const cached = manifestCache.get(baseUrl);
951
+ if (cached && Date.now() < cached.expiresAt) {
952
+ verifyManifestSignature(cached.manifest, expectedPayee);
953
+ assertClientVersionSupported(cached.manifest, baseUrl);
954
+ assertManifestValid(cached.manifest, baseUrl);
955
+ assertManifestActive(cached.manifest, baseUrl);
956
+ return cached.manifest;
957
+ }
958
+ const url = baseUrl.replace(/\/$/, "") + "/.well-known/routedock.json";
959
+ return withRetry(async () => {
960
+ let raw;
961
+ let resp;
962
+ let expiresAt = 0;
963
+ try {
964
+ resp = await fetch(url, { signal: AbortSignal.timeout(manifestTimeoutMs) });
965
+ if (!resp.ok) {
966
+ if (resp.status >= 500 || resp.status === 429 || resp.status === 503) {
967
+ throw httpStatusToError(
968
+ `Manifest fetch failed: HTTP ${resp.status} from ${url}`,
969
+ resp.status,
970
+ resp
971
+ );
972
+ }
973
+ throw new RouteDockManifestError(
974
+ `Manifest fetch failed: HTTP ${resp.status} from ${url}`
975
+ );
976
+ }
977
+ } catch (err) {
978
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
979
+ throw new RouteDockManifestTimeoutError(
980
+ `Manifest fetch timed out after ${manifestTimeoutMs}ms from ${url}`,
981
+ { cause: err }
982
+ );
983
+ }
984
+ if (err instanceof RouteDockError) throw err;
985
+ throw wrapFetchError(err, `Manifest fetch error from ${url}`);
986
+ }
987
+ const now = Date.now();
988
+ expiresAt = now + ttlFromHeaders(resp.headers, now);
989
+ try {
990
+ raw = await resp.json();
991
+ } catch (err) {
992
+ throw new RouteDockManifestError(`Manifest at ${url} is not valid JSON`, { cause: err });
993
+ }
994
+ const result = validator.validate(raw);
995
+ if (!result.valid) {
996
+ const msgs = result.errors.map((err) => err.error).join("; ");
997
+ throw new RouteDockManifestError(`Invalid manifest at ${url}: ${msgs}`);
998
+ }
999
+ const manifest = raw;
1000
+ assertManifestValid(manifest, baseUrl);
1001
+ verifyManifestSignature(manifest, expectedPayee);
1002
+ assertClientVersionSupported(manifest, baseUrl);
1003
+ assertManifestActive(manifest, baseUrl);
1004
+ manifestCache.set(baseUrl, { manifest, fetchedAt: Date.now(), expiresAt });
1005
+ return manifest;
1006
+ }, retryPolicy);
1007
+ }
1008
+ function selectFromModes(modes, manifest, options) {
1009
+ if (options.sustained || options.session) {
1010
+ if (options.transport === "websocket") {
1011
+ if (modes.includes("mpp-session-ws")) return { mode: "mpp-session-ws" };
1012
+ if (modes.includes("mpp-session")) return { mode: "mpp-session" };
1013
+ } else {
1014
+ if (modes.includes("mpp-session")) return { mode: "mpp-session" };
1015
+ if (modes.includes("mpp-session-ws")) return { mode: "mpp-session-ws" };
1016
+ }
1017
+ }
1018
+ if (options.optimize === "cost") {
1019
+ let budgetStroops = null;
1020
+ if (options.budget_per_request !== void 0) {
1021
+ try {
1022
+ budgetStroops = nulthSdk.usdcToStroops(options.budget_per_request);
1023
+ } catch {
1024
+ throw new RouteDockPolicyRejectError("invalid_budget_per_request");
1025
+ }
1026
+ }
1027
+ const candidates = ["x402", "mpp-charge"].filter((mode) => modes.includes(mode)).flatMap((mode) => {
1028
+ const amount = manifest.pricing[mode]?.amount;
1029
+ if (typeof amount !== "string") return [];
1030
+ try {
1031
+ return [{ mode, amountStroops: nulthSdk.usdcToStroops(amount) }];
1032
+ } catch {
1033
+ return [];
1034
+ }
1035
+ });
1036
+ if (candidates.length > 0) {
1037
+ const affordableCandidates = budgetStroops === null ? candidates : candidates.filter((candidate) => candidate.amountStroops <= budgetStroops);
1038
+ const cheapestCandidate = [...affordableCandidates].sort(
1039
+ (a, b) => a.amountStroops < b.amountStroops ? -1 : a.amountStroops > b.amountStroops ? 1 : 0
1040
+ )[0];
1041
+ if (cheapestCandidate) {
1042
+ return { mode: cheapestCandidate.mode, reason: "cost-optimized" };
1043
+ }
1044
+ if (budgetStroops !== null) {
1045
+ throw new RouteDockPolicyRejectError("budget_per_request_exceeded");
1046
+ }
1047
+ }
1048
+ }
1049
+ if (modes.includes("mpp-charge")) return { mode: "mpp-charge" };
1050
+ if (modes.includes("x402")) return { mode: "x402" };
1051
+ return void 0;
1052
+ }
1053
+ function logSelection(manifest, selection, log, deprecated) {
1054
+ const reason = selection.reason ? ` (${selection.reason})` : "";
1055
+ if (deprecated) {
1056
+ log(
1057
+ "warn",
1058
+ `[RouteDock] WARNING: ${manifest.name} \u2192 ${selection.mode}${reason}; selected deprecated mode because no active supported mode is available`
1059
+ );
1060
+ return;
1061
+ }
1062
+ log("info", `[RouteDock] ${manifest.name} \u2192 ${selection.mode}${reason}`);
1063
+ }
1064
+ function selectMode(manifest, options = {}) {
1065
+ const modes = manifest.modes;
1066
+ const log = options.logger ?? noopLogger;
1067
+ const deprecatedSet = new Set(manifest.deprecated_modes ?? []);
1068
+ if (options.forceMode) {
1069
+ if (!modes.includes(options.forceMode)) {
1070
+ throw new RouteDockNoSupportedModeError(
1071
+ `Provider does not support forced mode: ${options.forceMode} (available: ${modes.join(", ")})`
1072
+ );
1073
+ }
1074
+ if (deprecatedSet.has(options.forceMode)) {
1075
+ log(
1076
+ "warn",
1077
+ `[RouteDock] WARNING: ${manifest.name} \u2192 ${options.forceMode} (forced); selected mode is deprecated`
1078
+ );
1079
+ } else {
1080
+ log("info", `[RouteDock] ${manifest.name} \u2192 ${options.forceMode} (forced)`);
1081
+ }
1082
+ return options.forceMode;
1083
+ }
1084
+ const activeModes = modes.filter((mode) => !deprecatedSet.has(mode));
1085
+ const deprecatedModes = modes.filter((mode) => deprecatedSet.has(mode));
1086
+ const activeSelection = selectFromModes(activeModes, manifest, options);
1087
+ if (activeSelection) {
1088
+ logSelection(manifest, activeSelection, log, false);
1089
+ return activeSelection.mode;
1090
+ }
1091
+ const deprecatedSelection = selectFromModes(deprecatedModes, manifest, options);
1092
+ if (deprecatedSelection) {
1093
+ logSelection(manifest, deprecatedSelection, log, true);
1094
+ return deprecatedSelection.mode;
1095
+ }
1096
+ throw new RouteDockNoSupportedModeError(
1097
+ `No supported payment mode found in manifest (modes: ${modes.join(", ")})`
1098
+ );
1099
+ }
1100
+ function rankProvidersByLatency(manifests, targetRegion) {
1101
+ return [...manifests].sort((a, b) => {
1102
+ const latA = a.latency_hints?.[targetRegion];
1103
+ const latB = b.latency_hints?.[targetRegion];
1104
+ const inRegionsA = a.regions?.includes(targetRegion) ?? false;
1105
+ const inRegionsB = b.regions?.includes(targetRegion) ?? false;
1106
+ if (latA !== void 0 && latB !== void 0) {
1107
+ return latA - latB;
1108
+ }
1109
+ if (latA !== void 0) return -1;
1110
+ if (latB !== void 0) return 1;
1111
+ if (inRegionsA && !inRegionsB) return -1;
1112
+ if (!inRegionsA && inRegionsB) return 1;
1113
+ return 0;
1114
+ });
1115
+ }
1116
+
1117
+ // src/internal/payee.ts
1118
+ function resolvePayee(manifest, mode) {
1119
+ const override = manifest.pricing[mode]?.payee;
1120
+ return override ?? manifest.payee;
1121
+ }
1122
+
1123
+ // src/client/challenge.ts
1124
+ function isRecord(value) {
1125
+ return typeof value === "object" && value !== null;
1126
+ }
1127
+ function isPositiveIntegerString(value) {
1128
+ return typeof value === "string" && /^[1-9]\d*$/.test(value);
1129
+ }
1130
+ function checkAmount(amount, maxAmount) {
1131
+ if (!isPositiveIntegerString(amount)) {
1132
+ return new RouteDockPolicyRejectError("challenge_amount_invalid");
1133
+ }
1134
+ let max;
1135
+ try {
1136
+ max = nulthSdk.usdcToStroops(maxAmount);
1137
+ } catch {
1138
+ return new RouteDockPolicyRejectError("challenge_amount_invalid");
1139
+ }
1140
+ if (BigInt(amount) > max) {
1141
+ return new RouteDockPolicyRejectError("challenge_amount_exceeds_manifest");
1142
+ }
1143
+ return null;
1144
+ }
1145
+ function checkX402Accept(accept, manifest, network, maxAmount) {
1146
+ if (accept.network !== network) {
1147
+ return new RouteDockPolicyRejectError("challenge_network_mismatch");
1148
+ }
1149
+ if (accept.payTo !== resolvePayee(manifest, "x402")) {
1150
+ return new RouteDockPolicyRejectError("challenge_payee_mismatch");
1151
+ }
1152
+ if (accept.asset !== manifest.asset_contract) {
1153
+ return new RouteDockPolicyRejectError("challenge_asset_mismatch");
1154
+ }
1155
+ return checkAmount(accept.amount, maxAmount);
1156
+ }
1157
+ function filterX402Accepts(accepts, manifest, network, maxAmount) {
1158
+ return accepts.filter((accept) => checkX402Accept(accept, manifest, network, maxAmount) === null);
1159
+ }
1160
+ function checkChargeChallenge(request, manifest, network, maxAmount) {
1161
+ const methodDetails = request["methodDetails"];
1162
+ const rawNetwork = isRecord(methodDetails) ? methodDetails["network"] : void 0;
1163
+ const challengeNetwork = rawNetwork === void 0 ? "stellar:testnet" : rawNetwork;
1164
+ if (challengeNetwork !== network) {
1165
+ return new RouteDockPolicyRejectError("challenge_network_mismatch");
1166
+ }
1167
+ const recipient = request["recipient"];
1168
+ if (typeof recipient !== "string" || recipient !== resolvePayee(manifest, "mpp-charge")) {
1169
+ return new RouteDockPolicyRejectError("challenge_payee_mismatch");
1170
+ }
1171
+ const currency = request["currency"];
1172
+ if (typeof currency !== "string" || currency !== manifest.asset_contract) {
1173
+ return new RouteDockPolicyRejectError("challenge_asset_mismatch");
1174
+ }
1175
+ return checkAmount(request["amount"], maxAmount);
1176
+ }
1177
+
1178
+ // src/client/x402Client.ts
1179
+ var CAIP2 = {
1180
+ testnet: "stellar:testnet",
1181
+ mainnet: "stellar:pubnet"
1182
+ };
1183
+ var X402Client = class _X402Client {
1184
+ constructor(secretKeyOrSigner, network, retryPolicy) {
1185
+ this.network = network;
1186
+ this.retryPolicy = retryPolicy;
1187
+ const caip2 = CAIP2[network];
1188
+ this.signer = typeof secretKeyOrSigner === "string" ? stellar.createEd25519Signer(secretKeyOrSigner, caip2) : secretKeyOrSigner;
1189
+ const scheme = new client.ExactStellarScheme(this.signer);
1190
+ const core = new client$1.x402Client();
1191
+ core.register(caip2, scheme);
1192
+ this.httpClient = new client$1.x402HTTPClient(core);
1193
+ }
1194
+ network;
1195
+ retryPolicy;
1196
+ httpClient;
1197
+ signer;
1198
+ /** Replace signer (e.g. swap to Nulth ZK account payer before pay) */
1199
+ withSigner(signer) {
1200
+ return new _X402Client(signer, this.network, this.retryPolicy);
1201
+ }
1202
+ async pay(url, manifest) {
1203
+ const pricing = manifest.pricing.x402;
1204
+ if (!pricing) {
1205
+ throw new RouteDockManifestError("manifest.pricing.x402 missing");
1206
+ }
1207
+ if (!pricing.facilitator) {
1208
+ throw new RouteDockManifestError("manifest.pricing.x402.facilitator missing");
1209
+ }
1210
+ const caip2 = CAIP2[this.network];
1211
+ const probe = await withRetry(async () => {
1212
+ let init2;
1213
+ try {
1214
+ init2 = await fetch(url, { headers: { "X-Preferred-Mode": "x402" } });
1215
+ } catch (err) {
1216
+ throw wrapFetchError(err, "x402 initial request");
1217
+ }
1218
+ if (init2.status !== 402) {
1219
+ if (!init2.ok) {
1220
+ throw httpStatusToError(
1221
+ `x402 initial request failed: HTTP ${init2.status}`,
1222
+ init2.status,
1223
+ init2
1224
+ );
1225
+ }
1226
+ let data2;
1227
+ try {
1228
+ data2 = await init2.json();
1229
+ } catch {
1230
+ throw new RouteDockManifestError(
1231
+ `Failed to parse JSON from non-402 response (HTTP ${init2.status})`
1232
+ );
1233
+ }
1234
+ return { kind: "free", data: data2 };
1235
+ }
1236
+ return { kind: "payment-required", init: init2 };
1237
+ }, this.retryPolicy);
1238
+ if (probe.kind === "free") {
1239
+ return { data: probe.data, txHash: null, mode: "x402", amount: "0", timestamp: Date.now() };
1240
+ }
1241
+ const init = probe.init;
1242
+ const reqHeader = init.headers.get("X-Payment-Requirements");
1243
+ if (!reqHeader) {
1244
+ throw new RouteDockManifestError("402 response missing X-Payment-Requirements header");
1245
+ }
1246
+ let paymentRequired;
1247
+ try {
1248
+ paymentRequired = http.decodePaymentRequiredHeader(reqHeader);
1249
+ } catch (err) {
1250
+ throw new RouteDockManifestError("402 X-Payment-Requirements header is malformed", {
1251
+ cause: err
1252
+ });
1253
+ }
1254
+ const firstAccept = paymentRequired.accepts[0];
1255
+ if (!firstAccept) {
1256
+ throw new RouteDockManifestError("402 response carries no payment accepts");
1257
+ }
1258
+ const allowed = filterX402Accepts(paymentRequired.accepts, manifest, caip2, pricing.amount);
1259
+ if (allowed.length === 0) {
1260
+ throw checkX402Accept(firstAccept, manifest, caip2, pricing.amount);
1261
+ }
1262
+ let paymentPayload;
1263
+ try {
1264
+ paymentPayload = await this.httpClient.createPaymentPayload({
1265
+ ...paymentRequired,
1266
+ accepts: allowed
1267
+ });
1268
+ } catch (err) {
1269
+ throw new RouteDockSignatureError(`x402 payment signing failed: ${String(err)}`, {
1270
+ cause: err
1271
+ });
1272
+ }
1273
+ const paymentHeaders = this.httpClient.encodePaymentSignatureHeader(paymentPayload);
1274
+ const signedAmount = nulthSdk.stroopsToUsdc(BigInt(paymentPayload.accepted.amount));
1275
+ const settled = await withRetry(async () => {
1276
+ let response;
1277
+ try {
1278
+ response = await fetch(url, { headers: paymentHeaders });
1279
+ } catch (err) {
1280
+ throw wrapFetchError(err, "x402 settlement request");
1281
+ }
1282
+ if (!response.ok) {
1283
+ if (response.status >= 500 || response.status === 429 || response.status === 503) {
1284
+ throw httpStatusToError(
1285
+ `x402 payment failed: HTTP ${response.status}`,
1286
+ response.status,
1287
+ response
1288
+ );
1289
+ }
1290
+ throw new RouteDockManifestError(`x402 payment failed: HTTP ${response.status}`);
1291
+ }
1292
+ return response;
1293
+ }, this.retryPolicy);
1294
+ let txHash = null;
1295
+ const responseHeader = settled.headers.get("X-Payment-Response");
1296
+ if (responseHeader) {
1297
+ try {
1298
+ const settleResponse = http.decodePaymentResponseHeader(responseHeader);
319
1299
  txHash = settleResponse.transaction ?? null;
320
1300
  } catch {
321
1301
  }
322
1302
  }
323
- const data = await settled.json();
324
- return { data, txHash, mode: "x402", amount: pricing.amount, timestamp: Date.now() };
1303
+ let data;
1304
+ try {
1305
+ data = await settled.json();
1306
+ } catch {
1307
+ throw new RouteDockManifestError("Failed to parse JSON from settled response");
1308
+ }
1309
+ return { data, txHash, mode: "x402", amount: signedAmount, timestamp: Date.now() };
325
1310
  }
326
1311
  };
327
1312
  var MppChargeClient = class {
328
- constructor(keypair, network) {
1313
+ constructor(keypair, network, retryPolicy) {
329
1314
  this.keypair = keypair;
330
1315
  this.network = network;
1316
+ this.retryPolicy = retryPolicy;
331
1317
  }
332
1318
  keypair;
333
1319
  network;
1320
+ retryPolicy;
334
1321
  async pay(url, manifest) {
335
1322
  const pricing = manifest.pricing["mpp-charge"];
336
1323
  if (!pricing) {
337
1324
  throw new RouteDockManifestError("manifest.pricing.mpp-charge missing");
338
1325
  }
1326
+ const caip2 = this.network === "mainnet" ? "stellar:pubnet" : "stellar:testnet";
339
1327
  let txHash = null;
1328
+ let signedAmount;
1329
+ let credential;
340
1330
  const mppx = client$2.Mppx.create({
341
1331
  polyfill: false,
342
1332
  methods: [
@@ -349,28 +1339,108 @@ var MppChargeClient = class {
349
1339
  }
350
1340
  }
351
1341
  })
352
- ]
1342
+ ],
1343
+ onChallenge: async (challenge, { createCredential }) => {
1344
+ const request = challenge.request;
1345
+ const rejection = checkChargeChallenge(request, manifest, caip2, pricing.amount);
1346
+ if (rejection) throw rejection;
1347
+ const amount = request["amount"];
1348
+ if (typeof amount !== "string") {
1349
+ throw new RouteDockPolicyRejectError("challenge_amount_invalid");
1350
+ }
1351
+ signedAmount = nulthSdk.stroopsToUsdc(BigInt(amount));
1352
+ credential ??= await createCredential();
1353
+ return credential;
1354
+ }
353
1355
  });
354
- const response = await mppx.fetch(url);
355
- if (!response.ok) {
356
- throw new RouteDockManifestError(`MPP charge failed: HTTP ${response.status}`);
357
- }
358
- const data = await response.json();
359
- return { data, txHash, mode: "mpp-charge", amount: pricing.amount, timestamp: Date.now() };
1356
+ return withRetry(async () => {
1357
+ let response;
1358
+ try {
1359
+ response = credential ? await mppx.rawFetch(url, { headers: { Authorization: credential } }) : await mppx.fetch(url);
1360
+ } catch (err) {
1361
+ throw wrapMppError(err, "MPP charge request");
1362
+ }
1363
+ if (!response.ok) {
1364
+ if (response.status >= 500 || response.status === 429 || response.status === 503) {
1365
+ throw httpStatusToError(
1366
+ `MPP charge failed: HTTP ${response.status}`,
1367
+ response.status,
1368
+ response
1369
+ );
1370
+ }
1371
+ throw new RouteDockManifestError(`MPP charge failed: HTTP ${response.status}`);
1372
+ }
1373
+ let data;
1374
+ try {
1375
+ data = await response.json();
1376
+ } catch (cause) {
1377
+ throw new RouteDockManifestError(
1378
+ `Failed to parse JSON from response (HTTP ${response.status})`,
1379
+ { cause }
1380
+ );
1381
+ }
1382
+ return {
1383
+ data,
1384
+ txHash,
1385
+ mode: "mpp-charge",
1386
+ amount: signedAmount ?? pricing.amount,
1387
+ timestamp: Date.now()
1388
+ };
1389
+ }, this.retryPolicy);
360
1390
  }
361
1391
  };
362
1392
  var MIN_REFUND_WAITING_PERIOD = 17280;
1393
+ var STREAM_CLEANUP_TIMEOUT_MS = 3e3;
1394
+ var WS_CONNECTING = 0;
1395
+ var WS_OPEN = 1;
1396
+ function defaultWebSocketFactory(url, init, handlers) {
1397
+ const socket = new WebSocket(
1398
+ url,
1399
+ { headers: init.headers }
1400
+ );
1401
+ socket.onopen = () => handlers.onOpen();
1402
+ socket.onmessage = (event) => {
1403
+ const data = event.data;
1404
+ if (typeof data === "string") {
1405
+ handlers.onMessage(data);
1406
+ } else if (data instanceof ArrayBuffer) {
1407
+ handlers.onMessage(Buffer.from(data).toString("utf8"));
1408
+ } else {
1409
+ void data.arrayBuffer().then((buffer) => handlers.onMessage(Buffer.from(buffer).toString("utf8"))).catch(() => {
1410
+ });
1411
+ }
1412
+ };
1413
+ socket.onclose = (event) => handlers.onClose(event.code, event.reason);
1414
+ socket.onerror = () => handlers.onError();
1415
+ return socket;
1416
+ }
1417
+ function parseIntegerString(value) {
1418
+ return /^\d+$/.test(value) ? BigInt(value) : null;
1419
+ }
1420
+ function clientCumulativeStoreKey(networkId, channel) {
1421
+ return `stellar:channel:client:${networkId}:${channel}:cumulative`;
1422
+ }
1423
+ function resolveStoreNetworkId(network) {
1424
+ return network === mpp.STELLAR_PUBNET ? mpp.STELLAR_PUBNET : mpp.STELLAR_TESTNET;
1425
+ }
363
1426
  var MppSessionClient = class {
364
- constructor(keypair, network) {
1427
+ constructor(keypair, network, retryPolicy, webSocketFactory = defaultWebSocketFactory, logger = consoleLogger) {
365
1428
  this.keypair = keypair;
366
1429
  this.network = network;
1430
+ this.retryPolicy = retryPolicy;
1431
+ this.webSocketFactory = webSocketFactory;
1432
+ this.logger = logger;
367
1433
  }
368
1434
  keypair;
369
1435
  network;
370
- async openSession(url, manifest, commitmentSecret) {
371
- const pricing = manifest.pricing["mpp-session"];
1436
+ retryPolicy;
1437
+ webSocketFactory;
1438
+ logger;
1439
+ async openSession(url, manifest, commitmentSecret, options, onSpend) {
1440
+ const mode = options?.mode ?? "mpp-session";
1441
+ const pricing = manifest.pricing[mode];
372
1442
  if (!pricing) {
373
- throw new RouteDockManifestError("manifest.pricing.mpp-session missing");
1443
+ throw new RouteDockManifestError(`manifest.pricing.${mode} missing`);
374
1444
  }
375
1445
  const refundPeriod = pricing.refund_waiting_period_ledgers;
376
1446
  if (refundPeriod < MIN_REFUND_WAITING_PERIOD) {
@@ -379,166 +1449,1409 @@ var MppSessionClient = class {
379
1449
  );
380
1450
  }
381
1451
  const commitmentKey = stellarSdk.Keypair.fromSecret(commitmentSecret);
382
- const channelContract = pricing.channel_contract;
1452
+ const channelFactory = pricing.channel_factory;
383
1453
  const agentPublicKey = this.keypair.publicKey();
1454
+ const agentKeypair = this.keypair;
384
1455
  let currentCumulative = 0n;
385
1456
  let vouchersIssued = 0;
1457
+ let rateStroops;
1458
+ try {
1459
+ rateStroops = nulthSdk.usdcToStroops(pricing.rate);
1460
+ } catch (err) {
1461
+ throw new RouteDockManifestError(
1462
+ `manifest.pricing.${mode}.rate is not a valid USDC amount: "${pricing.rate}"`,
1463
+ { cause: err }
1464
+ );
1465
+ }
1466
+ const store = options?.store;
1467
+ let reservedCumulative = null;
1468
+ let storeSeed;
1469
+ const seedFromStore = (networkId, channel) => {
1470
+ storeSeed ??= Promise.resolve(
1471
+ store.get(clientCumulativeStoreKey(networkId, channel))
1472
+ ).then((stored) => {
1473
+ if (stored && typeof stored === "object" && "amount" in stored) {
1474
+ const raw = stored.amount;
1475
+ const amount = typeof raw === "string" ? parseIntegerString(raw) : null;
1476
+ if (amount === null) {
1477
+ throw new RouteDockChannelStateError(
1478
+ `Stored cumulative for channel ${channel} is not an integer string: ${JSON.stringify(raw)}`
1479
+ );
1480
+ }
1481
+ return amount;
1482
+ }
1483
+ return 0n;
1484
+ });
1485
+ return storeSeed;
1486
+ };
1487
+ const reserveNextCumulative = async (challenge) => {
1488
+ const request = challenge.request;
1489
+ const channelValue = request["channel"];
1490
+ if (typeof channelValue !== "string" || channelValue !== channelFactory) {
1491
+ throw new RouteDockChannelStateError(
1492
+ `Challenge names channel ${String(channelValue)}, but the manifest channel_factory is ${channelFactory}`
1493
+ );
1494
+ }
1495
+ const amountValue = request["amount"];
1496
+ const amount = typeof amountValue === "string" ? parseIntegerString(amountValue) : null;
1497
+ if (amount === null) {
1498
+ throw new RouteDockChannelStateError(
1499
+ `Challenge request.amount is not a base-10 integer string: ${JSON.stringify(amountValue)}`
1500
+ );
1501
+ }
1502
+ if (amount !== rateStroops) {
1503
+ throw new RouteDockChannelStateError(
1504
+ `Challenge request.amount ${amount} does not match the manifest rate ${rateStroops} stroops per voucher`
1505
+ );
1506
+ }
1507
+ const methodDetailsValue = request["methodDetails"];
1508
+ const methodDetails = methodDetailsValue !== null && typeof methodDetailsValue === "object" ? methodDetailsValue : void 0;
1509
+ let serverReported = 0n;
1510
+ if (methodDetails && "cumulativeAmount" in methodDetails) {
1511
+ const rawCumulative = methodDetails["cumulativeAmount"];
1512
+ const parsed = typeof rawCumulative === "string" ? parseIntegerString(rawCumulative) : null;
1513
+ if (parsed === null) {
1514
+ throw new RouteDockChannelStateError(
1515
+ `Challenge methodDetails.cumulativeAmount is not a base-10 integer string: ${JSON.stringify(rawCumulative)}`
1516
+ );
1517
+ }
1518
+ serverReported = parsed;
1519
+ }
1520
+ let baseline = reservedCumulative;
1521
+ if (baseline === null) {
1522
+ if (store) {
1523
+ const challengedNetwork = methodDetails?.["network"];
1524
+ const seeded = await seedFromStore(
1525
+ resolveStoreNetworkId(
1526
+ typeof challengedNetwork === "string" ? challengedNetwork : void 0
1527
+ ),
1528
+ channelValue
1529
+ );
1530
+ baseline = reservedCumulative ?? seeded;
1531
+ } else if (serverReported === 0n) {
1532
+ baseline = 0n;
1533
+ } else {
1534
+ throw new RouteDockChannelStateError(
1535
+ `Challenge reports cumulative ${serverReported} for a channel this client has no baseline for. Pass a \`store\` in SessionOptions so the signed cumulative survives restarts, or close the channel before reusing it.`
1536
+ );
1537
+ }
1538
+ }
1539
+ if (serverReported > baseline) {
1540
+ throw new RouteDockChannelStateError(
1541
+ `Challenge reports cumulative ${serverReported}, above the locally reserved baseline ${baseline}`
1542
+ );
1543
+ }
1544
+ const next = baseline + rateStroops;
1545
+ reservedCumulative = next;
1546
+ return next;
1547
+ };
1548
+ const releaseReservation = (reserved) => {
1549
+ if (reservedCumulative === reserved) {
1550
+ reservedCumulative = reserved - rateStroops;
1551
+ }
1552
+ };
1553
+ const createGuardedCredential = async (challenge, create) => {
1554
+ const next = await reserveNextCumulative(challenge);
1555
+ try {
1556
+ return await create(next.toString());
1557
+ } catch (err) {
1558
+ releaseReservation(next);
1559
+ throw err;
1560
+ }
1561
+ };
1562
+ const streamWs = (u, m, createCredential, onSigned) => this.streamWebSocket(u, m, createCredential, onSigned);
386
1563
  const mppx = client$2.Mppx.create({
387
1564
  polyfill: false,
388
1565
  methods: [
389
1566
  client$4.stellar.channel({
390
1567
  commitmentKey,
391
1568
  sourceAccount: this.keypair.publicKey(),
1569
+ ...store ? { store } : {},
392
1570
  onProgress(event) {
393
1571
  if (event.type === "signed") {
394
1572
  currentCumulative = BigInt(event.cumulativeAmount);
395
1573
  }
396
1574
  }
397
1575
  })
398
- ]
1576
+ ],
1577
+ // mppx runs onChallenge on the HTTP path only (createCredential skips it),
1578
+ // so the WebSocket path runs the same guard inside streamWebSocket.
1579
+ onChallenge: (challenge, helpers) => createGuardedCredential(
1580
+ challenge,
1581
+ (cumulativeAmount) => helpers.createCredential({ cumulativeAmount })
1582
+ )
399
1583
  });
400
- const openTxHash = channelContract;
1584
+ const retryPolicy = this.retryPolicy;
1585
+ const maxDurationMs = options?.maxDurationMs ?? DEFAULT_MAX_SESSION_DURATION_MS;
1586
+ const listeners = /* @__PURE__ */ new Map();
1587
+ let timeoutId;
1588
+ let closed = false;
1589
+ const emit = (event, payload) => {
1590
+ const set = listeners.get(event);
1591
+ if (!set) return;
1592
+ for (const listener of set) {
1593
+ try {
1594
+ const returned = listener(payload);
1595
+ if (returned && typeof returned.then === "function") {
1596
+ void Promise.resolve(returned).catch(() => {
1597
+ });
1598
+ }
1599
+ } catch {
1600
+ }
1601
+ }
1602
+ };
1603
+ const clearSessionTimer = () => {
1604
+ if (timeoutId !== void 0) {
1605
+ clearTimeout(timeoutId);
1606
+ timeoutId = void 0;
1607
+ }
1608
+ };
1609
+ const network = this.network;
401
1610
  const handle = {
402
- channelId: channelContract,
403
- openTxHash,
404
- async *stream() {
405
- while (true) {
406
- let resp = null;
407
- for (let attempt = 0; attempt < 3; attempt++) {
408
- try {
409
- resp = await mppx.fetch(url);
410
- if (resp.ok) break;
411
- resp = null;
412
- } catch {
413
- if (attempt === 2) throw new RouteDockSessionError("Voucher request failed after 3 retries");
414
- await new Promise((r) => setTimeout(r, 1e3 * (attempt + 1)));
1611
+ channelId: channelFactory,
1612
+ // The channel is pre-deployed and funded before the agent runs, so the
1613
+ // client never issues the channel-open transaction and has no hash for
1614
+ // it. Report null rather than the contract address (a non-transaction
1615
+ // identifier that produces broken explorer links downstream).
1616
+ openTxHash: null,
1617
+ /**
1618
+ * Live session snapshot. vouchersIssued increments once per signed voucher
1619
+ * and currentCumulative is updated by the channel client's onProgress when
1620
+ * a voucher is signed, so a stats() call immediately after a yield always
1621
+ * reflects everything consumed so far.
1622
+ */
1623
+ stats() {
1624
+ return {
1625
+ vouchersIssued,
1626
+ // Same conversion as SessionCloseResult.totalPaid so a per-session
1627
+ // sub-cap can be compared against stats().currentCumulative directly.
1628
+ currentCumulative: (Number(currentCumulative) / 1e7).toFixed(7),
1629
+ channelId: channelFactory,
1630
+ openTxHash: null
1631
+ };
1632
+ },
1633
+ async *stream(options2) {
1634
+ const checkSpend = () => {
1635
+ if (!onSpend) return Promise.resolve();
1636
+ return onSpend(pricing.rate);
1637
+ };
1638
+ if (mode === "mpp-session-ws") {
1639
+ await checkSpend();
1640
+ const onSigned = () => {
1641
+ vouchersIssued++;
1642
+ };
1643
+ for await (const item of streamWs(url, mppx, createGuardedCredential, onSigned)) {
1644
+ yield item;
1645
+ }
1646
+ return;
1647
+ }
1648
+ const concurrency = Math.max(1, options2?.concurrency ?? 1);
1649
+ const assertOpen = () => {
1650
+ if (closed) {
1651
+ throw new RouteDockChannelStateError("session closed");
1652
+ }
1653
+ };
1654
+ const abortController = new AbortController();
1655
+ const doFetch = () => withRetry(async () => {
1656
+ let resp;
1657
+ try {
1658
+ resp = await mppx.fetch(url, { signal: abortController.signal });
1659
+ } catch (err) {
1660
+ if (abortController.signal.aborted) {
1661
+ throw err;
1662
+ }
1663
+ throw wrapMppError(err, "Voucher request");
1664
+ }
1665
+ if (!resp.ok) {
1666
+ if (resp.status >= 500 || resp.status === 429 || resp.status === 503) {
1667
+ throw httpStatusToError(
1668
+ `Voucher request failed: HTTP ${resp.status}`,
1669
+ resp.status,
1670
+ resp
1671
+ );
415
1672
  }
1673
+ throw new RouteDockChannelStateError(
1674
+ `Voucher request failed: HTTP ${resp.status}`
1675
+ );
1676
+ }
1677
+ try {
1678
+ return await resp.json();
1679
+ } catch (cause) {
1680
+ throw new RouteDockChannelStateError(
1681
+ `Voucher response was not valid JSON (HTTP ${resp.status})`,
1682
+ { cause }
1683
+ );
416
1684
  }
417
- if (!resp || !resp.ok) {
418
- throw new RouteDockSessionError(`Voucher request failed: HTTP ${resp?.status ?? "unknown"}`);
1685
+ }, retryPolicy);
1686
+ if (concurrency === 1) {
1687
+ try {
1688
+ while (true) {
1689
+ assertOpen();
1690
+ await checkSpend();
1691
+ const data = await doFetch();
1692
+ vouchersIssued++;
1693
+ yield data;
1694
+ }
1695
+ } finally {
1696
+ abortController.abort();
1697
+ }
1698
+ } else {
1699
+ const queue = [];
1700
+ try {
1701
+ for (let i = 0; i < concurrency; i++) {
1702
+ assertOpen();
1703
+ await checkSpend();
1704
+ const p = doFetch();
1705
+ p.catch(() => {
1706
+ });
1707
+ queue.push(p);
1708
+ }
1709
+ while (true) {
1710
+ assertOpen();
1711
+ const data = await queue.shift();
1712
+ await checkSpend();
1713
+ const p = doFetch();
1714
+ p.catch(() => {
1715
+ });
1716
+ queue.push(p);
1717
+ vouchersIssued++;
1718
+ yield data;
1719
+ }
1720
+ } finally {
1721
+ abortController.abort();
1722
+ let timer;
1723
+ try {
1724
+ await Promise.race([
1725
+ Promise.allSettled(queue),
1726
+ new Promise((resolve) => {
1727
+ timer = setTimeout(resolve, STREAM_CLEANUP_TIMEOUT_MS);
1728
+ timer.unref?.();
1729
+ })
1730
+ ]);
1731
+ } finally {
1732
+ if (timer) {
1733
+ clearTimeout(timer);
1734
+ }
1735
+ }
1736
+ queue.length = 0;
419
1737
  }
420
- vouchersIssued++;
421
- yield await resp.json();
422
1738
  }
423
1739
  },
424
1740
  async close() {
1741
+ clearSessionTimer();
1742
+ closed = true;
425
1743
  const { rpc: rpcMod, Contract, nativeToScVal, TransactionBuilder, BASE_FEE } = await import('@stellar/stellar-sdk');
426
- const rpcUrl = "https://soroban-testnet.stellar.org";
1744
+ const rpcUrl = network === "testnet" ? "https://soroban-testnet.stellar.org" : "https://soroban.stellar.org";
427
1745
  const server = new rpcMod.Server(rpcUrl);
428
- const contract = new Contract(channelContract);
429
- const passphrase = "Test SDF Network ; September 2015";
430
- const account = await server.getAccount(agentPublicKey);
431
- const simTx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: passphrase }).addOperation(contract.call("prepare_commitment", nativeToScVal(currentCumulative, { type: "i128" }))).setTimeout(30).build();
432
- const simResult = await server.simulateTransaction(simTx);
1746
+ const contract = new Contract(channelFactory);
1747
+ const passphrase = network === "mainnet" ? stellarSdk.Networks.PUBLIC : stellarSdk.Networks.TESTNET;
1748
+ const account = await withRetry(async () => {
1749
+ try {
1750
+ return await server.getAccount(agentPublicKey);
1751
+ } catch (err) {
1752
+ throw wrapFetchError(err, "Horizon getAccount");
1753
+ }
1754
+ }, retryPolicy);
1755
+ const simResult = await withRetry(async () => {
1756
+ try {
1757
+ const simTx = new TransactionBuilder(account, {
1758
+ fee: BASE_FEE,
1759
+ networkPassphrase: passphrase
1760
+ }).addOperation(
1761
+ contract.call(
1762
+ "prepare_commitment",
1763
+ nativeToScVal(currentCumulative, { type: "i128" })
1764
+ )
1765
+ ).setTimeout(30).build();
1766
+ return await server.simulateTransaction(simTx);
1767
+ } catch (err) {
1768
+ throw wrapFetchError(err, "prepare_commitment RPC");
1769
+ }
1770
+ }, retryPolicy);
433
1771
  if (rpcMod.Api.isSimulationError(simResult)) {
434
- throw new RouteDockSessionError(`prepare_commitment simulation failed: ${simResult.error}`);
1772
+ throw new RouteDockChannelStateError(
1773
+ `prepare_commitment simulation failed: ${simResult.error}`
1774
+ );
435
1775
  }
436
1776
  const commitmentBytes = simResult.result?.retval?.bytes();
437
- if (!commitmentBytes) throw new RouteDockSessionError("prepare_commitment returned no bytes");
438
- const signature = commitmentKey.sign(Buffer.from(commitmentBytes));
439
- const closeResp = await fetch(url, {
440
- method: "DELETE",
441
- headers: { "Content-Type": "application/json" },
442
- body: JSON.stringify({
443
- amount: currentCumulative.toString(),
444
- signature: Buffer.from(signature).toString("hex")
445
- })
446
- });
447
- if (!closeResp.ok) {
448
- throw new RouteDockSessionError(`Channel close failed: HTTP ${closeResp.status}`);
1777
+ if (!commitmentBytes) {
1778
+ throw new RouteDockChannelStateError("prepare_commitment returned no bytes");
449
1779
  }
450
- const closeData = await closeResp.json();
451
- const closeTxHash = closeData.closeTxHash ?? null;
452
- if (!closeTxHash) {
453
- throw new RouteDockSessionError("Channel close response missing closeTxHash");
1780
+ let signature;
1781
+ try {
1782
+ signature = commitmentKey.sign(Buffer.from(commitmentBytes));
1783
+ } catch (err) {
1784
+ throw new RouteDockSignatureError("Channel close commitment signing failed", {
1785
+ cause: err
1786
+ });
454
1787
  }
1788
+ const closeData = await withRetry(async () => {
1789
+ let closeResp;
1790
+ try {
1791
+ closeResp = await fetch(url, {
1792
+ method: "DELETE",
1793
+ headers: { "Content-Type": "application/json" },
1794
+ body: JSON.stringify({
1795
+ amount: currentCumulative.toString(),
1796
+ signature: Buffer.from(signature).toString("hex")
1797
+ })
1798
+ });
1799
+ } catch (err) {
1800
+ throw wrapFetchError(err, "Channel close request");
1801
+ }
1802
+ if (!closeResp.ok) {
1803
+ if (closeResp.status >= 500 || closeResp.status === 429 || closeResp.status === 503) {
1804
+ throw httpStatusToError(
1805
+ `Channel close failed: HTTP ${closeResp.status}`,
1806
+ closeResp.status,
1807
+ closeResp
1808
+ );
1809
+ }
1810
+ throw new RouteDockChannelStateError(
1811
+ `Channel close failed: HTTP ${closeResp.status}`
1812
+ );
1813
+ }
1814
+ let body;
1815
+ try {
1816
+ body = await closeResp.json();
1817
+ } catch (cause) {
1818
+ throw new RouteDockChannelStateError(
1819
+ `Channel close response was not valid JSON (HTTP ${closeResp.status})`,
1820
+ { cause }
1821
+ );
1822
+ }
1823
+ const closeTxHash = body.closeTxHash ?? null;
1824
+ if (!closeTxHash) {
1825
+ throw new RouteDockChannelStateError(
1826
+ "Channel close response missing closeTxHash"
1827
+ );
1828
+ }
1829
+ return { closeTxHash, body };
1830
+ }, retryPolicy);
455
1831
  const totalPaid = (Number(currentCumulative) / 1e7).toFixed(7);
456
- return { closeTxHash, totalPaid, vouchersIssued };
1832
+ return {
1833
+ closeTxHash: closeData.closeTxHash,
1834
+ totalPaid,
1835
+ vouchersIssued
1836
+ };
1837
+ },
1838
+ async requestRefund() {
1839
+ const { rpc: rpcMod, Contract, TransactionBuilder, BASE_FEE } = await import('@stellar/stellar-sdk');
1840
+ const rpcUrl = network === "testnet" ? "https://soroban-testnet.stellar.org" : "https://soroban.stellar.org";
1841
+ const server = new rpcMod.Server(rpcUrl);
1842
+ const contract = new Contract(channelFactory);
1843
+ const passphrase = network === "mainnet" ? stellarSdk.Networks.PUBLIC : stellarSdk.Networks.TESTNET;
1844
+ try {
1845
+ const account = await server.getAccount(agentPublicKey);
1846
+ const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: passphrase }).addOperation(contract.call("request_refund")).setTimeout(30).build();
1847
+ const simResult = await server.simulateTransaction(tx);
1848
+ if (rpcMod.Api.isSimulationError(simResult)) {
1849
+ throw new RouteDockDisputeError(`request_refund simulation failed: ${simResult.error}`);
1850
+ }
1851
+ const preparedTx = await server.prepareTransaction(tx);
1852
+ preparedTx.sign(agentKeypair);
1853
+ const result = await server.sendTransaction(preparedTx);
1854
+ if (result.status === "ERROR") {
1855
+ const errDetail = result.errorResult ? JSON.stringify(result.errorResult) : "status ERROR";
1856
+ throw new RouteDockDisputeError(`Refund request transaction failed: ${errDetail}`);
1857
+ }
1858
+ if (!result.hash) {
1859
+ throw new RouteDockDisputeError("Refund request transaction not sent");
1860
+ }
1861
+ return result.hash;
1862
+ } catch (err) {
1863
+ if (err instanceof RouteDockDisputeError) throw err;
1864
+ throw new RouteDockDisputeError(`Failed to request refund: ${err instanceof Error ? err.message : String(err)}`);
1865
+ }
1866
+ },
1867
+ async settleWithLatestVoucher() {
1868
+ const { rpc: rpcMod, Contract, nativeToScVal, TransactionBuilder, BASE_FEE } = await import('@stellar/stellar-sdk');
1869
+ const rpcUrl = network === "testnet" ? "https://soroban-testnet.stellar.org" : "https://soroban.stellar.org";
1870
+ const server = new rpcMod.Server(rpcUrl);
1871
+ const contract = new Contract(channelFactory);
1872
+ const passphrase = network === "mainnet" ? stellarSdk.Networks.PUBLIC : stellarSdk.Networks.TESTNET;
1873
+ try {
1874
+ const account = await server.getAccount(agentPublicKey);
1875
+ const simTx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: passphrase }).addOperation(contract.call("prepare_commitment", nativeToScVal(currentCumulative, { type: "i128" }))).setTimeout(30).build();
1876
+ const simResult = await server.simulateTransaction(simTx);
1877
+ if (rpcMod.Api.isSimulationError(simResult)) {
1878
+ throw new RouteDockDisputeError(`prepare_commitment simulation failed: ${simResult.error}`);
1879
+ }
1880
+ const commitmentBytes = simResult.result?.retval?.bytes();
1881
+ if (!commitmentBytes) throw new RouteDockDisputeError("prepare_commitment returned no bytes");
1882
+ const signature = commitmentKey.sign(Buffer.from(commitmentBytes));
1883
+ const settleAccount = await server.getAccount(agentPublicKey);
1884
+ const settleTx = new TransactionBuilder(settleAccount, { fee: BASE_FEE, networkPassphrase: passphrase }).addOperation(
1885
+ contract.call(
1886
+ "settle_with_signature",
1887
+ nativeToScVal(currentCumulative, { type: "i128" }),
1888
+ nativeToScVal(Buffer.from(signature))
1889
+ )
1890
+ ).setTimeout(30).build();
1891
+ const preparedSettleTx = await server.prepareTransaction(settleTx);
1892
+ preparedSettleTx.sign(agentKeypair);
1893
+ const settleResult = await server.sendTransaction(preparedSettleTx);
1894
+ if (settleResult.status === "ERROR") {
1895
+ const errDetail = settleResult.errorResult ? JSON.stringify(settleResult.errorResult) : "status ERROR";
1896
+ throw new RouteDockDisputeError(`Settlement transaction failed: ${errDetail}`);
1897
+ }
1898
+ if (!settleResult.hash) {
1899
+ throw new RouteDockDisputeError("Settlement transaction not sent");
1900
+ }
1901
+ return settleResult.hash;
1902
+ } catch (err) {
1903
+ if (err instanceof RouteDockDisputeError) throw err;
1904
+ throw new RouteDockDisputeError(`Failed to settle with latest voucher: ${err instanceof Error ? err.message : String(err)}`);
1905
+ }
1906
+ },
1907
+ async getDisputeStatus() {
1908
+ const { rpc: rpcMod, Contract, TransactionBuilder, BASE_FEE } = await import('@stellar/stellar-sdk');
1909
+ const rpcUrl = network === "testnet" ? "https://soroban-testnet.stellar.org" : "https://soroban.stellar.org";
1910
+ const server = new rpcMod.Server(rpcUrl);
1911
+ const contract = new Contract(channelFactory);
1912
+ const passphrase = network === "mainnet" ? stellarSdk.Networks.PUBLIC : stellarSdk.Networks.TESTNET;
1913
+ try {
1914
+ const account = await server.getAccount(agentPublicKey);
1915
+ const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: passphrase }).addOperation(contract.call("get_channel_state")).setTimeout(30).build();
1916
+ const simResult = await server.simulateTransaction(tx);
1917
+ if (rpcMod.Api.isSimulationError(simResult)) {
1918
+ throw new RouteDockChannelStateError(`Failed to query channel state: ${simResult.error}`);
1919
+ }
1920
+ const retval = simResult.result?.retval;
1921
+ if (!retval) {
1922
+ throw new RouteDockChannelStateError("No channel state returned");
1923
+ }
1924
+ if (typeof retval === "object" && retval !== null) {
1925
+ const status = retval.status;
1926
+ if (status === "open") return "open";
1927
+ if (status === "in_refund_window") return "in-refund-window";
1928
+ if (status === "refundable") return "refundable";
1929
+ if (status === "settled") return "settled";
1930
+ }
1931
+ return "open";
1932
+ } catch (err) {
1933
+ if (err instanceof RouteDockChannelStateError) throw err;
1934
+ throw new RouteDockChannelStateError(`Failed to get dispute status: ${err instanceof Error ? err.message : String(err)}`);
1935
+ }
1936
+ },
1937
+ on(event, listener) {
1938
+ let set = listeners.get(event);
1939
+ if (!set) {
1940
+ set = /* @__PURE__ */ new Set();
1941
+ listeners.set(event, set);
1942
+ }
1943
+ const stored = listener;
1944
+ set.add(stored);
1945
+ return () => {
1946
+ set?.delete(stored);
1947
+ };
457
1948
  }
458
1949
  };
1950
+ if (Number.isFinite(maxDurationMs) && maxDurationMs > 0) {
1951
+ timeoutId = setTimeout(() => {
1952
+ if (closed) return;
1953
+ emit("session:timeout", { maxDurationMs });
1954
+ void handle.close().catch((error) => {
1955
+ emit("session:close-failed", { maxDurationMs, error });
1956
+ this.logger(
1957
+ "warn",
1958
+ `RouteDock: maxDuration auto-close failed after ${maxDurationMs}ms \u2014 the channel may still hold collateral; retry close() or call requestRefund().`,
1959
+ { error }
1960
+ );
1961
+ });
1962
+ }, maxDurationMs);
1963
+ timeoutId.unref?.();
1964
+ }
459
1965
  return handle;
460
1966
  }
1967
+ /**
1968
+ * mpp-session-ws streaming transport.
1969
+ *
1970
+ * Mirrors the issue's three-step sequence:
1971
+ * 1. open the channel — probe the provider URL over HTTP;
1972
+ * 2. negotiate the voucher — sign the mppx 402 challenge into a credential;
1973
+ * 3. upgrade the HTTP connection to WebSocket — hand the signed voucher to
1974
+ * the provider as the Authorization header of the WebSocket handshake.
1975
+ *
1976
+ * Each server frame is yielded (JSON frames parsed; raw strings yielded
1977
+ * as-is). The stream ends when the server closes the socket with a normal
1978
+ * close code (1000/1001); abnormal closes and connection failures surface as
1979
+ * RouteDockChannelStateError.
1980
+ */
1981
+ async *streamWebSocket(url, mppx$1, createCredential, onSigned) {
1982
+ const request = { method: "GET" };
1983
+ let probe;
1984
+ try {
1985
+ probe = await mppx$1.rawFetch(url, request);
1986
+ } catch (err) {
1987
+ throw wrapFetchError(err, "Voucher request");
1988
+ }
1989
+ if (probe.status !== 402) {
1990
+ if (probe.status >= 500 || probe.status === 429 || probe.status === 503) {
1991
+ throw httpStatusToError(
1992
+ `Voucher request failed: HTTP ${probe.status}`,
1993
+ probe.status,
1994
+ probe
1995
+ );
1996
+ }
1997
+ throw new RouteDockChannelStateError(
1998
+ `Voucher request failed: expected HTTP 402 challenge, got HTTP ${probe.status}`
1999
+ );
2000
+ }
2001
+ let credential;
2002
+ try {
2003
+ credential = await createCredential(
2004
+ mppx.Challenge.fromResponse(probe),
2005
+ (cumulativeAmount) => mppx$1.createCredential(probe, { cumulativeAmount })
2006
+ );
2007
+ onSigned?.();
2008
+ } catch (err) {
2009
+ throw wrapMppError(err, "Voucher credential");
2010
+ }
2011
+ const wsUrl = url.replace(/^http/, "ws");
2012
+ const queue = [];
2013
+ const waiters = [];
2014
+ const drain = () => {
2015
+ while (queue.length > 0 && waiters.length > 0) {
2016
+ const waiter = waiters.shift();
2017
+ waiter(queue.shift());
2018
+ }
2019
+ };
2020
+ const nextEvent = () => queue.length > 0 ? Promise.resolve(queue.shift()) : new Promise((resolve) => {
2021
+ waiters.push(resolve);
2022
+ });
2023
+ const socket = this.webSocketFactory(
2024
+ wsUrl,
2025
+ { headers: { authorization: credential } },
2026
+ {
2027
+ onOpen: () => {
2028
+ queue.push({ type: "open" });
2029
+ drain();
2030
+ },
2031
+ onMessage: (data) => {
2032
+ queue.push({ type: "message", data });
2033
+ drain();
2034
+ },
2035
+ onClose: (code, reason) => {
2036
+ queue.push({ type: "close", code, reason });
2037
+ drain();
2038
+ },
2039
+ onError: () => {
2040
+ queue.push({ type: "error" });
2041
+ drain();
2042
+ }
2043
+ }
2044
+ );
2045
+ try {
2046
+ for (; ; ) {
2047
+ const event = await nextEvent();
2048
+ if (event.type === "open") break;
2049
+ if (event.type === "error") {
2050
+ throw new RouteDockChannelStateError(
2051
+ "WebSocket upgrade failed: connection error"
2052
+ );
2053
+ }
2054
+ if (event.type === "close") {
2055
+ throw new RouteDockChannelStateError(
2056
+ `WebSocket upgrade failed: server closed the connection before upgrading (code ${event.code})`
2057
+ );
2058
+ }
2059
+ }
2060
+ for (; ; ) {
2061
+ const event = await nextEvent();
2062
+ if (event.type === "message") {
2063
+ let parsed = event.data;
2064
+ try {
2065
+ parsed = JSON.parse(event.data);
2066
+ } catch {
2067
+ }
2068
+ yield parsed;
2069
+ continue;
2070
+ }
2071
+ if (event.type === "error") {
2072
+ throw new RouteDockChannelStateError("WebSocket connection error");
2073
+ }
2074
+ if (event.type === "open") continue;
2075
+ if (event.code === 1e3 || event.code === 1001) {
2076
+ return;
2077
+ }
2078
+ throw new RouteDockChannelStateError(
2079
+ `WebSocket stream ended abnormally (code ${event.code}${event.reason ? `: ${event.reason}` : ""})`
2080
+ );
2081
+ }
2082
+ } finally {
2083
+ if (socket.readyState === WS_CONNECTING || socket.readyState === WS_OPEN) {
2084
+ socket.close(1e3, "stream ended");
2085
+ }
2086
+ }
2087
+ }
2088
+ };
2089
+ var NulthPolicyError = class extends Error {
2090
+ code;
2091
+ constructor(code, message) {
2092
+ super(message);
2093
+ this.name = "NulthPolicyError";
2094
+ this.code = code;
2095
+ }
2096
+ };
2097
+ function sha256Hex(data) {
2098
+ const buf = typeof data === "string" ? Buffer.from(data, "utf8") : data;
2099
+ return crypto.createHash("sha256").update(buf).digest("hex");
2100
+ }
2101
+ function commitDailyCap(dailyCapStroops, witnessSecret) {
2102
+ return sha256Hex(`${witnessSecret}:cap:${dailyCapStroops.toString()}`);
2103
+ }
2104
+ function commitAllowlist(payees, witnessSecret) {
2105
+ const sorted = [...payees].sort().join(",");
2106
+ return sha256Hex(`${witnessSecret}:allowlist:${sorted}`);
2107
+ }
2108
+ function hashPayee(payee) {
2109
+ return sha256Hex(`payee:${payee}`);
2110
+ }
2111
+ function dayBucketFromLedger(ledgerSequence) {
2112
+ return Math.floor(ledgerSequence / 17280);
2113
+ }
2114
+ function authDigestFromEntry(authEntryBase64) {
2115
+ const entryHash = stellarSdk.hash(Buffer.from(authEntryBase64, "base64"));
2116
+ return sha256Hex(entryHash);
2117
+ }
2118
+ function assertAuthEntryMatchesContext(authEntry, from, ctx) {
2119
+ let preimage;
2120
+ try {
2121
+ preimage = stellarSdk.xdr.HashIdPreimage.fromXDR(authEntry, "base64");
2122
+ } catch {
2123
+ throw new NulthPolicyError("auth_entry_mismatch", "authEntry does not decode as a HashIdPreimage");
2124
+ }
2125
+ if (preimage.switch() !== stellarSdk.xdr.EnvelopeType.envelopeTypeSorobanAuthorization()) {
2126
+ throw new NulthPolicyError(
2127
+ "auth_entry_mismatch",
2128
+ "authEntry is not a Soroban authorization preimage"
2129
+ );
2130
+ }
2131
+ const inv = preimage.sorobanAuthorization().invocation();
2132
+ if (inv.subInvocations().length !== 0) {
2133
+ throw new NulthPolicyError("auth_entry_mismatch", "authEntry has unexpected sub-invocations");
2134
+ }
2135
+ if (inv.function().switch() !== stellarSdk.xdr.SorobanAuthorizedFunctionType.sorobanAuthorizedFunctionTypeContractFn()) {
2136
+ throw new NulthPolicyError("auth_entry_mismatch", "authEntry does not invoke a contract function");
2137
+ }
2138
+ const fn = inv.function().contractFn();
2139
+ const contractAddress = stellarSdk.Address.fromScAddress(fn.contractAddress()).toString();
2140
+ if (contractAddress !== ctx.assetContract) {
2141
+ throw new NulthPolicyError(
2142
+ "auth_entry_mismatch",
2143
+ `authEntry contract ${contractAddress} does not match assetContract ${ctx.assetContract}`
2144
+ );
2145
+ }
2146
+ const functionName = fn.functionName().toString();
2147
+ if (functionName !== "transfer") {
2148
+ throw new NulthPolicyError(
2149
+ "auth_entry_mismatch",
2150
+ `authEntry function ${functionName} does not match expected transfer`
2151
+ );
2152
+ }
2153
+ const args = fn.args();
2154
+ if (args.length !== 3) {
2155
+ throw new NulthPolicyError("auth_entry_mismatch", `authEntry transfer has ${args.length} args, expected 3`);
2156
+ }
2157
+ const entryFrom = stellarSdk.scValToNative(args[0]);
2158
+ if (entryFrom !== from) {
2159
+ throw new NulthPolicyError(
2160
+ "auth_entry_mismatch",
2161
+ `authEntry from ${entryFrom} does not match nulthAccount ${from}`
2162
+ );
2163
+ }
2164
+ const entryTo = stellarSdk.scValToNative(args[1]);
2165
+ if (entryTo !== ctx.payee) {
2166
+ throw new NulthPolicyError(
2167
+ "auth_entry_mismatch",
2168
+ `authEntry to ${entryTo} does not match paymentContext.payee ${ctx.payee}`
2169
+ );
2170
+ }
2171
+ const entryAmount = stellarSdk.scValToNative(args[2]);
2172
+ if (entryAmount !== ctx.amountStroops) {
2173
+ throw new NulthPolicyError(
2174
+ "auth_entry_mismatch",
2175
+ `authEntry amount ${entryAmount} does not match paymentContext.amountStroops ${ctx.amountStroops}`
2176
+ );
2177
+ }
2178
+ }
2179
+ function insecureMockProof(preimage) {
2180
+ return crypto.createHash("sha512").update(`nulth:${preimage}`).digest("base64");
2181
+ }
2182
+ function encodeAuthSignature(proof) {
2183
+ const payload = { nulth: "zk-v1", proof };
2184
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
2185
+ }
2186
+ function usdcToStroops2(amount) {
2187
+ const [whole = "0", frac = ""] = amount.split(".");
2188
+ const padded = (frac + "0000000").slice(0, 7);
2189
+ return BigInt(whole) * 10000000n + BigInt(padded);
2190
+ }
2191
+ var NulthClient = class {
2192
+ constructor(config) {
2193
+ this.config = config;
2194
+ this.policy = { ...config.policy };
2195
+ this.prover = config.prover ?? "mock";
2196
+ if (this.prover !== "mock") {
2197
+ throw new RouteDockManifestError(
2198
+ `NulthClient: unknown prover backend ${String(config.prover)}; only 'mock' is implemented`
2199
+ );
2200
+ }
2201
+ if (config.network !== "testnet") {
2202
+ throw new RouteDockManifestError(
2203
+ `NulthClient cannot use the insecure mock prover on mainnet; a production prover is required (network must be 'testnet', got ${String(config.network)})`
2204
+ );
2205
+ }
2206
+ resolveLogger(config.logger)(
2207
+ "warn",
2208
+ "NulthClient is using the insecure mock prover; proofs are not cryptographically sound"
2209
+ );
2210
+ }
2211
+ config;
2212
+ policy;
2213
+ prover;
2214
+ get proverBackend() {
2215
+ return this.prover;
2216
+ }
2217
+ get nulthAccount() {
2218
+ return this.config.nulthAccount;
2219
+ }
2220
+ get allowlistCommitment() {
2221
+ return this.policy.allowlistCommitment;
2222
+ }
2223
+ get capCommitment() {
2224
+ return commitDailyCap(this.policy.dailyCapStroops, this.policy.witnessSecret);
2225
+ }
2226
+ buildPaymentAuthProof(context) {
2227
+ this.enforcePolicy(context);
2228
+ const bucket = dayBucketFromLedger(context.ledgerSequence);
2229
+ if (bucket !== this.policy.dayBucket) {
2230
+ this.policy.dayBucket = bucket;
2231
+ this.policy.dailySpendStroops = 0n;
2232
+ }
2233
+ const authDigest = authDigestFromEntry(context.authEntry);
2234
+ const capCommitment = this.capCommitment;
2235
+ const payeeHash = hashPayee(context.payee);
2236
+ const preimage = [
2237
+ authDigest,
2238
+ this.policy.allowlistCommitment,
2239
+ capCommitment,
2240
+ payeeHash,
2241
+ context.amountStroops.toString(),
2242
+ bucket.toString(),
2243
+ this.config.nulthAccount
2244
+ ].join("|");
2245
+ const proof = {
2246
+ version: 1,
2247
+ proof: insecureMockProof(preimage),
2248
+ publicInputs: {
2249
+ authDigest,
2250
+ allowlistCommitment: this.policy.allowlistCommitment,
2251
+ capCommitment,
2252
+ payeeHash,
2253
+ amountStroops: context.amountStroops.toString(),
2254
+ dayBucket: bucket.toString()
2255
+ }
2256
+ };
2257
+ this.policy.dailySpendStroops += context.amountStroops;
2258
+ return proof;
2259
+ }
2260
+ enforcePolicy(context) {
2261
+ if (context.amountStroops < 0n) {
2262
+ throw new RangeError(`Invalid amountStroops: ${context.amountStroops}`);
2263
+ }
2264
+ if (!Number.isSafeInteger(context.ledgerSequence) || context.ledgerSequence < 0) {
2265
+ throw new RangeError(`Invalid ledgerSequence: ${context.ledgerSequence}`);
2266
+ }
2267
+ if (this.policy.expiryLedger !== void 0 && context.ledgerSequence > this.policy.expiryLedger) {
2268
+ throw new NulthPolicyError("session_expired", "Nulth session expired");
2269
+ }
2270
+ if (!this.policy.allowedPayees.includes(context.payee)) {
2271
+ throw new NulthPolicyError("payee_not_allowed", `Payee ${context.payee} not in off-chain allowlist`);
2272
+ }
2273
+ const bucket = dayBucketFromLedger(context.ledgerSequence);
2274
+ const spend = bucket === this.policy.dayBucket ? this.policy.dailySpendStroops : 0n;
2275
+ if (spend + context.amountStroops > this.policy.dailyCapStroops) {
2276
+ throw new NulthPolicyError("daily_cap_exceeded", "Nulth daily cap exceeded");
2277
+ }
2278
+ }
2279
+ };
2280
+ function createNulthSigner(config) {
2281
+ const client = new NulthClient(config);
2282
+ const nulthAccount = config.nulthAccount;
2283
+ return {
2284
+ address: nulthAccount,
2285
+ signAuthEntry: async (authEntry) => {
2286
+ const ctx = config.paymentContext;
2287
+ if (!ctx) throw new Error("Nulth paymentContext must be set before signing");
2288
+ assertAuthEntryMatchesContext(authEntry, nulthAccount, ctx);
2289
+ const proof = client.buildPaymentAuthProof({ authEntry, ...ctx });
2290
+ return { signedAuthEntry: encodeAuthSignature(proof), signerAddress: nulthAccount };
2291
+ }
2292
+ };
2293
+ }
2294
+ function setNulthPaymentContext(config, context) {
2295
+ config.paymentContext = context;
2296
+ }
2297
+ function paymentContextFromManifest(manifest, mode, ledgerSequence) {
2298
+ const pricing = manifest.pricing[mode];
2299
+ if (!pricing) throw new Error(`manifest.pricing.${mode} missing`);
2300
+ return {
2301
+ payee: manifest.payee,
2302
+ amountStroops: usdcToStroops2(pricing.amount),
2303
+ assetContract: manifest.asset_contract,
2304
+ ledgerSequence
2305
+ };
2306
+ }
2307
+ function createPolicyState(input) {
2308
+ const dailyCapStroops = usdcToStroops2(input.dailyCapUsdc);
2309
+ return {
2310
+ dailyCapStroops,
2311
+ allowlistCommitment: commitAllowlist(input.allowedPayees, input.witnessSecret),
2312
+ allowedPayees: input.allowedPayees,
2313
+ dailySpendStroops: 0n,
2314
+ dayBucket: dayBucketFromLedger(input.ledgerSequence ?? 0),
2315
+ witnessSecret: input.witnessSecret,
2316
+ ...input.expiryLedger !== void 0 ? { expiryLedger: input.expiryLedger } : {}
2317
+ };
2318
+ }
2319
+ function assertNulthVaultManifest(manifest, nulthAccount) {
2320
+ if (manifest.vault !== void 0 && manifest.vault !== "nulth") {
2321
+ throw new RouteDockManifestError(`Provider vault mode ${manifest.vault} does not match client nulth vault`);
2322
+ }
2323
+ if (manifest.nulth_account && manifest.nulth_account !== nulthAccount) {
2324
+ throw new RouteDockManifestError(`Manifest nulth_account ${manifest.nulth_account} does not match configured ${nulthAccount}`);
2325
+ }
2326
+ }
2327
+ async function fetchLedgerSequence(network) {
2328
+ const rpcUrl = network === "testnet" ? "https://soroban-testnet.stellar.org" : "https://soroban.stellar.org";
2329
+ const server = new stellarSdk.rpc.Server(rpcUrl);
2330
+ const latest = await server.getLatestLedger();
2331
+ return latest.sequence;
2332
+ }
2333
+ async function prepareNulthSigner(vault, manifest, mode, network, ledgerSequenceOverride) {
2334
+ assertNulthVaultManifest(manifest, vault.nulthAccount);
2335
+ const prover = vault.prover ?? "mock";
2336
+ if (network === "mainnet" && prover === "mock") {
2337
+ throw new RouteDockManifestError(
2338
+ "nulth vault uses the insecure mock prover and cannot be used on mainnet"
2339
+ );
2340
+ }
2341
+ const ledgerSequence = ledgerSequenceOverride ?? await fetchLedgerSequence(network);
2342
+ const policy = createPolicyState({
2343
+ dailyCapUsdc: vault.dailyCapUsdc,
2344
+ allowedPayees: vault.allowedPayees,
2345
+ witnessSecret: vault.witnessSecret,
2346
+ ledgerSequence,
2347
+ ...vault.expiryLedger !== void 0 ? { expiryLedger: vault.expiryLedger } : {}
2348
+ });
2349
+ const config = {
2350
+ nulthAccount: vault.nulthAccount,
2351
+ network,
2352
+ prover,
2353
+ policy,
2354
+ ...vault.verifierContract !== void 0 ? { verifierContract: vault.verifierContract } : {}
2355
+ };
2356
+ if (mode === "x402" || mode === "mpp-charge") {
2357
+ setNulthPaymentContext(config, paymentContextFromManifest(manifest, mode, ledgerSequence));
2358
+ } else {
2359
+ throw new RouteDockManifestError(`Nulth ZK vault does not support payment mode: ${mode}`);
2360
+ }
2361
+ const signer = createNulthSigner(config);
2362
+ return { signer, config };
2363
+ }
2364
+ function decodeAuthSignature(encoded) {
2365
+ const raw = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
2366
+ if (typeof raw !== "object" || raw === null || raw.nulth !== "zk-v1") {
2367
+ throw new Error("Invalid Nulth ZK auth signature");
2368
+ }
2369
+ return raw;
2370
+ }
2371
+ var FileSpendStore = class {
2372
+ filePath;
2373
+ constructor(filePath) {
2374
+ this.filePath = filePath;
2375
+ }
2376
+ async read() {
2377
+ let data;
2378
+ try {
2379
+ data = await fs__default.default.readFile(this.filePath, "utf-8");
2380
+ } catch (err) {
2381
+ if (err.code === "ENOENT") {
2382
+ return null;
2383
+ }
2384
+ throw new Error(
2385
+ `[FileSpendStore] Failed to read spend file at ${this.filePath}: ${err.message}`
2386
+ );
2387
+ }
2388
+ try {
2389
+ return JSON.parse(data);
2390
+ } catch {
2391
+ throw new Error(
2392
+ `[FileSpendStore] Spend file at ${this.filePath} contains invalid JSON. Delete or repair it before resuming. Raw content: ${data.slice(0, 120)}`
2393
+ );
2394
+ }
2395
+ }
2396
+ async write(state) {
2397
+ const dir = path__default.default.dirname(this.filePath);
2398
+ await fs__default.default.mkdir(dir, { recursive: true });
2399
+ const tmpPath = `${this.filePath}.tmp`;
2400
+ await fs__default.default.writeFile(tmpPath, JSON.stringify(state, null, 2), "utf-8");
2401
+ await fs__default.default.rename(tmpPath, this.filePath);
2402
+ }
2403
+ };
2404
+
2405
+ // src/store/SpendStore.ts
2406
+ var InMemorySpendStore = class {
2407
+ state = null;
2408
+ constructor(options = {}) {
2409
+ if (options.warn !== false) {
2410
+ resolveLogger(options.logger)(
2411
+ "warn",
2412
+ "[RouteDock] Using in-memory SpendStore: the daily spend cap is NOT durable and resets on every process restart. Inject a persistent SpendStore via RouteDockClientConfig.spendStore for production safety."
2413
+ );
2414
+ }
2415
+ }
2416
+ async read() {
2417
+ return this.state ? { ...this.state, endpoints: { ...this.state.endpoints } } : null;
2418
+ }
2419
+ async write(state) {
2420
+ this.state = { ...state, endpoints: { ...state.endpoints } };
2421
+ }
461
2422
  };
462
2423
 
463
2424
  // src/client/RouteDockClient.ts
464
- var RouteDockClient = class {
2425
+ var _secrets = /* @__PURE__ */ new WeakMap();
2426
+ function normalizeEndpointCaps(endpointCaps) {
2427
+ if (!endpointCaps) return void 0;
2428
+ const normalized = {};
2429
+ for (const [key, value] of Object.entries(endpointCaps)) {
2430
+ let url;
2431
+ try {
2432
+ url = new URL(key);
2433
+ } catch {
2434
+ throw new RouteDockManifestError(
2435
+ `spendCap.endpointCaps key "${key}" is not a valid URL \u2014 use an origin such as "https://api.example.com"`
2436
+ );
2437
+ }
2438
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
2439
+ throw new RouteDockManifestError(
2440
+ `spendCap.endpointCaps key "${key}" must be an origin only (no path, query, or hash) \u2014 use "${url.origin}"`
2441
+ );
2442
+ }
2443
+ const origin = url.origin;
2444
+ if (Object.prototype.hasOwnProperty.call(normalized, origin)) {
2445
+ throw new RouteDockManifestError(
2446
+ `spendCap.endpointCaps has two keys that both normalize to origin "${origin}" \u2014 remove the duplicate`
2447
+ );
2448
+ }
2449
+ normalized[origin] = value;
2450
+ }
2451
+ return normalized;
2452
+ }
2453
+ function normalizeSpendCap(spendCap) {
2454
+ const endpointCaps = normalizeEndpointCaps(spendCap.endpointCaps);
2455
+ return endpointCaps === void 0 ? spendCap : { ...spendCap, endpointCaps };
2456
+ }
2457
+ var usdcToMicros = nulthSdk.usdcToStroops;
2458
+ var ASSET_ISSUERS = {
2459
+ USDC: USDC_ISSUERS
2460
+ };
2461
+ function getAssetIssuer(asset, network) {
2462
+ return ASSET_ISSUERS[asset]?.[network] ?? "";
2463
+ }
2464
+ var TRUSTLINE_CACHE_TTL_MS = 3e5;
2465
+ var RouteDockClient = class _RouteDockClient {
2466
+ /** Per-(account,asset) trustline existence cache keyed by `${network}:${pubkey}:${asset}` */
2467
+ static _trustlineCache = /* @__PURE__ */ new Map();
465
2468
  keypair;
466
2469
  network;
467
2470
  spendCap;
468
- commitmentSecret;
469
- /** Local daily accumulator keyed by YYYY-MM-DD */
470
- dailySpend = { date: "", total: 0 };
2471
+ retryPolicy;
2472
+ logger;
2473
+ manifestTimeoutMs;
2474
+ expectedPayee;
2475
+ vault;
2476
+ /**
2477
+ * Durable backing store for the local daily spend accumulator (keyed by
2478
+ * YYYY-MM-DD). Totals are persisted as decimal strings of microUSDC
2479
+ * (1 USDC = 10^7) so stores stay JSON-safe with no precision loss.
2480
+ */
2481
+ spendStore;
471
2482
  x402;
472
2483
  charge;
473
2484
  session;
2485
+ /**
2486
+ * Promise-chain mutex for serializing read-modify-write on the spend
2487
+ * accumulator. Each pay() call awaits the previous one, preventing
2488
+ * concurrent read-modify-write races that could overrun the cap.
2489
+ */
2490
+ _spendMutex = Promise.resolve();
2491
+ /**
2492
+ * Pending spend reservations keyed by reserveId. Used by _rollbackSpend
2493
+ * to revert the accumulator when a payment fails after reservation.
2494
+ */
2495
+ _pendingReserves = /* @__PURE__ */ new Map();
474
2496
  constructor(config) {
475
2497
  this.keypair = typeof config.wallet === "string" ? stellarSdk.Keypair.fromSecret(config.wallet) : config.wallet;
476
2498
  this.network = config.network;
477
- this.spendCap = config.spendCap;
478
- this.commitmentSecret = config.commitmentSecret;
2499
+ this.spendCap = config.spendCap ? normalizeSpendCap(config.spendCap) : void 0;
2500
+ this.retryPolicy = config.retryPolicy;
2501
+ this.spendStore = config.spendStore ?? new InMemorySpendStore({
2502
+ warn: !!config.spendCap,
2503
+ ...config.logger && { logger: config.logger }
2504
+ });
2505
+ this.logger = config.logger;
2506
+ this.manifestTimeoutMs = config.manifestTimeoutMs;
2507
+ this.expectedPayee = config.expectedPayee;
2508
+ if (config.commitmentSecret) {
2509
+ _secrets.set(this, config.commitmentSecret);
2510
+ }
2511
+ this.vault = config.vault;
2512
+ if (config.commitmentSecret) {
2513
+ _secrets.set(this, config.commitmentSecret);
2514
+ }
479
2515
  const secretKey = this.keypair.secret();
480
- this.x402 = new X402Client(secretKey, this.network);
481
- this.charge = new MppChargeClient(this.keypair, this.network);
482
- this.session = new MppSessionClient(this.keypair, this.network);
2516
+ const retryPolicy = this.logger ? { ...this.retryPolicy, logger: this.logger } : this.retryPolicy;
2517
+ this.x402 = new X402Client(secretKey, this.network, retryPolicy);
2518
+ this.charge = new MppChargeClient(this.keypair, this.network, retryPolicy);
2519
+ this.session = new MppSessionClient(this.keypair, this.network, retryPolicy, void 0, this.logger);
2520
+ }
2521
+ /** Fetch manifest and select mode — shared by pay() and estimateCost(). */
2522
+ async _resolveManifest(url, options) {
2523
+ const baseUrl = new URL(url).origin;
2524
+ const manifest = await fetchManifest(baseUrl, this.retryPolicy, this.manifestTimeoutMs, this.expectedPayee);
2525
+ assertEndpointActive(manifest, url, this.logger);
2526
+ const mode = selectMode(manifest, options);
2527
+ return { manifest, mode };
2528
+ }
2529
+ /**
2530
+ * Serialize async work through the per-instance spend mutex so concurrent
2531
+ * pay() calls cannot interleave read-modify-write on the accumulator.
2532
+ */
2533
+ _withSpendMutex(fn) {
2534
+ const prev = this._spendMutex;
2535
+ let next;
2536
+ next = prev.then(fn, fn);
2537
+ this._spendMutex = next.then(() => {
2538
+ }, () => {
2539
+ });
2540
+ return next;
2541
+ }
2542
+ /**
2543
+ * Check that the payer has a trustline for the payment asset and surface
2544
+ * manifest metadata (regions, latency hints, capabilities). Safe to
2545
+ * call before committing to a payment — for approval gates and manual
2546
+ * trustline remediation.
2547
+ */
2548
+ async preflight(manifest, mode, endpoint) {
2549
+ assertManifestValid(manifest);
2550
+ const selectedAsset = mode ? selectAsset(manifest, mode, endpoint).asset : manifest.asset;
2551
+ await this._checkTrustline(manifest, selectedAsset);
2552
+ return {
2553
+ hasTrustline: true,
2554
+ asset: selectedAsset,
2555
+ modes: manifest.modes,
2556
+ ...manifest.regions && { regions: manifest.regions },
2557
+ ...manifest.latency_hints && { latency_hints: manifest.latency_hints },
2558
+ ...manifest.capabilities && { capabilities: manifest.capabilities }
2559
+ };
2560
+ }
2561
+ /**
2562
+ * Verify via Horizon that the payer account has a trustline for the
2563
+ * payment asset declared in the manifest. Throws RouteDockTrustlineError
2564
+ * with an exact Stellar CLI change-trust remediation command when the
2565
+ * trustline is missing. Results are cached per (account, asset) so the
2566
+ * per-payment overhead is one RPC call amortized to zero after the first.
2567
+ */
2568
+ async _checkTrustline(manifest, targetAsset = manifest.asset) {
2569
+ const cacheKey = `${this.network}:${this.keypair.publicKey()}:${targetAsset}`;
2570
+ const cached = _RouteDockClient._trustlineCache.get(cacheKey);
2571
+ if (cached && Date.now() < cached.expiresAt) return;
2572
+ const horizonUrl = this.network === "testnet" ? "https://horizon-testnet.stellar.org" : "https://horizon.stellar.org";
2573
+ const server = new stellarSdk.Horizon.Server(horizonUrl);
2574
+ try {
2575
+ const account = await server.loadAccount(this.keypair.publicKey());
2576
+ const balances = account.balances;
2577
+ const expectedIssuer = getAssetIssuer(targetAsset, this.network);
2578
+ const hasTrustline = balances.some(
2579
+ (b) => typeof b === "object" && b !== null && (targetAsset === "XLM" && b.asset_type === "native" || "asset_code" in b && b.asset_code === targetAsset && (!expectedIssuer || b.asset_issuer === expectedIssuer))
2580
+ );
2581
+ if (!hasTrustline) {
2582
+ const remediation = expectedIssuer ? `Run: stellar tx new --source ${this.keypair.publicKey()} --network ${this.network} change-trust --asset ${targetAsset}:${expectedIssuer} --limit 100000` : `Establish a trustline for ${targetAsset} with the appropriate issuer on ${this.network}`;
2583
+ throw new RouteDockTrustlineError(targetAsset, expectedIssuer || "unknown", remediation);
2584
+ }
2585
+ _RouteDockClient._trustlineCache.set(cacheKey, {
2586
+ exists: true,
2587
+ expiresAt: Date.now() + TRUSTLINE_CACHE_TTL_MS
2588
+ });
2589
+ } catch (err) {
2590
+ if (err instanceof RouteDockTrustlineError) throw err;
2591
+ this.logger?.(
2592
+ "warn",
2593
+ `[RouteDock] Trustline preflight: could not verify trustline for ${targetAsset} \u2014 continuing`
2594
+ );
2595
+ }
483
2596
  }
484
2597
  /**
485
2598
  * Pay for one request at `url`. Fetches manifest, selects payment mode,
486
- * checks local spend cap, executes payment, returns result.
2599
+ * runs trustline preflight, reserves local spend cap BEFORE executing the
2600
+ * payment, then commits the spend record on success. Rolls back the
2601
+ * reservation if the on-chain payment fails, and also when the call
2602
+ * completes without paying anything (an x402 endpoint answering a plain
2603
+ * 200 with no challenge). Concurrent pay() calls are serialized through a
2604
+ * per-instance mutex to prevent spend-cap overrun.
487
2605
  */
488
2606
  async pay(url, options) {
489
2607
  const baseUrl = new URL(url).origin;
490
- const manifest = await fetchManifest(baseUrl);
491
- const mode = selectMode(manifest, options);
492
- let result;
2608
+ const manifest = await fetchManifest(baseUrl, this.retryPolicy, this.manifestTimeoutMs, this.expectedPayee);
2609
+ assertEndpointActive(manifest, url, this.logger);
2610
+ const mode = selectMode(manifest, { ...options, ...this.logger && { logger: this.logger } });
2611
+ const selectedAsset = selectAsset(manifest, mode, url).asset;
2612
+ await this._checkTrustline(manifest, selectedAsset);
2613
+ let amount;
493
2614
  switch (mode) {
494
2615
  case "x402":
495
- result = await this.x402.pay(url, manifest);
2616
+ amount = manifest.pricing.x402.amount;
496
2617
  break;
497
2618
  case "mpp-charge":
498
- result = await this.charge.pay(url, manifest);
2619
+ amount = manifest.pricing["mpp-charge"].amount;
499
2620
  break;
500
2621
  case "mpp-session":
2622
+ case "mpp-session-ws":
501
2623
  throw new RouteDockManifestError(
502
- "Use client.openSession() for mpp-session mode \u2014 client.pay() only handles discrete payments"
2624
+ `Use client.openSession() for ${mode} mode \u2014 client.pay() only handles discrete payments`
503
2625
  );
504
2626
  default:
505
2627
  throw new RouteDockManifestError(`Unknown payment mode: ${mode}`);
506
2628
  }
507
- this._checkAndRecordSpend(result.amount);
2629
+ const reserveId = await this._checkAndReserveSpend(amount, baseUrl);
2630
+ let result;
2631
+ try {
2632
+ if (this.vault?.mode === "nulth") {
2633
+ result = await this._payWithNulthVault(url, manifest, mode);
2634
+ } else {
2635
+ switch (mode) {
2636
+ case "x402":
2637
+ result = await this.x402.pay(url, manifest);
2638
+ break;
2639
+ case "mpp-charge":
2640
+ result = await this.charge.pay(url, manifest);
2641
+ break;
2642
+ default:
2643
+ throw new RouteDockManifestError(`Unknown payment mode: ${mode}`);
2644
+ }
2645
+ }
2646
+ } catch (err) {
2647
+ await this._rollbackSpend(reserveId).catch(() => {
2648
+ });
2649
+ throw err;
2650
+ }
2651
+ if (result.txHash === null && result.amount === "0") {
2652
+ await this._rollbackSpend(reserveId);
2653
+ } else {
2654
+ await this._commitSpend(reserveId);
2655
+ }
508
2656
  return result;
509
2657
  }
2658
+ /** Nulth ZK vault path — proof built off-chain, attached as auth signature */
2659
+ async _payWithNulthVault(url, manifest, mode) {
2660
+ const prover = this.vault?.prover ?? "mock";
2661
+ if (this.network === "mainnet" && prover === "mock") {
2662
+ throw new RouteDockManifestError("nulth vault uses a MOCK Groth16 prover and cannot be used on mainnet");
2663
+ }
2664
+ if (mode !== "x402") {
2665
+ throw new RouteDockManifestError(
2666
+ 'nulth vault currently supports x402 mode \u2014 force x402 via { forceMode: "x402" }'
2667
+ );
2668
+ }
2669
+ try {
2670
+ const { signer } = await prepareNulthSigner(this.vault, manifest, mode, this.network);
2671
+ const x402 = this.x402.withSigner(signer);
2672
+ const result = await x402.pay(url, manifest);
2673
+ return result;
2674
+ } catch (err) {
2675
+ if (err instanceof NulthPolicyError) {
2676
+ throw new RouteDockPolicyRejectError(err.code);
2677
+ }
2678
+ throw err;
2679
+ }
2680
+ }
2681
+ /**
2682
+ * Resolve manifest and compute the expected charge WITHOUT submitting any
2683
+ * transaction. Safe to call before committing — for approval gates and
2684
+ * budget-aware routing.
2685
+ */
2686
+ async estimateCost(url, options) {
2687
+ const { manifest, mode } = await this._resolveManifest(url, options);
2688
+ let amount;
2689
+ switch (mode) {
2690
+ case "x402":
2691
+ amount = manifest.pricing.x402.amount;
2692
+ break;
2693
+ case "mpp-charge":
2694
+ amount = manifest.pricing["mpp-charge"].amount;
2695
+ break;
2696
+ case "mpp-session":
2697
+ amount = manifest.pricing["mpp-session"].rate;
2698
+ break;
2699
+ case "mpp-session-ws":
2700
+ amount = manifest.pricing["mpp-session-ws"].rate;
2701
+ break;
2702
+ default:
2703
+ throw new RouteDockManifestError(`Unknown payment mode: ${mode}`);
2704
+ }
2705
+ const selectedAsset = selectAsset(manifest, mode, url).asset;
2706
+ return {
2707
+ amount,
2708
+ asset: selectedAsset,
2709
+ mode,
2710
+ manifest,
2711
+ ...manifest.regions && { regions: manifest.regions },
2712
+ ...manifest.latency_hints && { latency_hints: manifest.latency_hints },
2713
+ ...manifest.capabilities && { capabilities: manifest.capabilities }
2714
+ };
2715
+ }
510
2716
  /**
511
2717
  * Open a sustained MPP session at `url`. Verifies mpp-session is supported
512
2718
  * before opening a channel. Returns a SessionHandle for streaming + closing.
2719
+ *
2720
+ * By default the session auto-closes after a wall-clock timeout (1h) so an
2721
+ * orphaned channel cannot keep collateral locked on-chain — override or
2722
+ * disable via `options.maxDurationMs`.
513
2723
  */
514
- async openSession(url) {
2724
+ async openSession(url, options) {
515
2725
  const baseUrl = new URL(url).origin;
516
- const manifest = await fetchManifest(baseUrl);
517
- if (!manifest.modes.includes("mpp-session")) {
2726
+ const manifest = await fetchManifest(baseUrl, this.retryPolicy, this.manifestTimeoutMs, this.expectedPayee);
2727
+ assertEndpointActive(manifest, url, this.logger);
2728
+ const mode = options?.mode ?? "mpp-session";
2729
+ if (!manifest.modes.includes(mode)) {
518
2730
  throw new RouteDockManifestError(
519
- `Provider at ${baseUrl} does not support mpp-session mode`
2731
+ `Provider at ${baseUrl} does not support ${mode} mode`
520
2732
  );
521
2733
  }
522
- if (!this.commitmentSecret) {
2734
+ const secret = _secrets.get(this);
2735
+ if (!secret) {
523
2736
  throw new RouteDockManifestError(
524
2737
  "commitmentSecret is required in RouteDockClientConfig for mpp-session mode"
525
2738
  );
526
2739
  }
527
- return this.session.openSession(url, manifest, this.commitmentSecret);
2740
+ const endpointKey = new URL(url).origin;
2741
+ const onSpend = this.spendCap ? (amount) => this._recordSessionSpend(amount, endpointKey) : void 0;
2742
+ return this.session.openSession(url, manifest, secret, options, onSpend);
528
2743
  }
529
- /** Check local daily cap and record the spend. Throws if cap exceeded. */
530
- _checkAndRecordSpend(amount) {
531
- if (!this.spendCap) return;
532
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
533
- if (this.dailySpend.date !== today) {
534
- this.dailySpend = { date: today, total: 0 };
535
- }
536
- const amountNum = parseFloat(amount);
537
- const capNum = parseFloat(this.spendCap.daily);
538
- if (this.dailySpend.total + amountNum > capNum) {
539
- throw new RouteDockPolicyRejectedError("local_daily_cap_exceeded");
2744
+ /**
2745
+ * Record spend for an MPP session voucher. Called before each voucher
2746
+ * fetch in stream(). Enforces the same local daily and per-endpoint caps
2747
+ * as discrete pay() calls. Returns a commit function to clean up the
2748
+ * reservation after the voucher fetch succeeds.
2749
+ */
2750
+ async _recordSessionSpend(amount, endpointKey) {
2751
+ const reserveId = await this._checkAndReserveSpend(amount, endpointKey);
2752
+ if (reserveId) {
2753
+ await this._commitSpend(reserveId);
540
2754
  }
541
- this.dailySpend.total += amountNum;
2755
+ }
2756
+ /**
2757
+ * Remove the commitment secret from memory and make it eligible for GC.
2758
+ * Call when this client instance is no longer needed — particularly in
2759
+ * long-lived processes or Worker threads.
2760
+ */
2761
+ dispose() {
2762
+ _secrets.delete(this);
2763
+ }
2764
+ /**
2765
+ * Evict the cached manifest for `url` immediately, so the next pay() /
2766
+ * estimateCost() / openSession() call re-fetches it instead of routing on
2767
+ * the stale cached copy. Use when a provider signals their manifest
2768
+ * changed (e.g. after a config update) and the change must take effect
2769
+ * before the cache TTL expires.
2770
+ */
2771
+ invalidateManifest(url) {
2772
+ invalidateManifest(new URL(url).origin);
2773
+ }
2774
+ /**
2775
+ * Reserve spend against local daily caps BEFORE dispatching payment.
2776
+ * Returns a reserveId that must be passed to _commitSpend() on success
2777
+ * or _rollbackSpend() on failure.
2778
+ *
2779
+ * The entire read-check-write is serialized through the per-instance
2780
+ * mutex (_withSpendMutex) so concurrent pay() calls cannot interleave
2781
+ * and overrun the cap.
2782
+ *
2783
+ * Enforcement order:
2784
+ * 1. Per-endpoint cap (if `endpointCaps[endpointKey]` is set) — checked first.
2785
+ * 2. Global daily cap — checked second.
2786
+ *
2787
+ * Both limits are independent: a payment is only reserved after **both** pass.
2788
+ * All spend (regardless of endpoint) counts toward the global accumulator.
2789
+ */
2790
+ async _checkAndReserveSpend(amount, endpointKey) {
2791
+ if (!this.spendCap) return "";
2792
+ return this._withSpendMutex(async () => {
2793
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2794
+ const persisted = await this.spendStore.read();
2795
+ const current = persisted && persisted.date === today ? persisted : { date: today, totalMicros: "0", endpoints: {} };
2796
+ const amountMicros = nulthSdk.usdcToStroops(amount);
2797
+ const total = BigInt(current.totalMicros);
2798
+ const endpointCapStr = this.spendCap.endpointCaps?.[endpointKey];
2799
+ if (endpointCapStr !== void 0) {
2800
+ const endpointCapMicros = nulthSdk.usdcToStroops(endpointCapStr);
2801
+ const endpointTotal = BigInt(current.endpoints[endpointKey] ?? "0");
2802
+ if (endpointTotal + amountMicros > endpointCapMicros) {
2803
+ throw new RouteDockPolicyRejectError("local_endpoint_cap_exceeded");
2804
+ }
2805
+ }
2806
+ const globalCapMicros = nulthSdk.usdcToStroops(this.spendCap.daily);
2807
+ if (total + amountMicros > globalCapMicros) {
2808
+ throw new RouteDockPolicyRejectError("local_daily_cap_exceeded");
2809
+ }
2810
+ const reserveId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2811
+ this._pendingReserves.set(reserveId, { endpointKey, amountMicros });
2812
+ current.totalMicros = (total + amountMicros).toString();
2813
+ if (endpointCapStr !== void 0) {
2814
+ current.endpoints[endpointKey] = (BigInt(current.endpoints[endpointKey] ?? "0") + amountMicros).toString();
2815
+ }
2816
+ await this.spendStore.write(current);
2817
+ return reserveId;
2818
+ });
2819
+ }
2820
+ /**
2821
+ * Commit a previously reserved spend after payment succeeds. For discrete
2822
+ * pay() calls this is a no-op (the spend was already recorded by reserve).
2823
+ * Reserved for future use if the committed amount differs from the reserved.
2824
+ */
2825
+ async _commitSpend(reserveId) {
2826
+ this._pendingReserves.delete(reserveId);
2827
+ }
2828
+ /**
2829
+ * Rollback a previously reserved spend when payment fails. Reverts the
2830
+ * tentative accumulator write done by _checkAndReserveSpend.
2831
+ */
2832
+ async _rollbackSpend(reserveId) {
2833
+ if (!this.spendCap || !reserveId) return;
2834
+ const reserve = this._pendingReserves.get(reserveId);
2835
+ if (!reserve) return;
2836
+ this._pendingReserves.delete(reserveId);
2837
+ const { endpointKey, amountMicros } = reserve;
2838
+ await this._withSpendMutex(async () => {
2839
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2840
+ const persisted = await this.spendStore.read();
2841
+ if (!persisted || persisted.date !== today) return;
2842
+ const currentTotal = BigInt(persisted.totalMicros);
2843
+ persisted.totalMicros = (currentTotal - amountMicros).toString();
2844
+ if (persisted.endpoints[endpointKey]) {
2845
+ const endpointTotal = BigInt(persisted.endpoints[endpointKey]);
2846
+ const newEndpointTotal = endpointTotal - amountMicros;
2847
+ if (newEndpointTotal <= 0n) {
2848
+ delete persisted.endpoints[endpointKey];
2849
+ } else {
2850
+ persisted.endpoints[endpointKey] = newEndpointTotal.toString();
2851
+ }
2852
+ }
2853
+ await this.spendStore.write(persisted);
2854
+ });
542
2855
  }
543
2856
  };
544
2857
 
@@ -550,12 +2863,16 @@ var SupabaseSessionStore = class {
550
2863
  supabase;
551
2864
  async get(channelId) {
552
2865
  const { data, error } = await this.supabase.from("sessions").select("*").eq("channel_id", channelId).maybeSingle();
553
- if (error) throw new RouteDockSessionError(`SessionStore.get failed: ${error.message}`);
2866
+ if (error) {
2867
+ throw new RouteDockNetworkError(`SessionStore.get failed: ${error.message}`);
2868
+ }
554
2869
  if (!data) return null;
555
2870
  return {
556
2871
  channel_id: data.channel_id,
557
2872
  payee: data.payee,
558
2873
  payer: data.payer,
2874
+ channel_contract: data.channel_contract,
2875
+ network: data.network,
559
2876
  cumulative_amount: String(data.cumulative_amount),
560
2877
  last_signature: data.last_signature,
561
2878
  status: data.status,
@@ -570,7 +2887,7 @@ var SupabaseSessionStore = class {
570
2887
  const prev = parseFloat(existing.cumulative_amount);
571
2888
  const next = parseFloat(state.cumulative_amount);
572
2889
  if (next <= prev) {
573
- throw new RouteDockSessionError(
2890
+ throw new RouteDockVoucherMonotonicityError(
574
2891
  `cumulative_amount must be strictly increasing: ${next} <= ${prev}`
575
2892
  );
576
2893
  }
@@ -580,6 +2897,8 @@ var SupabaseSessionStore = class {
580
2897
  channel_id: state.channel_id,
581
2898
  payee: state.payee,
582
2899
  payer: state.payer,
2900
+ channel_contract: state.channel_contract,
2901
+ network: state.network,
583
2902
  cumulative_amount: state.cumulative_amount,
584
2903
  last_signature: state.last_signature,
585
2904
  status: state.status,
@@ -591,28 +2910,238 @@ var SupabaseSessionStore = class {
591
2910
  );
592
2911
  if (error) {
593
2912
  if (error.message.includes("strictly increasing")) {
594
- throw new RouteDockSessionError(
2913
+ throw new RouteDockVoucherMonotonicityError(
595
2914
  `cumulative_amount must be strictly increasing (DB): ${error.message}`
596
2915
  );
597
2916
  }
598
- throw new RouteDockSessionError(`SessionStore.upsert failed: ${error.message}`);
2917
+ throw new RouteDockNetworkError(`SessionStore.upsert failed: ${error.message}`);
2918
+ }
2919
+ }
2920
+ async setStatus(channelId, status, settlementTxHash) {
2921
+ const payload = {
2922
+ status,
2923
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
2924
+ };
2925
+ if (settlementTxHash !== void 0) {
2926
+ payload.settlement_tx_hash = settlementTxHash;
2927
+ }
2928
+ const { error } = await this.supabase.from("sessions").update(payload).eq("channel_id", channelId);
2929
+ if (error) {
2930
+ throw new RouteDockNetworkError(`SessionStore.setStatus failed: ${error.message}`);
599
2931
  }
600
2932
  }
601
2933
  async close(channelId) {
602
- const { error } = await this.supabase.from("sessions").update({ status: "closed", updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("channel_id", channelId);
603
- if (error) throw new RouteDockSessionError(`SessionStore.close failed: ${error.message}`);
2934
+ await this.setStatus(channelId, "closed");
2935
+ }
2936
+ };
2937
+ function tryDecodeBase64(value) {
2938
+ if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") || value.startsWith("[")) {
2939
+ return value;
2940
+ }
2941
+ try {
2942
+ const decoded = typeof Buffer !== "undefined" ? Buffer.from(value, "base64").toString("utf-8") : atob(value);
2943
+ if (decoded.length > 0 && decoded !== value) return decoded;
2944
+ } catch {
2945
+ }
2946
+ return value;
2947
+ }
2948
+ var OnChainRegistry = class {
2949
+ horizon;
2950
+ knownAccounts;
2951
+ timeoutMs;
2952
+ constructor(options) {
2953
+ this.horizon = new stellarSdk.Horizon.Server(options.horizonUrl);
2954
+ this.knownAccounts = options.knownAccounts;
2955
+ this.timeoutMs = options.timeoutMs ?? 1e4;
2956
+ }
2957
+ /**
2958
+ * stellar-sdk 14.6.1 has no way to cancel the underlying Horizon request, so
2959
+ * we stop waiting on it instead: the promise returned here rejects once
2960
+ * `timeoutMs` elapses, even though the request may still be in flight. The
2961
+ * timer is always cleared, including on the error path.
2962
+ */
2963
+ loadAccountWithTimeout(accountId) {
2964
+ let timer;
2965
+ const timeout = new Promise((_, reject) => {
2966
+ timer = setTimeout(
2967
+ () => reject(new Error(`Horizon loadAccount timed out after ${this.timeoutMs}ms`)),
2968
+ this.timeoutMs
2969
+ );
2970
+ });
2971
+ return Promise.race([this.horizon.loadAccount(accountId), timeout]).finally(() => {
2972
+ if (timer !== void 0) clearTimeout(timer);
2973
+ });
2974
+ }
2975
+ async listProviders() {
2976
+ const settled = await Promise.allSettled(
2977
+ this.knownAccounts.map((accountId) => this.loadAccountWithTimeout(accountId))
2978
+ );
2979
+ const results = [];
2980
+ for (let i = 0; i < settled.length; i++) {
2981
+ const outcome = settled[i];
2982
+ if (outcome.status !== "fulfilled") continue;
2983
+ const accountId = this.knownAccounts[i];
2984
+ const account = outcome.value;
2985
+ const dataEntries = account.data_attr;
2986
+ if (!dataEntries) continue;
2987
+ const rawEndpoint = dataEntries["routedock_endpoint"];
2988
+ if (!rawEndpoint) continue;
2989
+ const endpoint = tryDecodeBase64(rawEndpoint);
2990
+ if (!endpoint.startsWith("http://") && !endpoint.startsWith("https://")) continue;
2991
+ let tags = [];
2992
+ const rawTags = dataEntries["routedock_tags"];
2993
+ if (rawTags) {
2994
+ const decoded = tryDecodeBase64(rawTags);
2995
+ try {
2996
+ const parsed = JSON.parse(decoded);
2997
+ if (Array.isArray(parsed)) tags = parsed;
2998
+ } catch {
2999
+ tags = decoded.split(",").map((t) => t.trim()).filter(Boolean);
3000
+ }
3001
+ }
3002
+ results.push({ account: accountId, endpoint, tags });
3003
+ }
3004
+ return results;
3005
+ }
3006
+ };
3007
+
3008
+ // src/registry/ProviderRegistry.ts
3009
+ function deriveNetwork(horizonUrl) {
3010
+ return horizonUrl.includes("testnet") ? "testnet" : "mainnet";
3011
+ }
3012
+ var ProviderRegistry = class {
3013
+ supabase;
3014
+ onChain;
3015
+ network;
3016
+ constructor(config) {
3017
+ this.supabase = config.supabase;
3018
+ this.network = config.onChain.network ?? deriveNetwork(config.onChain.horizonUrl);
3019
+ this.onChain = new OnChainRegistry({
3020
+ horizonUrl: config.onChain.horizonUrl,
3021
+ knownAccounts: config.onChain.knownAccounts,
3022
+ ...config.onChain.timeoutMs !== void 0 ? { timeoutMs: config.onChain.timeoutMs } : {}
3023
+ });
3024
+ }
3025
+ async listProviders() {
3026
+ const supabaseProviders = await this.trySupabase();
3027
+ if (supabaseProviders.length > 0) return supabaseProviders;
3028
+ return this.tryOnChain();
3029
+ }
3030
+ async trySupabase() {
3031
+ if (!this.supabase) return [];
3032
+ try {
3033
+ const { data, error } = await this.supabase.from("providers").select("*").eq("verified", true).eq("network", this.network).limit(100);
3034
+ if (error) return [];
3035
+ if (!data || data.length === 0) return [];
3036
+ return data.map((r) => ({
3037
+ name: r.name,
3038
+ description: r.description ?? void 0,
3039
+ base_url: r.base_url,
3040
+ modes: r.modes,
3041
+ tags: r.tags,
3042
+ network: r.network,
3043
+ payee: r.payee,
3044
+ source: "supabase",
3045
+ verified: r.verified === true
3046
+ }));
3047
+ } catch {
3048
+ return [];
3049
+ }
3050
+ }
3051
+ async tryOnChain() {
3052
+ const providers = await this.onChain.listProviders();
3053
+ return providers.map((p) => ({
3054
+ name: `On-chain provider (${p.account.slice(0, 8)}...)`,
3055
+ description: `Provider registered on Stellar account ${p.account}`,
3056
+ base_url: p.endpoint,
3057
+ modes: [],
3058
+ tags: p.tags,
3059
+ network: this.network,
3060
+ payee: p.account,
3061
+ source: "onchain",
3062
+ verified: true
3063
+ }));
3064
+ }
3065
+ /**
3066
+ * Fetch a provider's manifest bound to the record's payee. The record's
3067
+ * `payee` (from supabase `verified` rows or the on-chain registry account)
3068
+ * is the out-of-band trust anchor: the fetched manifest's `payee` must
3069
+ * equal it, otherwise `RouteDockSignatureError` is thrown. This closes the
3070
+ * gap where the registry never cross-checked the on-chain payee against
3071
+ * the manifest payee.
3072
+ */
3073
+ async fetchProviderManifest(record) {
3074
+ const baseUrl = new URL(record.base_url).origin;
3075
+ return fetchManifest(baseUrl, void 0, void 0, record.payee);
604
3076
  }
605
3077
  };
606
3078
 
3079
+ Object.defineProperty(exports, "USDC_DECIMALS", {
3080
+ enumerable: true,
3081
+ get: function () { return nulthSdk.USDC_DECIMALS; }
3082
+ });
3083
+ Object.defineProperty(exports, "usdcToStroops", {
3084
+ enumerable: true,
3085
+ get: function () { return nulthSdk.usdcToStroops; }
3086
+ });
3087
+ exports.DEFAULT_MAX_SESSION_DURATION_MS = DEFAULT_MAX_SESSION_DURATION_MS;
3088
+ exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY;
3089
+ exports.FileSpendStore = FileSpendStore;
3090
+ exports.InMemorySpendStore = InMemorySpendStore;
607
3091
  exports.MppChargeClient = MppChargeClient;
608
3092
  exports.MppSessionClient = MppSessionClient;
3093
+ exports.NulthPolicyError = NulthPolicyError;
3094
+ exports.OnChainRegistry = OnChainRegistry;
3095
+ exports.ProviderRegistry = ProviderRegistry;
3096
+ exports.RouteDockChannelStateError = RouteDockChannelStateError;
609
3097
  exports.RouteDockClient = RouteDockClient;
3098
+ exports.RouteDockClientVersionError = RouteDockClientVersionError;
3099
+ exports.RouteDockDisputeError = RouteDockDisputeError;
610
3100
  exports.RouteDockError = RouteDockError;
3101
+ exports.RouteDockFacilitatorError = RouteDockFacilitatorError;
611
3102
  exports.RouteDockManifestError = RouteDockManifestError;
3103
+ exports.RouteDockManifestSunsetError = RouteDockManifestSunsetError;
3104
+ exports.RouteDockManifestTimeoutError = RouteDockManifestTimeoutError;
3105
+ exports.RouteDockNetworkError = RouteDockNetworkError;
612
3106
  exports.RouteDockNoSupportedModeError = RouteDockNoSupportedModeError;
3107
+ exports.RouteDockPolicyRejectError = RouteDockPolicyRejectError;
613
3108
  exports.RouteDockPolicyRejectedError = RouteDockPolicyRejectedError;
3109
+ exports.RouteDockRefundWindowError = RouteDockRefundWindowError;
614
3110
  exports.RouteDockSessionError = RouteDockSessionError;
3111
+ exports.RouteDockSignatureError = RouteDockSignatureError;
3112
+ exports.RouteDockTrustlineError = RouteDockTrustlineError;
3113
+ exports.RouteDockVoucherMonotonicityError = RouteDockVoucherMonotonicityError;
615
3114
  exports.SupabaseSessionStore = SupabaseSessionStore;
616
3115
  exports.X402Client = X402Client;
3116
+ exports.assertEndpointActive = assertEndpointActive;
3117
+ exports.assertManifestValid = assertManifestValid;
3118
+ exports.assertNulthVaultManifest = assertNulthVaultManifest;
3119
+ exports.backoffDelayMs = backoffDelayMs;
3120
+ exports.configureManifestCache = configureManifestCache;
3121
+ exports.consoleLogger = consoleLogger;
3122
+ exports.createConsoleLogger = createConsoleLogger;
3123
+ exports.createNulthSigner = createNulthSigner;
3124
+ exports.createPolicyState = createPolicyState;
3125
+ exports.decodeAuthSignature = decodeAuthSignature;
3126
+ exports.fetchLedgerSequence = fetchLedgerSequence;
617
3127
  exports.fetchManifest = fetchManifest;
3128
+ exports.getEligibleAssets = getEligibleAssets;
3129
+ exports.httpStatusToError = httpStatusToError;
3130
+ exports.invalidateManifest = invalidateManifest;
3131
+ exports.isAssetEligible = isAssetEligible;
3132
+ exports.noopLogger = noopLogger;
3133
+ exports.normalizeManifestAssets = normalizeManifestAssets;
3134
+ exports.parseRetryAfterMs = parseRetryAfterMs;
3135
+ exports.paymentContextFromManifest = paymentContextFromManifest;
3136
+ exports.prepareNulthSigner = prepareNulthSigner;
3137
+ exports.rankProvidersByLatency = rankProvidersByLatency;
3138
+ exports.resolveAssetContract = resolveAssetContract;
3139
+ exports.resolveLogger = resolveLogger;
3140
+ exports.selectAsset = selectAsset;
618
3141
  exports.selectMode = selectMode;
3142
+ exports.setNulthPaymentContext = setNulthPaymentContext;
3143
+ exports.usdcToMicros = usdcToMicros;
3144
+ exports.usdcToUnits = usdcToUnits;
3145
+ exports.withRetry = withRetry;
3146
+ exports.wrapFetchError = wrapFetchError;
3147
+ exports.wrapMppError = wrapMppError;