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