@dvmkit/dvm-cli 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +8 -0
  2. package/dist/{chunk-24VB7FR7.js → chunk-3YE43JJR.js} +4 -4
  3. package/dist/{chunk-SKKZ4OAA.js → chunk-4KINCBHL.js} +53 -56
  4. package/dist/{chunk-XN4YSEO6.js → chunk-EE2MREOM.js} +152 -93
  5. package/dist/chunk-ERJFRCJO.js +150 -0
  6. package/dist/chunk-FL2ICZW5.js +383 -0
  7. package/dist/chunk-FSYEZERJ.js +1667 -0
  8. package/dist/{chunk-V2BE4E5V.js → chunk-ID5G54HJ.js} +223 -73
  9. package/dist/{chunk-4NWEJTAW.js → chunk-MJ4X4BEW.js} +7953 -8036
  10. package/dist/{chunk-Z75N4GTG.js → chunk-QICJRKB7.js} +23557 -16012
  11. package/dist/{chunk-ECEM3ZAS.js → chunk-R55XNXAR.js} +53 -185
  12. package/dist/{chunk-R4MSO2GX.js → chunk-SHZMNEXE.js} +65 -24
  13. package/dist/chunk-TZWZTS37.js +1517 -0
  14. package/dist/{chunk-VY277ROG.js → chunk-VOO5IAK7.js} +600 -97
  15. package/dist/{chunk-2VVVWBQA.js → chunk-WTM2EICO.js} +2 -352
  16. package/dist/chunk-XHOFQ3OS.js +717 -0
  17. package/dist/{chunk-YLWATJ7F.js → chunk-Z4CZUMUT.js} +937 -1599
  18. package/dist/{client-OWIOFBKS.js → client-RYDA62DU.js} +11 -8
  19. package/dist/{dist-2G3QBGID.js → dist-GKCEIY2A.js} +7 -4
  20. package/dist/dvm.js +478 -70
  21. package/dist/{internal-OBEYRHMV.js → internal-INUTGTXQ.js} +56 -33
  22. package/dist/{payout-reporter-RG6XNGPI-KNY74HLM.js → payout-reporter-3Y2U55ZX-CMKACKA3.js} +2 -2
  23. package/dist/{pocket-refill-NXTJIVB5.js → pocket-refill-K5T4LZF6.js} +18 -14
  24. package/dist/{revenue-reporter-ASZ7SHHH-ISAMJDZQ.js → revenue-reporter-MAERPYGK-CCPZXGFA.js} +2 -2
  25. package/dist/tempo-AXTE4ZEA.js +34 -0
  26. package/dist/{tempo-lifecycle-DFIXQ54Q-LNXPKWK5.js → tempo-lifecycle-ZBBLFBMH-HWI4PLYP.js} +11 -7
  27. package/dist/{tempo-wallet-4QKSV65O-J6ZZQAD7.js → tempo-wallet-B5XXV3YH-SRQBMYFV.js} +2 -2
  28. package/dist/{x402-5H27DCBE-UEQQQ5UY.js → x402-R6HPBY5D-VMSW7Z32.js} +3 -3
  29. package/package.json +2 -2
  30. package/skills/dvm/calling.md +2 -0
  31. package/skills/dvm/credit.md +2 -0
  32. package/dist/chunk-3SWX5BQP.js +0 -66
@@ -5,14 +5,67 @@ import {
5
5
  BTC_RATE_FILE,
6
6
  CREDITS_FILE,
7
7
  DvmError,
8
+ bytesToHex,
8
9
  ensureConfigDir,
9
10
  ensureConfigSubdir,
10
- require_proper_lockfile
11
- } from "./chunk-SKKZ4OAA.js";
11
+ hexToBytes,
12
+ require_proper_lockfile,
13
+ schnorr,
14
+ sha256
15
+ } from "./chunk-4KINCBHL.js";
12
16
  import {
13
17
  __toESM
14
18
  } from "./chunk-IYHTITNZ.js";
15
19
 
