@dvmkit/dvm-cli 0.0.0 → 0.1.5
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 +67 -0
- package/NOTICE +2 -0
- package/README.md +28 -3
- package/dist/_esm-MN4BUYV6.js +885 -0
- package/dist/_esm-NRGECLJ7.js +35 -0
- package/dist/accounts-2WZE4N5F.js +73 -0
- package/dist/actions-LR65XILR.js +244 -0
- package/dist/ccip-JXYJSXTW.js +18 -0
- package/dist/chains-LJ7XK6H3.js +1460 -0
- package/dist/chunk-2VVVWBQA.js +15436 -0
- package/dist/chunk-3SWX5BQP.js +66 -0
- package/dist/chunk-3W2M46WM.js +61142 -0
- package/dist/chunk-4JXFXP4Y.js +757 -0
- package/dist/chunk-4NWEJTAW.js +16616 -0
- package/dist/chunk-65EY7CT4.js +2691 -0
- package/dist/chunk-6CC6JGEU.js +1815 -0
- package/dist/chunk-6O27TEXD.js +1181 -0
- package/dist/chunk-7OK7MBT6.js +258 -0
- package/dist/chunk-BECPI5H5.js +30063 -0
- package/dist/chunk-CJTE5TS3.js +1298 -0
- package/dist/chunk-ECEM3ZAS.js +339 -0
- package/dist/chunk-ECK465AY.js +5614 -0
- package/dist/chunk-EGY4KDBW.js +5149 -0
- package/dist/chunk-EVQERRCP.js +21369 -0
- package/dist/chunk-EZHT2RLJ.js +1447 -0
- package/dist/chunk-F55NNH2F.js +6484 -0
- package/dist/chunk-G5C6E6PJ.js +9063 -0
- package/dist/chunk-GZWKCIYN.js +3319 -0
- package/dist/chunk-IYHTITNZ.js +45 -0
- package/dist/chunk-LH3QPVN6.js +9869 -0
- package/dist/chunk-MLDUKBU3.js +2426 -0
- package/dist/chunk-N3UJT2NJ.js +3 -0
- package/dist/chunk-OWJZYYMG.js +185 -0
- package/dist/chunk-RA24J4QM.js +3717 -0
- package/dist/chunk-ZJYO7OLO.js +514 -0
- package/dist/client-OWIOFBKS.js +54 -0
- package/dist/dist-2G3QBGID.js +47 -0
- package/dist/dvm.js +56008 -0
- package/dist/esm-RQLHAH2K.js +5183 -0
- package/dist/internal-QFQ7MJ5V.js +1228 -0
- package/dist/mine.wasm-DNBKYCTQ.js +12 -0
- package/dist/payout-reporter-3UB5WRCV-XTVZFIAO.js +17 -0
- package/dist/pocket-refill-PQ5ZVSBY.js +129 -0
- package/dist/revenue-reporter-JIKUPXOK-TYUBTF4P.js +11 -0
- package/dist/secp256k1-JLZEQ2H7.js +19 -0
- package/dist/tempo-lifecycle-SQL3KLEZ-AATA2SKI.js +28 -0
- package/dist/tempo-wallet-QOLEIPCV-SWCXRBDS.js +33 -0
- package/dist/x402-FTG2GRAQ-UGAUMUL6.js +80 -0
- package/package.json +63 -6
- package/skills/dvm/SKILL.md +71 -0
|
@@ -0,0 +1,1815 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __dvmCreateRequire } from "node:module";
|
|
3
|
+
const require = __dvmCreateRequire(import.meta.url);
|
|
4
|
+
import {
|
|
5
|
+
BTC_RATE_FILE,
|
|
6
|
+
CREDITS_FILE,
|
|
7
|
+
DvmError,
|
|
8
|
+
ensureConfigDir,
|
|
9
|
+
ensureConfigSubdir,
|
|
10
|
+
require_proper_lockfile
|
|
11
|
+
} from "./chunk-EGY4KDBW.js";
|
|
12
|
+
import {
|
|
13
|
+
__toESM
|
|
14
|
+
} from "./chunk-IYHTITNZ.js";
|
|
15
|
+
|
|
16
|
+
// node_modules/@dvmkit/sdk/dist/chunk-AT6V3SY7.js
|
|
17
|
+
var InvalidFxRateError = class extends Error {
|
|
18
|
+
code = "invalid_fx_rate";
|
|
19
|
+
ratePerBtc;
|
|
20
|
+
constructor(ratePerBtc) {
|
|
21
|
+
super(
|
|
22
|
+
`invalid fx rate ${String(ratePerBtc)} \u2014 expected a finite positive number of fiat per BTC`
|
|
23
|
+
);
|
|
24
|
+
this.ratePerBtc = ratePerBtc;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
function fiatToSatsCeil(amount, ratePerBtc) {
|
|
28
|
+
if (!Number.isFinite(ratePerBtc) || ratePerBtc <= 0) {
|
|
29
|
+
throw new InvalidFxRateError(ratePerBtc);
|
|
30
|
+
}
|
|
31
|
+
if (!Number.isFinite(amount) || amount < 0) return 0;
|
|
32
|
+
return Math.ceil(amount * 1e8 / ratePerBtc);
|
|
33
|
+
}
|
|
34
|
+
function satsToFiat(sats, ratePerBtc) {
|
|
35
|
+
if (!Number.isFinite(ratePerBtc) || ratePerBtc <= 0) {
|
|
36
|
+
throw new InvalidFxRateError(ratePerBtc);
|
|
37
|
+
}
|
|
38
|
+
return sats / 1e8 * ratePerBtc;
|
|
39
|
+
}
|
|
40
|
+
var InvalidUsdPriceError = class extends Error {
|
|
41
|
+
constructor(field, value, detail) {
|
|
42
|
+
super(`${field}: ${detail}`);
|
|
43
|
+
this.field = field;
|
|
44
|
+
this.value = value;
|
|
45
|
+
this.name = "InvalidUsdPriceError";
|
|
46
|
+
}
|
|
47
|
+
field;
|
|
48
|
+
value;
|
|
49
|
+
code = "invalid_usd_price";
|
|
50
|
+
};
|
|
51
|
+
function parseUsdPrice(value, field) {
|
|
52
|
+
if (!USD_PRICE_RE.test(value)) {
|
|
53
|
+
throw new InvalidUsdPriceError(
|
|
54
|
+
field,
|
|
55
|
+
value,
|
|
56
|
+
`${JSON.stringify(value)} is not a USD price literal. Use a "$X.XX" string, e.g. "$0.05".`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
const usd = parseFloat(value.slice(1));
|
|
60
|
+
if (!Number.isFinite(usd) || usd < MIN_USD_PRICE) {
|
|
61
|
+
throw new InvalidUsdPriceError(
|
|
62
|
+
field,
|
|
63
|
+
value,
|
|
64
|
+
`${JSON.stringify(value)} is below ${MIN_USD_PRICE_LITERAL}, the smallest price the wire can carry \u2014 every price surface rounds to four decimals, so this would advertise as $0 and then charge anyway. Charge at least ${MIN_USD_PRICE_LITERAL}, or omit the price for a free capability.`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
if (roundUsd(usd) !== usd) {
|
|
68
|
+
throw new InvalidUsdPriceError(
|
|
69
|
+
field,
|
|
70
|
+
value,
|
|
71
|
+
`${JSON.stringify(value)} carries more than four decimal places. Every price surface rounds to four, so this would advertise ${formatUsd(roundUsd(usd))} and charge something else. Use at most four decimals.`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (!Number.isSafeInteger(Math.round(usd * 1e6))) {
|
|
75
|
+
throw new InvalidUsdPriceError(
|
|
76
|
+
field,
|
|
77
|
+
value,
|
|
78
|
+
`${JSON.stringify(value)} is too large to denominate. Use an amount under $9,007,199,254.`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return usd;
|
|
82
|
+
}
|
|
83
|
+
function roundUsd(usd) {
|
|
84
|
+
return Math.round(usd * 1e4) / 1e4;
|
|
85
|
+
}
|
|
86
|
+
function formatUsd(usd) {
|
|
87
|
+
if (usd === 0) return "$0.00";
|
|
88
|
+
if (usd >= 0.01) return `$${usd.toFixed(2)}`;
|
|
89
|
+
return `$${usd.toFixed(4)}`;
|
|
90
|
+
}
|
|
91
|
+
function formatFiat(amount, currency) {
|
|
92
|
+
const code = currency.toUpperCase();
|
|
93
|
+
const symbol = FIAT_SYMBOLS[currency] ?? "";
|
|
94
|
+
const digits = currency === "jpy" ? 0 : amount >= 0.01 || amount === 0 ? 2 : 4;
|
|
95
|
+
const body = `${amount.toFixed(digits)} ${code}`;
|
|
96
|
+
return symbol ? `${symbol}${body}` : body;
|
|
97
|
+
}
|
|
98
|
+
var USD_PRICE_RE = /^\$\d+(\.\d+)?$/;
|
|
99
|
+
var MIN_USD_PRICE = 1e-4;
|
|
100
|
+
var MIN_USD_PRICE_LITERAL = '"$0.0001"';
|
|
101
|
+
var FIAT_SYMBOLS = {
|
|
102
|
+
usd: "$",
|
|
103
|
+
eur: "\u20AC",
|
|
104
|
+
gbp: "\xA3",
|
|
105
|
+
jpy: "\xA5"
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// node_modules/@dvmkit/sdk/dist/chunk-5URG56JJ.js
|
|
109
|
+
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
110
|
+
import { dirname } from "path";
|
|
111
|
+
var IMPLICIT_CREDIT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
112
|
+
var COINGECKO_SIMPLE_PRICE_URL = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,usd-coin&vs_currencies=usd";
|
|
113
|
+
var COINGECKO_BTC_USD_URL = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd";
|
|
114
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
115
|
+
var DEFAULT_USER_AGENT = "dvmkit-platform/1.0 (+https://dvmkit.com)";
|
|
116
|
+
async function fetchCoinGeckoSpot(opts) {
|
|
117
|
+
const body = await fetchCoinGeckoBody(opts, COINGECKO_SIMPLE_PRICE_URL);
|
|
118
|
+
const btc = body.bitcoin?.usd;
|
|
119
|
+
const usdc = body["usd-coin"]?.usd;
|
|
120
|
+
if (!isPositiveNumber(btc)) {
|
|
121
|
+
throw new Error("coingecko response missing bitcoin.usd");
|
|
122
|
+
}
|
|
123
|
+
if (!isPositiveNumber(usdc)) {
|
|
124
|
+
throw new Error("coingecko response missing usd-coin.usd");
|
|
125
|
+
}
|
|
126
|
+
return { btc_usd: btc, usdc_usd: usdc, as_of: (/* @__PURE__ */ new Date()).toISOString() };
|
|
127
|
+
}
|
|
128
|
+
async function fetchCoinGeckoBtcUsd(opts) {
|
|
129
|
+
const body = await fetchCoinGeckoBody(opts, COINGECKO_BTC_USD_URL);
|
|
130
|
+
const btc = body.bitcoin?.usd;
|
|
131
|
+
if (!isPositiveNumber(btc)) {
|
|
132
|
+
throw new Error("coingecko response missing bitcoin.usd");
|
|
133
|
+
}
|
|
134
|
+
return { btc_usd: btc, as_of: (/* @__PURE__ */ new Date()).toISOString() };
|
|
135
|
+
}
|
|
136
|
+
async function fetchCoinGeckoBody(opts, defaultUrl) {
|
|
137
|
+
const url = opts?.url ?? defaultUrl;
|
|
138
|
+
const fetchImpl = opts?.fetchImpl ?? fetch;
|
|
139
|
+
const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
140
|
+
const userAgent = opts?.userAgent ?? DEFAULT_USER_AGENT;
|
|
141
|
+
const res = await fetchImpl(url, {
|
|
142
|
+
headers: { "User-Agent": userAgent, Accept: "application/json" },
|
|
143
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
144
|
+
});
|
|
145
|
+
if (!res.ok) {
|
|
146
|
+
throw new Error(`coingecko returned HTTP ${res.status.toString()}`);
|
|
147
|
+
}
|
|
148
|
+
return await res.json();
|
|
149
|
+
}
|
|
150
|
+
function isPositiveNumber(v) {
|
|
151
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
152
|
+
}
|
|
153
|
+
function msatsToUsd(msats, rate) {
|
|
154
|
+
return msats / 1e11 * rate;
|
|
155
|
+
}
|
|
156
|
+
function usdToMsats(usd, rate) {
|
|
157
|
+
return Math.round(usd / rate * 1e11);
|
|
158
|
+
}
|
|
159
|
+
function msatsToUsdCents(msats, btcPriceUsd) {
|
|
160
|
+
const usd = msatsToUsd(msats, btcPriceUsd);
|
|
161
|
+
return Math.round(usd * 100);
|
|
162
|
+
}
|
|
163
|
+
function msatsToUsdc(msats, btcUsdRate) {
|
|
164
|
+
const usd = msatsToUsd(msats, btcUsdRate);
|
|
165
|
+
return Math.ceil(usd * 1e6);
|
|
166
|
+
}
|
|
167
|
+
function usdcToMsats(usdc, btcUsdRate) {
|
|
168
|
+
return usdToMsats(usdc, btcUsdRate);
|
|
169
|
+
}
|
|
170
|
+
function formatSats(msats) {
|
|
171
|
+
if (msats === 0) return "0 sats";
|
|
172
|
+
if (msats < 1e3) return `${msats.toLocaleString("en-US")} msats`;
|
|
173
|
+
if (msats % 1e3 === 0) return `${(msats / 1e3).toLocaleString("en-US")} sats`;
|
|
174
|
+
return `${Math.round(msats / 1e3 * 100) / 100} sats`;
|
|
175
|
+
}
|
|
176
|
+
function formatAmount(msats, rate, opts) {
|
|
177
|
+
const usd = msatsToUsd(msats, rate);
|
|
178
|
+
const base = `~$${formatUsd2(usd)} (${formatSats(msats)})`;
|
|
179
|
+
return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(usd)}`;
|
|
180
|
+
}
|
|
181
|
+
function formatPaymentAmount(msats, fiat, opts) {
|
|
182
|
+
if (!fiat || fiat.amount <= 0) return formatAmountBestEffort(msats, opts);
|
|
183
|
+
const base = `${formatFiat(fiat.amount, fiat.currency)} (${formatSats(msats)})`;
|
|
184
|
+
return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(fiat.amount, fiat.currency)}`;
|
|
185
|
+
}
|
|
186
|
+
var COST_ANCHOR_BANDS = {
|
|
187
|
+
usd: [0.01, 0.1, 1, 10],
|
|
188
|
+
eur: [0.01, 0.1, 1, 10],
|
|
189
|
+
gbp: [0.01, 0.1, 1, 10],
|
|
190
|
+
jpy: [1, 10, 100, 1500]
|
|
191
|
+
};
|
|
192
|
+
function costAnchor(amount, currency = "usd") {
|
|
193
|
+
const bands = COST_ANCHOR_BANDS[currency] ?? COST_ANCHOR_BANDS.usd;
|
|
194
|
+
if (amount < bands[0]) return "fraction of a cent";
|
|
195
|
+
if (amount <= bands[1]) return "comparable to an API call";
|
|
196
|
+
if (amount <= bands[2]) return "comparable to a ChatGPT query";
|
|
197
|
+
if (amount <= bands[3]) return "comparable to a coffee";
|
|
198
|
+
return "significant purchase \u2014 review carefully";
|
|
199
|
+
}
|
|
200
|
+
function monetaryJson(msats, rate) {
|
|
201
|
+
const usd = msatsToUsd(msats, rate);
|
|
202
|
+
return {
|
|
203
|
+
msats,
|
|
204
|
+
usd: Math.round(usd * 100) / 100,
|
|
205
|
+
anchor: costAnchor(usd),
|
|
206
|
+
display: formatAmount(msats, rate)
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function formatUsd2(usd) {
|
|
210
|
+
if (usd === 0) return "0.00";
|
|
211
|
+
if (usd >= 0.01) return usd.toFixed(2);
|
|
212
|
+
const digits = Math.max(2, -Math.floor(Math.log10(usd)) + 1);
|
|
213
|
+
return usd.toFixed(digits);
|
|
214
|
+
}
|
|
215
|
+
function formatUsdcMicrounits(microunits) {
|
|
216
|
+
const value = typeof microunits === "bigint" ? microunits : BigInt(microunits);
|
|
217
|
+
const whole = value / 1000000n;
|
|
218
|
+
const fraction = (value % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
219
|
+
return `${whole}.${fraction.padEnd(2, "0") || "00"}`;
|
|
220
|
+
}
|
|
221
|
+
function parseBudget(budget, rate) {
|
|
222
|
+
const value = assertValidBudget(budget);
|
|
223
|
+
return budget.startsWith("$") ? usdToMsats(value, rate) : value;
|
|
224
|
+
}
|
|
225
|
+
function assertValidBudget(budget) {
|
|
226
|
+
const value = budget.startsWith("$") ? parseFloat(budget.slice(1)) : parseInt(budget, 10);
|
|
227
|
+
if (isNaN(value)) throw new Error(`Invalid budget: ${budget}`);
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
async function fetchBtcUsdRate() {
|
|
231
|
+
if (memRate && Date.now() - memTime < CACHE_TTL) {
|
|
232
|
+
return memRate;
|
|
233
|
+
}
|
|
234
|
+
const disk = readDiskCache();
|
|
235
|
+
if (disk) {
|
|
236
|
+
memRate = disk;
|
|
237
|
+
memTime = Date.now();
|
|
238
|
+
return disk;
|
|
239
|
+
}
|
|
240
|
+
const rate = await fetchFromApi();
|
|
241
|
+
memRate = rate;
|
|
242
|
+
memTime = Date.now();
|
|
243
|
+
writeDiskCache(rate);
|
|
244
|
+
return rate;
|
|
245
|
+
}
|
|
246
|
+
function getLastKnownBtcRate() {
|
|
247
|
+
if (memRate && memTime > 0) return { rate: memRate, cachedAt: memTime };
|
|
248
|
+
return readDiskCacheStale();
|
|
249
|
+
}
|
|
250
|
+
function formatStaleness(cachedAt, now = Date.now()) {
|
|
251
|
+
const ageMs = Math.max(0, now - cachedAt);
|
|
252
|
+
const seconds = Math.floor(ageMs / 1e3);
|
|
253
|
+
if (seconds < 60) return `${seconds}s ago`;
|
|
254
|
+
const minutes = Math.floor(seconds / 60);
|
|
255
|
+
if (minutes < 60) return `${minutes} min ago`;
|
|
256
|
+
const hours = Math.floor(minutes / 60);
|
|
257
|
+
if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
|
|
258
|
+
const days = Math.floor(hours / 24);
|
|
259
|
+
return `${days} day${days === 1 ? "" : "s"} ago`;
|
|
260
|
+
}
|
|
261
|
+
function formatAmountBestEffort(msats, opts) {
|
|
262
|
+
const m = msats ?? 0;
|
|
263
|
+
const cached = getLastKnownBtcRate();
|
|
264
|
+
if (cached === null) return `${Math.round(m / 1e3)} sats`;
|
|
265
|
+
const base = formatAmount(m, cached.rate, opts);
|
|
266
|
+
if (Date.now() - cached.cachedAt < CACHE_TTL) return base;
|
|
267
|
+
return `${base} (rate cached ${formatStaleness(cached.cachedAt)})`;
|
|
268
|
+
}
|
|
269
|
+
var CACHE_TTL = 5 * 60 * 1e3;
|
|
270
|
+
var CACHE_FILE = BTC_RATE_FILE;
|
|
271
|
+
var memRate = null;
|
|
272
|
+
var memTime = 0;
|
|
273
|
+
function readDiskCache() {
|
|
274
|
+
try {
|
|
275
|
+
if (!existsSync(CACHE_FILE)) return null;
|
|
276
|
+
const data = JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
|
|
277
|
+
if (Date.now() - data.timestamp >= CACHE_TTL) return null;
|
|
278
|
+
if (!isPlausibleBtcUsdRate(data.rate)) return null;
|
|
279
|
+
return data.rate;
|
|
280
|
+
} catch {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function readDiskCacheStale() {
|
|
285
|
+
try {
|
|
286
|
+
if (!existsSync(CACHE_FILE)) return null;
|
|
287
|
+
const data = JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
|
|
288
|
+
if (!isPlausibleBtcUsdRate(data.rate)) return null;
|
|
289
|
+
return { rate: data.rate, cachedAt: data.timestamp };
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function writeDiskCache(rate) {
|
|
295
|
+
try {
|
|
296
|
+
ensureConfigSubdir(dirname(CACHE_FILE));
|
|
297
|
+
writeFileSync(CACHE_FILE, JSON.stringify({ rate, timestamp: Date.now() }));
|
|
298
|
+
} catch {
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
var MAX_PLAUSIBLE_BTC_USD = 1e7;
|
|
302
|
+
function isPlausibleBtcUsdRate(rate) {
|
|
303
|
+
return typeof rate === "number" && Number.isFinite(rate) && rate > 0 && rate < MAX_PLAUSIBLE_BTC_USD;
|
|
304
|
+
}
|
|
305
|
+
async function fetchFromApi() {
|
|
306
|
+
const spot = await fetchCoinGeckoBtcUsd();
|
|
307
|
+
const rate = spot.btc_usd;
|
|
308
|
+
if (!isPlausibleBtcUsdRate(rate)) {
|
|
309
|
+
throw new Error(`implausible BTC/USD rate from upstream: ${String(rate)}`);
|
|
310
|
+
}
|
|
311
|
+
return rate;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// node_modules/@dvmkit/sdk/dist/chunk-KSQEFVFJ.js
|
|
315
|
+
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
|
|
316
|
+
import { writeSync } from "fs";
|
|
317
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
|
|
318
|
+
import { dirname as dirname2 } from "path";
|
|
319
|
+
var _traceId = null;
|
|
320
|
+
function setOutputTraceId(id) {
|
|
321
|
+
_traceId = id;
|
|
322
|
+
}
|
|
323
|
+
function getOutputTraceId() {
|
|
324
|
+
return _traceId;
|
|
325
|
+
}
|
|
326
|
+
function json(data) {
|
|
327
|
+
const out = _traceId !== null && typeof data === "object" && data !== null && !Array.isArray(data) && !("trace_id" in data) ? { trace_id: _traceId, ...data } : data;
|
|
328
|
+
writeAllSync(1, JSON.stringify(out) + "\n");
|
|
329
|
+
}
|
|
330
|
+
function info(msg) {
|
|
331
|
+
writeAllSync(2, msg + "\n");
|
|
332
|
+
}
|
|
333
|
+
function raw(msg) {
|
|
334
|
+
writeAllSync(1, msg + "\n");
|
|
335
|
+
}
|
|
336
|
+
function progress(event) {
|
|
337
|
+
writeAllSync(2, JSON.stringify(event) + "\n");
|
|
338
|
+
}
|
|
339
|
+
function writeAllSync(fd, text) {
|
|
340
|
+
const buf = Buffer.from(text, "utf8");
|
|
341
|
+
let offset = 0;
|
|
342
|
+
while (offset < buf.length) {
|
|
343
|
+
try {
|
|
344
|
+
offset += writeSync(fd, buf, offset, buf.length - offset);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
const code = err.code;
|
|
347
|
+
if (code === "EAGAIN" || code === "EINTR") continue;
|
|
348
|
+
throw err;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
var RAIL_FLAGS = ["cashu", "tempo", "x402"];
|
|
353
|
+
var ADVERTISED_AMOUNT_TOLERANCE_BPS = 1000n;
|
|
354
|
+
function maxAdvertisedMicro(localMicro) {
|
|
355
|
+
return localMicro * (10000n + ADVERTISED_AMOUNT_TOLERANCE_BPS) / 10000n;
|
|
356
|
+
}
|
|
357
|
+
function withinAdvertisedTolerance(advertisedMicro, localMicro) {
|
|
358
|
+
return advertisedMicro * 10000n <= localMicro * (10000n + ADVERTISED_AMOUNT_TOLERANCE_BPS);
|
|
359
|
+
}
|
|
360
|
+
var SUPPORTED_PROTOCOL_VERSION = 1;
|
|
361
|
+
function parseCreditTerms(raw2) {
|
|
362
|
+
if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
|
|
363
|
+
const credit = raw2;
|
|
364
|
+
if (typeof credit.min_micro !== "number" || typeof credit.max_micro !== "number" || typeof credit.ttl_ms !== "number" || typeof credit.currency !== "string" || !Array.isArray(credit.funding) || !credit.funding.every((method) => typeof method === "string") || credit.lightning_min_micro !== void 0 && typeof credit.lightning_min_micro !== "number")
|
|
365
|
+
return void 0;
|
|
366
|
+
const tempo = credit.tempo === void 0 ? void 0 : parseCreditTempoTerms(credit.tempo);
|
|
367
|
+
if (credit.tempo !== void 0 && !tempo) return void 0;
|
|
368
|
+
const x402 = credit.x402 === void 0 ? void 0 : parseCreditX402Terms(credit.x402);
|
|
369
|
+
if (credit.x402 !== void 0 && !x402) return void 0;
|
|
370
|
+
return {
|
|
371
|
+
min_micro: credit.min_micro,
|
|
372
|
+
max_micro: credit.max_micro,
|
|
373
|
+
ttl_ms: credit.ttl_ms,
|
|
374
|
+
currency: credit.currency,
|
|
375
|
+
funding: [...credit.funding],
|
|
376
|
+
...tempo && { tempo },
|
|
377
|
+
...x402 && { x402 },
|
|
378
|
+
...typeof credit.lightning_min_micro === "number" && {
|
|
379
|
+
lightning_min_micro: credit.lightning_min_micro
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function parseCreditMenu(raw2) {
|
|
384
|
+
const terms = parseCreditTerms(raw2);
|
|
385
|
+
if (!terms) return void 0;
|
|
386
|
+
const credit = raw2;
|
|
387
|
+
return {
|
|
388
|
+
...terms,
|
|
389
|
+
...typeof credit.credit_id === "string" && { credit_id: credit.credit_id },
|
|
390
|
+
...typeof credit.balance_micro === "number" && { balance_micro: credit.balance_micro },
|
|
391
|
+
...typeof credit.remaining_micro === "number" && {
|
|
392
|
+
remaining_micro: credit.remaining_micro
|
|
393
|
+
},
|
|
394
|
+
...typeof credit.expiry_ms === "number" && { expiry_ms: credit.expiry_ms }
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function parseCreditTempoTerms(raw2) {
|
|
398
|
+
if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
|
|
399
|
+
const block = raw2;
|
|
400
|
+
if (!Array.isArray(block.methods) || !block.methods.every(isCreditTempoMethod)) return void 0;
|
|
401
|
+
if (block.withheld !== void 0 && (!Array.isArray(block.withheld) || !block.withheld.every(isCreditTempoWithheldMethod)))
|
|
402
|
+
return void 0;
|
|
403
|
+
return {
|
|
404
|
+
methods: block.methods.map((method) => ({
|
|
405
|
+
method: method.method,
|
|
406
|
+
intent: method.intent
|
|
407
|
+
})),
|
|
408
|
+
...Array.isArray(block.withheld) && {
|
|
409
|
+
withheld: block.withheld.map((method) => ({
|
|
410
|
+
method: method.method,
|
|
411
|
+
intent: method.intent,
|
|
412
|
+
reason: method.reason
|
|
413
|
+
}))
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
function isCreditTempoMethod(raw2) {
|
|
418
|
+
return !!raw2 && typeof raw2 === "object" && typeof raw2.method === "string" && (raw2.intent === "charge" || raw2.intent === "session");
|
|
419
|
+
}
|
|
420
|
+
function isCreditTempoWithheldMethod(raw2) {
|
|
421
|
+
return isCreditTempoMethod(raw2) && typeof raw2.reason === "string";
|
|
422
|
+
}
|
|
423
|
+
function parseCreditX402Terms(raw2) {
|
|
424
|
+
if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
|
|
425
|
+
const schemes = raw2.schemes;
|
|
426
|
+
if (!Array.isArray(schemes) || !schemes.every(
|
|
427
|
+
(entry) => !!entry && typeof entry === "object" && typeof entry.scheme === "string" && typeof entry.network === "string"
|
|
428
|
+
))
|
|
429
|
+
return void 0;
|
|
430
|
+
return {
|
|
431
|
+
schemes: schemes.map((entry) => ({
|
|
432
|
+
scheme: entry.scheme,
|
|
433
|
+
network: entry.network
|
|
434
|
+
}))
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
function withCreditLock(fn, opts = {}) {
|
|
438
|
+
if (lockDepth > 0) {
|
|
439
|
+
lockDepth += 1;
|
|
440
|
+
try {
|
|
441
|
+
return rejectAsyncBody(fn());
|
|
442
|
+
} finally {
|
|
443
|
+
lockDepth -= 1;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const release = acquireCreditLock(opts);
|
|
447
|
+
lockDepth = 1;
|
|
448
|
+
try {
|
|
449
|
+
return rejectAsyncBody(fn());
|
|
450
|
+
} finally {
|
|
451
|
+
lockDepth = 0;
|
|
452
|
+
try {
|
|
453
|
+
release();
|
|
454
|
+
} catch {
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function normalizeCreditEndpoint(endpoint) {
|
|
459
|
+
try {
|
|
460
|
+
return new URL(endpoint).origin;
|
|
461
|
+
} catch {
|
|
462
|
+
return endpoint.replace(/\/+$/, "");
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function dvmLocationIdentity(record) {
|
|
466
|
+
if (typeof record.dvmId !== "string" || record.dvmId.length === 0) return void 0;
|
|
467
|
+
const pubkey = typeof record.attestedBuilderPubkey === "string" ? record.attestedBuilderPubkey.trim().toLowerCase() : "";
|
|
468
|
+
if (!/^[0-9a-f]{64}$/.test(pubkey)) return void 0;
|
|
469
|
+
return { dvmId: record.dvmId, builderPubkey: pubkey };
|
|
470
|
+
}
|
|
471
|
+
function findDvmLocated(records, args) {
|
|
472
|
+
const where = args.where ?? (() => true);
|
|
473
|
+
const identity = args.identity;
|
|
474
|
+
if (identity) {
|
|
475
|
+
const attested = records.find(
|
|
476
|
+
(record) => where(record) && matchesDvmIdentity(record, identity)
|
|
477
|
+
);
|
|
478
|
+
if (attested) return attested;
|
|
479
|
+
}
|
|
480
|
+
return records.find(
|
|
481
|
+
(record) => where(record) && matchesDvmOrigin(record, args.endpoint, identity)
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
function attachDvmLocation(record, endpoint, identity) {
|
|
485
|
+
let changed = false;
|
|
486
|
+
if (identity) {
|
|
487
|
+
if (record.dvmId !== identity.dvmId) {
|
|
488
|
+
record.dvmId = identity.dvmId;
|
|
489
|
+
changed = true;
|
|
490
|
+
}
|
|
491
|
+
if (record.attestedBuilderPubkey !== identity.builderPubkey) {
|
|
492
|
+
record.attestedBuilderPubkey = identity.builderPubkey;
|
|
493
|
+
changed = true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (endpoint !== record.endpoint && !dvmLocationOrigins(record).includes(endpoint)) {
|
|
497
|
+
record.endpointAliases = [...record.endpointAliases ?? [], endpoint];
|
|
498
|
+
changed = true;
|
|
499
|
+
}
|
|
500
|
+
return changed;
|
|
501
|
+
}
|
|
502
|
+
function dvmLocationOrigins(record) {
|
|
503
|
+
const aliases = Array.isArray(record.endpointAliases) ? record.endpointAliases.filter((endpoint) => typeof endpoint === "string") : [];
|
|
504
|
+
const primary = typeof record.endpoint === "string" ? [record.endpoint] : [];
|
|
505
|
+
return [...primary, ...aliases].map(normalizeCreditEndpoint);
|
|
506
|
+
}
|
|
507
|
+
function fundingReachableAt(funding, endpoint, credits) {
|
|
508
|
+
const at = normalizeCreditEndpoint(funding.endpoint);
|
|
509
|
+
const named = normalizeCreditEndpoint(endpoint);
|
|
510
|
+
if (at === named) return true;
|
|
511
|
+
const record = credits.find(
|
|
512
|
+
(c) => c.callerPubkey === funding.callerPubkey && c.creditId === funding.creditId
|
|
513
|
+
);
|
|
514
|
+
if (!record) return false;
|
|
515
|
+
const origins = dvmLocationOrigins(record);
|
|
516
|
+
return origins.includes(at) && origins.includes(named);
|
|
517
|
+
}
|
|
518
|
+
function pendingDrainFor(record, creditId) {
|
|
519
|
+
return record?.pendingDrains?.find((d) => d.creditId === creditId);
|
|
520
|
+
}
|
|
521
|
+
function pendingDrainById(record, drainId) {
|
|
522
|
+
return record?.pendingDrains?.find((d) => d.drainId === drainId);
|
|
523
|
+
}
|
|
524
|
+
function loadCredit(endpoint, callerPubkey, identity) {
|
|
525
|
+
return withCreditLock(() => {
|
|
526
|
+
const key = normalizeCreditEndpoint(endpoint);
|
|
527
|
+
const store = loadStore();
|
|
528
|
+
const record = findDvmLocated(store.credits, {
|
|
529
|
+
endpoint: key,
|
|
530
|
+
...identity ? { identity } : {},
|
|
531
|
+
where: (c) => c.callerPubkey === callerPubkey
|
|
532
|
+
});
|
|
533
|
+
if (record && attachDvmLocation(record, key, identity)) saveStore(store);
|
|
534
|
+
return record;
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
function clearCreditSelection(endpoint, callerPubkey, creditId, identity) {
|
|
538
|
+
return withCreditLock(() => {
|
|
539
|
+
const key = normalizeCreditEndpoint(endpoint);
|
|
540
|
+
const store = loadStore();
|
|
541
|
+
const record = findDvmLocated(store.credits, {
|
|
542
|
+
endpoint: key,
|
|
543
|
+
...identity ? { identity } : {},
|
|
544
|
+
where: (candidate) => candidate.callerPubkey === callerPubkey && candidate.creditId === creditId
|
|
545
|
+
});
|
|
546
|
+
if (!record) {
|
|
547
|
+
throw new DvmError(
|
|
548
|
+
"credit_not_found",
|
|
549
|
+
`Credit ${creditId} is not the selected local credit at ${key}.`
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
attachDvmLocation(record, key, identity);
|
|
553
|
+
record.selectionCleared = true;
|
|
554
|
+
record.updatedAt = Date.now();
|
|
555
|
+
saveStore(store);
|
|
556
|
+
return structuredClone(record);
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
function listCredits() {
|
|
560
|
+
return withCreditLock(() => [...loadStore().credits].sort((a, b) => b.updatedAt - a.updatedAt));
|
|
561
|
+
}
|
|
562
|
+
function listImplicitCredits(now = Date.now()) {
|
|
563
|
+
return withCreditLock(() => {
|
|
564
|
+
const store = loadStore();
|
|
565
|
+
const aged = ageImplicitCredits(store.implicitCredits, now);
|
|
566
|
+
const capped = capLostImplicitCredits(store.implicitCredits);
|
|
567
|
+
if (aged || capped.changed) {
|
|
568
|
+
store.implicitCredits = capped.credits;
|
|
569
|
+
saveStore(store);
|
|
570
|
+
}
|
|
571
|
+
return [...store.implicitCredits].sort(compareImplicitCredits);
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
function loadImplicitCredits(endpoint, callerPubkey, identity, now = Date.now()) {
|
|
575
|
+
return withCreditLock(() => {
|
|
576
|
+
const store = loadStore();
|
|
577
|
+
const key = normalizeCreditEndpoint(endpoint);
|
|
578
|
+
let changed = ageImplicitCredits(store.implicitCredits, now);
|
|
579
|
+
const matches = store.implicitCredits.filter(
|
|
580
|
+
(record) => Boolean(
|
|
581
|
+
findDvmLocated([record], {
|
|
582
|
+
endpoint: key,
|
|
583
|
+
...identity ? { identity } : {},
|
|
584
|
+
where: (candidate) => candidate.callerPubkey === callerPubkey
|
|
585
|
+
})
|
|
586
|
+
)
|
|
587
|
+
);
|
|
588
|
+
for (const record of matches) {
|
|
589
|
+
changed = attachDvmLocation(record, key, identity) || changed;
|
|
590
|
+
}
|
|
591
|
+
const capped = capLostImplicitCredits(store.implicitCredits);
|
|
592
|
+
if (changed || capped.changed) {
|
|
593
|
+
store.implicitCredits = capped.credits;
|
|
594
|
+
saveStore(store);
|
|
595
|
+
}
|
|
596
|
+
return matches.filter((record) => store.implicitCredits.includes(record)).sort(compareImplicitCredits);
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
function markImplicitCreditLost(args) {
|
|
600
|
+
return withCreditLock(() => {
|
|
601
|
+
const store = loadStore();
|
|
602
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
603
|
+
const record = findDvmLocated(store.implicitCredits, {
|
|
604
|
+
endpoint: key,
|
|
605
|
+
...args.identity ? { identity: args.identity } : {},
|
|
606
|
+
where: (candidate) => candidate.callerPubkey === args.callerPubkey && candidate.creditId === args.creditId
|
|
607
|
+
});
|
|
608
|
+
if (!record) return void 0;
|
|
609
|
+
attachDvmLocation(record, key, args.identity);
|
|
610
|
+
record.status = "lost";
|
|
611
|
+
record.lossReason = args.reason;
|
|
612
|
+
record.updatedAt = args.now ?? Date.now();
|
|
613
|
+
const capped = capLostImplicitCredits(store.implicitCredits);
|
|
614
|
+
store.implicitCredits = capped.credits;
|
|
615
|
+
saveStore(store);
|
|
616
|
+
return store.implicitCredits.includes(record) ? record : void 0;
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
function listFundingMenuSnapshots() {
|
|
620
|
+
return withCreditLock(
|
|
621
|
+
() => [...loadStore().fundingMenuSnapshots].sort((a, b) => b.observedAt - a.observedAt)
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
function recordFundingMenuSnapshot(args) {
|
|
625
|
+
const menu = parseCreditMenu(args.menu);
|
|
626
|
+
if (!menu) return;
|
|
627
|
+
withCreditLock(() => {
|
|
628
|
+
const store = loadStore();
|
|
629
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
630
|
+
const previous = findDvmLocated(store.fundingMenuSnapshots, {
|
|
631
|
+
endpoint: key,
|
|
632
|
+
...args.identity ? { identity: args.identity } : {},
|
|
633
|
+
where: (entry) => entry.callerPubkey === args.callerPubkey
|
|
634
|
+
});
|
|
635
|
+
const index = previous ? store.fundingMenuSnapshots.indexOf(previous) : -1;
|
|
636
|
+
const builderPubkey = args.builderPubkey ?? previous?.builderPubkey;
|
|
637
|
+
const snapshot = {
|
|
638
|
+
// The row keeps the origin it was opened at and learns the new spelling
|
|
639
|
+
// as an alias, so a caller who alternates hostnames still reads one menu.
|
|
640
|
+
endpoint: previous?.endpoint ?? key,
|
|
641
|
+
...previous?.endpointAliases ? { endpointAliases: [...previous.endpointAliases] } : {},
|
|
642
|
+
...previous?.dvmId ? { dvmId: previous.dvmId } : {},
|
|
643
|
+
...previous?.attestedBuilderPubkey ? { attestedBuilderPubkey: previous.attestedBuilderPubkey } : {},
|
|
644
|
+
callerPubkey: args.callerPubkey,
|
|
645
|
+
menu,
|
|
646
|
+
observedAt: args.now ?? Date.now(),
|
|
647
|
+
...builderPubkey ? { builderPubkey } : {}
|
|
648
|
+
};
|
|
649
|
+
attachDvmLocation(snapshot, key, args.identity);
|
|
650
|
+
if (index === -1) store.fundingMenuSnapshots.push(snapshot);
|
|
651
|
+
else store.fundingMenuSnapshots[index] = snapshot;
|
|
652
|
+
saveStore(store);
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
function listPendingFundings(args = {}) {
|
|
656
|
+
const endpoint = args.endpoint ? normalizeCreditEndpoint(args.endpoint) : void 0;
|
|
657
|
+
return withCreditLock(() => {
|
|
658
|
+
const store = loadStore();
|
|
659
|
+
return store.pendingFundings.filter(
|
|
660
|
+
(funding) => (!endpoint || fundingReachableAt(funding, endpoint, store.credits)) && (!args.callerPubkey || funding.callerPubkey === args.callerPubkey) && (!args.creditId || funding.creditId === args.creditId)
|
|
661
|
+
).sort((a, b) => a.requestedAt - b.requestedAt);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
function loadPendingFunding(endpoint, callerPubkey, creditId) {
|
|
665
|
+
return listPendingFundings({ endpoint, callerPubkey, ...creditId ? { creditId } : {} })[0];
|
|
666
|
+
}
|
|
667
|
+
function recordPendingFunding(funding) {
|
|
668
|
+
withCreditLock(() => {
|
|
669
|
+
const store = loadStore();
|
|
670
|
+
const normalized = { ...funding, endpoint: normalizeCreditEndpoint(funding.endpoint) };
|
|
671
|
+
const index = store.pendingFundings.findIndex(
|
|
672
|
+
(entry) => entry.callerPubkey === normalized.callerPubkey && entry.creditId === normalized.creditId && entry.fundId === normalized.fundId && fundingReachableAt(entry, normalized.endpoint, store.credits)
|
|
673
|
+
);
|
|
674
|
+
if (index === -1) store.pendingFundings.push(normalized);
|
|
675
|
+
else
|
|
676
|
+
store.pendingFundings[index] = {
|
|
677
|
+
...normalized,
|
|
678
|
+
endpoint: store.pendingFundings[index].endpoint
|
|
679
|
+
};
|
|
680
|
+
saveStore(store);
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
function clearPendingFunding(endpoint, callerPubkey, creditId, fundId) {
|
|
684
|
+
withCreditLock(() => {
|
|
685
|
+
const store = loadStore();
|
|
686
|
+
const normalized = normalizeCreditEndpoint(endpoint);
|
|
687
|
+
const remaining = store.pendingFundings.filter(
|
|
688
|
+
(entry) => !(entry.callerPubkey === callerPubkey && entry.creditId === creditId && entry.fundId === fundId && fundingReachableAt(entry, normalized, store.credits))
|
|
689
|
+
);
|
|
690
|
+
if (remaining.length === store.pendingFundings.length) return;
|
|
691
|
+
saveStore({ ...store, pendingFundings: remaining });
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
function recordFundResponse(args) {
|
|
695
|
+
const now = args.now ?? Date.now();
|
|
696
|
+
return withCreditLock(() => {
|
|
697
|
+
const store = loadStore();
|
|
698
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
699
|
+
let record = findDvmLocated(store.credits, {
|
|
700
|
+
endpoint: key,
|
|
701
|
+
...args.identity ? { identity: args.identity } : {},
|
|
702
|
+
where: (c) => c.callerPubkey === args.callerPubkey
|
|
703
|
+
});
|
|
704
|
+
if (!record) {
|
|
705
|
+
record = {
|
|
706
|
+
endpoint: key,
|
|
707
|
+
...identityFields(args.identity),
|
|
708
|
+
callerPubkey: args.callerPubkey,
|
|
709
|
+
creditId: args.credit.credit_id,
|
|
710
|
+
currency: args.credit.currency,
|
|
711
|
+
balanceMicro: 0,
|
|
712
|
+
remainingMicro: 0,
|
|
713
|
+
ledgerSeq: 0,
|
|
714
|
+
expiryMs: 0,
|
|
715
|
+
targetMicro: args.targetMicro,
|
|
716
|
+
status: "active",
|
|
717
|
+
openedAt: now,
|
|
718
|
+
updatedAt: now
|
|
719
|
+
};
|
|
720
|
+
store.credits.push(record);
|
|
721
|
+
}
|
|
722
|
+
attachDvmLocation(record, key, args.identity);
|
|
723
|
+
adoptCreditId(record, args.credit.credit_id);
|
|
724
|
+
record.currency = args.credit.currency;
|
|
725
|
+
record.balanceMicro = args.credit.balance_micro;
|
|
726
|
+
record.remainingMicro = args.credit.remaining_micro;
|
|
727
|
+
record.ledgerSeq = Math.max(record.ledgerSeq, args.credit.ledger_seq);
|
|
728
|
+
record.expiryMs = args.credit.expiry_ms;
|
|
729
|
+
record.targetMicro = args.targetMicro;
|
|
730
|
+
record.status = args.credit.status === "unbacked" ? "unbacked" : args.credit.expired ? "expired" : "active";
|
|
731
|
+
record.reconciliationPending = args.credit.reconciliation_pending;
|
|
732
|
+
record.updatedAt = now;
|
|
733
|
+
delete record.provisional;
|
|
734
|
+
if (args.sequenced === false) record.unsequencedBalance = true;
|
|
735
|
+
else delete record.unsequencedBalance;
|
|
736
|
+
if (args.menu) record.menu = args.menu;
|
|
737
|
+
if (args.rail) {
|
|
738
|
+
record.rail = args.rail;
|
|
739
|
+
delete record.refillUnavailableRail;
|
|
740
|
+
}
|
|
741
|
+
if (args.x402Instrument) record.x402Instrument = args.x402Instrument;
|
|
742
|
+
if (args.x402ChannelNetwork) record.x402ChannelNetwork = args.x402ChannelNetwork;
|
|
743
|
+
if (args.builderPubkey) record.builderPubkey = args.builderPubkey;
|
|
744
|
+
if (args.select) delete record.selectionCleared;
|
|
745
|
+
delete record.discrepancy;
|
|
746
|
+
saveStore(store);
|
|
747
|
+
return record;
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
function recordBalanceResponse(args) {
|
|
751
|
+
const now = args.now ?? Date.now();
|
|
752
|
+
return withCreditLock(() => {
|
|
753
|
+
const existing = loadCredit(args.endpoint, args.callerPubkey, args.identity);
|
|
754
|
+
const prepaidCredits = args.credits.filter((credit) => !credit.credit_id.startsWith("imp:"));
|
|
755
|
+
const selectedPrimary = args.primary && !args.primary.credit_id.startsWith("imp:") ? args.primary : void 0;
|
|
756
|
+
const primary = selectedPrimary ?? prepaidCredits.find((credit) => credit.credit_id === existing?.creditId);
|
|
757
|
+
if (!primary) {
|
|
758
|
+
if (existing) {
|
|
759
|
+
mutateCredit(
|
|
760
|
+
{
|
|
761
|
+
endpoint: args.endpoint,
|
|
762
|
+
callerPubkey: args.callerPubkey,
|
|
763
|
+
...args.identity ? { identity: args.identity } : {}
|
|
764
|
+
},
|
|
765
|
+
(record2) => {
|
|
766
|
+
record2.siblingCredits = [];
|
|
767
|
+
return void 0;
|
|
768
|
+
}
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
return existing;
|
|
772
|
+
}
|
|
773
|
+
const record = recordFundResponse({
|
|
774
|
+
endpoint: args.endpoint,
|
|
775
|
+
...args.identity ? { identity: args.identity } : {},
|
|
776
|
+
callerPubkey: args.callerPubkey,
|
|
777
|
+
credit: primary,
|
|
778
|
+
targetMicro: args.targetMicro ?? existing?.targetMicro ?? primary.remaining_micro,
|
|
779
|
+
...args.menu ? { menu: args.menu } : {},
|
|
780
|
+
...args.builderPubkey ? { builderPubkey: args.builderPubkey } : {},
|
|
781
|
+
...args.selectPrimary ? { select: true } : {},
|
|
782
|
+
...args.sequenced === false ? { sequenced: false } : {},
|
|
783
|
+
now
|
|
784
|
+
});
|
|
785
|
+
mutateCredit(
|
|
786
|
+
{
|
|
787
|
+
endpoint: args.endpoint,
|
|
788
|
+
callerPubkey: args.callerPubkey,
|
|
789
|
+
...args.identity ? { identity: args.identity } : {}
|
|
790
|
+
},
|
|
791
|
+
(current) => {
|
|
792
|
+
current.siblingCredits = prepaidCredits.filter((credit) => credit.credit_id !== current.creditId).map((credit) => siblingFromWire(credit, now));
|
|
793
|
+
return void 0;
|
|
794
|
+
}
|
|
795
|
+
);
|
|
796
|
+
return loadCredit(args.endpoint, args.callerPubkey, args.identity) ?? record;
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
function applyReceiptCredit(args) {
|
|
800
|
+
const now = args.now ?? Date.now();
|
|
801
|
+
return withCreditLock(() => {
|
|
802
|
+
const store = loadStore();
|
|
803
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
804
|
+
const record = findDvmLocated(store.credits, {
|
|
805
|
+
endpoint: key,
|
|
806
|
+
...args.identity ? { identity: args.identity } : {},
|
|
807
|
+
where: (c) => c.callerPubkey === args.callerPubkey && c.creditId === args.credit.credit_id
|
|
808
|
+
});
|
|
809
|
+
if (!record) return {};
|
|
810
|
+
attachDvmLocation(record, key, args.identity);
|
|
811
|
+
let mismatch;
|
|
812
|
+
const sequential = args.credit.ledger_seq === record.ledgerSeq + 1;
|
|
813
|
+
if (sequential && args.outcome === "completed" && record.status === "active" && !record.provisional && !record.unsequencedBalance) {
|
|
814
|
+
const expected = record.remainingMicro - args.credit.amount;
|
|
815
|
+
if (args.credit.balance_after !== expected) {
|
|
816
|
+
mismatch = {
|
|
817
|
+
atMs: now,
|
|
818
|
+
expectedMicro: expected,
|
|
819
|
+
reportedMicro: args.credit.balance_after,
|
|
820
|
+
drawId: args.credit.draw_id,
|
|
821
|
+
ledgerSeq: args.credit.ledger_seq,
|
|
822
|
+
...record.lastReceiptJobId ? { priorJobId: record.lastReceiptJobId } : {},
|
|
823
|
+
jobId: args.jobId
|
|
824
|
+
};
|
|
825
|
+
record.discrepancy = mismatch;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
if (args.credit.ledger_seq >= record.ledgerSeq) {
|
|
829
|
+
record.remainingMicro = args.credit.balance_after;
|
|
830
|
+
record.ledgerSeq = args.credit.ledger_seq;
|
|
831
|
+
delete record.unsequencedBalance;
|
|
832
|
+
}
|
|
833
|
+
delete record.provisional;
|
|
834
|
+
if (args.outcome === "completed") record.lastPriceMicro = args.credit.amount;
|
|
835
|
+
if (!mismatch && record.discrepancy && args.credit.ledger_seq > record.discrepancy.ledgerSeq) {
|
|
836
|
+
delete record.discrepancy;
|
|
837
|
+
}
|
|
838
|
+
record.lastReceiptJobId = args.jobId;
|
|
839
|
+
record.updatedAt = now;
|
|
840
|
+
saveStore(store);
|
|
841
|
+
return { credit: record, ...mismatch ? { mismatch } : {} };
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
function applyImplicitReceiptCredit(args) {
|
|
845
|
+
if (!args.credit.credit_id.startsWith("imp:")) return {};
|
|
846
|
+
const now = args.now ?? Date.now();
|
|
847
|
+
return withCreditLock(() => {
|
|
848
|
+
const store = loadStore();
|
|
849
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
850
|
+
let record = findDvmLocated(store.implicitCredits, {
|
|
851
|
+
endpoint: key,
|
|
852
|
+
...args.identity ? { identity: args.identity } : {},
|
|
853
|
+
where: (candidate) => candidate.callerPubkey === args.callerPubkey && candidate.creditId === args.credit.credit_id
|
|
854
|
+
});
|
|
855
|
+
if (!record && (args.outcome === "completed" || args.credit.balance_after <= 0)) return {};
|
|
856
|
+
if (!record) {
|
|
857
|
+
record = {
|
|
858
|
+
endpoint: key,
|
|
859
|
+
...identityFields(args.identity),
|
|
860
|
+
callerPubkey: args.callerPubkey,
|
|
861
|
+
creditId: args.credit.credit_id,
|
|
862
|
+
currency: args.currency,
|
|
863
|
+
remainingMicro: args.credit.balance_after,
|
|
864
|
+
ledgerSeq: args.credit.ledger_seq,
|
|
865
|
+
expiryMs: args.issuedAtMs + IMPLICIT_CREDIT_TTL_MS,
|
|
866
|
+
status: args.issuedAtMs + IMPLICIT_CREDIT_TTL_MS <= now ? "lost" : "active",
|
|
867
|
+
releasedByJobId: args.jobId,
|
|
868
|
+
releasedAt: args.issuedAtMs,
|
|
869
|
+
updatedAt: now,
|
|
870
|
+
lastReceiptJobId: args.jobId
|
|
871
|
+
};
|
|
872
|
+
store.implicitCredits.push(record);
|
|
873
|
+
const capped2 = capLostImplicitCredits(store.implicitCredits);
|
|
874
|
+
store.implicitCredits = capped2.credits;
|
|
875
|
+
saveStore(store);
|
|
876
|
+
return store.implicitCredits.includes(record) ? { credit: record } : {};
|
|
877
|
+
}
|
|
878
|
+
attachDvmLocation(record, key, args.identity);
|
|
879
|
+
let mismatch;
|
|
880
|
+
const sequential = args.credit.ledger_seq === record.ledgerSeq + 1;
|
|
881
|
+
if (sequential && args.outcome === "completed" && record.status === "active") {
|
|
882
|
+
const expected = record.remainingMicro - args.credit.amount;
|
|
883
|
+
if (args.credit.balance_after !== expected) {
|
|
884
|
+
mismatch = {
|
|
885
|
+
atMs: now,
|
|
886
|
+
expectedMicro: expected,
|
|
887
|
+
reportedMicro: args.credit.balance_after,
|
|
888
|
+
drawId: args.credit.draw_id,
|
|
889
|
+
ledgerSeq: args.credit.ledger_seq,
|
|
890
|
+
...record.lastReceiptJobId ? { priorJobId: record.lastReceiptJobId } : {},
|
|
891
|
+
jobId: args.jobId
|
|
892
|
+
};
|
|
893
|
+
record.discrepancy = mismatch;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (args.credit.ledger_seq >= record.ledgerSeq) {
|
|
897
|
+
record.remainingMicro = args.credit.balance_after;
|
|
898
|
+
record.ledgerSeq = args.credit.ledger_seq;
|
|
899
|
+
}
|
|
900
|
+
if (!mismatch && record.discrepancy && args.credit.ledger_seq > record.discrepancy.ledgerSeq) {
|
|
901
|
+
delete record.discrepancy;
|
|
902
|
+
}
|
|
903
|
+
record.currency = args.currency;
|
|
904
|
+
record.lastReceiptJobId = args.jobId;
|
|
905
|
+
record.updatedAt = now;
|
|
906
|
+
if (record.remainingMicro <= 0) {
|
|
907
|
+
store.implicitCredits = store.implicitCredits.filter((candidate) => candidate !== record);
|
|
908
|
+
saveStore(store);
|
|
909
|
+
return { ...mismatch ? { mismatch } : {}, pruned: true };
|
|
910
|
+
}
|
|
911
|
+
if (record.expiryMs <= now) record.status = "lost";
|
|
912
|
+
const capped = capLostImplicitCredits(store.implicitCredits);
|
|
913
|
+
store.implicitCredits = capped.credits;
|
|
914
|
+
saveStore(store);
|
|
915
|
+
return {
|
|
916
|
+
...store.implicitCredits.includes(record) ? { credit: record } : {},
|
|
917
|
+
...mismatch ? { mismatch } : {}
|
|
918
|
+
};
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
function ensureProvisionalCredit(args) {
|
|
922
|
+
const now = args.now ?? Date.now();
|
|
923
|
+
withCreditLock(() => {
|
|
924
|
+
const store = loadStore();
|
|
925
|
+
const key = normalizeCreditEndpoint(args.endpoint);
|
|
926
|
+
let record = findDvmLocated(store.credits, {
|
|
927
|
+
endpoint: key,
|
|
928
|
+
...args.identity ? { identity: args.identity } : {},
|
|
929
|
+
where: (c) => c.callerPubkey === args.callerPubkey
|
|
930
|
+
});
|
|
931
|
+
if (!record) {
|
|
932
|
+
record = {
|
|
933
|
+
endpoint: key,
|
|
934
|
+
...identityFields(args.identity),
|
|
935
|
+
callerPubkey: args.callerPubkey,
|
|
936
|
+
creditId: args.creditId,
|
|
937
|
+
currency: args.currency,
|
|
938
|
+
balanceMicro: 0,
|
|
939
|
+
remainingMicro: 0,
|
|
940
|
+
ledgerSeq: 0,
|
|
941
|
+
expiryMs: 0,
|
|
942
|
+
targetMicro: args.targetMicro,
|
|
943
|
+
status: "active",
|
|
944
|
+
openedAt: now,
|
|
945
|
+
updatedAt: now
|
|
946
|
+
};
|
|
947
|
+
store.credits.push(record);
|
|
948
|
+
}
|
|
949
|
+
attachDvmLocation(record, key, args.identity);
|
|
950
|
+
adoptCreditId(record, args.creditId);
|
|
951
|
+
record.currency = args.currency;
|
|
952
|
+
record.targetMicro = args.targetMicro;
|
|
953
|
+
record.status = "active";
|
|
954
|
+
record.provisional = true;
|
|
955
|
+
record.updatedAt = now;
|
|
956
|
+
if (args.menu) record.menu = args.menu;
|
|
957
|
+
saveStore(store);
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
function markCredit(endpoint, callerPubkey, status, opts = {}) {
|
|
961
|
+
mutateCredit(
|
|
962
|
+
{ endpoint, callerPubkey, ...opts.identity ? { identity: opts.identity } : {} },
|
|
963
|
+
(record) => {
|
|
964
|
+
if (opts.ifCreditId !== void 0 && record.creditId !== opts.ifCreditId) return "skip";
|
|
965
|
+
record.status = status;
|
|
966
|
+
if (status !== "active") {
|
|
967
|
+
delete record.refillUnavailableRail;
|
|
968
|
+
delete record.refillDrainNoticed;
|
|
969
|
+
}
|
|
970
|
+
if (status === "drained") record.remainingMicro = 0;
|
|
971
|
+
return void 0;
|
|
972
|
+
}
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
function loadCreditX402Binding(endpoint, callerPubkey, creditId, identity) {
|
|
976
|
+
const record = loadCredit(endpoint, callerPubkey, identity);
|
|
977
|
+
if (record?.creditId !== creditId) return {};
|
|
978
|
+
if (record.status !== "active" && record.status !== "expired") return {};
|
|
979
|
+
return {
|
|
980
|
+
...record.x402Instrument ? { instrument: record.x402Instrument } : {},
|
|
981
|
+
...record.x402ChannelNetwork ? { channelNetwork: record.x402ChannelNetwork } : {}
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
function recordCreditX402Instrument(endpoint, callerPubkey, creditId, instrument, identity, channelNetwork) {
|
|
985
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
986
|
+
if (record.creditId !== creditId) return "skip";
|
|
987
|
+
const instrumentChanged = record.x402Instrument !== instrument;
|
|
988
|
+
const channelNetworkChanged = instrument === "x402_channel" && channelNetwork !== void 0 && record.x402ChannelNetwork !== channelNetwork;
|
|
989
|
+
if (!instrumentChanged && !channelNetworkChanged) return "skip";
|
|
990
|
+
if (instrumentChanged) {
|
|
991
|
+
record.x402Instrument = instrument;
|
|
992
|
+
delete record.x402ChannelNetwork;
|
|
993
|
+
}
|
|
994
|
+
if (instrument === "x402_channel" && channelNetwork !== void 0) {
|
|
995
|
+
record.x402ChannelNetwork = channelNetwork;
|
|
996
|
+
}
|
|
997
|
+
return void 0;
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
function recordRefusedDrawBalance(args) {
|
|
1001
|
+
const remaining = safeMicro(args.remainingMicro);
|
|
1002
|
+
if (remaining === void 0) return;
|
|
1003
|
+
const balance = safeMicro(args.balanceMicro);
|
|
1004
|
+
mutateCredit(mutationAt(args.endpoint, args.callerPubkey, args.identity), (record) => {
|
|
1005
|
+
if (record.creditId !== args.creditId) return "skip";
|
|
1006
|
+
const unchanged = record.remainingMicro === remaining && (balance === void 0 || record.balanceMicro === balance) && record.unsequencedBalance === true && !record.provisional;
|
|
1007
|
+
if (unchanged) return "skip";
|
|
1008
|
+
record.remainingMicro = remaining;
|
|
1009
|
+
if (balance !== void 0) record.balanceMicro = balance;
|
|
1010
|
+
record.unsequencedBalance = true;
|
|
1011
|
+
delete record.provisional;
|
|
1012
|
+
return void 0;
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
function markRefillRailUnavailable(endpoint, callerPubkey, creditId, rail, identity) {
|
|
1016
|
+
let firstObservation = false;
|
|
1017
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1018
|
+
if (record.creditId !== creditId) return "skip";
|
|
1019
|
+
if (record.refillUnavailableRail === rail) return "skip";
|
|
1020
|
+
record.refillUnavailableRail = rail;
|
|
1021
|
+
firstObservation = true;
|
|
1022
|
+
return void 0;
|
|
1023
|
+
});
|
|
1024
|
+
return firstObservation;
|
|
1025
|
+
}
|
|
1026
|
+
function markRefillDrainNoticed(endpoint, callerPubkey, creditId, drainId, identity) {
|
|
1027
|
+
let firstObservation = false;
|
|
1028
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1029
|
+
if (record.creditId !== creditId) return "skip";
|
|
1030
|
+
if (record.refillDrainNoticed === drainId) return "skip";
|
|
1031
|
+
record.refillDrainNoticed = drainId;
|
|
1032
|
+
firstObservation = true;
|
|
1033
|
+
return void 0;
|
|
1034
|
+
});
|
|
1035
|
+
return firstObservation;
|
|
1036
|
+
}
|
|
1037
|
+
function clearRefillRailUnavailable(endpoint, callerPubkey, creditId, identity) {
|
|
1038
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1039
|
+
if (record.creditId !== creditId) return "skip";
|
|
1040
|
+
if (record.refillUnavailableRail === void 0) return "skip";
|
|
1041
|
+
delete record.refillUnavailableRail;
|
|
1042
|
+
return void 0;
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
function forgetCredit(endpoint, callerPubkey, identity) {
|
|
1046
|
+
withCreditLock(() => {
|
|
1047
|
+
const store = loadStore();
|
|
1048
|
+
const key = normalizeCreditEndpoint(endpoint);
|
|
1049
|
+
const record = findDvmLocated(store.credits, {
|
|
1050
|
+
endpoint: key,
|
|
1051
|
+
...identity ? { identity } : {},
|
|
1052
|
+
where: (c) => c.callerPubkey === callerPubkey
|
|
1053
|
+
});
|
|
1054
|
+
if (!record) return;
|
|
1055
|
+
saveStore({ ...store, credits: store.credits.filter((c) => c !== record) });
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
function recordPendingDrain(endpoint, callerPubkey, drain, identity) {
|
|
1059
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1060
|
+
const drains = record.pendingDrains ?? [];
|
|
1061
|
+
const index = drains.findIndex(
|
|
1062
|
+
(d) => d.drainId === drain.drainId && d.creditId === drain.creditId
|
|
1063
|
+
);
|
|
1064
|
+
if (index === -1) drains.push(drain);
|
|
1065
|
+
else drains[index] = drain;
|
|
1066
|
+
record.pendingDrains = capPendingDrains(drains, record.creditId);
|
|
1067
|
+
return void 0;
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
function clearPendingDrain(endpoint, callerPubkey, drain, identity) {
|
|
1071
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1072
|
+
const before = record.pendingDrains ?? [];
|
|
1073
|
+
const remaining = before.filter(
|
|
1074
|
+
(d) => !(d.drainId === drain.drainId && d.creditId === drain.creditId)
|
|
1075
|
+
);
|
|
1076
|
+
if (remaining.length === before.length) return "skip";
|
|
1077
|
+
if (remaining.length === 0) delete record.pendingDrains;
|
|
1078
|
+
else record.pendingDrains = remaining;
|
|
1079
|
+
return void 0;
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
function recordDrainReceipts(args) {
|
|
1083
|
+
const {
|
|
1084
|
+
endpoint,
|
|
1085
|
+
identity,
|
|
1086
|
+
callerPubkey,
|
|
1087
|
+
drainId,
|
|
1088
|
+
creditId,
|
|
1089
|
+
receipts,
|
|
1090
|
+
read,
|
|
1091
|
+
now = Date.now()
|
|
1092
|
+
} = args;
|
|
1093
|
+
if (receipts.length === 0) return;
|
|
1094
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1095
|
+
const evidence = record.drainEvidence ??= [];
|
|
1096
|
+
let bundle = evidence.find((e) => e.drainId === drainId);
|
|
1097
|
+
if (!bundle) {
|
|
1098
|
+
bundle = { drainId, creditId, receipts: [], collectedAt: now };
|
|
1099
|
+
evidence.push(bundle);
|
|
1100
|
+
}
|
|
1101
|
+
bundle.creditId = creditId;
|
|
1102
|
+
bundle.receipts = receipts;
|
|
1103
|
+
bundle.collectedAt = now;
|
|
1104
|
+
if (read.anchor) bundle.anchor = read.anchor;
|
|
1105
|
+
else if (read.reachable) delete bundle.anchor;
|
|
1106
|
+
record.drainEvidence = capDrainEvidence(evidence, endpoint);
|
|
1107
|
+
return void 0;
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
function settleDrainEvidence(args) {
|
|
1111
|
+
const { endpoint, identity, callerPubkey, drainId, now = Date.now() } = args;
|
|
1112
|
+
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1113
|
+
const evidence = record.drainEvidence ?? [];
|
|
1114
|
+
const bundle = evidence.find((e) => e.drainId === drainId);
|
|
1115
|
+
if (!bundle || bundle.settledAt !== void 0) return "skip";
|
|
1116
|
+
bundle.settledAt = now;
|
|
1117
|
+
record.drainEvidence = capDrainEvidence(evidence, endpoint);
|
|
1118
|
+
return void 0;
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
function identityFields(identity) {
|
|
1122
|
+
if (!identity) return {};
|
|
1123
|
+
return { dvmId: identity.dvmId, attestedBuilderPubkey: identity.builderPubkey };
|
|
1124
|
+
}
|
|
1125
|
+
function mutationAt(endpoint, callerPubkey, identity) {
|
|
1126
|
+
return { endpoint, callerPubkey, ...identity ? { identity } : {} };
|
|
1127
|
+
}
|
|
1128
|
+
function matchesDvmIdentity(record, identity) {
|
|
1129
|
+
const stored = dvmLocationIdentity(record);
|
|
1130
|
+
return stored?.dvmId === identity.dvmId && stored.builderPubkey === identity.builderPubkey;
|
|
1131
|
+
}
|
|
1132
|
+
function matchesDvmOrigin(record, endpoint, identity) {
|
|
1133
|
+
if (identity) {
|
|
1134
|
+
if (dvmLocationIdentity(record) !== void 0) return false;
|
|
1135
|
+
if (record.dvmId !== void 0 && record.dvmId !== identity.dvmId) return false;
|
|
1136
|
+
}
|
|
1137
|
+
return dvmLocationOrigins(record).includes(endpoint);
|
|
1138
|
+
}
|
|
1139
|
+
function adoptCreditId(record, creditId) {
|
|
1140
|
+
if (record.creditId === creditId) return;
|
|
1141
|
+
if (record.status === "active" || record.status === "expired" || record.status === "unbacked") {
|
|
1142
|
+
const prior = {
|
|
1143
|
+
creditId: record.creditId,
|
|
1144
|
+
status: record.status === "unbacked" ? "unbacked" : "active",
|
|
1145
|
+
currency: record.currency,
|
|
1146
|
+
balanceMicro: record.balanceMicro,
|
|
1147
|
+
remainingMicro: record.remainingMicro,
|
|
1148
|
+
ledgerSeq: record.ledgerSeq,
|
|
1149
|
+
expiryMs: record.expiryMs,
|
|
1150
|
+
expired: record.status === "expired",
|
|
1151
|
+
drainable: record.status !== "unbacked" && record.balanceMicro > 0,
|
|
1152
|
+
...record.reconciliationPending ? { reconciliationPending: true } : {},
|
|
1153
|
+
observedAt: record.updatedAt
|
|
1154
|
+
};
|
|
1155
|
+
record.siblingCredits = [
|
|
1156
|
+
...(record.siblingCredits ?? []).filter(
|
|
1157
|
+
(sibling) => sibling.creditId !== prior.creditId && sibling.creditId !== creditId
|
|
1158
|
+
),
|
|
1159
|
+
prior
|
|
1160
|
+
];
|
|
1161
|
+
} else if (record.siblingCredits) {
|
|
1162
|
+
record.siblingCredits = record.siblingCredits.filter(
|
|
1163
|
+
(sibling) => sibling.creditId !== creditId
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
record.creditId = creditId;
|
|
1167
|
+
record.ledgerSeq = 0;
|
|
1168
|
+
record.balanceMicro = 0;
|
|
1169
|
+
record.remainingMicro = 0;
|
|
1170
|
+
record.expiryMs = 0;
|
|
1171
|
+
delete record.unsequencedBalance;
|
|
1172
|
+
delete record.rail;
|
|
1173
|
+
delete record.x402Instrument;
|
|
1174
|
+
delete record.x402ChannelNetwork;
|
|
1175
|
+
delete record.refillUnavailableRail;
|
|
1176
|
+
delete record.refillDrainNoticed;
|
|
1177
|
+
delete record.discrepancy;
|
|
1178
|
+
delete record.lastReceiptJobId;
|
|
1179
|
+
}
|
|
1180
|
+
var MAX_PENDING_DRAINS = 8;
|
|
1181
|
+
var MAX_SETTLED_DRAIN_EVIDENCE = 8;
|
|
1182
|
+
var MAX_LOST_IMPLICIT_CREDITS = 8;
|
|
1183
|
+
var MAX_DATE_MS = 864e13;
|
|
1184
|
+
function loadStore() {
|
|
1185
|
+
if (!existsSync2(CREDITS_FILE)) {
|
|
1186
|
+
return { credits: [], implicitCredits: [], pendingFundings: [], fundingMenuSnapshots: [] };
|
|
1187
|
+
}
|
|
1188
|
+
let raw2;
|
|
1189
|
+
try {
|
|
1190
|
+
raw2 = readFileSync2(CREDITS_FILE, "utf-8");
|
|
1191
|
+
} catch (cause) {
|
|
1192
|
+
throw unreadableStore(cause);
|
|
1193
|
+
}
|
|
1194
|
+
let data;
|
|
1195
|
+
try {
|
|
1196
|
+
const parsed = JSON.parse(raw2);
|
|
1197
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1198
|
+
throw new Error("the file parsed as JSON but is not a credit-store object");
|
|
1199
|
+
}
|
|
1200
|
+
data = parsed;
|
|
1201
|
+
} catch (cause) {
|
|
1202
|
+
throw quarantineCorruptStore(cause);
|
|
1203
|
+
}
|
|
1204
|
+
const merged = mergeDuplicateCredits(
|
|
1205
|
+
Array.isArray(data.credits) ? data.credits.filter((record) => isObjectRecord(record)).map(
|
|
1206
|
+
(record) => normalizeRailKey(normalizeEvidence(normalizeDrains(normalizeSiblingCredits(record))))
|
|
1207
|
+
) : []
|
|
1208
|
+
);
|
|
1209
|
+
const snapshots = mergeDuplicateSnapshots(
|
|
1210
|
+
Array.isArray(data.fundingMenuSnapshots) ? data.fundingMenuSnapshots.filter(isFundingMenuSnapshot) : [],
|
|
1211
|
+
merged.credits
|
|
1212
|
+
);
|
|
1213
|
+
const fundings = dedupePendingFundings(
|
|
1214
|
+
Array.isArray(data.pendingFundings) ? data.pendingFundings.filter((funding) => isObjectRecord(funding)).map(normalizeRailKey) : []
|
|
1215
|
+
);
|
|
1216
|
+
const implicit = dedupeImplicitCredits(
|
|
1217
|
+
Array.isArray(data.implicitCredits) ? data.implicitCredits.filter(isStoredImplicitCredit) : []
|
|
1218
|
+
);
|
|
1219
|
+
const store = {
|
|
1220
|
+
credits: merged.credits,
|
|
1221
|
+
implicitCredits: implicit.credits,
|
|
1222
|
+
pendingFundings: fundings.fundings,
|
|
1223
|
+
fundingMenuSnapshots: snapshots.snapshots
|
|
1224
|
+
};
|
|
1225
|
+
if (merged.changed || snapshots.changed || fundings.changed || implicit.changed) saveStore(store);
|
|
1226
|
+
return store;
|
|
1227
|
+
}
|
|
1228
|
+
function isStoredImplicitCredit(value) {
|
|
1229
|
+
if (!isObjectRecord(value)) return false;
|
|
1230
|
+
return typeof value.endpoint === "string" && typeof value.callerPubkey === "string" && typeof value.creditId === "string" && value.creditId.startsWith("imp:") && typeof value.currency === "string" && typeof value.remainingMicro === "number" && Number.isFinite(value.remainingMicro) && typeof value.ledgerSeq === "number" && Number.isInteger(value.ledgerSeq) && typeof value.expiryMs === "number" && Number.isFinite(value.expiryMs) && (value.status === "active" || value.status === "lost") && typeof value.releasedByJobId === "string" && typeof value.releasedAt === "number" && Number.isFinite(value.releasedAt) && typeof value.updatedAt === "number" && Number.isFinite(value.updatedAt);
|
|
1231
|
+
}
|
|
1232
|
+
function dedupeImplicitCredits(credits) {
|
|
1233
|
+
const merged = [];
|
|
1234
|
+
let changed = false;
|
|
1235
|
+
for (const candidate of credits) {
|
|
1236
|
+
candidate.endpoint = normalizeCreditEndpoint(candidate.endpoint);
|
|
1237
|
+
const identity = dvmLocationIdentity(candidate);
|
|
1238
|
+
const existing = findDvmLocated(merged, {
|
|
1239
|
+
endpoint: candidate.endpoint,
|
|
1240
|
+
...identity ? { identity } : {},
|
|
1241
|
+
where: (record) => record.callerPubkey === candidate.callerPubkey && record.creditId === candidate.creditId
|
|
1242
|
+
});
|
|
1243
|
+
if (!existing) {
|
|
1244
|
+
merged.push(candidate);
|
|
1245
|
+
continue;
|
|
1246
|
+
}
|
|
1247
|
+
changed = true;
|
|
1248
|
+
for (const origin of dvmLocationOrigins(candidate)) {
|
|
1249
|
+
attachDvmLocation(existing, origin, identity);
|
|
1250
|
+
}
|
|
1251
|
+
if (candidate.ledgerSeq > existing.ledgerSeq || candidate.ledgerSeq === existing.ledgerSeq && candidate.updatedAt > existing.updatedAt) {
|
|
1252
|
+
existing.currency = candidate.currency;
|
|
1253
|
+
existing.remainingMicro = candidate.remainingMicro;
|
|
1254
|
+
existing.ledgerSeq = candidate.ledgerSeq;
|
|
1255
|
+
existing.status = candidate.status;
|
|
1256
|
+
if (candidate.lossReason) existing.lossReason = candidate.lossReason;
|
|
1257
|
+
else delete existing.lossReason;
|
|
1258
|
+
existing.updatedAt = candidate.updatedAt;
|
|
1259
|
+
existing.lastReceiptJobId = candidate.lastReceiptJobId;
|
|
1260
|
+
existing.discrepancy = candidate.discrepancy;
|
|
1261
|
+
}
|
|
1262
|
+
existing.expiryMs = Math.min(existing.expiryMs, candidate.expiryMs);
|
|
1263
|
+
if (candidate.releasedAt < existing.releasedAt) {
|
|
1264
|
+
existing.releasedAt = candidate.releasedAt;
|
|
1265
|
+
existing.releasedByJobId = candidate.releasedByJobId;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
const capped = capLostImplicitCredits(merged);
|
|
1269
|
+
return { credits: capped.credits, changed: changed || capped.changed };
|
|
1270
|
+
}
|
|
1271
|
+
function ageImplicitCredits(credits, now) {
|
|
1272
|
+
let changed = false;
|
|
1273
|
+
for (const credit of credits) {
|
|
1274
|
+
if (credit.status === "active" && credit.expiryMs <= now) {
|
|
1275
|
+
credit.status = "lost";
|
|
1276
|
+
credit.lossReason = "expired";
|
|
1277
|
+
credit.updatedAt = now;
|
|
1278
|
+
changed = true;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
return changed;
|
|
1282
|
+
}
|
|
1283
|
+
function capLostImplicitCredits(credits) {
|
|
1284
|
+
const lostByOwner = /* @__PURE__ */ new Map();
|
|
1285
|
+
for (const credit of credits) {
|
|
1286
|
+
if (credit.status !== "lost") continue;
|
|
1287
|
+
const identity = dvmLocationIdentity(credit);
|
|
1288
|
+
const dvmKey = identity ? `${identity.dvmId}\0${identity.builderPubkey}` : normalizeCreditEndpoint(credit.endpoint);
|
|
1289
|
+
const key = `${credit.callerPubkey}\0${dvmKey}`;
|
|
1290
|
+
const group = lostByOwner.get(key) ?? [];
|
|
1291
|
+
group.push(credit);
|
|
1292
|
+
lostByOwner.set(key, group);
|
|
1293
|
+
}
|
|
1294
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
1295
|
+
for (const group of lostByOwner.values()) {
|
|
1296
|
+
group.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1297
|
+
for (const credit of group.slice(MAX_LOST_IMPLICIT_CREDITS)) dropped.add(credit);
|
|
1298
|
+
}
|
|
1299
|
+
return dropped.size === 0 ? { credits, changed: false } : { credits: credits.filter((credit) => !dropped.has(credit)), changed: true };
|
|
1300
|
+
}
|
|
1301
|
+
function compareImplicitCredits(a, b) {
|
|
1302
|
+
if (a.status !== b.status) return a.status === "active" ? -1 : 1;
|
|
1303
|
+
return a.status === "active" ? a.expiryMs - b.expiryMs : b.updatedAt - a.updatedAt;
|
|
1304
|
+
}
|
|
1305
|
+
function mergeDuplicateSnapshots(snapshots, credits) {
|
|
1306
|
+
const identities = originIdentityMap(credits);
|
|
1307
|
+
const merged = [];
|
|
1308
|
+
const byIdentity = /* @__PURE__ */ new Map();
|
|
1309
|
+
let changed = false;
|
|
1310
|
+
for (const snapshot of snapshots) {
|
|
1311
|
+
const stamped = identities.get(`${snapshot.callerPubkey}\0${snapshot.endpoint}`);
|
|
1312
|
+
if (stamped !== void 0 && snapshot.dvmId === void 0) {
|
|
1313
|
+
snapshot.dvmId = stamped.dvmId;
|
|
1314
|
+
if (stamped.attestedBuilderPubkey !== void 0) {
|
|
1315
|
+
snapshot.attestedBuilderPubkey = stamped.attestedBuilderPubkey;
|
|
1316
|
+
}
|
|
1317
|
+
changed = true;
|
|
1318
|
+
}
|
|
1319
|
+
if (snapshot.dvmId === void 0) {
|
|
1320
|
+
merged.push(snapshot);
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
const key = `${snapshot.callerPubkey}\0${snapshot.dvmId}\0${snapshot.attestedBuilderPubkey ?? ""}`;
|
|
1324
|
+
const index = byIdentity.get(key);
|
|
1325
|
+
if (index === void 0) {
|
|
1326
|
+
byIdentity.set(key, merged.length);
|
|
1327
|
+
merged.push(snapshot);
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
merged[index] = mergeSnapshots(merged[index], snapshot);
|
|
1331
|
+
changed = true;
|
|
1332
|
+
}
|
|
1333
|
+
return { snapshots: merged, changed };
|
|
1334
|
+
}
|
|
1335
|
+
function mergeSnapshots(left, right) {
|
|
1336
|
+
const leftSeen = Number.isFinite(left.observedAt) ? left.observedAt : 0;
|
|
1337
|
+
const rightSeen = Number.isFinite(right.observedAt) ? right.observedAt : 0;
|
|
1338
|
+
const [newer, older] = rightSeen >= leftSeen ? [right, left] : [left, right];
|
|
1339
|
+
const snapshot = { ...newer };
|
|
1340
|
+
if (snapshot.builderPubkey === void 0 && older.builderPubkey !== void 0) {
|
|
1341
|
+
snapshot.builderPubkey = older.builderPubkey;
|
|
1342
|
+
}
|
|
1343
|
+
const origins = dvmLocationOrigins(newer).concat(dvmLocationOrigins(older));
|
|
1344
|
+
const aliases = [...new Set(origins)].filter((origin) => origin !== snapshot.endpoint);
|
|
1345
|
+
if (aliases.length > 0) snapshot.endpointAliases = aliases;
|
|
1346
|
+
else delete snapshot.endpointAliases;
|
|
1347
|
+
return snapshot;
|
|
1348
|
+
}
|
|
1349
|
+
function originIdentityMap(credits) {
|
|
1350
|
+
const identities = /* @__PURE__ */ new Map();
|
|
1351
|
+
const ambiguous = /* @__PURE__ */ new Set();
|
|
1352
|
+
for (const record of credits) {
|
|
1353
|
+
if (typeof record.dvmId !== "string" || typeof record.callerPubkey !== "string") continue;
|
|
1354
|
+
const identity = {
|
|
1355
|
+
dvmId: record.dvmId,
|
|
1356
|
+
...record.attestedBuilderPubkey !== void 0 ? { attestedBuilderPubkey: record.attestedBuilderPubkey } : {}
|
|
1357
|
+
};
|
|
1358
|
+
for (const origin of dvmLocationOrigins(record)) {
|
|
1359
|
+
const key = `${record.callerPubkey}\0${origin}`;
|
|
1360
|
+
const seen = identities.get(key);
|
|
1361
|
+
if (seen !== void 0 && (seen.dvmId !== identity.dvmId || seen.attestedBuilderPubkey !== identity.attestedBuilderPubkey)) {
|
|
1362
|
+
ambiguous.add(key);
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
identities.set(key, identity);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
for (const key of ambiguous) identities.delete(key);
|
|
1369
|
+
return identities;
|
|
1370
|
+
}
|
|
1371
|
+
function dedupePendingFundings(fundings) {
|
|
1372
|
+
const kept = [];
|
|
1373
|
+
const byIntent = /* @__PURE__ */ new Map();
|
|
1374
|
+
let changed = false;
|
|
1375
|
+
for (const funding of fundings) {
|
|
1376
|
+
if (typeof funding.callerPubkey !== "string" || typeof funding.creditId !== "string" || typeof funding.fundId !== "string") {
|
|
1377
|
+
kept.push(funding);
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
const key = `${funding.callerPubkey}\0${funding.creditId}\0${funding.fundId}`;
|
|
1381
|
+
const index = byIntent.get(key);
|
|
1382
|
+
if (index === void 0) {
|
|
1383
|
+
byIntent.set(key, kept.length);
|
|
1384
|
+
kept.push(funding);
|
|
1385
|
+
continue;
|
|
1386
|
+
}
|
|
1387
|
+
const seen = kept[index];
|
|
1388
|
+
const seenAt = Number.isFinite(seen.requestedAt) ? seen.requestedAt : 0;
|
|
1389
|
+
const at = Number.isFinite(funding.requestedAt) ? funding.requestedAt : 0;
|
|
1390
|
+
if (at > seenAt) kept[index] = funding;
|
|
1391
|
+
changed = true;
|
|
1392
|
+
}
|
|
1393
|
+
return { fundings: kept, changed };
|
|
1394
|
+
}
|
|
1395
|
+
function isObjectRecord(value) {
|
|
1396
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1397
|
+
}
|
|
1398
|
+
function mergeDuplicateCredits(credits) {
|
|
1399
|
+
const merged = [];
|
|
1400
|
+
const byCredit = /* @__PURE__ */ new Map();
|
|
1401
|
+
let changed = false;
|
|
1402
|
+
for (const record of credits) {
|
|
1403
|
+
if (typeof record.creditId !== "string" || typeof record.callerPubkey !== "string") {
|
|
1404
|
+
merged.push(record);
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
const key = `${record.callerPubkey}\0${record.creditId}`;
|
|
1408
|
+
const index = byCredit.get(key);
|
|
1409
|
+
if (index === void 0) {
|
|
1410
|
+
byCredit.set(key, merged.length);
|
|
1411
|
+
merged.push(record);
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
merged[index] = mergeCreditRecords(merged[index], record);
|
|
1415
|
+
changed = true;
|
|
1416
|
+
}
|
|
1417
|
+
return { credits: merged, changed };
|
|
1418
|
+
}
|
|
1419
|
+
function mergeCreditRecords(left, right) {
|
|
1420
|
+
const leftUpdated = Number.isFinite(left.updatedAt) ? left.updatedAt : 0;
|
|
1421
|
+
const rightUpdated = Number.isFinite(right.updatedAt) ? right.updatedAt : 0;
|
|
1422
|
+
const [newer, older] = rightUpdated >= leftUpdated ? [right, left] : [left, right];
|
|
1423
|
+
const record = { ...newer };
|
|
1424
|
+
if (record.dvmId === void 0 && older.dvmId !== void 0) record.dvmId = older.dvmId;
|
|
1425
|
+
if (record.attestedBuilderPubkey === void 0 && older.attestedBuilderPubkey !== void 0 && record.dvmId === older.dvmId) {
|
|
1426
|
+
record.attestedBuilderPubkey = older.attestedBuilderPubkey;
|
|
1427
|
+
}
|
|
1428
|
+
if (record.rail === void 0 && older.rail !== void 0) record.rail = older.rail;
|
|
1429
|
+
if (record.x402Instrument === void 0 && older.x402Instrument !== void 0) {
|
|
1430
|
+
record.x402Instrument = older.x402Instrument;
|
|
1431
|
+
}
|
|
1432
|
+
if (record.x402ChannelNetwork === void 0 && older.x402ChannelNetwork !== void 0) {
|
|
1433
|
+
record.x402ChannelNetwork = older.x402ChannelNetwork;
|
|
1434
|
+
}
|
|
1435
|
+
if (record.menu === void 0 && older.menu !== void 0) record.menu = older.menu;
|
|
1436
|
+
if (record.builderPubkey === void 0 && older.builderPubkey !== void 0) {
|
|
1437
|
+
record.builderPubkey = older.builderPubkey;
|
|
1438
|
+
}
|
|
1439
|
+
const endpoints = dvmLocationOrigins(newer).concat(dvmLocationOrigins(older));
|
|
1440
|
+
const aliases = [...new Set(endpoints)].filter((endpoint) => endpoint !== record.endpoint);
|
|
1441
|
+
if (aliases.length > 0) record.endpointAliases = aliases;
|
|
1442
|
+
else delete record.endpointAliases;
|
|
1443
|
+
const pendingDrains = unionPendingDrains(newer.pendingDrains, older.pendingDrains);
|
|
1444
|
+
if (pendingDrains.length > 0) record.pendingDrains = pendingDrains;
|
|
1445
|
+
else delete record.pendingDrains;
|
|
1446
|
+
const drainEvidence = unionDrainEvidence(newer.drainEvidence, older.drainEvidence);
|
|
1447
|
+
if (drainEvidence.length > 0) record.drainEvidence = drainEvidence;
|
|
1448
|
+
else delete record.drainEvidence;
|
|
1449
|
+
const siblings = Array.isArray(newer.siblingCredits) ? newer.siblingCredits : older.siblingCredits;
|
|
1450
|
+
if (siblings) {
|
|
1451
|
+
record.siblingCredits = siblings.filter((sibling) => sibling.creditId !== record.creditId);
|
|
1452
|
+
} else {
|
|
1453
|
+
delete record.siblingCredits;
|
|
1454
|
+
}
|
|
1455
|
+
return record;
|
|
1456
|
+
}
|
|
1457
|
+
function unionPendingDrains(preferred, fallback) {
|
|
1458
|
+
const byDrain = /* @__PURE__ */ new Map();
|
|
1459
|
+
for (const drain of [...fallback ?? [], ...preferred ?? []]) {
|
|
1460
|
+
const key = `${drain.drainId}\0${drain.creditId ?? ""}`;
|
|
1461
|
+
byDrain.set(key, { ...byDrain.get(key) ?? {}, ...drain });
|
|
1462
|
+
}
|
|
1463
|
+
return [...byDrain.values()];
|
|
1464
|
+
}
|
|
1465
|
+
function unionDrainEvidence(preferred, fallback) {
|
|
1466
|
+
const byDrain = /* @__PURE__ */ new Map();
|
|
1467
|
+
for (const evidence of [...fallback ?? [], ...preferred ?? []]) {
|
|
1468
|
+
const key = `${evidence.drainId}\0${evidence.creditId}`;
|
|
1469
|
+
const existing = byDrain.get(key);
|
|
1470
|
+
if (!existing) {
|
|
1471
|
+
byDrain.set(key, evidence);
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
const [newer, older] = evidence.collectedAt >= existing.collectedAt ? [evidence, existing] : [existing, evidence];
|
|
1475
|
+
const receipts = unionUnknown(newer.receipts, older.receipts);
|
|
1476
|
+
byDrain.set(key, {
|
|
1477
|
+
...older,
|
|
1478
|
+
...newer,
|
|
1479
|
+
receipts,
|
|
1480
|
+
collectedAt: Math.max(existing.collectedAt, evidence.collectedAt),
|
|
1481
|
+
...existing.settledAt !== void 0 || evidence.settledAt !== void 0 ? { settledAt: Math.max(existing.settledAt ?? 0, evidence.settledAt ?? 0) } : {}
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
return [...byDrain.values()];
|
|
1485
|
+
}
|
|
1486
|
+
function unionUnknown(preferred, fallback) {
|
|
1487
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1488
|
+
const values = [];
|
|
1489
|
+
for (const value of [...preferred, ...fallback]) {
|
|
1490
|
+
let key;
|
|
1491
|
+
try {
|
|
1492
|
+
const serialized = JSON.stringify(value);
|
|
1493
|
+
key = typeof serialized === "string" ? serialized : String(value);
|
|
1494
|
+
} catch {
|
|
1495
|
+
key = String(value);
|
|
1496
|
+
}
|
|
1497
|
+
if (seen.has(key)) continue;
|
|
1498
|
+
seen.add(key);
|
|
1499
|
+
values.push(value);
|
|
1500
|
+
}
|
|
1501
|
+
return values;
|
|
1502
|
+
}
|
|
1503
|
+
function isFundingMenuSnapshot(value) {
|
|
1504
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1505
|
+
const snapshot = value;
|
|
1506
|
+
return typeof snapshot.endpoint === "string" && typeof snapshot.callerPubkey === "string" && typeof snapshot.observedAt === "number" && Number.isFinite(snapshot.observedAt) && Math.abs(snapshot.observedAt) <= MAX_DATE_MS && parseCreditMenu(snapshot.menu) !== void 0 && (snapshot.builderPubkey === void 0 || typeof snapshot.builderPubkey === "string");
|
|
1507
|
+
}
|
|
1508
|
+
function siblingFromWire(credit, observedAt) {
|
|
1509
|
+
return {
|
|
1510
|
+
creditId: credit.credit_id,
|
|
1511
|
+
status: credit.status ?? "active",
|
|
1512
|
+
currency: credit.currency,
|
|
1513
|
+
balanceMicro: credit.balance_micro,
|
|
1514
|
+
remainingMicro: credit.remaining_micro,
|
|
1515
|
+
ledgerSeq: credit.ledger_seq,
|
|
1516
|
+
expiryMs: credit.expiry_ms,
|
|
1517
|
+
expired: credit.expired,
|
|
1518
|
+
drainable: credit.drainable,
|
|
1519
|
+
...credit.reconciliation_pending ? { reconciliationPending: true } : {},
|
|
1520
|
+
observedAt
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
function normalizeRailKey(record) {
|
|
1524
|
+
const loose = record;
|
|
1525
|
+
if (loose.rail === LEGACY_TEMPO_RAIL_KEY) loose.rail = "tempo";
|
|
1526
|
+
if (loose.refillUnavailableRail === LEGACY_TEMPO_RAIL_KEY) loose.refillUnavailableRail = "tempo";
|
|
1527
|
+
if (Array.isArray(loose.pendingDrains)) {
|
|
1528
|
+
for (const drain of loose.pendingDrains) {
|
|
1529
|
+
if (drain?.method === LEGACY_TEMPO_RAIL_KEY) drain.method = "tempo";
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
return record;
|
|
1533
|
+
}
|
|
1534
|
+
var LEGACY_TEMPO_RAIL_KEY = "mpp";
|
|
1535
|
+
function normalizeSiblingCredits(record) {
|
|
1536
|
+
if (!Array.isArray(record.siblingCredits)) {
|
|
1537
|
+
delete record.siblingCredits;
|
|
1538
|
+
return record;
|
|
1539
|
+
}
|
|
1540
|
+
record.siblingCredits = record.siblingCredits.filter(
|
|
1541
|
+
(sibling) => isSiblingCredit(sibling) && sibling.creditId !== record.creditId
|
|
1542
|
+
);
|
|
1543
|
+
return record;
|
|
1544
|
+
}
|
|
1545
|
+
function isSiblingCredit(value) {
|
|
1546
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1547
|
+
const sibling = value;
|
|
1548
|
+
const status = value.status;
|
|
1549
|
+
return typeof sibling.creditId === "string" && typeof sibling.currency === "string" && Number.isSafeInteger(sibling.balanceMicro) && Number.isSafeInteger(sibling.remainingMicro) && Number.isSafeInteger(sibling.ledgerSeq) && Number.isFinite(sibling.expiryMs) && Math.abs(sibling.expiryMs) <= MAX_DATE_MS && typeof sibling.expired === "boolean" && typeof sibling.drainable === "boolean" && (status === void 0 || status === "active" || status === "unbacked") && (sibling.reconciliationPending === void 0 || typeof sibling.reconciliationPending === "boolean") && Number.isFinite(sibling.observedAt) && Math.abs(sibling.observedAt) <= MAX_DATE_MS;
|
|
1550
|
+
}
|
|
1551
|
+
function normalizeDrains(record) {
|
|
1552
|
+
const legacy = record;
|
|
1553
|
+
const drains = (Array.isArray(record.pendingDrains) ? record.pendingDrains : []).filter(
|
|
1554
|
+
isDrainish
|
|
1555
|
+
);
|
|
1556
|
+
if (isDrainish(legacy.pendingDrain)) drains.unshift(legacy.pendingDrain);
|
|
1557
|
+
delete legacy.pendingDrain;
|
|
1558
|
+
if (drains.length === 0) delete record.pendingDrains;
|
|
1559
|
+
else record.pendingDrains = drains;
|
|
1560
|
+
return record;
|
|
1561
|
+
}
|
|
1562
|
+
function normalizeEvidence(record) {
|
|
1563
|
+
if (!Array.isArray(record.drainEvidence)) {
|
|
1564
|
+
delete record.drainEvidence;
|
|
1565
|
+
return record;
|
|
1566
|
+
}
|
|
1567
|
+
const evidence = record.drainEvidence.filter(isEvidenceish).map((e) => {
|
|
1568
|
+
const bundle = {
|
|
1569
|
+
...e,
|
|
1570
|
+
creditId: typeof e.creditId === "string" ? e.creditId : "",
|
|
1571
|
+
collectedAt: Number.isFinite(e.collectedAt) ? e.collectedAt : 0
|
|
1572
|
+
};
|
|
1573
|
+
if (!Number.isFinite(bundle.settledAt)) delete bundle.settledAt;
|
|
1574
|
+
return bundle;
|
|
1575
|
+
});
|
|
1576
|
+
if (evidence.length === 0) delete record.drainEvidence;
|
|
1577
|
+
else record.drainEvidence = evidence;
|
|
1578
|
+
return record;
|
|
1579
|
+
}
|
|
1580
|
+
function isEvidenceish(value) {
|
|
1581
|
+
return typeof value === "object" && value !== null && typeof value.drainId === "string" && Array.isArray(value.receipts);
|
|
1582
|
+
}
|
|
1583
|
+
function isDrainish(value) {
|
|
1584
|
+
return typeof value === "object" && value !== null && typeof value.drainId === "string";
|
|
1585
|
+
}
|
|
1586
|
+
function capPendingDrains(drains, creditId) {
|
|
1587
|
+
if (drains.length <= MAX_PENDING_DRAINS) return drains;
|
|
1588
|
+
const evictable = drains.filter((d) => d.creditId !== creditId).sort((a, b) => a.requestedAt - b.requestedAt);
|
|
1589
|
+
const dropped = new Set(evictable.slice(0, drains.length - MAX_PENDING_DRAINS));
|
|
1590
|
+
for (const d of dropped) {
|
|
1591
|
+
info(
|
|
1592
|
+
`Dropping the oldest unclaimed drain record (${d.drainId}${d.creditId ? ` on credit ${d.creditId}` : ""}) \u2014 ${String(MAX_PENDING_DRAINS)} is the most this DVM's record keeps.`
|
|
1593
|
+
);
|
|
1594
|
+
}
|
|
1595
|
+
return drains.filter((d) => !dropped.has(d));
|
|
1596
|
+
}
|
|
1597
|
+
function capDrainEvidence(evidence, endpoint) {
|
|
1598
|
+
const settled = evidence.filter((e) => e.settledAt !== void 0).sort((a, b) => (a.settledAt ?? 0) - (b.settledAt ?? 0));
|
|
1599
|
+
if (settled.length <= MAX_SETTLED_DRAIN_EVIDENCE) return evidence;
|
|
1600
|
+
const dropped = new Set(settled.slice(0, settled.length - MAX_SETTLED_DRAIN_EVIDENCE));
|
|
1601
|
+
for (const e of dropped) {
|
|
1602
|
+
info(
|
|
1603
|
+
`Dropping the oldest completed reclaim's receipts (drain ${e.drainId}${e.creditId ? ` on credit ${e.creditId}` : ""}) \u2014 ${String(MAX_SETTLED_DRAIN_EVIDENCE)} is the most this DVM's record archives. Export the ones still held before they age out too: 'dvm credit receipts ${endpoint} --export'.`
|
|
1604
|
+
);
|
|
1605
|
+
}
|
|
1606
|
+
return evidence.filter((e) => !dropped.has(e));
|
|
1607
|
+
}
|
|
1608
|
+
function saveStore(store) {
|
|
1609
|
+
ensureConfigDir();
|
|
1610
|
+
const tmp = `${CREDITS_FILE}.${String(process.pid)}.tmp`;
|
|
1611
|
+
writeFileSync2(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
|
|
1612
|
+
try {
|
|
1613
|
+
renameSync(tmp, CREDITS_FILE);
|
|
1614
|
+
} catch (err) {
|
|
1615
|
+
try {
|
|
1616
|
+
unlinkSync(tmp);
|
|
1617
|
+
} catch {
|
|
1618
|
+
}
|
|
1619
|
+
throw err;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
function unreadableStore(cause) {
|
|
1623
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
1624
|
+
return new DvmError(
|
|
1625
|
+
"credit_store_unreadable",
|
|
1626
|
+
`The prepaid-credit record at ${CREDITS_FILE} exists but could not be opened: ${detail}`,
|
|
1627
|
+
`The file was left untouched. Check that you own it and can read it ('ls -l ${CREDITS_FILE}'), then retry \u2014 'chmod 600 ${CREDITS_FILE}' fixes the common case. Do not delete it: it may hold DVM-signed drain receipts for a refund that is still owed.`,
|
|
1628
|
+
{ credits_file: CREDITS_FILE, cause: detail },
|
|
1629
|
+
`Your local record of prepaid credits could not be opened \u2014 this looks like a file-permissions problem on this machine, not damage to the record. Nothing was changed or deleted, so any signed proof of a refund you are owed is still there.`
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
function quarantineCorruptStore(cause) {
|
|
1633
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1634
|
+
const quarantined = `${CREDITS_FILE}.corrupt-${stamp}-${String(process.pid)}`;
|
|
1635
|
+
let moved = false;
|
|
1636
|
+
try {
|
|
1637
|
+
renameSync(CREDITS_FILE, quarantined);
|
|
1638
|
+
moved = true;
|
|
1639
|
+
} catch {
|
|
1640
|
+
}
|
|
1641
|
+
const kept = moved ? quarantined : CREDITS_FILE;
|
|
1642
|
+
return new DvmError(
|
|
1643
|
+
"credit_store_corrupt",
|
|
1644
|
+
moved ? `The prepaid-credit record at ${CREDITS_FILE} is damaged and could not be parsed; it was moved aside to ${quarantined}.` : `The prepaid-credit record at ${CREDITS_FILE} is damaged and could not be parsed, and could not be moved aside.`,
|
|
1645
|
+
`Do not delete ${kept} \u2014 it may hold DVM-signed drain receipts for a refund that is still owed. Balances themselves live on the DVM, so 'dvm credit balance <dvm>' re-reads them.`,
|
|
1646
|
+
{
|
|
1647
|
+
credits_file: CREDITS_FILE,
|
|
1648
|
+
...moved ? { quarantined_path: quarantined } : {},
|
|
1649
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
1650
|
+
},
|
|
1651
|
+
`The local record of your prepaid credits is damaged. It was set aside at ${kept} rather than overwritten, so any signed proof of a refund you are owed is still in that file. Your credits are held by each DVM, not by this file, so re-reading a balance will restore what the CLI shows.`
|
|
1652
|
+
);
|
|
1653
|
+
}
|
|
1654
|
+
function safeMicro(value) {
|
|
1655
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
1656
|
+
}
|
|
1657
|
+
function mutateCredit(location, mutate) {
|
|
1658
|
+
withCreditLock(() => {
|
|
1659
|
+
const store = loadStore();
|
|
1660
|
+
const key = normalizeCreditEndpoint(location.endpoint);
|
|
1661
|
+
const record = findDvmLocated(store.credits, {
|
|
1662
|
+
endpoint: key,
|
|
1663
|
+
...location.identity ? { identity: location.identity } : {},
|
|
1664
|
+
where: (c) => c.callerPubkey === location.callerPubkey
|
|
1665
|
+
});
|
|
1666
|
+
if (!record) return;
|
|
1667
|
+
const locationChanged = attachDvmLocation(record, key, location.identity);
|
|
1668
|
+
if (mutate(record) === "skip") {
|
|
1669
|
+
if (locationChanged) saveStore(store);
|
|
1670
|
+
return;
|
|
1671
|
+
}
|
|
1672
|
+
record.updatedAt = Date.now();
|
|
1673
|
+
saveStore(store);
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
var DEFAULT_LOCK_STALE_MS = 1e4;
|
|
1677
|
+
var DEFAULT_LOCK_RETRIES = 600;
|
|
1678
|
+
var DEFAULT_LOCK_RETRY_INTERVAL_MS = 25;
|
|
1679
|
+
var lockDepth = 0;
|
|
1680
|
+
function acquireCreditLock(opts) {
|
|
1681
|
+
ensureConfigDir();
|
|
1682
|
+
const lockPath = `${CREDITS_FILE}.lock`;
|
|
1683
|
+
const stale = opts.stale ?? DEFAULT_LOCK_STALE_MS;
|
|
1684
|
+
const retries = opts.retries ?? DEFAULT_LOCK_RETRIES;
|
|
1685
|
+
const interval = opts.retryIntervalMs ?? DEFAULT_LOCK_RETRY_INTERVAL_MS;
|
|
1686
|
+
let lastError;
|
|
1687
|
+
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
1688
|
+
try {
|
|
1689
|
+
return import_proper_lockfile.default.lockSync(CREDITS_FILE, {
|
|
1690
|
+
lockfilePath: lockPath,
|
|
1691
|
+
stale,
|
|
1692
|
+
realpath: false
|
|
1693
|
+
});
|
|
1694
|
+
} catch (err) {
|
|
1695
|
+
lastError = err;
|
|
1696
|
+
if (err.code !== "ELOCKED") {
|
|
1697
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1698
|
+
const configDir = dirname2(lockPath);
|
|
1699
|
+
throw new DvmError(
|
|
1700
|
+
"credit_store_lock_failed",
|
|
1701
|
+
`Could not create the prepaid-credit lock at ${lockPath}: ${detail}`,
|
|
1702
|
+
`This is not contention \u2014 nothing is holding the lock. Check that ${configDir} exists and is writable by you ('ls -ld ${configDir}'), then retry.`,
|
|
1703
|
+
{
|
|
1704
|
+
lock_file: lockPath,
|
|
1705
|
+
config_dir: configDir,
|
|
1706
|
+
underlying: detail,
|
|
1707
|
+
errno_code: err.code
|
|
1708
|
+
},
|
|
1709
|
+
`The dvm CLI could not create the small lock file it uses to keep two commands from writing your credit record at once. Its folder looks unwritable \u2014 nothing about your credits is wrong, and nothing was changed.`
|
|
1710
|
+
);
|
|
1711
|
+
}
|
|
1712
|
+
if (attempt === retries) break;
|
|
1713
|
+
sleepSync(interval);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
throw new DvmError(
|
|
1717
|
+
"credit_store_locked",
|
|
1718
|
+
`Could not acquire the prepaid-credit lock at ${lockPath} within the retry budget.`,
|
|
1719
|
+
`Another dvm CLI may be writing to ${CREDITS_FILE}. Wait a moment and retry. If no other dvm CLI is running, remove ${lockPath} and try again.`,
|
|
1720
|
+
{
|
|
1721
|
+
lock_file: lockPath,
|
|
1722
|
+
underlying: lastError instanceof Error ? lastError.message : String(lastError)
|
|
1723
|
+
}
|
|
1724
|
+
);
|
|
1725
|
+
}
|
|
1726
|
+
function rejectAsyncBody(result) {
|
|
1727
|
+
if (typeof result?.then !== "function") {
|
|
1728
|
+
return result;
|
|
1729
|
+
}
|
|
1730
|
+
throw new DvmError(
|
|
1731
|
+
"credit_store_lock_misuse",
|
|
1732
|
+
"withCreditLock was called with an asynchronous body. The lock is released when the body returns, so a promise's writes would run unprotected.",
|
|
1733
|
+
"Make the locked body synchronous \u2014 the credit store's whole surface is sync \u2014 and do any awaiting outside the lock."
|
|
1734
|
+
);
|
|
1735
|
+
}
|
|
1736
|
+
function sleepSync(ms) {
|
|
1737
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
export {
|
|
1741
|
+
fiatToSatsCeil,
|
|
1742
|
+
satsToFiat,
|
|
1743
|
+
InvalidUsdPriceError,
|
|
1744
|
+
parseUsdPrice,
|
|
1745
|
+
roundUsd,
|
|
1746
|
+
formatFiat,
|
|
1747
|
+
IMPLICIT_CREDIT_TTL_MS,
|
|
1748
|
+
COINGECKO_SIMPLE_PRICE_URL,
|
|
1749
|
+
fetchCoinGeckoSpot,
|
|
1750
|
+
fetchCoinGeckoBtcUsd,
|
|
1751
|
+
msatsToUsd,
|
|
1752
|
+
usdToMsats,
|
|
1753
|
+
msatsToUsdCents,
|
|
1754
|
+
msatsToUsdc,
|
|
1755
|
+
usdcToMsats,
|
|
1756
|
+
formatSats,
|
|
1757
|
+
formatAmount,
|
|
1758
|
+
formatPaymentAmount,
|
|
1759
|
+
costAnchor,
|
|
1760
|
+
monetaryJson,
|
|
1761
|
+
formatUsd2 as formatUsd,
|
|
1762
|
+
formatUsdcMicrounits,
|
|
1763
|
+
parseBudget,
|
|
1764
|
+
assertValidBudget,
|
|
1765
|
+
fetchBtcUsdRate,
|
|
1766
|
+
getLastKnownBtcRate,
|
|
1767
|
+
formatStaleness,
|
|
1768
|
+
formatAmountBestEffort,
|
|
1769
|
+
setOutputTraceId,
|
|
1770
|
+
getOutputTraceId,
|
|
1771
|
+
json,
|
|
1772
|
+
info,
|
|
1773
|
+
raw,
|
|
1774
|
+
progress,
|
|
1775
|
+
RAIL_FLAGS,
|
|
1776
|
+
maxAdvertisedMicro,
|
|
1777
|
+
withinAdvertisedTolerance,
|
|
1778
|
+
SUPPORTED_PROTOCOL_VERSION,
|
|
1779
|
+
parseCreditTerms,
|
|
1780
|
+
parseCreditMenu,
|
|
1781
|
+
normalizeCreditEndpoint,
|
|
1782
|
+
dvmLocationIdentity,
|
|
1783
|
+
fundingReachableAt,
|
|
1784
|
+
pendingDrainFor,
|
|
1785
|
+
pendingDrainById,
|
|
1786
|
+
loadCredit,
|
|
1787
|
+
clearCreditSelection,
|
|
1788
|
+
listCredits,
|
|
1789
|
+
listImplicitCredits,
|
|
1790
|
+
loadImplicitCredits,
|
|
1791
|
+
markImplicitCreditLost,
|
|
1792
|
+
listFundingMenuSnapshots,
|
|
1793
|
+
recordFundingMenuSnapshot,
|
|
1794
|
+
listPendingFundings,
|
|
1795
|
+
loadPendingFunding,
|
|
1796
|
+
recordPendingFunding,
|
|
1797
|
+
clearPendingFunding,
|
|
1798
|
+
recordFundResponse,
|
|
1799
|
+
recordBalanceResponse,
|
|
1800
|
+
applyReceiptCredit,
|
|
1801
|
+
applyImplicitReceiptCredit,
|
|
1802
|
+
ensureProvisionalCredit,
|
|
1803
|
+
markCredit,
|
|
1804
|
+
loadCreditX402Binding,
|
|
1805
|
+
recordCreditX402Instrument,
|
|
1806
|
+
recordRefusedDrawBalance,
|
|
1807
|
+
markRefillRailUnavailable,
|
|
1808
|
+
markRefillDrainNoticed,
|
|
1809
|
+
clearRefillRailUnavailable,
|
|
1810
|
+
forgetCredit,
|
|
1811
|
+
recordPendingDrain,
|
|
1812
|
+
clearPendingDrain,
|
|
1813
|
+
recordDrainReceipts,
|
|
1814
|
+
settleDrainEvidence
|
|
1815
|
+
};
|