@dvmkit/dvm-cli 0.19.2 → 0.20.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.
@@ -3,19 +3,20 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  connectedTempoAccount
6
- } from "./chunk-MM646MFM.js";
6
+ } from "./chunk-2B2MCZ2I.js";
7
7
  import {
8
8
  loadX402Wallet,
9
9
  x402NetworkLabel
10
- } from "./chunk-NKD4NEUF.js";
10
+ } from "./chunk-2YPUKPJN.js";
11
11
  import {
12
12
  isCreditPosture,
13
13
  loadConfig
14
- } from "./chunk-3NXAIRFF.js";
14
+ } from "./chunk-EEQPFGPM.js";
15
15
  import {
16
16
  addOutputWarnings,
17
17
  costAnchor,
18
18
  formatAmount,
19
+ formatAmountBestEffort,
19
20
  formatPaymentAmount,
20
21
  formatSats,
21
22
  hasUnsavedJobState,
@@ -26,8 +27,9 @@ import {
26
27
  resolveBtcUsdRate,
27
28
  tryResolveBtcUsdRate,
28
29
  tryX402Payment
29
- } from "./chunk-7HJ5ZR3D.js";
30
+ } from "./chunk-QXXPXQLM.js";
30
31
  import {
32
+ A,
31
33
  BUDGET_FILE,
32
34
  CONFIG_DIR,
33
35
  FAVORITES_FILE,
@@ -183,7 +185,7 @@ import {
183
185
  x402PendingUnsettled,
184
186
  x402RequiredFromError,
185
187
  x402VoucherPendingState
186
- } from "./chunk-X6BETQ7V.js";
188
+ } from "./chunk-4RINUKY4.js";
187
189
  import {
188
190
  Challenge_exports,
189
191
  Credential_exports
@@ -338,24 +340,35 @@ function origin(endpoint) {
338
340
  }
339
341
 
340
342
  // src/lib/duration.ts
343
+ var UNIT_MS = { d: 864e5, h: 36e5, m: 6e4, s: 1e3 };
344
+ var MAX_DURATION_MS = 365 * UNIT_MS.d;
345
+ var DURATION_PATTERN = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/;
346
+ function isDuration(input) {
347
+ const text = input.trim();
348
+ return text !== "" && DURATION_PATTERN.test(text);
349
+ }
341
350
  function parseDurationMs(input) {
342
- const match = /^(\d+)(s|m|h|d)$/.exec(input.trim());
343
- if (!match) {
344
- throw new Error(`Invalid duration "${input}"; use e.g. 30s, 5m, 2h, 1d`);
345
- }
346
- const count = Number(match[1]);
347
- const unitMs = {
348
- s: 1e3,
349
- m: 6e4,
350
- h: 36e5,
351
- d: 864e5
352
- };
353
- return count * unitMs[match[2]];
351
+ const match = isDuration(input) ? DURATION_PATTERN.exec(input.trim()) : null;
352
+ const components = match?.slice(1).map((count, index) => Number(count ?? 0) * Object.values(UNIT_MS)[index]) ?? [];
353
+ const total = components.reduce((sum, component) => sum + component, 0);
354
+ if (!match || components.some((component) => !Number.isSafeInteger(component)) || !Number.isSafeInteger(total) || total > MAX_DURATION_MS) {
355
+ throw new DvmError(
356
+ "invalid_arguments",
357
+ `Invalid duration "${input}"; use e.g. 30s, 5m, 2h, 1d or 1h30m`,
358
+ "Give a length of time from now as whole numbers with units d, h, m, s, largest first: 30s, 45m, 12h, 1d or 1h30m. The maximum duration is 365d. A clock time or date is not accepted; work out how long until then."
359
+ );
360
+ }
361
+ return total;
354
362
  }
355
363
  function formatDurationMs(ms) {
356
- for (const [unit, size] of [["d", 864e5], ["h", 36e5], ["m", 6e4]])
357
- if (ms >= size && ms % size === 0) return `${ms / size}${unit}`;
358
- return `${Math.ceil(ms / 1e3)}s`;
364
+ let remaining = Math.ceil(ms / 1e3) * 1e3;
365
+ const parts = [];
366
+ for (const [unit, size] of Object.entries(UNIT_MS)) {
367
+ const count = Math.floor(remaining / size);
368
+ if (count > 0) parts.push(`${count}${unit}`);
369
+ remaining %= size;
370
+ }
371
+ return parts.join("") || "0s";
359
372
  }
360
373
 
361
374
  // src/commands/wallet-history.ts
@@ -512,8 +525,8 @@ function dvmLabelFromEndpoint(endpoint) {
512
525
  const firstLabel = host.split(".")[0];
513
526
  return firstLabel || host;
514
527
  }
515
- function sanitizeLabel(label, max = 40) {
516
- const clean = label.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim();
528
+ function sanitizeLabel(label2, max = 40) {
529
+ const clean = label2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim();
517
530
  return clean.length > max ? `${clean.slice(0, max - 1)}\u2026` : clean;
518
531
  }
519
532
  function ledgerRow(e) {
@@ -624,7 +637,7 @@ function renderHuman(shown, meta) {
624
637
  function formatRow(e) {
625
638
  const when = formatWhen(e.timestamp);
626
639
  const dvm = dvmLabelFromEndpoint(e.endpoint).padEnd(12);
627
- const label = (e.label ? sanitizeLabel(e.label) : "").padEnd(40);
640
+ const label2 = (e.label ? sanitizeLabel(e.label) : "").padEnd(40);
628
641
  if (!isBudgetCharge(e)) {
629
642
  const amount2 = e.details?.amount_micro;
630
643
  const currency = e.details?.currency;
@@ -634,7 +647,7 @@ function formatRow(e) {
634
647
  expired_credit_loss: "credit expired/lost",
635
648
  active_recovery: "recovery pending"
636
649
  }[e.kind];
637
- return `${when} ${dvm} ${label} ${rowLabel}: ${amount2 === null || amount2 === void 0 ? "amount unknown" : `${String(Number(amount2) / 1e6)} ${sanitizeLabel(String(currency ?? "currency unknown"))}`} \xB7 ${String(e.details?.outcome ?? "consumed")} \xB7 rail ${sanitizeLabel(String(e.details?.rail ?? "unknown"))} \xB7 fee ${e.details?.fee_micro === null || e.details?.fee_micro === void 0 ? "unknown" : String(Number(e.details.fee_micro) / 1e6)}`;
650
+ return `${when} ${dvm} ${label2} ${rowLabel}: ${amount2 === null || amount2 === void 0 ? "amount unknown" : `${String(Number(amount2) / 1e6)} ${sanitizeLabel(String(currency ?? "currency unknown"))}`} \xB7 ${String(e.details?.outcome ?? "consumed")} \xB7 rail ${sanitizeLabel(String(e.details?.rail ?? "unknown"))} \xB7 fee ${e.details?.fee_micro === null || e.details?.fee_micro === void 0 ? "unknown" : String(Number(e.details.fee_micro) / 1e6)}`;
638
651
  }
639
652
  const sats = Math.round((e.msats ?? 0) / 1e3);
640
653
  const amount = e.usd !== null ? `$${formatUsd(e.usd)} (${sats} sats)` : `? (${sats} sats, usd unknown)`;
@@ -642,30 +655,30 @@ function formatRow(e) {
642
655
  const principal = e.principalMsats / 1e3;
643
656
  if (e.walletDebitMsats === null) {
644
657
  const routing = e.routingFeeMsats === null ? "wallet-reported routing fee unknown" : e.routingFeeMsats !== void 0 ? `wallet-reported routing fee ${String(e.routingFeeMsats / 1e3)} sats` : void 0;
645
- return `${when} ${dvm} ${label} ${amount}; principal ${String(principal)} sats, total wallet debit unknown${routing ? `; ${routing}` : ""}`;
658
+ return `${when} ${dvm} ${label2} ${amount}; principal ${String(principal)} sats, total wallet debit unknown${routing ? `; ${routing}` : ""}`;
646
659
  }
647
660
  if (e.walletDebitMsats !== void 0 && e.totalWalletFeeMsats !== void 0) {
648
661
  const debit = e.walletDebitMsats / 1e3;
649
662
  if (e.totalWalletFeeMsats === null) {
650
- return `${when} ${dvm} ${label} ${amount}; total wallet debit ${String(debit)} sats; principal ${String(principal)} sats, total wallet fee unknown`;
663
+ return `${when} ${dvm} ${label2} ${amount}; total wallet debit ${String(debit)} sats; principal ${String(principal)} sats, total wallet fee unknown`;
651
664
  }
652
665
  const totalFee = e.totalWalletFeeMsats / 1e3;
653
666
  if (e.routingFeeMsats === null) {
654
- return `${when} ${dvm} ${label} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats; routing and unitemized fee split unknown`;
667
+ return `${when} ${dvm} ${label2} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats; routing and unitemized fee split unknown`;
655
668
  }
656
669
  if (e.routingFeeMsats !== void 0 && e.unitemizedWalletFeeMsats !== void 0) {
657
670
  const routing = e.routingFeeMsats / 1e3;
658
671
  if (e.unitemizedWalletFeeMsats === null) {
659
- return `${when} ${dvm} ${label} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats; wallet-reported routing fee ${String(routing)} sats, unitemized fee split unknown`;
672
+ return `${when} ${dvm} ${label2} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats; wallet-reported routing fee ${String(routing)} sats, unitemized fee split unknown`;
660
673
  }
661
- return `${when} ${dvm} ${label} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats (${satCount(routing)} wallet-reported routing fee + ${satCount(e.unitemizedWalletFeeMsats / 1e3)} unitemized wallet fee)`;
674
+ return `${when} ${dvm} ${label2} ${amount}; total wallet debit ${String(debit)} sats = principal ${String(principal)} + total wallet fee ${String(totalFee)} sats (${satCount(routing)} wallet-reported routing fee + ${satCount(e.unitemizedWalletFeeMsats / 1e3)} unitemized wallet fee)`;
662
675
  }
663
676
  }
664
677
  if (typeof e.routingFeeMsats === "number" && e.walletDebitMsats !== void 0) {
665
- return `${when} ${dvm} ${label} ${amount}; principal ${String(principal)} + routing ${String(e.routingFeeMsats / 1e3)} sats`;
678
+ return `${when} ${dvm} ${label2} ${amount}; principal ${String(principal)} + routing ${String(e.routingFeeMsats / 1e3)} sats`;
666
679
  }
667
680
  }
668
- return `${when} ${dvm} ${label} ${amount}${e.principalMsats === void 0 ? " (BTC-equivalent budget valuation; native settlement unknown)" : ""}`;
681
+ return `${when} ${dvm} ${label2} ${amount}${e.principalMsats === void 0 ? " (BTC-equivalent budget valuation; native settlement unknown)" : ""}`;
669
682
  }
670
683
  function formatWhen(ts) {
671
684
  return new Date(ts).toISOString().slice(0, 16).replace("T", " ");
@@ -683,7 +696,7 @@ function resolveWindow(opts, now) {
683
696
  return { sinceMs: null, filter: "all" };
684
697
  }
685
698
  function parseSince(raw, now) {
686
- if (/^\d+[smhd]$/.test(raw.trim())) {
699
+ if (isDuration(raw)) {
687
700
  return now.getTime() - parseDurationMs(raw);
688
701
  }
689
702
  const parsed = Date.parse(raw);
@@ -691,7 +704,7 @@ function parseSince(raw, now) {
691
704
  throw new DvmError(
692
705
  "invalid_since",
693
706
  `Could not parse --since "${raw}".`,
694
- "Pass an ISO date (2026-07-01) or a duration like 7d, 24h, 30m."
707
+ "Pass an ISO date (2026-07-01) or a duration like 7d, 24h, 30m or 1h30m."
695
708
  );
696
709
  }
697
710
  return parsed;
@@ -847,8 +860,8 @@ function emitFloatBudgetWarning(args) {
847
860
  const warning = unrecordedFloatBudgetWarning(args.float);
848
861
  if (!warning) return;
849
862
  if (args.human) {
850
- const label = args.operation === "credit_funding" ? "Lightning credit funding" : "Ecash pocket refill";
851
- info(`${label} warning: ${warning}`);
863
+ const label2 = args.operation === "credit_funding" ? "Lightning credit funding" : "Ecash pocket refill";
864
+ info(`${label2} warning: ${warning}`);
852
865
  return;
853
866
  }
854
867
  progress({
@@ -947,6 +960,20 @@ async function payViaFloat(params) {
947
960
  throw toFloatError(err);
948
961
  }
949
962
  }
963
+ async function lookupFloatInvoice(params) {
964
+ const { methods } = params.float;
965
+ if (methods && !supportsMethod(methods, "lookup_invoice")) return "unknown";
966
+ try {
967
+ const status = await withNwcPool(
968
+ params.float.conn,
969
+ (opts) => backendFor(params.float, opts).lookupInvoice(params.paymentHash),
970
+ params.timeoutMs
971
+ );
972
+ return status.settled ? "paid" : "unknown";
973
+ } catch (err) {
974
+ return err instanceof NwcError && err.code.toUpperCase() === "NOT_FOUND" ? "unpaid" : "unknown";
975
+ }
976
+ }
950
977
  var FLOAT_TRANSACTION_LIMIT = 100;
951
978
  var FLOAT_HISTORY_LOOKBACK_SECONDS = 300;
952
979
  async function payViaLightningBackend(params) {
@@ -1410,6 +1437,12 @@ function fail(mode, refusal) {
1410
1437
  return null;
1411
1438
  }
1412
1439
 
1440
+ // src/lib/card-credit/minimum.ts
1441
+ var STRIPE_CARD_FLOOR_MICRO = 5e5;
1442
+ function cardMinimumMicro(menu) {
1443
+ return Math.max(STRIPE_CARD_FLOOR_MICRO, menu?.min_micro ?? 0, menu?.stripe?.min_micro ?? 0);
1444
+ }
1445
+
1413
1446
  // src/lib/card-credit/journal.ts
1414
1447
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1415
1448
  import { createHash as createHash2 } from "crypto";
@@ -1619,7 +1652,7 @@ async function fundOverCheckout(args, fundId, deps, prior, booked2) {
1619
1652
  const error = new DvmError("invalid_argument", "Card top-ups must be whole USD cents.");
1620
1653
  return { creditId: args.creditId, fundId, rail: "stripe", status: "refused", error, display: error.message };
1621
1654
  }
1622
- const minimum = Math.max(args.menu?.stripe?.min_micro ?? 5e5, args.menu?.min_micro ?? 0);
1655
+ const minimum = cardMinimumMicro(args.menu);
1623
1656
  const amountMicro = prior?.amountMicro ?? Math.max(args.amountMicro, minimum);
1624
1657
  const startedAt = args.cardInvocationStartedAt ?? Date.now();
1625
1658
  const reserved = await withCardFundingLock({ endpoint: args.ref.endpoint, callerPubkey: args.signing.pubkey }, () => {
@@ -1664,7 +1697,8 @@ async function fundOverCheckout(args, fundId, deps, prior, booked2) {
1664
1697
  };
1665
1698
  }
1666
1699
  const { entry } = reserved;
1667
- const raised = reserved.created && entry.amountMicro > args.amountMicro ? `Raised the requested $${formatUsd(args.amountMicro / 1e6)} to this DVM's card minimum of $${formatUsd(entry.amountMicro / 1e6)}.` : void 0;
1700
+ const minimumSource = minimum === STRIPE_CARD_FLOOR_MICRO ? "Stripe's card charge floor" : "this DVM's card minimum";
1701
+ const raised = reserved.created && entry.amountMicro > args.amountMicro ? `Raised the requested $${formatUsd(args.amountMicro / 1e6)} to ${minimumSource} of $${formatUsd(entry.amountMicro / 1e6)}.` : void 0;
1668
1702
  const base = { creditId: entry.creditId, fundId: entry.fundId, rail: "stripe" };
1669
1703
  const body = {
1670
1704
  op: "fund",
@@ -1694,13 +1728,13 @@ async function fundOverCheckout(args, fundId, deps, prior, booked2) {
1694
1728
  }
1695
1729
  entry.checkout = { url: pending.checkout.url, expires_at: pending.checkout.expires_at };
1696
1730
  updatePendingCheckout(entry);
1697
- const handoff = checkoutHandoff(entry, args.cardIdentity);
1698
- const display = [raised, handoff.display].filter(Boolean).join(" ");
1731
+ const handoff2 = checkoutHandoff(entry, args.cardIdentity);
1732
+ const display = [raised, handoff2.display].filter(Boolean).join(" ");
1699
1733
  if (args.cardWait === false || Date.now() >= entry.checkout.expires_at * 1e3) {
1700
- return { ...base, status: "checkout_pending", checkoutHandoff: { ...handoff, display }, display };
1734
+ return { ...base, status: "checkout_pending", checkoutHandoff: { ...handoff2, display }, display };
1701
1735
  }
1702
1736
  if (!announced) {
1703
- args.cardCheckoutProgress?.({ ...handoff, display });
1737
+ args.cardCheckoutProgress?.({ ...handoff2, display });
1704
1738
  announced = true;
1705
1739
  }
1706
1740
  } catch (err) {
@@ -1731,7 +1765,6 @@ async function fundOverCheckout(args, fundId, deps, prior, booked2) {
1731
1765
  }
1732
1766
 
1733
1767
  // src/lib/card-credit/fund.ts
1734
- var CARD_MIN_MICRO = 5e5;
1735
1768
  var MICRO_PER_CENT = 1e4;
1736
1769
  var PRESENT_ATTEMPTS = 3;
1737
1770
  var PRESENT_BACKOFF_MS = [2e3, 4e3];
@@ -1768,7 +1801,7 @@ async function fundOverStripe(args, fundId, deps) {
1768
1801
  hint: `This DVM funds credit over ${args.menu.funding.join(", ") || "no rail at all"}. Fund over one of those with --rail <rail>, or drop --rail and --spt to let dvm pick.`
1769
1802
  };
1770
1803
  }
1771
- const local = localAmountRefusal(base, args.amountMicro);
1804
+ const local = localAmountRefusal(base, args.amountMicro, args.menu);
1772
1805
  if (local) return local;
1773
1806
  const spt = args.cardSpt;
1774
1807
  if (spt === void 0) {
@@ -2043,18 +2076,20 @@ function approvalNeededOutcome(args, base) {
2043
2076
  hint: `Run 'dvm credit fund ${shellQuoteArg(args.ref.endpoint)} --rail stripe --amount ${shellQuoteArg(`$${usd(args.amountMicro)}`)}' for the approval steps.`
2044
2077
  };
2045
2078
  }
2046
- function localAmountRefusal(base, amountMicro) {
2047
- if (amountMicro < CARD_MIN_MICRO) {
2079
+ function localAmountRefusal(base, amountMicro, menu) {
2080
+ const minimum = cardMinimumMicro(menu);
2081
+ if (amountMicro < minimum) {
2082
+ const source = minimum === STRIPE_CARD_FLOOR_MICRO ? "Stripe's minimum card charge" : "this DVM's card top-up minimum";
2048
2083
  return refused(
2049
2084
  base,
2050
2085
  new DvmError(
2051
2086
  "below_rail_minimum",
2052
- `A card top-up must be at least $${usd(CARD_MIN_MICRO)}; $${usd(amountMicro)} is below Stripe's minimum card charge.`,
2053
- `Fund at least $${usd(CARD_MIN_MICRO)} by card, or use another rail for smaller amounts.`,
2054
- { rail: "stripe", min_micro: CARD_MIN_MICRO }
2087
+ `A card top-up must be at least $${usd(minimum)}; $${usd(amountMicro)} is below ${source}.`,
2088
+ `Fund at least $${usd(minimum)} by card, or use another rail for smaller amounts.`,
2089
+ { rail: "stripe", min_micro: minimum }
2055
2090
  ),
2056
- `Card top-ups start at $${usd(CARD_MIN_MICRO)}, so $${usd(amountMicro)} can't be paid by card. Nothing was charged.`,
2057
- `Fund at least $${usd(CARD_MIN_MICRO)} by card.`
2091
+ `Card top-ups start at $${usd(minimum)} (${source}), so $${usd(amountMicro)} can't be paid by card. Nothing was charged.`,
2092
+ `Fund at least $${usd(minimum)} by card.`
2058
2093
  );
2059
2094
  }
2060
2095
  if (amountMicro % MICRO_PER_CENT !== 0) {
@@ -2239,6 +2274,122 @@ function walletInvoiceFundingAdvice(amountMicro) {
2239
2274
  };
2240
2275
  }
2241
2276
 
2277
+ // src/lib/credit-invoice.ts
2278
+ function isInvoiceFunding(pending) {
2279
+ return pending.rail === "lightning" && pending.lightningPaymentMode === "invoice";
2280
+ }
2281
+ function creditInvoiceCommand(args) {
2282
+ const amount = (args.amountMicro / 1e6).toFixed(6).replace(/(\.\d{2,}?)0+$/, "$1");
2283
+ return `dvm credit fund ${shellQuoteArg(args.endpoint)} --rail lightning --invoice --amount ${shellQuoteArg(`$${amount}`)}` + (args.creditId ? ` --credit-id ${shellQuoteArg(args.creditId)}` : "") + (args.identity ? ` --as ${shellQuoteArg(args.identity)}` : "");
2284
+ }
2285
+ function handoff(pending, identity) {
2286
+ return {
2287
+ status: "awaiting_payment",
2288
+ rail: "lightning",
2289
+ credit_id: pending.creditId,
2290
+ fund_id: pending.fundId,
2291
+ bolt11: pending.bolt11,
2292
+ amount_micro: pending.amountMicro,
2293
+ amount_msats: pending.amountMsats,
2294
+ amount_sats: pending.amountMsats / 1e3,
2295
+ expires_at_ms: pending.expiresAtMs,
2296
+ expires_at: new Date(pending.expiresAtMs).toISOString(),
2297
+ relay: { copy_text: pending.bolt11, standalone: true },
2298
+ next_step: creditInvoiceCommand({
2299
+ endpoint: pending.endpoint,
2300
+ amountMicro: pending.amountMicro,
2301
+ creditId: pending.creditId,
2302
+ identity
2303
+ }),
2304
+ display: `Pay this invoice from any Lightning wallet to load $${formatUsd(pending.amountMicro / 1e6)} of prepaid credit. The CLI confirms funding with the DVM; the invoice alone is not proof of payment.`
2305
+ };
2306
+ }
2307
+ async function fundOverInvoice(args, pending, deps) {
2308
+ const base = { creditId: pending.creditId, fundId: pending.fundId, rail: "lightning" };
2309
+ let announced = false;
2310
+ let delay = 1e3;
2311
+ for (; ; ) {
2312
+ let result;
2313
+ try {
2314
+ result = await deps.post();
2315
+ } catch (err) {
2316
+ const error = err instanceof DvmError ? err : new DvmError("provider_error", "Could not confirm the Lightning funding.");
2317
+ const offer = error.code === "lightning_settlement_pending" ? error.data?.lightning : void 0;
2318
+ if (!offer || typeof offer.invoice !== "string" || !offer.invoice || !Number.isSafeInteger(offer.amount_msats) || offer.amount_msats <= 0 || !Number.isSafeInteger(offer.expires_at_ms) || offer.expires_at_ms <= 0 || offer.expires_at_ms > 864e13) {
2319
+ const terminal = deps.terminal(error, pending);
2320
+ if (terminal) deps.clear(pending);
2321
+ return {
2322
+ ...base,
2323
+ status: "refused",
2324
+ error,
2325
+ display: terminal ? `The DVM refused this Lightning funding (${error.code}). No credit was recorded.` : `This Lightning funding is unresolved (${error.code}). Its original funding id is saved; payment may already have happened.`,
2326
+ hint: terminal ? `If you already paid, quote funding id ${pending.fundId} to the DVM operator before funding again.` : `Re-run the same command to check this funding before paying again. ${creditInvoiceCommand({ endpoint: pending.endpoint, amountMicro: pending.amountMicro, creditId: pending.creditId, identity: args.invoiceIdentity })}`
2327
+ };
2328
+ }
2329
+ if (pending.bolt11 && pending.bolt11 !== offer.invoice) {
2330
+ throw new DvmError(
2331
+ "provider_error",
2332
+ "The DVM changed the invoice for an unresolved funding.",
2333
+ "Do not pay another invoice. Check the original funding with the DVM operator."
2334
+ );
2335
+ }
2336
+ const payable = {
2337
+ ...pending,
2338
+ bolt11: offer.invoice,
2339
+ paymentHash: offer.payment_hash,
2340
+ amountMsats: offer.amount_msats,
2341
+ expiresAtMs: offer.expires_at_ms
2342
+ };
2343
+ pending = payable;
2344
+ recordPendingFunding(pending);
2345
+ if (Date.now() >= payable.expiresAtMs) {
2346
+ const expired = new DvmError(
2347
+ "lightning_invoice_expired",
2348
+ "The Lightning invoice expired before funding was confirmed.",
2349
+ "Do not pay this expired invoice. Re-run to reconcile the saved funding before starting another."
2350
+ );
2351
+ return { ...base, status: "refused", error: expired, display: expired.message, hint: expired.hint };
2352
+ }
2353
+ if (pending.paymentOutcome !== void 0) {
2354
+ if (args.invoiceWait !== true) {
2355
+ return {
2356
+ ...base,
2357
+ status: "settlement_pending",
2358
+ display: "The connected wallet's payment is already recorded, but the DVM has not confirmed the credit yet.",
2359
+ hint: "Do not pay this invoice again. Re-run this funding or check 'dvm credit balance' to reconcile it."
2360
+ };
2361
+ }
2362
+ } else {
2363
+ const output = handoff(payable, args.invoiceIdentity);
2364
+ if (args.invoiceWait !== true) {
2365
+ return {
2366
+ ...base,
2367
+ status: "invoice_pending",
2368
+ invoiceHandoff: output,
2369
+ display: args.invoiceWait === false ? String(output.display) : "The original Lightning funding is still pending. Its invoice and funding id are saved; no new payment was made.",
2370
+ hint: "Re-run the original 'dvm credit fund --invoice' command to finish this funding before starting another payment."
2371
+ };
2372
+ }
2373
+ if (!announced) {
2374
+ await args.invoiceProgress?.(output);
2375
+ announced = true;
2376
+ }
2377
+ }
2378
+ await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(delay, payable.expiresAtMs - Date.now()))));
2379
+ delay = Math.min(delay * 2, 1e4);
2380
+ continue;
2381
+ }
2382
+ if (!result.credit || result.funded_micro === void 0) {
2383
+ throw new DvmError(
2384
+ "provider_error",
2385
+ "The DVM returned no confirmed Lightning credit.",
2386
+ "Re-run the same command to reconcile the saved funding before paying again."
2387
+ );
2388
+ }
2389
+ return deps.settled(result, pending);
2390
+ }
2391
+ }
2392
+
2242
2393
  // src/lib/job-store.ts
2243
2394
  import { isDeepStrictEqual } from "util";
2244
2395
  import { randomUUID as randomUUID2 } from "crypto";
@@ -2949,6 +3100,13 @@ function recordUpfrontRailPayment(jobId, value, freshSubmit = false) {
2949
3100
  job.upfrontRailPayment = payment;
2950
3101
  }, true);
2951
3102
  }
3103
+ function addCashuSwapFee(jobId, sats) {
3104
+ if (!Number.isSafeInteger(sats) || sats <= 0) return;
3105
+ mutateJobs((jobs) => {
3106
+ const job = jobs.find((entry) => entry.id === jobId);
3107
+ if (job) job.cashuSwapFeeSats = (job.cashuSwapFeeSats ?? 0) + sats;
3108
+ });
3109
+ }
2952
3110
  function hasUnknownUpfrontRail(job) {
2953
3111
  return job.upfrontRailPayment === "unknown" || job.upfrontRailConflict === true;
2954
3112
  }
@@ -4033,6 +4191,28 @@ function reservedForMarker(builderHandle) {
4033
4191
  return `${BUILDER_RESERVE_PREFIX}${builderHandle}`;
4034
4192
  }
4035
4193
 
4194
+ // src/lib/mint-fee.ts
4195
+ function submissionSwapFeeSats(submission) {
4196
+ const fee = submission.swap_fee_sats;
4197
+ return Number.isSafeInteger(fee) && fee > 0 ? fee : 0;
4198
+ }
4199
+ var MINT_FEE_EXPLAINER = "A mint fee is a small charge the mint that holds your ecash takes for each coin it handles.";
4200
+ function label(sats) {
4201
+ return formatAmountBestEffort(sats * 1e3, { anchor: false });
4202
+ }
4203
+ function describeCashuPayment(paidSats, feeSats) {
4204
+ if (feeSats <= 0) return "";
4205
+ return `Paid ${label(paidSats)} to the provider plus ${label(feeSats)} mint fee; ${label(paidSats + feeSats)} left your wallet. ${MINT_FEE_EXPLAINER}`;
4206
+ }
4207
+ function cashuPaymentFeeFields(paidSats, feeSats) {
4208
+ const display = describeCashuPayment(paidSats, feeSats);
4209
+ return {
4210
+ swap_fee_sats: feeSats,
4211
+ wallet_debit_sats: paidSats + feeSats,
4212
+ ...display ? { fee_display: display } : {}
4213
+ };
4214
+ }
4215
+
4036
4216
  // src/lib/wallet-agent/inflight.ts
4037
4217
  var DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC = 60;
4038
4218
  var INFLIGHT_TIMEOUT_ENV = "DVM_INFLIGHT_PROOF_TIMEOUT_SEC";
@@ -4144,6 +4324,9 @@ function formatLocktime(seconds) {
4144
4324
  }
4145
4325
 
4146
4326
  // src/lib/wallet-agent/spend.ts
4327
+ function sumAmounts(proofs) {
4328
+ return proofs.reduce((sum, proof) => sum + A.from(proof.amount).toNumber(), 0);
4329
+ }
4147
4330
  async function prepareAgentSpend(args) {
4148
4331
  if (args.maxCashuPrincipalSats !== void 0 && (!Number.isSafeInteger(args.maxCashuPrincipalSats) || args.maxCashuPrincipalSats < 0)) {
4149
4332
  return {
@@ -4300,6 +4483,7 @@ async function prepareAgentSpend(args) {
4300
4483
  requestId: inner2.requestId,
4301
4484
  mint: inner2.mint,
4302
4485
  totalSats: inner2.submission.amount_sats,
4486
+ swapFeeSats: 0,
4303
4487
  endpoint: args.endpoint,
4304
4488
  intendedLockPubkey: args.cashuP2pk.lock_pubkey,
4305
4489
  fromReserve: true,
@@ -4314,29 +4498,26 @@ async function prepareAgentSpend(args) {
4314
4498
  let inner;
4315
4499
  let sendProofs = [];
4316
4500
  let keepProofs = [];
4501
+ let swapFeeSats = 0;
4317
4502
  for (const [index, mint] of lock1.candidateMints.entries()) {
4318
4503
  const hasNextCandidate = index < lock1.candidateMints.length - 1;
4319
4504
  let candidateWallet;
4320
4505
  try {
4321
4506
  candidateWallet = await getWalletForMint(mint);
4322
4507
  rememberKeysetFees(mint, candidateWallet);
4323
- } catch (err) {
4324
- attempts.push({ mint, reason: "unreachable", message: errorText(err) });
4508
+ } catch {
4509
+ attempts.push(spendMintAttempt(mint, "unreachable"));
4325
4510
  continue;
4326
4511
  }
4327
4512
  let reserveSats;
4328
4513
  try {
4329
4514
  reserveSats = swapSendReserve(candidateWallet, args.amountSats);
4330
- } catch (err) {
4331
- attempts.push({ mint, reason: "keys_unavailable", message: errorText(err) });
4515
+ } catch {
4516
+ attempts.push(spendMintAttempt(mint, "keys_unavailable"));
4332
4517
  continue;
4333
4518
  }
4334
4519
  if (!swapEnabled(candidateWallet)) {
4335
- attempts.push({
4336
- mint,
4337
- reason: "swap_disabled",
4338
- message: "Mint advertises swaps switched off (NUT-3 disabled)."
4339
- });
4520
+ attempts.push(spendMintAttempt(mint, "swap_disabled"));
4340
4521
  continue;
4341
4522
  }
4342
4523
  const lock2 = await withWalletLock(() => {
@@ -4370,7 +4551,7 @@ async function prepareAgentSpend(args) {
4370
4551
  return {
4371
4552
  error: {
4372
4553
  code: "cashu_fee_cap_exceeded",
4373
- message: `Cashu fees at ${mint} would be ${selectedFeeSats} sats, over the ${args.maxCashuFeeSats}-sat --max-cashu-fee-sats limit.`,
4554
+ message: `Cashu fees at ${spendDiagnosticMint(mint)} would be ${selectedFeeSats} sats, over the ${args.maxCashuFeeSats}-sat --max-cashu-fee-sats limit.`,
4374
4555
  hint: "Raise --max-cashu-fee-sats only after approval, or fund an accepted mint with a lower swap fee."
4375
4556
  }
4376
4557
  };
@@ -4419,12 +4600,12 @@ async function prepareAgentSpend(args) {
4419
4600
  if (lock2.error.code === "no_agent_wallet") return lock2;
4420
4601
  if (lock2.error.code === "cashu_fee_cap_exceeded") {
4421
4602
  lastFeeCapError = lock2.error;
4422
- attempts.push({ mint, reason: "fee_cap_exceeded", message: lock2.error.message });
4603
+ attempts.push(spendMintAttempt(mint, "fee_cap_exceeded", lock2.error.message));
4423
4604
  continue;
4424
4605
  }
4425
4606
  const selectError = lock2.error;
4426
4607
  lastSelectError = selectError;
4427
- attempts.push({ mint, reason: selectError.code, message: selectError.message });
4608
+ attempts.push(spendMintAttempt(mint, selectError.code, selectError.message));
4428
4609
  continue;
4429
4610
  }
4430
4611
  const swapBuilder = candidateWallet.ops.send(lock2.submission.amount_sats, toCashuProofs(lock2.selectedProofs)).asP2PK({
@@ -4434,8 +4615,8 @@ async function prepareAgentSpend(args) {
4434
4615
  let preview;
4435
4616
  try {
4436
4617
  preview = await swapBuilder.prepare();
4437
- } catch (err) {
4438
- attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
4618
+ } catch {
4619
+ attempts.push(spendMintAttempt(mint, "swap_rejected"));
4439
4620
  await rollbackAttempt(requestId, lock2.selectedKeys);
4440
4621
  if (hasNextCandidate) continue;
4441
4622
  break;
@@ -4479,14 +4660,19 @@ async function prepareAgentSpend(args) {
4479
4660
  inner = { ...lock2, submission: preparedSubmission };
4480
4661
  sendProofs = result.send;
4481
4662
  keepProofs = result.keep;
4663
+ swapFeeSats = Math.max(
4664
+ 0,
4665
+ sumAmounts(preview.inputs) - sumAmounts(keepProofs) - lock2.submission.amount_sats
4666
+ );
4482
4667
  break;
4483
4668
  } catch (err) {
4484
- attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
4485
4669
  if (err instanceof te) {
4670
+ attempts.push(spendMintAttempt(mint, "swap_rejected"));
4486
4671
  await rollbackAttempt(requestId, lock2.selectedKeys);
4487
4672
  if (hasNextCandidate) continue;
4488
4673
  break;
4489
4674
  }
4675
+ attempts.push(spendMintAttempt(mint, "swap_rejected", "Mint swap outcome is unknown; recovery is required."));
4490
4676
  inputsLeftInFlight = true;
4491
4677
  break;
4492
4678
  }
@@ -4512,6 +4698,7 @@ async function prepareAgentSpend(args) {
4512
4698
  ...s,
4513
4699
  output_proofs: agentOutputs,
4514
4700
  swapping: void 0,
4701
+ swap_fee_sats: swapFeeSats,
4515
4702
  cashu_token: cashuToken,
4516
4703
  ...boundContext ? { context: boundContext } : {},
4517
4704
  // What a later reclaim needs. Only the swap path
@@ -4533,32 +4720,36 @@ async function prepareAgentSpend(args) {
4533
4720
  requestId: inner.requestId,
4534
4721
  mint: inner.mint,
4535
4722
  totalSats: inner.submission.amount_sats,
4723
+ swapFeeSats,
4536
4724
  endpoint: args.endpoint,
4537
4725
  intendedLockPubkey: args.cashuP2pk.lock_pubkey,
4538
4726
  ...attempts.length > 0 ? { attempts: successfulSpendAttempts(attempts) } : {},
4539
4727
  ...boundContext?.binding_fingerprint ? { submissionBindingFingerprint: boundContext.binding_fingerprint } : {}
4540
4728
  };
4541
4729
  }
4730
+ var SPEND_ATTEMPT_MESSAGES = {
4731
+ unreachable: "Mint could not be loaded.",
4732
+ keys_unavailable: "Mint did not provide an active keyset.",
4733
+ swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
4734
+ fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
4735
+ insufficient_balance: "Mint balance cannot cover the price and swap fee.",
4736
+ no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
4737
+ swap_rejected: "Mint swap could not be prepared or was definitely refused."
4738
+ };
4739
+ function spendDiagnosticMint(mint) {
4740
+ try {
4741
+ const url = new URL(mint);
4742
+ if (url.protocol !== "https:" && url.protocol !== "http:") return "[invalid mint URL]";
4743
+ return redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
4744
+ } catch {
4745
+ return "[invalid mint URL]";
4746
+ }
4747
+ }
4748
+ function spendMintAttempt(mint, reason, message = SPEND_ATTEMPT_MESSAGES[reason]) {
4749
+ return { mint: spendDiagnosticMint(mint), reason, message };
4750
+ }
4542
4751
  function successfulSpendAttempts(attempts) {
4543
- const messages = {
4544
- unreachable: "Mint could not be loaded.",
4545
- keys_unavailable: "Mint did not provide an active keyset.",
4546
- swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
4547
- fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
4548
- insufficient_balance: "Mint balance cannot cover the price and swap fee.",
4549
- no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
4550
- swap_rejected: "Mint swap could not be prepared or was definitely refused."
4551
- };
4552
- return attempts.map(({ mint, reason }) => {
4553
- let safeMint;
4554
- try {
4555
- new URL(mint);
4556
- safeMint = redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
4557
- } catch {
4558
- safeMint = "[invalid mint URL]";
4559
- }
4560
- return { mint: safeMint, reason, message: messages[reason] };
4561
- });
4752
+ return attempts.map((attempt) => ({ ...attempt, message: SPEND_ATTEMPT_MESSAGES[attempt.reason] }));
4562
4753
  }
4563
4754
  function principalCapFailure(principalSats, maxCashuPrincipalSats) {
4564
4755
  return {
@@ -4639,6 +4830,7 @@ async function commitHeldSubmission(requestId, now = Date.now) {
4639
4830
  dvm_endpoint: submission.endpoint,
4640
4831
  mint: submission.mint,
4641
4832
  amount_sats: submission.amount_sats,
4833
+ ...submissionSwapFeeSats(submission) > 0 ? { fee_sats: submissionSwapFeeSats(submission) } : {},
4642
4834
  signed_at_ms: now()
4643
4835
  }].slice(-RECENT_SPENDS_CAP)
4644
4836
  });
@@ -4754,7 +4946,7 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
4754
4946
  if (attempts.length === 1) return { ...lastSelectError, attempts };
4755
4947
  return {
4756
4948
  code: lastSelectError.code,
4757
- message: `Agent wallet can't cover the price plus the per-call swap fee at any of the DVM's mints: ${describeAttempts(attempts)}.`,
4949
+ message: boundedSpendMessage(`Agent wallet can't cover the price plus the per-call swap fee at any of the DVM's mints: ${describeAttempts(attempts)}.`),
4758
4950
  hint: lastSelectError.hint,
4759
4951
  attempts
4760
4952
  };
@@ -4765,14 +4957,14 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
4765
4957
  if (attempts.length === 1) return { ...lastFeeCapError, attempts };
4766
4958
  return {
4767
4959
  ...lastFeeCapError,
4768
- message: `Every accepted mint that can cover this payment exceeds --max-cashu-fee-sats: ${describeAttempts(attempts)}.`,
4960
+ message: boundedSpendMessage(`Every accepted mint that can cover this payment exceeds --max-cashu-fee-sats: ${describeAttempts(attempts)}.`),
4769
4961
  attempts
4770
4962
  };
4771
4963
  }
4772
4964
  const message = attempts.length === 1 ? `Mint swap failed at ${attempts[0].mint}: ${attempts[0].message}` : `Every mint the DVM accepts failed for this payment: ${describeAttempts(attempts)}.`;
4773
4965
  return {
4774
4966
  code: "swap_failed",
4775
- message,
4967
+ message: boundedSpendMessage(message),
4776
4968
  hint: inputsLeftInFlight ? "The swap outcome is being recovered from the mint. Run `dvm wallet show` to restore signed outputs or return inputs once the mint confirms they stayed unspent." : "Nothing was spent and the balance is untouched. Retry now \u2014 a mint that's down now is tried again on the next call.",
4777
4969
  attempts
4778
4970
  };
@@ -4783,6 +4975,9 @@ function isSelectionReason(reason) {
4783
4975
  function describeAttempts(attempts) {
4784
4976
  return attempts.map((a) => `${a.mint} \u2014 ${a.reason} (${a.message})`).join("; ");
4785
4977
  }
4978
+ function boundedSpendMessage(message) {
4979
+ return message.length <= 4096 ? message : `${message.slice(0, 4095)}\u2026`;
4980
+ }
4786
4981
  function swapEnabled(cashuWallet) {
4787
4982
  const loose = cashuWallet;
4788
4983
  let nuts;
@@ -4795,9 +4990,6 @@ function swapEnabled(cashuWallet) {
4795
4990
  if (typeof nuts !== "object" || nuts === null) return true;
4796
4991
  return canSwap(nuts);
4797
4992
  }
4798
- function errorText(err) {
4799
- return err instanceof Error ? err.message : String(err);
4800
- }
4801
4993
  function selectReserveProofs(args) {
4802
4994
  const marker = reservedForMarker(args.builderHandle);
4803
4995
  const candidates = args.proofs.filter(
@@ -5366,12 +5558,12 @@ async function stablecoinRemaining(rail) {
5366
5558
  const balance = await Promise.race([
5367
5559
  (async () => {
5368
5560
  if (rail === "x402") {
5369
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
5561
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-J7JCMFZ2.js");
5370
5562
  const wallet = loadX402Wallet2();
5371
5563
  if (!wallet) return;
5372
5564
  return (await getX402Balance(await ensureAddress(wallet))).usdc;
5373
5565
  }
5374
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-GDDZZP5S.js");
5566
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-AY6R3E4Z.js");
5375
5567
  const account = await connectedTempoAccount2();
5376
5568
  if (account) return (await getTempoUsdcBalance(account)).usdc;
5377
5569
  })(),
@@ -5508,6 +5700,8 @@ function settlementCurrency(receipt, job, messages, hint) {
5508
5700
  candidates.push(hint);
5509
5701
  const creditId = receipt.credit?.credit_id;
5510
5702
  if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
5703
+ const railUsd = typeof job?.upfrontRailPayment === "object" ? job.upfrontRailPayment?.usdMicro : void 0;
5704
+ if (!job?.upfrontRailConflict && validMicro2(railUsd) && railUsd === receipt.settlement?.held) candidates.push("usd");
5511
5705
  const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
5512
5706
  return found ? found.toLowerCase() : null;
5513
5707
  }
@@ -6112,6 +6306,12 @@ var TEMPO_AMOUNT_REFUSALS = /* @__PURE__ */ new Set(["tempo_amount_exceeds_limit
6112
6306
  var SETTLEMENT_POLLS = 3;
6113
6307
  var SETTLEMENT_POLL_DELAY_MS = 1500;
6114
6308
  async function fundCredit(args) {
6309
+ if (args.invoice) {
6310
+ if (args.rail && args.rail !== "lightning" || args.fundingMode) {
6311
+ throw new DvmError("invalid_argument", "--invoice only applies to Lightning credit funding.");
6312
+ }
6313
+ args = { ...args, rail: "lightning" };
6314
+ }
6115
6315
  return withFundingMode(await runCreditFunding(args));
6116
6316
  }
6117
6317
  async function runCreditFunding(args) {
@@ -6154,7 +6354,7 @@ async function runCreditFunding(args) {
6154
6354
  }
6155
6355
  const pending = loadPendingFunding(args.ref.endpoint, args.signing.pubkey, args.creditId);
6156
6356
  if (pending) {
6157
- if (!pendingFundingExpired(pending)) {
6357
+ if (pending.rail === "lightning" || !pendingFundingExpired(pending)) {
6158
6358
  const resumed = argsFromPending(args, pending);
6159
6359
  return pending.rail === "tempo" ? fundOverMpp(resumed, pending.fundId, pending) : fundOverLightning(resumed, pending.fundId, pending);
6160
6360
  }
@@ -6234,17 +6434,18 @@ async function runCreditFunding(args) {
6234
6434
  };
6235
6435
  }
6236
6436
  async function pollPendingCreditFundings(args) {
6437
+ const refused2 = [];
6237
6438
  const pending = listPendingFundings({
6238
6439
  endpoint: args.ref.endpoint,
6239
6440
  callerPubkey: args.signing.pubkey
6240
6441
  });
6241
6442
  for (const funding of pending) {
6242
- if (pendingFundingExpired(funding)) {
6243
- clearPending(funding);
6244
- continue;
6245
- }
6246
6443
  const fundArgs = argsFromPending(args, funding);
6247
6444
  if (funding.rail === "tempo") {
6445
+ if (pendingFundingExpired(funding)) {
6446
+ clearPending(funding);
6447
+ continue;
6448
+ }
6248
6449
  await fundOverMpp(fundArgs, funding.fundId, funding).catch(() => void 0);
6249
6450
  continue;
6250
6451
  }
@@ -6259,11 +6460,19 @@ async function pollPendingCreditFundings(args) {
6259
6460
  } catch (err) {
6260
6461
  const offer = lightningOffer(err);
6261
6462
  if (offer) {
6262
- const enriched = withLightningOffer(funding, offer);
6263
- recordPendingFunding(enriched);
6264
- if (pendingFundingExpired(enriched)) clearPending(enriched);
6265
- } else if (shouldClearPending(err)) {
6266
- clearPending(funding);
6463
+ if (isInvoiceFunding(funding) && funding.bolt11 && funding.bolt11 !== offer.invoice) continue;
6464
+ const verdict = await replacementInvoiceVerdict(funding, offer, void 0);
6465
+ if (verdict === "refuse") continue;
6466
+ recordPendingFunding(
6467
+ verdict === "paid" ? withReconciledPayment(funding) : withLightningOffer(funding, offer)
6468
+ );
6469
+ } else if (lightningFundingTerminal(err, funding)) {
6470
+ const spend = lightningSpendFromPending(funding);
6471
+ if (spend) {
6472
+ refused2.push(paidButRefused(fundArgs, base, spend, lightningSpendDisplay(spend), err));
6473
+ } else {
6474
+ clearPending(funding);
6475
+ }
6267
6476
  }
6268
6477
  }
6269
6478
  }
@@ -6309,7 +6518,7 @@ async function pollPendingCreditFundings(args) {
6309
6518
  }
6310
6519
  }
6311
6520
  const exactWallet = loadX402Wallet();
6312
- if (!exactWallet) return;
6521
+ if (!exactWallet) return refused2;
6313
6522
  for (const funding of listResumableX402ExactFundings({
6314
6523
  endpoint: args.ref.endpoint,
6315
6524
  callerPubkey: args.signing.pubkey
@@ -6329,6 +6538,7 @@ async function pollPendingCreditFundings(args) {
6329
6538
  funding
6330
6539
  ).catch(() => void 0);
6331
6540
  }
6541
+ return refused2;
6332
6542
  }
6333
6543
  function availableRails(args) {
6334
6544
  const advertised = args.menu?.funding;
@@ -6338,8 +6548,8 @@ function availableRails(args) {
6338
6548
  if (offers("cashu") && cashu && cashu.lock_pubkeys.length > 0 && cashu.mints.length > 0) {
6339
6549
  rails.push("cashu");
6340
6550
  }
6341
- const float = args.float === void 0 ? loadFloat() : args.float;
6342
- if (offers("lightning") && float) rails.push("lightning");
6551
+ const float = args.invoice ? null : args.float === void 0 ? loadFloat() : args.float;
6552
+ if (offers("lightning") && (float || args.invoice)) rails.push("lightning");
6343
6553
  const x402Wallet = offers("x402") ? loadX402Wallet() : null;
6344
6554
  if (x402Wallet && offersX402CreditFunding(args.menu, x402Wallet.network)) rails.push("x402");
6345
6555
  if (offers("tempo") && offersTempoCreditFunding(args.menu) && hasConnectedTempoWallet(args)) {
@@ -7365,6 +7575,7 @@ async function fundOverCashu(args, fundId) {
7365
7575
  dvm_endpoint: args.ref.endpoint,
7366
7576
  mint: prepared.mint,
7367
7577
  amount_sats: prepared.totalSats,
7578
+ ...prepared.swapFeeSats > 0 ? { fee_sats: prepared.swapFeeSats } : {},
7368
7579
  signed_at_ms: Date.now()
7369
7580
  }
7370
7581
  });
@@ -8096,27 +8307,29 @@ async function fundOverLightning(args, fundId, resumed) {
8096
8307
  };
8097
8308
  }
8098
8309
  }
8099
- const float2 = args.float === void 0 ? loadFloat() : args.float;
8100
- if (!float2) {
8310
+ const float2 = args.invoice ? null : args.float === void 0 ? loadFloat() : args.float;
8311
+ if (!float2 && !args.invoice) {
8101
8312
  return {
8102
8313
  ...base,
8103
8314
  status: "unavailable",
8104
8315
  display: "No Lightning wallet is connected, so the credit can't be funded that way.",
8105
- ...args.menu?.stripe?.checkout ? { hint: cardCheckoutAlternative(args) + walletInvoiceFundingAdvice(args.amountMicro).text } : {}
8316
+ hint: `Run ${creditInvoiceCommand({ endpoint: args.ref.endpoint, amountMicro: args.amountMicro, creditId: args.creditId, identity: args.invoiceIdentity })} to pay from any Lightning wallet. ` + cardCheckoutAlternative(args) + walletInvoiceFundingAdvice(args.amountMicro).text
8106
8317
  };
8107
8318
  }
8108
- const rate = (await tryResolveBtcUsdRate())?.rate ?? 0;
8109
- if (rate <= 0) {
8110
- return {
8111
- ...base,
8112
- status: "unavailable",
8113
- display: "The bitcoin exchange rate couldn't be read, so the funding amount can't be sized."
8114
- };
8115
- }
8116
- try {
8117
- await assertFloatBudget(microToSats(args.amountMicro, rate) * 1e3);
8118
- } catch (err) {
8119
- return budgetRefusal(base, err);
8319
+ if (!args.invoice) {
8320
+ const rate = (await tryResolveBtcUsdRate())?.rate ?? 0;
8321
+ if (rate <= 0) {
8322
+ return {
8323
+ ...base,
8324
+ status: "unavailable",
8325
+ display: "The bitcoin exchange rate couldn't be read, so the funding amount can't be sized."
8326
+ };
8327
+ }
8328
+ try {
8329
+ await assertFloatBudget(microToSats(args.amountMicro, rate) * 1e3);
8330
+ } catch (err) {
8331
+ return budgetRefusal(base, err);
8332
+ }
8120
8333
  }
8121
8334
  pending = {
8122
8335
  endpoint: args.ref.endpoint,
@@ -8127,36 +8340,68 @@ async function fundOverLightning(args, fundId, resumed) {
8127
8340
  rail: "lightning",
8128
8341
  targetMicro: args.targetMicro ?? args.amountMicro,
8129
8342
  ...args.menu ? { menu: args.menu } : {},
8130
- requestedAt: Date.now()
8343
+ requestedAt: Date.now(),
8344
+ ...args.invoice ? { lightningPaymentMode: "invoice" } : {}
8131
8345
  };
8132
8346
  recordPendingFunding(pending);
8133
8347
  }
8134
8348
  const creditBody = lightningCreditBody(pending);
8349
+ if (args.invoice || isInvoiceFunding(pending)) {
8350
+ const manual = { ...pending, lightningPaymentMode: "invoice" };
8351
+ recordPendingFunding(manual);
8352
+ const outcome = await fundOverInvoice(args, manual, {
8353
+ post: () => postCredit(args, creditBody),
8354
+ settled: (result, entry) => settleAndClear(args, base, result, lightningSpendFromPending(entry), entry),
8355
+ terminal: lightningFundingTerminal,
8356
+ clear: clearPending
8357
+ });
8358
+ return { ...outcome, ...lightningSpendFromPending(manual) ?? {} };
8359
+ }
8135
8360
  let offer;
8136
8361
  try {
8137
8362
  const replay = await postCredit(args, creditBody);
8138
8363
  return settleAndClear(args, base, replay, lightningSpendFromPending(pending), pending);
8139
8364
  } catch (err) {
8140
8365
  const parsed = lightningOffer(err);
8366
+ const recorded = lightningSpendFromPending(pending);
8141
8367
  if (!parsed) {
8142
- if (shouldClearPending(err)) clearPending(pending);
8368
+ const terminal = lightningFundingTerminal(err, pending);
8369
+ if (terminal) clearPending(pending);
8370
+ if (recorded) {
8371
+ return terminal ? paidButRefused(args, base, recorded, lightningSpendDisplay(recorded), err) : (
8372
+ // Inconclusive: the error is surfaced as a failure so the caller retries the same ids.
8373
+ { ...unresolvedFunding(base, err), ...recorded }
8374
+ );
8375
+ }
8376
+ if (!terminal && pending.bolt11) return unresolvedFunding(base, err);
8143
8377
  return lightningRefusal(base, err);
8144
8378
  }
8145
8379
  offer = parsed;
8380
+ if (recorded) {
8381
+ recordPendingFunding(withLightningOffer(pending, offer));
8382
+ return paidAwaitingSettlement(base, recorded, lightningSpendDisplay(recorded));
8383
+ }
8384
+ const verdict = await replacementInvoiceVerdict(pending, offer, args.float);
8385
+ if (verdict === "refuse") return replacementInvoiceRefusal(base, pending);
8386
+ if (verdict === "paid") {
8387
+ pending = withReconciledPayment(pending);
8388
+ recordPendingFunding(pending);
8389
+ const reconciled = lightningSpendFromPending(pending);
8390
+ if (reconciled) {
8391
+ return paidAwaitingSettlement(base, reconciled, lightningSpendDisplay(reconciled));
8392
+ }
8393
+ }
8146
8394
  pending = withLightningOffer(pending, offer);
8147
8395
  recordPendingFunding(pending);
8148
8396
  }
8149
- if (pendingFundingExpired(pending)) {
8150
- clearPending(pending);
8151
- return expiredFunding(base);
8152
- }
8397
+ if (pendingFundingExpired(pending)) return expiredUnresolvedFunding(base);
8153
8398
  const float = args.float === void 0 ? loadFloat() : args.float;
8154
8399
  if (!float) {
8155
8400
  return {
8156
8401
  ...base,
8157
8402
  status: "unavailable",
8158
8403
  display: "The original Lightning invoice is still pending, but no wallet is connected to pay or reconcile it.",
8159
- hint: "Reconnect the Lightning wallet, then re-run this funding. The same invoice and funding id will be reused."
8404
+ hint: `Run ${creditInvoiceCommand({ endpoint: pending.endpoint, amountMicro: pending.amountMicro, creditId: pending.creditId, identity: args.invoiceIdentity })} to pay the original invoice from any Lightning wallet, or reconnect the Lightning wallet and re-run this funding. The same invoice and funding id will be reused.`
8160
8405
  };
8161
8406
  }
8162
8407
  let payment;
@@ -8214,32 +8459,15 @@ async function fundOverLightning(args, fundId, resumed) {
8214
8459
  };
8215
8460
  } catch (err) {
8216
8461
  if (isPermanentRefusal(err)) {
8217
- const mapped = err;
8218
8462
  clearPending(pending);
8219
- return {
8220
- ...base,
8221
- ...paid,
8222
- status: "refused",
8223
- error: mapped,
8224
- display: `The Lightning payment went out, but the DVM won't be crediting it (${mapped.code}). ${mapped.message} ${floatPaymentDisplay(payment)}`,
8225
- hint: `Don't fund again \u2014 a fresh funding id issues a second invoice. The payment is on record ('dvm wallet history'); quote funding id ${fundId} to the operator of ${args.ref.endpoint}.`
8226
- };
8463
+ return paidButRefused(args, base, paid, floatPaymentDisplay(payment), err);
8227
8464
  }
8228
8465
  unconfirmed = err instanceof DvmError && !isSettlementPending(err) ? err : void 0;
8229
8466
  if (attempt < SETTLEMENT_POLLS - 1) await sleep(SETTLEMENT_POLL_DELAY_MS);
8230
8467
  }
8231
8468
  }
8232
8469
  recordPendingFunding(pending);
8233
- return {
8234
- ...base,
8235
- ...paid,
8236
- status: "settlement_pending",
8237
- ...unconfirmed ? { error: unconfirmed } : {},
8238
- display: unconfirmed ? `The Lightning payment went out and is recorded, but the DVM couldn't be reached to confirm it (${unconfirmed.code}). It credits the balance the next time it hears from you \u2014 nothing is lost. ${floatPaymentDisplay(payment)}` : `The Lightning payment went out and is recorded, but the DVM hasn't seen it land yet. It credits the balance on your next call \u2014 nothing is lost. ${floatPaymentDisplay(payment)}`,
8239
- // Both verbs poll the durable `(credit_id, fund_id)`: neither can mint a
8240
- // second invoice while this intent remains in flight.
8241
- hint: "Re-run this funding or check with 'dvm credit balance' \u2014 both re-poll the original funding id, and any next request makes the DVM look for settlement."
8242
- };
8470
+ return paidAwaitingSettlement(base, paid, floatPaymentDisplay(payment), unconfirmed);
8243
8471
  }
8244
8472
  async function postCredit(args, body, payment) {
8245
8473
  const transport = args.transport;
@@ -8423,6 +8651,10 @@ function argsFromPending(args, pending) {
8423
8651
  ...pending.menu ? { menu: pending.menu } : {},
8424
8652
  ...args.signBody ? { signBody: args.signBody } : {},
8425
8653
  ..."float" in args ? { float: args.float } : {},
8654
+ ...args.invoice ? { invoice: true } : {},
8655
+ ...args.invoiceWait !== void 0 ? { invoiceWait: args.invoiceWait } : {},
8656
+ ...args.invoiceIdentity ? { invoiceIdentity: args.invoiceIdentity } : {},
8657
+ ...args.invoiceProgress ? { invoiceProgress: args.invoiceProgress } : {},
8426
8658
  ..."tempoAccount" in args ? { tempoAccount: args.tempoAccount } : {},
8427
8659
  ...args.tempoGetClient ? { tempoGetClient: args.tempoGetClient } : {},
8428
8660
  ...args.tempoFetch ? { tempoFetch: args.tempoFetch } : {}
@@ -8528,6 +8760,7 @@ function otherCreditPendingX402(args) {
8528
8760
  ).sort((a, b) => a.requestedAt - b.requestedAt)[0];
8529
8761
  }
8530
8762
  function withLightningOffer(pending, offer) {
8763
+ if (pending.paymentOutcome !== void 0 && pending.bolt11) return pending;
8531
8764
  return {
8532
8765
  ...pending,
8533
8766
  bolt11: offer.invoice,
@@ -8536,29 +8769,107 @@ function withLightningOffer(pending, offer) {
8536
8769
  expiresAtMs: offer.expires_at_ms
8537
8770
  };
8538
8771
  }
8772
+ async function replacementInvoiceVerdict(pending, offer, float) {
8773
+ if (pending.paymentOutcome !== void 0 || !pending.bolt11 || pending.bolt11 === offer.invoice) {
8774
+ return "same";
8775
+ }
8776
+ if (!pending.paymentHash) return "refuse";
8777
+ let wallet;
8778
+ try {
8779
+ wallet = float === void 0 ? loadFloat() : float;
8780
+ } catch {
8781
+ return "refuse";
8782
+ }
8783
+ if (!wallet) return "refuse";
8784
+ const state = await lookupFloatInvoice({ float: wallet, paymentHash: pending.paymentHash });
8785
+ return state === "unknown" ? "refuse" : state;
8786
+ }
8787
+ function withReconciledPayment(pending) {
8788
+ return {
8789
+ ...pending,
8790
+ principalMsats: pending.amountMsats ?? 0,
8791
+ routingFeeMsats: null,
8792
+ totalWalletFeeMsats: null,
8793
+ unitemizedWalletFeeMsats: null,
8794
+ walletDebitMsats: null,
8795
+ paymentOutcome: "reconciled"
8796
+ };
8797
+ }
8798
+ function replacementInvoiceRefusal(base, pending) {
8799
+ const error = new DvmError(
8800
+ "lightning_invoice_changed",
8801
+ "The DVM offered a different invoice for a funding whose first invoice may already be paid.",
8802
+ `Do not pay another invoice or fund again. Check the wallet's history for the original invoice, or quote funding id ${pending.fundId} to the DVM operator.`,
8803
+ { credit_id: pending.creditId, fund_id: pending.fundId }
8804
+ );
8805
+ return {
8806
+ ...base,
8807
+ status: "refused",
8808
+ error,
8809
+ display: `The DVM replaced the Lightning invoice for saved funding ${pending.fundId}, and the wallet could not show that the original went unpaid. Nothing was paid on this attempt; the original invoice and funding id are kept.`,
8810
+ hint: error.hint
8811
+ };
8812
+ }
8539
8813
  function pendingFundingExpired(pending, now = Date.now()) {
8540
8814
  return pending.expiresAtMs !== void 0 && pending.expiresAtMs <= now;
8541
8815
  }
8542
8816
  function clearPending(pending) {
8543
8817
  clearPendingFunding(pending.endpoint, pending.callerPubkey, pending.creditId, pending.fundId);
8544
8818
  }
8545
- function shouldClearPending(err) {
8546
- return isPermanentRefusal(err) || err instanceof DvmError && err.code === "lightning_unavailable";
8819
+ function lightningFundingTerminal(err, pending) {
8820
+ if (!(err instanceof DvmError)) return false;
8821
+ if (err.code === "lightning_invoice_expired") return true;
8822
+ if (err.code === "lightning_unavailable") {
8823
+ return !pending.bolt11 && pending.paymentOutcome === void 0;
8824
+ }
8825
+ return isPermanentRefusal(err);
8547
8826
  }
8548
- function expiredFunding(base) {
8827
+ function expiredUnresolvedFunding(base) {
8549
8828
  const error = new DvmError(
8550
8829
  "lightning_invoice_expired",
8551
- "The original Lightning funding invoice expired before it was confirmed.",
8552
- "Re-run the funding to start a new intent with a new funding id."
8830
+ "The original Lightning funding invoice expired before the DVM confirmed it.",
8831
+ "Re-run this funding or check 'dvm credit balance' to reconcile the saved funding id. A new invoice is only issued once the DVM resolves this one."
8553
8832
  );
8554
8833
  return {
8555
8834
  ...base,
8556
8835
  status: "refused",
8557
8836
  error,
8558
- display: "The original Lightning invoice expired before it was funded. It was cleared and will not be polled again.",
8837
+ display: "The original Lightning invoice expired and the DVM has not resolved it yet. Nothing was paid on this attempt; the funding id is saved so a payment sent before expiry can still be credited.",
8559
8838
  hint: error.hint
8560
8839
  };
8561
8840
  }
8841
+ function unresolvedFunding(base, err) {
8842
+ const error = err instanceof DvmError ? err : new DvmError("provider_error", "Could not confirm the Lightning funding.");
8843
+ return {
8844
+ ...base,
8845
+ status: "refused",
8846
+ error,
8847
+ display: `This Lightning funding is unresolved (${error.code}). Its original funding id is saved; payment may already have happened.`,
8848
+ hint: "Re-run this funding or check 'dvm credit balance' to reconcile the saved funding id before paying again."
8849
+ };
8850
+ }
8851
+ function paidButRefused(args, base, spend, spendDisplay, err) {
8852
+ return {
8853
+ ...base,
8854
+ ...spend,
8855
+ status: "refused",
8856
+ error: err,
8857
+ display: `The Lightning payment went out, but the DVM won't be crediting it (${err.code}). ${err.message} ${spendDisplay}`,
8858
+ hint: `Don't fund again \u2014 a fresh funding id issues a second invoice. The payment is on record ('dvm wallet history'); quote funding id ${base.fundId} to the operator of ${args.ref.endpoint}.`
8859
+ };
8860
+ }
8861
+ function paidAwaitingSettlement(base, spend, spendDisplay, unconfirmed) {
8862
+ return {
8863
+ ...base,
8864
+ ...spend,
8865
+ status: "settlement_pending",
8866
+ ...unconfirmed ? { error: unconfirmed } : {},
8867
+ display: unconfirmed ? `The Lightning payment went out and is recorded, but the DVM couldn't be reached to confirm it (${unconfirmed.code}). It credits the balance the next time it hears from you \u2014 nothing is lost. ${spendDisplay}` : `The Lightning payment went out and is recorded, but the DVM hasn't seen it land yet. It credits the balance on your next call \u2014 nothing is lost. ${spendDisplay}`,
8868
+ // Both verbs poll the durable `(credit_id, fund_id)`: neither can mint a
8869
+ // second invoice while this intent remains in flight.
8870
+ hint: "Re-run this funding or check with 'dvm credit balance' \u2014 both re-poll the original funding id, and any next request makes the DVM look for settlement."
8871
+ };
8872
+ }
8562
8873
  function lightningOffer(err) {
8563
8874
  if (!isSettlementPending(err)) return void 0;
8564
8875
  const offer = err.data?.lightning;
@@ -8655,7 +8966,8 @@ function forcedRailHint(args, rail) {
8655
8966
  return `This DVM advertises credit funding over ${advertised.join(", ") || "no rail at all"}, not ${rail}. ${release.text}`;
8656
8967
  }
8657
8968
  if (rail === "lightning") {
8658
- const connect = `No Lightning wallet is connected here, so direct Lightning credit funding cannot proceed. No money moved. ${walletInvoiceFundingAdvice(args.amountMicro).text} Or connect a wallet that supports it with 'dvm wallet connect', piping the connection string in`;
8969
+ const invoice = creditInvoiceCommand({ endpoint: args.ref.endpoint, amountMicro: args.amountMicro, creditId: args.creditId, identity: args.invoiceIdentity });
8970
+ const connect = `No Lightning wallet is connected here. No money moved. Run ${invoice} to fund this credit by paying an invoice from any Lightning wallet. ${walletInvoiceFundingAdvice(args.amountMicro).text} Or connect a wallet that supports it with 'dvm wallet connect', piping the connection string in`;
8659
8971
  return release.instruction ? `${connect}, or ${lowerFirst(release.text)}` : `${connect}. ${release.text}`;
8660
8972
  }
8661
8973
  if (rail === "x402") {
@@ -9670,6 +9982,7 @@ export {
9670
9982
  recordUpfrontCreditPayment,
9671
9983
  hasUnknownUpfrontCredit,
9672
9984
  recordUpfrontRailPayment,
9985
+ addCashuSwapFee,
9673
9986
  hasUnknownUpfrontRail,
9674
9987
  updateJob,
9675
9988
  updateObservedJob,
@@ -9710,6 +10023,10 @@ export {
9710
10023
  journalFile,
9711
10024
  extractBuilderHandle,
9712
10025
  reservedForMarker,
10026
+ submissionSwapFeeSats,
10027
+ MINT_FEE_EXPLAINER,
10028
+ describeCashuPayment,
10029
+ cashuPaymentFeeFields,
9713
10030
  inFlightTimeoutSeconds,
9714
10031
  meltInFlightTimeoutSeconds,
9715
10032
  proofKey,
@@ -9753,6 +10070,7 @@ export {
9753
10070
  paymentCountHint,
9754
10071
  overBudgetHint,
9755
10072
  buildTempoCredential,
10073
+ cardMinimumMicro,
9756
10074
  listPendingCardFundings,
9757
10075
  completedCreditHistory,
9758
10076
  completedDrainMatches,
@@ -9762,7 +10080,6 @@ export {
9762
10080
  formatDurationMs,
9763
10081
  walletHistory,
9764
10082
  dvmLabelFromEndpoint,
9765
- CARD_MIN_MICRO,
9766
10083
  walletInvoiceFundingAdvice,
9767
10084
  floatPaymentJson,
9768
10085
  floatPaymentDisplay,