20
+ // node_modules/@dvmkit/sdk/dist/chunk-OFVV37XC.js
21
+ function canonicalize(value) {
22
+ return JSON.stringify(sortDeep(value));
23
+ }
24
+ function canonicaliseForSigning(value) {
25
+ return new TextEncoder().encode(canonicalize(value));
26
+ }
27
+ function sortDeep(value) {
28
+ if (value === null) return null;
29
+ if (typeof value === "string" || typeof value === "boolean") return value;
30
+ if (typeof value === "number") {
31
+ if (!Number.isFinite(value)) {
32
+ throw new TypeError(`canonicalize: non-finite number is not JSON-serialisable`);
33
+ }
34
+ return value;
35
+ }
36
+ if (Array.isArray(value)) return value.map(sortDeep);
37
+ if (typeof value === "object") {
38
+ const sorted = {};
39
+ for (const key of Object.keys(value).sort()) {
40
+ const v = value[key];
41
+ if (v === void 0) continue;
42
+ sorted[key] = sortDeep(v);
43
+ }
44
+ return sorted;
45
+ }
46
+ throw new TypeError(`canonicalize: unsupported value of type ${typeof value}`);
47
+ }
48
+ function verifyCanonicalSignedRequest(payload, signatureHex, pubkeyHex) {
49
+ if (!/^[0-9a-f]{64}$/i.test(pubkeyHex) || !/^[0-9a-f]{128}$/i.test(signatureHex)) {
50
+ return false;
51
+ }
52
+ const data = canonicaliseForSigning(payload);
53
+ const signature = hexToBytes2(signatureHex);
54
+ const pubkey = hexToBytes2(pubkeyHex);
55
+ try {
56
+ return schnorr.verify(signature, data, pubkey);
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+ function hexToBytes2(hex) {
62
+ const out = new Uint8Array(hex.length / 2);
63
+ for (let i = 0; i < out.length; i++) {
64
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
65
+ }
66
+ return out;
67
+ }
68
+
16
69
  // node_modules/@dvmkit/sdk/dist/chunk-AT6V3SY7.js
17
70
  var InvalidFxRateError = class extends Error {
18
71
  code = "invalid_fx_rate";
@@ -105,7 +158,7 @@ var FIAT_SYMBOLS = {
105
158
  jpy: "\xA5"
106
159
  };
107
160
 
108
- // node_modules/@dvmkit/sdk/dist/chunk-5URG56JJ.js
161
+ // node_modules/@dvmkit/sdk/dist/chunk-PAIM66YA.js
109
162
  import { existsSync, readFileSync, writeFileSync } from "fs";
110
163
  import { dirname } from "path";
111
164
  var IMPLICIT_CREDIT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
@@ -161,8 +214,24 @@ function msatsToUsdCents(msats, btcPriceUsd) {
161
214
  return Math.round(usd * 100);
162
215
  }
163
216
  function msatsToUsdc(msats, btcUsdRate) {
164
- const usd = msatsToUsd(msats, btcUsdRate);
165
- return Math.ceil(usd * 1e6);
217
+ if (!Number.isSafeInteger(msats) || msats < 0) {
218
+ throw new RangeError("msats must be a non-negative safe integer");
219
+ }
220
+ if (!Number.isFinite(btcUsdRate) || btcUsdRate <= 0) {
221
+ throw new RangeError("BTC/USD rate must be finite and positive");
222
+ }
223
+ const [mantissa, exponent = "0"] = btcUsdRate.toString().split("e");
224
+ const decimalPlaces = mantissa.split(".")[1]?.length ?? 0;
225
+ const shift = Number(exponent) - decimalPlaces;
226
+ let numerator = BigInt(msats) * BigInt(mantissa.replace(".", ""));
227
+ let denominator = 100000n;
228
+ if (shift > 0) numerator *= 10n ** BigInt(shift);
229
+ else if (shift < 0) denominator *= 10n ** BigInt(-shift);
230
+ const micro = (numerator + denominator - 1n) / denominator;
231
+ if (micro > BigInt(Number.MAX_SAFE_INTEGER)) {
232
+ throw new RangeError("USDC micro-unit amount exceeds the safe integer range");
233
+ }
234
+ return Number(micro);
166
235
  }
167
236
  function usdcToMsats(usdc, btcUsdRate) {
168
237
  return usdToMsats(usdc, btcUsdRate);
@@ -175,13 +244,13 @@ function formatSats(msats) {
175
244
  }
176
245
  function formatAmount(msats, rate, opts) {
177
246
  const usd = msatsToUsd(msats, rate);
178
- const base = `~$${formatUsd2(usd)} (${formatSats(msats)})`;
179
- return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(usd)}`;
247
+ const base2 = `~$${formatUsd2(usd)} (${formatSats(msats)})`;
248
+ return opts?.anchor === false ? base2 : `${base2} \u2014 ${costAnchor(usd)}`;
180
249
  }
181
250
  function formatPaymentAmount(msats, fiat, opts) {
182
251
  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)}`;
252
+ const base2 = `${formatFiat(fiat.amount, fiat.currency)} (${formatSats(msats)})`;
253
+ return opts?.anchor === false ? base2 : `${base2} \u2014 ${costAnchor(fiat.amount, fiat.currency)}`;
185
254
  }
186
255
  var COST_ANCHOR_BANDS = {
187
256
  usd: [0.01, 0.1, 1, 10],
@@ -262,9 +331,9 @@ function formatAmountBestEffort(msats, opts) {
262
331
  const m = msats ?? 0;
263
332
  const cached = getLastKnownBtcRate();
264
333
  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)})`;
334
+ const base2 = formatAmount(m, cached.rate, opts);
335
+ if (Date.now() - cached.cachedAt < CACHE_TTL) return base2;
336
+ return `${base2} (rate cached ${formatStaleness(cached.cachedAt)})`;
268
337
  }
269
338
  var CACHE_TTL = 5 * 60 * 1e3;
270
339
  var CACHE_FILE = BTC_RATE_FILE;
@@ -310,45 +379,91 @@ async function fetchFromApi() {
310
379
  }
311
380
  return rate;
312
381
  }
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;
382
+ function computeResultHash(summary, artifactContents) {
383
+ const artifactHashes = artifactContents.map(
384
+ (content) => bytesToHex(sha256(canonicaliseForSigning(content)))
385
+ );
386
+ return bytesToHex(
387
+ sha256(
388
+ canonicaliseForSigning({
389
+ summary: summary ?? null,
390
+ artifact_hashes: artifactHashes
391
+ })
392
+ )
393
+ );
394
+ }
395
+ function signReceipt(unsigned, secretHex) {
396
+ const bytes = canonicaliseForSigning(unsigned);
397
+ const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
398
+ return { ...unsigned, signature };
322
399
  }
323
- function getOutputTraceId() {
324
- return _traceId;
400
+ function verifyReceipt(receipt) {
401
+ try {
402
+ const { signature, ...unsigned } = receipt;
403
+ const bytes = canonicaliseForSigning(unsigned);
404
+ return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
405
+ } catch {
406
+ return false;
407
+ }
325
408
  }
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");
409
+ function isSignedJobReceipt(value) {
410
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
411
+ const r = value;
412
+ const paid = r.paid;
413
+ return r.v === 1 && typeof r.job_id === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.capability === "string" && (r.outcome === "completed" || r.outcome === "failed" || r.outcome === "cancelled") && typeof r.seq === "number" && typeof r.issued_at === "number" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string" && !!paid && typeof paid === "object" && !Array.isArray(paid) && typeof paid.msats === "number";
329
414
  }
330
- function info(msg) {
331
- writeAllSync(2, msg + "\n");
415
+ function signDrainReceipt(unsigned, secretHex) {
416
+ const bytes = canonicaliseForSigning(unsigned);
417
+ const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
418
+ return { ...unsigned, signature };
332
419
  }
333
- function raw(msg) {
334
- writeAllSync(1, msg + "\n");
420
+ function signFundingReceipt(unsigned, secretHex) {
421
+ const bytes = canonicaliseForSigning(unsigned);
422
+ const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
423
+ return { ...unsigned, signature };
335
424
  }
336
- function progress(event) {
337
- writeAllSync(2, JSON.stringify(event) + "\n");
425
+ function isFundingReceipt(value) {
426
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
427
+ const r = value;
428
+ return r.v === 1 && r.kind === "credit_funding" && typeof r.credit_id === "string" && typeof r.fund_id === "string" && typeof r.funded_micro === "number" && typeof r.balance_after_micro === "number" && typeof r.ledger_seq === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
338
429
  }
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
- }
430
+ function verifyFundingReceipt(receipt) {
431
+ try {
432
+ const { signature, ...unsigned } = receipt;
433
+ const bytes = canonicaliseForSigning(unsigned);
434
+ return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
435
+ } catch {
436
+ return false;
350
437
  }
351
438
  }
439
+ function isDrainReceipt(value) {
440
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
441
+ const r = value;
442
+ return r.v === 1 && r.kind === "credit_drain" && typeof r.credit_id === "string" && typeof r.drain_id === "string" && (r.event === "requested" || r.event === "parked" || r.event === "picked_up" || r.event === "sent" || r.event === "released") && typeof r.method === "string" && typeof r.amount_micro === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
443
+ }
444
+ function verifyDrainReceipt(receipt) {
445
+ try {
446
+ const { signature, ...unsigned } = receipt;
447
+ const bytes = canonicaliseForSigning(unsigned);
448
+ return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
449
+ } catch {
450
+ return false;
451
+ }
452
+ }
453
+
454
+ // node_modules/@dvmkit/sdk/dist/chunk-B2IROPQF.js
455
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
456
+ import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
457
+ import { dirname as dirname2 } from "path";
458
+ import { createHash } from "crypto";
459
+ import {
460
+ closeSync,
461
+ fsyncSync,
462
+ openSync,
463
+ readFileSync as readFileSync3,
464
+ writeSync,
465
+ ftruncateSync
466
+ } from "fs";
352
467
  var RAIL_FLAGS = ["cashu", "tempo", "x402"];
353
468
  var ADVERTISED_AMOUNT_TOLERANCE_BPS = 1000n;
354
469
  function maxAdvertisedMicro(localMicro) {
@@ -358,9 +473,9 @@ function withinAdvertisedTolerance(advertisedMicro, localMicro) {
358
473
  return advertisedMicro * 10000n <= localMicro * (10000n + ADVERTISED_AMOUNT_TOLERANCE_BPS);
359
474
  }
360
475
  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;
476
+ function parseCreditTerms(raw) {
477
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
478
+ const credit = raw;
364
479
  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
480
  return void 0;
366
481
  const tempo = credit.tempo === void 0 ? void 0 : parseCreditTempoTerms(credit.tempo);
@@ -380,10 +495,10 @@ function parseCreditTerms(raw2) {
380
495
  }
381
496
  };
382
497
  }
383
- function parseCreditMenu(raw2) {
384
- const terms = parseCreditTerms(raw2);
498
+ function parseCreditMenu(raw) {
499
+ const terms = parseCreditTerms(raw);
385
500
  if (!terms) return void 0;
386
- const credit = raw2;
501
+ const credit = raw;
387
502
  return {
388
503
  ...terms,
389
504
  ...typeof credit.credit_id === "string" && { credit_id: credit.credit_id },
@@ -394,9 +509,9 @@ function parseCreditMenu(raw2) {
394
509
  ...typeof credit.expiry_ms === "number" && { expiry_ms: credit.expiry_ms }
395
510
  };
396
511
  }
397
- function parseCreditTempoTerms(raw2) {
398
- if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
399
- const block = raw2;
512
+ function parseCreditTempoTerms(raw) {
513
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
514
+ const block = raw;
400
515
  if (!Array.isArray(block.methods) || !block.methods.every(isCreditTempoMethod)) return void 0;
401
516
  if (block.withheld !== void 0 && (!Array.isArray(block.withheld) || !block.withheld.every(isCreditTempoWithheldMethod)))
402
517
  return void 0;
@@ -414,15 +529,15 @@ function parseCreditTempoTerms(raw2) {
414
529
  }
415
530
  };
416
531
  }
417
- function isCreditTempoMethod(raw2) {
418
- return !!raw2 && typeof raw2 === "object" && typeof raw2.method === "string" && (raw2.intent === "charge" || raw2.intent === "session");
532
+ function isCreditTempoMethod(raw) {
533
+ return !!raw && typeof raw === "object" && typeof raw.method === "string" && (raw.intent === "charge" || raw.intent === "session");
419
534
  }
420
- function isCreditTempoWithheldMethod(raw2) {
421
- return isCreditTempoMethod(raw2) && typeof raw2.reason === "string";
535
+ function isCreditTempoWithheldMethod(raw) {
536
+ return isCreditTempoMethod(raw) && typeof raw.reason === "string";
422
537
  }
423
- function parseCreditX402Terms(raw2) {
424
- if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
425
- const schemes = raw2.schemes;
538
+ function parseCreditX402Terms(raw) {
539
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
540
+ const schemes = raw.schemes;
426
541
  if (!Array.isArray(schemes) || !schemes.every(
427
542
  (entry) => !!entry && typeof entry === "object" && typeof entry.scheme === "string" && typeof entry.network === "string"
428
543
  ))
@@ -434,6 +549,332 @@ function parseCreditX402Terms(raw2) {
434
549
  }))
435
550
  };
436
551
  }
552
+ function historyPath() {
553
+ return `${CREDITS_FILE.slice(0, -5)}-history.jsonl`;
554
+ }
555
+ function hash(value) {
556
+ return createHash("sha256").update(value).digest("hex");
557
+ }
558
+ function fail(detail) {
559
+ throw new DvmError(
560
+ "credit_history_unavailable",
561
+ `Completed credit history could not be preserved: ${detail}`,
562
+ "Keep the credit store and history file intact, fix the file access or damage, and retry. Working evidence was not evicted."
563
+ );
564
+ }
565
+ var receiptKeys = /* @__PURE__ */ new Set([
566
+ "v",
567
+ "kind",
568
+ "credit_id",
569
+ "drain_id",
570
+ "event",
571
+ "method",
572
+ "amount_micro",
573
+ "balance_after_micro",
574
+ "ledger_seq",
575
+ "issued_at",
576
+ "caller_pubkey",
577
+ "dvm_id",
578
+ "dvm",
579
+ "receipt_pubkey",
580
+ "signature"
581
+ ]);
582
+ var attestationKeys = /* @__PURE__ */ new Set([
583
+ "dvm_id",
584
+ "slug",
585
+ "capabilities_hash",
586
+ "builder_pubkey",
587
+ "receipt_pubkey",
588
+ "deployed_at"
589
+ ]);
590
+ function safeReceipts(bundle) {
591
+ const receipts = [];
592
+ for (const receipt of bundle.receipts) {
593
+ if (!isDrainReceipt(receipt))
594
+ fail("a completed bundle contains an unrecognized receipt");
595
+ if (Object.keys(receipt).some((key) => !receiptKeys.has(key)))
596
+ fail("a receipt contains unsupported fields");
597
+ if (Object.values(receipt).some(
598
+ (value) => typeof value !== "string" && typeof value !== "number" || typeof value === "number" && (!Number.isSafeInteger(value) || value < 0)
599
+ ))
600
+ fail("a receipt contains unsupported values");
601
+ receipts.push(receipt);
602
+ }
603
+ return receipts;
604
+ }
605
+ function safeAnchor(anchor) {
606
+ if (!anchor) return void 0;
607
+ if (typeof anchor.pubkey !== "string" || typeof anchor.signature !== "string" || !anchor.attestation || Object.keys(anchor.attestation).some((key) => !attestationKeys.has(key)) || Object.values(anchor.attestation).some(
608
+ (value) => typeof value !== "string" && typeof value !== "number"
609
+ ))
610
+ fail("an advertisement contains unsupported fields");
611
+ return {
612
+ pubkey: anchor.pubkey,
613
+ signature: anchor.signature,
614
+ attestation: anchor.attestation
615
+ };
616
+ }
617
+ function hasAttestedIdentity(record) {
618
+ return Boolean(record.dvmId && record.attestedBuilderPubkey);
619
+ }
620
+ function compatibleLocations(left, right) {
621
+ if (hasAttestedIdentity(left) && hasAttestedIdentity(right))
622
+ return left.dvmId === right.dvmId && left.attestedBuilderPubkey === right.attestedBuilderPubkey;
623
+ return [left.endpoint, ...left.endpointAliases].some(
624
+ (origin) => [right.endpoint, ...right.endpointAliases].includes(origin)
625
+ );
626
+ }
627
+ function base(record, identity, occurredAt) {
628
+ return {
629
+ v: 1,
630
+ id: hash(
631
+ JSON.stringify([
632
+ record.callerPubkey,
633
+ hasAttestedIdentity(record) ? record.dvmId : record.endpoint,
634
+ hasAttestedIdentity(record) ? record.attestedBuilderPubkey : null,
635
+ record.creditId,
636
+ identity
637
+ ])
638
+ ),
639
+ endpoint: record.endpoint,
640
+ endpointAliases: record.endpointAliases ?? [],
641
+ dvmId: record.dvmId ?? null,
642
+ attestedBuilderPubkey: record.attestedBuilderPubkey ?? null,
643
+ callerPubkey: record.callerPubkey,
644
+ creditId: record.creditId,
645
+ occurredAt,
646
+ rail: null,
647
+ currency: null,
648
+ amountMicro: null,
649
+ feeMicro: null
650
+ };
651
+ }
652
+ function completedRefund(record, bundle) {
653
+ const receipts = safeReceipts(bundle);
654
+ const anchor = safeAnchor(bundle.anchor);
655
+ const receipt = receipts.find(
656
+ (r) => r.drain_id === bundle.drainId && r.credit_id === bundle.creditId
657
+ );
658
+ const metadata = bundle.settlement;
659
+ if (metadata && (metadata.rail !== null && typeof metadata.rail !== "string" || metadata.currency !== null && typeof metadata.currency !== "string" || [metadata.amountMicro, metadata.feeMicro].some(
660
+ (value) => value !== null && (!Number.isSafeInteger(value) || value < 0)
661
+ )))
662
+ fail("invalid settlement metadata");
663
+ return {
664
+ ...base(
665
+ { ...record, creditId: bundle.creditId },
666
+ `refund:${bundle.drainId}`,
667
+ bundle.settledAt
668
+ ),
669
+ kind: "completed_refund",
670
+ outcome: "refunded",
671
+ drainId: bundle.drainId,
672
+ settledAt: bundle.settledAt,
673
+ collectedAt: bundle.collectedAt === 0 ? null : bundle.collectedAt,
674
+ rail: metadata?.rail ?? receipt?.method ?? null,
675
+ currency: metadata?.currency ?? null,
676
+ amountMicro: metadata?.amountMicro ?? receipt?.amount_micro ?? null,
677
+ feeMicro: metadata?.feeMicro ?? null,
678
+ receipts,
679
+ ...anchor ? { anchor } : {},
680
+ provenance: {
681
+ settlement: "local_observation",
682
+ receipts: "unverified_observations",
683
+ advertisement: anchor ? "present" : "absent"
684
+ }
685
+ };
686
+ }
687
+ function completedLoss(record) {
688
+ return {
689
+ ...base(record, "loss", record.updatedAt),
690
+ kind: "expired_credit_loss",
691
+ outcome: "lost",
692
+ rail: record.creditId.startsWith("imp:") ? record.creditId.split(":")[1] || null : null,
693
+ currency: record.currency,
694
+ amountMicro: record.remainingMicro,
695
+ reason: record.lossReason ?? "expired",
696
+ releasedAt: record.releasedAt,
697
+ expiryMs: record.expiryMs,
698
+ releasedByJobId: record.releasedByJobId
699
+ };
700
+ }
701
+ function validateHistoryRecord(row) {
702
+ if (!row || row.v !== 1 || typeof row.id !== "string" || !Number.isSafeInteger(row.occurredAt) || typeof row.endpoint !== "string" || typeof row.callerPubkey !== "string" || typeof row.creditId !== "string" || !Array.isArray(row.endpointAliases) || row.endpointAliases.some((value) => typeof value !== "string") || [row.dvmId, row.attestedBuilderPubkey, row.currency, row.rail].some(
703
+ (value) => value !== null && typeof value !== "string"
704
+ ) || [row.amountMicro, row.feeMicro].some(
705
+ (value) => value !== null && (!Number.isSafeInteger(value) || value < 0)
706
+ ))
707
+ fail("invalid complete journal entry");
708
+ if (row.kind === "completed_refund") {
709
+ if (row.outcome !== "refunded" || typeof row.drainId !== "string" || !Number.isSafeInteger(row.settledAt) || row.collectedAt !== null && !Number.isSafeInteger(row.collectedAt) || !Array.isArray(row.receipts) || row.provenance?.settlement !== "local_observation" || row.provenance.receipts !== "unverified_observations" || !["present", "absent"].includes(row.provenance.advertisement))
710
+ fail("invalid refund entry");
711
+ safeReceipts({
712
+ drainId: row.drainId,
713
+ creditId: row.creditId,
714
+ receipts: row.receipts,
715
+ collectedAt: row.collectedAt ?? 0
716
+ });
717
+ safeAnchor(row.anchor);
718
+ } else if (row.kind === "expired_credit_loss") {
719
+ if (row.outcome !== "lost" || !["expired", "not_found"].includes(row.reason) || !Number.isSafeInteger(row.releasedAt) || !Number.isSafeInteger(row.expiryMs) || typeof row.releasedByJobId !== "string")
720
+ fail("invalid loss entry");
721
+ } else fail("invalid complete journal entry");
722
+ }
723
+ function journal() {
724
+ let bytes;
725
+ try {
726
+ bytes = readFileSync3(historyPath());
727
+ } catch (error) {
728
+ if (error.code === "ENOENT")
729
+ return { bytes: Buffer.alloc(0), complete: 0, rows: [] };
730
+ fail(error instanceof Error ? error.message : String(error));
731
+ }
732
+ const complete = bytes.lastIndexOf(10) + 1;
733
+ const rows = bytes.subarray(0, complete).toString("utf8").split("\n").filter(Boolean).map((line) => {
734
+ let row;
735
+ try {
736
+ row = JSON.parse(line);
737
+ } catch {
738
+ fail("damaged complete journal line");
739
+ }
740
+ validateHistoryRecord(row);
741
+ return row;
742
+ });
743
+ return { bytes, complete, rows };
744
+ }
745
+ function archiveCompletedCreditRecords(records) {
746
+ if (!records.length) return;
747
+ try {
748
+ const current = journal();
749
+ const latest = new Map(
750
+ current.rows.map((record) => [record.id, JSON.stringify(record)])
751
+ );
752
+ const observed = new Map(current.rows.map((record) => [record.id, record]));
753
+ const additions = [];
754
+ for (const incoming of records) {
755
+ const prior = [...observed.values()].reverse().find(
756
+ (row) => row.kind === incoming.kind && row.callerPubkey === incoming.callerPubkey && row.creditId === incoming.creditId && (row.kind !== "completed_refund" || incoming.kind === "completed_refund" && row.drainId === incoming.drainId) && compatibleLocations(row, incoming)
757
+ );
758
+ const newerPrior = prior && (incoming.kind === "completed_refund" && prior.kind === "completed_refund" ? (prior.collectedAt ?? 0) > (incoming.collectedAt ?? 0) : prior.occurredAt > incoming.occurredAt);
759
+ const facts = newerPrior ? prior : incoming;
760
+ const identity = prior && hasAttestedIdentity(prior) ? prior : hasAttestedIdentity(incoming) ? incoming : newerPrior || !incoming.dvmId && !incoming.attestedBuilderPubkey ? prior ?? incoming : incoming;
761
+ const record = prior ? {
762
+ ...facts,
763
+ id: prior.id,
764
+ dvmId: identity.dvmId,
765
+ attestedBuilderPubkey: identity.attestedBuilderPubkey,
766
+ endpointAliases: [
767
+ .../* @__PURE__ */ new Set([
768
+ prior.endpoint,
769
+ ...prior.endpointAliases,
770
+ incoming.endpoint,
771
+ ...incoming.endpointAliases
772
+ ])
773
+ ].filter((origin) => origin !== facts.endpoint)
774
+ } : incoming;
775
+ validateHistoryRecord(record);
776
+ const encoded = JSON.stringify(record);
777
+ if (latest.get(record.id) === encoded) continue;
778
+ additions.push(encoded + "\n");
779
+ latest.set(record.id, encoded);
780
+ observed.set(record.id, record);
781
+ }
782
+ const fd = openSync(historyPath(), "a", 384);
783
+ try {
784
+ if (current.complete !== current.bytes.length)
785
+ ftruncateSync(fd, current.complete);
786
+ const bytes = Buffer.from(additions.join(""));
787
+ let written = 0;
788
+ while (written < bytes.length) {
789
+ const count = writeSync(fd, bytes, written, bytes.length - written);
790
+ if (!count) fail("zero-length append");
791
+ written += count;
792
+ }
793
+ fsyncSync(fd);
794
+ } finally {
795
+ closeSync(fd);
796
+ }
797
+ {
798
+ const directory = openSync(
799
+ historyPath().slice(0, historyPath().lastIndexOf("/")),
800
+ "r"
801
+ );
802
+ try {
803
+ fsyncSync(directory);
804
+ } finally {
805
+ closeSync(directory);
806
+ }
807
+ }
808
+ } catch (error) {
809
+ fail(error instanceof Error ? error.message : String(error));
810
+ }
811
+ }
812
+ function readCreditHistoryPage(query) {
813
+ const limit = query.limit ?? 50;
814
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
815
+ throw new DvmError(
816
+ "invalid_credit_history_query",
817
+ "History page limit must be an integer from 1 through 100."
818
+ );
819
+ const order = query.order ?? "asc";
820
+ if (order !== "asc" && order !== "desc")
821
+ throw new DvmError(
822
+ "invalid_credit_history_query",
823
+ "History order must be asc or desc."
824
+ );
825
+ const direction = order === "asc" ? 1 : -1;
826
+ const filter = JSON.stringify([
827
+ order,
828
+ query.endpoint ? new URL(query.endpoint).origin : null,
829
+ query.dvmId ?? null,
830
+ query.callerPubkey ?? null
831
+ ]);
832
+ const current = journal();
833
+ let end = current.complete;
834
+ let after;
835
+ if (query.cursor) {
836
+ try {
837
+ const cursor = JSON.parse(
838
+ Buffer.from(query.cursor, "base64url").toString("utf8")
839
+ );
840
+ if (cursor.v !== 1 || !Number.isSafeInteger(cursor.end) || cursor.end < 0 || cursor.end > current.complete || cursor.end > 0 && current.bytes[cursor.end - 1] !== 10 || cursor.filter !== filter || cursor.prefix !== hash(current.bytes.subarray(0, cursor.end).toString("utf8")) || !Array.isArray(cursor.after) || !Number.isFinite(cursor.after[0]) || typeof cursor.after[1] !== "string")
841
+ throw new Error("cursor mismatch");
842
+ end = cursor.end;
843
+ after = cursor.after;
844
+ } catch {
845
+ throw new DvmError(
846
+ "invalid_credit_history_cursor",
847
+ "History cursor is invalid, stale, or belongs to different filters."
848
+ );
849
+ }
850
+ }
851
+ const rows = current.bytes.subarray(0, end).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
852
+ const endpoint = query.endpoint ? new URL(query.endpoint).origin : void 0;
853
+ const ordered = [...new Map(rows.map((row) => [row.id, row])).values()].filter(
854
+ (row) => (!endpoint || row.endpoint === endpoint || row.endpointAliases.includes(endpoint)) && (!query.dvmId || row.dvmId === query.dvmId) && (!query.callerPubkey || row.callerPubkey === query.callerPubkey)
855
+ ).sort(
856
+ (a, b) => direction * (a.occurredAt - b.occurredAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
857
+ );
858
+ const remaining = ordered.filter(
859
+ (row) => !after || direction * (row.occurredAt - after[0]) > 0 || row.occurredAt === after[0] && (direction === 1 ? row.id > after[1] : row.id < after[1])
860
+ );
861
+ const records = remaining.slice(0, limit);
862
+ const last = records.at(-1);
863
+ return {
864
+ records,
865
+ ...remaining.length > limit && last ? {
866
+ nextCursor: Buffer.from(
867
+ JSON.stringify({
868
+ v: 1,
869
+ end,
870
+ prefix: hash(current.bytes.subarray(0, end).toString("utf8")),
871
+ filter,
872
+ after: [last.occurredAt, last.id]
873
+ })
874
+ ).toString("base64url")
875
+ } : {}
876
+ };
877
+ }
437
878
  function withCreditLock(fn, opts = {}) {
438
879
  if (lockDepth > 0) {
439
880
  lockDepth += 1;
@@ -556,6 +997,12 @@ function clearCreditSelection(endpoint, callerPubkey, creditId, identity) {
556
997
  return structuredClone(record);
557
998
  });
558
999
  }
1000
+ function readCompletedCreditHistory(query = {}) {
1001
+ return withCreditLock(() => {
1002
+ loadStore(true);
1003
+ return readCreditHistoryPage(query);
1004
+ });
1005
+ }
559
1006
  function listCredits() {
560
1007
  return withCreditLock(() => [...loadStore().credits].sort((a, b) => b.updatedAt - a.updatedAt));
561
1008
  }
@@ -606,7 +1053,13 @@ function markImplicitCreditLost(args) {
606
1053
  where: (candidate) => candidate.callerPubkey === args.callerPubkey && candidate.creditId === args.creditId
607
1054
  });
608
1055
  if (!record) return void 0;
609
- attachDvmLocation(record, key, args.identity);
1056
+ const locationChanged = attachDvmLocation(record, key, args.identity);
1057
+ if (record.status === "lost" && !archiveOrKeep(
1058
+ () => archiveCompletedCreditRecords([completedLoss(record)])
1059
+ )) {
1060
+ if (locationChanged) saveStore(store);
1061
+ return record;
1062
+ }
610
1063
  record.status = "lost";
611
1064
  record.lossReason = args.reason;
612
1065
  record.updatedAt = args.now ?? Date.now();
@@ -875,7 +1328,13 @@ function applyImplicitReceiptCredit(args) {
875
1328
  saveStore(store);
876
1329
  return store.implicitCredits.includes(record) ? { credit: record } : {};
877
1330
  }
878
- attachDvmLocation(record, key, args.identity);
1331
+ const locationChanged = attachDvmLocation(record, key, args.identity);
1332
+ if (record.status === "lost" && !archiveOrKeep(
1333
+ () => archiveCompletedCreditRecords([completedLoss(record)])
1334
+ )) {
1335
+ if (locationChanged) saveStore(store);
1336
+ return { credit: record };
1337
+ }
879
1338
  let mismatch;
880
1339
  const sequential = args.credit.ledger_seq === record.ledgerSeq + 1;
881
1340
  if (sequential && args.outcome === "completed" && record.status === "active") {
@@ -1052,6 +1511,9 @@ function forgetCredit(endpoint, callerPubkey, identity) {
1052
1511
  where: (c) => c.callerPubkey === callerPubkey
1053
1512
  });
1054
1513
  if (!record) return;
1514
+ archiveCompletedCreditRecords(
1515
+ (record.drainEvidence ?? []).filter((bundle) => bundle.settledAt !== void 0).map((bundle) => completedRefund(record, bundle))
1516
+ );
1055
1517
  saveStore({ ...store, credits: store.credits.filter((c) => c !== record) });
1056
1518
  });
1057
1519
  }
@@ -1063,7 +1525,7 @@ function recordPendingDrain(endpoint, callerPubkey, drain, identity) {
1063
1525
  );
1064
1526
  if (index === -1) drains.push(drain);
1065
1527
  else drains[index] = drain;
1066
- record.pendingDrains = capPendingDrains(drains, record.creditId);
1528
+ record.pendingDrains = drains;
1067
1529
  return void 0;
1068
1530
  });
1069
1531
  }
@@ -1094,6 +1556,11 @@ function recordDrainReceipts(args) {
1094
1556
  mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
1095
1557
  const evidence = record.drainEvidence ??= [];
1096
1558
  let bundle = evidence.find((e) => e.drainId === drainId);
1559
+ if (bundle?.settledAt !== void 0 && !archiveOrKeep(
1560
+ () => archiveCompletedCreditRecords([completedRefund(record, bundle)])
1561
+ )) {
1562
+ return "skip";
1563
+ }
1097
1564
  if (!bundle) {
1098
1565
  bundle = { drainId, creditId, receipts: [], collectedAt: now };
1099
1566
  evidence.push(bundle);
@@ -1101,9 +1568,15 @@ function recordDrainReceipts(args) {
1101
1568
  bundle.creditId = creditId;
1102
1569
  bundle.receipts = receipts;
1103
1570
  bundle.collectedAt = now;
1571
+ bundle.settlement ??= {
1572
+ rail: null,
1573
+ currency: record.creditId === creditId ? record.currency : null,
1574
+ amountMicro: null,
1575
+ feeMicro: null
1576
+ };
1104
1577
  if (read.anchor) bundle.anchor = read.anchor;
1105
1578
  else if (read.reachable) delete bundle.anchor;
1106
- record.drainEvidence = capDrainEvidence(evidence, endpoint);
1579
+ record.drainEvidence = evidence;
1107
1580
  return void 0;
1108
1581
  });
1109
1582
  }
@@ -1114,7 +1587,8 @@ function settleDrainEvidence(args) {
1114
1587
  const bundle = evidence.find((e) => e.drainId === drainId);
1115
1588
  if (!bundle || bundle.settledAt !== void 0) return "skip";
1116
1589
  bundle.settledAt = now;
1117
- record.drainEvidence = capDrainEvidence(evidence, endpoint);
1590
+ if (args.settlement) bundle.settlement = args.settlement;
1591
+ record.drainEvidence = evidence;
1118
1592
  return void 0;
1119
1593
  });
1120
1594
  }
@@ -1177,23 +1651,22 @@ function adoptCreditId(record, creditId) {
1177
1651
  delete record.discrepancy;
1178
1652
  delete record.lastReceiptJobId;
1179
1653
  }
1180
- var MAX_PENDING_DRAINS = 8;
1181
1654
  var MAX_SETTLED_DRAIN_EVIDENCE = 8;
1182
1655
  var MAX_LOST_IMPLICIT_CREDITS = 8;
1183
1656
  var MAX_DATE_MS = 864e13;
1184
- function loadStore() {
1657
+ function loadStore(requireArchive = false) {
1185
1658
  if (!existsSync2(CREDITS_FILE)) {
1186
1659
  return { credits: [], implicitCredits: [], pendingFundings: [], fundingMenuSnapshots: [] };
1187
1660
  }
1188
- let raw2;
1661
+ let raw;
1189
1662
  try {
1190
- raw2 = readFileSync2(CREDITS_FILE, "utf-8");
1663
+ raw = readFileSync2(CREDITS_FILE, "utf-8");
1191
1664
  } catch (cause) {
1192
1665
  throw unreadableStore(cause);
1193
1666
  }
1194
1667
  let data;
1195
1668
  try {
1196
- const parsed = JSON.parse(raw2);
1669
+ const parsed = JSON.parse(raw);
1197
1670
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1198
1671
  throw new Error("the file parsed as JSON but is not a credit-store object");
1199
1672
  }
@@ -1214,7 +1687,8 @@ function loadStore() {
1214
1687
  Array.isArray(data.pendingFundings) ? data.pendingFundings.filter((funding) => isObjectRecord(funding)).map(normalizeRailKey) : []
1215
1688
  );
1216
1689
  const implicit = dedupeImplicitCredits(
1217
- Array.isArray(data.implicitCredits) ? data.implicitCredits.filter(isStoredImplicitCredit) : []
1690
+ Array.isArray(data.implicitCredits) ? data.implicitCredits.filter(isStoredImplicitCredit) : [],
1691
+ requireArchive
1218
1692
  );
1219
1693
  const store = {
1220
1694
  credits: merged.credits,
@@ -1222,14 +1696,16 @@ function loadStore() {
1222
1696
  pendingFundings: fundings.fundings,
1223
1697
  fundingMenuSnapshots: snapshots.snapshots
1224
1698
  };
1699
+ if (requireArchive) archiveStore(store);
1225
1700
  if (merged.changed || snapshots.changed || fundings.changed || implicit.changed) saveStore(store);
1701
+ else if (!requireArchive) archiveOrKeep(() => archiveStore(store));
1226
1702
  return store;
1227
1703
  }
1228
1704
  function isStoredImplicitCredit(value) {
1229
1705
  if (!isObjectRecord(value)) return false;
1230
1706
  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
1707
  }
1232
- function dedupeImplicitCredits(credits) {
1708
+ function dedupeImplicitCredits(credits, requireArchive = false) {
1233
1709
  const merged = [];
1234
1710
  let changed = false;
1235
1711
  for (const candidate of credits) {
@@ -1244,6 +1720,9 @@ function dedupeImplicitCredits(credits) {
1244
1720
  merged.push(candidate);
1245
1721
  continue;
1246
1722
  }
1723
+ if (!archiveOrKeep(() => archiveCompletedCreditRecords(
1724
+ [existing, candidate].filter((record) => record.status === "lost").map(completedLoss)
1725
+ ), requireArchive)) return { credits, changed: false };
1247
1726
  changed = true;
1248
1727
  for (const origin of dvmLocationOrigins(candidate)) {
1249
1728
  attachDvmLocation(existing, origin, identity);
@@ -1265,7 +1744,7 @@ function dedupeImplicitCredits(credits) {
1265
1744
  existing.releasedByJobId = candidate.releasedByJobId;
1266
1745
  }
1267
1746
  }
1268
- const capped = capLostImplicitCredits(merged);
1747
+ const capped = capLostImplicitCredits(merged, requireArchive);
1269
1748
  return { credits: capped.credits, changed: changed || capped.changed };
1270
1749
  }
1271
1750
  function ageImplicitCredits(credits, now) {
@@ -1280,7 +1759,14 @@ function ageImplicitCredits(credits, now) {
1280
1759
  }
1281
1760
  return changed;
1282
1761
  }
1283
- function capLostImplicitCredits(credits) {
1762
+ function capLostImplicitCredits(credits, requireArchive = false) {
1763
+ const archived = archiveOrKeep(
1764
+ () => archiveCompletedCreditRecords(
1765
+ credits.filter((credit) => credit.status === "lost").map(completedLoss)
1766
+ ),
1767
+ requireArchive
1768
+ );
1769
+ if (!archived) return { credits, changed: false };
1284
1770
  const lostByOwner = /* @__PURE__ */ new Map();
1285
1771
  for (const credit of credits) {
1286
1772
  if (credit.status !== "lost") continue;
@@ -1583,30 +2069,39 @@ function isEvidenceish(value) {
1583
2069
  function isDrainish(value) {
1584
2070
  return typeof value === "object" && value !== null && typeof value.drainId === "string";
1585
2071
  }
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
- );
2072
+ function archiveOrKeep(action, requireArchive = false) {
2073
+ try {
2074
+ action();
2075
+ return true;
2076
+ } catch (error) {
2077
+ if (requireArchive || !(error instanceof DvmError) || error.code !== "credit_history_unavailable") {
2078
+ throw error;
2079
+ }
2080
+ return false;
1594
2081
  }
1595
- return drains.filter((d) => !dropped.has(d));
1596
2082
  }
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
- }
2083
+ function archiveStore(store) {
2084
+ archiveCompletedCreditRecords([
2085
+ ...store.credits.flatMap(
2086
+ (credit) => (credit.drainEvidence ?? []).filter((bundle) => bundle.settledAt !== void 0).map((bundle) => completedRefund(credit, bundle))
2087
+ ),
2088
+ ...store.implicitCredits.filter((credit) => credit.status === "lost").map(completedLoss)
2089
+ ]);
2090
+ }
2091
+ function capDrainEvidence(evidence) {
2092
+ const settled = evidence.filter((e) => e.settledAt !== void 0).sort((a, b) => a.settledAt - b.settledAt);
2093
+ const dropped = new Set(
2094
+ settled.slice(0, Math.max(0, settled.length - MAX_SETTLED_DRAIN_EVIDENCE))
2095
+ );
1606
2096
  return evidence.filter((e) => !dropped.has(e));
1607
2097
  }
1608
2098
  function saveStore(store) {
1609
2099
  ensureConfigDir();
2100
+ if (archiveOrKeep(() => archiveStore(store))) {
2101
+ for (const credit of store.credits) {
2102
+ if (credit.drainEvidence) credit.drainEvidence = capDrainEvidence(credit.drainEvidence);
2103
+ }
2104
+ }
1610
2105
  const tmp = `${CREDITS_FILE}.${String(process.pid)}.tmp`;
1611
2106
  writeFileSync2(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
1612
2107
  try {
@@ -1738,6 +2233,9 @@ function sleepSync(ms) {
1738
2233
  }
1739
2234
 
1740
2235
  export {
2236
+ canonicalize,
2237
+ canonicaliseForSigning,
2238
+ verifyCanonicalSignedRequest,
1741
2239
  fiatToSatsCeil,
1742
2240
  satsToFiat,
1743
2241
  InvalidUsdPriceError,
@@ -1766,12 +2264,16 @@ export {
1766
2264
  getLastKnownBtcRate,
1767
2265
  formatStaleness,
1768
2266
  formatAmountBestEffort,
1769
- setOutputTraceId,
1770
- getOutputTraceId,
1771
- json,
1772
- info,
1773
- raw,
1774
- progress,
2267
+ computeResultHash,
2268
+ signReceipt,
2269
+ verifyReceipt,
2270
+ isSignedJobReceipt,
2271
+ signDrainReceipt,
2272
+ signFundingReceipt,
2273
+ isFundingReceipt,
2274
+ verifyFundingReceipt,
2275
+ isDrainReceipt,
2276
+ verifyDrainReceipt,
1775
2277
  RAIL_FLAGS,
1776
2278
  maxAdvertisedMicro,
1777
2279
  withinAdvertisedTolerance,
@@ -1785,6 +2287,7 @@ export {
1785
2287
  pendingDrainById,
1786
2288
  loadCredit,
1787
2289
  clearCreditSelection,
2290
+ readCompletedCreditHistory,
1788
2291
  listCredits,
1789
2292
  listImplicitCredits,
1790
2293
  loadImplicitCredits,