@dvmkit/dvm-cli 0.19.2 → 0.21.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-OCVRCWBL.js → chunk-7UGJALAX.js} +3 -3
- package/dist/{chunk-3NXAIRFF.js → chunk-BU5E7IDF.js} +2 -2
- package/dist/{chunk-X6BETQ7V.js → chunk-CMIEPFKP.js} +8327 -27312
- package/dist/{chunk-ZZCYSYXR.js → chunk-EA6RU4OR.js} +10 -10
- package/dist/{chunk-WCX4PNEF.js → chunk-GEG2YAIB.js} +19 -1
- package/dist/{chunk-5ZY5IKS2.js → chunk-GWISSHP6.js} +684 -170
- package/dist/{chunk-MM646MFM.js → chunk-L3PHIA5L.js} +4 -4
- package/dist/{chunk-NKD4NEUF.js → chunk-M4Q3DBQO.js} +3 -3
- package/dist/chunk-MP63OWTD.js +27343 -0
- package/dist/{chunk-W4ADV3HW.js → chunk-NSHMTEFJ.js} +27 -17
- package/dist/{chunk-B5KW2TPR.js → chunk-QVX7KPLS.js} +2 -2
- package/dist/{chunk-7HJ5ZR3D.js → chunk-YRLRHJ6O.js} +2 -2
- package/dist/{client-PY4T2DOA.js → client-MJZL7XTD.js} +6 -6
- package/dist/dvm.js +6219 -773
- package/dist/{internal-WAQ3LZN4.js → internal-TUEXUURQ.js} +5 -5
- package/dist/{lifecycle-NOK3MKL4.js → lifecycle-7PSR5CYB.js} +6 -6
- package/dist/{payout-reporter-5PH53T44-7IA4NGIN.js → payout-reporter-O4OLJXKQ-7N2HPPPY.js} +2 -2
- package/dist/{pocket-refill-ETV6QWO6.js → pocket-refill-OX3WXUZ4.js} +10 -10
- package/dist/{revenue-reporter-4XV3OO5O-RYHS3M34.js → revenue-reporter-RMK4HFEW-7HGJQOXL.js} +2 -2
- package/dist/{tempo-lifecycle-QGJ4JEHN.js → tempo-lifecycle-BOW6OFSI.js} +8 -8
- package/dist/{tempo-wallet-GDDZZP5S.js → tempo-wallet-D424H37T.js} +7 -7
- package/dist/{wallet-2M3H75UP.js → wallet-CZV4TOJ3.js} +7 -7
- package/dist/{x402-FHHB3V4V-CM6OMLHE.js → x402-JCKCGEM3-NFTGP54F.js} +2 -2
- package/package.json +2 -2
- package/skills/dvm/SKILL.md +1 -1
- package/skills/dvm/calling.md +26 -4
- package/skills/dvm/credit.md +10 -2
- package/skills/dvm/recovery.md +6 -0
- package/skills/dvm/wallets.md +4 -0
- package/dist/chunk-DF2OWCRY.js +0 -11127
|
@@ -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-L3PHIA5L.js";
|
|
7
7
|
import {
|
|
8
8
|
loadX402Wallet,
|
|
9
9
|
x402NetworkLabel
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-M4Q3DBQO.js";
|
|
11
11
|
import {
|
|
12
12
|
isCreditPosture,
|
|
13
13
|
loadConfig
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-BU5E7IDF.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-YRLRHJ6O.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-CMIEPFKP.js";
|
|
187
189
|
import {
|
|
188
190
|
Challenge_exports,
|
|
189
191
|
Credential_exports
|
|
@@ -204,7 +206,7 @@ import {
|
|
|
204
206
|
redactUrlsInText,
|
|
205
207
|
usdToMsats,
|
|
206
208
|
x402NetworkToCaip2
|
|
207
|
-
} from "./chunk-
|
|
209
|
+
} from "./chunk-MP63OWTD.js";
|
|
208
210
|
import {
|
|
209
211
|
privateKeyToAccount
|
|
210
212
|
} from "./chunk-EVQERRCP.js";
|
|
@@ -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";
|
|
@@ -2949,19 +3100,32 @@ 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
|
}
|
|
2955
3113
|
function updateJob(id, update) {
|
|
2956
3114
|
mutateJobs((jobs) => {
|
|
2957
3115
|
const idx = jobs.findIndex((j) => j.id === id);
|
|
2958
|
-
if (idx !== -1)
|
|
3116
|
+
if (idx !== -1) {
|
|
3117
|
+
jobs[idx] = { ...jobs[idx], ...update };
|
|
3118
|
+
if (update.status && ["completed", "failed", "cancelled"].includes(update.status)) clearPaymentCreditRefusals(jobs[idx]);
|
|
3119
|
+
}
|
|
2959
3120
|
});
|
|
2960
3121
|
}
|
|
2961
3122
|
function updateObservedJob(id, update) {
|
|
2962
3123
|
mutateJobs((jobs) => {
|
|
2963
3124
|
const idx = jobs.findIndex((j) => j.id === id);
|
|
2964
|
-
if (idx !== -1)
|
|
3125
|
+
if (idx !== -1) {
|
|
3126
|
+
jobs[idx] = { ...jobs[idx], ...update };
|
|
3127
|
+
if (update.status && ["completed", "failed", "cancelled"].includes(update.status)) clearPaymentCreditRefusals(jobs[idx]);
|
|
3128
|
+
}
|
|
2965
3129
|
}, true);
|
|
2966
3130
|
}
|
|
2967
3131
|
function recordCallerMessageHash(jobId, endpoint, hash) {
|
|
@@ -3018,6 +3182,18 @@ function recordBudgetRefusal(jobId, requestSeq, overrun) {
|
|
|
3018
3182
|
if (job) (job.budgetRefusals ??= {})[String(requestSeq)] = overrun;
|
|
3019
3183
|
}, true);
|
|
3020
3184
|
}
|
|
3185
|
+
function recordPaymentCreditLanding(jobId, requestSeq, credit) {
|
|
3186
|
+
mutateCreditPayment(jobId, (job) => {
|
|
3187
|
+
const landings = job.paymentCreditLandings ??= {};
|
|
3188
|
+
const existing = Object.keys(landings).find((key) => landings[key].fund_id === credit.fund_id);
|
|
3189
|
+
landings[existing ?? (landings[requestSeq] ? credit.fund_id : String(requestSeq))] = credit;
|
|
3190
|
+
if (existing !== void 0) return;
|
|
3191
|
+
clearUnconfirmedSubmission(job, requestSeq);
|
|
3192
|
+
job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
|
|
3193
|
+
if (!job.inFlightPaymentRequestSeqs?.length) delete job.inFlightPaymentRequestSeqs;
|
|
3194
|
+
clearPaymentRequestStartTime(job, requestSeq);
|
|
3195
|
+
}, true);
|
|
3196
|
+
}
|
|
3021
3197
|
function markPaymentRequestInFlight(jobId, requestSeq, submission) {
|
|
3022
3198
|
mutateJobs((jobs) => {
|
|
3023
3199
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
@@ -3049,6 +3225,7 @@ function markPaymentRequestPaid(jobId, requestSeq) {
|
|
|
3049
3225
|
const booked2 = mutateJobs((jobs) => {
|
|
3050
3226
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
3051
3227
|
if (!job) return void 0;
|
|
3228
|
+
clearPaymentCreditRefusals(job, requestSeq);
|
|
3052
3229
|
if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
3053
3230
|
(job.paidPaymentRequestSeqs ??= []).push(requestSeq);
|
|
3054
3231
|
if (job.inFlightPaymentRequestSeqs) {
|
|
@@ -3077,10 +3254,16 @@ function markPaymentRequestPaid(jobId, requestSeq) {
|
|
|
3077
3254
|
});
|
|
3078
3255
|
return booked2;
|
|
3079
3256
|
}
|
|
3257
|
+
function clearPaymentCreditRefusals(job, requestSeq) {
|
|
3258
|
+
for (const landing of Object.values(job.paymentCreditLandings ?? {})) {
|
|
3259
|
+
if (requestSeq === void 0 || landing.request_seq === requestSeq) delete landing.credit_payment_unavailable;
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3080
3262
|
function markPaymentRequestAnswered(jobId, requestSeq) {
|
|
3081
3263
|
mutateJobs((jobs) => {
|
|
3082
3264
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
3083
3265
|
if (!job) return;
|
|
3266
|
+
clearPaymentCreditRefusals(job, requestSeq);
|
|
3084
3267
|
if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
3085
3268
|
(job.paidPaymentRequestSeqs ??= []).push(requestSeq);
|
|
3086
3269
|
job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
|
|
@@ -3308,6 +3491,7 @@ function mutateCreditPayment(jobId, change, observed = false) {
|
|
|
3308
3491
|
}
|
|
3309
3492
|
function bookCreditPayment(jobId, intent) {
|
|
3310
3493
|
const booked2 = mutateCreditPayment(jobId, (job) => {
|
|
3494
|
+
clearPaymentCreditRefusals(job, intent.authorization.request_seq);
|
|
3311
3495
|
let booked3 = false;
|
|
3312
3496
|
if (!job.bookedCreditPayments?.some((entry) => entry.authorization.payment_id === intent.authorization.payment_id)) {
|
|
3313
3497
|
booked3 = true;
|
|
@@ -3936,6 +4120,149 @@ function providerJobJson(data, providerJob = true) {
|
|
|
3936
4120
|
}, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
|
|
3937
4121
|
}
|
|
3938
4122
|
|
|
4123
|
+
// src/lib/mandate-payments.ts
|
|
4124
|
+
function mandateCredit(message) {
|
|
4125
|
+
if (message.from !== "requester" || message.type !== "payment") return void 0;
|
|
4126
|
+
const credit = message.content.credit;
|
|
4127
|
+
return credit?.mandate === true ? credit : void 0;
|
|
4128
|
+
}
|
|
4129
|
+
function validMicro2(value) {
|
|
4130
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
4131
|
+
}
|
|
4132
|
+
function safeCurrency(value) {
|
|
4133
|
+
return typeof value === "string" && /^[a-z]{3}$/i.test(value) ? value.toLowerCase() : null;
|
|
4134
|
+
}
|
|
4135
|
+
function money(micro, currency) {
|
|
4136
|
+
if (!validMicro2(micro)) return "an unrecorded amount";
|
|
4137
|
+
return currency ? formatFiat(micro / 1e6, currency) : `${(micro / 1e6).toLocaleString("en-US", { maximumFractionDigits: 6 })} (currency not recorded)`;
|
|
4138
|
+
}
|
|
4139
|
+
function mandateDrawTotal(job, history) {
|
|
4140
|
+
const mandate = job.mandate;
|
|
4141
|
+
if (!mandate) return 0;
|
|
4142
|
+
const bound = (credit) => credit?.credit_id === mandate.credit_id && credit.draw_id === mandate.draw_id && credit.currency === mandate.currency && validMicro2(credit.amount_micro) ? credit.amount_micro : 0;
|
|
4143
|
+
let total = bound(job.upfrontPayment);
|
|
4144
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4145
|
+
for (const message of history) {
|
|
4146
|
+
if (seen.has(message.seq)) continue;
|
|
4147
|
+
seen.add(message.seq);
|
|
4148
|
+
if (message.from === "requester" && message.type === "payment") total += bound(message.content.credit);
|
|
4149
|
+
}
|
|
4150
|
+
return total;
|
|
4151
|
+
}
|
|
4152
|
+
function mandatePaymentReports(job, history) {
|
|
4153
|
+
const mandate = job?.mandate;
|
|
4154
|
+
const currency = safeCurrency(mandate?.currency);
|
|
4155
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4156
|
+
const paidAsks = /* @__PURE__ */ new Set();
|
|
4157
|
+
const reports = [];
|
|
4158
|
+
const asks = /* @__PURE__ */ new Map();
|
|
4159
|
+
const prefix = [];
|
|
4160
|
+
for (const message of [...history].sort((a, b) => a.seq - b.seq)) {
|
|
4161
|
+
if (seen.has(message.seq)) continue;
|
|
4162
|
+
seen.add(message.seq);
|
|
4163
|
+
prefix.push(message);
|
|
4164
|
+
if (message.from === "provider" && message.type === "payment-request") asks.set(message.seq, message);
|
|
4165
|
+
const paid = mandateCredit(message);
|
|
4166
|
+
if (!paid) {
|
|
4167
|
+
if (message.from === "requester" && message.type === "payment") {
|
|
4168
|
+
const seq = message.content.credit?.request_seq ?? [...asks.keys()].at(-1);
|
|
4169
|
+
if (seq !== void 0) paidAsks.add(seq);
|
|
4170
|
+
}
|
|
4171
|
+
continue;
|
|
4172
|
+
}
|
|
4173
|
+
const total = job ? mandateDrawTotal(job, prefix) : 0;
|
|
4174
|
+
const ask = asks.get(paid.request_seq);
|
|
4175
|
+
const violations = [];
|
|
4176
|
+
const reasons = [];
|
|
4177
|
+
const breach = (field, reason) => {
|
|
4178
|
+
violations.push(field);
|
|
4179
|
+
reasons.push(reason);
|
|
4180
|
+
};
|
|
4181
|
+
if (!validMicro2(paid.amount_micro) || paid.amount_micro === 0) breach("amount_micro", "an invalid payment amount");
|
|
4182
|
+
if (!ask) breach("request_seq", "a payment for a charge missing from the job's requests");
|
|
4183
|
+
else if (!ask.content.credit) breach("ask_unpriced", "a payment for a charge with no credit price");
|
|
4184
|
+
else {
|
|
4185
|
+
if (paid.amount_micro > ask.content.credit.amount_micro)
|
|
4186
|
+
breach("ask_amount_micro", `more than the provider requested for this charge (${money(ask.content.credit.amount_micro, currency)})`);
|
|
4187
|
+
if (paid.currency !== ask.content.credit.currency)
|
|
4188
|
+
breach("ask_currency", "a payment in a different currency from the requested charge");
|
|
4189
|
+
}
|
|
4190
|
+
if (paidAsks.has(paid.request_seq)) breach("duplicate_request_seq", "more than one payment for the same charge");
|
|
4191
|
+
paidAsks.add(paid.request_seq);
|
|
4192
|
+
if (mandate) {
|
|
4193
|
+
if (paid.amount_micro > mandate.max_ask_micro)
|
|
4194
|
+
breach("max_ask_micro", `more than your per-charge limit of ${money(mandate.max_ask_micro, currency)}`);
|
|
4195
|
+
if (total > mandate.max_total_micro)
|
|
4196
|
+
breach("max_total_micro", `more than your standing credit budget of ${money(mandate.max_total_micro, currency)}`);
|
|
4197
|
+
if (message.timestamp * 1e3 >= mandate.expires_at_ms)
|
|
4198
|
+
breach("expires_at_ms", `a payment after your standing limit ended on ${new Date(mandate.expires_at_ms).toISOString()}`);
|
|
4199
|
+
if (paid.credit_id !== mandate.credit_id) breach("credit_id", "a different prepaid credit than you authorised");
|
|
4200
|
+
if (paid.draw_id !== mandate.draw_id) breach("draw_id", "a different job credit reservation than you authorised");
|
|
4201
|
+
if (paid.currency !== mandate.currency) breach("currency", "a different currency than you authorised");
|
|
4202
|
+
}
|
|
4203
|
+
const paidCurrency = mandate ? paid.currency === mandate.currency ? currency : null : safeCurrency(paid.currency);
|
|
4204
|
+
const amount = { amount_micro: paid.amount_micro, currency: paid.currency, display: money(paid.amount_micro, paidCurrency) };
|
|
4205
|
+
const overchargeDisplay = reasons.length ? `Provider overcharge: ${reasons.join("; ")}.` : void 0;
|
|
4206
|
+
const display = `${amount.display} paid from your credit under your standing limit. ` + (mandate ? `Running credit total ${money(total, currency)} of ${money(mandate.max_total_micro, currency)} budget.` : "The signed standing limit is not available locally, so its limits could not be checked.") + (overchargeDisplay ? ` ${overchargeDisplay}` : "");
|
|
4207
|
+
reports.push({
|
|
4208
|
+
amount_msats: ask?.content.amount_msats ?? 0,
|
|
4209
|
+
seq: message.seq,
|
|
4210
|
+
request_seq: paid.request_seq,
|
|
4211
|
+
mandate: true,
|
|
4212
|
+
amount,
|
|
4213
|
+
limits_checked: !!mandate,
|
|
4214
|
+
total_micro: total,
|
|
4215
|
+
budget_micro: mandate?.max_total_micro,
|
|
4216
|
+
currency,
|
|
4217
|
+
overcharged: violations.length > 0,
|
|
4218
|
+
violated_limits: violations,
|
|
4219
|
+
overcharge_display: overchargeDisplay,
|
|
4220
|
+
display
|
|
4221
|
+
});
|
|
4222
|
+
}
|
|
4223
|
+
return reports;
|
|
4224
|
+
}
|
|
4225
|
+
function mandatePaymentSummary(job, messages) {
|
|
4226
|
+
const payments = mandatePaymentReports(job, messages);
|
|
4227
|
+
if (!payments.length) return {};
|
|
4228
|
+
const violated = [...new Set(payments.flatMap((payment) => payment.violated_limits))];
|
|
4229
|
+
return { mandate_payments: payments, ...violated.length ? {
|
|
4230
|
+
overcharged: true,
|
|
4231
|
+
violated_limits: violated,
|
|
4232
|
+
display: [...new Set(payments.map((payment) => payment.overcharge_display).filter(Boolean))].join(" ")
|
|
4233
|
+
} : {} };
|
|
4234
|
+
}
|
|
4235
|
+
function recordMandatePayments(jobId, history) {
|
|
4236
|
+
if (!loadJob(jobId)?.mandate || !history.some(mandateCredit)) return;
|
|
4237
|
+
mutateCreditPayment(jobId, (job) => {
|
|
4238
|
+
for (const message of history) {
|
|
4239
|
+
const credit = mandateCredit(message);
|
|
4240
|
+
if (!credit) continue;
|
|
4241
|
+
if (job.pendingCreditPayment?.authorization.request_seq === credit.request_seq)
|
|
4242
|
+
delete job.pendingCreditPayment;
|
|
4243
|
+
const booked2 = job.mandatePaymentSeqs?.includes(message.seq) === true;
|
|
4244
|
+
const ask = history.find((entry) => entry.seq === credit.request_seq && entry.type === "payment-request");
|
|
4245
|
+
const msats = ask?.type === "payment-request" ? ask.content.amount_msats : 0;
|
|
4246
|
+
const valuations = job.mandatePaymentMsats ??= {};
|
|
4247
|
+
const previous = valuations[message.seq] ?? 0;
|
|
4248
|
+
if (!booked2 || previous === 0 && msats > 0) {
|
|
4249
|
+
valuations[message.seq] = msats;
|
|
4250
|
+
job.totalPaidMsats = (job.totalPaidMsats ?? 0) + msats - previous;
|
|
4251
|
+
if (credit.currency === "usd") job.paidUsdMsats = (job.paidUsdMsats ?? 0) + msats - previous;
|
|
4252
|
+
}
|
|
4253
|
+
if (!booked2) {
|
|
4254
|
+
(job.mandatePaymentSeqs ??= []).push(message.seq);
|
|
4255
|
+
job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
|
|
4256
|
+
if (credit.currency === "usd") job.paidUsdMicro = (job.paidUsdMicro ?? 0) + credit.amount_micro;
|
|
4257
|
+
(job.paymentApprovals ??= []).push({ requestSeq: credit.request_seq, approval: "auto" });
|
|
4258
|
+
}
|
|
4259
|
+
}
|
|
4260
|
+
}, true);
|
|
4261
|
+
}
|
|
4262
|
+
function storedMandateSummary(jobId) {
|
|
4263
|
+
return mandatePaymentSummary(loadJob(jobId), loadMessages(jobId));
|
|
4264
|
+
}
|
|
4265
|
+
|
|
3939
4266
|
// src/lib/wallet-agent/journal-file.ts
|
|
3940
4267
|
var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
|
|
3941
4268
|
import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "fs";
|
|
@@ -4033,6 +4360,28 @@ function reservedForMarker(builderHandle) {
|
|
|
4033
4360
|
return `${BUILDER_RESERVE_PREFIX}${builderHandle}`;
|
|
4034
4361
|
}
|
|
4035
4362
|
|
|
4363
|
+
// src/lib/mint-fee.ts
|
|
4364
|
+
function submissionSwapFeeSats(submission) {
|
|
4365
|
+
const fee = submission.swap_fee_sats;
|
|
4366
|
+
return Number.isSafeInteger(fee) && fee > 0 ? fee : 0;
|
|
4367
|
+
}
|
|
4368
|
+
var MINT_FEE_EXPLAINER = "A mint fee is a small charge the mint that holds your ecash takes for each coin it handles.";
|
|
4369
|
+
function label(sats) {
|
|
4370
|
+
return formatAmountBestEffort(sats * 1e3, { anchor: false });
|
|
4371
|
+
}
|
|
4372
|
+
function describeCashuPayment(paidSats, feeSats) {
|
|
4373
|
+
if (feeSats <= 0) return "";
|
|
4374
|
+
return `Paid ${label(paidSats)} to the provider plus ${label(feeSats)} mint fee; ${label(paidSats + feeSats)} left your wallet. ${MINT_FEE_EXPLAINER}`;
|
|
4375
|
+
}
|
|
4376
|
+
function cashuPaymentFeeFields(paidSats, feeSats) {
|
|
4377
|
+
const display = describeCashuPayment(paidSats, feeSats);
|
|
4378
|
+
return {
|
|
4379
|
+
swap_fee_sats: feeSats,
|
|
4380
|
+
wallet_debit_sats: paidSats + feeSats,
|
|
4381
|
+
...display ? { fee_display: display } : {}
|
|
4382
|
+
};
|
|
4383
|
+
}
|
|
4384
|
+
|
|
4036
4385
|
// src/lib/wallet-agent/inflight.ts
|
|
4037
4386
|
var DEFAULT_INFLIGHT_PROOF_TIMEOUT_SEC = 60;
|
|
4038
4387
|
var INFLIGHT_TIMEOUT_ENV = "DVM_INFLIGHT_PROOF_TIMEOUT_SEC";
|
|
@@ -4144,6 +4493,9 @@ function formatLocktime(seconds) {
|
|
|
4144
4493
|
}
|
|
4145
4494
|
|
|
4146
4495
|
// src/lib/wallet-agent/spend.ts
|
|
4496
|
+
function sumAmounts(proofs) {
|
|
4497
|
+
return proofs.reduce((sum, proof) => sum + A.from(proof.amount).toNumber(), 0);
|
|
4498
|
+
}
|
|
4147
4499
|
async function prepareAgentSpend(args) {
|
|
4148
4500
|
if (args.maxCashuPrincipalSats !== void 0 && (!Number.isSafeInteger(args.maxCashuPrincipalSats) || args.maxCashuPrincipalSats < 0)) {
|
|
4149
4501
|
return {
|
|
@@ -4300,6 +4652,7 @@ async function prepareAgentSpend(args) {
|
|
|
4300
4652
|
requestId: inner2.requestId,
|
|
4301
4653
|
mint: inner2.mint,
|
|
4302
4654
|
totalSats: inner2.submission.amount_sats,
|
|
4655
|
+
swapFeeSats: 0,
|
|
4303
4656
|
endpoint: args.endpoint,
|
|
4304
4657
|
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
4305
4658
|
fromReserve: true,
|
|
@@ -4314,29 +4667,26 @@ async function prepareAgentSpend(args) {
|
|
|
4314
4667
|
let inner;
|
|
4315
4668
|
let sendProofs = [];
|
|
4316
4669
|
let keepProofs = [];
|
|
4670
|
+
let swapFeeSats = 0;
|
|
4317
4671
|
for (const [index, mint] of lock1.candidateMints.entries()) {
|
|
4318
4672
|
const hasNextCandidate = index < lock1.candidateMints.length - 1;
|
|
4319
4673
|
let candidateWallet;
|
|
4320
4674
|
try {
|
|
4321
4675
|
candidateWallet = await getWalletForMint(mint);
|
|
4322
4676
|
rememberKeysetFees(mint, candidateWallet);
|
|
4323
|
-
} catch
|
|
4324
|
-
attempts.push(
|
|
4677
|
+
} catch {
|
|
4678
|
+
attempts.push(spendMintAttempt(mint, "unreachable"));
|
|
4325
4679
|
continue;
|
|
4326
4680
|
}
|
|
4327
4681
|
let reserveSats;
|
|
4328
4682
|
try {
|
|
4329
4683
|
reserveSats = swapSendReserve(candidateWallet, args.amountSats);
|
|
4330
|
-
} catch
|
|
4331
|
-
attempts.push(
|
|
4684
|
+
} catch {
|
|
4685
|
+
attempts.push(spendMintAttempt(mint, "keys_unavailable"));
|
|
4332
4686
|
continue;
|
|
4333
4687
|
}
|
|
4334
4688
|
if (!swapEnabled(candidateWallet)) {
|
|
4335
|
-
attempts.push(
|
|
4336
|
-
mint,
|
|
4337
|
-
reason: "swap_disabled",
|
|
4338
|
-
message: "Mint advertises swaps switched off (NUT-3 disabled)."
|
|
4339
|
-
});
|
|
4689
|
+
attempts.push(spendMintAttempt(mint, "swap_disabled"));
|
|
4340
4690
|
continue;
|
|
4341
4691
|
}
|
|
4342
4692
|
const lock2 = await withWalletLock(() => {
|
|
@@ -4370,7 +4720,7 @@ async function prepareAgentSpend(args) {
|
|
|
4370
4720
|
return {
|
|
4371
4721
|
error: {
|
|
4372
4722
|
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.`,
|
|
4723
|
+
message: `Cashu fees at ${spendDiagnosticMint(mint)} would be ${selectedFeeSats} sats, over the ${args.maxCashuFeeSats}-sat --max-cashu-fee-sats limit.`,
|
|
4374
4724
|
hint: "Raise --max-cashu-fee-sats only after approval, or fund an accepted mint with a lower swap fee."
|
|
4375
4725
|
}
|
|
4376
4726
|
};
|
|
@@ -4419,12 +4769,12 @@ async function prepareAgentSpend(args) {
|
|
|
4419
4769
|
if (lock2.error.code === "no_agent_wallet") return lock2;
|
|
4420
4770
|
if (lock2.error.code === "cashu_fee_cap_exceeded") {
|
|
4421
4771
|
lastFeeCapError = lock2.error;
|
|
4422
|
-
attempts.push(
|
|
4772
|
+
attempts.push(spendMintAttempt(mint, "fee_cap_exceeded", lock2.error.message));
|
|
4423
4773
|
continue;
|
|
4424
4774
|
}
|
|
4425
4775
|
const selectError = lock2.error;
|
|
4426
4776
|
lastSelectError = selectError;
|
|
4427
|
-
attempts.push(
|
|
4777
|
+
attempts.push(spendMintAttempt(mint, selectError.code, selectError.message));
|
|
4428
4778
|
continue;
|
|
4429
4779
|
}
|
|
4430
4780
|
const swapBuilder = candidateWallet.ops.send(lock2.submission.amount_sats, toCashuProofs(lock2.selectedProofs)).asP2PK({
|
|
@@ -4434,8 +4784,8 @@ async function prepareAgentSpend(args) {
|
|
|
4434
4784
|
let preview;
|
|
4435
4785
|
try {
|
|
4436
4786
|
preview = await swapBuilder.prepare();
|
|
4437
|
-
} catch
|
|
4438
|
-
attempts.push(
|
|
4787
|
+
} catch {
|
|
4788
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected"));
|
|
4439
4789
|
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4440
4790
|
if (hasNextCandidate) continue;
|
|
4441
4791
|
break;
|
|
@@ -4479,14 +4829,19 @@ async function prepareAgentSpend(args) {
|
|
|
4479
4829
|
inner = { ...lock2, submission: preparedSubmission };
|
|
4480
4830
|
sendProofs = result.send;
|
|
4481
4831
|
keepProofs = result.keep;
|
|
4832
|
+
swapFeeSats = Math.max(
|
|
4833
|
+
0,
|
|
4834
|
+
sumAmounts(preview.inputs) - sumAmounts(keepProofs) - lock2.submission.amount_sats
|
|
4835
|
+
);
|
|
4482
4836
|
break;
|
|
4483
4837
|
} catch (err) {
|
|
4484
|
-
attempts.push({ mint, reason: "swap_rejected", message: errorText(err) });
|
|
4485
4838
|
if (err instanceof te) {
|
|
4839
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected"));
|
|
4486
4840
|
await rollbackAttempt(requestId, lock2.selectedKeys);
|
|
4487
4841
|
if (hasNextCandidate) continue;
|
|
4488
4842
|
break;
|
|
4489
4843
|
}
|
|
4844
|
+
attempts.push(spendMintAttempt(mint, "swap_rejected", "Mint swap outcome is unknown; recovery is required."));
|
|
4490
4845
|
inputsLeftInFlight = true;
|
|
4491
4846
|
break;
|
|
4492
4847
|
}
|
|
@@ -4512,6 +4867,7 @@ async function prepareAgentSpend(args) {
|
|
|
4512
4867
|
...s,
|
|
4513
4868
|
output_proofs: agentOutputs,
|
|
4514
4869
|
swapping: void 0,
|
|
4870
|
+
swap_fee_sats: swapFeeSats,
|
|
4515
4871
|
cashu_token: cashuToken,
|
|
4516
4872
|
...boundContext ? { context: boundContext } : {},
|
|
4517
4873
|
// What a later reclaim needs. Only the swap path
|
|
@@ -4533,32 +4889,36 @@ async function prepareAgentSpend(args) {
|
|
|
4533
4889
|
requestId: inner.requestId,
|
|
4534
4890
|
mint: inner.mint,
|
|
4535
4891
|
totalSats: inner.submission.amount_sats,
|
|
4892
|
+
swapFeeSats,
|
|
4536
4893
|
endpoint: args.endpoint,
|
|
4537
4894
|
intendedLockPubkey: args.cashuP2pk.lock_pubkey,
|
|
4538
4895
|
...attempts.length > 0 ? { attempts: successfulSpendAttempts(attempts) } : {},
|
|
4539
4896
|
...boundContext?.binding_fingerprint ? { submissionBindingFingerprint: boundContext.binding_fingerprint } : {}
|
|
4540
4897
|
};
|
|
4541
4898
|
}
|
|
4899
|
+
var SPEND_ATTEMPT_MESSAGES = {
|
|
4900
|
+
unreachable: "Mint could not be loaded.",
|
|
4901
|
+
keys_unavailable: "Mint did not provide an active keyset.",
|
|
4902
|
+
swap_disabled: "Mint advertises swaps switched off (NUT-3 disabled).",
|
|
4903
|
+
fee_cap_exceeded: "Mint swap fee exceeds the approved limit.",
|
|
4904
|
+
insufficient_balance: "Mint balance cannot cover the price and swap fee.",
|
|
4905
|
+
no_eligible_mint: "Mint no longer has eligible proofs for this payment.",
|
|
4906
|
+
swap_rejected: "Mint swap could not be prepared or was definitely refused."
|
|
4907
|
+
};
|
|
4908
|
+
function spendDiagnosticMint(mint) {
|
|
4909
|
+
try {
|
|
4910
|
+
const url = new URL(mint);
|
|
4911
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return "[invalid mint URL]";
|
|
4912
|
+
return redactUrl(mint).replace(/\/$/u, "").slice(0, 2048);
|
|
4913
|
+
} catch {
|
|
4914
|
+
return "[invalid mint URL]";
|
|
4915
|
+
}
|
|
4916
|
+
}
|
|
4917
|
+
function spendMintAttempt(mint, reason, message = SPEND_ATTEMPT_MESSAGES[reason]) {
|
|
4918
|
+
return { mint: spendDiagnosticMint(mint), reason, message };
|
|
4919
|
+
}
|
|
4542
4920
|
function successfulSpendAttempts(attempts) {
|
|
4543
|
-
|
|
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
|
-
});
|
|
4921
|
+
return attempts.map((attempt) => ({ ...attempt, message: SPEND_ATTEMPT_MESSAGES[attempt.reason] }));
|
|
4562
4922
|
}
|
|
4563
4923
|
function principalCapFailure(principalSats, maxCashuPrincipalSats) {
|
|
4564
4924
|
return {
|
|
@@ -4639,6 +4999,7 @@ async function commitHeldSubmission(requestId, now = Date.now) {
|
|
|
4639
4999
|
dvm_endpoint: submission.endpoint,
|
|
4640
5000
|
mint: submission.mint,
|
|
4641
5001
|
amount_sats: submission.amount_sats,
|
|
5002
|
+
...submissionSwapFeeSats(submission) > 0 ? { fee_sats: submissionSwapFeeSats(submission) } : {},
|
|
4642
5003
|
signed_at_ms: now()
|
|
4643
5004
|
}].slice(-RECENT_SPENDS_CAP)
|
|
4644
5005
|
});
|
|
@@ -4754,7 +5115,7 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
|
|
|
4754
5115
|
if (attempts.length === 1) return { ...lastSelectError, attempts };
|
|
4755
5116
|
return {
|
|
4756
5117
|
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)}
|
|
5118
|
+
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
5119
|
hint: lastSelectError.hint,
|
|
4759
5120
|
attempts
|
|
4760
5121
|
};
|
|
@@ -4765,14 +5126,14 @@ function exhaustedError(attempts, lastSelectError, lastFeeCapError, inputsLeftIn
|
|
|
4765
5126
|
if (attempts.length === 1) return { ...lastFeeCapError, attempts };
|
|
4766
5127
|
return {
|
|
4767
5128
|
...lastFeeCapError,
|
|
4768
|
-
message: `Every accepted mint that can cover this payment exceeds --max-cashu-fee-sats: ${describeAttempts(attempts)}
|
|
5129
|
+
message: boundedSpendMessage(`Every accepted mint that can cover this payment exceeds --max-cashu-fee-sats: ${describeAttempts(attempts)}.`),
|
|
4769
5130
|
attempts
|
|
4770
5131
|
};
|
|
4771
5132
|
}
|
|
4772
5133
|
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
5134
|
return {
|
|
4774
5135
|
code: "swap_failed",
|
|
4775
|
-
message,
|
|
5136
|
+
message: boundedSpendMessage(message),
|
|
4776
5137
|
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
5138
|
attempts
|
|
4778
5139
|
};
|
|
@@ -4783,6 +5144,9 @@ function isSelectionReason(reason) {
|
|
|
4783
5144
|
function describeAttempts(attempts) {
|
|
4784
5145
|
return attempts.map((a) => `${a.mint} \u2014 ${a.reason} (${a.message})`).join("; ");
|
|
4785
5146
|
}
|
|
5147
|
+
function boundedSpendMessage(message) {
|
|
5148
|
+
return message.length <= 4096 ? message : `${message.slice(0, 4095)}\u2026`;
|
|
5149
|
+
}
|
|
4786
5150
|
function swapEnabled(cashuWallet) {
|
|
4787
5151
|
const loose = cashuWallet;
|
|
4788
5152
|
let nuts;
|
|
@@ -4795,9 +5159,6 @@ function swapEnabled(cashuWallet) {
|
|
|
4795
5159
|
if (typeof nuts !== "object" || nuts === null) return true;
|
|
4796
5160
|
return canSwap(nuts);
|
|
4797
5161
|
}
|
|
4798
|
-
function errorText(err) {
|
|
4799
|
-
return err instanceof Error ? err.message : String(err);
|
|
4800
|
-
}
|
|
4801
5162
|
function selectReserveProofs(args) {
|
|
4802
5163
|
const marker = reservedForMarker(args.builderHandle);
|
|
4803
5164
|
const candidates = args.proofs.filter(
|
|
@@ -5010,6 +5371,8 @@ function loadAnsweredYieldSeqs(jobId) {
|
|
|
5010
5371
|
const answered = answeredYieldSeqs(loadMessages(jobId));
|
|
5011
5372
|
const job = loadJob(jobId);
|
|
5012
5373
|
for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
|
|
5374
|
+
for (const landing of Object.values(job?.paymentCreditLandings ?? {}))
|
|
5375
|
+
if (landing.ask_answered && landing.request_seq !== void 0) answered.add(landing.request_seq);
|
|
5013
5376
|
for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
|
|
5014
5377
|
for (const seq of declinedAskSeqs(jobId)) answered.add(seq);
|
|
5015
5378
|
return answered;
|
|
@@ -5061,6 +5424,14 @@ async function reconcilePaymentRequestHistory(jobId, requestSeq, history, status
|
|
|
5061
5424
|
async function settleRecordedPayments(jobId) {
|
|
5062
5425
|
await applySubmissionVerdicts().catch(() => void 0);
|
|
5063
5426
|
const job = loadJob(jobId);
|
|
5427
|
+
const recorded = job?.mandate || job?.pendingCreditPayment ? loadMessages(jobId) : [];
|
|
5428
|
+
if (job?.mandate) recordMandatePayments(jobId, recorded);
|
|
5429
|
+
const pending = loadJob(jobId)?.pendingCreditPayment;
|
|
5430
|
+
if (pending && recorded.some((message) => {
|
|
5431
|
+
const credit = message.type === "payment" && message.from === "requester" ? message.content.credit : void 0;
|
|
5432
|
+
const expected = pending.authorization;
|
|
5433
|
+
return credit && credit.payment_id === expected.payment_id && credit.request_seq === expected.request_seq && credit.credit_id === expected.credit_id && credit.draw_id === expected.draw_id && credit.amount_micro === expected.amount_micro && credit.currency === expected.currency;
|
|
5434
|
+
})) bookCreditPayment(jobId, pending);
|
|
5064
5435
|
const held = /* @__PURE__ */ new Set([
|
|
5065
5436
|
...job?.inFlightPaymentRequestSeqs ?? [],
|
|
5066
5437
|
...Object.keys(job?.unconfirmedPaymentSubmissions ?? {}).map(Number)
|
|
@@ -5191,8 +5562,8 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
|
|
|
5191
5562
|
case "payment-request": {
|
|
5192
5563
|
const c = msg.content;
|
|
5193
5564
|
const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
|
|
5194
|
-
const
|
|
5195
|
-
const priceGuidance =
|
|
5565
|
+
const safeCurrency2 = !c.fiat_amount || c.fiat_amount.amount <= 0 || c.fiat_amount.currency.length === 3 && /^[A-Z]{3}$/i.test(c.fiat_amount.currency);
|
|
5566
|
+
const priceGuidance = safeCurrency2 ? display : "see the provider price in next_action.fiat_amount";
|
|
5196
5567
|
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
|
|
5197
5568
|
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
5198
5569
|
const policy = context?.policy;
|
|
@@ -5366,12 +5737,12 @@ async function stablecoinRemaining(rail) {
|
|
|
5366
5737
|
const balance = await Promise.race([
|
|
5367
5738
|
(async () => {
|
|
5368
5739
|
if (rail === "x402") {
|
|
5369
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
5740
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-CZV4TOJ3.js");
|
|
5370
5741
|
const wallet = loadX402Wallet2();
|
|
5371
5742
|
if (!wallet) return;
|
|
5372
5743
|
return (await getX402Balance(await ensureAddress(wallet))).usdc;
|
|
5373
5744
|
}
|
|
5374
|
-
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-
|
|
5745
|
+
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-D424H37T.js");
|
|
5375
5746
|
const account = await connectedTempoAccount2();
|
|
5376
5747
|
if (account) return (await getTempoUsdcBalance(account)).usdc;
|
|
5377
5748
|
})(),
|
|
@@ -5413,10 +5784,12 @@ function pieceSettlement(receipt, context = {}) {
|
|
|
5413
5784
|
);
|
|
5414
5785
|
const basis = lowest?.[0];
|
|
5415
5786
|
const ceiling = lowest?.[1];
|
|
5416
|
-
const
|
|
5417
|
-
const
|
|
5418
|
-
|
|
5419
|
-
|
|
5787
|
+
const mandateCheck = mandatePaymentSummary(job, messages);
|
|
5788
|
+
const overcharged = mandateCheck.overcharged === true || ceiling !== void 0 && settlement.charged > ceiling;
|
|
5789
|
+
const money2 = (micro) => formatMicro(micro, currency);
|
|
5790
|
+
let display = `Charged ${money2(settlement.charged)} of ${money2(settlement.held)} held, ${money2(settlement.released)} released.`;
|
|
5791
|
+
if (mandateCheck.overcharged) display += ` ${mandateCheck.display}`;
|
|
5792
|
+
if (ceiling !== void 0 && settlement.charged > ceiling) display += ` ${overchargeClause(basis, money2(ceiling))}`;
|
|
5420
5793
|
return {
|
|
5421
5794
|
held_micro: settlement.held,
|
|
5422
5795
|
charged_micro: settlement.charged,
|
|
@@ -5424,6 +5797,7 @@ function pieceSettlement(receipt, context = {}) {
|
|
|
5424
5797
|
stopped_micro: stopped,
|
|
5425
5798
|
currency,
|
|
5426
5799
|
...ceiling !== void 0 ? { ceiling_micro: ceiling, ceiling_basis: basis } : {},
|
|
5800
|
+
...mandateCheck.violated_limits ? { violated_limits: mandateCheck.violated_limits } : {},
|
|
5427
5801
|
overcharged,
|
|
5428
5802
|
display
|
|
5429
5803
|
};
|
|
@@ -5464,7 +5838,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5464
5838
|
asks.set(message.seq, message.content);
|
|
5465
5839
|
latestAsk = message.seq;
|
|
5466
5840
|
const declined = message.content.charged_if_declined_micro;
|
|
5467
|
-
if (
|
|
5841
|
+
if (validMicro3(declined) && sameCurrency(message.content.credit?.currency, currency)) {
|
|
5468
5842
|
finished = declined;
|
|
5469
5843
|
afterAsk = 0;
|
|
5470
5844
|
}
|
|
@@ -5472,7 +5846,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5472
5846
|
const credit = message.content.credit;
|
|
5473
5847
|
const ask = asks.get(credit?.request_seq ?? latestAsk ?? -1)?.credit;
|
|
5474
5848
|
const price = credit ? credit : ask;
|
|
5475
|
-
if (!price || !
|
|
5849
|
+
if (!price || !validMicro3(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
|
|
5476
5850
|
paid += price.amount_micro;
|
|
5477
5851
|
afterAsk += price.amount_micro;
|
|
5478
5852
|
}
|
|
@@ -5482,7 +5856,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5482
5856
|
}
|
|
5483
5857
|
function declineCap(job, messages) {
|
|
5484
5858
|
const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
5485
|
-
if (!ask || !
|
|
5859
|
+
if (!ask || !validMicro3(ask.content.charged_if_declined_micro)) return void 0;
|
|
5486
5860
|
const recorded = [
|
|
5487
5861
|
...job.paidPaymentRequestSeqs ?? [],
|
|
5488
5862
|
...job.inFlightPaymentRequestSeqs ?? [],
|
|
@@ -5492,7 +5866,7 @@ function declineCap(job, messages) {
|
|
|
5492
5866
|
const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
|
|
5493
5867
|
if (!paidAsk) return ask.content.charged_if_declined_micro;
|
|
5494
5868
|
const price = ask.content.credit?.amount_micro;
|
|
5495
|
-
return
|
|
5869
|
+
return validMicro3(price) ? ask.content.charged_if_declined_micro + price : void 0;
|
|
5496
5870
|
}
|
|
5497
5871
|
function wholeThroughEnd(messages) {
|
|
5498
5872
|
if (messages.length === 0 || messages[0].seq > 1) return false;
|
|
@@ -5508,6 +5882,8 @@ function settlementCurrency(receipt, job, messages, hint) {
|
|
|
5508
5882
|
candidates.push(hint);
|
|
5509
5883
|
const creditId = receipt.credit?.credit_id;
|
|
5510
5884
|
if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
|
|
5885
|
+
const railUsd = typeof job?.upfrontRailPayment === "object" ? job.upfrontRailPayment?.usdMicro : void 0;
|
|
5886
|
+
if (!job?.upfrontRailConflict && validMicro3(railUsd) && railUsd === receipt.settlement?.held) candidates.push("usd");
|
|
5511
5887
|
const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
|
|
5512
5888
|
return found ? found.toLowerCase() : null;
|
|
5513
5889
|
}
|
|
@@ -5521,13 +5897,13 @@ function safeCredits() {
|
|
|
5521
5897
|
function sameCurrency(a, b) {
|
|
5522
5898
|
return typeof a === "string" && a.toLowerCase() === b;
|
|
5523
5899
|
}
|
|
5524
|
-
function
|
|
5900
|
+
function validMicro3(value) {
|
|
5525
5901
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
5526
5902
|
}
|
|
5527
5903
|
function isSettlement(value) {
|
|
5528
5904
|
if (!value || typeof value !== "object") return false;
|
|
5529
5905
|
const s = value;
|
|
5530
|
-
return
|
|
5906
|
+
return validMicro3(s.held) && validMicro3(s.charged) && validMicro3(s.released) && Array.isArray(s.pieces) && s.pieces.every((piece) => piece && typeof piece === "object" && validMicro3(piece.amount) && validMicro3(piece.charged) && typeof piece.state === "string");
|
|
5531
5907
|
}
|
|
5532
5908
|
|
|
5533
5909
|
// src/lib/job-settlement.ts
|
|
@@ -5565,6 +5941,7 @@ function receiptSettlement(receipt, verification, rate, context) {
|
|
|
5565
5941
|
currency: pieces.currency,
|
|
5566
5942
|
...pieces.ceiling_micro !== void 0 ? { ceiling_micro: pieces.ceiling_micro, ceiling_basis: pieces.ceiling_basis } : {},
|
|
5567
5943
|
overcharged: pieces.overcharged,
|
|
5944
|
+
...pieces.violated_limits ? { violated_limits: pieces.violated_limits } : {},
|
|
5568
5945
|
display: pieces.display
|
|
5569
5946
|
};
|
|
5570
5947
|
}
|
|
@@ -5916,7 +6293,12 @@ function captureJobReceipt(jobId, receipt, parseError) {
|
|
|
5916
6293
|
}
|
|
5917
6294
|
function warnPieceOvercharge(jobId, receipt, job) {
|
|
5918
6295
|
const pieces = pieceSettlement(receipt, { job, messages: loadMessages(jobId) });
|
|
5919
|
-
if (!pieces?.overcharged
|
|
6296
|
+
if (!pieces?.overcharged) return;
|
|
6297
|
+
if (pieces.violated_limits?.length) {
|
|
6298
|
+
info(`Warning: ${pieces.display} Keep the receipt for job ${jobId} as evidence.`);
|
|
6299
|
+
return;
|
|
6300
|
+
}
|
|
6301
|
+
if (pieces.ceiling_micro === void 0) return;
|
|
5920
6302
|
const ceiling = formatMicro(pieces.ceiling_micro, pieces.currency);
|
|
5921
6303
|
const basis = pieces.ceiling_basis === "payments" ? `the ${ceiling} of finished pieces this CLI paid for` : pieces.ceiling_basis === "declined_ask" ? `the ${ceiling} the job's last ask said stopping would cost` : `the ${ceiling} its own pieces add up to`;
|
|
5922
6304
|
info(
|
|
@@ -6112,6 +6494,12 @@ var TEMPO_AMOUNT_REFUSALS = /* @__PURE__ */ new Set(["tempo_amount_exceeds_limit
|
|
|
6112
6494
|
var SETTLEMENT_POLLS = 3;
|
|
6113
6495
|
var SETTLEMENT_POLL_DELAY_MS = 1500;
|
|
6114
6496
|
async function fundCredit(args) {
|
|
6497
|
+
if (args.invoice) {
|
|
6498
|
+
if (args.rail && args.rail !== "lightning" || args.fundingMode) {
|
|
6499
|
+
throw new DvmError("invalid_argument", "--invoice only applies to Lightning credit funding.");
|
|
6500
|
+
}
|
|
6501
|
+
args = { ...args, rail: "lightning" };
|
|
6502
|
+
}
|
|
6115
6503
|
return withFundingMode(await runCreditFunding(args));
|
|
6116
6504
|
}
|
|
6117
6505
|
async function runCreditFunding(args) {
|
|
@@ -6154,7 +6542,7 @@ async function runCreditFunding(args) {
|
|
|
6154
6542
|
}
|
|
6155
6543
|
const pending = loadPendingFunding(args.ref.endpoint, args.signing.pubkey, args.creditId);
|
|
6156
6544
|
if (pending) {
|
|
6157
|
-
if (!pendingFundingExpired(pending)) {
|
|
6545
|
+
if (pending.rail === "lightning" || !pendingFundingExpired(pending)) {
|
|
6158
6546
|
const resumed = argsFromPending(args, pending);
|
|
6159
6547
|
return pending.rail === "tempo" ? fundOverMpp(resumed, pending.fundId, pending) : fundOverLightning(resumed, pending.fundId, pending);
|
|
6160
6548
|
}
|
|
@@ -6234,17 +6622,18 @@ async function runCreditFunding(args) {
|
|
|
6234
6622
|
};
|
|
6235
6623
|
}
|
|
6236
6624
|
async function pollPendingCreditFundings(args) {
|
|
6625
|
+
const refused2 = [];
|
|
6237
6626
|
const pending = listPendingFundings({
|
|
6238
6627
|
endpoint: args.ref.endpoint,
|
|
6239
6628
|
callerPubkey: args.signing.pubkey
|
|
6240
6629
|
});
|
|
6241
6630
|
for (const funding of pending) {
|
|
6242
|
-
if (pendingFundingExpired(funding)) {
|
|
6243
|
-
clearPending(funding);
|
|
6244
|
-
continue;
|
|
6245
|
-
}
|
|
6246
6631
|
const fundArgs = argsFromPending(args, funding);
|
|
6247
6632
|
if (funding.rail === "tempo") {
|
|
6633
|
+
if (pendingFundingExpired(funding)) {
|
|
6634
|
+
clearPending(funding);
|
|
6635
|
+
continue;
|
|
6636
|
+
}
|
|
6248
6637
|
await fundOverMpp(fundArgs, funding.fundId, funding).catch(() => void 0);
|
|
6249
6638
|
continue;
|
|
6250
6639
|
}
|
|
@@ -6259,11 +6648,19 @@ async function pollPendingCreditFundings(args) {
|
|
|
6259
6648
|
} catch (err) {
|
|
6260
6649
|
const offer = lightningOffer(err);
|
|
6261
6650
|
if (offer) {
|
|
6262
|
-
|
|
6263
|
-
|
|
6264
|
-
if (
|
|
6265
|
-
|
|
6266
|
-
|
|
6651
|
+
if (isInvoiceFunding(funding) && funding.bolt11 && funding.bolt11 !== offer.invoice) continue;
|
|
6652
|
+
const verdict = await replacementInvoiceVerdict(funding, offer, void 0);
|
|
6653
|
+
if (verdict === "refuse") continue;
|
|
6654
|
+
recordPendingFunding(
|
|
6655
|
+
verdict === "paid" ? withReconciledPayment(funding) : withLightningOffer(funding, offer)
|
|
6656
|
+
);
|
|
6657
|
+
} else if (lightningFundingTerminal(err, funding)) {
|
|
6658
|
+
const spend = lightningSpendFromPending(funding);
|
|
6659
|
+
if (spend) {
|
|
6660
|
+
refused2.push(paidButRefused(fundArgs, base, spend, lightningSpendDisplay(spend), err));
|
|
6661
|
+
} else {
|
|
6662
|
+
clearPending(funding);
|
|
6663
|
+
}
|
|
6267
6664
|
}
|
|
6268
6665
|
}
|
|
6269
6666
|
}
|
|
@@ -6309,7 +6706,7 @@ async function pollPendingCreditFundings(args) {
|
|
|
6309
6706
|
}
|
|
6310
6707
|
}
|
|
6311
6708
|
const exactWallet = loadX402Wallet();
|
|
6312
|
-
if (!exactWallet) return;
|
|
6709
|
+
if (!exactWallet) return refused2;
|
|
6313
6710
|
for (const funding of listResumableX402ExactFundings({
|
|
6314
6711
|
endpoint: args.ref.endpoint,
|
|
6315
6712
|
callerPubkey: args.signing.pubkey
|
|
@@ -6329,6 +6726,7 @@ async function pollPendingCreditFundings(args) {
|
|
|
6329
6726
|
funding
|
|
6330
6727
|
).catch(() => void 0);
|
|
6331
6728
|
}
|
|
6729
|
+
return refused2;
|
|
6332
6730
|
}
|
|
6333
6731
|
function availableRails(args) {
|
|
6334
6732
|
const advertised = args.menu?.funding;
|
|
@@ -6338,8 +6736,8 @@ function availableRails(args) {
|
|
|
6338
6736
|
if (offers("cashu") && cashu && cashu.lock_pubkeys.length > 0 && cashu.mints.length > 0) {
|
|
6339
6737
|
rails.push("cashu");
|
|
6340
6738
|
}
|
|
6341
|
-
const float = args.float === void 0 ? loadFloat() : args.float;
|
|
6342
|
-
if (offers("lightning") && float) rails.push("lightning");
|
|
6739
|
+
const float = args.invoice ? null : args.float === void 0 ? loadFloat() : args.float;
|
|
6740
|
+
if (offers("lightning") && (float || args.invoice)) rails.push("lightning");
|
|
6343
6741
|
const x402Wallet = offers("x402") ? loadX402Wallet() : null;
|
|
6344
6742
|
if (x402Wallet && offersX402CreditFunding(args.menu, x402Wallet.network)) rails.push("x402");
|
|
6345
6743
|
if (offers("tempo") && offersTempoCreditFunding(args.menu) && hasConnectedTempoWallet(args)) {
|
|
@@ -7071,6 +7469,7 @@ async function fundOverX402(args, fundId, resumed, corrected = false, locked = f
|
|
|
7071
7469
|
await processX402BatchResponseForWallet({
|
|
7072
7470
|
wallet,
|
|
7073
7471
|
depositMicro: pending.targetMicro,
|
|
7472
|
+
paymentHeader: pending.paymentHeader,
|
|
7074
7473
|
paymentResponse: result.x402PaymentResponse,
|
|
7075
7474
|
channelId: pending.channelId
|
|
7076
7475
|
});
|
|
@@ -7365,6 +7764,7 @@ async function fundOverCashu(args, fundId) {
|
|
|
7365
7764
|
dvm_endpoint: args.ref.endpoint,
|
|
7366
7765
|
mint: prepared.mint,
|
|
7367
7766
|
amount_sats: prepared.totalSats,
|
|
7767
|
+
...prepared.swapFeeSats > 0 ? { fee_sats: prepared.swapFeeSats } : {},
|
|
7368
7768
|
signed_at_ms: Date.now()
|
|
7369
7769
|
}
|
|
7370
7770
|
});
|
|
@@ -8096,27 +8496,29 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8096
8496
|
};
|
|
8097
8497
|
}
|
|
8098
8498
|
}
|
|
8099
|
-
const float2 = args.float === void 0 ? loadFloat() : args.float;
|
|
8100
|
-
if (!float2) {
|
|
8499
|
+
const float2 = args.invoice ? null : args.float === void 0 ? loadFloat() : args.float;
|
|
8500
|
+
if (!float2 && !args.invoice) {
|
|
8101
8501
|
return {
|
|
8102
8502
|
...base,
|
|
8103
8503
|
status: "unavailable",
|
|
8104
8504
|
display: "No Lightning wallet is connected, so the credit can't be funded that way.",
|
|
8105
|
-
|
|
8505
|
+
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
8506
|
};
|
|
8107
8507
|
}
|
|
8108
|
-
|
|
8109
|
-
|
|
8110
|
-
|
|
8111
|
-
|
|
8112
|
-
|
|
8113
|
-
|
|
8114
|
-
|
|
8115
|
-
|
|
8116
|
-
|
|
8117
|
-
|
|
8118
|
-
|
|
8119
|
-
|
|
8508
|
+
if (!args.invoice) {
|
|
8509
|
+
const rate = (await tryResolveBtcUsdRate())?.rate ?? 0;
|
|
8510
|
+
if (rate <= 0) {
|
|
8511
|
+
return {
|
|
8512
|
+
...base,
|
|
8513
|
+
status: "unavailable",
|
|
8514
|
+
display: "The bitcoin exchange rate couldn't be read, so the funding amount can't be sized."
|
|
8515
|
+
};
|
|
8516
|
+
}
|
|
8517
|
+
try {
|
|
8518
|
+
await assertFloatBudget(microToSats(args.amountMicro, rate) * 1e3);
|
|
8519
|
+
} catch (err) {
|
|
8520
|
+
return budgetRefusal(base, err);
|
|
8521
|
+
}
|
|
8120
8522
|
}
|
|
8121
8523
|
pending = {
|
|
8122
8524
|
endpoint: args.ref.endpoint,
|
|
@@ -8127,36 +8529,68 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8127
8529
|
rail: "lightning",
|
|
8128
8530
|
targetMicro: args.targetMicro ?? args.amountMicro,
|
|
8129
8531
|
...args.menu ? { menu: args.menu } : {},
|
|
8130
|
-
requestedAt: Date.now()
|
|
8532
|
+
requestedAt: Date.now(),
|
|
8533
|
+
...args.invoice ? { lightningPaymentMode: "invoice" } : {}
|
|
8131
8534
|
};
|
|
8132
8535
|
recordPendingFunding(pending);
|
|
8133
8536
|
}
|
|
8134
8537
|
const creditBody = lightningCreditBody(pending);
|
|
8538
|
+
if (args.invoice || isInvoiceFunding(pending)) {
|
|
8539
|
+
const manual = { ...pending, lightningPaymentMode: "invoice" };
|
|
8540
|
+
recordPendingFunding(manual);
|
|
8541
|
+
const outcome = await fundOverInvoice(args, manual, {
|
|
8542
|
+
post: () => postCredit(args, creditBody),
|
|
8543
|
+
settled: (result, entry) => settleAndClear(args, base, result, lightningSpendFromPending(entry), entry),
|
|
8544
|
+
terminal: lightningFundingTerminal,
|
|
8545
|
+
clear: clearPending
|
|
8546
|
+
});
|
|
8547
|
+
return { ...outcome, ...lightningSpendFromPending(manual) ?? {} };
|
|
8548
|
+
}
|
|
8135
8549
|
let offer;
|
|
8136
8550
|
try {
|
|
8137
8551
|
const replay = await postCredit(args, creditBody);
|
|
8138
8552
|
return settleAndClear(args, base, replay, lightningSpendFromPending(pending), pending);
|
|
8139
8553
|
} catch (err) {
|
|
8140
8554
|
const parsed = lightningOffer(err);
|
|
8555
|
+
const recorded = lightningSpendFromPending(pending);
|
|
8141
8556
|
if (!parsed) {
|
|
8142
|
-
|
|
8557
|
+
const terminal = lightningFundingTerminal(err, pending);
|
|
8558
|
+
if (terminal) clearPending(pending);
|
|
8559
|
+
if (recorded) {
|
|
8560
|
+
return terminal ? paidButRefused(args, base, recorded, lightningSpendDisplay(recorded), err) : (
|
|
8561
|
+
// Inconclusive: the error is surfaced as a failure so the caller retries the same ids.
|
|
8562
|
+
{ ...unresolvedFunding(base, err), ...recorded }
|
|
8563
|
+
);
|
|
8564
|
+
}
|
|
8565
|
+
if (!terminal && pending.bolt11) return unresolvedFunding(base, err);
|
|
8143
8566
|
return lightningRefusal(base, err);
|
|
8144
8567
|
}
|
|
8145
8568
|
offer = parsed;
|
|
8569
|
+
if (recorded) {
|
|
8570
|
+
recordPendingFunding(withLightningOffer(pending, offer));
|
|
8571
|
+
return paidAwaitingSettlement(base, recorded, lightningSpendDisplay(recorded));
|
|
8572
|
+
}
|
|
8573
|
+
const verdict = await replacementInvoiceVerdict(pending, offer, args.float);
|
|
8574
|
+
if (verdict === "refuse") return replacementInvoiceRefusal(base, pending);
|
|
8575
|
+
if (verdict === "paid") {
|
|
8576
|
+
pending = withReconciledPayment(pending);
|
|
8577
|
+
recordPendingFunding(pending);
|
|
8578
|
+
const reconciled = lightningSpendFromPending(pending);
|
|
8579
|
+
if (reconciled) {
|
|
8580
|
+
return paidAwaitingSettlement(base, reconciled, lightningSpendDisplay(reconciled));
|
|
8581
|
+
}
|
|
8582
|
+
}
|
|
8146
8583
|
pending = withLightningOffer(pending, offer);
|
|
8147
8584
|
recordPendingFunding(pending);
|
|
8148
8585
|
}
|
|
8149
|
-
if (pendingFundingExpired(pending))
|
|
8150
|
-
clearPending(pending);
|
|
8151
|
-
return expiredFunding(base);
|
|
8152
|
-
}
|
|
8586
|
+
if (pendingFundingExpired(pending)) return expiredUnresolvedFunding(base);
|
|
8153
8587
|
const float = args.float === void 0 ? loadFloat() : args.float;
|
|
8154
8588
|
if (!float) {
|
|
8155
8589
|
return {
|
|
8156
8590
|
...base,
|
|
8157
8591
|
status: "unavailable",
|
|
8158
8592
|
display: "The original Lightning invoice is still pending, but no wallet is connected to pay or reconcile it.",
|
|
8159
|
-
hint:
|
|
8593
|
+
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
8594
|
};
|
|
8161
8595
|
}
|
|
8162
8596
|
let payment;
|
|
@@ -8214,32 +8648,15 @@ async function fundOverLightning(args, fundId, resumed) {
|
|
|
8214
8648
|
};
|
|
8215
8649
|
} catch (err) {
|
|
8216
8650
|
if (isPermanentRefusal(err)) {
|
|
8217
|
-
const mapped = err;
|
|
8218
8651
|
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
|
-
};
|
|
8652
|
+
return paidButRefused(args, base, paid, floatPaymentDisplay(payment), err);
|
|
8227
8653
|
}
|
|
8228
8654
|
unconfirmed = err instanceof DvmError && !isSettlementPending(err) ? err : void 0;
|
|
8229
8655
|
if (attempt < SETTLEMENT_POLLS - 1) await sleep(SETTLEMENT_POLL_DELAY_MS);
|
|
8230
8656
|
}
|
|
8231
8657
|
}
|
|
8232
8658
|
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
|
-
};
|
|
8659
|
+
return paidAwaitingSettlement(base, paid, floatPaymentDisplay(payment), unconfirmed);
|
|
8243
8660
|
}
|
|
8244
8661
|
async function postCredit(args, body, payment) {
|
|
8245
8662
|
const transport = args.transport;
|
|
@@ -8423,6 +8840,10 @@ function argsFromPending(args, pending) {
|
|
|
8423
8840
|
...pending.menu ? { menu: pending.menu } : {},
|
|
8424
8841
|
...args.signBody ? { signBody: args.signBody } : {},
|
|
8425
8842
|
..."float" in args ? { float: args.float } : {},
|
|
8843
|
+
...args.invoice ? { invoice: true } : {},
|
|
8844
|
+
...args.invoiceWait !== void 0 ? { invoiceWait: args.invoiceWait } : {},
|
|
8845
|
+
...args.invoiceIdentity ? { invoiceIdentity: args.invoiceIdentity } : {},
|
|
8846
|
+
...args.invoiceProgress ? { invoiceProgress: args.invoiceProgress } : {},
|
|
8426
8847
|
..."tempoAccount" in args ? { tempoAccount: args.tempoAccount } : {},
|
|
8427
8848
|
...args.tempoGetClient ? { tempoGetClient: args.tempoGetClient } : {},
|
|
8428
8849
|
...args.tempoFetch ? { tempoFetch: args.tempoFetch } : {}
|
|
@@ -8528,6 +8949,7 @@ function otherCreditPendingX402(args) {
|
|
|
8528
8949
|
).sort((a, b) => a.requestedAt - b.requestedAt)[0];
|
|
8529
8950
|
}
|
|
8530
8951
|
function withLightningOffer(pending, offer) {
|
|
8952
|
+
if (pending.paymentOutcome !== void 0 && pending.bolt11) return pending;
|
|
8531
8953
|
return {
|
|
8532
8954
|
...pending,
|
|
8533
8955
|
bolt11: offer.invoice,
|
|
@@ -8536,29 +8958,107 @@ function withLightningOffer(pending, offer) {
|
|
|
8536
8958
|
expiresAtMs: offer.expires_at_ms
|
|
8537
8959
|
};
|
|
8538
8960
|
}
|
|
8961
|
+
async function replacementInvoiceVerdict(pending, offer, float) {
|
|
8962
|
+
if (pending.paymentOutcome !== void 0 || !pending.bolt11 || pending.bolt11 === offer.invoice) {
|
|
8963
|
+
return "same";
|
|
8964
|
+
}
|
|
8965
|
+
if (!pending.paymentHash) return "refuse";
|
|
8966
|
+
let wallet;
|
|
8967
|
+
try {
|
|
8968
|
+
wallet = float === void 0 ? loadFloat() : float;
|
|
8969
|
+
} catch {
|
|
8970
|
+
return "refuse";
|
|
8971
|
+
}
|
|
8972
|
+
if (!wallet) return "refuse";
|
|
8973
|
+
const state = await lookupFloatInvoice({ float: wallet, paymentHash: pending.paymentHash });
|
|
8974
|
+
return state === "unknown" ? "refuse" : state;
|
|
8975
|
+
}
|
|
8976
|
+
function withReconciledPayment(pending) {
|
|
8977
|
+
return {
|
|
8978
|
+
...pending,
|
|
8979
|
+
principalMsats: pending.amountMsats ?? 0,
|
|
8980
|
+
routingFeeMsats: null,
|
|
8981
|
+
totalWalletFeeMsats: null,
|
|
8982
|
+
unitemizedWalletFeeMsats: null,
|
|
8983
|
+
walletDebitMsats: null,
|
|
8984
|
+
paymentOutcome: "reconciled"
|
|
8985
|
+
};
|
|
8986
|
+
}
|
|
8987
|
+
function replacementInvoiceRefusal(base, pending) {
|
|
8988
|
+
const error = new DvmError(
|
|
8989
|
+
"lightning_invoice_changed",
|
|
8990
|
+
"The DVM offered a different invoice for a funding whose first invoice may already be paid.",
|
|
8991
|
+
`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.`,
|
|
8992
|
+
{ credit_id: pending.creditId, fund_id: pending.fundId }
|
|
8993
|
+
);
|
|
8994
|
+
return {
|
|
8995
|
+
...base,
|
|
8996
|
+
status: "refused",
|
|
8997
|
+
error,
|
|
8998
|
+
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.`,
|
|
8999
|
+
hint: error.hint
|
|
9000
|
+
};
|
|
9001
|
+
}
|
|
8539
9002
|
function pendingFundingExpired(pending, now = Date.now()) {
|
|
8540
9003
|
return pending.expiresAtMs !== void 0 && pending.expiresAtMs <= now;
|
|
8541
9004
|
}
|
|
8542
9005
|
function clearPending(pending) {
|
|
8543
9006
|
clearPendingFunding(pending.endpoint, pending.callerPubkey, pending.creditId, pending.fundId);
|
|
8544
9007
|
}
|
|
8545
|
-
function
|
|
8546
|
-
|
|
9008
|
+
function lightningFundingTerminal(err, pending) {
|
|
9009
|
+
if (!(err instanceof DvmError)) return false;
|
|
9010
|
+
if (err.code === "lightning_invoice_expired") return true;
|
|
9011
|
+
if (err.code === "lightning_unavailable") {
|
|
9012
|
+
return !pending.bolt11 && pending.paymentOutcome === void 0;
|
|
9013
|
+
}
|
|
9014
|
+
return isPermanentRefusal(err);
|
|
8547
9015
|
}
|
|
8548
|
-
function
|
|
9016
|
+
function expiredUnresolvedFunding(base) {
|
|
8549
9017
|
const error = new DvmError(
|
|
8550
9018
|
"lightning_invoice_expired",
|
|
8551
|
-
"The original Lightning funding invoice expired before
|
|
8552
|
-
"Re-run
|
|
9019
|
+
"The original Lightning funding invoice expired before the DVM confirmed it.",
|
|
9020
|
+
"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
9021
|
);
|
|
8554
9022
|
return {
|
|
8555
9023
|
...base,
|
|
8556
9024
|
status: "refused",
|
|
8557
9025
|
error,
|
|
8558
|
-
display: "The original Lightning invoice expired
|
|
9026
|
+
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
9027
|
hint: error.hint
|
|
8560
9028
|
};
|
|
8561
9029
|
}
|
|
9030
|
+
function unresolvedFunding(base, err) {
|
|
9031
|
+
const error = err instanceof DvmError ? err : new DvmError("provider_error", "Could not confirm the Lightning funding.");
|
|
9032
|
+
return {
|
|
9033
|
+
...base,
|
|
9034
|
+
status: "refused",
|
|
9035
|
+
error,
|
|
9036
|
+
display: `This Lightning funding is unresolved (${error.code}). Its original funding id is saved; payment may already have happened.`,
|
|
9037
|
+
hint: "Re-run this funding or check 'dvm credit balance' to reconcile the saved funding id before paying again."
|
|
9038
|
+
};
|
|
9039
|
+
}
|
|
9040
|
+
function paidButRefused(args, base, spend, spendDisplay, err) {
|
|
9041
|
+
return {
|
|
9042
|
+
...base,
|
|
9043
|
+
...spend,
|
|
9044
|
+
status: "refused",
|
|
9045
|
+
error: err,
|
|
9046
|
+
display: `The Lightning payment went out, but the DVM won't be crediting it (${err.code}). ${err.message} ${spendDisplay}`,
|
|
9047
|
+
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}.`
|
|
9048
|
+
};
|
|
9049
|
+
}
|
|
9050
|
+
function paidAwaitingSettlement(base, spend, spendDisplay, unconfirmed) {
|
|
9051
|
+
return {
|
|
9052
|
+
...base,
|
|
9053
|
+
...spend,
|
|
9054
|
+
status: "settlement_pending",
|
|
9055
|
+
...unconfirmed ? { error: unconfirmed } : {},
|
|
9056
|
+
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}`,
|
|
9057
|
+
// Both verbs poll the durable `(credit_id, fund_id)`: neither can mint a
|
|
9058
|
+
// second invoice while this intent remains in flight.
|
|
9059
|
+
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."
|
|
9060
|
+
};
|
|
9061
|
+
}
|
|
8562
9062
|
function lightningOffer(err) {
|
|
8563
9063
|
if (!isSettlementPending(err)) return void 0;
|
|
8564
9064
|
const offer = err.data?.lightning;
|
|
@@ -8655,7 +9155,8 @@ function forcedRailHint(args, rail) {
|
|
|
8655
9155
|
return `This DVM advertises credit funding over ${advertised.join(", ") || "no rail at all"}, not ${rail}. ${release.text}`;
|
|
8656
9156
|
}
|
|
8657
9157
|
if (rail === "lightning") {
|
|
8658
|
-
const
|
|
9158
|
+
const invoice = creditInvoiceCommand({ endpoint: args.ref.endpoint, amountMicro: args.amountMicro, creditId: args.creditId, identity: args.invoiceIdentity });
|
|
9159
|
+
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
9160
|
return release.instruction ? `${connect}, or ${lowerFirst(release.text)}` : `${connect}. ${release.text}`;
|
|
8660
9161
|
}
|
|
8661
9162
|
if (rail === "x402") {
|
|
@@ -9670,6 +10171,7 @@ export {
|
|
|
9670
10171
|
recordUpfrontCreditPayment,
|
|
9671
10172
|
hasUnknownUpfrontCredit,
|
|
9672
10173
|
recordUpfrontRailPayment,
|
|
10174
|
+
addCashuSwapFee,
|
|
9673
10175
|
hasUnknownUpfrontRail,
|
|
9674
10176
|
updateJob,
|
|
9675
10177
|
updateObservedJob,
|
|
@@ -9679,6 +10181,7 @@ export {
|
|
|
9679
10181
|
loadAllJobs,
|
|
9680
10182
|
addPayment,
|
|
9681
10183
|
recordBudgetRefusal,
|
|
10184
|
+
recordPaymentCreditLanding,
|
|
9682
10185
|
markPaymentRequestInFlight,
|
|
9683
10186
|
clearPaymentRequestInFlight,
|
|
9684
10187
|
markPaymentRequestPaid,
|
|
@@ -9707,9 +10210,19 @@ export {
|
|
|
9707
10210
|
recordSpendOnce,
|
|
9708
10211
|
enforceGlobalBudget,
|
|
9709
10212
|
statusSnapshot,
|
|
10213
|
+
mandateCredit,
|
|
10214
|
+
mandateDrawTotal,
|
|
10215
|
+
mandatePaymentReports,
|
|
10216
|
+
mandatePaymentSummary,
|
|
10217
|
+
recordMandatePayments,
|
|
10218
|
+
storedMandateSummary,
|
|
9710
10219
|
journalFile,
|
|
9711
10220
|
extractBuilderHandle,
|
|
9712
10221
|
reservedForMarker,
|
|
10222
|
+
submissionSwapFeeSats,
|
|
10223
|
+
MINT_FEE_EXPLAINER,
|
|
10224
|
+
describeCashuPayment,
|
|
10225
|
+
cashuPaymentFeeFields,
|
|
9713
10226
|
inFlightTimeoutSeconds,
|
|
9714
10227
|
meltInFlightTimeoutSeconds,
|
|
9715
10228
|
proofKey,
|
|
@@ -9721,6 +10234,7 @@ export {
|
|
|
9721
10234
|
formatLocktime,
|
|
9722
10235
|
prepareAgentSpend,
|
|
9723
10236
|
commitAgentSpend,
|
|
10237
|
+
commitHeldSubmission,
|
|
9724
10238
|
correctPendingFundAmount,
|
|
9725
10239
|
abandonPendingSubmission,
|
|
9726
10240
|
abandonSubmissionInWallet,
|
|
@@ -9753,6 +10267,7 @@ export {
|
|
|
9753
10267
|
paymentCountHint,
|
|
9754
10268
|
overBudgetHint,
|
|
9755
10269
|
buildTempoCredential,
|
|
10270
|
+
cardMinimumMicro,
|
|
9756
10271
|
listPendingCardFundings,
|
|
9757
10272
|
completedCreditHistory,
|
|
9758
10273
|
completedDrainMatches,
|
|
@@ -9762,7 +10277,6 @@ export {
|
|
|
9762
10277
|
formatDurationMs,
|
|
9763
10278
|
walletHistory,
|
|
9764
10279
|
dvmLabelFromEndpoint,
|
|
9765
|
-
CARD_MIN_MICRO,
|
|
9766
10280
|
walletInvoiceFundingAdvice,
|
|
9767
10281
|
floatPaymentJson,
|
|
9768
10282
|
floatPaymentDisplay,
|