@dvmkit/dvm-cli 0.20.0 → 0.22.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-QXXPXQLM.js → chunk-23FGJKIX.js} +2 -2
- package/dist/{chunk-2B2MCZ2I.js → chunk-AFR5KKJX.js} +4 -4
- package/dist/{chunk-DOAMK5C6.js → chunk-AWK22TUP.js} +2 -2
- package/dist/{chunk-4RINUKY4.js → chunk-AWWLO2WW.js} +8330 -27312
- package/dist/{chunk-ZZCYSYXR.js → chunk-EA6RU4OR.js} +10 -10
- package/dist/{chunk-WCX4PNEF.js → chunk-GEG2YAIB.js} +19 -1
- package/dist/{chunk-2YPUKPJN.js → chunk-ITESN5XP.js} +3 -3
- package/dist/chunk-MP63OWTD.js +27343 -0
- package/dist/{chunk-W4ADV3HW.js → chunk-NSHMTEFJ.js} +27 -17
- package/dist/{chunk-4S6TNP4N.js → chunk-WGZ3HBST.js} +388 -92
- package/dist/{chunk-MSQJWCPT.js → chunk-X2CKIG2D.js} +3 -3
- package/dist/{chunk-EEQPFGPM.js → chunk-YSALCR5X.js} +3 -5
- package/dist/{client-FKYQXFBN.js → client-5SB2HSH5.js} +6 -6
- package/dist/dvm.js +5969 -772
- package/dist/{internal-EQJXMIR2.js → internal-EVD5WVAK.js} +5 -5
- package/dist/{lifecycle-3IBVUCTB.js → lifecycle-GR7WGYVQ.js} +6 -6
- package/dist/{payout-reporter-5PH53T44-7IA4NGIN.js → payout-reporter-O4OLJXKQ-7N2HPPPY.js} +2 -2
- package/dist/{pocket-refill-M65PPCN3.js → pocket-refill-TF7M2XCZ.js} +10 -10
- package/dist/{revenue-reporter-4XV3OO5O-RYHS3M34.js → revenue-reporter-RMK4HFEW-7HGJQOXL.js} +2 -2
- package/dist/{tempo-lifecycle-Q3N5GGIQ.js → tempo-lifecycle-7EYW5W5Z.js} +8 -8
- package/dist/{tempo-wallet-AY6R3E4Z.js → tempo-wallet-QOC3BHVE.js} +7 -7
- package/dist/{wallet-J7JCMFZ2.js → wallet-RIHHIQRK.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 +22 -4
- package/skills/dvm/credit.md +2 -0
- package/skills/dvm/wallets.md +3 -1
- package/dist/chunk-DF2OWCRY.js +0 -11127
|
@@ -3,15 +3,15 @@ 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-AFR5KKJX.js";
|
|
7
7
|
import {
|
|
8
8
|
loadX402Wallet,
|
|
9
9
|
x402NetworkLabel
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ITESN5XP.js";
|
|
11
11
|
import {
|
|
12
12
|
isCreditPosture,
|
|
13
13
|
loadConfig
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-YSALCR5X.js";
|
|
15
15
|
import {
|
|
16
16
|
addOutputWarnings,
|
|
17
17
|
costAnchor,
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
resolveBtcUsdRate,
|
|
28
28
|
tryResolveBtcUsdRate,
|
|
29
29
|
tryX402Payment
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-23FGJKIX.js";
|
|
31
31
|
import {
|
|
32
32
|
A,
|
|
33
33
|
BUDGET_FILE,
|
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
STABLECOIN_FUND_RAILS,
|
|
43
43
|
TEMPO_CHARGE_PENDING_STALE_MS,
|
|
44
44
|
TEMPO_SESSION_UPDATED_REASON,
|
|
45
|
+
WALLET_FILE,
|
|
45
46
|
acknowledgeReplayedX402Payment,
|
|
46
47
|
acknowledgeX402ChannelOwner,
|
|
47
48
|
amountBoundsVerdict,
|
|
@@ -134,6 +135,7 @@ import {
|
|
|
134
135
|
recordPendingTempoChargeFunding,
|
|
135
136
|
recordPendingX402ExactFunding,
|
|
136
137
|
recordPendingX402Funding,
|
|
138
|
+
rehydrateOutputData,
|
|
137
139
|
require_proper_lockfile,
|
|
138
140
|
restoreProofsFromOutputs,
|
|
139
141
|
retirePendingX402Funding,
|
|
@@ -185,7 +187,7 @@ import {
|
|
|
185
187
|
x402PendingUnsettled,
|
|
186
188
|
x402RequiredFromError,
|
|
187
189
|
x402VoucherPendingState
|
|
188
|
-
} from "./chunk-
|
|
190
|
+
} from "./chunk-AWWLO2WW.js";
|
|
189
191
|
import {
|
|
190
192
|
Challenge_exports,
|
|
191
193
|
Credential_exports
|
|
@@ -206,7 +208,7 @@ import {
|
|
|
206
208
|
redactUrlsInText,
|
|
207
209
|
usdToMsats,
|
|
208
210
|
x402NetworkToCaip2
|
|
209
|
-
} from "./chunk-
|
|
211
|
+
} from "./chunk-MP63OWTD.js";
|
|
210
212
|
import {
|
|
211
213
|
privateKeyToAccount
|
|
212
214
|
} from "./chunk-EVQERRCP.js";
|
|
@@ -3113,13 +3115,19 @@ function hasUnknownUpfrontRail(job) {
|
|
|
3113
3115
|
function updateJob(id, update) {
|
|
3114
3116
|
mutateJobs((jobs) => {
|
|
3115
3117
|
const idx = jobs.findIndex((j) => j.id === id);
|
|
3116
|
-
if (idx !== -1)
|
|
3118
|
+
if (idx !== -1) {
|
|
3119
|
+
jobs[idx] = { ...jobs[idx], ...update };
|
|
3120
|
+
if (update.status && ["completed", "failed", "cancelled"].includes(update.status)) clearPaymentCreditRefusals(jobs[idx]);
|
|
3121
|
+
}
|
|
3117
3122
|
});
|
|
3118
3123
|
}
|
|
3119
3124
|
function updateObservedJob(id, update) {
|
|
3120
3125
|
mutateJobs((jobs) => {
|
|
3121
3126
|
const idx = jobs.findIndex((j) => j.id === id);
|
|
3122
|
-
if (idx !== -1)
|
|
3127
|
+
if (idx !== -1) {
|
|
3128
|
+
jobs[idx] = { ...jobs[idx], ...update };
|
|
3129
|
+
if (update.status && ["completed", "failed", "cancelled"].includes(update.status)) clearPaymentCreditRefusals(jobs[idx]);
|
|
3130
|
+
}
|
|
3123
3131
|
}, true);
|
|
3124
3132
|
}
|
|
3125
3133
|
function recordCallerMessageHash(jobId, endpoint, hash) {
|
|
@@ -3176,6 +3184,18 @@ function recordBudgetRefusal(jobId, requestSeq, overrun) {
|
|
|
3176
3184
|
if (job) (job.budgetRefusals ??= {})[String(requestSeq)] = overrun;
|
|
3177
3185
|
}, true);
|
|
3178
3186
|
}
|
|
3187
|
+
function recordPaymentCreditLanding(jobId, requestSeq, credit) {
|
|
3188
|
+
mutateCreditPayment(jobId, (job) => {
|
|
3189
|
+
const landings = job.paymentCreditLandings ??= {};
|
|
3190
|
+
const existing = Object.keys(landings).find((key) => landings[key].fund_id === credit.fund_id);
|
|
3191
|
+
landings[existing ?? (landings[requestSeq] ? credit.fund_id : String(requestSeq))] = credit;
|
|
3192
|
+
if (existing !== void 0) return;
|
|
3193
|
+
clearUnconfirmedSubmission(job, requestSeq);
|
|
3194
|
+
job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
|
|
3195
|
+
if (!job.inFlightPaymentRequestSeqs?.length) delete job.inFlightPaymentRequestSeqs;
|
|
3196
|
+
clearPaymentRequestStartTime(job, requestSeq);
|
|
3197
|
+
}, true);
|
|
3198
|
+
}
|
|
3179
3199
|
function markPaymentRequestInFlight(jobId, requestSeq, submission) {
|
|
3180
3200
|
mutateJobs((jobs) => {
|
|
3181
3201
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
@@ -3207,6 +3227,7 @@ function markPaymentRequestPaid(jobId, requestSeq) {
|
|
|
3207
3227
|
const booked2 = mutateJobs((jobs) => {
|
|
3208
3228
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
3209
3229
|
if (!job) return void 0;
|
|
3230
|
+
clearPaymentCreditRefusals(job, requestSeq);
|
|
3210
3231
|
if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
3211
3232
|
(job.paidPaymentRequestSeqs ??= []).push(requestSeq);
|
|
3212
3233
|
if (job.inFlightPaymentRequestSeqs) {
|
|
@@ -3235,17 +3256,25 @@ function markPaymentRequestPaid(jobId, requestSeq) {
|
|
|
3235
3256
|
});
|
|
3236
3257
|
return booked2;
|
|
3237
3258
|
}
|
|
3259
|
+
function clearPaymentCreditRefusals(job, requestSeq) {
|
|
3260
|
+
for (const landing of Object.values(job.paymentCreditLandings ?? {})) {
|
|
3261
|
+
if (requestSeq === void 0 || landing.request_seq === requestSeq) delete landing.credit_payment_unavailable;
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3238
3264
|
function markPaymentRequestAnswered(jobId, requestSeq) {
|
|
3239
3265
|
mutateJobs((jobs) => {
|
|
3240
3266
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
3241
|
-
if (
|
|
3242
|
-
if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
3243
|
-
(job.paidPaymentRequestSeqs ??= []).push(requestSeq);
|
|
3244
|
-
job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
|
|
3245
|
-
if (!job.inFlightPaymentRequestSeqs?.length) delete job.inFlightPaymentRequestSeqs;
|
|
3246
|
-
clearPaymentRequestStartTime(job, requestSeq);
|
|
3267
|
+
if (job) recordAnsweredPaymentRequest(job, requestSeq);
|
|
3247
3268
|
}, true);
|
|
3248
3269
|
}
|
|
3270
|
+
function recordAnsweredPaymentRequest(job, requestSeq) {
|
|
3271
|
+
clearPaymentCreditRefusals(job, requestSeq);
|
|
3272
|
+
if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
3273
|
+
(job.paidPaymentRequestSeqs ??= []).push(requestSeq);
|
|
3274
|
+
job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
|
|
3275
|
+
if (!job.inFlightPaymentRequestSeqs?.length) delete job.inFlightPaymentRequestSeqs;
|
|
3276
|
+
clearPaymentRequestStartTime(job, requestSeq);
|
|
3277
|
+
}
|
|
3249
3278
|
function blockHeldPayment(jobId, requestSeq, blocked) {
|
|
3250
3279
|
mutateJobs((jobs) => {
|
|
3251
3280
|
const job = jobs.find((entry) => entry.id === jobId);
|
|
@@ -3466,6 +3495,7 @@ function mutateCreditPayment(jobId, change, observed = false) {
|
|
|
3466
3495
|
}
|
|
3467
3496
|
function bookCreditPayment(jobId, intent) {
|
|
3468
3497
|
const booked2 = mutateCreditPayment(jobId, (job) => {
|
|
3498
|
+
clearPaymentCreditRefusals(job, intent.authorization.request_seq);
|
|
3469
3499
|
let booked3 = false;
|
|
3470
3500
|
if (!job.bookedCreditPayments?.some((entry) => entry.authorization.payment_id === intent.authorization.payment_id)) {
|
|
3471
3501
|
booked3 = true;
|
|
@@ -4094,6 +4124,175 @@ function providerJobJson(data, providerJob = true) {
|
|
|
4094
4124
|
}, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
|
|
4095
4125
|
}
|
|
4096
4126
|
|
|
4127
|
+
// src/lib/mandate-payments.ts
|
|
4128
|
+
function mandateCredit(message) {
|
|
4129
|
+
if (message.from !== "requester" || message.type !== "payment") return void 0;
|
|
4130
|
+
const credit = message.content.credit;
|
|
4131
|
+
return credit?.mandate === true ? credit : void 0;
|
|
4132
|
+
}
|
|
4133
|
+
function validMicro2(value) {
|
|
4134
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
4135
|
+
}
|
|
4136
|
+
function safeCurrency(value) {
|
|
4137
|
+
return typeof value === "string" && /^[a-z]{3}$/i.test(value) ? value.toLowerCase() : null;
|
|
4138
|
+
}
|
|
4139
|
+
function money(micro, currency) {
|
|
4140
|
+
if (!validMicro2(micro)) return "an unrecorded amount";
|
|
4141
|
+
return currency ? formatFiat(micro / 1e6, currency) : `${(micro / 1e6).toLocaleString("en-US", { maximumFractionDigits: 6 })} (currency not recorded)`;
|
|
4142
|
+
}
|
|
4143
|
+
function mandateDrawTotal(job, history) {
|
|
4144
|
+
const mandate = job.mandate;
|
|
4145
|
+
if (!mandate) return 0;
|
|
4146
|
+
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;
|
|
4147
|
+
let total = bound(job.upfrontPayment);
|
|
4148
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4149
|
+
for (const message of history) {
|
|
4150
|
+
if (seen.has(message.seq)) continue;
|
|
4151
|
+
seen.add(message.seq);
|
|
4152
|
+
if (message.from === "requester" && message.type === "payment") total += bound(message.content.credit);
|
|
4153
|
+
}
|
|
4154
|
+
return total;
|
|
4155
|
+
}
|
|
4156
|
+
function confirmedMissingAsk(job, paymentSeq, requestSeq, fullHistoryThrough) {
|
|
4157
|
+
return fullHistoryThrough !== void 0 && paymentSeq <= fullHistoryThrough || job?.mandateMissingAskSeqs?.includes(requestSeq) === true;
|
|
4158
|
+
}
|
|
4159
|
+
function mandatePaymentReports(job, history, fullHistoryThrough) {
|
|
4160
|
+
const mandate = job?.mandate;
|
|
4161
|
+
const currency = safeCurrency(mandate?.currency);
|
|
4162
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4163
|
+
const paidAsks = /* @__PURE__ */ new Set();
|
|
4164
|
+
const reports = [];
|
|
4165
|
+
const asks = /* @__PURE__ */ new Map();
|
|
4166
|
+
const prefix = [];
|
|
4167
|
+
for (const message of [...history].sort((a, b) => a.seq - b.seq)) {
|
|
4168
|
+
if (seen.has(message.seq)) continue;
|
|
4169
|
+
seen.add(message.seq);
|
|
4170
|
+
prefix.push(message);
|
|
4171
|
+
if (message.from === "provider" && message.type === "payment-request") asks.set(message.seq, message);
|
|
4172
|
+
const paid = mandateCredit(message);
|
|
4173
|
+
if (!paid) {
|
|
4174
|
+
if (message.from === "requester" && message.type === "payment") {
|
|
4175
|
+
const seq = message.content.credit?.request_seq ?? [...asks.keys()].at(-1);
|
|
4176
|
+
if (seq !== void 0) paidAsks.add(seq);
|
|
4177
|
+
}
|
|
4178
|
+
continue;
|
|
4179
|
+
}
|
|
4180
|
+
const total = job ? mandateDrawTotal(job, prefix) : 0;
|
|
4181
|
+
const ask = asks.get(paid.request_seq);
|
|
4182
|
+
const requestUnverified = !ask && !seen.has(paid.request_seq) && !confirmedMissingAsk(job, message.seq, paid.request_seq, fullHistoryThrough);
|
|
4183
|
+
const violations = [];
|
|
4184
|
+
const reasons = [];
|
|
4185
|
+
const breach = (field, reason) => {
|
|
4186
|
+
violations.push(field);
|
|
4187
|
+
reasons.push(reason);
|
|
4188
|
+
};
|
|
4189
|
+
if (!validMicro2(paid.amount_micro) || paid.amount_micro === 0) breach("amount_micro", "an invalid payment amount");
|
|
4190
|
+
if (!ask) {
|
|
4191
|
+
if (!requestUnverified) breach("request_seq", "a payment for a charge missing from the job's requests");
|
|
4192
|
+
} else if (!ask.content.credit) breach("ask_unpriced", "a payment for a charge with no credit price");
|
|
4193
|
+
else {
|
|
4194
|
+
if (paid.amount_micro > ask.content.credit.amount_micro)
|
|
4195
|
+
breach("ask_amount_micro", `more than the provider requested for this charge (${money(ask.content.credit.amount_micro, currency)})`);
|
|
4196
|
+
if (paid.currency !== ask.content.credit.currency)
|
|
4197
|
+
breach("ask_currency", "a payment in a different currency from the requested charge");
|
|
4198
|
+
}
|
|
4199
|
+
if (paidAsks.has(paid.request_seq)) breach("duplicate_request_seq", "more than one payment for the same charge");
|
|
4200
|
+
paidAsks.add(paid.request_seq);
|
|
4201
|
+
if (mandate) {
|
|
4202
|
+
if (paid.amount_micro > mandate.max_ask_micro)
|
|
4203
|
+
breach("max_ask_micro", `more than your per-charge limit of ${money(mandate.max_ask_micro, currency)}`);
|
|
4204
|
+
if (total > mandate.max_total_micro)
|
|
4205
|
+
breach("max_total_micro", `more than your standing credit budget of ${money(mandate.max_total_micro, currency)}`);
|
|
4206
|
+
if (message.timestamp * 1e3 >= mandate.expires_at_ms)
|
|
4207
|
+
breach("expires_at_ms", `a payment after your standing limit ended on ${new Date(mandate.expires_at_ms).toISOString()}`);
|
|
4208
|
+
if (paid.credit_id !== mandate.credit_id) breach("credit_id", "a different prepaid credit than you authorised");
|
|
4209
|
+
if (paid.draw_id !== mandate.draw_id) breach("draw_id", "a different job credit reservation than you authorised");
|
|
4210
|
+
if (paid.currency !== mandate.currency) breach("currency", "a different currency than you authorised");
|
|
4211
|
+
}
|
|
4212
|
+
const paidCurrency = mandate ? paid.currency === mandate.currency ? currency : null : safeCurrency(paid.currency);
|
|
4213
|
+
const amount = { amount_micro: paid.amount_micro, currency: paid.currency, display: money(paid.amount_micro, paidCurrency) };
|
|
4214
|
+
const overchargeDisplay = reasons.length ? `Provider overcharge: ${reasons.join("; ")}.` : void 0;
|
|
4215
|
+
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.") + (requestUnverified ? " The link to the payment request could not be verified from the available messages." : "") + (overchargeDisplay ? ` ${overchargeDisplay}` : "");
|
|
4216
|
+
reports.push({
|
|
4217
|
+
amount_msats: ask?.content.amount_msats ?? 0,
|
|
4218
|
+
seq: message.seq,
|
|
4219
|
+
request_seq: paid.request_seq,
|
|
4220
|
+
mandate: true,
|
|
4221
|
+
amount,
|
|
4222
|
+
limits_checked: !!mandate,
|
|
4223
|
+
...requestUnverified ? { request_seq_unverified: true } : {},
|
|
4224
|
+
total_micro: total,
|
|
4225
|
+
budget_micro: mandate?.max_total_micro,
|
|
4226
|
+
currency,
|
|
4227
|
+
overcharged: violations.length > 0,
|
|
4228
|
+
violated_limits: violations,
|
|
4229
|
+
overcharge_display: overchargeDisplay,
|
|
4230
|
+
display
|
|
4231
|
+
});
|
|
4232
|
+
}
|
|
4233
|
+
return reports;
|
|
4234
|
+
}
|
|
4235
|
+
function readMandatePaymentReport(message, jobId) {
|
|
4236
|
+
if (!mandateCredit(message)) return void 0;
|
|
4237
|
+
return mandatePaymentReports(
|
|
4238
|
+
jobId ? loadJob(jobId) : void 0,
|
|
4239
|
+
[message, ...jobId ? loadMessages(jobId) : []]
|
|
4240
|
+
).find((entry) => entry.seq === message.seq);
|
|
4241
|
+
}
|
|
4242
|
+
function mandatePaymentSummary(job, messages, fullHistoryThrough) {
|
|
4243
|
+
const payments = mandatePaymentReports(job, messages, fullHistoryThrough);
|
|
4244
|
+
if (!payments.length) return {};
|
|
4245
|
+
const violated = [...new Set(payments.flatMap((payment) => payment.violated_limits))];
|
|
4246
|
+
return { mandate_payments: payments, ...violated.length ? {
|
|
4247
|
+
overcharged: true,
|
|
4248
|
+
violated_limits: violated,
|
|
4249
|
+
display: [...new Set(payments.map((payment) => payment.overcharge_display).filter(Boolean))].join(" ")
|
|
4250
|
+
} : {} };
|
|
4251
|
+
}
|
|
4252
|
+
function recordMandatePayments(jobId, history, fullHistoryThrough) {
|
|
4253
|
+
if (!loadJob(jobId)?.mandate || !history.some(mandateCredit)) return;
|
|
4254
|
+
mutateCreditPayment(jobId, (job) => {
|
|
4255
|
+
for (const message of history) {
|
|
4256
|
+
const credit = mandateCredit(message);
|
|
4257
|
+
if (!credit) continue;
|
|
4258
|
+
const requestSeq = credit.request_seq;
|
|
4259
|
+
const request = history.find((entry) => entry.seq === requestSeq);
|
|
4260
|
+
const ask = request?.from === "provider" && request.type === "payment-request" ? request : void 0;
|
|
4261
|
+
if (Number.isSafeInteger(requestSeq) && requestSeq >= 0 && requestSeq < message.seq) {
|
|
4262
|
+
if (!ask && (request || confirmedMissingAsk(job, message.seq, requestSeq, fullHistoryThrough))) {
|
|
4263
|
+
if (!job.mandateMissingAskSeqs?.includes(requestSeq)) (job.mandateMissingAskSeqs ??= []).push(requestSeq);
|
|
4264
|
+
if (job.paidPaymentRequestSeqs?.includes(requestSeq))
|
|
4265
|
+
job.paidPaymentRequestSeqs = job.paidPaymentRequestSeqs.filter((seq) => seq !== requestSeq);
|
|
4266
|
+
} else {
|
|
4267
|
+
if (ask && job.mandateMissingAskSeqs?.includes(requestSeq))
|
|
4268
|
+
job.mandateMissingAskSeqs = job.mandateMissingAskSeqs.filter((seq) => seq !== requestSeq);
|
|
4269
|
+
recordAnsweredPaymentRequest(job, requestSeq);
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
if (job.pendingCreditPayment?.authorization.request_seq === credit.request_seq)
|
|
4273
|
+
delete job.pendingCreditPayment;
|
|
4274
|
+
const booked2 = job.mandatePaymentSeqs?.includes(message.seq) === true;
|
|
4275
|
+
const msats = ask?.content.amount_msats ?? 0;
|
|
4276
|
+
const valuations = job.mandatePaymentMsats ??= {};
|
|
4277
|
+
const previous = valuations[message.seq] ?? 0;
|
|
4278
|
+
if (!booked2 || previous === 0 && msats > 0) {
|
|
4279
|
+
valuations[message.seq] = msats;
|
|
4280
|
+
job.totalPaidMsats = (job.totalPaidMsats ?? 0) + msats - previous;
|
|
4281
|
+
if (credit.currency === "usd") job.paidUsdMsats = (job.paidUsdMsats ?? 0) + msats - previous;
|
|
4282
|
+
}
|
|
4283
|
+
if (!booked2) {
|
|
4284
|
+
(job.mandatePaymentSeqs ??= []).push(message.seq);
|
|
4285
|
+
job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
|
|
4286
|
+
if (credit.currency === "usd") job.paidUsdMicro = (job.paidUsdMicro ?? 0) + credit.amount_micro;
|
|
4287
|
+
(job.paymentApprovals ??= []).push({ requestSeq: credit.request_seq, approval: "auto" });
|
|
4288
|
+
}
|
|
4289
|
+
}
|
|
4290
|
+
}, true);
|
|
4291
|
+
}
|
|
4292
|
+
function storedMandateSummary(jobId) {
|
|
4293
|
+
return mandatePaymentSummary(loadJob(jobId), loadMessages(jobId));
|
|
4294
|
+
}
|
|
4295
|
+
|
|
4097
4296
|
// src/lib/wallet-agent/journal-file.ts
|
|
4098
4297
|
var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
|
|
4099
4298
|
import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "fs";
|
|
@@ -5202,6 +5401,8 @@ function loadAnsweredYieldSeqs(jobId) {
|
|
|
5202
5401
|
const answered = answeredYieldSeqs(loadMessages(jobId));
|
|
5203
5402
|
const job = loadJob(jobId);
|
|
5204
5403
|
for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
|
|
5404
|
+
for (const landing of Object.values(job?.paymentCreditLandings ?? {}))
|
|
5405
|
+
if (landing.ask_answered && landing.request_seq !== void 0) answered.add(landing.request_seq);
|
|
5205
5406
|
for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
|
|
5206
5407
|
for (const seq of declinedAskSeqs(jobId)) answered.add(seq);
|
|
5207
5408
|
return answered;
|
|
@@ -5250,9 +5451,18 @@ async function reconcilePaymentRequestHistory(jobId, requestSeq, history, status
|
|
|
5250
5451
|
);
|
|
5251
5452
|
return false;
|
|
5252
5453
|
}
|
|
5253
|
-
async function settleRecordedPayments(jobId) {
|
|
5454
|
+
async function settleRecordedPayments(jobId, fullHistoryThrough) {
|
|
5254
5455
|
await applySubmissionVerdicts().catch(() => void 0);
|
|
5255
5456
|
const job = loadJob(jobId);
|
|
5457
|
+
const recorded = job?.mandate || job?.pendingCreditPayment ? loadMessages(jobId) : [];
|
|
5458
|
+
if (job?.mandate) recordMandatePayments(jobId, recorded, fullHistoryThrough);
|
|
5459
|
+
const reconciled = loadJob(jobId);
|
|
5460
|
+
const pending = reconciled?.pendingCreditPayment;
|
|
5461
|
+
if (pending && recorded.some((message) => {
|
|
5462
|
+
const credit = message.type === "payment" && message.from === "requester" ? message.content.credit : void 0;
|
|
5463
|
+
const expected = pending.authorization;
|
|
5464
|
+
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;
|
|
5465
|
+
})) bookCreditPayment(jobId, pending);
|
|
5256
5466
|
const held = /* @__PURE__ */ new Set([
|
|
5257
5467
|
...job?.inFlightPaymentRequestSeqs ?? [],
|
|
5258
5468
|
...Object.keys(job?.unconfirmedPaymentSubmissions ?? {}).map(Number)
|
|
@@ -5261,7 +5471,11 @@ async function settleRecordedPayments(jobId) {
|
|
|
5261
5471
|
if (held.size === 0) return;
|
|
5262
5472
|
const history = loadMessages(jobId);
|
|
5263
5473
|
const answers = paymentAnswers(history);
|
|
5264
|
-
for (const seq of held)
|
|
5474
|
+
for (const seq of held) {
|
|
5475
|
+
const payments = answers.get(seq);
|
|
5476
|
+
if (payments?.some((payment) => !mandateCredit(payment) || !reconciled?.mandateMissingAskSeqs?.includes(seq)))
|
|
5477
|
+
await settleAnsweredAsk(jobId, seq, history);
|
|
5478
|
+
}
|
|
5265
5479
|
}
|
|
5266
5480
|
function settleUntilMs(jobId, requestSeq, now) {
|
|
5267
5481
|
const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
|
|
@@ -5383,8 +5597,8 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
|
|
|
5383
5597
|
case "payment-request": {
|
|
5384
5598
|
const c = msg.content;
|
|
5385
5599
|
const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
|
|
5386
|
-
const
|
|
5387
|
-
const priceGuidance =
|
|
5600
|
+
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);
|
|
5601
|
+
const priceGuidance = safeCurrency2 ? display : "see the provider price in next_action.fiat_amount";
|
|
5388
5602
|
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
|
|
5389
5603
|
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
5390
5604
|
const policy = context?.policy;
|
|
@@ -5558,12 +5772,12 @@ async function stablecoinRemaining(rail) {
|
|
|
5558
5772
|
const balance = await Promise.race([
|
|
5559
5773
|
(async () => {
|
|
5560
5774
|
if (rail === "x402") {
|
|
5561
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
5775
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
|
|
5562
5776
|
const wallet = loadX402Wallet2();
|
|
5563
5777
|
if (!wallet) return;
|
|
5564
5778
|
return (await getX402Balance(await ensureAddress(wallet))).usdc;
|
|
5565
5779
|
}
|
|
5566
|
-
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-
|
|
5780
|
+
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-QOC3BHVE.js");
|
|
5567
5781
|
const account = await connectedTempoAccount2();
|
|
5568
5782
|
if (account) return (await getTempoUsdcBalance(account)).usdc;
|
|
5569
5783
|
})(),
|
|
@@ -5605,10 +5819,12 @@ function pieceSettlement(receipt, context = {}) {
|
|
|
5605
5819
|
);
|
|
5606
5820
|
const basis = lowest?.[0];
|
|
5607
5821
|
const ceiling = lowest?.[1];
|
|
5608
|
-
const
|
|
5609
|
-
const
|
|
5610
|
-
|
|
5611
|
-
|
|
5822
|
+
const mandateCheck = mandatePaymentSummary(job, messages);
|
|
5823
|
+
const overcharged = mandateCheck.overcharged === true || ceiling !== void 0 && settlement.charged > ceiling;
|
|
5824
|
+
const money2 = (micro) => formatMicro(micro, currency);
|
|
5825
|
+
let display = `Charged ${money2(settlement.charged)} of ${money2(settlement.held)} held, ${money2(settlement.released)} released.`;
|
|
5826
|
+
if (mandateCheck.overcharged) display += ` ${mandateCheck.display}`;
|
|
5827
|
+
if (ceiling !== void 0 && settlement.charged > ceiling) display += ` ${overchargeClause(basis, money2(ceiling))}`;
|
|
5612
5828
|
return {
|
|
5613
5829
|
held_micro: settlement.held,
|
|
5614
5830
|
charged_micro: settlement.charged,
|
|
@@ -5616,6 +5832,7 @@ function pieceSettlement(receipt, context = {}) {
|
|
|
5616
5832
|
stopped_micro: stopped,
|
|
5617
5833
|
currency,
|
|
5618
5834
|
...ceiling !== void 0 ? { ceiling_micro: ceiling, ceiling_basis: basis } : {},
|
|
5835
|
+
...mandateCheck.violated_limits ? { violated_limits: mandateCheck.violated_limits } : {},
|
|
5619
5836
|
overcharged,
|
|
5620
5837
|
display
|
|
5621
5838
|
};
|
|
@@ -5656,7 +5873,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5656
5873
|
asks.set(message.seq, message.content);
|
|
5657
5874
|
latestAsk = message.seq;
|
|
5658
5875
|
const declined = message.content.charged_if_declined_micro;
|
|
5659
|
-
if (
|
|
5876
|
+
if (validMicro3(declined) && sameCurrency(message.content.credit?.currency, currency)) {
|
|
5660
5877
|
finished = declined;
|
|
5661
5878
|
afterAsk = 0;
|
|
5662
5879
|
}
|
|
@@ -5664,7 +5881,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5664
5881
|
const credit = message.content.credit;
|
|
5665
5882
|
const ask = asks.get(credit?.request_seq ?? latestAsk ?? -1)?.credit;
|
|
5666
5883
|
const price = credit ? credit : ask;
|
|
5667
|
-
if (!price || !
|
|
5884
|
+
if (!price || !validMicro3(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
|
|
5668
5885
|
paid += price.amount_micro;
|
|
5669
5886
|
afterAsk += price.amount_micro;
|
|
5670
5887
|
}
|
|
@@ -5674,7 +5891,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
|
|
|
5674
5891
|
}
|
|
5675
5892
|
function declineCap(job, messages) {
|
|
5676
5893
|
const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
5677
|
-
if (!ask || !
|
|
5894
|
+
if (!ask || !validMicro3(ask.content.charged_if_declined_micro)) return void 0;
|
|
5678
5895
|
const recorded = [
|
|
5679
5896
|
...job.paidPaymentRequestSeqs ?? [],
|
|
5680
5897
|
...job.inFlightPaymentRequestSeqs ?? [],
|
|
@@ -5684,7 +5901,7 @@ function declineCap(job, messages) {
|
|
|
5684
5901
|
const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
|
|
5685
5902
|
if (!paidAsk) return ask.content.charged_if_declined_micro;
|
|
5686
5903
|
const price = ask.content.credit?.amount_micro;
|
|
5687
|
-
return
|
|
5904
|
+
return validMicro3(price) ? ask.content.charged_if_declined_micro + price : void 0;
|
|
5688
5905
|
}
|
|
5689
5906
|
function wholeThroughEnd(messages) {
|
|
5690
5907
|
if (messages.length === 0 || messages[0].seq > 1) return false;
|
|
@@ -5701,7 +5918,7 @@ function settlementCurrency(receipt, job, messages, hint) {
|
|
|
5701
5918
|
const creditId = receipt.credit?.credit_id;
|
|
5702
5919
|
if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
|
|
5703
5920
|
const railUsd = typeof job?.upfrontRailPayment === "object" ? job.upfrontRailPayment?.usdMicro : void 0;
|
|
5704
|
-
if (!job?.upfrontRailConflict &&
|
|
5921
|
+
if (!job?.upfrontRailConflict && validMicro3(railUsd) && railUsd === receipt.settlement?.held) candidates.push("usd");
|
|
5705
5922
|
const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
|
|
5706
5923
|
return found ? found.toLowerCase() : null;
|
|
5707
5924
|
}
|
|
@@ -5715,13 +5932,13 @@ function safeCredits() {
|
|
|
5715
5932
|
function sameCurrency(a, b) {
|
|
5716
5933
|
return typeof a === "string" && a.toLowerCase() === b;
|
|
5717
5934
|
}
|
|
5718
|
-
function
|
|
5935
|
+
function validMicro3(value) {
|
|
5719
5936
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
5720
5937
|
}
|
|
5721
5938
|
function isSettlement(value) {
|
|
5722
5939
|
if (!value || typeof value !== "object") return false;
|
|
5723
5940
|
const s = value;
|
|
5724
|
-
return
|
|
5941
|
+
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");
|
|
5725
5942
|
}
|
|
5726
5943
|
|
|
5727
5944
|
// src/lib/job-settlement.ts
|
|
@@ -5759,6 +5976,7 @@ function receiptSettlement(receipt, verification, rate, context) {
|
|
|
5759
5976
|
currency: pieces.currency,
|
|
5760
5977
|
...pieces.ceiling_micro !== void 0 ? { ceiling_micro: pieces.ceiling_micro, ceiling_basis: pieces.ceiling_basis } : {},
|
|
5761
5978
|
overcharged: pieces.overcharged,
|
|
5979
|
+
...pieces.violated_limits ? { violated_limits: pieces.violated_limits } : {},
|
|
5762
5980
|
display: pieces.display
|
|
5763
5981
|
};
|
|
5764
5982
|
}
|
|
@@ -6110,7 +6328,12 @@ function captureJobReceipt(jobId, receipt, parseError) {
|
|
|
6110
6328
|
}
|
|
6111
6329
|
function warnPieceOvercharge(jobId, receipt, job) {
|
|
6112
6330
|
const pieces = pieceSettlement(receipt, { job, messages: loadMessages(jobId) });
|
|
6113
|
-
if (!pieces?.overcharged
|
|
6331
|
+
if (!pieces?.overcharged) return;
|
|
6332
|
+
if (pieces.violated_limits?.length) {
|
|
6333
|
+
info(`Warning: ${pieces.display} Keep the receipt for job ${jobId} as evidence.`);
|
|
6334
|
+
return;
|
|
6335
|
+
}
|
|
6336
|
+
if (pieces.ceiling_micro === void 0) return;
|
|
6114
6337
|
const ceiling = formatMicro(pieces.ceiling_micro, pieces.currency);
|
|
6115
6338
|
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`;
|
|
6116
6339
|
info(
|
|
@@ -7281,6 +7504,7 @@ async function fundOverX402(args, fundId, resumed, corrected = false, locked = f
|
|
|
7281
7504
|
await processX402BatchResponseForWallet({
|
|
7282
7505
|
wallet,
|
|
7283
7506
|
depositMicro: pending.targetMicro,
|
|
7507
|
+
paymentHeader: pending.paymentHeader,
|
|
7284
7508
|
paymentResponse: result.x402PaymentResponse,
|
|
7285
7509
|
channelId: pending.channelId
|
|
7286
7510
|
});
|
|
@@ -9737,6 +9961,9 @@ async function findFundableAlternatives(configured, skip, sats) {
|
|
|
9737
9961
|
}
|
|
9738
9962
|
|
|
9739
9963
|
// src/lib/wallet-agent/recovery.ts
|
|
9964
|
+
import { createHash as createHash4 } from "crypto";
|
|
9965
|
+
import { setTimeout as sleepFor } from "timers/promises";
|
|
9966
|
+
var import_proper_lockfile5 = __toESM(require_proper_lockfile(), 1);
|
|
9740
9967
|
var DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS = 1e4;
|
|
9741
9968
|
var MINT_QUOTE_EXPIRY_GRACE_MS = 24 * 60 * 60 * 1e3;
|
|
9742
9969
|
async function sweepPendingMints(opts = {}) {
|
|
@@ -9744,27 +9971,17 @@ async function sweepPendingMints(opts = {}) {
|
|
|
9744
9971
|
if (!wallet || wallet.pending_mints.length === 0) {
|
|
9745
9972
|
return { outcomes: [], recovered_proofs: [], still_pending: [], refused: [], errors: [] };
|
|
9746
9973
|
}
|
|
9747
|
-
const now = opts.now ?? (() => Date.now());
|
|
9748
|
-
const expiryGraceMs = opts.expiryGraceMs ?? MINT_QUOTE_EXPIRY_GRACE_MS;
|
|
9749
|
-
const getWalletForMint = opts.getWalletForMint ?? getWallet;
|
|
9750
|
-
const quoteRetryTimeoutMs = opts.quoteRetryTimeoutMs ?? DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS;
|
|
9751
9974
|
const outcomes = [];
|
|
9752
9975
|
for (const entry of wallet.pending_mints) {
|
|
9753
|
-
const outcome = await
|
|
9754
|
-
|
|
9755
|
-
|
|
9756
|
-
|
|
9757
|
-
})
|
|
9758
|
-
|
|
9759
|
-
|
|
9760
|
-
|
|
9761
|
-
|
|
9762
|
-
)) {
|
|
9763
|
-
await withWalletLock(() => {
|
|
9764
|
-
const fresh = loadAgentWallet() ?? wallet;
|
|
9765
|
-
const updated = outcomes.reduce(applyOutcome, fresh);
|
|
9766
|
-
saveAgentWallet(updated);
|
|
9767
|
-
});
|
|
9976
|
+
const outcome = await reconcilePendingMint(entry, opts);
|
|
9977
|
+
if (outcome.kind === "no_longer_pending") continue;
|
|
9978
|
+
if (outcome.kind === "busy") {
|
|
9979
|
+
outcomes.push({ kind: "error", entry, error: "Another command is checking this mint quote." });
|
|
9980
|
+
} else if (outcome.kind === "error") {
|
|
9981
|
+
outcomes.push({ kind: "error", entry: outcome.entry, error: errorMessage(outcome.cause) });
|
|
9982
|
+
} else {
|
|
9983
|
+
outcomes.push(outcome);
|
|
9984
|
+
}
|
|
9768
9985
|
}
|
|
9769
9986
|
return {
|
|
9770
9987
|
outcomes,
|
|
@@ -9778,7 +9995,69 @@ async function sweepPendingMints(opts = {}) {
|
|
|
9778
9995
|
errors: outcomes.filter((o) => o.kind === "error").map((o) => ({ quote_id: o.entry.quote_id, error: o.error }))
|
|
9779
9996
|
};
|
|
9780
9997
|
}
|
|
9781
|
-
async function
|
|
9998
|
+
async function reconcilePendingMint(entry, opts = {}) {
|
|
9999
|
+
const key = createHash4("sha256").update(JSON.stringify([entry.mint, entry.quote_id])).digest("hex");
|
|
10000
|
+
let release;
|
|
10001
|
+
try {
|
|
10002
|
+
release = await import_proper_lockfile5.default.lock(`${WALLET_FILE}.mint-${key}`, { realpath: false, stale: 3e4, retries: 0 });
|
|
10003
|
+
} catch (err) {
|
|
10004
|
+
if (err.code === "ELOCKED") return { kind: "busy" };
|
|
10005
|
+
return { kind: "error", entry, cause: err };
|
|
10006
|
+
}
|
|
10007
|
+
try {
|
|
10008
|
+
const wallet = loadAgentWallet();
|
|
10009
|
+
const current = wallet?.pending_mints.find((pending) => matchesPendingMint(pending, entry));
|
|
10010
|
+
if (!wallet || !current) return { kind: "no_longer_pending" };
|
|
10011
|
+
const outcome = await processEntry(wallet, current, opts);
|
|
10012
|
+
if (outcome.kind === "minted" || outcome.kind === "restored" || outcome.kind === "already_issued" || outcome.kind === "expired") {
|
|
10013
|
+
const committed = await withMintWriteLock(opts.deadlineMs, () => {
|
|
10014
|
+
const fresh = currentMintWallet(wallet, current);
|
|
10015
|
+
if (!fresh) return false;
|
|
10016
|
+
const proofs = outcome.kind === "minted" || outcome.kind === "restored" ? outcome.proofs : [];
|
|
10017
|
+
saveAgentWallet({
|
|
10018
|
+
...fresh,
|
|
10019
|
+
pending_mints: fresh.pending_mints.filter((pending) => !matchesPendingMint(pending, current)),
|
|
10020
|
+
proofs: [...fresh.proofs, ...proofs]
|
|
10021
|
+
});
|
|
10022
|
+
return true;
|
|
10023
|
+
});
|
|
10024
|
+
if (!committed) return { kind: "no_longer_pending" };
|
|
10025
|
+
}
|
|
10026
|
+
return outcome;
|
|
10027
|
+
} catch (err) {
|
|
10028
|
+
return { kind: "error", entry, cause: err };
|
|
10029
|
+
} finally {
|
|
10030
|
+
await release().catch(() => void 0);
|
|
10031
|
+
}
|
|
10032
|
+
}
|
|
10033
|
+
function matchesPendingMint(left, right) {
|
|
10034
|
+
return left.mint === right.mint && left.quote_id === right.quote_id && left.requested_at === right.requested_at;
|
|
10035
|
+
}
|
|
10036
|
+
function currentMintWallet(wallet, entry) {
|
|
10037
|
+
const fresh = loadAgentWallet();
|
|
10038
|
+
if (fresh?.lock_pubkey === wallet.lock_pubkey && fresh.pending_mints.some((pending) => matchesPendingMint(pending, entry))) {
|
|
10039
|
+
return fresh;
|
|
10040
|
+
}
|
|
10041
|
+
}
|
|
10042
|
+
async function withMintWriteLock(deadlineMs, write) {
|
|
10043
|
+
if (deadlineMs === void 0) return withWalletLock(write);
|
|
10044
|
+
for (; ; ) {
|
|
10045
|
+
try {
|
|
10046
|
+
return await withWalletLock(write, { retries: 0 });
|
|
10047
|
+
} catch (err) {
|
|
10048
|
+
const remaining = deadlineMs - Date.now();
|
|
10049
|
+
if (!(err instanceof DvmError && err.code === "wallet_locked") || remaining <= 0) throw err;
|
|
10050
|
+
await sleepFor(Math.min(remaining, 50));
|
|
10051
|
+
}
|
|
10052
|
+
}
|
|
10053
|
+
}
|
|
10054
|
+
async function processEntry(wallet, entry, opts) {
|
|
10055
|
+
const now = opts.now ?? Date.now;
|
|
10056
|
+
const nowMs = now();
|
|
10057
|
+
if (opts.pollDeadlineMs !== void 0 && nowMs >= opts.pollDeadlineMs) {
|
|
10058
|
+
return { kind: "still_pending", entry };
|
|
10059
|
+
}
|
|
10060
|
+
const getWalletForMint = opts.getWalletForMint ?? getWallet;
|
|
9782
10061
|
let cashuWallet;
|
|
9783
10062
|
let quoteResponse;
|
|
9784
10063
|
try {
|
|
@@ -9789,10 +10068,13 @@ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMin
|
|
|
9789
10068
|
return { cashuWallet: candidate, quoteResponse: quote };
|
|
9790
10069
|
},
|
|
9791
10070
|
{
|
|
9792
|
-
deadlineMs:
|
|
10071
|
+
deadlineMs: Math.min(
|
|
10072
|
+
opts.pollDeadlineMs ?? Infinity,
|
|
10073
|
+
nowMs + (opts.quoteRetryTimeoutMs ?? DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS)
|
|
10074
|
+
),
|
|
9793
10075
|
quoteId: entry.quote_id,
|
|
9794
|
-
now
|
|
9795
|
-
sleep:
|
|
10076
|
+
now,
|
|
10077
|
+
sleep: opts.sleep
|
|
9796
10078
|
}
|
|
9797
10079
|
));
|
|
9798
10080
|
} catch (err) {
|
|
@@ -9805,7 +10087,7 @@ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMin
|
|
|
9805
10087
|
() => getWalletForMint(entry.mint)
|
|
9806
10088
|
);
|
|
9807
10089
|
}
|
|
9808
|
-
return { kind: "error", entry,
|
|
10090
|
+
return { kind: "error", entry, cause: err };
|
|
9809
10091
|
}
|
|
9810
10092
|
const state = quoteResponse.state;
|
|
9811
10093
|
if (state === sa.ISSUED) {
|
|
@@ -9824,36 +10106,53 @@ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMin
|
|
|
9824
10106
|
}
|
|
9825
10107
|
return { kind: "restored", entry, proofs: restoredProofs };
|
|
9826
10108
|
} catch (err) {
|
|
9827
|
-
return { kind: "error", entry,
|
|
10109
|
+
return { kind: "error", entry, cause: err };
|
|
9828
10110
|
}
|
|
9829
10111
|
}
|
|
9830
10112
|
if (state === sa.PAID) {
|
|
9831
10113
|
try {
|
|
9832
|
-
|
|
9833
|
-
|
|
9834
|
-
|
|
9835
|
-
|
|
9836
|
-
|
|
10114
|
+
let savedMinting = entry.minting;
|
|
10115
|
+
if (savedMinting && cashuWallet.keyChain.getKeysets().some(
|
|
10116
|
+
(keyset) => keyset.id === savedMinting?.keyset_id && keyset.isActive === false
|
|
10117
|
+
)) {
|
|
10118
|
+
await cashuWallet.ensureOperableKeysets([savedMinting.keyset_id]);
|
|
10119
|
+
const proofs2 = await restoreFromMintingState(cashuWallet, savedMinting, wallet.lock_pubkey, entry.mint);
|
|
10120
|
+
if (proofs2.length > 0) return { kind: "restored", entry, proofs: proofs2 };
|
|
10121
|
+
savedMinting = void 0;
|
|
10122
|
+
}
|
|
10123
|
+
const preview = savedMinting ? await cashuWallet.prepareMint(
|
|
10124
|
+
"bolt11",
|
|
10125
|
+
entry.amount_sats,
|
|
10126
|
+
quoteResponse,
|
|
10127
|
+
{ privkey: wallet.lock_privkey, keysetId: savedMinting.keyset_id },
|
|
10128
|
+
{ type: "custom", data: rehydrateOutputData(savedMinting.outputs) }
|
|
10129
|
+
) : await prepareP2PKMint(
|
|
9837
10130
|
cashuWallet,
|
|
9838
10131
|
entry.amount_sats,
|
|
9839
10132
|
quoteResponse,
|
|
9840
10133
|
wallet.lock_privkey,
|
|
9841
10134
|
wallet.lock_pubkey,
|
|
9842
|
-
|
|
10135
|
+
computeSmartDenominations(entry.amount_sats, {
|
|
10136
|
+
maxDenomination: maxKeysetDenomination(cashuWallet),
|
|
10137
|
+
includeTinyTail: false
|
|
10138
|
+
})
|
|
9843
10139
|
);
|
|
9844
|
-
|
|
9845
|
-
|
|
9846
|
-
|
|
9847
|
-
|
|
9848
|
-
|
|
9849
|
-
const
|
|
9850
|
-
|
|
9851
|
-
|
|
9852
|
-
|
|
9853
|
-
|
|
9854
|
-
|
|
10140
|
+
if (!savedMinting) {
|
|
10141
|
+
const minting = {
|
|
10142
|
+
keyset_id: preview.keysetId,
|
|
10143
|
+
outputs: serializeOutputData(preview.outputData)
|
|
10144
|
+
};
|
|
10145
|
+
const saved = await withMintWriteLock(opts.deadlineMs, () => {
|
|
10146
|
+
const fresh = currentMintWallet(wallet, entry);
|
|
10147
|
+
if (!fresh) return false;
|
|
10148
|
+
saveAgentWallet({
|
|
10149
|
+
...fresh,
|
|
10150
|
+
pending_mints: fresh.pending_mints.map((p) => matchesPendingMint(p, entry) ? { ...p, minting } : p)
|
|
10151
|
+
});
|
|
10152
|
+
return true;
|
|
9855
10153
|
});
|
|
9856
|
-
|
|
10154
|
+
if (!saved) return { kind: "no_longer_pending" };
|
|
10155
|
+
}
|
|
9857
10156
|
const proofs = await cashuWallet.completeMint(preview);
|
|
9858
10157
|
const agentProofs = proofs.map((p) => toAgentProof(p, entry.mint, wallet.lock_pubkey));
|
|
9859
10158
|
return { kind: "minted", entry, proofs: agentProofs };
|
|
@@ -9861,7 +10160,7 @@ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMin
|
|
|
9861
10160
|
if (mintQuoteRefusal(err) === "expired") {
|
|
9862
10161
|
return { kind: "paid_refused", entry, reason: "quote_expired" };
|
|
9863
10162
|
}
|
|
9864
|
-
return { kind: "error", entry,
|
|
10163
|
+
return { kind: "error", entry, cause: err };
|
|
9865
10164
|
}
|
|
9866
10165
|
}
|
|
9867
10166
|
if (state === "EXPIRED") {
|
|
@@ -9875,7 +10174,7 @@ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMin
|
|
|
9875
10174
|
if (nowMs <= expiredAtMs) {
|
|
9876
10175
|
return { kind: "still_pending", entry };
|
|
9877
10176
|
}
|
|
9878
|
-
const dropAfterMs = expiredAtMs + expiryGraceMs;
|
|
10177
|
+
const dropAfterMs = expiredAtMs + (opts.expiryGraceMs ?? MINT_QUOTE_EXPIRY_GRACE_MS);
|
|
9879
10178
|
if (nowMs > dropAfterMs) {
|
|
9880
10179
|
return finalAnswer(wallet, entry, "grace_elapsed", async () => cashuWallet);
|
|
9881
10180
|
}
|
|
@@ -9896,13 +10195,13 @@ async function finalAnswer(wallet, entry, reason, getCashuWallet) {
|
|
|
9896
10195
|
);
|
|
9897
10196
|
if (restored.length > 0) return { kind: "restored", entry, proofs: restored };
|
|
9898
10197
|
} catch (err) {
|
|
9899
|
-
return { kind: "error", entry,
|
|
10198
|
+
return { kind: "error", entry, cause: err };
|
|
9900
10199
|
}
|
|
9901
10200
|
if (reason === "mint_expired") return { kind: "paid_refused", entry, reason: "quote_expired" };
|
|
9902
10201
|
return {
|
|
9903
10202
|
kind: "error",
|
|
9904
10203
|
entry,
|
|
9905
|
-
|
|
10204
|
+
cause: reason === "mint_unknown" ? "The mint reported this quote paid earlier and no longer knows it; nothing could be restored, so the quote is kept." : "The mint reported this quote paid earlier and now reports it unpaid; nothing could be restored, so the quote is kept."
|
|
9906
10205
|
};
|
|
9907
10206
|
}
|
|
9908
10207
|
var MINT_QUOTE_EXPIRED_CODE = 20007;
|
|
@@ -9922,19 +10221,6 @@ async function restoreFromMintingState(cashuWallet, minting, lockPubkey, mintUrl
|
|
|
9922
10221
|
const proofs = await restoreProofsFromOutputs(cashuWallet, minting.keyset_id, minting.outputs);
|
|
9923
10222
|
return proofs.map((proof) => toAgentProof(proof, mintUrl, lockPubkey));
|
|
9924
10223
|
}
|
|
9925
|
-
function applyOutcome(wallet, outcome) {
|
|
9926
|
-
if (outcome.kind === "still_pending" || outcome.kind === "paid_refused" || outcome.kind === "error") {
|
|
9927
|
-
return wallet;
|
|
9928
|
-
}
|
|
9929
|
-
const next = {
|
|
9930
|
-
...wallet,
|
|
9931
|
-
pending_mints: wallet.pending_mints.filter((p) => p.quote_id !== outcome.entry.quote_id)
|
|
9932
|
-
};
|
|
9933
|
-
if (outcome.kind === "minted" || outcome.kind === "restored") {
|
|
9934
|
-
next.proofs = [...wallet.proofs, ...outcome.proofs];
|
|
9935
|
-
}
|
|
9936
|
-
return next;
|
|
9937
|
-
}
|
|
9938
10224
|
function errorMessage(err) {
|
|
9939
10225
|
return err instanceof Error ? err.message : String(err);
|
|
9940
10226
|
}
|
|
@@ -9992,6 +10278,7 @@ export {
|
|
|
9992
10278
|
loadAllJobs,
|
|
9993
10279
|
addPayment,
|
|
9994
10280
|
recordBudgetRefusal,
|
|
10281
|
+
recordPaymentCreditLanding,
|
|
9995
10282
|
markPaymentRequestInFlight,
|
|
9996
10283
|
clearPaymentRequestInFlight,
|
|
9997
10284
|
markPaymentRequestPaid,
|
|
@@ -10020,6 +10307,13 @@ export {
|
|
|
10020
10307
|
recordSpendOnce,
|
|
10021
10308
|
enforceGlobalBudget,
|
|
10022
10309
|
statusSnapshot,
|
|
10310
|
+
mandateCredit,
|
|
10311
|
+
mandateDrawTotal,
|
|
10312
|
+
mandatePaymentReports,
|
|
10313
|
+
readMandatePaymentReport,
|
|
10314
|
+
mandatePaymentSummary,
|
|
10315
|
+
recordMandatePayments,
|
|
10316
|
+
storedMandateSummary,
|
|
10023
10317
|
journalFile,
|
|
10024
10318
|
extractBuilderHandle,
|
|
10025
10319
|
reservedForMarker,
|
|
@@ -10038,6 +10332,7 @@ export {
|
|
|
10038
10332
|
formatLocktime,
|
|
10039
10333
|
prepareAgentSpend,
|
|
10040
10334
|
commitAgentSpend,
|
|
10335
|
+
commitHeldSubmission,
|
|
10041
10336
|
correctPendingFundAmount,
|
|
10042
10337
|
abandonPendingSubmission,
|
|
10043
10338
|
abandonSubmissionInWallet,
|
|
@@ -10158,5 +10453,6 @@ export {
|
|
|
10158
10453
|
describeMintBounds,
|
|
10159
10454
|
MINT_QUOTE_EXPIRY_GRACE_MS,
|
|
10160
10455
|
sweepPendingMints,
|
|
10456
|
+
reconcilePendingMint,
|
|
10161
10457
|
mintQuoteRefusal
|
|
10162
10458
|
};
|