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