@dvmkit/dvm-cli 0.19.1 → 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.
- package/dist/{chunk-MM646MFM.js → chunk-2B2MCZ2I.js} +3 -3
- package/dist/{chunk-NKD4NEUF.js → chunk-2YPUKPJN.js} +2 -2
- package/dist/{chunk-X6BETQ7V.js → chunk-4RINUKY4.js} +1 -0
- package/dist/{chunk-NCX4JVLU.js → chunk-4S6TNP4N.js} +546 -170
- package/dist/{chunk-B5KW2TPR.js → chunk-DOAMK5C6.js} +1 -1
- package/dist/{chunk-3NXAIRFF.js → chunk-EEQPFGPM.js} +1 -1
- package/dist/{chunk-OCVRCWBL.js → chunk-MSQJWCPT.js} +2 -2
- package/dist/{chunk-7HJ5ZR3D.js → chunk-QXXPXQLM.js} +1 -1
- package/dist/{client-PY4T2DOA.js → client-FKYQXFBN.js} +2 -2
- package/dist/dvm.js +1016 -497
- package/dist/{internal-WAQ3LZN4.js → internal-EQJXMIR2.js} +1 -1
- package/dist/{lifecycle-NOK3MKL4.js → lifecycle-3IBVUCTB.js} +2 -2
- package/dist/{pocket-refill-U4VK5WGO.js → pocket-refill-M65PPCN3.js} +6 -6
- package/dist/{tempo-lifecycle-QGJ4JEHN.js → tempo-lifecycle-Q3N5GGIQ.js} +4 -4
- package/dist/{tempo-wallet-GDDZZP5S.js → tempo-wallet-AY6R3E4Z.js} +3 -3
- package/dist/{wallet-2M3H75UP.js → wallet-J7JCMFZ2.js} +3 -3
- package/package.json +1 -1
- package/skills/dvm/calling.md +5 -1
- package/skills/dvm/credit.md +10 -2
- package/skills/dvm/recovery.md +7 -1
- package/skills/dvm/wallets.md +6 -0
|
@@ -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-
|
|
6
|
+
} from "./chunk-2B2MCZ2I.js";
|
|
7
7
|
import {
|
|
8
8
|
loadX402Wallet,
|
|
9
9
|
x402NetworkLabel
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-2YPUKPJN.js";
|
|
11
11
|
import {
|
|
12
12
|
isCreditPosture,
|
|
13
13
|
loadConfig
|
|
14
|
-
} from "./chunk-
|
|
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-
|
|
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-
|
|
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 =
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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(
|
|
516
|
-
const clean =
|
|
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
|
|
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} ${
|
|
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} ${
|
|
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} ${
|
|
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} ${
|
|
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} ${
|
|
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} ${
|
|
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} ${
|
|
678
|
+
return `${when} ${dvm} ${label2} ${amount}; principal ${String(principal)} + routing ${String(e.routingFeeMsats / 1e3)} sats`;
|
|
666
679
|
}
|
|
667
680
|
}
|
|
668
|
-
return `${when} ${dvm} ${
|
|
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 (
|
|
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
|
|
851
|
-
info(`${
|
|
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 =
|
|
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
|
|
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
|
|
1698
|
-
const display = [raised,
|
|
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: { ...
|
|
1734
|
+
return { ...base, status: "checkout_pending", checkoutHandoff: { ...handoff2, display }, display };
|
|
1701
1735
|
}
|
|
1702
1736
|
if (!announced) {
|
|
1703
|
-
args.cardCheckoutProgress?.({ ...
|
|
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
|
-
|
|
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(
|
|
2053
|
-
`Fund at least $${usd(
|
|
2054
|
-
{ rail: "stripe", 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(
|
|
2057
|
-
`Fund at least $${usd(
|
|
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";
|
|
@@ -2744,27 +2895,61 @@ function parseUpfrontRailPayment(value) {
|
|
|
2744
2895
|
...Number.isSafeInteger(raw.usdMicro) && raw.usdMicro >= 0 ? { usdMicro: raw.usdMicro } : {}
|
|
2745
2896
|
};
|
|
2746
2897
|
}
|
|
2747
|
-
|
|
2748
|
-
|
|
2898
|
+
var UPFRONT_RAILS = {
|
|
2899
|
+
cashu: true,
|
|
2900
|
+
x402: true,
|
|
2901
|
+
tempo: true,
|
|
2902
|
+
lightning: true,
|
|
2903
|
+
stripe: true
|
|
2904
|
+
};
|
|
2905
|
+
function isUpfrontRail(value) {
|
|
2906
|
+
return typeof value === "string" && Object.hasOwn(UPFRONT_RAILS, value);
|
|
2907
|
+
}
|
|
2908
|
+
function checkUpfrontPayment(value) {
|
|
2909
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { reason: "upfront_payment is not an object" };
|
|
2749
2910
|
const raw = value;
|
|
2750
|
-
if (!Number.isSafeInteger(raw.amount_msats) || Number(raw.amount_msats) < 0)
|
|
2911
|
+
if (!Number.isSafeInteger(raw.amount_msats) || Number(raw.amount_msats) < 0)
|
|
2912
|
+
return { reason: "amount_msats is not a non-negative integer" };
|
|
2751
2913
|
for (const key of ["amount_micro", "native_amount"]) {
|
|
2752
|
-
if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || Number(raw[key]) < 0))
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
if (raw.
|
|
2914
|
+
if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || Number(raw[key]) < 0))
|
|
2915
|
+
return { reason: `${key} is not a non-negative integer` };
|
|
2916
|
+
}
|
|
2917
|
+
if (raw.amount_micro === void 0 !== (raw.currency === void 0))
|
|
2918
|
+
return { reason: "amount_micro and currency must be set together" };
|
|
2919
|
+
if (raw.currency !== void 0 && (typeof raw.currency !== "string" || !/^[a-z]{3}$/.test(raw.currency)))
|
|
2920
|
+
return { reason: "currency is not a lowercase three-letter code" };
|
|
2921
|
+
if (raw.credit_id === void 0 !== (raw.draw_id === void 0))
|
|
2922
|
+
return { reason: "credit_id and draw_id must be set together" };
|
|
2756
2923
|
for (const key of ["credit_id", "draw_id", "native_asset"]) {
|
|
2757
|
-
if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key].trim().length === 0))
|
|
2924
|
+
if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key].trim().length === 0))
|
|
2925
|
+
return { reason: `${key} is not a non-empty string` };
|
|
2758
2926
|
}
|
|
2759
|
-
if (raw.rail !== void 0 && !
|
|
2760
|
-
|
|
2927
|
+
if (raw.rail !== void 0 && !isUpfrontRail(raw.rail))
|
|
2928
|
+
return { reason: `rail ${JSON.stringify(String(raw.rail)).slice(0, 40)} is not a known funding rail` };
|
|
2929
|
+
return { payment: {
|
|
2761
2930
|
amount_msats: raw.amount_msats,
|
|
2762
2931
|
...raw.amount_micro !== void 0 ? { amount_micro: raw.amount_micro, currency: raw.currency } : {},
|
|
2763
2932
|
...raw.rail !== void 0 ? { rail: raw.rail } : {},
|
|
2764
2933
|
...raw.native_amount !== void 0 ? { native_amount: raw.native_amount } : {},
|
|
2765
2934
|
...raw.native_asset !== void 0 ? { native_asset: raw.native_asset } : {},
|
|
2766
2935
|
...raw.credit_id !== void 0 ? { credit_id: raw.credit_id, draw_id: raw.draw_id } : {}
|
|
2767
|
-
};
|
|
2936
|
+
} };
|
|
2937
|
+
}
|
|
2938
|
+
function parseUpfrontPayment(value) {
|
|
2939
|
+
const checked = checkUpfrontPayment(value);
|
|
2940
|
+
return "payment" in checked ? checked.payment : void 0;
|
|
2941
|
+
}
|
|
2942
|
+
function upfrontPaymentFault(value) {
|
|
2943
|
+
if (value === void 0 || value === null) return void 0;
|
|
2944
|
+
const checked = checkUpfrontPayment(value);
|
|
2945
|
+
return "reason" in checked ? checked.reason : void 0;
|
|
2946
|
+
}
|
|
2947
|
+
function upfrontReceiptFields(value) {
|
|
2948
|
+
const fault = upfrontPaymentFault(value);
|
|
2949
|
+
return { upfrontPayment: parseUpfrontPayment(value), ...fault ? { upfrontPaymentFault: fault } : {} };
|
|
2950
|
+
}
|
|
2951
|
+
function receiptUpfrontFault(receipt) {
|
|
2952
|
+
return receipt.upfrontPaymentFault;
|
|
2768
2953
|
}
|
|
2769
2954
|
|
|
2770
2955
|
// src/lib/job-budget.ts
|
|
@@ -2832,28 +3017,51 @@ function saveSubmittedJob(job) {
|
|
|
2832
3017
|
throw new Error("Submitted job conflicts with an existing local job.");
|
|
2833
3018
|
}, true, job);
|
|
2834
3019
|
}
|
|
2835
|
-
function
|
|
3020
|
+
function markUpfrontCreditConflict(job, reason, recoverable = false) {
|
|
3021
|
+
const wasRecoverable = job.upfrontCreditConflictRecoverable === true;
|
|
3022
|
+
if (job.upfrontCreditConflict && !(wasRecoverable && !recoverable)) {
|
|
3023
|
+
job.upfrontCreditConflictReason ??= reason;
|
|
3024
|
+
return;
|
|
3025
|
+
}
|
|
3026
|
+
job.upfrontCreditConflict = true;
|
|
3027
|
+
job.upfrontCreditConflictReason = reason;
|
|
3028
|
+
if (recoverable) job.upfrontCreditConflictRecoverable = true;
|
|
3029
|
+
else delete job.upfrontCreditConflictRecoverable;
|
|
3030
|
+
}
|
|
3031
|
+
function recordUpfrontCreditPayment(jobId, value, paidOnRail = false, fault) {
|
|
2836
3032
|
const payment = parseUpfrontPayment(value);
|
|
3033
|
+
const unusable = fault ?? upfrontPaymentFault(value);
|
|
2837
3034
|
mutateJobs((jobs) => {
|
|
2838
3035
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
2839
|
-
if (!job
|
|
3036
|
+
if (!job) return;
|
|
3037
|
+
if (!payment) {
|
|
3038
|
+
if (unusable && !paidOnRail && job.paymentMethod === "credit" && !job.upfrontCreditBooked) {
|
|
3039
|
+
markUpfrontCreditConflict(job, `the provider's upfront_payment was unusable: ${unusable}`, true);
|
|
3040
|
+
}
|
|
3041
|
+
return;
|
|
3042
|
+
}
|
|
2840
3043
|
if (paidOnRail || job.paymentMethod && job.paymentMethod !== "credit") {
|
|
2841
3044
|
job.upfrontPayment ??= payment;
|
|
2842
3045
|
return;
|
|
2843
3046
|
}
|
|
2844
3047
|
if (!payment.credit_id || !payment.draw_id) {
|
|
2845
|
-
if (job.paymentMethod === "credit") job
|
|
3048
|
+
if (job.paymentMethod === "credit") markUpfrontCreditConflict(job, "the accepted debit names no credit draw");
|
|
2846
3049
|
return;
|
|
2847
3050
|
}
|
|
2848
3051
|
const binding = job.creditBinding;
|
|
2849
3052
|
if (!binding || "unbound" in binding || binding.creditId !== payment.credit_id || binding.drawId !== payment.draw_id) {
|
|
2850
|
-
job
|
|
3053
|
+
markUpfrontCreditConflict(job, "the accepted debit does not match this job's credit draw");
|
|
2851
3054
|
return;
|
|
2852
3055
|
}
|
|
2853
3056
|
if (job.upfrontPayment && JSON.stringify(job.upfrontPayment) !== JSON.stringify(payment)) {
|
|
2854
|
-
job
|
|
3057
|
+
markUpfrontCreditConflict(job, "the provider reported a different accepted debit than the one recorded");
|
|
2855
3058
|
return;
|
|
2856
3059
|
}
|
|
3060
|
+
if (job.upfrontCreditConflictRecoverable) {
|
|
3061
|
+
delete job.upfrontCreditConflict;
|
|
3062
|
+
delete job.upfrontCreditConflictReason;
|
|
3063
|
+
delete job.upfrontCreditConflictRecoverable;
|
|
3064
|
+
}
|
|
2857
3065
|
job.upfrontPayment = payment;
|
|
2858
3066
|
job.paymentMethod = "credit";
|
|
2859
3067
|
if (job.upfrontCreditBooked) return;
|
|
@@ -2892,6 +3100,13 @@ function recordUpfrontRailPayment(jobId, value, freshSubmit = false) {
|
|
|
2892
3100
|
job.upfrontRailPayment = payment;
|
|
2893
3101
|
}, true);
|
|
2894
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
|
+
}
|
|
2895
3110
|
function hasUnknownUpfrontRail(job) {
|
|
2896
3111
|
return job.upfrontRailPayment === "unknown" || job.upfrontRailConflict === true;
|
|
2897
3112
|
}
|
|
@@ -3976,6 +4191,28 @@ function reservedForMarker(builderHandle) {
|
|
|
3976
4191
|
return `${BUILDER_RESERVE_PREFIX}${builderHandle}`;
|
|
3977
4192
|
}
|
|
3978
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
|
+
|
|
3979
4216
|
// src/lib/wallet-agent/inflight.ts
|
|
3980
4217
|
var DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC = 60;
|
|
3981
4218
|
var INFLIGHT_TIMEOUT_ENV = "DVM_INFLIGHT_PROOF_TIMEOUT_SEC";
|
|
@@ -4087,6 +4324,9 @@ function formatLocktime(seconds) {
|
|
|
4087
4324
|
}
|
|
4088
4325
|
|
|
4089
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
|
+
}
|
|
4090
4330
|
async function prepareAgentSpend(args) {
|
|
4091
4331
|
if (args.maxCashuPrincipalSats !== void 0 && (!Number.isSafeInteger(args.maxCashuPrincipalSats) || args.maxCashuPrincipalSats < 0)) {
|
|
4092
4332
|
return {
|
|
@@ -4243,6 +4483,7 @@ async function prepareAgentSpend(args) {
|
|
|
4243
4483
|
requestId: inner2.requestId,
|
|
4244
4484
|
mint: inner2.mint,
|
|
4245
4485
|
totalSats: inner2.submission.amount_sats,
|
|
4486
|
+
swapFeeSats: 0,
|
|
4246
4487
|
endpoint: args.endpoint,
|
|
4247
4488
|
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
4248
4489
|
fromReserve: true,
|
|
@@ -4257,29 +4498,26 @@ async function prepareAgentSpend(args) {
|
|
|
4257
4498
|
let inner;
|
|
4258
4499
|
let sendProofs = [];
|
|
4259
4500
|
let keepProofs = [];
|
|
4501
|
+
let swapFeeSats = 0;
|
|
4260
4502
|
for (const [index, mint] of lock1.candidateMints.entries()) {
|
|
4261
4503
|
const hasNextCandidate = index < lock1.candidateMints.length - 1;
|
|
4262
4504
|
let candidateWallet;
|
|
4263
4505
|
try {
|
|
4264
4506
|
candidateWallet = await getWalletForMint(mint);
|
|
4265
4507
|
rememberKeysetFees(mint, candidateWallet);
|
|
4266
|
-
} catch
|
|
4267
|
-
attempts.push(
|
|
4508
|
+
} catch {
|
|
4509
|
+
attempts.push(spendMintAttempt(mint, "unreachable"));
|
|
4268
4510
|
continue;
|
|
4269
4511
|
}
|
|
4270
4512
|
let reserveSats;
|
|
4271
4513
|
try {
|
|
4272
4514
|
reserveSats = swapSendReserve(candidateWallet, args.amountSats);
|
|
4273
|
-
} catch
|
|
4274
|
-
attempts.push(
|
|
4515
|
+
} catch {
|
|
4516
|
+
attempts.push(spendMintAttempt(mint, "keys_unavailable"));
|
|
4275
4517
|
continue;
|
|
4276
4518
|
}
|
|
4277
4519
|
if (!swapEnabled(candidateWallet)) {
|
|
4278
|
-
attempts.push(
|
|
4279
|
-
mint,
|
|
4280
|
-
reason: "swap_disabled",
|
|
4281
|
-
message: "Mint advertises swaps switched off (NUT-3 disabled)."
|
|
4282
|
-
});
|
|
4520
|
+
attempts.push(spendMintAttempt(mint, "swap_disabled"));
|
|
4283
4521
|
continue;
|
|
4284
4522
|
}
|
|
4285
4523
|
const lock2 = await withWalletLock(() => {
|
|
@@ -4313,7 +4551,7 @@ async function prepareAgentSpend(args) {
|
|
|
4313
4551
|
return {
|
|
4314
4552
|
error: {
|
|
4315
4553
|
code: "cashu_fee_cap_exceeded",
|
|
4316
|
-
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.`,
|
|
4317
4555
|
hint: "Raise --max-cashu-fee-sats only after approval, or fund an accepted mint with a lower swap fee."
|
|
4318
4556
|
}
|
|
4319
4557
|
};
|
|
@@ -4362,12 +4600,12 @@ async function prepareAgentSpend(args) {
|
|
|
4362
4600
|
if (lock2.error.code === "no_agent_wallet") return lock2;
|
|
4363
4601
|
if (lock2.error.code === "cashu_fee_cap_exceeded") {
|
|
4364
4602
|
lastFeeCapError = lock2.error;
|
|
4365
|
-
attempts.push(
|
|
4603
|
+
attempts.push(spendMintAttempt(mint, "fee_cap_exceeded", lock2.error.message));
|
|
4366
4604
|
continue;
|
|
4367
4605
|
}
|
|
4368
4606
|
const selectError = lock2.error;
|
|
4369
4607
|
lastSelectError = selectError;
|
|
4370
|
-
attempts.push(
|
|
4608
|
+
attempts.push(spendMintAttempt(mint, selectError.code, selectError.message));
|
|
4371
4609
|
continue;
|
|
4372
4610
|
}
|
|
4373
4611
|
const swapBuilder = candidateWallet.ops.send(lock2.submission.amount_sats, toCashuProofs(lock2.selectedProofs)).asP2PK({
|
|
@@ -4377,8 +4615,8 @@ async function prepareAgentSpend(args) {
|
|
|
4377
4615
|
let preview;
|
|
4378
4616
|
try {
|
|
4379
4617
|
preview = await swapBuilder.prepare();
|
|
4380
|
-
} catch
|
|
4381
|
-
attempts.push(
|
|
4618
|
+
} catch {
|
|
4619
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected"));
|
|
4382
4620
|
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4383
4621
|
if (hasNextCandidate) continue;
|
|
4384
4622
|
break;
|
|
@@ -4422,14 +4660,19 @@ async function prepareAgentSpend(args) {
|
|
|
4422
4660
|
inner = { ...lock2, submission: preparedSubmission };
|
|
4423
4661
|
sendProofs = result.send;
|
|
4424
4662
|
keepProofs = result.keep;
|
|
4663
|
+
swapFeeSats = Math.max(
|
|
4664
|
+
0,
|
|
4665
|
+
sumAmounts(preview.inputs) - sumAmounts(keepProofs) - lock2.submission.amount_sats
|
|
4666
|
+
);
|
|
4425
4667
|
break;
|
|
4426
4668
|
} catch (err) {
|
|
4427
|
-
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
4428
4669
|
if (err instanceof te) {
|
|
4670
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected"));
|
|
4429
4671
|
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4430
4672
|
if (hasNextCandidate) continue;
|
|
4431
4673
|
break;
|
|
4432
4674
|
}
|
|
4675
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected", "Mint swap outcome is unknown; recovery is required."));
|
|
4433
4676
|
inputsLeftInFlight = true;
|
|
4434
4677
|
break;
|
|
4435
4678
|
}
|
|
@@ -4455,6 +4698,7 @@ async function prepareAgentSpend(args) {
|
|
|
4455
4698
|
...s,
|
|
4456
4699
|
output_proofs: agentOutputs,
|
|
4457
4700
|
swapping: void 0,
|
|
4701
|
+
swap_fee_sats: swapFeeSats,
|
|
4458
4702
|
cashu_token: cashuToken,
|
|
4459
4703
|
...boundContext ? { context: boundContext } : {},
|
|
4460
4704
|
// What a later reclaim needs. Only the swap path
|
|
@@ -4476,32 +4720,36 @@ async function prepareAgentSpend(args) {
|
|
|
4476
4720
|
requestId: inner.requestId,
|
|
4477
4721
|
mint: inner.mint,
|
|
4478
4722
|
totalSats: inner.submission.amount_sats,
|
|
4723
|
+
swapFeeSats,
|
|
4479
4724
|
endpoint: args.endpoint,
|
|
4480
4725
|
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
4481
4726
|
...attempts.length > 0 ? { attempts: successfulSpendAttempts(attempts) } : {},
|
|
4482
4727
|
...boundContext?.binding_fingerprint ? { submissionBindingFingerprint: boundContext.binding_fingerprint } : {}
|
|
4483
4728
|
};
|
|
4484
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
|
+
}
|
|
4485
4751
|
function successfulSpendAttempts(attempts) {
|
|
4486
|
-
|
|
4487
|
-
unreachable: "Mint could not be loaded.",
|
|
4488
|
-
keys_unavailable: "Mint did not provide an active keyset.",
|
|
4489
|
-
swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
|
|
4490
|
-
fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
|
|
4491
|
-
insufficient_balance: "Mint balance cannot cover the price and swap fee.",
|
|
4492
|
-
no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
|
|
4493
|
-
swap_rejected: "Mint swap could not be prepared or was definitely refused."
|
|
4494
|
-
};
|
|
4495
|
-
return attempts.map(({ mint, reason }) => {
|
|
4496
|
-
let safeMint;
|
|
4497
|
-
try {
|
|
4498
|
-
new URL(mint);
|
|
4499
|
-
safeMint = redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
|
|
4500
|
-
} catch {
|
|
4501
|
-
safeMint = "[invalid mint URL]";
|
|
4502
|
-
}
|
|
4503
|
-
return { mint: safeMint, reason, message: messages[reason] };
|
|
4504
|
-
});
|
|
4752
|
+
return attempts.map((attempt) => ({ ...attempt, message: SPEND_ATTEMPT_MESSAGES[attempt.reason] }));
|
|
4505
4753
|
}
|
|
4506
4754
|
function principalCapFailure(principalSats, maxCashuPrincipalSats) {
|
|
4507
4755
|
return {
|
|
@@ -4582,6 +4830,7 @@ async function commitHeldSubmission(requestId, now = Date.now) {
|
|
|
4582
4830
|
dvm_endpoint: submission.endpoint,
|
|
4583
4831
|
mint: submission.mint,
|
|
4584
4832
|
amount_sats: submission.amount_sats,
|
|
4833
|
+
...submissionSwapFeeSats(submission) > 0 ? { fee_sats: submissionSwapFeeSats(submission) } : {},
|
|
4585
4834
|
signed_at_ms: now()
|
|
4586
4835
|
}].slice(-RECENT_SPENDS_CAP)
|
|
4587
4836
|
});
|
|
@@ -4697,7 +4946,7 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
|
|
|
4697
4946
|
if (attempts.length === 1) return { ...lastSelectError, attempts };
|
|
4698
4947
|
return {
|
|
4699
4948
|
code: lastSelectError.code,
|
|
4700
|
-
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)}.`),
|
|
4701
4950
|
hint: lastSelectError.hint,
|
|
4702
4951
|
attempts
|
|
4703
4952
|
};
|
|
@@ -4708,14 +4957,14 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
|
|
|
4708
4957
|
if (attempts.length === 1) return { ...lastFeeCapError, attempts };
|
|
4709
4958
|
return {
|
|
4710
4959
|
...lastFeeCapError,
|
|
4711
|
-
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)}.`),
|
|
4712
4961
|
attempts
|
|
4713
4962
|
};
|
|
4714
4963
|
}
|
|
4715
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)}.`;
|
|
4716
4965
|
return {
|
|
4717
4966
|
code: "swap_failed",
|
|
4718
|
-
message,
|
|
4967
|
+
message: boundedSpendMessage(message),
|
|
4719
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.",
|
|
4720
4969
|
attempts
|
|
4721
4970
|
};
|
|
@@ -4726,6 +4975,9 @@ function isSelectionReason(reason) {
|
|
|
4726
4975
|
function describeAttempts(attempts) {
|
|
4727
4976
|
return attempts.map((a) => `${a.mint} \u2014 ${a.reason} (${a.message})`).join("; ");
|
|
4728
4977
|
}
|
|
4978
|
+
function boundedSpendMessage(message) {
|
|
4979
|
+
return message.length <= 4096 ? message : `${message.slice(0, 4095)}\u2026`;
|
|
4980
|
+
}
|
|
4729
4981
|
function swapEnabled(cashuWallet) {
|
|
4730
4982
|
const loose = cashuWallet;
|
|
4731
4983
|
let nuts;
|
|
@@ -4738,9 +4990,6 @@ function swapEnabled(cashuWallet) {
|
|
|
4738
4990
|
if (typeof nuts !== "object" || nuts === null) return true;
|
|
4739
4991
|
return canSwap(nuts);
|
|
4740
4992
|
}
|
|
4741
|
-
function errorText(err) {
|
|
4742
|
-
return err instanceof Error ? err.message : String(err);
|
|
4743
|
-
}
|
|
4744
4993
|
function selectReserveProofs(args) {
|
|
4745
4994
|
const marker = reservedForMarker(args.builderHandle);
|
|
4746
4995
|
const candidates = args.proofs.filter(
|
|
@@ -5309,12 +5558,12 @@ async function stablecoinRemaining(rail) {
|
|
|
5309
5558
|
const balance = await Promise.race([
|
|
5310
5559
|
(async () => {
|
|
5311
5560
|
if (rail === "x402") {
|
|
5312
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
5561
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-J7JCMFZ2.js");
|
|
5313
5562
|
const wallet = loadX402Wallet2();
|
|
5314
5563
|
if (!wallet) return;
|
|
5315
5564
|
return (await getX402Balance(await ensureAddress(wallet))).usdc;
|
|
5316
5565
|
}
|
|
5317
|
-
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-
|
|
5566
|
+
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-AY6R3E4Z.js");
|
|
5318
5567
|
const account = await connectedTempoAccount2();
|
|
5319
5568
|
if (account) return (await getTempoUsdcBalance(account)).usdc;
|
|
5320
5569
|
})(),
|
|
@@ -5451,6 +5700,8 @@ function settlementCurrency(receipt, job, messages, hint) {
|
|
|
5451
5700
|
candidates.push(hint);
|
|
5452
5701
|
const creditId = receipt.credit?.credit_id;
|
|
5453
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");
|
|
5454
5705
|
const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
|
|
5455
5706
|
return found ? found.toLowerCase() : null;
|
|
5456
5707
|
}
|
|
@@ -6055,6 +6306,12 @@ var TEMPO_AMOUNT_REFUSALS = /* @__PURE__ */ new Set(["tempo_amount_exceeds_limit
|
|
|
6055
6306
|
var SETTLEMENT_POLLS = 3;
|
|
6056
6307
|
var SETTLEMENT_POLL_DELAY_MS = 1500;
|
|
6057
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
|
+
}
|
|
6058
6315
|
return withFundingMode(await runCreditFunding(args));
|
|
6059
6316
|
}
|
|
6060
6317
|
async function runCreditFunding(args) {
|
|
@@ -6097,7 +6354,7 @@ async function runCreditFunding(args) {
|
|
|
6097
6354
|
}
|
|
6098
6355
|
const pending = loadPendingFunding(args.ref.endpoint, args.signing.pubkey, args.creditId);
|
|
6099
6356
|
if (pending) {
|
|
6100
|
-
if (!pendingFundingExpired(pending)) {
|
|
6357
|
+
if (pending.rail === "lightning" || !pendingFundingExpired(pending)) {
|
|
6101
6358
|
const resumed = argsFromPending(args, pending);
|
|
6102
6359
|
return pending.rail === "tempo" ? fundOverMpp(resumed, pending.fundId, pending) : fundOverLightning(resumed, pending.fundId, pending);
|
|
6103
6360
|
}
|
|
@@ -6177,17 +6434,18 @@ async function runCreditFunding(args) {
|
|
|
6177
6434
|
};
|
|
6178
6435
|
}
|
|
6179
6436
|
async function pollPendingCreditFundings(args) {
|
|
6437
|
+
const refused2 = [];
|
|
6180
6438
|
const pending = listPendingFundings({
|
|
6181
6439
|
endpoint: args.ref.endpoint,
|
|
6182
6440
|
callerPubkey: args.signing.pubkey
|
|
6183
6441
|
});
|
|
6184
6442
|
for (const funding of pending) {
|
|
6185
|
-
if (pendingFundingExpired(funding)) {
|
|
6186
|
-
clearPending(funding);
|
|
6187
|
-
continue;
|
|
6188
|
-
}
|
|
6189
6443
|
const fundArgs = argsFromPending(args, funding);
|
|
6190
6444
|
if (funding.rail === "tempo") {
|
|
6445
|
+
if (pendingFundingExpired(funding)) {
|
|
6446
|
+
clearPending(funding);
|
|
6447
|
+
continue;
|
|
6448
|
+
}
|
|
6191
6449
|
await fundOverMpp(fundArgs, funding.fundId, funding).catch(() => void 0);
|
|
6192
6450
|
continue;
|
|
6193
6451
|
}
|
|
@@ -6202,11 +6460,19 @@ async function pollPendingCreditFundings(args) {
|
|
|
6202
6460
|
} catch (err) {
|
|
6203
6461
|
const offer = lightningOffer(err);
|
|
6204
6462
|
if (offer) {
|
|
6205
|
-
|
|
6206
|
-
|
|
6207
|
-
if (
|
|
6208
|
-
|
|
6209
|
-
|
|
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
|
+
}
|
|
6210
6476
|
}
|
|
6211
6477
|
}
|
|
6212
6478
|
}
|
|
@@ -6252,7 +6518,7 @@ async function pollPendingCreditFundings(args) {
|
|
|
6252
6518
|
}
|
|
6253
6519
|
}
|
|
6254
6520
|
const exactWallet = loadX402Wallet();
|
|
6255
|
-
if (!exactWallet) return;
|
|
6521
|
+
if (!exactWallet) return refused2;
|
|
6256
6522
|
for (const funding of listResumableX402ExactFundings({
|
|
6257
6523
|
endpoint: args.ref.endpoint,
|
|
6258
6524
|
callerPubkey: args.signing.pubkey
|
|
@@ -6272,6 +6538,7 @@ async function pollPendingCreditFundings(args) {
|
|
|
6272
6538
|
funding
|
|
6273
6539
|
).catch(() => void 0);
|
|
6274
6540
|
}
|
|
6541
|
+
return refused2;
|
|
6275
6542
|
}
|
|
6276
6543
|
function availableRails(args) {
|
|
6277
6544
|
const advertised = args.menu?.funding;
|
|
@@ -6281,8 +6548,8 @@ function availableRails(args) {
|
|
|
6281
6548
|
if (offers("cashu") && cashu && cashu.lock_pubkeys.length > 0 && cashu.mints.length > 0) {
|
|
6282
6549
|
rails.push("cashu");
|
|
6283
6550
|
}
|
|
6284
|
-
const float = args.float === void 0 ? loadFloat() : args.float;
|
|
6285
|
-
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");
|
|
6286
6553
|
const x402Wallet = offers("x402") ? loadX402Wallet() : null;
|
|
6287
6554
|
if (x402Wallet && offersX402CreditFunding(args.menu, x402Wallet.network)) rails.push("x402");
|
|
6288
6555
|
if (offers("tempo") && offersTempoCreditFunding(args.menu) && hasConnectedTempoWallet(args)) {
|
|
@@ -7308,6 +7575,7 @@ async function fundOverCashu(args, fundId) {
|
|
|
7308
7575
|
dvm_endpoint: args.ref.endpoint,
|
|
7309
7576
|
mint: prepared.mint,
|
|
7310
7577
|
amount_sats: prepared.totalSats,
|
|
7578
|
+
...prepared.swapFeeSats > 0 ? { fee_sats: prepared.swapFeeSats } : {},
|
|
7311
7579
|
signed_at_ms: Date.now()
|
|
7312
7580
|
}
|
|
7313
7581
|
});
|
|
@@ -8039,27 +8307,29 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8039
8307
|
};
|
|
8040
8308
|
}
|
|
8041
8309
|
}
|
|
8042
|
-
const float2 = args.float === void 0 ? loadFloat() : args.float;
|
|
8043
|
-
if (!float2) {
|
|
8310
|
+
const float2 = args.invoice ? null : args.float === void 0 ? loadFloat() : args.float;
|
|
8311
|
+
if (!float2 && !args.invoice) {
|
|
8044
8312
|
return {
|
|
8045
8313
|
...base,
|
|
8046
8314
|
status: "unavailable",
|
|
8047
8315
|
display: "No Lightning wallet is connected, so the credit can't be funded that way.",
|
|
8048
|
-
|
|
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
|
|
8049
8317
|
};
|
|
8050
8318
|
}
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
|
|
8054
|
-
|
|
8055
|
-
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
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
|
+
}
|
|
8063
8333
|
}
|
|
8064
8334
|
pending = {
|
|
8065
8335
|
endpoint: args.ref.endpoint,
|
|
@@ -8070,36 +8340,68 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8070
8340
|
rail: "lightning",
|
|
8071
8341
|
targetMicro: args.targetMicro ?? args.amountMicro,
|
|
8072
8342
|
...args.menu ? { menu: args.menu } : {},
|
|
8073
|
-
requestedAt: Date.now()
|
|
8343
|
+
requestedAt: Date.now(),
|
|
8344
|
+
...args.invoice ? { lightningPaymentMode: "invoice" } : {}
|
|
8074
8345
|
};
|
|
8075
8346
|
recordPendingFunding(pending);
|
|
8076
8347
|
}
|
|
8077
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
|
+
}
|
|
8078
8360
|
let offer;
|
|
8079
8361
|
try {
|
|
8080
8362
|
const replay = await postCredit(args, creditBody);
|
|
8081
8363
|
return settleAndClear(args, base, replay, lightningSpendFromPending(pending), pending);
|
|
8082
8364
|
} catch (err) {
|
|
8083
8365
|
const parsed = lightningOffer(err);
|
|
8366
|
+
const recorded = lightningSpendFromPending(pending);
|
|
8084
8367
|
if (!parsed) {
|
|
8085
|
-
|
|
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);
|
|
8086
8377
|
return lightningRefusal(base, err);
|
|
8087
8378
|
}
|
|
8088
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
|
+
}
|
|
8089
8394
|
pending = withLightningOffer(pending, offer);
|
|
8090
8395
|
recordPendingFunding(pending);
|
|
8091
8396
|
}
|
|
8092
|
-
if (pendingFundingExpired(pending))
|
|
8093
|
-
clearPending(pending);
|
|
8094
|
-
return expiredFunding(base);
|
|
8095
|
-
}
|
|
8397
|
+
if (pendingFundingExpired(pending)) return expiredUnresolvedFunding(base);
|
|
8096
8398
|
const float = args.float === void 0 ? loadFloat() : args.float;
|
|
8097
8399
|
if (!float) {
|
|
8098
8400
|
return {
|
|
8099
8401
|
...base,
|
|
8100
8402
|
status: "unavailable",
|
|
8101
8403
|
display: "The original Lightning invoice is still pending, but no wallet is connected to pay or reconcile it.",
|
|
8102
|
-
hint:
|
|
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.`
|
|
8103
8405
|
};
|
|
8104
8406
|
}
|
|
8105
8407
|
let payment;
|
|
@@ -8157,32 +8459,15 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8157
8459
|
};
|
|
8158
8460
|
} catch (err) {
|
|
8159
8461
|
if (isPermanentRefusal(err)) {
|
|
8160
|
-
const mapped = err;
|
|
8161
8462
|
clearPending(pending);
|
|
8162
|
-
return
|
|
8163
|
-
...base,
|
|
8164
|
-
...paid,
|
|
8165
|
-
status: "refused",
|
|
8166
|
-
error: mapped,
|
|
8167
|
-
display: `The Lightning payment went out, but the DVM won't be crediting it (${mapped.code}). ${mapped.message} ${floatPaymentDisplay(payment)}`,
|
|
8168
|
-
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}.`
|
|
8169
|
-
};
|
|
8463
|
+
return paidButRefused(args, base, paid, floatPaymentDisplay(payment), err);
|
|
8170
8464
|
}
|
|
8171
8465
|
unconfirmed = err instanceof DvmError && !isSettlementPending(err) ? err : void 0;
|
|
8172
8466
|
if (attempt < SETTLEMENT_POLLS - 1) await sleep(SETTLEMENT_POLL_DELAY_MS);
|
|
8173
8467
|
}
|
|
8174
8468
|
}
|
|
8175
8469
|
recordPendingFunding(pending);
|
|
8176
|
-
return
|
|
8177
|
-
...base,
|
|
8178
|
-
...paid,
|
|
8179
|
-
status: "settlement_pending",
|
|
8180
|
-
...unconfirmed ? { error: unconfirmed } : {},
|
|
8181
|
-
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)}`,
|
|
8182
|
-
// Both verbs poll the durable `(credit_id, fund_id)`: neither can mint a
|
|
8183
|
-
// second invoice while this intent remains in flight.
|
|
8184
|
-
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."
|
|
8185
|
-
};
|
|
8470
|
+
return paidAwaitingSettlement(base, paid, floatPaymentDisplay(payment), unconfirmed);
|
|
8186
8471
|
}
|
|
8187
8472
|
async function postCredit(args, body, payment) {
|
|
8188
8473
|
const transport = args.transport;
|
|
@@ -8366,6 +8651,10 @@ function argsFromPending(args, pending) {
|
|
|
8366
8651
|
...pending.menu ? { menu: pending.menu } : {},
|
|
8367
8652
|
...args.signBody ? { signBody: args.signBody } : {},
|
|
8368
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 } : {},
|
|
8369
8658
|
..."tempoAccount" in args ? { tempoAccount: args.tempoAccount } : {},
|
|
8370
8659
|
...args.tempoGetClient ? { tempoGetClient: args.tempoGetClient } : {},
|
|
8371
8660
|
...args.tempoFetch ? { tempoFetch: args.tempoFetch } : {}
|
|
@@ -8471,6 +8760,7 @@ function otherCreditPendingX402(args) {
|
|
|
8471
8760
|
).sort((a, b) => a.requestedAt - b.requestedAt)[0];
|
|
8472
8761
|
}
|
|
8473
8762
|
function withLightningOffer(pending, offer) {
|
|
8763
|
+
if (pending.paymentOutcome !== void 0 && pending.bolt11) return pending;
|
|
8474
8764
|
return {
|
|
8475
8765
|
...pending,
|
|
8476
8766
|
bolt11: offer.invoice,
|
|
@@ -8479,29 +8769,107 @@ function withLightningOffer(pending, offer) {
|
|
|
8479
8769
|
expiresAtMs: offer.expires_at_ms
|
|
8480
8770
|
};
|
|
8481
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
|
+
}
|
|
8482
8813
|
function pendingFundingExpired(pending, now = Date.now()) {
|
|
8483
8814
|
return pending.expiresAtMs !== void 0 && pending.expiresAtMs <= now;
|
|
8484
8815
|
}
|
|
8485
8816
|
function clearPending(pending) {
|
|
8486
8817
|
clearPendingFunding(pending.endpoint, pending.callerPubkey, pending.creditId, pending.fundId);
|
|
8487
8818
|
}
|
|
8488
|
-
function
|
|
8489
|
-
|
|
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);
|
|
8490
8826
|
}
|
|
8491
|
-
function
|
|
8827
|
+
function expiredUnresolvedFunding(base) {
|
|
8492
8828
|
const error = new DvmError(
|
|
8493
8829
|
"lightning_invoice_expired",
|
|
8494
|
-
"The original Lightning funding invoice expired before
|
|
8495
|
-
"Re-run
|
|
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."
|
|
8496
8832
|
);
|
|
8497
8833
|
return {
|
|
8498
8834
|
...base,
|
|
8499
8835
|
status: "refused",
|
|
8500
8836
|
error,
|
|
8501
|
-
display: "The original Lightning invoice expired
|
|
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.",
|
|
8502
8838
|
hint: error.hint
|
|
8503
8839
|
};
|
|
8504
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
|
+
}
|
|
8505
8873
|
function lightningOffer(err) {
|
|
8506
8874
|
if (!isSettlementPending(err)) return void 0;
|
|
8507
8875
|
const offer = err.data?.lightning;
|
|
@@ -8598,7 +8966,8 @@ function forcedRailHint(args, rail) {
|
|
|
8598
8966
|
return `This DVM advertises credit funding over ${advertised.join(", ") || "no rail at all"}, not ${rail}. ${release.text}`;
|
|
8599
8967
|
}
|
|
8600
8968
|
if (rail === "lightning") {
|
|
8601
|
-
const
|
|
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`;
|
|
8602
8971
|
return release.instruction ? `${connect}, or ${lowerFirst(release.text)}` : `${connect}. ${release.text}`;
|
|
8603
8972
|
}
|
|
8604
8973
|
if (rail === "x402") {
|
|
@@ -9599,6 +9968,8 @@ export {
|
|
|
9599
9968
|
upfrontRailPayment,
|
|
9600
9969
|
parseUpfrontRailPayment,
|
|
9601
9970
|
parseUpfrontPayment,
|
|
9971
|
+
upfrontReceiptFields,
|
|
9972
|
+
receiptUpfrontFault,
|
|
9602
9973
|
budgetVerdict,
|
|
9603
9974
|
dollarBoundUsdMicro,
|
|
9604
9975
|
askUsdMicro,
|
|
@@ -9611,6 +9982,7 @@ export {
|
|
|
9611
9982
|
recordUpfrontCreditPayment,
|
|
9612
9983
|
hasUnknownUpfrontCredit,
|
|
9613
9984
|
recordUpfrontRailPayment,
|
|
9985
|
+
addCashuSwapFee,
|
|
9614
9986
|
hasUnknownUpfrontRail,
|
|
9615
9987
|
updateJob,
|
|
9616
9988
|
updateObservedJob,
|
|
@@ -9651,6 +10023,10 @@ export {
|
|
|
9651
10023
|
journalFile,
|
|
9652
10024
|
extractBuilderHandle,
|
|
9653
10025
|
reservedForMarker,
|
|
10026
|
+
submissionSwapFeeSats,
|
|
10027
|
+
MINT_FEE_EXPLAINER,
|
|
10028
|
+
describeCashuPayment,
|
|
10029
|
+
cashuPaymentFeeFields,
|
|
9654
10030
|
inFlightTimeoutSeconds,
|
|
9655
10031
|
meltInFlightTimeoutSeconds,
|
|
9656
10032
|
proofKey,
|
|
@@ -9694,6 +10070,7 @@ export {
|
|
|
9694
10070
|
paymentCountHint,
|
|
9695
10071
|
overBudgetHint,
|
|
9696
10072
|
buildTempoCredential,
|
|
10073
|
+
cardMinimumMicro,
|
|
9697
10074
|
listPendingCardFundings,
|
|
9698
10075
|
completedCreditHistory,
|
|
9699
10076
|
completedDrainMatches,
|
|
@@ -9703,7 +10080,6 @@ export {
|
|
|
9703
10080
|
formatDurationMs,
|
|
9704
10081
|
walletHistory,
|
|
9705
10082
|
dvmLabelFromEndpoint,
|
|
9706
|
-
CARD_MIN_MICRO,
|
|
9707
10083
|
walletInvoiceFundingAdvice,
|
|
9708
10084
|
floatPaymentJson,
|
|
9709
10085
|
floatPaymentDisplay,
|