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