@dvmkit/dvm-cli 0.13.0 → 0.14.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-GWLOO5XD.js → chunk-2MCZ4QOK.js} +2 -2
- package/dist/{chunk-C2BJETRG.js → chunk-57PXJ56K.js} +4 -4
- package/dist/{chunk-RPM5XEVS.js → chunk-CO2TD5RO.js} +2 -2
- package/dist/{chunk-PS4AUWK3.js → chunk-D5CGDS3V.js} +2 -2
- package/dist/{chunk-NLUOHCX2.js → chunk-DU7YCGCQ.js} +214 -21
- package/dist/{chunk-ZDWZT6NA.js → chunk-EZL4IVCU.js} +3 -3
- package/dist/{chunk-I2C3YEUN.js → chunk-HJ2JYBTT.js} +4 -4
- package/dist/{chunk-CCF4QONY.js → chunk-HXTASGHL.js} +2 -2
- package/dist/{chunk-C2EZ3VY2.js → chunk-I7ZBID4L.js} +2 -2
- package/dist/{chunk-ZV57FFIL.js → chunk-UCCT5IKU.js} +9 -1
- package/dist/{chunk-KQQALLOL.js → chunk-UWVMG4VG.js} +3 -3
- package/dist/{chunk-SEJWBDGY.js → chunk-YQJRKWNT.js} +1739 -788
- package/dist/{client-6JRGRKFQ.js → client-DC7TVYNU.js} +6 -6
- package/dist/dvm.js +690 -487
- package/dist/{internal-KPPGYK5N.js → internal-O7IQD6EQ.js} +5 -5
- package/dist/{lifecycle-7YRNRLDQ.js → lifecycle-MIJH3JE4.js} +6 -6
- package/dist/{payout-reporter-KTLBNJJ7-WDT6M4GN.js → payout-reporter-Y6OW3FYD-K6MRWQXK.js} +2 -2
- package/dist/{pocket-refill-E2QVQDME.js → pocket-refill-HEVLAMKN.js} +10 -10
- package/dist/{revenue-reporter-FD3GDQZS-COUBEUDN.js → revenue-reporter-CIG2MEDN-ZXMO6NWG.js} +2 -2
- package/dist/{tempo-lifecycle-EOP5IHJT.js → tempo-lifecycle-FMBCHD2M.js} +8 -8
- package/dist/{tempo-wallet-4A5M3FVO.js → tempo-wallet-U3WBWIIH.js} +7 -7
- package/dist/{wallet-LASVQ72F.js → wallet-Z3FDX43V.js} +7 -7
- package/dist/{x402-MFBRORHG-34VE7EWO.js → x402-ARXZQ5BD-H6PNJYYT.js} +2 -2
- package/package.json +2 -2
- package/skills/dvm/SKILL.md +2 -0
- package/skills/dvm/calling.md +12 -1
- package/skills/dvm/recovery.md +3 -0
|
@@ -82,10 +82,10 @@ import {
|
|
|
82
82
|
x402ResourceServer,
|
|
83
83
|
x402SupportedNetworksHint,
|
|
84
84
|
x402Version
|
|
85
|
-
} from "./chunk-
|
|
85
|
+
} from "./chunk-57PXJ56K.js";
|
|
86
86
|
import {
|
|
87
87
|
x402EarnedCeiling
|
|
88
|
-
} from "./chunk-
|
|
88
|
+
} from "./chunk-D5CGDS3V.js";
|
|
89
89
|
import {
|
|
90
90
|
withSdkInitLock
|
|
91
91
|
} from "./chunk-R2DSAZBO.js";
|
|
@@ -98,7 +98,7 @@ import {
|
|
|
98
98
|
extendDiagnosticIdentityAuthority,
|
|
99
99
|
projectDiagnosticFields,
|
|
100
100
|
projectSpanRow
|
|
101
|
-
} from "./chunk-
|
|
101
|
+
} from "./chunk-UCCT5IKU.js";
|
|
102
102
|
import {
|
|
103
103
|
privateKeyToAccount
|
|
104
104
|
} from "./chunk-EVQERRCP.js";
|
|
@@ -1747,7 +1747,7 @@ var require_proper_lockfile = __commonJS({
|
|
|
1747
1747
|
// node_modules/@dvmkit/sdk/dist/chunk-A262WVYX.js
|
|
1748
1748
|
var CAPABILITY_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
1749
1749
|
|
|
1750
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
1750
|
+
// node_modules/@dvmkit/sdk/dist/chunk-4G4PNOLI.js
|
|
1751
1751
|
import { createHash } from "crypto";
|
|
1752
1752
|
|
|
1753
1753
|
// node_modules/@noble/ciphers/utils.js
|
|
@@ -3884,7 +3884,7 @@ var getPublicKey2 = i2.getPublicKey;
|
|
|
3884
3884
|
var finalizeEvent2 = i2.finalizeEvent;
|
|
3885
3885
|
var verifyEvent2 = i2.verifyEvent;
|
|
3886
3886
|
|
|
3887
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
3887
|
+
// node_modules/@dvmkit/sdk/dist/chunk-4G4PNOLI.js
|
|
3888
3888
|
var X402_SELF_RELAY_KEY = "DVMKIT_X402_SELF_RELAY_KEY";
|
|
3889
3889
|
var X402_RECEIVER_AUTHORIZER_KEY = "DVMKIT_X402_RECEIVER_AUTHORIZER_KEY";
|
|
3890
3890
|
var X402_BATCH_SETTLEMENT_KEY = "DVMKIT_X402_BATCH_SETTLEMENT";
|
|
@@ -4970,7 +4970,7 @@ function verifyDrainReceipt(receipt) {
|
|
|
4970
4970
|
}
|
|
4971
4971
|
}
|
|
4972
4972
|
|
|
4973
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
4973
|
+
// node_modules/@dvmkit/sdk/dist/chunk-T35BQR6J.js
|
|
4974
4974
|
import { homedir } from "os";
|
|
4975
4975
|
import { join as join3 } from "path";
|
|
4976
4976
|
import { chmodSync, mkdirSync, statSync } from "fs";
|
|
@@ -10213,7 +10213,7 @@ zero
|
|
|
10213
10213
|
zone
|
|
10214
10214
|
zoo`.split("\n");
|
|
10215
10215
|
|
|
10216
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
10216
|
+
// node_modules/@dvmkit/sdk/dist/chunk-T35BQR6J.js
|
|
10217
10217
|
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
|
|
10218
10218
|
import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
10219
10219
|
|
|
@@ -20768,7 +20768,7 @@ function expand(hash4, prk, info, length = 32) {
|
|
|
20768
20768
|
}
|
|
20769
20769
|
var hkdf = (hash4, ikm, salt, info, length) => expand(hash4, extract(hash4, ikm, salt), info, length);
|
|
20770
20770
|
|
|
20771
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
20771
|
+
// node_modules/@dvmkit/sdk/dist/chunk-T35BQR6J.js
|
|
20772
20772
|
import { randomBytes as randomBytes6 } from "crypto";
|
|
20773
20773
|
import {
|
|
20774
20774
|
chmodSync as chmodSync4,
|
|
@@ -22520,7 +22520,7 @@ function canonicalRequestPath(pathOrUrl) {
|
|
|
22520
22520
|
return parsed.pathname.startsWith("/") ? parsed.pathname : `/${parsed.pathname}`;
|
|
22521
22521
|
}
|
|
22522
22522
|
|
|
22523
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
22523
|
+
// node_modules/@dvmkit/sdk/dist/chunk-2AYDNH6L.js
|
|
22524
22524
|
function createConsoleLogger(_jobId) {
|
|
22525
22525
|
return {
|
|
22526
22526
|
debug(_message, data) {
|
|
@@ -22590,7 +22590,7 @@ var StepCache = class _StepCache {
|
|
|
22590
22590
|
}
|
|
22591
22591
|
};
|
|
22592
22592
|
|
|
22593
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
22593
|
+
// node_modules/@dvmkit/sdk/dist/chunk-6AZFMBKH.js
|
|
22594
22594
|
var InvalidCurrencyError = class extends Error {
|
|
22595
22595
|
code = "invalid_currency";
|
|
22596
22596
|
raw;
|
|
@@ -23042,7 +23042,7 @@ function resolveFxSourceFromEnv(env) {
|
|
|
23042
23042
|
return raw2;
|
|
23043
23043
|
}
|
|
23044
23044
|
|
|
23045
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
23045
|
+
// node_modules/@dvmkit/sdk/dist/chunk-E4WQHYXC.js
|
|
23046
23046
|
import { AsyncLocalStorage } from "async_hooks";
|
|
23047
23047
|
var postgresRecovery = new AsyncLocalStorage();
|
|
23048
23048
|
var queryingPool = new AsyncLocalStorage();
|
|
@@ -23226,7 +23226,7 @@ function truncateUtf8(value, maxBytes) {
|
|
|
23226
23226
|
return result;
|
|
23227
23227
|
}
|
|
23228
23228
|
|
|
23229
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
23229
|
+
// node_modules/@dvmkit/sdk/dist/chunk-FLYNYW3N.js
|
|
23230
23230
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
23231
23231
|
import { randomBytes as randomBytes7, randomUUID } from "crypto";
|
|
23232
23232
|
import { hostname } from "os";
|
|
@@ -27599,15 +27599,18 @@ function applyReceiptCredit(args) {
|
|
|
27599
27599
|
let mismatch;
|
|
27600
27600
|
let fundedMicro;
|
|
27601
27601
|
const sequential = args.credit.ledger_seq === record2.ledgerSeq + 1;
|
|
27602
|
-
|
|
27602
|
+
const charged = args.settlement ? args.settlement.charged : args.credit.amount;
|
|
27603
|
+
const charges = args.outcome === "completed" || (args.settlement?.charged ?? 0) > 0;
|
|
27604
|
+
if (sequential && charges && record2.status === "active" && !record2.provisional && !record2.unsequencedBalance) {
|
|
27603
27605
|
const eligible = (record2.drawFundings ?? []).filter(
|
|
27604
27606
|
(fact) => fact.drawId === args.credit.draw_id && fact.ledgerSeq === args.credit.ledger_seq
|
|
27605
27607
|
);
|
|
27606
27608
|
if (eligible.length > 0) {
|
|
27607
27609
|
fundedMicro = eligible.reduce((sum2, fact) => sum2 + fact.fundedMicro, 0);
|
|
27608
27610
|
}
|
|
27609
|
-
const
|
|
27610
|
-
|
|
27611
|
+
const paidMicro = record2.remainingMicro + (fundedMicro ?? 0);
|
|
27612
|
+
const expected = paidMicro - charged;
|
|
27613
|
+
if (args.credit.balance_after !== expected || charged > paidMicro) {
|
|
27611
27614
|
mismatch = {
|
|
27612
27615
|
atMs: now,
|
|
27613
27616
|
expectedMicro: expected,
|
|
@@ -32026,7 +32029,7 @@ function parseStoreValue(value) {
|
|
|
32026
32029
|
return parsed;
|
|
32027
32030
|
}
|
|
32028
32031
|
|
|
32029
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
32032
|
+
// node_modules/@dvmkit/sdk/dist/chunk-B3NPAJVG.js
|
|
32030
32033
|
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
|
|
32031
32034
|
var PostgresTempoSessionStore = class {
|
|
32032
32035
|
constructor(pool) {
|
|
@@ -32604,7 +32607,7 @@ function acceptanceVoucherAmount(acceptance, key, current, next) {
|
|
|
32604
32607
|
return authorized !== void 0 && authorized >= acceptance.cumulativeAmount ? acceptance.cumulativeAmount : void 0;
|
|
32605
32608
|
}
|
|
32606
32609
|
|
|
32607
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
32610
|
+
// node_modules/@dvmkit/sdk/dist/chunk-2J4RBSAL.js
|
|
32608
32611
|
import { createHash as createHash5 } from "crypto";
|
|
32609
32612
|
var DEFAULT_TABLE_NAME = "mpp_tempo_charge_replays";
|
|
32610
32613
|
var DEFAULT_RETENTION_MS = 60 * 60 * 1e3;
|
|
@@ -32959,7 +32962,7 @@ function isUniqueViolation(err) {
|
|
|
32959
32962
|
return typeof err === "object" && err !== null && err.code === "23505";
|
|
32960
32963
|
}
|
|
32961
32964
|
|
|
32962
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
32965
|
+
// node_modules/@dvmkit/sdk/dist/chunk-QVPJQ565.js
|
|
32963
32966
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
32964
32967
|
import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
|
|
32965
32968
|
import { isDeepStrictEqual } from "util";
|
|
@@ -33013,6 +33016,8 @@ function lotSats(lot, micro) {
|
|
|
33013
33016
|
const taken = Math.min(micro, lot.creditedMicro);
|
|
33014
33017
|
return Number(BigInt(lot.satsFunded) * BigInt(taken) / BigInt(lot.creditedMicro));
|
|
33015
33018
|
}
|
|
33019
|
+
var DRAW_NOT_SETTLED_REFUSAL = "Only a settled draw, or the settled part of a partly settled draw, can be refunded.";
|
|
33020
|
+
var REFUND_EXCEEDS_SETTLED_REFUSAL = "The refund exceeds the draw's remaining unrefunded settled charge.";
|
|
33016
33021
|
function refundRequest(args) {
|
|
33017
33022
|
const id = (value) => typeof value === "string" && value.length > 0;
|
|
33018
33023
|
if (!id(args.refundId) || !(id(args.jobId) && args.creditId === void 0 && args.drawId === void 0 || args.jobId === void 0 && id(args.creditId) && id(args.drawId)) || args.amountMicro !== void 0 && (!Number.isSafeInteger(args.amountMicro) || args.amountMicro <= 0) || args.reason !== void 0 && (typeof args.reason !== "string" || args.reason.length > 280)) {
|
|
@@ -33032,6 +33037,41 @@ function refundAssetDelta(original, amountMicro, before, after) {
|
|
|
33032
33037
|
const denominator = BigInt(amountMicro);
|
|
33033
33038
|
return Number(value * BigInt(after) / denominator - value * BigInt(before) / denominator);
|
|
33034
33039
|
}
|
|
33040
|
+
function assertSettleMicro(settleMicro) {
|
|
33041
|
+
if (!Number.isSafeInteger(settleMicro) || settleMicro < 0) {
|
|
33042
|
+
throw new CreditLedgerError(
|
|
33043
|
+
"invalid_amount",
|
|
33044
|
+
`settleMicro must be a safe integer \u2265 0 (got ${settleMicro})`
|
|
33045
|
+
);
|
|
33046
|
+
}
|
|
33047
|
+
}
|
|
33048
|
+
function planDrawResolution(draw, request) {
|
|
33049
|
+
const holdMicro = draw.heldMicro ?? draw.amountMicro;
|
|
33050
|
+
const settleMicro = request === "hold" ? holdMicro : request;
|
|
33051
|
+
if (settleMicro > holdMicro) {
|
|
33052
|
+
throw new CreditLedgerError(
|
|
33053
|
+
"invalid_amount",
|
|
33054
|
+
`cannot settle ${settleMicro} of draw ${draw.drawId}: its hold is ${holdMicro}`
|
|
33055
|
+
);
|
|
33056
|
+
}
|
|
33057
|
+
const status = request === "hold" || settleMicro > 0 ? "settled" : "released";
|
|
33058
|
+
if (draw.status === "pending") {
|
|
33059
|
+
return { status, settleMicro, replay: false, partial: status === "settled" && settleMicro < holdMicro };
|
|
33060
|
+
}
|
|
33061
|
+
const recordedMicro = draw.status === "settled" ? draw.amountMicro : 0;
|
|
33062
|
+
if (draw.status === status && recordedMicro === settleMicro) {
|
|
33063
|
+
return { status, settleMicro, replay: true, partial: draw.heldMicro !== null };
|
|
33064
|
+
}
|
|
33065
|
+
throw new CreditLedgerError(
|
|
33066
|
+
"invalid_draw_state",
|
|
33067
|
+
draw.status === status ? `cannot settle ${settleMicro} of draw ${draw.drawId}: it already settled ${recordedMicro}` : `cannot ${status === "settled" ? "settle" : "release"} draw ${draw.drawId}: status is ${draw.status}`,
|
|
33068
|
+
{ currentStatus: draw.status, settledMicro: recordedMicro }
|
|
33069
|
+
);
|
|
33070
|
+
}
|
|
33071
|
+
function settledShare(value, settleMicro, holdMicro) {
|
|
33072
|
+
if (settleMicro >= holdMicro) return value;
|
|
33073
|
+
return Number(BigInt(value) * BigInt(settleMicro) / BigInt(holdMicro));
|
|
33074
|
+
}
|
|
33035
33075
|
var X402SettlementRaceError = class extends Error {
|
|
33036
33076
|
};
|
|
33037
33077
|
var X402RelaySubmissionLockError = class extends Error {
|
|
@@ -34445,6 +34485,10 @@ var CreditLedger = class {
|
|
|
34445
34485
|
`CREATE INDEX IF NOT EXISTS idx_credit_expiry_releases_open
|
|
34446
34486
|
ON credit_expiry_releases(credit_id) WHERE reversed_at IS NULL;`
|
|
34447
34487
|
);
|
|
34488
|
+
await this.pool.query(`ALTER TABLE credit_draws
|
|
34489
|
+
ADD COLUMN IF NOT EXISTS held_micro BIGINT,
|
|
34490
|
+
ADD COLUMN IF NOT EXISTS released_micro BIGINT,
|
|
34491
|
+
ADD COLUMN IF NOT EXISTS released_native BIGINT`);
|
|
34448
34492
|
}
|
|
34449
34493
|
/**
|
|
34450
34494
|
* Backfill an open non-channel Bitcoin credit only when it has no funding lot. Pair
|
|
@@ -34853,12 +34897,13 @@ var CreditLedger = class {
|
|
|
34853
34897
|
const existing = await this.readDraw(client, args.creditId, args.drawId);
|
|
34854
34898
|
if (existing) {
|
|
34855
34899
|
const recordedJobId = existing.job_id ?? null;
|
|
34856
|
-
|
|
34900
|
+
const holdMicro = toSafeInt(existing.held_micro ?? existing.amount_micro);
|
|
34901
|
+
if (holdMicro !== args.amountMicro || recordedJobId !== jobId) {
|
|
34857
34902
|
throw new CreditLedgerError(
|
|
34858
34903
|
"draw_conflict",
|
|
34859
34904
|
`draw ${args.drawId} on credit ${args.creditId} was recorded with different parameters`,
|
|
34860
34905
|
{
|
|
34861
|
-
expectedAmountMicro:
|
|
34906
|
+
expectedAmountMicro: holdMicro,
|
|
34862
34907
|
expectedJobId: recordedJobId
|
|
34863
34908
|
}
|
|
34864
34909
|
);
|
|
@@ -35193,7 +35238,7 @@ var CreditLedger = class {
|
|
|
35193
35238
|
throw new CreditLedgerError("draw_not_found", "No draw with proven ownership matches this DVM.");
|
|
35194
35239
|
}
|
|
35195
35240
|
if (draw.status !== "settled") {
|
|
35196
|
-
throw new CreditLedgerError("draw_not_completed",
|
|
35241
|
+
throw new CreditLedgerError("draw_not_completed", DRAW_NOT_SETTLED_REFUSAL);
|
|
35197
35242
|
}
|
|
35198
35243
|
const nowMs = args.nowMs ?? Date.now();
|
|
35199
35244
|
const drained = await client.query(`SELECT 1 FROM credit_drains d
|
|
@@ -35223,7 +35268,7 @@ var CreditLedger = class {
|
|
|
35223
35268
|
const originalMicro = toSafeInt(draw.amount_micro);
|
|
35224
35269
|
const amountMicro = args.amountMicro ?? originalMicro - before;
|
|
35225
35270
|
if (amountMicro <= 0 || amountMicro > originalMicro - before) {
|
|
35226
|
-
throw new CreditLedgerError("refund_exceeds_draw",
|
|
35271
|
+
throw new CreditLedgerError("refund_exceeds_draw", REFUND_EXCEEDS_SETTLED_REFUSAL);
|
|
35227
35272
|
}
|
|
35228
35273
|
const after = before + amountMicro;
|
|
35229
35274
|
if (!isFundingRail(credit.rail)) {
|
|
@@ -35302,20 +35347,55 @@ var CreditLedger = class {
|
|
|
35302
35347
|
* receipt chain countersigns. Idempotent: settling a settled draw returns
|
|
35303
35348
|
* the original tuple. A released draw cannot be settled
|
|
35304
35349
|
* (`invalid_draw_state`) — release-then-settle would debit money the caller
|
|
35305
|
-
* was already told is theirs again.
|
|
35350
|
+
* was already told is theirs again. Neither can a partly settled one: it
|
|
35351
|
+
* already charged a different figure.
|
|
35306
35352
|
*
|
|
35307
35353
|
* Deliberately **no expiry check** here (nor on `release`): a job accepted
|
|
35308
35354
|
* pre-expiry routinely reaches its terminal post-expiry, and refusing would
|
|
35309
35355
|
* leak the hold forever. Expiry gates new draws only.
|
|
35310
35356
|
*/
|
|
35311
35357
|
async settle(args) {
|
|
35312
|
-
|
|
35358
|
+
return this.resolveTerminal(args, "hold");
|
|
35359
|
+
}
|
|
35360
|
+
/**
|
|
35361
|
+
* Release a pending draw: the hold evaporates, the balance is untouched —
|
|
35362
|
+
* this is how "no debit on job failure" is mechanically real (the credit lifecycle contract).
|
|
35363
|
+
* Idempotent: releasing a released draw returns the original tuple. A
|
|
35364
|
+
* settled draw cannot be released (`invalid_draw_state`) — un-settling
|
|
35365
|
+
* booked revenue is a reconciliation problem, not a ledger verb.
|
|
35366
|
+
*/
|
|
35367
|
+
async release(args) {
|
|
35368
|
+
return this.resolveTerminal(args, 0);
|
|
35369
|
+
}
|
|
35370
|
+
/**
|
|
35371
|
+
* Settle `settleMicro` of a pending draw and release the rest, in one terminal step under
|
|
35372
|
+
* the credit lock. Zero is `release`; the whole hold is `settle`. Between them the draw row
|
|
35373
|
+
* is rewritten down to the settled part (amount, balance-after, rail value), the hold and
|
|
35374
|
+
* the released remainder are kept beside it, and only the settled part debits the balance,
|
|
35375
|
+
* depletes funding lots (oldest first) and consumes a Tempo channel. Everything that charges
|
|
35376
|
+
* money off a settled draw then charges the settled part alone.
|
|
35377
|
+
*
|
|
35378
|
+
* `settleMicro` is micro-units of the draw's currency: a safe integer from zero to the hold.
|
|
35379
|
+
* A replay with the recorded figure changes nothing; a different figure is
|
|
35380
|
+
* `invalid_draw_state`. A frozen card credit still resolves, like `settle` and `release`.
|
|
35381
|
+
*/
|
|
35382
|
+
async resolveDraw(args) {
|
|
35383
|
+
assertSettleMicro(args.settleMicro);
|
|
35384
|
+
return this.resolveTerminal(args, args.settleMicro);
|
|
35385
|
+
}
|
|
35386
|
+
/**
|
|
35387
|
+
* A settle on a Tempo session credit runs under the channel row, ahead of the credit lock,
|
|
35388
|
+
* so the channel consumes exactly what the ledger settles. A release consumes nothing and
|
|
35389
|
+
* takes the credit lock alone.
|
|
35390
|
+
*/
|
|
35391
|
+
async resolveTerminal(args, request) {
|
|
35392
|
+
if (request === 0 || !this.tempoSessionStore) return this.resolveUnderCreditLock({ ...args, request });
|
|
35313
35393
|
const { rows: rows2 } = await this.pool.query(
|
|
35314
35394
|
`SELECT tempo_channel_id FROM credits WHERE credit_id = $1`,
|
|
35315
35395
|
[args.creditId]
|
|
35316
35396
|
);
|
|
35317
35397
|
const channelId = rows2[0]?.tempo_channel_id;
|
|
35318
|
-
if (!channelId) return this.
|
|
35398
|
+
if (!channelId) return this.resolveUnderCreditLock({ ...args, request });
|
|
35319
35399
|
return this.tempoSessionStore.withTerminalConsumption(channelId, async (tx, lifecycle) => {
|
|
35320
35400
|
const credit = await this.lockCreditRow(tx, args.creditId);
|
|
35321
35401
|
const draw = await this.readDraw(tx, args.creditId, args.drawId);
|
|
@@ -35325,22 +35405,18 @@ var CreditLedger = class {
|
|
|
35325
35405
|
`draw ${args.drawId} not found on credit ${args.creditId}`
|
|
35326
35406
|
);
|
|
35327
35407
|
}
|
|
35328
|
-
|
|
35329
|
-
if (drawNative === null) {
|
|
35408
|
+
if (draw.draw_native === null) {
|
|
35330
35409
|
throw new CreditLedgerError(
|
|
35331
35410
|
"invalid_basis",
|
|
35332
35411
|
`Tempo session draw ${args.drawId} has no native value to consume`
|
|
35333
35412
|
);
|
|
35334
35413
|
}
|
|
35335
35414
|
if (draw.status === "settled") {
|
|
35336
|
-
const value2 = await this.resolveDrawLocked(tx, credit, { ...args,
|
|
35337
|
-
return { value: value2, amount:
|
|
35415
|
+
const value2 = await this.resolveDrawLocked(tx, credit, { ...args, request });
|
|
35416
|
+
return { value: value2, amount: 0n, consume: false };
|
|
35338
35417
|
}
|
|
35339
35418
|
if (credit.status === "unbacked") {
|
|
35340
|
-
const value2 = await this.resolveDrawLocked(tx, credit, {
|
|
35341
|
-
...args,
|
|
35342
|
-
to: "released"
|
|
35343
|
-
});
|
|
35419
|
+
const value2 = await this.resolveDrawLocked(tx, credit, { ...args, request: 0 });
|
|
35344
35420
|
return { value: value2, amount: 0n, consume: false };
|
|
35345
35421
|
}
|
|
35346
35422
|
const closing = lifecycle.finalized || lifecycle.closeRequestedAt !== 0n;
|
|
@@ -35352,30 +35428,17 @@ var CreditLedger = class {
|
|
|
35352
35428
|
`Tempo channel settlement has not yet covered draw ${args.drawId}`
|
|
35353
35429
|
);
|
|
35354
35430
|
}
|
|
35355
|
-
const value2 = await this.resolveDrawLocked(tx, credit, {
|
|
35356
|
-
...args,
|
|
35357
|
-
to: "released"
|
|
35358
|
-
});
|
|
35431
|
+
const value2 = await this.resolveDrawLocked(tx, credit, { ...args, request: 0 });
|
|
35359
35432
|
return { value: value2, amount: 0n, consume: false };
|
|
35360
35433
|
}
|
|
35361
|
-
const value = await this.resolveDrawLocked(tx, credit, { ...args,
|
|
35434
|
+
const value = await this.resolveDrawLocked(tx, credit, { ...args, request });
|
|
35362
35435
|
return {
|
|
35363
35436
|
value,
|
|
35364
|
-
amount: drawNative,
|
|
35437
|
+
amount: BigInt(value.railValue.drawNative ?? 0),
|
|
35365
35438
|
consume: !closing && !value.replayed
|
|
35366
35439
|
};
|
|
35367
35440
|
});
|
|
35368
35441
|
}
|
|
35369
|
-
/**
|
|
35370
|
-
* Release a pending draw: the hold evaporates, the balance is untouched —
|
|
35371
|
-
* this is how "no debit on job failure" is mechanically real (the credit lifecycle contract).
|
|
35372
|
-
* Idempotent: releasing a released draw returns the original tuple. A
|
|
35373
|
-
* settled draw cannot be released (`invalid_draw_state`) — un-settling
|
|
35374
|
-
* booked revenue is a reconciliation problem, not a ledger verb.
|
|
35375
|
-
*/
|
|
35376
|
-
async release(args) {
|
|
35377
|
-
return this.resolveDraw({ ...args, to: "released" });
|
|
35378
|
-
}
|
|
35379
35442
|
/**
|
|
35380
35443
|
* Record the fund-only replay key without moving money. A duplicate (credit_id, fund_id)
|
|
35381
35444
|
* raises funding_replayed. Compose this insert, fund and rail acceptance on the same
|
|
@@ -37011,11 +37074,7 @@ var CreditLedger = class {
|
|
|
37011
37074
|
);
|
|
37012
37075
|
}
|
|
37013
37076
|
}
|
|
37014
|
-
async
|
|
37015
|
-
if (args.tx) {
|
|
37016
|
-
const credit = await this.lockCreditRow(args.tx, args.creditId);
|
|
37017
|
-
return this.resolveDrawLocked(args.tx, credit, args);
|
|
37018
|
-
}
|
|
37077
|
+
async resolveUnderCreditLock(args) {
|
|
37019
37078
|
return this.withCreditLock(
|
|
37020
37079
|
args.creditId,
|
|
37021
37080
|
(client, credit) => this.resolveDrawLocked(client, credit, args)
|
|
@@ -37030,31 +37089,35 @@ var CreditLedger = class {
|
|
|
37030
37089
|
`draw ${args.drawId} not found on credit ${args.creditId}`
|
|
37031
37090
|
);
|
|
37032
37091
|
}
|
|
37092
|
+
const request = credit.status === "unbacked" && draw.status !== "settled" ? 0 : args.request;
|
|
37093
|
+
const plan = planDrawResolution(
|
|
37094
|
+
{
|
|
37095
|
+
drawId: args.drawId,
|
|
37096
|
+
status: draw.status,
|
|
37097
|
+
amountMicro: toSafeInt(draw.amount_micro),
|
|
37098
|
+
heldMicro: draw.held_micro === null || draw.held_micro === void 0 ? null : toSafeInt(draw.held_micro)
|
|
37099
|
+
},
|
|
37100
|
+
request
|
|
37101
|
+
);
|
|
37033
37102
|
let balanceMicro = toSafeInt(credit.balance_micro);
|
|
37034
|
-
|
|
37035
|
-
if (draw.status === args.to) {
|
|
37036
|
-
replayed = true;
|
|
37037
|
-
} else if (draw.status !== "pending") {
|
|
37038
|
-
throw new CreditLedgerError(
|
|
37039
|
-
"invalid_draw_state",
|
|
37040
|
-
`cannot ${args.to === "settled" ? "settle" : "release"} draw ${args.drawId}: status is ${draw.status}`,
|
|
37041
|
-
{ currentStatus: draw.status }
|
|
37042
|
-
);
|
|
37043
|
-
} else {
|
|
37103
|
+
if (!plan.replay) {
|
|
37044
37104
|
await client.query(
|
|
37045
37105
|
`UPDATE credit_draws SET status = $3, resolved_at = $4
|
|
37046
37106
|
WHERE credit_id = $1 AND draw_id = $2`,
|
|
37047
|
-
[args.creditId, args.drawId,
|
|
37107
|
+
[args.creditId, args.drawId, plan.status, nowMs]
|
|
37048
37108
|
);
|
|
37049
|
-
if (
|
|
37050
|
-
const
|
|
37051
|
-
|
|
37109
|
+
if (plan.status === "settled") {
|
|
37110
|
+
const holdMicro = toSafeInt(draw.amount_micro);
|
|
37111
|
+
const settleMicro = plan.settleMicro;
|
|
37112
|
+
balanceMicro -= settleMicro;
|
|
37052
37113
|
const forecastMsats = toSafeInt(draw.draw_msats);
|
|
37053
|
-
|
|
37114
|
+
const holdNative = draw.draw_native === null ? null : toSafeInt(draw.draw_native);
|
|
37115
|
+
const settledNative = holdNative === null ? null : settledShare(holdNative, settleMicro, holdMicro);
|
|
37116
|
+
let settledMsats = settledShare(forecastMsats, settleMicro, holdMicro);
|
|
37054
37117
|
if (isNonChannelBitcoinRail(credit.rail)) {
|
|
37055
|
-
const depletion = depleteLots(await this.openLots(client, args.creditId),
|
|
37056
|
-
const inKindMsats = inKindDrawMsats(depletion,
|
|
37057
|
-
settledMsats = inKindMsats ??
|
|
37118
|
+
const depletion = depleteLots(await this.openLots(client, args.creditId), settleMicro);
|
|
37119
|
+
const inKindMsats = inKindDrawMsats(depletion, settleMicro);
|
|
37120
|
+
settledMsats = inKindMsats ?? settledMsats;
|
|
37058
37121
|
await client.query(
|
|
37059
37122
|
`UPDATE credit_draws SET settled_sats = $3
|
|
37060
37123
|
WHERE credit_id = $1 AND draw_id = $2`,
|
|
@@ -37062,6 +37125,33 @@ var CreditLedger = class {
|
|
|
37062
37125
|
);
|
|
37063
37126
|
await this.applyLotDebits(client, depletion.debits, -1);
|
|
37064
37127
|
}
|
|
37128
|
+
if (plan.partial) {
|
|
37129
|
+
const releasedMicro = holdMicro - settleMicro;
|
|
37130
|
+
const releasedNative = holdNative === null ? null : holdNative - (settledNative ?? 0);
|
|
37131
|
+
const balanceAfterMicro = toSafeInt(toSafeInt(draw.balance_after_micro) + releasedMicro);
|
|
37132
|
+
await client.query(
|
|
37133
|
+
`UPDATE credit_draws
|
|
37134
|
+
SET amount_micro = $3, balance_after_micro = $4, draw_native = $5,
|
|
37135
|
+
held_micro = $6, released_micro = $7, released_native = $8
|
|
37136
|
+
WHERE credit_id = $1 AND draw_id = $2`,
|
|
37137
|
+
[
|
|
37138
|
+
args.creditId,
|
|
37139
|
+
args.drawId,
|
|
37140
|
+
settleMicro,
|
|
37141
|
+
balanceAfterMicro,
|
|
37142
|
+
settledNative,
|
|
37143
|
+
holdMicro,
|
|
37144
|
+
releasedMicro,
|
|
37145
|
+
releasedNative
|
|
37146
|
+
]
|
|
37147
|
+
);
|
|
37148
|
+
draw.amount_micro = String(settleMicro);
|
|
37149
|
+
draw.balance_after_micro = String(balanceAfterMicro);
|
|
37150
|
+
draw.draw_native = settledNative === null ? null : String(settledNative);
|
|
37151
|
+
draw.held_micro = String(holdMicro);
|
|
37152
|
+
draw.released_micro = String(releasedMicro);
|
|
37153
|
+
draw.released_native = releasedNative === null ? null : String(releasedNative);
|
|
37154
|
+
}
|
|
37065
37155
|
if (settledMsats !== forecastMsats) {
|
|
37066
37156
|
await client.query(
|
|
37067
37157
|
`UPDATE credit_draws SET draw_msats = $3, allocated_msats = $4
|
|
@@ -37078,19 +37168,19 @@ var CreditLedger = class {
|
|
|
37078
37168
|
native_remaining = CASE WHEN native_remaining IS NULL THEN NULL
|
|
37079
37169
|
ELSE GREATEST(native_remaining - $4, 0) END
|
|
37080
37170
|
WHERE credit_id = $1`,
|
|
37081
|
-
[args.creditId, balanceMicro, settledMsats,
|
|
37171
|
+
[args.creditId, balanceMicro, settledMsats, settledNative ?? 0]
|
|
37082
37172
|
);
|
|
37083
37173
|
}
|
|
37084
37174
|
}
|
|
37085
37175
|
const availableMicro = credit.status === "unbacked" ? 0 : balanceMicro - (await this.pendingSums(client, args.creditId)).micro;
|
|
37086
37176
|
const resolution = {
|
|
37087
37177
|
...drawResultFromRow(draw, credit),
|
|
37088
|
-
status:
|
|
37089
|
-
replayed,
|
|
37178
|
+
status: plan.status,
|
|
37179
|
+
replayed: plan.replay,
|
|
37090
37180
|
availableMicro,
|
|
37091
|
-
resolvedAt:
|
|
37181
|
+
resolvedAt: plan.replay ? Number(draw.resolved_at ?? nowMs) : nowMs
|
|
37092
37182
|
};
|
|
37093
|
-
if (!
|
|
37183
|
+
if (!plan.replay && plan.status === "released" && resolution.amountMicro > 0 && args.releaseOutbox) {
|
|
37094
37184
|
await args.releaseOutbox.enqueue(client, {
|
|
37095
37185
|
dvmId: args.releaseOutbox.dvmId,
|
|
37096
37186
|
creditId: resolution.creditId,
|
|
@@ -37396,7 +37486,14 @@ function drawResultFromRow(row, basis) {
|
|
|
37396
37486
|
status: row.status,
|
|
37397
37487
|
replayed: false,
|
|
37398
37488
|
railValue: railValueFromRow(row, basis),
|
|
37399
|
-
resolvedAt: row.resolved_at === null ? null : toSafeInt(row.resolved_at)
|
|
37489
|
+
resolvedAt: row.resolved_at === null ? null : toSafeInt(row.resolved_at),
|
|
37490
|
+
...typeof row.held_micro === "string" && {
|
|
37491
|
+
partialSettle: {
|
|
37492
|
+
heldMicro: toSafeInt(row.held_micro),
|
|
37493
|
+
releasedMicro: toSafeInt(row.released_micro ?? 0),
|
|
37494
|
+
releasedNative: typeof row.released_native === "string" ? toSafeInt(row.released_native) : null
|
|
37495
|
+
}
|
|
37496
|
+
}
|
|
37400
37497
|
};
|
|
37401
37498
|
}
|
|
37402
37499
|
function drawRecordFromRow(row, basis) {
|
|
@@ -37564,7 +37661,7 @@ function expiryReleaseReport(dvmId, row) {
|
|
|
37564
37661
|
};
|
|
37565
37662
|
}
|
|
37566
37663
|
|
|
37567
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
37664
|
+
// node_modules/@dvmkit/sdk/dist/chunk-JSVSJZQJ.js
|
|
37568
37665
|
import { randomUUID as randomUUID4 } from "crypto";
|
|
37569
37666
|
var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
37570
37667
|
/**
|
|
@@ -37617,7 +37714,7 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
|
37617
37714
|
throw new CreditLedgerError("draw_not_found", "No unique job-bound draw matches this selector.");
|
|
37618
37715
|
}
|
|
37619
37716
|
const { credit, draw } = matches[0];
|
|
37620
|
-
if (draw.status !== "settled") throw new CreditLedgerError("draw_not_completed",
|
|
37717
|
+
if (draw.status !== "settled") throw new CreditLedgerError("draw_not_completed", DRAW_NOT_SETTLED_REFUSAL);
|
|
37621
37718
|
const nowMs = args.nowMs ?? Date.now();
|
|
37622
37719
|
const lastDrain = [...credit.drains.values()].filter((drain) => drain.status !== "released").sort((a, b2) => b2.ledgerSeq - a.ledgerSeq)[0];
|
|
37623
37720
|
const drained = lastDrain && lastDrain.balanceAfterMicro === 0 && (credit.lastFundingLedgerSeq === null || credit.lastFundingLedgerSeq < lastDrain.ledgerSeq) && ![...credit.draws.values()].some((later) => later.ledgerSeq > lastDrain.ledgerSeq && later.amountMicro > 0) && ![...this.fundings.values()].some((funding) => funding.creditId === credit.creditId && funding.ledgerSeq !== null && funding.ledgerSeq >= lastDrain.ledgerSeq && funding.amountMicro > 0);
|
|
@@ -37636,7 +37733,7 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
|
37636
37733
|
const before = [...this.refunds.values()].reduce((sum2, refund) => sum2 + (refund.result.creditId === credit.creditId && refund.result.drawId === draw.drawId ? refund.result.amountMicro : 0), 0);
|
|
37637
37734
|
const amountMicro = args.amountMicro ?? draw.amountMicro - before;
|
|
37638
37735
|
if (amountMicro <= 0 || amountMicro > draw.amountMicro - before) {
|
|
37639
|
-
throw new CreditLedgerError("refund_exceeds_draw",
|
|
37736
|
+
throw new CreditLedgerError("refund_exceeds_draw", REFUND_EXCEEDS_SETTLED_REFUSAL);
|
|
37640
37737
|
}
|
|
37641
37738
|
if (!isFundingRail(credit.rail)) throw new CreditLedgerError("credit_refund_basis_unavailable", "The original funding rail is not recorded on this older credit.");
|
|
37642
37739
|
const bitcoin = isNonChannelBitcoinRail(credit.rail);
|
|
@@ -37706,15 +37803,24 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
|
37706
37803
|
return run(() => this.growDrawSync(args, blocking));
|
|
37707
37804
|
}
|
|
37708
37805
|
settle(args) {
|
|
37806
|
+
return run(() => this.resolveTerminal(args, "hold"));
|
|
37807
|
+
}
|
|
37808
|
+
release(args) {
|
|
37809
|
+
return run(() => this.resolve({ ...args, request: 0 }));
|
|
37810
|
+
}
|
|
37811
|
+
/** See {@link CreditLedger.resolveDraw}. */
|
|
37812
|
+
resolveDraw(args) {
|
|
37709
37813
|
return run(() => {
|
|
37710
|
-
|
|
37711
|
-
|
|
37712
|
-
const to = draw?.status === "settled" ? "settled" : credit.status === "unbacked" ? "released" : "settled";
|
|
37713
|
-
return this.resolve({ ...args, to });
|
|
37814
|
+
assertSettleMicro(args.settleMicro);
|
|
37815
|
+
return this.resolveTerminal(args, args.settleMicro);
|
|
37714
37816
|
});
|
|
37715
37817
|
}
|
|
37716
|
-
|
|
37717
|
-
|
|
37818
|
+
/** A settle on an unbacked credit releases instead: its backing is gone. */
|
|
37819
|
+
resolveTerminal(args, request) {
|
|
37820
|
+
const credit = this.requireCredit(args.creditId);
|
|
37821
|
+
const draw = credit.draws.get(args.drawId);
|
|
37822
|
+
const unbacked = request !== 0 && draw?.status !== "settled" && credit.status === "unbacked";
|
|
37823
|
+
return this.resolve({ ...args, request: unbacked ? 0 : request });
|
|
37718
37824
|
}
|
|
37719
37825
|
recordFunding(args) {
|
|
37720
37826
|
return run(() => {
|
|
@@ -38126,11 +38232,12 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
|
38126
38232
|
const credit = this.requireCredit(args.creditId);
|
|
38127
38233
|
const existing = credit.draws.get(args.drawId);
|
|
38128
38234
|
if (existing) {
|
|
38129
|
-
|
|
38235
|
+
const holdMicro = existing.heldMicro ?? existing.amountMicro;
|
|
38236
|
+
if (holdMicro !== args.amountMicro || existing.jobId !== jobId) {
|
|
38130
38237
|
throw new CreditLedgerError(
|
|
38131
38238
|
"draw_conflict",
|
|
38132
38239
|
`draw ${args.drawId} on credit ${args.creditId} was recorded with different parameters`,
|
|
38133
|
-
{ expectedAmountMicro:
|
|
38240
|
+
{ expectedAmountMicro: holdMicro, expectedJobId: existing.jobId }
|
|
38134
38241
|
);
|
|
38135
38242
|
}
|
|
38136
38243
|
return { ...drawResult(existing, credit), replayed: true };
|
|
@@ -38804,40 +38911,50 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
|
|
|
38804
38911
|
`draw ${args.drawId} not found on credit ${args.creditId}`
|
|
38805
38912
|
);
|
|
38806
38913
|
}
|
|
38807
|
-
|
|
38808
|
-
|
|
38809
|
-
|
|
38810
|
-
|
|
38811
|
-
|
|
38812
|
-
|
|
38813
|
-
`cannot ${args.to === "settled" ? "settle" : "release"} draw ${args.drawId}: status is ${draw.status}`,
|
|
38814
|
-
{ currentStatus: draw.status }
|
|
38815
|
-
);
|
|
38816
|
-
} else {
|
|
38817
|
-
draw.status = args.to;
|
|
38914
|
+
const plan = planDrawResolution(
|
|
38915
|
+
{ drawId: draw.drawId, status: draw.status, amountMicro: draw.amountMicro, heldMicro: draw.heldMicro ?? null },
|
|
38916
|
+
args.request
|
|
38917
|
+
);
|
|
38918
|
+
if (!plan.replay) {
|
|
38919
|
+
draw.status = plan.status;
|
|
38818
38920
|
draw.resolvedAt = nowMs;
|
|
38819
|
-
if (
|
|
38820
|
-
|
|
38921
|
+
if (plan.status === "settled") {
|
|
38922
|
+
const holdMicro = draw.amountMicro;
|
|
38923
|
+
const settleMicro = plan.settleMicro;
|
|
38924
|
+
const forecastMsats = draw.drawMsats;
|
|
38925
|
+
const holdNative = draw.drawNative;
|
|
38926
|
+
const settledNative = holdNative === null ? null : settledShare(holdNative, settleMicro, holdMicro);
|
|
38927
|
+
let settledMsats = settledShare(forecastMsats, settleMicro, holdMicro);
|
|
38928
|
+
credit.balanceMicro -= settleMicro;
|
|
38821
38929
|
if (isNonChannelBitcoinRail(credit.rail)) {
|
|
38822
|
-
const depletion = depleteLots(openLots(credit),
|
|
38823
|
-
const
|
|
38824
|
-
draw.settledSats =
|
|
38825
|
-
|
|
38826
|
-
draw.allocatedMsats = draw.drawMsats;
|
|
38827
|
-
draw.drawMsats = settledMsats;
|
|
38828
|
-
}
|
|
38930
|
+
const depletion = depleteLots(openLots(credit), settleMicro);
|
|
38931
|
+
const inKindMsats = inKindDrawMsats(depletion, settleMicro);
|
|
38932
|
+
draw.settledSats = inKindMsats === null ? null : inKindMsats / 1e3;
|
|
38933
|
+
settledMsats = inKindMsats ?? settledMsats;
|
|
38829
38934
|
applyLotDebits(credit, depletion.debits, -1);
|
|
38830
38935
|
}
|
|
38831
|
-
|
|
38936
|
+
if (plan.partial) {
|
|
38937
|
+
draw.heldMicro = holdMicro;
|
|
38938
|
+
draw.releasedMicro = holdMicro - settleMicro;
|
|
38939
|
+
draw.releasedNative = holdNative === null ? null : holdNative - (settledNative ?? 0);
|
|
38940
|
+
draw.amountMicro = settleMicro;
|
|
38941
|
+
draw.balanceAfterMicro += holdMicro - settleMicro;
|
|
38942
|
+
draw.drawNative = settledNative;
|
|
38943
|
+
}
|
|
38944
|
+
if (settledMsats !== forecastMsats) {
|
|
38945
|
+
draw.allocatedMsats = forecastMsats;
|
|
38946
|
+
draw.drawMsats = settledMsats;
|
|
38947
|
+
}
|
|
38948
|
+
credit.msatsRemaining = Math.max(0, credit.msatsRemaining - settledMsats);
|
|
38832
38949
|
if (credit.nativeRemaining !== null) {
|
|
38833
|
-
credit.nativeRemaining = Math.max(0, credit.nativeRemaining - (
|
|
38950
|
+
credit.nativeRemaining = Math.max(0, credit.nativeRemaining - (settledNative ?? 0));
|
|
38834
38951
|
}
|
|
38835
38952
|
}
|
|
38836
38953
|
}
|
|
38837
38954
|
return {
|
|
38838
38955
|
...drawResult(draw, credit),
|
|
38839
|
-
status:
|
|
38840
|
-
replayed,
|
|
38956
|
+
status: plan.status,
|
|
38957
|
+
replayed: plan.replay,
|
|
38841
38958
|
availableMicro: credit.status === "unbacked" ? 0 : credit.balanceMicro - pendingSums(credit).micro,
|
|
38842
38959
|
resolvedAt: draw.resolvedAt ?? nowMs
|
|
38843
38960
|
};
|
|
@@ -38956,7 +39073,14 @@ function drawResult(draw, credit) {
|
|
|
38956
39073
|
status: draw.status,
|
|
38957
39074
|
replayed: false,
|
|
38958
39075
|
railValue: railValue(draw, credit),
|
|
38959
|
-
resolvedAt: draw.resolvedAt
|
|
39076
|
+
resolvedAt: draw.resolvedAt,
|
|
39077
|
+
...draw.heldMicro !== void 0 && {
|
|
39078
|
+
partialSettle: {
|
|
39079
|
+
heldMicro: draw.heldMicro,
|
|
39080
|
+
releasedMicro: draw.releasedMicro ?? 0,
|
|
39081
|
+
releasedNative: draw.releasedNative ?? null
|
|
39082
|
+
}
|
|
39083
|
+
}
|
|
38960
39084
|
};
|
|
38961
39085
|
}
|
|
38962
39086
|
function drawRecord(draw, credit) {
|
|
@@ -39017,8 +39141,15 @@ function assertAmount2(amountMicro, opts) {
|
|
|
39017
39141
|
}
|
|
39018
39142
|
}
|
|
39019
39143
|
|
|
39020
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
39144
|
+
// node_modules/@dvmkit/sdk/dist/chunk-BLSRYX3M.js
|
|
39021
39145
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
39146
|
+
var ASK_EXPIRY_GRACE_MS = 3e4;
|
|
39147
|
+
function askExpiryAtMs(expiresAtMs) {
|
|
39148
|
+
return expiresAtMs + ASK_EXPIRY_GRACE_MS;
|
|
39149
|
+
}
|
|
39150
|
+
function askExpired(expiresAtMs, nowMs) {
|
|
39151
|
+
return expiresAtMs !== void 0 && Number.isSafeInteger(expiresAtMs) && nowMs >= askExpiryAtMs(expiresAtMs);
|
|
39152
|
+
}
|
|
39022
39153
|
function toJobRecord(job) {
|
|
39023
39154
|
return {
|
|
39024
39155
|
id: job.id,
|
|
@@ -39069,6 +39200,9 @@ function toJobRecord(job) {
|
|
|
39069
39200
|
askedTopUpCurrency: job.askedTopUpCurrency,
|
|
39070
39201
|
topUpCapUnenforcedReason: job.topUpCapUnenforcedReason,
|
|
39071
39202
|
requiredMsats: job.requiredMsats,
|
|
39203
|
+
pieces: job.pieces,
|
|
39204
|
+
settlement: job.settlement,
|
|
39205
|
+
pieceEnding: job.pieceEnding,
|
|
39072
39206
|
receipt: job.receipt,
|
|
39073
39207
|
stepCache: job.stepCache.serialize(),
|
|
39074
39208
|
state: job.state,
|
|
@@ -39126,6 +39260,8 @@ function fromJobRecord(record2) {
|
|
|
39126
39260
|
askedTopUpCurrency: record2.askedTopUpCurrency,
|
|
39127
39261
|
topUpCapUnenforcedReason: record2.topUpCapUnenforcedReason,
|
|
39128
39262
|
requiredMsats: record2.requiredMsats,
|
|
39263
|
+
pieces: record2.pieces ? structuredClone(record2.pieces) : void 0,
|
|
39264
|
+
settlement: record2.settlement,
|
|
39129
39265
|
receipt: record2.receipt,
|
|
39130
39266
|
listeners: /* @__PURE__ */ new Set(),
|
|
39131
39267
|
abort: new AbortController(),
|
|
@@ -39151,6 +39287,14 @@ var JobCancelledError = class extends Error {
|
|
|
39151
39287
|
this.name = "JobCancelledError";
|
|
39152
39288
|
}
|
|
39153
39289
|
};
|
|
39290
|
+
var AskAlreadyOpenError = class extends Error {
|
|
39291
|
+
code = "ask_already_open";
|
|
39292
|
+
status = 409;
|
|
39293
|
+
constructor(jobId) {
|
|
39294
|
+
super(`job ${jobId} already has an open payment request; wait for it to be paid before asking again`);
|
|
39295
|
+
this.name = "AskAlreadyOpenError";
|
|
39296
|
+
}
|
|
39297
|
+
};
|
|
39154
39298
|
function providerMessage(job, type, content) {
|
|
39155
39299
|
if (job.replayProviderSkip > 0) {
|
|
39156
39300
|
job.replayProviderSkip--;
|
|
@@ -39168,15 +39312,19 @@ function providerMessage(job, type, content) {
|
|
|
39168
39312
|
awaitingInput: job.status === "awaiting-input",
|
|
39169
39313
|
pendingPaymentDelta,
|
|
39170
39314
|
pendingMppChallengeIds,
|
|
39171
|
-
|
|
39315
|
+
// An ask that withheld x402 still binds the job to an unadvertised nonce, so a stray x402
|
|
39316
|
+
// payment is refused before it settles; that nonce is on the job, not in the content.
|
|
39317
|
+
pendingX402Nonce: typeof paymentRequest.x402?.nonce === "string" ? paymentRequest.x402.nonce : job.pendingX402Nonce,
|
|
39172
39318
|
pendingX402AmountUsdcMicro: typeof paymentRequest.x402?.required_usdc_micro === "string" ? paymentRequest.x402.required_usdc_micro : void 0,
|
|
39173
39319
|
// read off the job rather than the content — the fiat envelope
|
|
39174
39320
|
// is ledger state, not part of the wire shape, and `requestPayment` has
|
|
39175
39321
|
// already pinned it on the job by the time this fires (same ordering the
|
|
39176
39322
|
// `pendingPaymentMsats` comment above describes).
|
|
39177
39323
|
pendingPaymentFiatMicro: job.pendingPaymentFiatMicro,
|
|
39178
|
-
pendingPaymentFiatCurrency: job.pendingPaymentFiatCurrency
|
|
39324
|
+
pendingPaymentFiatCurrency: job.pendingPaymentFiatCurrency,
|
|
39325
|
+
finishedChargeMicro: job.finishingChargeMicro
|
|
39179
39326
|
});
|
|
39327
|
+
job.finishingChargeMicro = void 0;
|
|
39180
39328
|
return;
|
|
39181
39329
|
}
|
|
39182
39330
|
job.messageAppender?.(msg, type === "prompt" ? { awaitingInput: job.status === "awaiting-input" } : void 0);
|
|
@@ -39262,12 +39410,23 @@ function callerDeadline(job, legacyTimeoutMs) {
|
|
|
39262
39410
|
}
|
|
39263
39411
|
const asks = [...prompts.values(), ...payment && (job.pendingPaymentMsats ?? 0) > 0 ? [payment] : []];
|
|
39264
39412
|
const deadlines = asks.map((ask) => ask.content.expires_at_ms).filter((stamp) => Number.isSafeInteger(stamp));
|
|
39265
|
-
if (deadlines.length > 0) return Math.min(...deadlines);
|
|
39413
|
+
if (deadlines.length > 0) return askExpiryAtMs(Math.min(...deadlines));
|
|
39266
39414
|
if (job.status === "awaiting-input" && legacyTimeoutMs !== void 0 && (asks.length > 0 || job.messages.length === 0)) {
|
|
39267
39415
|
return (job.awaitingInputAtMs ?? job.lastActivityAt) + legacyTimeoutMs;
|
|
39268
39416
|
}
|
|
39269
39417
|
return void 0;
|
|
39270
39418
|
}
|
|
39419
|
+
function hasOpenAsk(job) {
|
|
39420
|
+
if (isTerminal(job.status)) return false;
|
|
39421
|
+
const prompts = /* @__PURE__ */ new Set();
|
|
39422
|
+
let paymentAsked = false;
|
|
39423
|
+
for (const message of job.messages) {
|
|
39424
|
+
if (message.from === "provider" && message.type === "prompt") prompts.add(message.content.id);
|
|
39425
|
+
if (message.from === "provider" && message.type === "payment-request") paymentAsked = true;
|
|
39426
|
+
if (message.from === "requester" && message.type === "response") prompts.delete(message.content.prompt_id);
|
|
39427
|
+
}
|
|
39428
|
+
return prompts.size > 0 || paymentAsked && (job.pendingPaymentMsats ?? 0) > 0;
|
|
39429
|
+
}
|
|
39271
39430
|
function hasCallerDeadline(messages) {
|
|
39272
39431
|
return messages.some((message) => message.from === "provider" && (message.type === "prompt" || message.type === "payment-request") && Number.isSafeInteger(message.content.expires_at_ms));
|
|
39273
39432
|
}
|
|
@@ -39327,8 +39486,185 @@ function applyContentHoldMutation(job, history, mutation) {
|
|
|
39327
39486
|
});
|
|
39328
39487
|
return result;
|
|
39329
39488
|
}
|
|
39489
|
+
var JobEndedError = class extends Error {
|
|
39490
|
+
constructor(jobId) {
|
|
39491
|
+
super(`job ${jobId} has ended; it takes no further asks`);
|
|
39492
|
+
this.jobId = jobId;
|
|
39493
|
+
this.name = "JobEndedError";
|
|
39494
|
+
}
|
|
39495
|
+
jobId;
|
|
39496
|
+
code = "job_ended";
|
|
39497
|
+
};
|
|
39498
|
+
function accumulateAskedTopUp(prior, ask) {
|
|
39499
|
+
const poisoned = (reason) => ({
|
|
39500
|
+
micro: UNCAPPABLE_ASK_TOTAL,
|
|
39501
|
+
currency: prior.currency,
|
|
39502
|
+
reason: prior.reason ?? reason
|
|
39503
|
+
});
|
|
39504
|
+
if (prior.micro === UNCAPPABLE_ASK_TOTAL) {
|
|
39505
|
+
return { micro: prior.micro, currency: prior.currency, reason: prior.reason };
|
|
39506
|
+
}
|
|
39507
|
+
if (ask.micro === void 0) return poisoned("ask_unpriceable");
|
|
39508
|
+
if (prior.micro === void 0) {
|
|
39509
|
+
return { micro: ask.micro, currency: ask.currency, reason: prior.reason };
|
|
39510
|
+
}
|
|
39511
|
+
if (prior.currency !== ask.currency) return poisoned("ask_currency_switch");
|
|
39512
|
+
return { micro: prior.micro + ask.micro, currency: prior.currency, reason: prior.reason };
|
|
39513
|
+
}
|
|
39514
|
+
var UNCAPPABLE_ASK_TOTAL = -1;
|
|
39515
|
+
function isJobRetentionStore(store) {
|
|
39516
|
+
return "listJobsForRetention" in store && "redactJob" in store;
|
|
39517
|
+
}
|
|
39518
|
+
function isReceiptIssuingStore(store) {
|
|
39519
|
+
return "claimReceiptSeq" in store && "saveReceipt" in store;
|
|
39520
|
+
}
|
|
39521
|
+
function isStreamableJobStore(store) {
|
|
39522
|
+
return "appendOutgoing" in store && "recordInbound" in store && "verifyAndCredit" in store && "getVerifiedInbound" in store && "subscribeMessages" in store && "subscribeNotifications" in store && "getCounters" in store && "getMessages" in store && "cancelJob" in store && "initStreaming" in store;
|
|
39523
|
+
}
|
|
39524
|
+
function isStaleJobReapable(store) {
|
|
39525
|
+
return "findStaleJobs" in store && "cancelStaleJob" in store;
|
|
39526
|
+
}
|
|
39527
|
+
function runningPiece(pieces) {
|
|
39528
|
+
return pieces?.findLast((piece) => piece.state === "running");
|
|
39529
|
+
}
|
|
39530
|
+
function pieceCharge(piece) {
|
|
39531
|
+
if (piece.state !== "finished" && piece.state !== "stopped") return 0;
|
|
39532
|
+
return loweredCharge(piece, piece.chargeMicro) ?? piece.amountMicro;
|
|
39533
|
+
}
|
|
39534
|
+
function loweredCharge(piece, chargeMicro) {
|
|
39535
|
+
return chargeMicro !== void 0 && Number.isSafeInteger(chargeMicro) && chargeMicro >= 0 && chargeMicro < piece.amountMicro ? chargeMicro : void 0;
|
|
39536
|
+
}
|
|
39537
|
+
function appendPiece(pieces, amountMicro, paidSeq) {
|
|
39538
|
+
return [...pieces, { amountMicro, paidSeq, state: "running" }];
|
|
39539
|
+
}
|
|
39540
|
+
function finishRunningPiece(pieces, chargeMicro) {
|
|
39541
|
+
const running = runningPiece(pieces);
|
|
39542
|
+
return pieces.map((piece) => {
|
|
39543
|
+
if (piece !== running) return { ...piece };
|
|
39544
|
+
const lowered = loweredCharge(piece, chargeMicro);
|
|
39545
|
+
return { ...piece, state: "finished", ...lowered !== void 0 && { chargeMicro: lowered } };
|
|
39546
|
+
});
|
|
39547
|
+
}
|
|
39548
|
+
function chargedIfDeclinedMicro(pieces) {
|
|
39549
|
+
return (pieces ?? []).reduce((sum2, piece) => piece.state === "finished" ? sum2 + piece.amountMicro : sum2, 0);
|
|
39550
|
+
}
|
|
39551
|
+
function endPieces(pieces, ending) {
|
|
39552
|
+
if (pieces === void 0) {
|
|
39553
|
+
return {
|
|
39554
|
+
pieces: void 0,
|
|
39555
|
+
settlement: { whole: ending.kind === "release" ? "release" : "settle", stoppedPiece: ending.kind === "stop" }
|
|
39556
|
+
};
|
|
39557
|
+
}
|
|
39558
|
+
let stoppedPiece = false;
|
|
39559
|
+
const ended = pieces.map((piece) => {
|
|
39560
|
+
if (piece.state !== "running") return { ...piece };
|
|
39561
|
+
if (ending.kind === "stop") {
|
|
39562
|
+
stoppedPiece = true;
|
|
39563
|
+
return { ...piece, state: "stopped" };
|
|
39564
|
+
}
|
|
39565
|
+
if (ending.kind === "finish" && (ending.paidSeq === void 0 || ending.paidSeq === piece.paidSeq)) {
|
|
39566
|
+
const lowered = loweredCharge(piece, ending.chargeMicro);
|
|
39567
|
+
return { ...piece, state: "finished", ...lowered !== void 0 && { chargeMicro: lowered } };
|
|
39568
|
+
}
|
|
39569
|
+
return { ...piece, state: "released" };
|
|
39570
|
+
});
|
|
39571
|
+
return {
|
|
39572
|
+
pieces: ended,
|
|
39573
|
+
settlement: { chargedMicro: ended.reduce((sum2, piece) => sum2 + pieceCharge(piece), 0), stoppedPiece }
|
|
39574
|
+
};
|
|
39575
|
+
}
|
|
39576
|
+
function terminalEnding(record2) {
|
|
39577
|
+
return record2.pieceEnding ?? (record2.status === "completed" ? { kind: "finish" } : { kind: "release" });
|
|
39578
|
+
}
|
|
39579
|
+
function checkFinishedCharge(running, chargeMicro) {
|
|
39580
|
+
if (chargeMicro === void 0) return;
|
|
39581
|
+
if (!Number.isSafeInteger(chargeMicro) || chargeMicro < 0) {
|
|
39582
|
+
throw new RangeError(`finishedChargeMicro must be a non-negative integer of micro-units; got ${String(chargeMicro)}`);
|
|
39583
|
+
}
|
|
39584
|
+
if (running && chargeMicro > running.amountMicro) {
|
|
39585
|
+
throw new RangeError(
|
|
39586
|
+
`finishedChargeMicro ${chargeMicro} exceeds the running piece's price of ${running.amountMicro} micro-units`
|
|
39587
|
+
);
|
|
39588
|
+
}
|
|
39589
|
+
}
|
|
39590
|
+
function storedPieces(value) {
|
|
39591
|
+
if (typeof value === "string") return storedPieces(JSON.parse(value));
|
|
39592
|
+
return Array.isArray(value) ? value : void 0;
|
|
39593
|
+
}
|
|
39594
|
+
var PAYMENT_INTENT_LEASE_MS = 12e4;
|
|
39595
|
+
function decidePaymentDisposition(args) {
|
|
39596
|
+
if (args.status === "completed" || args.status === "failed" || args.status === "cancelled") {
|
|
39597
|
+
return { disposition: "balance", reason: "job_ended" };
|
|
39598
|
+
}
|
|
39599
|
+
if (!((args.pendingPaymentMsats ?? 0) > 0)) return { disposition: "balance", reason: "no_open_ask" };
|
|
39600
|
+
const expiresAtMs = args.ask?.content?.expires_at_ms;
|
|
39601
|
+
if (typeof expiresAtMs === "number" && askExpired(expiresAtMs, args.arrivedAtMs)) {
|
|
39602
|
+
return { disposition: "balance", reason: "ask_expired" };
|
|
39603
|
+
}
|
|
39604
|
+
return { disposition: "ask" };
|
|
39605
|
+
}
|
|
39606
|
+
var PaymentIntentOpenError = class extends Error {
|
|
39607
|
+
constructor(jobId, retryAtMs) {
|
|
39608
|
+
super(`job ${jobId} has a payment being verified; it cannot end before ${new Date(retryAtMs).toISOString()}`);
|
|
39609
|
+
this.jobId = jobId;
|
|
39610
|
+
this.retryAtMs = retryAtMs;
|
|
39611
|
+
this.name = "PaymentIntentOpenError";
|
|
39612
|
+
}
|
|
39613
|
+
jobId;
|
|
39614
|
+
retryAtMs;
|
|
39615
|
+
code = "payment_intent_open";
|
|
39616
|
+
};
|
|
39617
|
+
function isPaymentArrivalStore(store) {
|
|
39618
|
+
return "recordPaymentArrival" in store && "openPaymentIntentUntil" in store;
|
|
39619
|
+
}
|
|
39620
|
+
var PAYMENT_INTENT_POLL_MS = 100;
|
|
39621
|
+
var PAYMENT_INTENT_POLL_MAX_MS = 2e3;
|
|
39622
|
+
var PAYMENT_INTENT_REQUEST_WAIT_MS = 5e3;
|
|
39623
|
+
function paymentIntentOpen(error62) {
|
|
39624
|
+
if (error62 instanceof PaymentIntentOpenError) return error62;
|
|
39625
|
+
const cause = error62 instanceof Error ? error62.cause : void 0;
|
|
39626
|
+
return cause instanceof PaymentIntentOpenError ? cause : void 0;
|
|
39627
|
+
}
|
|
39628
|
+
function paymentIntentRetryDelayMs(retryAtMs, attempt, nowMs = Date.now()) {
|
|
39629
|
+
const backoff = Math.min(PAYMENT_INTENT_POLL_MAX_MS, PAYMENT_INTENT_POLL_MS * 2 ** Math.min(attempt, 16));
|
|
39630
|
+
return Math.max(1, Math.min(backoff, retryAtMs - nowMs));
|
|
39631
|
+
}
|
|
39632
|
+
async function afterPaymentIntents(write, opts = {}) {
|
|
39633
|
+
const started = performance.now();
|
|
39634
|
+
for (let attempt = 0; ; attempt++) {
|
|
39635
|
+
try {
|
|
39636
|
+
return await write();
|
|
39637
|
+
} catch (error62) {
|
|
39638
|
+
const open2 = paymentIntentOpen(error62);
|
|
39639
|
+
if (!open2) throw error62;
|
|
39640
|
+
await waitBeforeRetry(paymentIntentRetryDelayMs(open2.retryAtMs, attempt), started, opts.maxWaitMs, open2);
|
|
39641
|
+
}
|
|
39642
|
+
}
|
|
39643
|
+
}
|
|
39644
|
+
async function waitForPaymentIntents(store, jobId, opts = {}) {
|
|
39645
|
+
if (!isPaymentArrivalStore(store)) return;
|
|
39646
|
+
const started = performance.now();
|
|
39647
|
+
for (let attempt = 0; ; attempt++) {
|
|
39648
|
+
const until = await store.openPaymentIntentUntil(jobId, Date.now());
|
|
39649
|
+
if (until === void 0) return;
|
|
39650
|
+
await waitBeforeRetry(
|
|
39651
|
+
paymentIntentRetryDelayMs(until, attempt),
|
|
39652
|
+
started,
|
|
39653
|
+
opts.maxWaitMs,
|
|
39654
|
+
new PaymentIntentOpenError(jobId, until)
|
|
39655
|
+
);
|
|
39656
|
+
}
|
|
39657
|
+
}
|
|
39658
|
+
async function waitBeforeRetry(delayMs, started, maxWaitMs, open2) {
|
|
39659
|
+
if (maxWaitMs !== void 0) {
|
|
39660
|
+
const left = started + maxWaitMs - performance.now();
|
|
39661
|
+
if (left <= 0) throw open2;
|
|
39662
|
+
delayMs = Math.min(delayMs, left);
|
|
39663
|
+
}
|
|
39664
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
39665
|
+
}
|
|
39330
39666
|
|
|
39331
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
39667
|
+
// node_modules/@dvmkit/sdk/dist/chunk-6TUBMSP7.js
|
|
39332
39668
|
import { createHash as createHash6 } from "crypto";
|
|
39333
39669
|
var DEFAULT_BACKOFF_MS = [1e3, 4e3, 15e3, 3e4];
|
|
39334
39670
|
var ListenChannel = class {
|
|
@@ -39678,6 +40014,30 @@ var PostgresJobStore = class {
|
|
|
39678
40014
|
CONSTRAINT receipt_counter_singleton CHECK (id)
|
|
39679
40015
|
);
|
|
39680
40016
|
INSERT INTO receipt_counter (id, n) VALUES (TRUE, 0) ON CONFLICT (id) DO NOTHING;
|
|
40017
|
+
|
|
40018
|
+
-- One row per payment that reached recordPaymentArrival, written under
|
|
40019
|
+
-- the job row lock before verification. An unresolved row whose lease
|
|
40020
|
+
-- has not passed holds the job non-terminal; Tx C or a refusal resolves
|
|
40021
|
+
-- it. Kept after resolution as the arrival record.
|
|
40022
|
+
CREATE TABLE IF NOT EXISTS job_payment_intents (
|
|
40023
|
+
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
|
|
40024
|
+
seq INTEGER NOT NULL,
|
|
40025
|
+
arrived_at_ms BIGINT NOT NULL,
|
|
40026
|
+
lease_expires_at_ms BIGINT NOT NULL,
|
|
40027
|
+
disposition TEXT NOT NULL,
|
|
40028
|
+
balance_reason TEXT,
|
|
40029
|
+
resolved_at_ms BIGINT,
|
|
40030
|
+
outcome TEXT,
|
|
40031
|
+
PRIMARY KEY (job_id, seq)
|
|
40032
|
+
);
|
|
40033
|
+
CREATE INDEX IF NOT EXISTS job_payment_intents_open
|
|
40034
|
+
ON job_payment_intents (job_id) WHERE resolved_at_ms IS NULL;
|
|
40035
|
+
|
|
40036
|
+
-- Charging by the piece. pieces is the ordered list of work the job's payments bought;
|
|
40037
|
+
-- settlement is the figure the terminal transition froze for the draw. NULL pieces is a
|
|
40038
|
+
-- job accepted before this column existed, which settles as one piece.
|
|
40039
|
+
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS pieces JSONB;
|
|
40040
|
+
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS settlement JSONB;
|
|
39681
40041
|
`);
|
|
39682
40042
|
}
|
|
39683
40043
|
async get(id) {
|
|
@@ -39873,8 +40233,9 @@ var PostgresJobStore = class {
|
|
|
39873
40233
|
last_activity_at, next_seq, requester_token_hash, requester_token,
|
|
39874
40234
|
request_fingerprint, requester_pubkey, request_id, credit_id, draw_id,
|
|
39875
40235
|
pending_payment_fiat_micro, pending_payment_fiat_currency, auth_request_path,
|
|
39876
|
-
funding_receipt, funding_credit, dvm_id, terminal_at_ms, caller_wait_ms, awaiting_input_at_ms, ended_by, timing_known, upfront_payment
|
|
39877
|
-
|
|
40236
|
+
funding_receipt, funding_credit, dvm_id, terminal_at_ms, caller_wait_ms, awaiting_input_at_ms, ended_by, timing_known, upfront_payment,
|
|
40237
|
+
pieces
|
|
40238
|
+
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$51,$52,$53)
|
|
39878
40239
|
ON CONFLICT (id) DO UPDATE SET
|
|
39879
40240
|
terminal_at_ms = COALESCE(jobs.terminal_at_ms, EXCLUDED.terminal_at_ms),
|
|
39880
40241
|
ended_by = CASE WHEN jobs.status IN ('completed', 'failed', 'cancelled') THEN jobs.ended_by ELSE EXCLUDED.ended_by END,
|
|
@@ -40014,7 +40375,9 @@ var PostgresJobStore = class {
|
|
|
40014
40375
|
isTerminalStatus(record2.status) && record2.status !== "completed" ? record2.endedBy ?? "provider" : null,
|
|
40015
40376
|
now,
|
|
40016
40377
|
record2.timingKnown ?? true,
|
|
40017
|
-
record2.upfrontPayment ? JSON.stringify(record2.upfrontPayment) : null
|
|
40378
|
+
record2.upfrontPayment ? JSON.stringify(record2.upfrontPayment) : null,
|
|
40379
|
+
// INSERT-only: after insert the transactional paths own the piece list.
|
|
40380
|
+
record2.pieces ? JSON.stringify(record2.pieces) : null
|
|
40018
40381
|
]
|
|
40019
40382
|
);
|
|
40020
40383
|
let rowCount;
|
|
@@ -40022,9 +40385,14 @@ var PostgresJobStore = class {
|
|
|
40022
40385
|
try {
|
|
40023
40386
|
await tx.query("BEGIN");
|
|
40024
40387
|
const existing = await tx.query(
|
|
40025
|
-
"SELECT dvm_id FROM jobs WHERE id=$1 FOR UPDATE",
|
|
40388
|
+
"SELECT dvm_id, status, pieces FROM jobs WHERE id=$1 FOR UPDATE",
|
|
40026
40389
|
[record2.id]
|
|
40027
40390
|
);
|
|
40391
|
+
const prior = existing.rows[0];
|
|
40392
|
+
const ending = isTerminalStatus(record2.status) && (!prior || !isTerminalStatus(prior.status));
|
|
40393
|
+
if (prior && ending) {
|
|
40394
|
+
await this.assertNoOpenPaymentIntent(tx, record2.id);
|
|
40395
|
+
}
|
|
40028
40396
|
if (this.hostingCleanupFence) {
|
|
40029
40397
|
if (existing.rows[0]) {
|
|
40030
40398
|
if (existing.rows[0].dvm_id !== null && existing.rows[0].dvm_id !== this.hostingCleanupFence.dvmId) {
|
|
@@ -40035,6 +40403,13 @@ var PostgresJobStore = class {
|
|
|
40035
40403
|
}
|
|
40036
40404
|
}
|
|
40037
40405
|
({ rowCount } = await write(tx));
|
|
40406
|
+
if (rowCount && ending) {
|
|
40407
|
+
const ended = prior ? endPieces(storedPieces(prior.pieces), terminalEnding(record2)) : record2.settlement ? { pieces: record2.pieces, settlement: record2.settlement } : endPieces(record2.pieces, terminalEnding(record2));
|
|
40408
|
+
await tx.query(
|
|
40409
|
+
"UPDATE jobs SET pieces = $2, settlement = $3 WHERE id = $1",
|
|
40410
|
+
[record2.id, ended.pieces ? JSON.stringify(ended.pieces) : null, JSON.stringify(ended.settlement)]
|
|
40411
|
+
);
|
|
40412
|
+
}
|
|
40038
40413
|
await tx.query("COMMIT");
|
|
40039
40414
|
} catch (error62) {
|
|
40040
40415
|
await tx.query("ROLLBACK").catch(() => void 0);
|
|
@@ -40290,13 +40665,18 @@ var PostgresJobStore = class {
|
|
|
40290
40665
|
status = CASE WHEN $3::boolean AND status NOT IN ('completed', 'failed', 'cancelled')
|
|
40291
40666
|
THEN 'awaiting-input' ELSE status END
|
|
40292
40667
|
WHERE id = $1 AND redacted_at IS NULL
|
|
40293
|
-
RETURNING (next_seq - 1) AS seq`,
|
|
40668
|
+
RETURNING (next_seq - 1) AS seq, status, pieces`,
|
|
40294
40669
|
[jobId, Date.now(), opts?.awaitingInput ?? false]
|
|
40295
40670
|
);
|
|
40296
40671
|
if (rows2.length === 0) {
|
|
40297
40672
|
await client.query("ROLLBACK");
|
|
40298
40673
|
throw new Error(`appendOutgoing: job ${jobId} not found`);
|
|
40299
40674
|
}
|
|
40675
|
+
const ask = message.type === "payment-request" || message.type === "prompt";
|
|
40676
|
+
if (ask && isTerminalStatus(rows2[0].status)) {
|
|
40677
|
+
await client.query("ROLLBACK");
|
|
40678
|
+
throw new JobEndedError(jobId);
|
|
40679
|
+
}
|
|
40300
40680
|
const seq = rows2[0].seq;
|
|
40301
40681
|
const fullMessage = { ...message, seq };
|
|
40302
40682
|
await client.query(
|
|
@@ -40362,6 +40742,13 @@ var PostgresJobStore = class {
|
|
|
40362
40742
|
]
|
|
40363
40743
|
);
|
|
40364
40744
|
}
|
|
40745
|
+
const pieces = storedPieces(rows2[0].pieces);
|
|
40746
|
+
if (message.type === "payment-request" && pieces) {
|
|
40747
|
+
await client.query(
|
|
40748
|
+
"UPDATE jobs SET pieces = $2 WHERE id = $1",
|
|
40749
|
+
[jobId, JSON.stringify(finishRunningPiece(pieces, opts?.finishedChargeMicro))]
|
|
40750
|
+
);
|
|
40751
|
+
}
|
|
40365
40752
|
if (opts?.appendId) {
|
|
40366
40753
|
await client.query(
|
|
40367
40754
|
"INSERT INTO job_outgoing_appends (job_id, append_id, seq) VALUES ($1,$2,$3)",
|
|
@@ -40417,14 +40804,94 @@ var PostgresJobStore = class {
|
|
|
40417
40804
|
client.release();
|
|
40418
40805
|
}
|
|
40419
40806
|
}
|
|
40420
|
-
async
|
|
40807
|
+
async recordPaymentArrival(jobId, message, opts) {
|
|
40808
|
+
const client = await this.pool.connect();
|
|
40809
|
+
try {
|
|
40810
|
+
await client.query("BEGIN");
|
|
40811
|
+
await this.hostingCleanupFence?.assertNewIntent(client);
|
|
40812
|
+
const { rows: [row] } = await client.query(
|
|
40813
|
+
"SELECT status, pending_payment_msats FROM jobs WHERE id = $1 AND redacted_at IS NULL FOR UPDATE",
|
|
40814
|
+
[jobId]
|
|
40815
|
+
);
|
|
40816
|
+
if (!row) throw new Error(`recordPaymentArrival: job ${jobId} not found`);
|
|
40817
|
+
const { rows: [ask] } = await client.query(
|
|
40818
|
+
`SELECT data FROM job_messages WHERE job_id = $1 AND status = 'verified'
|
|
40819
|
+
AND data->>'from' = 'provider' AND data->>'type' = 'payment-request'
|
|
40820
|
+
ORDER BY seq DESC LIMIT 1`,
|
|
40821
|
+
[jobId]
|
|
40822
|
+
);
|
|
40823
|
+
const disposition = decidePaymentDisposition({
|
|
40824
|
+
status: row.status,
|
|
40825
|
+
pendingPaymentMsats: row.pending_payment_msats === null ? void 0 : Number(row.pending_payment_msats),
|
|
40826
|
+
ask: ask?.data,
|
|
40827
|
+
arrivedAtMs: opts.arrivedAtMs
|
|
40828
|
+
});
|
|
40829
|
+
const { rows: [allocated] } = await client.query(
|
|
40830
|
+
`UPDATE jobs SET next_seq = next_seq + 1,
|
|
40831
|
+
last_activity_at = CASE WHEN status IN ('completed','failed','cancelled') THEN last_activity_at ELSE $2 END
|
|
40832
|
+
WHERE id = $1 RETURNING (next_seq - 1) AS seq`,
|
|
40833
|
+
[jobId, Date.now()]
|
|
40834
|
+
);
|
|
40835
|
+
const seq = allocated.seq;
|
|
40836
|
+
await client.query(
|
|
40837
|
+
`INSERT INTO job_messages (job_id, seq, data, status, created_at_ms)
|
|
40838
|
+
VALUES ($1, $2, $3, 'pending-verification', $4)`,
|
|
40839
|
+
[jobId, seq, JSON.stringify({ ...message, seq }), opts.arrivedAtMs]
|
|
40840
|
+
);
|
|
40841
|
+
await client.query(
|
|
40842
|
+
`INSERT INTO job_payment_intents
|
|
40843
|
+
(job_id, seq, arrived_at_ms, lease_expires_at_ms, disposition, balance_reason)
|
|
40844
|
+
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
40845
|
+
[
|
|
40846
|
+
jobId,
|
|
40847
|
+
seq,
|
|
40848
|
+
opts.arrivedAtMs,
|
|
40849
|
+
opts.arrivedAtMs + opts.leaseMs,
|
|
40850
|
+
disposition.disposition,
|
|
40851
|
+
disposition.disposition === "balance" ? disposition.reason : null
|
|
40852
|
+
]
|
|
40853
|
+
);
|
|
40854
|
+
await client.query("SELECT pg_notify('job_messages', $1)", [jobId]);
|
|
40855
|
+
await client.query("COMMIT");
|
|
40856
|
+
return { seq, disposition };
|
|
40857
|
+
} catch (err) {
|
|
40858
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
40859
|
+
throw err;
|
|
40860
|
+
} finally {
|
|
40861
|
+
client.release();
|
|
40862
|
+
}
|
|
40863
|
+
}
|
|
40864
|
+
async openPaymentIntentUntil(jobId, nowMs) {
|
|
40865
|
+
return this.openPaymentIntentUntilOn(this.pool, jobId, nowMs);
|
|
40866
|
+
}
|
|
40867
|
+
async openPaymentIntentUntilOn(q2, jobId, nowMs) {
|
|
40868
|
+
const { rows: [row] } = await q2.query(
|
|
40869
|
+
`SELECT MAX(lease_expires_at_ms) AS until FROM job_payment_intents
|
|
40870
|
+
WHERE job_id = $1 AND resolved_at_ms IS NULL AND lease_expires_at_ms > $2`,
|
|
40871
|
+
[jobId, nowMs]
|
|
40872
|
+
);
|
|
40873
|
+
return row?.until == null ? void 0 : Number(row.until);
|
|
40874
|
+
}
|
|
40875
|
+
/** Under the job row lock: refuse a terminal write while a payment intent is open. */
|
|
40876
|
+
async assertNoOpenPaymentIntent(tx, jobId) {
|
|
40877
|
+
const until = await this.openPaymentIntentUntilOn(tx, jobId, Date.now());
|
|
40878
|
+
if (until !== void 0) throw new PaymentIntentOpenError(jobId, until);
|
|
40879
|
+
}
|
|
40880
|
+
async verifyAndCredit(jobId, seq, credit, opts) {
|
|
40421
40881
|
const client = await this.pool.connect();
|
|
40422
40882
|
try {
|
|
40423
40883
|
await client.query("BEGIN");
|
|
40424
40884
|
const { rowCount } = await client.query(
|
|
40425
|
-
"UPDATE job_messages SET status
|
|
40426
|
-
[jobId, seq]
|
|
40885
|
+
"UPDATE job_messages SET status=$3 WHERE job_id = $1 AND seq = $2 AND status = 'pending-verification'",
|
|
40886
|
+
[jobId, seq, opts?.landedAsBalance ? "balance" : "verified"]
|
|
40427
40887
|
);
|
|
40888
|
+
if (rowCount) {
|
|
40889
|
+
await client.query(
|
|
40890
|
+
`UPDATE job_payment_intents SET resolved_at_ms = $3, outcome = 'verified'
|
|
40891
|
+
WHERE job_id = $1 AND seq = $2 AND resolved_at_ms IS NULL`,
|
|
40892
|
+
[jobId, seq, Date.now()]
|
|
40893
|
+
);
|
|
40894
|
+
}
|
|
40428
40895
|
if (!rowCount) {
|
|
40429
40896
|
const counters2 = await this.fetchCountersTx(client, jobId);
|
|
40430
40897
|
const binding2 = await this.fetchCreditBindingTx(client, jobId);
|
|
@@ -40486,19 +40953,33 @@ var PostgresJobStore = class {
|
|
|
40486
40953
|
cashu_flow = COALESCE($9, cashu_flow),
|
|
40487
40954
|
pending_x402_nonce = CASE WHEN $11::boolean THEN NULL ELSE pending_x402_nonce END,
|
|
40488
40955
|
pending_x402_amount_usdc_micro = CASE WHEN $11::boolean THEN NULL ELSE pending_x402_amount_usdc_micro END,
|
|
40489
|
-
last_activity_at =
|
|
40490
|
-
WHERE id = $1
|
|
40491
|
-
RETURNING status, paid_msats, pending_payment_msats, credit_id, draw_id`,
|
|
40956
|
+
last_activity_at = $12
|
|
40957
|
+
WHERE id = $1 AND status NOT IN ('completed','failed','cancelled')
|
|
40958
|
+
RETURNING status, paid_msats, pending_payment_msats, credit_id, draw_id, pieces`,
|
|
40492
40959
|
params
|
|
40493
40960
|
);
|
|
40494
40961
|
if (rows2.length === 0) {
|
|
40495
|
-
await
|
|
40496
|
-
|
|
40962
|
+
const ended = await this.fetchCountersTx(client, jobId);
|
|
40963
|
+
if (!ended) {
|
|
40964
|
+
await client.query("ROLLBACK");
|
|
40965
|
+
throw new Error(`verifyAndCredit: job ${jobId} not found`);
|
|
40966
|
+
}
|
|
40967
|
+
const endedBinding = await this.fetchCreditBindingTx(client, jobId);
|
|
40968
|
+
await client.query("UPDATE job_messages SET status='balance' WHERE job_id = $1 AND seq = $2", [jobId, seq]);
|
|
40969
|
+
await client.query("SELECT pg_notify('job_messages', $1)", [jobId]);
|
|
40970
|
+
await client.query("COMMIT");
|
|
40971
|
+
return { counters: ended, alreadyVerified: false, ...endedBinding, creditRefused: "job_ended" };
|
|
40972
|
+
}
|
|
40973
|
+
let pieces = storedPieces(rows2[0].pieces);
|
|
40974
|
+
if (pieces && credit.piece && credit.piece.amountMicro > 0 && rows2[0].draw_id === credit.piece.drawId) {
|
|
40975
|
+
pieces = appendPiece(pieces, credit.piece.amountMicro, seq);
|
|
40976
|
+
await client.query("UPDATE jobs SET pieces = $2 WHERE id = $1", [jobId, JSON.stringify(pieces)]);
|
|
40497
40977
|
}
|
|
40498
40978
|
counters = {
|
|
40499
40979
|
status: rows2[0].status,
|
|
40500
40980
|
paidMsats: Number(rows2[0].paid_msats),
|
|
40501
|
-
pendingPaymentMsats: rows2[0].pending_payment_msats == null ? void 0 : Number(rows2[0].pending_payment_msats)
|
|
40981
|
+
pendingPaymentMsats: rows2[0].pending_payment_msats == null ? void 0 : Number(rows2[0].pending_payment_msats),
|
|
40982
|
+
...pieces && { pieces }
|
|
40502
40983
|
};
|
|
40503
40984
|
binding = {
|
|
40504
40985
|
...rows2[0].credit_id !== null && { creditId: rows2[0].credit_id },
|
|
@@ -40527,10 +41008,10 @@ var PostgresJobStore = class {
|
|
|
40527
41008
|
}
|
|
40528
41009
|
async getVerifiedInbound(jobId, seq) {
|
|
40529
41010
|
const { rows: rows2 } = await this.pool.query(
|
|
40530
|
-
`SELECT j.status, j.paid_msats, j.pending_payment_msats, j.summary, j.credit_id, j.draw_id
|
|
41011
|
+
`SELECT j.status, j.paid_msats, j.pending_payment_msats, j.summary, j.pieces, j.credit_id, j.draw_id
|
|
40531
41012
|
FROM jobs j
|
|
40532
41013
|
JOIN job_messages m ON m.job_id = j.id AND m.seq = $2
|
|
40533
|
-
WHERE j.id = $1 AND m.status
|
|
41014
|
+
WHERE j.id = $1 AND m.status IN ('verified', 'balance')`,
|
|
40534
41015
|
[jobId, seq]
|
|
40535
41016
|
);
|
|
40536
41017
|
if (rows2.length === 0) return void 0;
|
|
@@ -40547,9 +41028,12 @@ var PostgresJobStore = class {
|
|
|
40547
41028
|
`WITH failed AS (
|
|
40548
41029
|
UPDATE job_messages SET status='failed-verify'
|
|
40549
41030
|
WHERE job_id = $1 AND seq = $2 AND status = 'pending-verification'
|
|
40550
|
-
RETURNING job_id
|
|
41031
|
+
RETURNING job_id, seq
|
|
41032
|
+
), resolved AS (
|
|
41033
|
+
UPDATE job_payment_intents SET resolved_at_ms = $3, outcome = 'failed'
|
|
41034
|
+
WHERE (job_id, seq) IN (SELECT job_id, seq FROM failed) AND resolved_at_ms IS NULL
|
|
40551
41035
|
) SELECT pg_notify('job_messages', job_id) FROM failed`,
|
|
40552
|
-
[jobId, seq]
|
|
41036
|
+
[jobId, seq, Date.now()]
|
|
40553
41037
|
);
|
|
40554
41038
|
}
|
|
40555
41039
|
async findStaleJobs(processingThresholdMs, awaitingThresholdMs, limit, capabilities) {
|
|
@@ -40577,21 +41061,33 @@ var PostgresJobStore = class {
|
|
|
40577
41061
|
[now, jobIds]
|
|
40578
41062
|
);
|
|
40579
41063
|
}
|
|
40580
|
-
cancelStaleJob(jobId, expectedActivityBefore, reason, terminalStatus) {
|
|
40581
|
-
return this.terminateJob(
|
|
41064
|
+
async cancelStaleJob(jobId, expectedActivityBefore, reason, terminalStatus) {
|
|
41065
|
+
return await this.terminateJob(
|
|
41066
|
+
jobId,
|
|
41067
|
+
reason,
|
|
41068
|
+
terminalStatus,
|
|
41069
|
+
expectedActivityBefore,
|
|
41070
|
+
null,
|
|
41071
|
+
{ kind: "release" }
|
|
41072
|
+
) === "ended";
|
|
40582
41073
|
}
|
|
40583
|
-
|
|
40584
|
-
|
|
41074
|
+
/** A caller's cancel stops the piece in progress and charges it. */
|
|
41075
|
+
async cancelJob(jobId, reason) {
|
|
41076
|
+
return await this.terminateJob(jobId, reason, "cancelled", null, "caller", { kind: "stop" }) === "ended";
|
|
40585
41077
|
}
|
|
40586
|
-
failJob(jobId, reason) {
|
|
40587
|
-
return this.terminateJob(jobId, reason, "failed", null, "provider");
|
|
41078
|
+
async failJob(jobId, reason) {
|
|
41079
|
+
return await this.terminateJob(jobId, reason, "failed", null, "provider", { kind: "release" }) === "ended";
|
|
40588
41080
|
}
|
|
40589
|
-
|
|
40590
|
-
|
|
41081
|
+
async declineJob(jobId, reason) {
|
|
41082
|
+
const outcome = await this.terminateJob(jobId, reason, "cancelled", null, "caller", { kind: "release" }, true);
|
|
41083
|
+
return outcome === "ended" ? "declined" : outcome;
|
|
41084
|
+
}
|
|
41085
|
+
async cancelJobForHosting(jobId, reason) {
|
|
41086
|
+
return await this.terminateJob(jobId, reason, "cancelled", null, "provider", { kind: "release" }) === "ended";
|
|
40591
41087
|
}
|
|
40592
41088
|
async getCounters(jobId) {
|
|
40593
41089
|
const { rows: rows2 } = await this.pool.query(
|
|
40594
|
-
`SELECT status, paid_msats, pending_payment_msats, summary,
|
|
41090
|
+
`SELECT status, paid_msats, pending_payment_msats, summary, pieces,
|
|
40595
41091
|
EXISTS (SELECT 1 FROM credit_balance_payments p WHERE p.job_id=jobs.id
|
|
40596
41092
|
AND p.request_seq=(SELECT MAX(m.seq) FROM job_messages m WHERE m.job_id=jobs.id
|
|
40597
41093
|
AND m.data->>'type'='payment-request' AND m.data->>'from'='provider'
|
|
@@ -40759,7 +41255,7 @@ var PostgresJobStore = class {
|
|
|
40759
41255
|
* machine running the handler wakes as soon as the terminal status is
|
|
40760
41256
|
* visible.
|
|
40761
41257
|
*/
|
|
40762
|
-
async terminateJob(jobId, reason, terminalStatus, expectedActivityBefore, endedBy) {
|
|
41258
|
+
async terminateJob(jobId, reason, terminalStatus, expectedActivityBefore, endedBy, ending, requireOpenAsk = false) {
|
|
40763
41259
|
const staleOnly = expectedActivityBefore !== null;
|
|
40764
41260
|
const client = await this.pool.connect();
|
|
40765
41261
|
try {
|
|
@@ -40774,8 +41270,9 @@ var PostgresJobStore = class {
|
|
|
40774
41270
|
);
|
|
40775
41271
|
if (rows2.length === 0) {
|
|
40776
41272
|
await client.query("ROLLBACK");
|
|
40777
|
-
return
|
|
41273
|
+
return "not_active";
|
|
40778
41274
|
}
|
|
41275
|
+
await this.assertNoOpenPaymentIntent(client, jobId);
|
|
40779
41276
|
const record2 = rowToRecord(rows2[0]);
|
|
40780
41277
|
const { rows: messages } = await client.query(
|
|
40781
41278
|
"SELECT data FROM job_messages WHERE job_id=$1 AND status='verified' ORDER BY seq",
|
|
@@ -40787,9 +41284,14 @@ var PostgresJobStore = class {
|
|
|
40787
41284
|
const awaiting = deadline !== void 0 || record2.status === "awaiting-input" && !hasCallerDeadline(terminalMessages);
|
|
40788
41285
|
if (terminalStatus === "cancelled" !== awaiting || deadline !== void 0 && Date.now() < deadline) {
|
|
40789
41286
|
await client.query("ROLLBACK");
|
|
40790
|
-
return
|
|
41287
|
+
return "not_active";
|
|
40791
41288
|
}
|
|
40792
41289
|
}
|
|
41290
|
+
if (requireOpenAsk && !hasOpenAsk({ ...record2, messages: terminalMessages })) {
|
|
41291
|
+
await client.query("ROLLBACK");
|
|
41292
|
+
return "no_open_ask";
|
|
41293
|
+
}
|
|
41294
|
+
const ended = endPieces(record2.pieces, ending);
|
|
40793
41295
|
const nextSeq = rows2[0].next_seq;
|
|
40794
41296
|
const now = Date.now();
|
|
40795
41297
|
const cancelMsg = {
|
|
@@ -40815,7 +41317,9 @@ var PostgresJobStore = class {
|
|
|
40815
41317
|
messages = $3::jsonb,
|
|
40816
41318
|
seq = $4,
|
|
40817
41319
|
next_seq = $4 + 1,
|
|
40818
|
-
last_activity_at = $5
|
|
41320
|
+
last_activity_at = $5,
|
|
41321
|
+
pieces = $8::jsonb,
|
|
41322
|
+
settlement = $9::jsonb
|
|
40819
41323
|
WHERE id = $1`,
|
|
40820
41324
|
[
|
|
40821
41325
|
jobId,
|
|
@@ -40824,7 +41328,9 @@ var PostgresJobStore = class {
|
|
|
40824
41328
|
nextSeq,
|
|
40825
41329
|
now,
|
|
40826
41330
|
terminalStatus,
|
|
40827
|
-
staleOnly ? terminalStatus === "cancelled" ? "caller" : "provider" : endedBy
|
|
41331
|
+
staleOnly ? terminalStatus === "cancelled" ? "caller" : "provider" : endedBy,
|
|
41332
|
+
ended.pieces ? JSON.stringify(ended.pieces) : null,
|
|
41333
|
+
JSON.stringify(ended.settlement)
|
|
40828
41334
|
]
|
|
40829
41335
|
);
|
|
40830
41336
|
await client.query("SELECT pg_notify('job_messages', $1)", [jobId]);
|
|
@@ -40839,7 +41345,7 @@ var PostgresJobStore = class {
|
|
|
40839
41345
|
client.release();
|
|
40840
41346
|
}
|
|
40841
41347
|
await this.deleteResolvedMessages(jobId).catch(() => void 0);
|
|
40842
|
-
return
|
|
41348
|
+
return "ended";
|
|
40843
41349
|
}
|
|
40844
41350
|
async deleteResolvedMessages(jobId) {
|
|
40845
41351
|
await this.pool.query(
|
|
@@ -40851,7 +41357,7 @@ var PostgresJobStore = class {
|
|
|
40851
41357
|
}
|
|
40852
41358
|
async fetchCountersTx(client, jobId) {
|
|
40853
41359
|
const { rows: rows2 } = await client.query(
|
|
40854
|
-
"SELECT status, paid_msats, pending_payment_msats, summary FROM jobs WHERE id = $1",
|
|
41360
|
+
"SELECT status, paid_msats, pending_payment_msats, summary, pieces FROM jobs WHERE id = $1",
|
|
40855
41361
|
[jobId]
|
|
40856
41362
|
);
|
|
40857
41363
|
if (rows2.length === 0) return void 0;
|
|
@@ -40884,7 +41390,8 @@ function rowToCounters(row) {
|
|
|
40884
41390
|
...row.balance_payment_satisfied && { balancePaymentSatisfied: true },
|
|
40885
41391
|
paidMsats: Number(row.paid_msats),
|
|
40886
41392
|
pendingPaymentMsats: row.pending_payment_msats == null ? void 0 : Number(row.pending_payment_msats),
|
|
40887
|
-
summary: row.summary ?? void 0
|
|
41393
|
+
summary: row.summary ?? void 0,
|
|
41394
|
+
...storedPieces(row.pieces) && { pieces: storedPieces(row.pieces) }
|
|
40888
41395
|
};
|
|
40889
41396
|
}
|
|
40890
41397
|
function rowToRecord(row) {
|
|
@@ -40940,6 +41447,8 @@ function rowToRecord(row) {
|
|
|
40940
41447
|
askedTopUpCurrency: row.asked_topup_currency ?? void 0,
|
|
40941
41448
|
topUpCapUnenforcedReason: row.topup_cap_unenforced_reason ?? void 0,
|
|
40942
41449
|
requiredMsats: row.required_msats == null ? void 0 : Number(row.required_msats),
|
|
41450
|
+
pieces: storedPieces(row.pieces),
|
|
41451
|
+
settlement: row.settlement ?? void 0,
|
|
40943
41452
|
receipt: row.receipt ?? void 0,
|
|
40944
41453
|
stepCache: row.step_cache,
|
|
40945
41454
|
state: row.state,
|
|
@@ -40952,7 +41461,7 @@ function isTerminalStatus(status) {
|
|
|
40952
41461
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
40953
41462
|
}
|
|
40954
41463
|
|
|
40955
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
41464
|
+
// node_modules/@dvmkit/sdk/dist/chunk-JHCMJ2UU.js
|
|
40956
41465
|
function humanizeZodError(err, opts) {
|
|
40957
41466
|
return humanizeZodIssues(err.issues, opts);
|
|
40958
41467
|
}
|
|
@@ -41123,38 +41632,10 @@ function shortestCashuLockWindowSeconds(cashu, servesUnsigned) {
|
|
|
41123
41632
|
return servesUnsigned ? Math.min(signed, unsignedCashuLockWindowSeconds(cashu)) : signed;
|
|
41124
41633
|
}
|
|
41125
41634
|
|
|
41126
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
41127
|
-
function accumulateAskedTopUp(prior, ask) {
|
|
41128
|
-
const poisoned = (reason) => ({
|
|
41129
|
-
micro: UNCAPPABLE_ASK_TOTAL,
|
|
41130
|
-
currency: prior.currency,
|
|
41131
|
-
reason: prior.reason ?? reason
|
|
41132
|
-
});
|
|
41133
|
-
if (prior.micro === UNCAPPABLE_ASK_TOTAL) {
|
|
41134
|
-
return { micro: prior.micro, currency: prior.currency, reason: prior.reason };
|
|
41135
|
-
}
|
|
41136
|
-
if (ask.micro === void 0) return poisoned("ask_unpriceable");
|
|
41137
|
-
if (prior.micro === void 0) {
|
|
41138
|
-
return { micro: ask.micro, currency: ask.currency, reason: prior.reason };
|
|
41139
|
-
}
|
|
41140
|
-
if (prior.currency !== ask.currency) return poisoned("ask_currency_switch");
|
|
41141
|
-
return { micro: prior.micro + ask.micro, currency: prior.currency, reason: prior.reason };
|
|
41142
|
-
}
|
|
41143
|
-
var UNCAPPABLE_ASK_TOTAL = -1;
|
|
41144
|
-
function isJobRetentionStore(store) {
|
|
41145
|
-
return "listJobsForRetention" in store && "redactJob" in store;
|
|
41146
|
-
}
|
|
41147
|
-
function isReceiptIssuingStore(store) {
|
|
41148
|
-
return "claimReceiptSeq" in store && "saveReceipt" in store;
|
|
41149
|
-
}
|
|
41150
|
-
function isStreamableJobStore(store) {
|
|
41151
|
-
return "appendOutgoing" in store && "recordInbound" in store && "verifyAndCredit" in store && "getVerifiedInbound" in store && "subscribeMessages" in store && "subscribeNotifications" in store && "getCounters" in store && "getMessages" in store && "cancelJob" in store && "initStreaming" in store;
|
|
41152
|
-
}
|
|
41153
|
-
function isStaleJobReapable(store) {
|
|
41154
|
-
return "findStaleJobs" in store && "cancelStaleJob" in store;
|
|
41155
|
-
}
|
|
41635
|
+
// node_modules/@dvmkit/sdk/dist/chunk-ZMTD3PTH.js
|
|
41156
41636
|
var MemoryJobStore = class {
|
|
41157
41637
|
contentHolds = /* @__PURE__ */ new Map();
|
|
41638
|
+
paymentIntents = /* @__PURE__ */ new Map();
|
|
41158
41639
|
data = /* @__PURE__ */ new Map();
|
|
41159
41640
|
messages = /* @__PURE__ */ new Map();
|
|
41160
41641
|
nextSeq = /* @__PURE__ */ new Map();
|
|
@@ -41225,10 +41706,22 @@ var MemoryJobStore = class {
|
|
|
41225
41706
|
if (existing && (existing.redactedAt !== void 0 || isTerminal(existing.status) && existing.status !== record2.status)) {
|
|
41226
41707
|
return Promise.resolve();
|
|
41227
41708
|
}
|
|
41709
|
+
if (existing && !isTerminal(existing.status) && isTerminal(record2.status)) {
|
|
41710
|
+
const until = this.openIntentUntil(record2.id, Date.now());
|
|
41711
|
+
if (until !== void 0) return Promise.reject(new PaymentIntentOpenError(record2.id, until));
|
|
41712
|
+
}
|
|
41228
41713
|
const snapshot = structuredClone(record2);
|
|
41714
|
+
delete snapshot.pieceEnding;
|
|
41229
41715
|
if (existing) {
|
|
41230
41716
|
snapshot.createdAt = existing.createdAt;
|
|
41231
41717
|
snapshot.upfrontPayment = structuredClone(existing.upfrontPayment);
|
|
41718
|
+
snapshot.pieces = structuredClone(existing.pieces);
|
|
41719
|
+
snapshot.settlement = structuredClone(existing.settlement);
|
|
41720
|
+
}
|
|
41721
|
+
if (isTerminal(record2.status) && (!existing || !isTerminal(existing.status))) {
|
|
41722
|
+
const ended = !existing && record2.settlement ? { pieces: snapshot.pieces, settlement: snapshot.settlement } : endPieces(snapshot.pieces, terminalEnding(record2));
|
|
41723
|
+
snapshot.pieces = ended.pieces;
|
|
41724
|
+
snapshot.settlement = ended.settlement;
|
|
41232
41725
|
}
|
|
41233
41726
|
if (existing && isTerminal(existing.status)) snapshot.lastActivityAt = existing.lastActivityAt;
|
|
41234
41727
|
if (existing?.receipt) snapshot.receipt = existing.receipt;
|
|
@@ -41239,12 +41732,13 @@ var MemoryJobStore = class {
|
|
|
41239
41732
|
this.nextSeq.set(record2.id, Math.max(cur, record2.seq + 1));
|
|
41240
41733
|
if (isTerminal(record2.status)) {
|
|
41241
41734
|
this.notify(record2.id);
|
|
41242
|
-
this.
|
|
41735
|
+
this.deleteResolvedMessages(record2.id);
|
|
41243
41736
|
}
|
|
41244
41737
|
return Promise.resolve();
|
|
41245
41738
|
}
|
|
41246
41739
|
delete(id) {
|
|
41247
41740
|
this.contentHolds.delete(id);
|
|
41741
|
+
this.paymentIntents.delete(id);
|
|
41248
41742
|
this.data.delete(id);
|
|
41249
41743
|
this.outgoingAppends.delete(id);
|
|
41250
41744
|
this.messages.delete(id);
|
|
@@ -41318,6 +41812,12 @@ var MemoryJobStore = class {
|
|
|
41318
41812
|
}
|
|
41319
41813
|
const prior = opts?.appendId ? this.outgoingAppends.get(jobId)?.get(opts.appendId) : void 0;
|
|
41320
41814
|
if (prior !== void 0) return Promise.resolve(prior);
|
|
41815
|
+
if ((message.type === "payment-request" || message.type === "prompt") && isTerminal(record2.status)) {
|
|
41816
|
+
return Promise.reject(new JobEndedError(jobId));
|
|
41817
|
+
}
|
|
41818
|
+
if (message.type === "payment-request" && record2.pieces) {
|
|
41819
|
+
record2.pieces = finishRunningPiece(record2.pieces, opts?.finishedChargeMicro);
|
|
41820
|
+
}
|
|
41321
41821
|
const seq = this.allocateSeq(jobId);
|
|
41322
41822
|
const fullMessage = { ...message, seq };
|
|
41323
41823
|
if (opts?.awaitingInput && !isTerminal(record2.status)) {
|
|
@@ -41374,7 +41874,32 @@ var MemoryJobStore = class {
|
|
|
41374
41874
|
this.fireNotifyOnly(jobId);
|
|
41375
41875
|
return Promise.resolve(seq);
|
|
41376
41876
|
}
|
|
41377
|
-
|
|
41877
|
+
recordPaymentArrival(jobId, message, opts) {
|
|
41878
|
+
const record2 = this.data.get(jobId);
|
|
41879
|
+
if (!record2 || record2.redactedAt !== void 0) {
|
|
41880
|
+
return Promise.reject(new Error(`recordPaymentArrival: job ${jobId} not found`));
|
|
41881
|
+
}
|
|
41882
|
+
const ask = this.messagesFor(jobId).findLast((entry) => entry.status === "verified" && entry.message.from === "provider" && entry.message.type === "payment-request")?.message;
|
|
41883
|
+
const disposition = decidePaymentDisposition({
|
|
41884
|
+
status: record2.status,
|
|
41885
|
+
pendingPaymentMsats: record2.pendingPaymentMsats,
|
|
41886
|
+
ask,
|
|
41887
|
+
arrivedAtMs: opts.arrivedAtMs
|
|
41888
|
+
});
|
|
41889
|
+
const seq = this.allocateSeq(jobId);
|
|
41890
|
+
this.messagesFor(jobId).push({ message: { ...message, seq }, status: "pending-verification" });
|
|
41891
|
+
if (!isTerminal(record2.status)) record2.lastActivityAt = Date.now();
|
|
41892
|
+
if (seq > record2.seq) record2.seq = seq;
|
|
41893
|
+
let intents = this.paymentIntents.get(jobId);
|
|
41894
|
+
if (!intents) this.paymentIntents.set(jobId, intents = /* @__PURE__ */ new Map());
|
|
41895
|
+
intents.set(seq, { leaseExpiresAtMs: opts.arrivedAtMs + opts.leaseMs, resolved: false });
|
|
41896
|
+
this.fireNotifyOnly(jobId);
|
|
41897
|
+
return Promise.resolve({ seq, disposition });
|
|
41898
|
+
}
|
|
41899
|
+
openPaymentIntentUntil(jobId, nowMs) {
|
|
41900
|
+
return Promise.resolve(this.openIntentUntil(jobId, nowMs));
|
|
41901
|
+
}
|
|
41902
|
+
verifyAndCredit(jobId, seq, credit, opts) {
|
|
41378
41903
|
const record2 = this.data.get(jobId);
|
|
41379
41904
|
if (!record2) return Promise.reject(new Error(`verifyAndCredit: job ${jobId} not found`));
|
|
41380
41905
|
const stored = this.messagesFor(jobId).find((m) => m.message.seq === seq);
|
|
@@ -41387,8 +41912,10 @@ var MemoryJobStore = class {
|
|
|
41387
41912
|
...creditBinding(record2)
|
|
41388
41913
|
});
|
|
41389
41914
|
}
|
|
41390
|
-
|
|
41391
|
-
|
|
41915
|
+
this.resolveIntent(jobId, seq);
|
|
41916
|
+
const refused = credit !== null && isTerminal(record2.status);
|
|
41917
|
+
stored.status = opts?.landedAsBalance || refused ? "balance" : "verified";
|
|
41918
|
+
if (credit && !refused) {
|
|
41392
41919
|
record2.paidMsats += credit.paidMsatsDelta;
|
|
41393
41920
|
if (credit.clearPending || (record2.pendingPaymentMsats ?? 0) <= credit.paidMsatsDelta) {
|
|
41394
41921
|
record2.pendingPaymentFiatMicro = void 0;
|
|
@@ -41405,6 +41932,9 @@ var MemoryJobStore = class {
|
|
|
41405
41932
|
}
|
|
41406
41933
|
record2.creditId ??= credit.creditId;
|
|
41407
41934
|
record2.drawId ??= credit.drawId;
|
|
41935
|
+
if (record2.pieces && credit.piece && credit.piece.amountMicro > 0 && record2.drawId === credit.piece.drawId) {
|
|
41936
|
+
record2.pieces = appendPiece(record2.pieces, credit.piece.amountMicro, seq);
|
|
41937
|
+
}
|
|
41408
41938
|
if (credit.paymentMint) record2.paymentMint = credit.paymentMint;
|
|
41409
41939
|
if (credit.paymentRail) record2.paymentRail = credit.paymentRail;
|
|
41410
41940
|
if (credit.paymentTxHash) record2.paymentTxHash = credit.paymentTxHash;
|
|
@@ -41423,13 +41953,14 @@ var MemoryJobStore = class {
|
|
|
41423
41953
|
return Promise.resolve({
|
|
41424
41954
|
counters: snapshotCounters(record2),
|
|
41425
41955
|
alreadyVerified: false,
|
|
41426
|
-
...creditBinding(record2)
|
|
41956
|
+
...creditBinding(record2),
|
|
41957
|
+
...refused && { creditRefused: "job_ended" }
|
|
41427
41958
|
});
|
|
41428
41959
|
}
|
|
41429
41960
|
getVerifiedInbound(jobId, seq) {
|
|
41430
41961
|
const record2 = this.data.get(jobId);
|
|
41431
41962
|
const stored = this.messagesFor(jobId).find((m) => m.message.seq === seq);
|
|
41432
|
-
if (!record2 || stored?.status !== "verified") return Promise.resolve(void 0);
|
|
41963
|
+
if (!record2 || stored?.status !== "verified" && stored?.status !== "balance") return Promise.resolve(void 0);
|
|
41433
41964
|
return Promise.resolve({
|
|
41434
41965
|
counters: snapshotCounters(record2),
|
|
41435
41966
|
alreadyVerified: true,
|
|
@@ -41440,6 +41971,7 @@ var MemoryJobStore = class {
|
|
|
41440
41971
|
const stored = this.messagesFor(jobId).find((m) => m.message.seq === seq);
|
|
41441
41972
|
if (stored?.status === "pending-verification") {
|
|
41442
41973
|
stored.status = "failed-verify";
|
|
41974
|
+
this.resolveIntent(jobId, seq);
|
|
41443
41975
|
this.notify(jobId);
|
|
41444
41976
|
}
|
|
41445
41977
|
return Promise.resolve();
|
|
@@ -41468,14 +42000,19 @@ var MemoryJobStore = class {
|
|
|
41468
42000
|
}
|
|
41469
42001
|
return Promise.resolve();
|
|
41470
42002
|
}
|
|
41471
|
-
cancelStaleJob(jobId, expectedActivityBefore, reason, terminalStatus) {
|
|
41472
|
-
return this.terminateJob(jobId, reason, terminalStatus, expectedActivityBefore);
|
|
42003
|
+
async cancelStaleJob(jobId, expectedActivityBefore, reason, terminalStatus) {
|
|
42004
|
+
return await this.terminateJob(jobId, reason, terminalStatus, expectedActivityBefore, { kind: "release" }) === "ended";
|
|
42005
|
+
}
|
|
42006
|
+
/** A caller's cancel stops the piece in progress and charges it. */
|
|
42007
|
+
async cancelJob(jobId, reason) {
|
|
42008
|
+
return await this.terminateJob(jobId, reason, "cancelled", null, { kind: "stop" }) === "ended";
|
|
41473
42009
|
}
|
|
41474
|
-
|
|
41475
|
-
return this.terminateJob(jobId, reason, "
|
|
42010
|
+
async failJob(jobId, reason) {
|
|
42011
|
+
return await this.terminateJob(jobId, reason, "failed", null, { kind: "release" }) === "ended";
|
|
41476
42012
|
}
|
|
41477
|
-
|
|
41478
|
-
|
|
42013
|
+
async declineJob(jobId, reason) {
|
|
42014
|
+
const outcome = await this.terminateJob(jobId, reason, "cancelled", null, { kind: "release" }, true);
|
|
42015
|
+
return outcome === "ended" ? "declined" : outcome;
|
|
41479
42016
|
}
|
|
41480
42017
|
getCounters(jobId) {
|
|
41481
42018
|
const record2 = this.data.get(jobId);
|
|
@@ -41551,18 +42088,21 @@ var MemoryJobStore = class {
|
|
|
41551
42088
|
* the terminal status and the final `cancel` message land together and the
|
|
41552
42089
|
* notify fires before the incremental log is cleaned up.
|
|
41553
42090
|
*/
|
|
41554
|
-
terminateJob(jobId, reason, terminalStatus, expectedActivityBefore) {
|
|
42091
|
+
terminateJob(jobId, reason, terminalStatus, expectedActivityBefore, ending, requireOpenAsk = false) {
|
|
41555
42092
|
const record2 = this.data.get(jobId);
|
|
41556
|
-
if (!record2) return Promise.resolve(
|
|
42093
|
+
if (!record2) return Promise.resolve("not_active");
|
|
41557
42094
|
const eligible = (record2.status === "processing" || record2.status === "working" || record2.status === "awaiting-input") && (expectedActivityBefore === null || record2.lastActivityAt <= expectedActivityBefore);
|
|
41558
|
-
if (!eligible) return Promise.resolve(
|
|
42095
|
+
if (!eligible) return Promise.resolve("not_active");
|
|
42096
|
+
const until = this.openIntentUntil(jobId, Date.now());
|
|
42097
|
+
if (until !== void 0) return Promise.reject(new PaymentIntentOpenError(jobId, until));
|
|
41559
42098
|
const messages = this.messagesFor(jobId).filter((entry) => entry.status === "verified").map((entry) => entry.message);
|
|
41560
42099
|
const terminalMessages = messages.length ? messages : record2.messages;
|
|
41561
42100
|
if (expectedActivityBefore !== null) {
|
|
41562
42101
|
const deadline = callerDeadline({ ...record2, messages: terminalMessages });
|
|
41563
42102
|
const awaiting = deadline !== void 0 || record2.status === "awaiting-input" && !hasCallerDeadline(terminalMessages);
|
|
41564
|
-
if (terminalStatus === "cancelled" !== awaiting || deadline !== void 0 && Date.now() < deadline) return Promise.resolve(
|
|
42103
|
+
if (terminalStatus === "cancelled" !== awaiting || deadline !== void 0 && Date.now() < deadline) return Promise.resolve("not_active");
|
|
41565
42104
|
}
|
|
42105
|
+
if (requireOpenAsk && !hasOpenAsk({ ...record2, messages: terminalMessages })) return Promise.resolve("no_open_ask");
|
|
41566
42106
|
const seq = this.allocateSeq(jobId);
|
|
41567
42107
|
const cancelMsg = {
|
|
41568
42108
|
seq,
|
|
@@ -41573,6 +42113,9 @@ var MemoryJobStore = class {
|
|
|
41573
42113
|
};
|
|
41574
42114
|
this.messagesFor(jobId).push({ message: cancelMsg, status: "verified" });
|
|
41575
42115
|
record2.endedBy = terminalStatus === "cancelled" ? "caller" : "provider";
|
|
42116
|
+
const ended = endPieces(record2.pieces, ending);
|
|
42117
|
+
record2.pieces = ended.pieces;
|
|
42118
|
+
record2.settlement = ended.settlement;
|
|
41576
42119
|
applyTiming(record2, structuredClone(record2), Date.now(), terminalStatus);
|
|
41577
42120
|
record2.status = terminalStatus;
|
|
41578
42121
|
record2.summary = record2.summary ?? reason;
|
|
@@ -41580,8 +42123,29 @@ var MemoryJobStore = class {
|
|
|
41580
42123
|
record2.seq = seq;
|
|
41581
42124
|
record2.lastActivityAt = Date.now();
|
|
41582
42125
|
this.notify(jobId);
|
|
41583
|
-
this.
|
|
41584
|
-
return Promise.resolve(
|
|
42126
|
+
this.deleteResolvedMessages(jobId);
|
|
42127
|
+
return Promise.resolve("ended");
|
|
42128
|
+
}
|
|
42129
|
+
/** The latest lease among this job's unresolved, unexpired payment intents. */
|
|
42130
|
+
openIntentUntil(jobId, nowMs) {
|
|
42131
|
+
let until;
|
|
42132
|
+
for (const intent of this.paymentIntents.get(jobId)?.values() ?? []) {
|
|
42133
|
+
if (!intent.resolved && intent.leaseExpiresAtMs > nowMs) until = Math.max(until ?? 0, intent.leaseExpiresAtMs);
|
|
42134
|
+
}
|
|
42135
|
+
return until;
|
|
42136
|
+
}
|
|
42137
|
+
/**
|
|
42138
|
+
* Terminal log cleanup. Mirrors `PostgresJobStore`: a payment still being
|
|
42139
|
+
* verified keeps its row, so its outcome can still be recorded.
|
|
42140
|
+
*/
|
|
42141
|
+
deleteResolvedMessages(jobId) {
|
|
42142
|
+
const pending = this.messagesFor(jobId).filter((entry) => entry.status === "pending-verification" && entry.message.type === "payment");
|
|
42143
|
+
if (pending.length) this.messages.set(jobId, pending);
|
|
42144
|
+
else this.messages.delete(jobId);
|
|
42145
|
+
}
|
|
42146
|
+
resolveIntent(jobId, seq) {
|
|
42147
|
+
const intent = this.paymentIntents.get(jobId)?.get(seq);
|
|
42148
|
+
if (intent) intent.resolved = true;
|
|
41585
42149
|
}
|
|
41586
42150
|
allocateSeq(jobId) {
|
|
41587
42151
|
const seq = this.nextSeq.get(jobId) ?? 1;
|
|
@@ -41654,7 +42218,8 @@ function snapshotCounters(record2) {
|
|
|
41654
42218
|
status: record2.status,
|
|
41655
42219
|
paidMsats: record2.paidMsats,
|
|
41656
42220
|
pendingPaymentMsats: record2.pendingPaymentMsats,
|
|
41657
|
-
summary: record2.summary
|
|
42221
|
+
summary: record2.summary,
|
|
42222
|
+
...record2.pieces && { pieces: structuredClone(record2.pieces) }
|
|
41658
42223
|
};
|
|
41659
42224
|
}
|
|
41660
42225
|
function applyTiming(next, prior, now, status = next.status) {
|
|
@@ -41695,7 +42260,7 @@ function mergeSignals(a, b2) {
|
|
|
41695
42260
|
return AbortSignal.any([a, b2]);
|
|
41696
42261
|
}
|
|
41697
42262
|
|
|
41698
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
42263
|
+
// node_modules/@dvmkit/sdk/dist/chunk-MCO3VBIB.js
|
|
41699
42264
|
import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
|
|
41700
42265
|
var TEMPO_SETTLEMENT_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
|
|
41701
42266
|
function isTempoInsufficientFundsError(error62) {
|
|
@@ -43046,7 +43611,7 @@ function isTempoCloseTransaction(reference) {
|
|
|
43046
43611
|
return typeof reference === "string" && /^0x[0-9a-fA-F]{64}$/.test(reference);
|
|
43047
43612
|
}
|
|
43048
43613
|
|
|
43049
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
43614
|
+
// node_modules/@dvmkit/sdk/dist/chunk-IUCPKTRA.js
|
|
43050
43615
|
import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
|
|
43051
43616
|
import { createHash as createHash23 } from "crypto";
|
|
43052
43617
|
import { createHash as createHash33 } from "crypto";
|
|
@@ -46504,7 +47069,7 @@ var BatchSettlementEvmScheme3 = class {
|
|
|
46504
47069
|
}
|
|
46505
47070
|
};
|
|
46506
47071
|
|
|
46507
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
47072
|
+
// node_modules/@dvmkit/sdk/dist/chunk-IUCPKTRA.js
|
|
46508
47073
|
import { randomUUID as randomUUID22 } from "crypto";
|
|
46509
47074
|
import { createHash as createHash42 } from "crypto";
|
|
46510
47075
|
import { createHash as createHash62, randomBytes as randomBytes8, randomUUID as randomUUID32 } from "crypto";
|
|
@@ -66228,7 +66793,7 @@ function date4(params) {
|
|
|
66228
66793
|
return _coercedDate(ZodDate, params);
|
|
66229
66794
|
}
|
|
66230
66795
|
|
|
66231
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
66796
|
+
// node_modules/@dvmkit/sdk/dist/chunk-IUCPKTRA.js
|
|
66232
66797
|
import { createHash as createHash72 } from "crypto";
|
|
66233
66798
|
import { createHash as createHash82, randomUUID as randomUUID42 } from "crypto";
|
|
66234
66799
|
import { isDeepStrictEqual as isDeepStrictEqual22 } from "util";
|
|
@@ -68286,7 +68851,7 @@ var streamSSE = (c, cb, onError) => {
|
|
|
68286
68851
|
return c.newResponse(stream2.responseReadable);
|
|
68287
68852
|
};
|
|
68288
68853
|
|
|
68289
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
68854
|
+
// node_modules/@dvmkit/sdk/dist/chunk-IUCPKTRA.js
|
|
68290
68855
|
import { createHash as createHash12 } from "crypto";
|
|
68291
68856
|
async function initLockPubkeyTable(db) {
|
|
68292
68857
|
await withSdkInitLock(db, () => createLockPubkeyTable(db));
|
|
@@ -69196,10 +69761,16 @@ async function msatsToFiatMicro(args) {
|
|
|
69196
69761
|
}
|
|
69197
69762
|
function pinAskFiat(args) {
|
|
69198
69763
|
if (!args.msats) return void 0;
|
|
69199
|
-
|
|
69200
|
-
|
|
69764
|
+
if (args.exact?.currency === args.currency) return fiatAmountMicro(args.exact);
|
|
69765
|
+
return fiatAmountMicro({
|
|
69766
|
+
amount: satsToFiat(args.msats / 1e3, fxRateFor(args.fx, args.currency)),
|
|
69767
|
+
currency: args.currency
|
|
69768
|
+
});
|
|
69769
|
+
}
|
|
69770
|
+
function fiatAmountMicro(fiat) {
|
|
69771
|
+
const rounded = Math.round(fiat.amount * 1e6);
|
|
69201
69772
|
if (!Number.isSafeInteger(rounded)) return void 0;
|
|
69202
|
-
return { currency:
|
|
69773
|
+
return { currency: fiat.currency, amountMicro: Math.max(1, rounded) };
|
|
69203
69774
|
}
|
|
69204
69775
|
function fundedMicroFor(priceFiat, paidMsats, requiredMsats) {
|
|
69205
69776
|
if (!Number.isFinite(requiredMsats) || requiredMsats <= 0) {
|
|
@@ -69226,6 +69797,7 @@ function implicitCreditId(rail, paymentId) {
|
|
|
69226
69797
|
}
|
|
69227
69798
|
var DEFERRED_X402_SETTLE_MARGIN_SECONDS = 15;
|
|
69228
69799
|
var DEFERRED_X402_SIGNING_ALLOWANCE_SECONDS = 15;
|
|
69800
|
+
var DEFERRED_X402_MAX_OUTSTANDING_PER_PAYER = 1;
|
|
69229
69801
|
function deferredX402Window(maxRuntimeSeconds) {
|
|
69230
69802
|
const minValidSeconds = maxRuntimeSeconds + DEFERRED_X402_SETTLE_MARGIN_SECONDS;
|
|
69231
69803
|
return {
|
|
@@ -71263,18 +71835,42 @@ var PostgresX402ExactSettlementStore = class {
|
|
|
71263
71835
|
`CREATE INDEX IF NOT EXISTS idx_x402_exact_settlement_queue
|
|
71264
71836
|
ON x402_exact_settlement_intents (dvm_id, status, updated_at)`
|
|
71265
71837
|
);
|
|
71838
|
+
await this.pool.query(
|
|
71839
|
+
`CREATE INDEX IF NOT EXISTS idx_x402_exact_settlement_payer
|
|
71840
|
+
ON x402_exact_settlement_intents (dvm_id, authorizer, status)`
|
|
71841
|
+
);
|
|
71266
71842
|
});
|
|
71267
71843
|
}
|
|
71268
71844
|
async prepare(intent) {
|
|
71269
71845
|
return (await this.claim(intent)).intent;
|
|
71270
71846
|
}
|
|
71271
|
-
async claim(intent) {
|
|
71847
|
+
async claim(intent, opts) {
|
|
71272
71848
|
const now = Date.now();
|
|
71273
71849
|
const existing = await this.get(intent.dvmId, intent.id);
|
|
71274
71850
|
if (existing && !sameIntentBinding(existing, intent)) {
|
|
71275
71851
|
throw new X402ExactIntentConflictError(intent.id);
|
|
71276
71852
|
}
|
|
71853
|
+
const limit = existing ? void 0 : opts?.maxOutstandingPerPayer;
|
|
71277
71854
|
const write = async (q2) => {
|
|
71855
|
+
if (limit !== void 0) {
|
|
71856
|
+
await q2.query(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
|
|
71857
|
+
`x402-payer:${intent.dvmId}:${intent.from}`
|
|
71858
|
+
]);
|
|
71859
|
+
const present = await q2.query(
|
|
71860
|
+
`SELECT 1 FROM x402_exact_settlement_intents WHERE dvm_id = $1 AND intent_id = $2`,
|
|
71861
|
+
[intent.dvmId, intent.id]
|
|
71862
|
+
);
|
|
71863
|
+
if (present.rowCount) return false;
|
|
71864
|
+
const { rows: rows2 } = await q2.query(
|
|
71865
|
+
`SELECT count(*)::text AS n FROM x402_exact_settlement_intents
|
|
71866
|
+
WHERE dvm_id = $1 AND authorizer = $2
|
|
71867
|
+
AND (status IN ('submitting', 'ambiguous')
|
|
71868
|
+
OR (status = 'prepared' AND CASE WHEN valid_before ~ '^[0-9]+$'
|
|
71869
|
+
THEN valid_before::numeric > $3 ELSE false END))`,
|
|
71870
|
+
[intent.dvmId, intent.from, Math.floor(now / 1e3)]
|
|
71871
|
+
);
|
|
71872
|
+
if (Number(rows2[0]?.n ?? 0) >= limit) throw new X402ExactPayerLimitError(intent.from);
|
|
71873
|
+
}
|
|
71278
71874
|
const authFingerprint = intent.effect?.jobAdmission?.authFingerprint;
|
|
71279
71875
|
if (authFingerprint) {
|
|
71280
71876
|
await q2.query(
|
|
@@ -71331,6 +71927,18 @@ var PostgresX402ExactSettlementStore = class {
|
|
|
71331
71927
|
fundId: effect?.fundOnly?.fundId,
|
|
71332
71928
|
callerPubkey: effect?.jobId ? void 0 : effect?.callerId
|
|
71333
71929
|
}, write);
|
|
71930
|
+
} else if (limit !== void 0) {
|
|
71931
|
+
const tx = await this.pool.connect();
|
|
71932
|
+
try {
|
|
71933
|
+
await tx.query("BEGIN");
|
|
71934
|
+
inserted = await write(tx);
|
|
71935
|
+
await tx.query("COMMIT");
|
|
71936
|
+
} catch (error62) {
|
|
71937
|
+
await tx.query("ROLLBACK").catch(() => void 0);
|
|
71938
|
+
throw error62;
|
|
71939
|
+
} finally {
|
|
71940
|
+
tx.release();
|
|
71941
|
+
}
|
|
71334
71942
|
} else {
|
|
71335
71943
|
inserted = await write(this.pool);
|
|
71336
71944
|
}
|
|
@@ -71537,6 +72145,14 @@ var X402ExactIntentConflictError = class extends Error {
|
|
|
71537
72145
|
}
|
|
71538
72146
|
intentId;
|
|
71539
72147
|
};
|
|
72148
|
+
var X402ExactPayerLimitError = class extends Error {
|
|
72149
|
+
constructor(payer) {
|
|
72150
|
+
super(`x402 payer ${payer} has too many outstanding authorizations`);
|
|
72151
|
+
this.payer = payer;
|
|
72152
|
+
this.name = "X402ExactPayerLimitError";
|
|
72153
|
+
}
|
|
72154
|
+
payer;
|
|
72155
|
+
};
|
|
71540
72156
|
var X402ExactSettlementNotReadyError = class extends Error {
|
|
71541
72157
|
constructor(intentId, status) {
|
|
71542
72158
|
super(`x402 exact intent ${intentId} is ${status}, not settled`);
|
|
@@ -71660,16 +72276,25 @@ var X402ExactSettlementServer = class {
|
|
|
71660
72276
|
if (!verified.isValid) {
|
|
71661
72277
|
return { outcome: "rejected", intentId, reason: verified.invalidReason ?? "verify_failed" };
|
|
71662
72278
|
}
|
|
71663
|
-
|
|
71664
|
-
|
|
71665
|
-
|
|
71666
|
-
|
|
71667
|
-
|
|
71668
|
-
|
|
71669
|
-
|
|
72279
|
+
let payerLimited = false;
|
|
72280
|
+
const claimed = await this.opts.store.claim(
|
|
72281
|
+
{
|
|
72282
|
+
id: intentId,
|
|
72283
|
+
dvmId: args.dvmId,
|
|
72284
|
+
resource: args.resource,
|
|
72285
|
+
...facts,
|
|
72286
|
+
effect: args.effect
|
|
72287
|
+
},
|
|
72288
|
+
{ maxOutstandingPerPayer: args.maxOutstandingPerPayer }
|
|
72289
|
+
).catch((err) => {
|
|
72290
|
+
if (err instanceof X402ExactPayerLimitError) {
|
|
72291
|
+
payerLimited = true;
|
|
72292
|
+
return void 0;
|
|
72293
|
+
}
|
|
71670
72294
|
if (err instanceof X402ExactIntentConflictError) return void 0;
|
|
71671
72295
|
throw err;
|
|
71672
72296
|
});
|
|
72297
|
+
if (payerLimited) return { outcome: "payer_limit", intentId };
|
|
71673
72298
|
if (!claimed?.inserted) return { outcome: "replayed", intentId };
|
|
71674
72299
|
return { outcome: "prepared", intentId, payload, requirements, validBeforeMs };
|
|
71675
72300
|
}
|
|
@@ -73173,7 +73798,7 @@ async function verifyUpfrontPaymentInScope(opts) {
|
|
|
73173
73798
|
x402Requirements
|
|
73174
73799
|
});
|
|
73175
73800
|
}
|
|
73176
|
-
const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-
|
|
73801
|
+
const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-ARXZQ5BD-H6PNJYYT.js");
|
|
73177
73802
|
const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
|
|
73178
73803
|
x402Payment,
|
|
73179
73804
|
x402Config,
|
|
@@ -73186,18 +73811,8 @@ async function verifyUpfrontPaymentInScope(opts) {
|
|
|
73186
73811
|
const settledUsdcMicro = receipt.amountUsdcMicro;
|
|
73187
73812
|
const paidMsats = settledUsdcMicro === void 0 ? receipt.amountMsats : x402SettledShare(requiredMsats, Number(requiredUsdcMicro), settledUsdcMicro);
|
|
73188
73813
|
let credited;
|
|
73189
|
-
const paymentId = receipt.txHash;
|
|
73190
|
-
if (ledgerCtx
|
|
73191
|
-
if (creditEnv?.fund) {
|
|
73192
|
-
logCreditRejected("x402_missing_tx_hash_explicit_fund", creditEnv.creditId);
|
|
73193
|
-
return creditRefusal(
|
|
73194
|
-
"payment_invalid",
|
|
73195
|
-
"The payment settled but returned no transaction reference, so the signed funding commitment cannot be recorded. The explicit funding was refused; retry without a fund block or contact the service operator."
|
|
73196
|
-
);
|
|
73197
|
-
}
|
|
73198
|
-
logCreditRejected("x402_missing_tx_hash", void 0);
|
|
73199
|
-
}
|
|
73200
|
-
if (ledgerCtx && paymentId) {
|
|
73814
|
+
const paymentId = x402FundingId(receipt.txHash, x402Payment);
|
|
73815
|
+
if (ledgerCtx) {
|
|
73201
73816
|
const fundedMicro = settledUsdcMicro === void 0 ? fundedMicroFor(ledgerCtx.priceFiat, paidMsats, ledgerCtx.requiredMsats) : x402SettledShare(
|
|
73202
73817
|
ledgerCtx.priceFiat.amountMicro,
|
|
73203
73818
|
Number(requiredUsdcMicro),
|
|
@@ -73786,6 +74401,11 @@ var PAYMENT_ERROR_COPY = {
|
|
|
73786
74401
|
hint: "Sign a new authorization that stays valid for at least the maxTimeoutSeconds in the payment requirements, and send it again.",
|
|
73787
74402
|
retryable: true
|
|
73788
74403
|
},
|
|
74404
|
+
x402_payer_busy: {
|
|
74405
|
+
display: "This wallet already has a payment authorization in use for a running job, so this one was not accepted. Nothing was charged.",
|
|
74406
|
+
hint: "Wait for the running job to finish, or pay from another wallet, then send the request again.",
|
|
74407
|
+
retryable: true
|
|
74408
|
+
},
|
|
73789
74409
|
x402_not_offered: {
|
|
73790
74410
|
display: "This service does not offer x402 payment for prices in its configured currency. Nothing was charged.",
|
|
73791
74411
|
hint: "Use one of the payment methods advertised by this service and submit the request again.",
|
|
@@ -74166,7 +74786,9 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74166
74786
|
};
|
|
74167
74787
|
}
|
|
74168
74788
|
const requestId = typeof body.content.cashu_request_id === "string" ? body.content.cashu_request_id : void 0;
|
|
74169
|
-
const
|
|
74789
|
+
const resolved = await resolveTopUpLedgerContext(opts, snapshot, { rail: "cashu" });
|
|
74790
|
+
if (resolved.error) return { error: resolved.error };
|
|
74791
|
+
const ledgerCtx = resolved.ctx;
|
|
74170
74792
|
const result = await verifyAccumulatorReceipt(
|
|
74171
74793
|
{
|
|
74172
74794
|
cashuToken: body.content.cashu_token,
|
|
@@ -74179,7 +74801,9 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74179
74801
|
cashuLockWindowSeconds: lockWindowOrDefault(opts.cashuLockWindowSeconds)
|
|
74180
74802
|
},
|
|
74181
74803
|
mints,
|
|
74182
|
-
|
|
74804
|
+
// A balance landing has no ask to fall short of: whatever arrived is
|
|
74805
|
+
// the caller's balance, never a short payment refused after receipt.
|
|
74806
|
+
ledgerCtx.askSatisfied ? void 0 : snapshot.pendingPaymentMsats,
|
|
74183
74807
|
ledgerCtx
|
|
74184
74808
|
);
|
|
74185
74809
|
if (result.error) {
|
|
@@ -74234,7 +74858,30 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74234
74858
|
snapshot
|
|
74235
74859
|
});
|
|
74236
74860
|
}
|
|
74237
|
-
const
|
|
74861
|
+
const resolved = await resolveTopUpLedgerContext(
|
|
74862
|
+
opts,
|
|
74863
|
+
snapshot,
|
|
74864
|
+
await incomingCreditBinding({
|
|
74865
|
+
rail: "x402",
|
|
74866
|
+
x402Payment: body.content.x402_payment
|
|
74867
|
+
})
|
|
74868
|
+
);
|
|
74869
|
+
if (resolved.error) return { error: resolved.error };
|
|
74870
|
+
const ledgerCtx = resolved.ctx;
|
|
74871
|
+
if (snapshot.pendingX402Nonce !== void 0) {
|
|
74872
|
+
const incomingNonce = decodePayment(body.content.x402_payment).payload.authorization.nonce;
|
|
74873
|
+
if (incomingNonce !== snapshot.pendingX402Nonce) {
|
|
74874
|
+
return {
|
|
74875
|
+
error: {
|
|
74876
|
+
body: paymentErrorBody("payment_invalid", {
|
|
74877
|
+
message: "x402 payment not bound to this job"
|
|
74878
|
+
}),
|
|
74879
|
+
status: 402
|
|
74880
|
+
}
|
|
74881
|
+
};
|
|
74882
|
+
}
|
|
74883
|
+
}
|
|
74884
|
+
const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-ARXZQ5BD-H6PNJYYT.js");
|
|
74238
74885
|
const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
|
|
74239
74886
|
body.content.x402_payment,
|
|
74240
74887
|
opts.x402Config,
|
|
@@ -74253,55 +74900,29 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74253
74900
|
}
|
|
74254
74901
|
};
|
|
74255
74902
|
}
|
|
74256
|
-
|
|
74257
|
-
|
|
74258
|
-
|
|
74903
|
+
let credited;
|
|
74904
|
+
const paymentId = x402FundingId(receipt.txHash, body.content.x402_payment);
|
|
74905
|
+
try {
|
|
74906
|
+
credited = await commitMarkedFunding(ledgerCtx, {
|
|
74907
|
+
rail: "x402",
|
|
74908
|
+
paymentId,
|
|
74909
|
+
paidMsats: midJobFundedMsats(snapshot, receipt.amountMsats),
|
|
74910
|
+
nativeAmount: receipt.amountUsdcMicro,
|
|
74911
|
+
nativeAsset: "usdc"
|
|
74912
|
+
});
|
|
74913
|
+
} catch (err) {
|
|
74914
|
+
const mapped = mapLedgerCommitError(err, void 0, true);
|
|
74915
|
+
if (mapped?.error) {
|
|
74916
|
+
logCredentialRejected("x402", "mid-job", err);
|
|
74259
74917
|
return {
|
|
74260
74918
|
error: {
|
|
74261
|
-
body:
|
|
74262
|
-
|
|
74263
|
-
}
|
|
74264
|
-
status: 402
|
|
74919
|
+
body: mapped.error.body,
|
|
74920
|
+
status: mapped.error.status,
|
|
74921
|
+
...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
|
|
74265
74922
|
}
|
|
74266
74923
|
};
|
|
74267
74924
|
}
|
|
74268
|
-
|
|
74269
|
-
const ledgerCtx = await resolveTopUpLedgerContext(
|
|
74270
|
-
opts,
|
|
74271
|
-
snapshot,
|
|
74272
|
-
await incomingCreditBinding({
|
|
74273
|
-
rail: "x402",
|
|
74274
|
-
x402Payment: body.content.x402_payment
|
|
74275
|
-
})
|
|
74276
|
-
);
|
|
74277
|
-
let credited;
|
|
74278
|
-
const paymentId = receipt.txHash;
|
|
74279
|
-
if (ledgerCtx && !paymentId) {
|
|
74280
|
-
logCreditRejected("x402_missing_tx_hash", void 0);
|
|
74281
|
-
}
|
|
74282
|
-
if (ledgerCtx && paymentId) {
|
|
74283
|
-
try {
|
|
74284
|
-
credited = await commitMarkedFunding(ledgerCtx, {
|
|
74285
|
-
rail: "x402",
|
|
74286
|
-
paymentId,
|
|
74287
|
-
paidMsats: midJobFundedMsats(snapshot, receipt.amountMsats),
|
|
74288
|
-
nativeAmount: receipt.amountUsdcMicro,
|
|
74289
|
-
nativeAsset: "usdc"
|
|
74290
|
-
});
|
|
74291
|
-
} catch (err) {
|
|
74292
|
-
const mapped = mapLedgerCommitError(err, void 0, true);
|
|
74293
|
-
if (mapped?.error) {
|
|
74294
|
-
logCredentialRejected("x402", "mid-job", err);
|
|
74295
|
-
return {
|
|
74296
|
-
error: {
|
|
74297
|
-
body: mapped.error.body,
|
|
74298
|
-
status: mapped.error.status,
|
|
74299
|
-
...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
|
|
74300
|
-
}
|
|
74301
|
-
};
|
|
74302
|
-
}
|
|
74303
|
-
throw err;
|
|
74304
|
-
}
|
|
74925
|
+
throw err;
|
|
74305
74926
|
}
|
|
74306
74927
|
const info = withDrawBasis(
|
|
74307
74928
|
{
|
|
@@ -74386,11 +75007,13 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74386
75007
|
credential.challenge.method
|
|
74387
75008
|
);
|
|
74388
75009
|
const nativeAsset = methodNativeAsset(credential.challenge.method);
|
|
74389
|
-
const
|
|
75010
|
+
const resolved = await resolveTopUpLedgerContext(
|
|
74390
75011
|
opts,
|
|
74391
75012
|
snapshot,
|
|
74392
75013
|
await incomingCreditBinding({ rail: "tempo", mppCredential: credential })
|
|
74393
75014
|
);
|
|
75015
|
+
if (resolved.error) return { error: resolved.error };
|
|
75016
|
+
const ledgerCtx = resolved.ctx;
|
|
74394
75017
|
const funding = {
|
|
74395
75018
|
rail: "tempo",
|
|
74396
75019
|
paymentId: mppPaymentId(credential),
|
|
@@ -74415,23 +75038,21 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74415
75038
|
{ onError: paymentFailureFields }
|
|
74416
75039
|
);
|
|
74417
75040
|
let credited;
|
|
74418
|
-
|
|
74419
|
-
|
|
74420
|
-
|
|
74421
|
-
|
|
74422
|
-
|
|
74423
|
-
|
|
74424
|
-
|
|
74425
|
-
|
|
74426
|
-
|
|
74427
|
-
|
|
74428
|
-
|
|
74429
|
-
|
|
74430
|
-
|
|
74431
|
-
};
|
|
74432
|
-
}
|
|
74433
|
-
throw err;
|
|
75041
|
+
try {
|
|
75042
|
+
credited = await commitMppFunding(ledgerCtx, credential, funding);
|
|
75043
|
+
} catch (err) {
|
|
75044
|
+
const mapped = mapLedgerCommitError(err, void 0, true);
|
|
75045
|
+
if (mapped?.error) {
|
|
75046
|
+
logCredentialRejected("tempo", "mid-job", err);
|
|
75047
|
+
return {
|
|
75048
|
+
error: {
|
|
75049
|
+
body: mapped.error.body,
|
|
75050
|
+
status: mapped.error.status,
|
|
75051
|
+
...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
|
|
75052
|
+
}
|
|
75053
|
+
};
|
|
74434
75054
|
}
|
|
75055
|
+
throw err;
|
|
74435
75056
|
}
|
|
74436
75057
|
if (credited) {
|
|
74437
75058
|
await mppServer.completeHostedTempoCharge?.(credential.challenge.id).catch((error62) => {
|
|
@@ -74477,6 +75098,11 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
|
|
|
74477
75098
|
message: "Payment method is not configured"
|
|
74478
75099
|
}) } };
|
|
74479
75100
|
}
|
|
75101
|
+
function x402FundingId(txHash, paymentHeader) {
|
|
75102
|
+
if (txHash) return txHash;
|
|
75103
|
+
const { from, nonce } = decodePayment(paymentHeader).payload.authorization;
|
|
75104
|
+
return `eip3009:${from.toLowerCase()}:${nonce.toLowerCase()}`;
|
|
75105
|
+
}
|
|
74480
75106
|
function midJobFundedMsats(snapshot, railMsats) {
|
|
74481
75107
|
const pending = snapshot.pendingPaymentMsats ?? 0;
|
|
74482
75108
|
return pending > 0 ? pending : railMsats;
|
|
@@ -74495,16 +75121,18 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74495
75121
|
}
|
|
74496
75122
|
const requiredMsats = args.snapshot.pendingPaymentMsats ?? 0;
|
|
74497
75123
|
const authorizedUsdcMicro = Number.parseInt(authorization.value, 10);
|
|
74498
|
-
const
|
|
75124
|
+
const resolved = await resolveTopUpLedgerContext(
|
|
74499
75125
|
args.opts,
|
|
74500
75126
|
args.snapshot,
|
|
74501
75127
|
await incomingCreditBinding({ rail: "x402", x402Payment: args.paymentHeader })
|
|
74502
75128
|
);
|
|
75129
|
+
if (resolved.error) return { error: resolved.error };
|
|
75130
|
+
const ledgerCtx = resolved.ctx;
|
|
74503
75131
|
const paidMsats = midJobFundedMsats(
|
|
74504
75132
|
args.snapshot,
|
|
74505
75133
|
x402SettledShare(requiredMsats, Number(args.requiredUsdcMicro), authorizedUsdcMicro)
|
|
74506
75134
|
);
|
|
74507
|
-
const fundedMicro =
|
|
75135
|
+
const fundedMicro = fundedMicroFor(ledgerCtx.priceFiat, paidMsats, ledgerCtx.requiredMsats);
|
|
74508
75136
|
const accepted = await args.settlement.accept({
|
|
74509
75137
|
paymentHeader: args.paymentHeader,
|
|
74510
75138
|
config: args.config,
|
|
@@ -74513,13 +75141,13 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74513
75141
|
btcUsdRate: args.btcUsdRate,
|
|
74514
75142
|
exactVersions: args.exactVersions,
|
|
74515
75143
|
dvmId: args.opts.dvmId ?? "",
|
|
74516
|
-
effect:
|
|
75144
|
+
effect: exactSettlementEffect(ledgerCtx, {
|
|
74517
75145
|
paidMsats,
|
|
74518
75146
|
fundedMicro,
|
|
74519
75147
|
nativeAmount: authorizedUsdcMicro
|
|
74520
|
-
})
|
|
75148
|
+
}),
|
|
74521
75149
|
commit: async (receipt, tx) => {
|
|
74522
|
-
if (!
|
|
75150
|
+
if (!receipt.txHash) return void 0;
|
|
74523
75151
|
return commitMarkedFunding(
|
|
74524
75152
|
ledgerCtx,
|
|
74525
75153
|
{
|
|
@@ -74561,7 +75189,7 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74561
75189
|
let replayedDrawFound = false;
|
|
74562
75190
|
let replayedCreditId;
|
|
74563
75191
|
let replayedDrawId;
|
|
74564
|
-
if (accepted.replayed &&
|
|
75192
|
+
if (accepted.replayed && accepted.receipt.txHash) {
|
|
74565
75193
|
replayedCreditId = ledgerCtx.topUp?.creditId ?? ledgerCtx.creditEnvelope?.creditId ?? implicitCreditId("x402", accepted.receipt.txHash);
|
|
74566
75194
|
replayedDrawId = ledgerCtx.topUp?.drawId ?? ledgerCtx.creditEnvelope?.drawId ?? accepted.receipt.txHash;
|
|
74567
75195
|
replayedDrawFound = await ledgerCtx.ledger.getDraw({
|
|
@@ -74569,7 +75197,7 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74569
75197
|
drawId: replayedDrawId
|
|
74570
75198
|
}) !== void 0;
|
|
74571
75199
|
}
|
|
74572
|
-
const replayedDrawFunding = accepted.replayed && ledgerCtx
|
|
75200
|
+
const replayedDrawFunding = accepted.replayed && ledgerCtx.topUp && accepted.receipt.txHash ? await ledgerCtx.ledger.getFunding({
|
|
74573
75201
|
creditId: ledgerCtx.topUp.creditId,
|
|
74574
75202
|
fundId: accepted.receipt.txHash
|
|
74575
75203
|
}) : void 0;
|
|
@@ -74579,7 +75207,7 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74579
75207
|
paidMsats: args.snapshot.pendingPaymentMsats ?? accepted.receipt.amountMsats,
|
|
74580
75208
|
paymentRail: "x402",
|
|
74581
75209
|
receivedProofs: [],
|
|
74582
|
-
paymentTxHash: replayedDrawFound && replayedCreditId && replayedDrawId ? drawSettlementRef(ledgerCtx
|
|
75210
|
+
paymentTxHash: replayedDrawFound && replayedCreditId && replayedDrawId ? drawSettlementRef(ledgerCtx.dvmId, replayedCreditId, replayedDrawId) : accepted.receipt.txHash,
|
|
74583
75211
|
nativeAmount: authorizedUsdcMicro,
|
|
74584
75212
|
nativeAsset: "usdc",
|
|
74585
75213
|
...replayedDrawFound && replayedCreditId && replayedDrawId ? { creditId: replayedCreditId, drawId: replayedDrawId } : {}
|
|
@@ -74602,6 +75230,10 @@ async function acceptDurableExactIncoming(args) {
|
|
|
74602
75230
|
function topUpBinding(info, snapshot) {
|
|
74603
75231
|
const fresh = !snapshot.creditId && info.creditId && info.drawId;
|
|
74604
75232
|
return {
|
|
75233
|
+
...info.drawId && info.drawAddedMicro !== void 0 && !info.landedAsBalance && {
|
|
75234
|
+
piece: { amountMicro: info.drawAddedMicro, drawId: info.drawId }
|
|
75235
|
+
},
|
|
75236
|
+
...info.landedAsBalance && { landedAsBalance: info.landedAsBalance },
|
|
74605
75237
|
...fresh && { creditId: info.creditId, drawId: info.drawId },
|
|
74606
75238
|
...info.funding && { funding: info.funding },
|
|
74607
75239
|
...info.unappliedMicro !== void 0 && { unappliedMicro: info.unappliedMicro },
|
|
@@ -74629,180 +75261,46 @@ function applyPaymentInfoToJob(job, info) {
|
|
|
74629
75261
|
}
|
|
74630
75262
|
creditPendingPayment(job);
|
|
74631
75263
|
}
|
|
74632
|
-
|
|
74633
|
-
return
|
|
75264
|
+
function incomingPaymentSnapshot(job) {
|
|
75265
|
+
return {
|
|
75266
|
+
pendingPaymentMsats: job.pendingPaymentMsats,
|
|
75267
|
+
pendingMppChallengeIds: job.pendingMppChallengeIds,
|
|
75268
|
+
pendingX402Nonce: job.pendingX402Nonce,
|
|
75269
|
+
pendingX402AmountUsdcMicro: job.pendingX402AmountUsdcMicro,
|
|
75270
|
+
paymentRail: job.paymentRail,
|
|
75271
|
+
creditId: job.creditId,
|
|
75272
|
+
drawId: job.drawId,
|
|
75273
|
+
paymentTxHash: job.paymentTxHash,
|
|
75274
|
+
pendingPaymentFiatMicro: job.pendingPaymentFiatMicro,
|
|
75275
|
+
pendingPaymentFiatCurrency: job.pendingPaymentFiatCurrency,
|
|
75276
|
+
askedTopUpMicro: job.askedTopUpMicro,
|
|
75277
|
+
askedTopUpCurrency: job.askedTopUpCurrency,
|
|
75278
|
+
topUpCapUnenforcedReason: job.topUpCapUnenforcedReason,
|
|
75279
|
+
requesterPubkey: job.requesterPubkey,
|
|
75280
|
+
requesterId: job.requesterId,
|
|
75281
|
+
...askFiatAmount(job) && { askFiatAmount: askFiatAmount(job) }
|
|
75282
|
+
};
|
|
74634
75283
|
}
|
|
74635
|
-
|
|
74636
|
-
|
|
74637
|
-
|
|
74638
|
-
|
|
74639
|
-
|
|
74640
|
-
|
|
74641
|
-
|
|
74642
|
-
|
|
74643
|
-
|
|
74644
|
-
}),
|
|
74645
|
-
status: 402
|
|
74646
|
-
};
|
|
74647
|
-
}
|
|
74648
|
-
const requestId = typeof body.content.cashu_request_id === "string" ? body.content.cashu_request_id : void 0;
|
|
74649
|
-
const result = await verifyAccumulatorReceipt(
|
|
74650
|
-
{
|
|
74651
|
-
cashuToken: body.content.cashu_token,
|
|
74652
|
-
accumulatorDb: opts.accumulatorDb,
|
|
74653
|
-
disposableCashu: opts.disposableCashu,
|
|
74654
|
-
dvmId: opts.dvmId,
|
|
74655
|
-
lockPubkeys: opts.lockPubkeys,
|
|
74656
|
-
requestId,
|
|
74657
|
-
mintHealthTracker: opts.mintHealthTracker,
|
|
74658
|
-
cashuLockWindowSeconds: lockWindowOrDefault(opts.cashuLockWindowSeconds)
|
|
74659
|
-
},
|
|
74660
|
-
mints,
|
|
74661
|
-
job.pendingPaymentMsats
|
|
74662
|
-
);
|
|
74663
|
-
if (result.error) {
|
|
74664
|
-
return { body: result.error.body, status: result.error.status };
|
|
74665
|
-
}
|
|
74666
|
-
job.paidMsats += result.paidMsats;
|
|
74667
|
-
if (result.paymentMint) job.paymentMint = result.paymentMint;
|
|
74668
|
-
job.paymentRail = "cashu";
|
|
74669
|
-
job.paymentTxHash = result.paymentTxHash;
|
|
74670
|
-
job.cashuFlow = result.cashuFlow;
|
|
74671
|
-
creditPendingPayment(job);
|
|
74672
|
-
return null;
|
|
74673
|
-
}
|
|
74674
|
-
return {
|
|
74675
|
-
body: paymentErrorBody("cashu_not_p2pk_locked", {
|
|
74676
|
-
message: "This DVM requires P2PK-locked Cashu proofs. Initialize an agent wallet first."
|
|
74677
|
-
}),
|
|
74678
|
-
status: 402
|
|
74679
|
-
};
|
|
74680
|
-
} else if (body.content.x402_payment && opts.x402Config) {
|
|
74681
|
-
if ((opts.pricingCurrency ?? "usd") !== "usd") {
|
|
74682
|
-
return x402NotOfferedPaymentError(opts.pricingCurrency);
|
|
74683
|
-
}
|
|
74684
|
-
const rate = await resolveRateOrNull(opts.fxFetcher);
|
|
74685
|
-
if (rate === null) return rateUnavailablePaymentError();
|
|
74686
|
-
try {
|
|
74687
|
-
const requiredMsats = job.pendingPaymentMsats ?? 0;
|
|
74688
|
-
const requiredUsdcMicro = job.pendingX402AmountUsdcMicro !== void 0 ? BigInt(job.pendingX402AmountUsdcMicro) : BigInt(msatsToUsdc(requiredMsats, rate));
|
|
74689
|
-
const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-MFBRORHG-34VE7EWO.js");
|
|
74690
|
-
const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
|
|
74691
|
-
body.content.x402_payment,
|
|
74692
|
-
opts.x402Config,
|
|
74693
|
-
requiredUsdcMicro,
|
|
74694
|
-
opts.resourcePath ?? "/v1/job",
|
|
74695
|
-
rate,
|
|
74696
|
-
opts.x402ExactVersions
|
|
74697
|
-
));
|
|
74698
|
-
if (receipt.verified) {
|
|
74699
|
-
if (job.pendingX402Nonce !== void 0) {
|
|
74700
|
-
const incomingNonce = decodePayment(body.content.x402_payment).payload.authorization.nonce;
|
|
74701
|
-
if (incomingNonce !== job.pendingX402Nonce) {
|
|
74702
|
-
return {
|
|
74703
|
-
body: paymentErrorBody("payment_invalid", {
|
|
74704
|
-
message: "x402 payment not bound to this job"
|
|
74705
|
-
}),
|
|
74706
|
-
status: 402
|
|
74707
|
-
};
|
|
74708
|
-
}
|
|
74709
|
-
}
|
|
74710
|
-
job.paidMsats += job.pendingPaymentMsats ?? receipt.amountMsats;
|
|
74711
|
-
const sameRail = job.paymentRail === "x402";
|
|
74712
|
-
job.nativeAmount = (sameRail ? job.nativeAmount ?? 0 : 0) + (receipt.amountUsdcMicro ?? 0);
|
|
74713
|
-
job.nativeAsset = "usdc";
|
|
74714
|
-
job.paymentTxHash = receipt.txHash;
|
|
74715
|
-
job.paymentRail = "x402";
|
|
74716
|
-
job.pendingX402Nonce = void 0;
|
|
74717
|
-
job.pendingX402AmountUsdcMicro = void 0;
|
|
74718
|
-
creditPendingPayment(job);
|
|
74719
|
-
} else {
|
|
74720
|
-
return {
|
|
74721
|
-
body: paymentErrorBody("payment_invalid", {
|
|
74722
|
-
message: "x402 signature verification failed"
|
|
74723
|
-
}),
|
|
74724
|
-
status: 402
|
|
74725
|
-
};
|
|
74726
|
-
}
|
|
74727
|
-
} catch (err) {
|
|
74728
|
-
logCredentialRejected("x402", "mid-job", err);
|
|
74729
|
-
return {
|
|
74730
|
-
body: paymentErrorBody("payment_invalid", { message: "x402 verification error" }),
|
|
74731
|
-
status: 402
|
|
74732
|
-
};
|
|
74733
|
-
}
|
|
74734
|
-
} else if (body.content.tempo_credential && opts.mpp) {
|
|
74735
|
-
const mppHandle = opts.mpp;
|
|
74736
|
-
const rate = await resolveRateOrNull(opts.fxFetcher);
|
|
74737
|
-
if (rate === null) return rateUnavailablePaymentError();
|
|
74738
|
-
try {
|
|
74739
|
-
const credential = body.content.tempo_credential;
|
|
74740
|
-
if (isMppSessionCredential(credential)) {
|
|
74741
|
-
return {
|
|
74742
|
-
body: paymentErrorBody("payment_invalid", { message: MPP_SESSION_ONLY_ON_CREDIT }),
|
|
74743
|
-
status: 402
|
|
74744
|
-
};
|
|
74745
|
-
}
|
|
74746
|
-
const expectedMsats = job.pendingPaymentMsats ?? 0;
|
|
74747
|
-
if (expectedMsats <= 0) {
|
|
74748
|
-
return {
|
|
74749
|
-
body: paymentErrorBody("payment_invalid", {
|
|
74750
|
-
message: "MPP credential without pending payment-request"
|
|
74751
|
-
}),
|
|
74752
|
-
status: 402
|
|
74753
|
-
};
|
|
74754
|
-
}
|
|
74755
|
-
const expectedAmount = job.pendingPaymentFiatCurrency === "usd" && job.pendingPaymentFiatMicro !== void 0 ? fiatMicroToMethodAmount(job.pendingPaymentFiatMicro, credential.challenge.method) : msatsToMethodAmount(expectedMsats, credential.challenge.method, rate);
|
|
74756
|
-
const expectedMeta = challengeMeta(credential.challenge);
|
|
74757
|
-
await loggers.tempo.span(
|
|
74758
|
-
"tempo.verify_credential",
|
|
74759
|
-
{
|
|
74760
|
-
method: credential.challenge.method,
|
|
74761
|
-
challenge_id: credential.challenge.id,
|
|
74762
|
-
amount: expectedAmount
|
|
74763
|
-
},
|
|
74764
|
-
() => withPaymentStage("verifier_broadcast", () => mppHandle.broadcastCredential(credential, {
|
|
74765
|
-
request: { amount: expectedAmount },
|
|
74766
|
-
...opts.hostingPaymentSeq !== void 0 && {
|
|
74767
|
-
hostedPaymentIntent: { jobId: opts.jobId, paymentSeq: opts.hostingPaymentSeq }
|
|
74768
|
-
},
|
|
74769
|
-
...expectedMeta && { meta: expectedMeta }
|
|
74770
|
-
})),
|
|
74771
|
-
{ onError: paymentFailureFields }
|
|
74772
|
-
);
|
|
74773
|
-
if (!job.pendingMppChallengeIds?.includes(credential.challenge.id)) {
|
|
74774
|
-
return {
|
|
74775
|
-
body: paymentErrorBody("payment_invalid", {
|
|
74776
|
-
message: "MPP credential not bound to this job"
|
|
74777
|
-
}),
|
|
74778
|
-
status: 402
|
|
74779
|
-
};
|
|
74780
|
-
}
|
|
74781
|
-
job.paidMsats += expectedMsats;
|
|
74782
|
-
const sameRail = job.paymentRail === "tempo";
|
|
74783
|
-
const creditNative = methodNativeAmountFromDecimal(
|
|
74784
|
-
expectedAmount,
|
|
74785
|
-
credential.challenge.method
|
|
74786
|
-
);
|
|
74787
|
-
job.nativeAmount = (sameRail ? job.nativeAmount ?? 0 : 0) + creditNative;
|
|
74788
|
-
job.nativeAsset = methodNativeAsset(credential.challenge.method);
|
|
74789
|
-
job.paymentTxHash = credential.challenge.id;
|
|
74790
|
-
job.paymentRail = "tempo";
|
|
74791
|
-
job.pendingMppChallengeIds = void 0;
|
|
74792
|
-
creditPendingPayment(job);
|
|
74793
|
-
await mppHandle.completeHostedTempoCharge?.(credential.challenge.id).catch((error62) => {
|
|
74794
|
-
console.warn("Hosted Tempo charge completion remains unresolved", error62);
|
|
74795
|
-
});
|
|
74796
|
-
} catch (err) {
|
|
74797
|
-
logCredentialRejected("tempo", "mid-job", err);
|
|
74798
|
-
return {
|
|
74799
|
-
body: paymentErrorBody("payment_invalid", {
|
|
74800
|
-
message: "MPP credential verification failed"
|
|
74801
|
-
}),
|
|
74802
|
-
status: 402
|
|
74803
|
-
};
|
|
74804
|
-
}
|
|
75284
|
+
function askFiatAmount(job) {
|
|
75285
|
+
const ask = job.messages?.findLast((message) => message.from === "provider" && message.type === "payment-request");
|
|
75286
|
+
const fiat = ask?.content?.fiat_amount;
|
|
75287
|
+
return typeof fiat?.amount === "number" && typeof fiat.currency === "string" ? { amount: fiat.amount, currency: fiat.currency } : void 0;
|
|
75288
|
+
}
|
|
75289
|
+
function askQuote(snapshot, currency) {
|
|
75290
|
+
if (currency === "usd" && snapshot.pendingX402AmountUsdcMicro !== void 0) {
|
|
75291
|
+
const micro = Number(snapshot.pendingX402AmountUsdcMicro);
|
|
75292
|
+
if (Number.isSafeInteger(micro) && micro > 0) return { currency, amountMicro: micro };
|
|
74805
75293
|
}
|
|
75294
|
+
return snapshot.askFiatAmount?.currency === currency ? fiatAmountMicro(snapshot.askFiatAmount) : void 0;
|
|
75295
|
+
}
|
|
75296
|
+
function paymentFullyUnapplied(info) {
|
|
75297
|
+
return info.unappliedMicro !== void 0 && info.funding !== void 0 && info.unappliedMicro >= info.funding.amountMicro;
|
|
75298
|
+
}
|
|
75299
|
+
async function processIncomingPayment(job, body, opts) {
|
|
75300
|
+
if (body.type !== "payment") return null;
|
|
75301
|
+
const result = await verifyIncomingPayment(body, { ...opts, jobId: opts.jobId ?? job.id }, incomingPaymentSnapshot(job));
|
|
75302
|
+
if (result.error) return { body: result.error.body, status: result.error.status };
|
|
75303
|
+
if (result.verified && !paymentFullyUnapplied(result.verified)) applyPaymentInfoToJob(job, result.verified);
|
|
74806
75304
|
return null;
|
|
74807
75305
|
}
|
|
74808
75306
|
function creditPendingPayment(job) {
|
|
@@ -75101,9 +75599,16 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
|
|
|
75101
75599
|
const ledger = opts.creditLedger;
|
|
75102
75600
|
const rail = binding.rail;
|
|
75103
75601
|
const requiredMsats = snapshot.pendingPaymentMsats ?? 0;
|
|
75104
|
-
if (!ledger)
|
|
75105
|
-
|
|
75106
|
-
|
|
75602
|
+
if (!ledger) {
|
|
75603
|
+
return {
|
|
75604
|
+
error: {
|
|
75605
|
+
body: paymentErrorBody("payment_invalid", {
|
|
75606
|
+
message: "Mid-job payments need a credit ledger to record them; none is wired."
|
|
75607
|
+
}),
|
|
75608
|
+
status: 402
|
|
75609
|
+
}
|
|
75610
|
+
};
|
|
75611
|
+
}
|
|
75107
75612
|
const dvmId = opts.dvmId ?? "";
|
|
75108
75613
|
const logTopUp = (event, extra) => {
|
|
75109
75614
|
diagnosticConsole.warn(
|
|
@@ -75121,63 +75626,63 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
|
|
|
75121
75626
|
}
|
|
75122
75627
|
);
|
|
75123
75628
|
};
|
|
75124
|
-
const
|
|
75125
|
-
logTopUp("
|
|
75629
|
+
const logRedirect = (reason, extra) => {
|
|
75630
|
+
logTopUp("credit_topup_redirected", { reason, ...extra });
|
|
75126
75631
|
};
|
|
75632
|
+
const landAsBalance = snapshot.landAsBalance ?? (requiredMsats <= 0 ? "no_open_ask" : void 0);
|
|
75127
75633
|
let topUp;
|
|
75128
|
-
let callerId;
|
|
75129
|
-
let currency;
|
|
75634
|
+
let callerId = snapshot.requesterPubkey ?? snapshot.requesterId ?? "anonymous";
|
|
75635
|
+
let currency = snapshot.pendingPaymentFiatCurrency ?? opts.pricingCurrency ?? "usd";
|
|
75130
75636
|
let drawBasis = false;
|
|
75131
|
-
|
|
75637
|
+
let growsDraw = false;
|
|
75638
|
+
let redirect;
|
|
75639
|
+
const ownCredit = landAsBalance !== void 0 && !snapshot.requesterPubkey;
|
|
75640
|
+
if (snapshot.creditId && snapshot.drawId && !ownCredit) {
|
|
75132
75641
|
const [credit, draw] = await Promise.all([
|
|
75133
75642
|
ledger.get(snapshot.creditId).catch(() => void 0),
|
|
75134
75643
|
ledger.getDraw({ creditId: snapshot.creditId, drawId: snapshot.drawId }).catch(() => void 0)
|
|
75135
75644
|
]);
|
|
75136
|
-
|
|
75137
|
-
logSkip("credit_or_draw_missing");
|
|
75138
|
-
return void 0;
|
|
75139
|
-
}
|
|
75140
|
-
if (draw.status !== "pending") {
|
|
75141
|
-
logSkip("draw_not_pending", { status: draw.status });
|
|
75142
|
-
return void 0;
|
|
75143
|
-
}
|
|
75144
|
-
if (opts.jobId !== void 0 && (draw.jobId ?? null) !== opts.jobId) {
|
|
75145
|
-
logSkip("draw_job_mismatch", { draw_job_id: draw.jobId });
|
|
75146
|
-
return void 0;
|
|
75147
|
-
}
|
|
75148
|
-
const creditRail = draw.railValue.rail;
|
|
75149
|
-
if (creditRail !== null && creditRail !== rail) {
|
|
75150
|
-
logSkip("rail_mismatch", { credit_rail: creditRail });
|
|
75151
|
-
return void 0;
|
|
75152
|
-
}
|
|
75645
|
+
const creditRail = draw?.railValue.rail ?? null;
|
|
75153
75646
|
const incomingChannels = incomingChannelColumns(binding);
|
|
75154
|
-
const storedChannels = storedChannelColumns(credit);
|
|
75155
|
-
|
|
75156
|
-
|
|
75157
|
-
|
|
75158
|
-
|
|
75159
|
-
|
|
75647
|
+
const storedChannels = credit ? storedChannelColumns(credit) : void 0;
|
|
75648
|
+
const redirectReason = !credit || !draw ? "credit_or_draw_missing" : credit.status !== "active" ? "credit_not_active" : opts.jobId !== void 0 && (draw.jobId ?? null) !== opts.jobId ? "draw_job_mismatch" : creditRail !== null && creditRail !== rail ? "rail_mismatch" : incomingChannels && storedChannels && (incomingChannels.tempo !== storedChannels.tempo || incomingChannels.x402 !== storedChannels.x402) ? "channel_binding_mismatch" : void 0;
|
|
75649
|
+
if (redirectReason) {
|
|
75650
|
+
logRedirect(redirectReason, {
|
|
75651
|
+
...credit && { credit_status: credit.status },
|
|
75652
|
+
...draw && { draw_job_id: draw.jobId, credit_rail: creditRail },
|
|
75653
|
+
...storedChannels && {
|
|
75654
|
+
credit_tempo_channel_id: storedChannels.tempo,
|
|
75655
|
+
credit_x402_channel_id: storedChannels.x402
|
|
75656
|
+
},
|
|
75160
75657
|
...binding.instrument ? { payment_instrument: binding.instrument } : {},
|
|
75161
75658
|
...binding.channelId ? { payment_channel_id: binding.channelId } : {}
|
|
75162
75659
|
});
|
|
75163
|
-
|
|
75660
|
+
if (credit) {
|
|
75661
|
+
callerId = credit.callerPubkey;
|
|
75662
|
+
currency = credit.currency;
|
|
75663
|
+
}
|
|
75664
|
+
redirect = redirectReason === "rail_mismatch" || redirectReason === "channel_binding_mismatch" ? { reason: "rail_mismatch", ...creditRail !== null && { jobRail: creditRail } } : { reason: "credit_unavailable" };
|
|
75665
|
+
} else if (credit && draw) {
|
|
75666
|
+
topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId, ledgerSeq: draw.ledgerSeq };
|
|
75667
|
+
callerId = credit.callerPubkey;
|
|
75668
|
+
currency = credit.currency;
|
|
75669
|
+
growsDraw = !landAsBalance && draw.status === "pending";
|
|
75670
|
+
drawBasis = snapshot.paymentTxHash === drawSettlementRef(dvmId, snapshot.creditId, snapshot.drawId);
|
|
75164
75671
|
}
|
|
75165
|
-
topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId, ledgerSeq: draw.ledgerSeq };
|
|
75166
|
-
callerId = credit.callerPubkey;
|
|
75167
|
-
currency = credit.currency;
|
|
75168
|
-
drawBasis = snapshot.paymentTxHash === drawSettlementRef(dvmId, snapshot.creditId, snapshot.drawId);
|
|
75169
75672
|
} else {
|
|
75170
|
-
|
|
75171
|
-
currency = snapshot.pendingPaymentFiatCurrency ?? "usd";
|
|
75673
|
+
growsDraw = !landAsBalance;
|
|
75172
75674
|
}
|
|
75173
|
-
const priceBasisMsats =
|
|
75174
|
-
|
|
75675
|
+
const priceBasisMsats = requiredMsats > 0 ? requiredMsats : NO_ASK_RATE_REFERENCE_MSATS;
|
|
75676
|
+
let denomination = requiredMsats > 0 ? await resolveTopUpFiat(snapshot, currency, priceBasisMsats, opts.fxFetcher) : await msatsToFiatMicro({
|
|
75175
75677
|
msats: priceBasisMsats,
|
|
75176
75678
|
currency,
|
|
75177
75679
|
fxFetcher: opts.fxFetcher ?? createFxFetcher()
|
|
75178
|
-
})
|
|
75680
|
+
});
|
|
75681
|
+
const quote = !denomination.ok && requiredMsats > 0 ? askQuote(snapshot, currency) : void 0;
|
|
75682
|
+
if (quote) denomination = { ok: true, price: quote, stale: false };
|
|
75179
75683
|
if (!denomination.ok) {
|
|
75180
|
-
|
|
75684
|
+
logTopUp("credit_topup_refused", {
|
|
75685
|
+
reason: "denomination_unavailable",
|
|
75181
75686
|
currency,
|
|
75182
75687
|
cause: denomination.reason,
|
|
75183
75688
|
...denomination.sourceFailure && {
|
|
@@ -75185,7 +75690,7 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
|
|
|
75185
75690
|
source_status: denomination.sourceFailure.httpStatus
|
|
75186
75691
|
}
|
|
75187
75692
|
});
|
|
75188
|
-
return
|
|
75693
|
+
return { error: rateUnavailablePaymentError() };
|
|
75189
75694
|
}
|
|
75190
75695
|
const priceFiat = denomination.price;
|
|
75191
75696
|
if (denomination.stale) {
|
|
@@ -75203,23 +75708,26 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
|
|
|
75203
75708
|
}
|
|
75204
75709
|
});
|
|
75205
75710
|
}
|
|
75206
|
-
const topUpCapMicro = topUp ? resolveTopUpCap(snapshot, currency,
|
|
75711
|
+
const topUpCapMicro = topUp && growsDraw ? resolveTopUpCap(snapshot, currency, (reason, extra) => logTopUp("credit_topup_skipped", { reason, ...extra })) : void 0;
|
|
75207
75712
|
return {
|
|
75208
|
-
|
|
75209
|
-
|
|
75210
|
-
|
|
75211
|
-
|
|
75212
|
-
|
|
75213
|
-
|
|
75214
|
-
|
|
75215
|
-
|
|
75216
|
-
|
|
75217
|
-
|
|
75218
|
-
|
|
75219
|
-
|
|
75220
|
-
|
|
75221
|
-
|
|
75222
|
-
|
|
75713
|
+
ctx: {
|
|
75714
|
+
ledger,
|
|
75715
|
+
processedPayments: opts.processedPayments,
|
|
75716
|
+
enqueueCreditDeposit: opts.enqueueCreditDeposit,
|
|
75717
|
+
priceFiat,
|
|
75718
|
+
requiredMsats: priceBasisMsats,
|
|
75719
|
+
callerId,
|
|
75720
|
+
jobId: opts.jobId,
|
|
75721
|
+
hostingPaymentSeq: opts.hostingPaymentSeq,
|
|
75722
|
+
dvmId,
|
|
75723
|
+
topUp,
|
|
75724
|
+
topUpCapMicro,
|
|
75725
|
+
...!growsDraw && { askSatisfied: true },
|
|
75726
|
+
...redirect && { redirect },
|
|
75727
|
+
midJob: true,
|
|
75728
|
+
drawBasis,
|
|
75729
|
+
ttlMs: opts.creditTtlMs ?? IMPLICIT_CREDIT_TTL_MS
|
|
75730
|
+
}
|
|
75223
75731
|
};
|
|
75224
75732
|
}
|
|
75225
75733
|
var NO_ASK_RATE_REFERENCE_MSATS = 1e6;
|
|
@@ -75304,8 +75812,10 @@ var CashuFundingAmountMismatchError = class extends Error {
|
|
|
75304
75812
|
};
|
|
75305
75813
|
function withDrawBasis(info, ctx, committed) {
|
|
75306
75814
|
if (!committed || !ctx) return info;
|
|
75815
|
+
const landedAsBalance = committed.drawResolved ? { reason: "job_ended" } : ctx.redirect;
|
|
75307
75816
|
const base22 = {
|
|
75308
75817
|
...info,
|
|
75818
|
+
...landedAsBalance && { landedAsBalance },
|
|
75309
75819
|
creditId: committed.creditId,
|
|
75310
75820
|
creditCurrency: ctx.priceFiat.currency,
|
|
75311
75821
|
funding: committed.deposit,
|
|
@@ -75322,6 +75832,7 @@ function withDrawBasis(info, ctx, committed) {
|
|
|
75322
75832
|
...base22,
|
|
75323
75833
|
drawId,
|
|
75324
75834
|
drawAmountMicro: draw.amountMicro,
|
|
75835
|
+
drawAddedMicro: committed.added?.amountMicro ?? draw.amountMicro,
|
|
75325
75836
|
...!ctx.midJob && !ctx.fundOnly && { upfrontPayment: upfrontPaymentFromDraw(draw) }
|
|
75326
75837
|
};
|
|
75327
75838
|
if (!ctx.drawBasis) return withDraw;
|
|
@@ -75463,6 +75974,11 @@ async function fundAndDrawInScope(ctx, funding, tx) {
|
|
|
75463
75974
|
const drawFunding2 = await completeDrawFunding(credit.availableMicro, await drawLedgerSeq());
|
|
75464
75975
|
return commitDeposit({ creditId: creditId2, drawFunding: drawFunding2 }, credit);
|
|
75465
75976
|
}
|
|
75977
|
+
const live = await ctx.ledger.getDraw({ creditId: creditId2, drawId: drawId2 });
|
|
75978
|
+
if (live?.status !== "pending") {
|
|
75979
|
+
const drawFunding2 = await completeDrawFunding(credit.availableMicro, live?.ledgerSeq);
|
|
75980
|
+
return commitDeposit({ creditId: creditId2, unappliedMicro: fundedMicro, drawResolved: true, drawFunding: drawFunding2 }, credit);
|
|
75981
|
+
}
|
|
75466
75982
|
const grown = await ctx.ledger.growDraw({
|
|
75467
75983
|
creditId: creditId2,
|
|
75468
75984
|
drawId: drawId2,
|
|
@@ -75525,6 +76041,7 @@ async function fundAndDrawInScope(ctx, funding, tx) {
|
|
|
75525
76041
|
basis,
|
|
75526
76042
|
tx
|
|
75527
76043
|
});
|
|
76044
|
+
if (ctx.midJob && ctx.askSatisfied) return commitDeposit({ creditId, unappliedMicro: fundedMicro }, fundedCredit);
|
|
75528
76045
|
if (shortMidJob) return commitDeposit({ creditId }, fundedCredit);
|
|
75529
76046
|
let draw;
|
|
75530
76047
|
try {
|
|
@@ -75809,9 +76326,18 @@ async function acceptDeferredExactUpfront(args) {
|
|
|
75809
76326
|
dvmId: args.dvmId,
|
|
75810
76327
|
effect: exactSettlementEffect(ctx, { paidMsats, fundedMicro, nativeAmount: authorizedUsdcMicro }),
|
|
75811
76328
|
minValidSeconds: window.minValidSeconds,
|
|
75812
|
-
maxTimeoutSeconds: window.advertisedTimeoutSeconds
|
|
76329
|
+
maxTimeoutSeconds: window.advertisedTimeoutSeconds,
|
|
76330
|
+
maxOutstandingPerPayer: DEFERRED_X402_MAX_OUTSTANDING_PER_PAYER
|
|
75813
76331
|
});
|
|
75814
76332
|
if (prepared.outcome === "rejected") return invalid();
|
|
76333
|
+
if (prepared.outcome === "payer_limit") {
|
|
76334
|
+
return refuse(
|
|
76335
|
+
paymentErrorBody("x402_payer_busy", {
|
|
76336
|
+
message: "This wallet already has an x402 authorization in use for a running job."
|
|
76337
|
+
}),
|
|
76338
|
+
429
|
|
76339
|
+
);
|
|
76340
|
+
}
|
|
75815
76341
|
if (prepared.outcome === "authorization_too_short") {
|
|
75816
76342
|
return refuse(
|
|
75817
76343
|
paymentErrorBody("payment_authorization_too_short", {
|
|
@@ -81982,6 +82508,28 @@ function instrumentKVStore(inner) {
|
|
|
81982
82508
|
}
|
|
81983
82509
|
};
|
|
81984
82510
|
}
|
|
82511
|
+
function restrictToCreditRail(content, rail, job) {
|
|
82512
|
+
if (!rail) return;
|
|
82513
|
+
const offered = {
|
|
82514
|
+
cashu: content.mints !== void 0,
|
|
82515
|
+
x402: content.x402 !== void 0,
|
|
82516
|
+
tempo: content.tempo !== void 0
|
|
82517
|
+
};
|
|
82518
|
+
if (!offered[rail]) return;
|
|
82519
|
+
if (rail !== "cashu") {
|
|
82520
|
+
delete content.mints;
|
|
82521
|
+
delete content.min_locktime_seconds;
|
|
82522
|
+
}
|
|
82523
|
+
if (rail !== "x402" && offered.x402) {
|
|
82524
|
+
delete content.x402;
|
|
82525
|
+
job.pendingX402Nonce = `0x${randomBytes32(32).toString("hex")}`;
|
|
82526
|
+
job.pendingX402AmountUsdcMicro = void 0;
|
|
82527
|
+
}
|
|
82528
|
+
if (rail !== "tempo" && offered.tempo) {
|
|
82529
|
+
delete content.tempo;
|
|
82530
|
+
job.pendingMppChallengeIds = void 0;
|
|
82531
|
+
}
|
|
82532
|
+
}
|
|
81985
82533
|
var stepCostScope = new AsyncLocalStorage6();
|
|
81986
82534
|
function buildContext(job, opts) {
|
|
81987
82535
|
const log = createConsoleLogger(job.id);
|
|
@@ -82006,9 +82554,18 @@ function buildContext(job, opts) {
|
|
|
82006
82554
|
replayPrompts = job.messages.filter((m) => m.from === "provider" && m.type === "prompt" && m.seq <= job.replayHighSeq);
|
|
82007
82555
|
}
|
|
82008
82556
|
};
|
|
82009
|
-
let
|
|
82010
|
-
|
|
82011
|
-
|
|
82557
|
+
let askInFlight = false;
|
|
82558
|
+
const withdrawAsk = () => {
|
|
82559
|
+
const pending = job.pendingPayment;
|
|
82560
|
+
job.pendingPayment = null;
|
|
82561
|
+
job.pendingPaymentMsats = void 0;
|
|
82562
|
+
job.pendingPaymentFiatMicro = void 0;
|
|
82563
|
+
job.pendingPaymentFiatCurrency = void 0;
|
|
82564
|
+
job.pendingMppChallengeIds = void 0;
|
|
82565
|
+
job.pendingX402Nonce = void 0;
|
|
82566
|
+
job.pendingX402AmountUsdcMicro = void 0;
|
|
82567
|
+
pending?.reject(new JobCancelledError("The job completed; its open payment request was withdrawn"));
|
|
82568
|
+
};
|
|
82012
82569
|
let declaredCostAmount = 0;
|
|
82013
82570
|
let declaredCostCurrency;
|
|
82014
82571
|
let declaredCostRevision = 0;
|
|
@@ -82049,7 +82606,7 @@ function buildContext(job, opts) {
|
|
|
82049
82606
|
job.costAmountMicro = micro;
|
|
82050
82607
|
job.costCurrency = currency;
|
|
82051
82608
|
};
|
|
82052
|
-
|
|
82609
|
+
const ctx = {
|
|
82053
82610
|
jobId: job.id,
|
|
82054
82611
|
tags: job.tags,
|
|
82055
82612
|
input: opts.parsedInput ?? job.input,
|
|
@@ -82070,6 +82627,7 @@ function buildContext(job, opts) {
|
|
|
82070
82627
|
sendMessage: (type, content) => {
|
|
82071
82628
|
if (terminated("sendMessage")) return;
|
|
82072
82629
|
if (type === "payment-request" && typeof content.amount_msats === "number") job.pendingPaymentMsats = content.amount_msats;
|
|
82630
|
+
if (type === "payment-request" && job.pieces) job.pieces = finishRunningPiece(job.pieces);
|
|
82073
82631
|
providerMessage(job, type, content);
|
|
82074
82632
|
if ((type === "prompt" || type === "payment-request") && opts.onYield) {
|
|
82075
82633
|
void opts.onYield().catch((err) => {
|
|
@@ -82125,6 +82683,7 @@ function buildContext(job, opts) {
|
|
|
82125
82683
|
"ctx.requestPayment is unavailable: this job was paid by an x402 authorization that settles only when it succeeds"
|
|
82126
82684
|
);
|
|
82127
82685
|
}
|
|
82686
|
+
const finishedChargeMicro = payOpts?.finishedChargeMicro;
|
|
82128
82687
|
let amountMsats;
|
|
82129
82688
|
let fiatAmount;
|
|
82130
82689
|
let fxSnapshot;
|
|
@@ -82143,7 +82702,6 @@ function buildContext(job, opts) {
|
|
|
82143
82702
|
}
|
|
82144
82703
|
const pool = opts.drawPool ? await opts.drawPool().catch(() => ({ basis: "unpriced" })) : { basis: "rail" };
|
|
82145
82704
|
const poolCurrency = pool.basis === "draw" ? pool.currency : void 0;
|
|
82146
|
-
poolBasis ||= pool.basis !== "rail";
|
|
82147
82705
|
const askCurrency = job.askedTopUpCurrency ?? poolCurrency ?? (pool.basis === "draw" ? void 0 : pool.creditCurrency) ?? opts.pricingCurrency ?? "usd";
|
|
82148
82706
|
let pinned;
|
|
82149
82707
|
let pinnedDone = false;
|
|
@@ -82199,47 +82757,11 @@ function buildContext(job, opts) {
|
|
|
82199
82757
|
}
|
|
82200
82758
|
return pinned;
|
|
82201
82759
|
};
|
|
82202
|
-
const askMicro = pool.basis === "draw" && askCurrency === pool.currency ? (await pinAsk())?.amountMicro : void 0;
|
|
82203
|
-
let covered;
|
|
82204
|
-
if (pool.basis === "rail") {
|
|
82205
|
-
covered = job.paidMsats - creditedToHandlerMsats >= amountMsats;
|
|
82206
|
-
} else if (pool.basis === "draw" && askMicro !== void 0) {
|
|
82207
|
-
covered = pool.amountMicro - creditedToHandlerMicro >= askMicro;
|
|
82208
|
-
} else {
|
|
82209
|
-
covered = false;
|
|
82210
|
-
log.warn("requestPayment pool unpriceable \u2014 yielding rather than guessing", {
|
|
82211
|
-
amountMsats,
|
|
82212
|
-
reason,
|
|
82213
|
-
poolBasis: pool.basis,
|
|
82214
|
-
askCurrency,
|
|
82215
|
-
// `draw` here means the pool read fine and either the ASK wouldn't pin
|
|
82216
|
-
// an fx outage on a bare-msats ask, or a sub-micro amount — or it
|
|
82217
|
-
// pinned in a currency this pool isn't denominated in.
|
|
82218
|
-
...pool.basis === "draw" && { poolCurrency: pool.currency }
|
|
82219
|
-
});
|
|
82220
|
-
}
|
|
82221
|
-
if (covered) {
|
|
82222
|
-
creditedToHandlerMsats += amountMsats;
|
|
82223
|
-
creditedToHandlerMicro += askMicro ?? 0;
|
|
82224
|
-
log.info("requestPayment auto-credited from upfront pool", {
|
|
82225
|
-
amountMsats,
|
|
82226
|
-
reason,
|
|
82227
|
-
...pool.basis === "draw" && askMicro !== void 0 ? {
|
|
82228
|
-
amountMicro: askMicro,
|
|
82229
|
-
poolCurrency: pool.currency,
|
|
82230
|
-
poolRemainingMicro: pool.amountMicro - creditedToHandlerMicro
|
|
82231
|
-
} : { poolRemaining: job.paidMsats - creditedToHandlerMsats }
|
|
82232
|
-
});
|
|
82233
|
-
if (job.replayHighSeq !== null) {
|
|
82234
|
-
job.status = job.pendingPrompts.size > 0 ? "awaiting-input" : "processing";
|
|
82235
|
-
opts.onCallerResume?.();
|
|
82236
|
-
}
|
|
82237
|
-
advanceReplayPaymentIndex(job);
|
|
82238
|
-
return { amount_msats: amountMsats };
|
|
82239
|
-
}
|
|
82240
82760
|
const replayedPaymentRequest = job.replayHighSeq !== null && job.replayPaymentIndex >= job.messages.filter((m) => m.from === "requester" && m.type === "payment").length ? job.messages.findLast((m) => m.from === "provider" && m.type === "payment-request" && m.seq <= job.replayHighSeq && m.seq > (job.messages.findLast((message) => message.from === "requester" && message.type === "payment")?.seq ?? -1)) : void 0;
|
|
82241
82761
|
const originalAsk = replayedPaymentRequest?.type === "payment-request" ? replayedPaymentRequest.content : void 0;
|
|
82242
82762
|
if (originalAsk) amountMsats = originalAsk.amount_msats;
|
|
82763
|
+
const replayingPaidAsk = job.replayHighSeq !== null && job.replayPaymentIndex < job.messages.filter((m) => m.type === "payment" && m.from === "requester" && m.seq <= job.replayHighSeq).length;
|
|
82764
|
+
if (!originalAsk && !replayingPaidAsk) checkFinishedCharge(runningPiece(job.pieces), finishedChargeMicro);
|
|
82243
82765
|
const pendingFiat = originalAsk ? originalAsk.credit ? { amountMicro: originalAsk.credit.amount_micro, currency: originalAsk.credit.currency } : void 0 : await pinAsk();
|
|
82244
82766
|
job.pendingPaymentMsats = amountMsats;
|
|
82245
82767
|
job.pendingPaymentFiatMicro = pendingFiat?.amountMicro;
|
|
@@ -82247,7 +82769,7 @@ function buildContext(job, opts) {
|
|
|
82247
82769
|
let paymentRequestContent;
|
|
82248
82770
|
if (originalAsk) {
|
|
82249
82771
|
paymentRequestContent = { ...originalAsk };
|
|
82250
|
-
job.pendingX402Nonce = originalAsk.x402
|
|
82772
|
+
job.pendingX402Nonce = originalAsk.x402 ? originalAsk.x402.nonce : job.pendingX402Nonce;
|
|
82251
82773
|
job.pendingX402AmountUsdcMicro = originalAsk.x402?.required_usdc_micro;
|
|
82252
82774
|
job.pendingMppChallengeIds = originalAsk.tempo?.challenges.map((challenge2) => challenge2.id);
|
|
82253
82775
|
} else {
|
|
@@ -82258,7 +82780,12 @@ function buildContext(job, opts) {
|
|
|
82258
82780
|
...fiatAmount && { fiat_amount: fiatAmount },
|
|
82259
82781
|
...payOpts?.mints && { mints: payOpts.mints },
|
|
82260
82782
|
...payOpts?.minLocktimeSeconds && { min_locktime_seconds: payOpts.minLocktimeSeconds },
|
|
82261
|
-
...!payOpts?.mints && opts.mints && { mints: opts.mints }
|
|
82783
|
+
...!payOpts?.mints && opts.mints && { mints: opts.mints },
|
|
82784
|
+
// What declining this ask costs: the pieces finished so far, this ask finishing the
|
|
82785
|
+
// one in progress. Absent on a job accepted before piece accounting.
|
|
82786
|
+
...job.pieces && {
|
|
82787
|
+
charged_if_declined_micro: chargedIfDeclinedMicro(finishRunningPiece(job.pieces, finishedChargeMicro))
|
|
82788
|
+
}
|
|
82262
82789
|
};
|
|
82263
82790
|
let paymentRate;
|
|
82264
82791
|
let x402Nonce;
|
|
@@ -82329,6 +82856,11 @@ function buildContext(job, opts) {
|
|
|
82329
82856
|
}
|
|
82330
82857
|
}
|
|
82331
82858
|
job.pendingMppChallengeIds = mppChallengeIds;
|
|
82859
|
+
restrictToCreditRail(
|
|
82860
|
+
paymentRequestContent,
|
|
82861
|
+
opts.creditRail ? await opts.creditRail().catch(() => void 0) : void 0,
|
|
82862
|
+
job
|
|
82863
|
+
);
|
|
82332
82864
|
}
|
|
82333
82865
|
if (job.replayHighSeq !== null) {
|
|
82334
82866
|
const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester" && m.seq <= job.replayHighSeq);
|
|
@@ -82336,7 +82868,7 @@ function buildContext(job, opts) {
|
|
|
82336
82868
|
const payment = payments[job.replayPaymentIndex];
|
|
82337
82869
|
job.replayPaymentIndex++;
|
|
82338
82870
|
const balance = payment.content.credit;
|
|
82339
|
-
const accepted = balance ? await opts.acceptedBalancePayment?.(payment.seq, pendingFiat?.amountMicro, pendingFiat?.currency) : job.reactivationPaymentApplied === true;
|
|
82871
|
+
const accepted = balance ? await opts.acceptedBalancePayment?.(payment.seq, pendingFiat?.amountMicro, pendingFiat?.currency) : job.pieces?.some((piece) => piece.paidSeq === payment.seq) === true || job.messages.some((m) => m.from === "provider" && m.seq > payment.seq) || job.reactivationPaymentApplied === true;
|
|
82340
82872
|
if (!accepted) throw new Error("[internal_error] payment replay reached without credit");
|
|
82341
82873
|
job.pendingPaymentMsats = void 0;
|
|
82342
82874
|
job.pendingPaymentFiatMicro = void 0;
|
|
@@ -82346,8 +82878,6 @@ function buildContext(job, opts) {
|
|
|
82346
82878
|
job.pendingX402AmountUsdcMicro = void 0;
|
|
82347
82879
|
job.status = job.pendingPrompts.size > 0 ? "awaiting-input" : "processing";
|
|
82348
82880
|
opts.onCallerResume?.();
|
|
82349
|
-
creditedToHandlerMsats += amountMsats;
|
|
82350
|
-
creditedToHandlerMicro += pendingFiat?.amountMicro ?? 0;
|
|
82351
82881
|
return payment.content;
|
|
82352
82882
|
}
|
|
82353
82883
|
if (!originalAsk) {
|
|
@@ -82377,7 +82907,11 @@ function buildContext(job, opts) {
|
|
|
82377
82907
|
}
|
|
82378
82908
|
}
|
|
82379
82909
|
job.status = "awaiting-input";
|
|
82380
|
-
if (!originalAsk)
|
|
82910
|
+
if (!originalAsk) {
|
|
82911
|
+
if (job.pieces) job.pieces = finishRunningPiece(job.pieces, finishedChargeMicro);
|
|
82912
|
+
job.finishingChargeMicro = finishedChargeMicro;
|
|
82913
|
+
providerMessage(job, "payment-request", paymentRequestContent);
|
|
82914
|
+
}
|
|
82381
82915
|
const paidMsatsAtYield = job.paidMsats;
|
|
82382
82916
|
const p = new Promise((resolve, reject) => {
|
|
82383
82917
|
let resolved = false;
|
|
@@ -82400,8 +82934,6 @@ function buildContext(job, opts) {
|
|
|
82400
82934
|
opts.onCallerResume?.();
|
|
82401
82935
|
resolved = true;
|
|
82402
82936
|
cleanup();
|
|
82403
|
-
creditedToHandlerMsats += amountMsats;
|
|
82404
|
-
creditedToHandlerMicro += pendingFiat?.amountMicro ?? 0;
|
|
82405
82937
|
resolve(pc);
|
|
82406
82938
|
};
|
|
82407
82939
|
const doReject = (err) => {
|
|
@@ -82419,11 +82951,12 @@ function buildContext(job, opts) {
|
|
|
82419
82951
|
try {
|
|
82420
82952
|
const counters = await getCounters();
|
|
82421
82953
|
if (!counters || resolved) return;
|
|
82422
|
-
const satisfied = counters.balancePaymentSatisfied === true ||
|
|
82954
|
+
const satisfied = counters.balancePaymentSatisfied === true || counters.paidMsats - paidMsatsAtYield >= amountMsats;
|
|
82423
82955
|
if (satisfied) {
|
|
82424
82956
|
const resume = async () => {
|
|
82425
82957
|
job.paidMsats = counters.paidMsats;
|
|
82426
82958
|
job.pendingPaymentMsats = counters.pendingPaymentMsats;
|
|
82959
|
+
if (counters.pieces) job.pieces = counters.pieces;
|
|
82427
82960
|
await doResolve({ amount_msats: amountMsats });
|
|
82428
82961
|
};
|
|
82429
82962
|
if (opts.claimForProcessing) {
|
|
@@ -82479,8 +83012,12 @@ function buildContext(job, opts) {
|
|
|
82479
83012
|
if (hint) content.hint = hint;
|
|
82480
83013
|
providerMessage(job, "progress", content);
|
|
82481
83014
|
},
|
|
82482
|
-
complete: (summary) => {
|
|
83015
|
+
complete: (summary, completeOpts) => {
|
|
82483
83016
|
if (terminated("complete")) return;
|
|
83017
|
+
const running = runningPiece(job.pieces);
|
|
83018
|
+
checkFinishedCharge(running, completeOpts?.finishedChargeMicro);
|
|
83019
|
+
if (job.pendingPayment || job.pendingPaymentMsats !== void 0) withdrawAsk();
|
|
83020
|
+
job.pieceEnding = job.pieces === void 0 ? { kind: "finish" } : running ? { kind: "finish", paidSeq: running.paidSeq, chargeMicro: completeOpts?.finishedChargeMicro } : { kind: "release" };
|
|
82484
83021
|
job.status = "completed";
|
|
82485
83022
|
job.summary = summary;
|
|
82486
83023
|
providerMessage(job, "complete", { summary });
|
|
@@ -82534,6 +83071,17 @@ function buildContext(job, opts) {
|
|
|
82534
83071
|
env: opts.env,
|
|
82535
83072
|
log
|
|
82536
83073
|
};
|
|
83074
|
+
const ask = ctx.requestPayment;
|
|
83075
|
+
ctx.requestPayment = (amount, reason, payOpts) => {
|
|
83076
|
+
if (!isTerminal(job.status) && (askInFlight || job.pendingPayment)) {
|
|
83077
|
+
return Promise.reject(new AskAlreadyOpenError(job.id));
|
|
83078
|
+
}
|
|
83079
|
+
askInFlight = true;
|
|
83080
|
+
return ask(amount, reason, payOpts).finally(() => {
|
|
83081
|
+
askInFlight = false;
|
|
83082
|
+
});
|
|
83083
|
+
};
|
|
83084
|
+
return ctx;
|
|
82537
83085
|
}
|
|
82538
83086
|
var _lazyFxFetcher2 = null;
|
|
82539
83087
|
function lazyFxFetcher2() {
|
|
@@ -82549,13 +83097,6 @@ function warnPinLost(jobId, currency, amountMsats, reason, detail) {
|
|
|
82549
83097
|
...detail !== void 0 && { detail }
|
|
82550
83098
|
});
|
|
82551
83099
|
}
|
|
82552
|
-
function advanceReplayPaymentIndex(job) {
|
|
82553
|
-
if (job.replayHighSeq === null) return;
|
|
82554
|
-
const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester" && m.seq <= job.replayHighSeq);
|
|
82555
|
-
if (job.replayPaymentIndex < payments.length) {
|
|
82556
|
-
job.replayPaymentIndex++;
|
|
82557
|
-
}
|
|
82558
|
-
}
|
|
82559
83100
|
var ReceiptIssuer = class {
|
|
82560
83101
|
/** x-only pubkey this issuer signs under; the attested `receipt_pubkey`. */
|
|
82561
83102
|
pubkey;
|
|
@@ -82572,9 +83113,11 @@ var ReceiptIssuer = class {
|
|
|
82572
83113
|
* seq is store-allocated; issuedAt is epoch seconds. Free jobs also consume a
|
|
82573
83114
|
* sequence and attest their outcome. Timing/attribution comes from the committed
|
|
82574
83115
|
* terminal row; legacy rows omit unknown historical fields. credit is present
|
|
82575
|
-
* only for a resolved ledger draw.
|
|
83116
|
+
* only for a resolved ledger draw, with `settlement` saying how it settled by the piece.
|
|
83117
|
+
* `unpaid` attests a completed job whose admitted payment was never collected, so `paid`
|
|
83118
|
+
* reports none.
|
|
82576
83119
|
*/
|
|
82577
|
-
issue(record2, seq, issuedAt, credit) {
|
|
83120
|
+
issue(record2, seq, issuedAt, credit, unpaid = false, settlement) {
|
|
82578
83121
|
const unsigned2 = {
|
|
82579
83122
|
v: 1,
|
|
82580
83123
|
job_id: record2.id,
|
|
@@ -82594,7 +83137,7 @@ var ReceiptIssuer = class {
|
|
|
82594
83137
|
seq,
|
|
82595
83138
|
issued_at: issuedAt ?? Math.floor(Date.now() / 1e3),
|
|
82596
83139
|
requester_pubkey: record2.requesterPubkey ?? null,
|
|
82597
|
-
paid: {
|
|
83140
|
+
paid: unpaid ? { msats: 0, rail: null, native_amount: null, native_asset: null, tx_hash: null, mint: null } : {
|
|
82598
83141
|
msats: record2.paidMsats,
|
|
82599
83142
|
rail: record2.paymentRail ?? null,
|
|
82600
83143
|
native_amount: record2.nativeAmount ?? null,
|
|
@@ -82604,7 +83147,8 @@ var ReceiptIssuer = class {
|
|
|
82604
83147
|
},
|
|
82605
83148
|
result_hash: resultHashFor(record2),
|
|
82606
83149
|
receipt_pubkey: this.pubkey,
|
|
82607
|
-
...credit && { credit }
|
|
83150
|
+
...credit && { credit },
|
|
83151
|
+
...credit && settlement && { settlement }
|
|
82608
83152
|
};
|
|
82609
83153
|
return signReceipt(unsigned2, this.secret);
|
|
82610
83154
|
}
|
|
@@ -82709,6 +83253,66 @@ function resultHashFor(record2) {
|
|
|
82709
83253
|
if (summary === void 0 && artifacts.length === 0) return null;
|
|
82710
83254
|
return computeResultHash(summary, artifacts);
|
|
82711
83255
|
}
|
|
83256
|
+
function settledDrawRevenue(job, draw) {
|
|
83257
|
+
return {
|
|
83258
|
+
paidMsats: settledDrawMsats(job.paidMsats, draw),
|
|
83259
|
+
...job.nativeAmount !== void 0 && { nativeAmount: settledDrawNative(job.nativeAmount, draw) }
|
|
83260
|
+
};
|
|
83261
|
+
}
|
|
83262
|
+
function settledDrawMsats(paidMsats, draw) {
|
|
83263
|
+
if (draw.allocatedMsats > 0) {
|
|
83264
|
+
return Math.max(0, paidMsats - draw.allocatedMsats + draw.railValue.drawMsats);
|
|
83265
|
+
}
|
|
83266
|
+
if (draw.railValue.drawMsats > 0) return draw.railValue.drawMsats;
|
|
83267
|
+
if (draw.partialSettle) {
|
|
83268
|
+
return settledShare(Math.max(0, paidMsats), draw.amountMicro, draw.partialSettle.heldMicro);
|
|
83269
|
+
}
|
|
83270
|
+
return paidMsats;
|
|
83271
|
+
}
|
|
83272
|
+
function settledDrawNative(nativeAmount2, draw) {
|
|
83273
|
+
const released = draw.partialSettle?.releasedNative;
|
|
83274
|
+
if (released === void 0 || released === null) return nativeAmount2;
|
|
83275
|
+
return Math.max(0, nativeAmount2 - released);
|
|
83276
|
+
}
|
|
83277
|
+
function drawHeldMicro(draw) {
|
|
83278
|
+
return draw.partialSettle?.heldMicro ?? draw.amountMicro;
|
|
83279
|
+
}
|
|
83280
|
+
function frozenSettleMicro(record2, heldMicro) {
|
|
83281
|
+
const settlement = record2.settlement ?? (record2.pieces ? endPieces(record2.pieces, terminalEnding(record2)).settlement : void 0);
|
|
83282
|
+
let figure;
|
|
83283
|
+
if (deferredX402IntentId(record2.creditId)) figure = record2.status === "completed" ? heldMicro : 0;
|
|
83284
|
+
else if (settlement?.chargedMicro !== void 0) figure = settlement.chargedMicro;
|
|
83285
|
+
else if (settlement?.whole) figure = settlement.whole === "settle" ? heldMicro : 0;
|
|
83286
|
+
else figure = record2.status === "completed" ? heldMicro : 0;
|
|
83287
|
+
return figure > heldMicro ? { settleMicro: heldMicro, clamped: true } : { settleMicro: figure, clamped: false };
|
|
83288
|
+
}
|
|
83289
|
+
function drawChargedMicro(draw) {
|
|
83290
|
+
return draw.status === "settled" ? draw.amountMicro : 0;
|
|
83291
|
+
}
|
|
83292
|
+
function receiptCreditFor(draw, balanceAfterMicro) {
|
|
83293
|
+
return {
|
|
83294
|
+
credit_id: draw.creditId,
|
|
83295
|
+
draw_id: draw.drawId,
|
|
83296
|
+
amount: drawChargedMicro(draw),
|
|
83297
|
+
balance_after: balanceAfterMicro,
|
|
83298
|
+
ledger_seq: draw.ledgerSeq
|
|
83299
|
+
};
|
|
83300
|
+
}
|
|
83301
|
+
function receiptSettlementFor(record2, draw) {
|
|
83302
|
+
const held = drawHeldMicro(draw);
|
|
83303
|
+
const charged = drawChargedMicro(draw);
|
|
83304
|
+
return {
|
|
83305
|
+
held,
|
|
83306
|
+
charged,
|
|
83307
|
+
released: held - charged,
|
|
83308
|
+
pieces: (record2.pieces ?? []).map((piece) => ({
|
|
83309
|
+
amount: piece.amountMicro,
|
|
83310
|
+
charged: pieceCharge(piece),
|
|
83311
|
+
paid_seq: piece.paidSeq,
|
|
83312
|
+
state: piece.state
|
|
83313
|
+
}))
|
|
83314
|
+
};
|
|
83315
|
+
}
|
|
82712
83316
|
function takesUnsignedPath(auth, body) {
|
|
82713
83317
|
if (!auth?.allowUnsignedPaid) return false;
|
|
82714
83318
|
return !carriesSignedEnvelope(signedRequestInput(body));
|
|
@@ -82962,7 +83566,6 @@ var ORPHAN_DRAW_SWEEP_BATCH = 50;
|
|
|
82962
83566
|
var ORPHAN_DRAW_SWEEP_MAX_PAGES = 20;
|
|
82963
83567
|
var ANY_DRAW_AGE_CUTOFF_MS = Number.MAX_SAFE_INTEGER;
|
|
82964
83568
|
var ORPHAN_SWEEP_CLAIMS = /* @__PURE__ */ new WeakSet();
|
|
82965
|
-
var ATTACH_RAILS = ["cashu", "x402", "tempo"];
|
|
82966
83569
|
var CREDIT_INBOUND_ATTEMPTS = 3;
|
|
82967
83570
|
var CREDIT_INBOUND_BACKOFF_MS = 50;
|
|
82968
83571
|
var TERMINAL_PERSIST_RETRY_MS = 3e4;
|
|
@@ -82997,6 +83600,10 @@ var JobManager = class {
|
|
|
82997
83600
|
paymentAskSeqs = /* @__PURE__ */ new WeakMap();
|
|
82998
83601
|
reactivationAskSeqs = /* @__PURE__ */ new WeakMap();
|
|
82999
83602
|
pendingPaymentMessages = /* @__PURE__ */ new WeakMap();
|
|
83603
|
+
/** How many times idle expiry has found a payment holding each job open. */
|
|
83604
|
+
idleIntentWaits = /* @__PURE__ */ new WeakMap();
|
|
83605
|
+
/** What each recorded payment arrival is for, decided under the job row lock. */
|
|
83606
|
+
paymentDispositions = /* @__PURE__ */ new WeakMap();
|
|
83000
83607
|
// Every local input resume holds this queue through its durable wait update.
|
|
83001
83608
|
// A prompt response and a payment NOTIFY must not mistake each other for a
|
|
83002
83609
|
// different machine's successful claim.
|
|
@@ -83357,6 +83964,11 @@ var JobManager = class {
|
|
|
83357
83964
|
fundingCredit: payment.fundingCredit,
|
|
83358
83965
|
receivedProofs: payment.receivedProofs,
|
|
83359
83966
|
requiredMsats,
|
|
83967
|
+
// The upfront payment buys the first piece; a free job starts with none, and so does an
|
|
83968
|
+
// unsigned x402 job, which is one piece settled only on completion whatever its list
|
|
83969
|
+
// says. A draw whose amount the payment did not report keeps no list: it settles as one
|
|
83970
|
+
// piece, its hold.
|
|
83971
|
+
pieces: !payment.drawId || deferredX402IntentId(payment.creditId) ? [] : payment.drawAmountMicro !== void 0 ? [{ amountMicro: payment.drawAmountMicro, paidSeq: 0, state: "running" }] : void 0,
|
|
83360
83972
|
listeners: /* @__PURE__ */ new Set(),
|
|
83361
83973
|
abort: new AbortController(),
|
|
83362
83974
|
stepCache: new StepCache(),
|
|
@@ -83504,6 +84116,7 @@ var JobManager = class {
|
|
|
83504
84116
|
job.pendingMppChallengeIds = record2.pendingMppChallengeIds;
|
|
83505
84117
|
job.pendingX402Nonce = record2.pendingX402Nonce;
|
|
83506
84118
|
job.pendingX402AmountUsdcMicro = record2.pendingX402AmountUsdcMicro;
|
|
84119
|
+
job.pieces = record2.pieces;
|
|
83507
84120
|
return true;
|
|
83508
84121
|
}
|
|
83509
84122
|
async resumeClaimedPayment(job, resume) {
|
|
@@ -83562,16 +84175,18 @@ var JobManager = class {
|
|
|
83562
84175
|
}
|
|
83563
84176
|
} else if (type === "approval" && cap?.onApproval && ctx) {
|
|
83564
84177
|
await cap.onApproval(ctx, content);
|
|
83565
|
-
} else if (type === "cancel") {
|
|
83566
|
-
const reason = content?.reason ?? "Job cancelled";
|
|
84178
|
+
} else if (type === "cancel" || type === "decline") {
|
|
84179
|
+
const reason = content?.reason ?? (type === "decline" ? "Job declined" : "Job cancelled");
|
|
83567
84180
|
abortJob(job, reason);
|
|
83568
84181
|
job.endedBy = "caller";
|
|
83569
84182
|
job.status = "cancelled";
|
|
84183
|
+
job.pieceEnding = { kind: type === "decline" ? "release" : "stop" };
|
|
83570
84184
|
if (cap?.onCancel && ctx) {
|
|
83571
84185
|
await cap.onCancel(ctx, content);
|
|
83572
84186
|
}
|
|
83573
|
-
|
|
83574
|
-
|
|
84187
|
+
const ended = type === "decline" ? "Job declined" : "Job cancelled";
|
|
84188
|
+
for (const [, p] of job.pendingPrompts) p.reject(new JobCancelledError(ended));
|
|
84189
|
+
if (job.pendingPayment) job.pendingPayment.reject(new JobCancelledError(ended));
|
|
83575
84190
|
job.pendingPrompts.clear();
|
|
83576
84191
|
job.pendingPayment = null;
|
|
83577
84192
|
this.clearIdleTimer(job.id);
|
|
@@ -83622,7 +84237,8 @@ var JobManager = class {
|
|
|
83622
84237
|
this.terminalPersistenceRetries.set(job.id, timer);
|
|
83623
84238
|
}
|
|
83624
84239
|
async persistTerminalSnapshot(job) {
|
|
83625
|
-
|
|
84240
|
+
let deadline = performance.now() + TERMINAL_PERSIST_RETRY_MS;
|
|
84241
|
+
let intentWaits = 0;
|
|
83626
84242
|
await job.messageAppenderTail;
|
|
83627
84243
|
while (!this.terminalFailures.has(job)) {
|
|
83628
84244
|
try {
|
|
@@ -83630,7 +84246,14 @@ var JobManager = class {
|
|
|
83630
84246
|
await this.flushOutgoing(job);
|
|
83631
84247
|
await this.persistSnapshot(job, true);
|
|
83632
84248
|
return;
|
|
83633
|
-
} catch {
|
|
84249
|
+
} catch (error62) {
|
|
84250
|
+
const open2 = paymentIntentOpen(error62);
|
|
84251
|
+
if (open2) {
|
|
84252
|
+
const waitMs = paymentIntentRetryDelayMs(open2.retryAtMs, intentWaits++);
|
|
84253
|
+
deadline += waitMs;
|
|
84254
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
84255
|
+
continue;
|
|
84256
|
+
}
|
|
83634
84257
|
if (performance.now() >= deadline) break;
|
|
83635
84258
|
await new Promise((resolve) => setTimeout(resolve, Math.min(500, deadline - performance.now())));
|
|
83636
84259
|
}
|
|
@@ -83645,10 +84268,12 @@ var JobManager = class {
|
|
|
83645
84268
|
}
|
|
83646
84269
|
job.status = "failed";
|
|
83647
84270
|
job.summary = reason;
|
|
84271
|
+
job.pieceEnding = void 0;
|
|
83648
84272
|
this.outgoingQueues.delete(job);
|
|
83649
84273
|
const store = this.jobStore;
|
|
83650
84274
|
if (isStreamableJobStore(store) && store.failJob) {
|
|
83651
|
-
|
|
84275
|
+
const failJob = store.failJob.bind(store);
|
|
84276
|
+
await afterPaymentIntents(() => failJob(job.id, reason));
|
|
83652
84277
|
const saved = await store.get(job.id);
|
|
83653
84278
|
if (!saved || !isTerminal(saved.status)) throw new JobSnapshotPersistenceError("failure not committed");
|
|
83654
84279
|
job.status = saved.status;
|
|
@@ -83673,6 +84298,11 @@ var JobManager = class {
|
|
|
83673
84298
|
if (await this.adoptDurableTerminal(job)) return;
|
|
83674
84299
|
if (isTerminal(job.status) && !terminalReady) return this.persistJob(job);
|
|
83675
84300
|
const record2 = toJobRecord(job);
|
|
84301
|
+
if (isTerminal(job.status) && record2.settlement === void 0) {
|
|
84302
|
+
const ended = endPieces(record2.pieces, terminalEnding(record2));
|
|
84303
|
+
record2.pieces = ended.pieces;
|
|
84304
|
+
record2.settlement = ended.settlement;
|
|
84305
|
+
}
|
|
83676
84306
|
if (isTerminal(job.status) && isStreamableJobStore(this.jobStore)) {
|
|
83677
84307
|
const durable = await this.jobStore.getMessages(job.id, 0, { includeHeld: true });
|
|
83678
84308
|
if (durable.length >= record2.messages.length) {
|
|
@@ -83739,6 +84369,8 @@ var JobManager = class {
|
|
|
83739
84369
|
job.terminalAtMs = durable.terminalAtMs;
|
|
83740
84370
|
job.callerWaitMs = durable.callerWaitMs;
|
|
83741
84371
|
job.awaitingInputAtMs = durable.awaitingInputAtMs;
|
|
84372
|
+
job.pieces = durable.pieces;
|
|
84373
|
+
job.settlement = durable.settlement;
|
|
83742
84374
|
const reason = durable.status !== "completed" && durable.summary ? durable.summary : `Job ${durable.status}`;
|
|
83743
84375
|
for (const [, p] of job.pendingPrompts) p.reject(new JobCancelledError(reason));
|
|
83744
84376
|
job.pendingPayment?.reject(new JobCancelledError(reason));
|
|
@@ -83959,12 +84591,20 @@ var JobManager = class {
|
|
|
83959
84591
|
const entry = queue[0];
|
|
83960
84592
|
if (entry.pending === void 0) entry.pending = job.pendingPayment;
|
|
83961
84593
|
const { msg, opts, pending } = entry;
|
|
83962
|
-
|
|
83963
|
-
|
|
83964
|
-
|
|
83965
|
-
|
|
83966
|
-
|
|
83967
|
-
|
|
84594
|
+
let stored;
|
|
84595
|
+
try {
|
|
84596
|
+
stored = await store.appendOutgoing(job.id, {
|
|
84597
|
+
from: msg.from,
|
|
84598
|
+
type: msg.type,
|
|
84599
|
+
timestamp: msg.timestamp,
|
|
84600
|
+
content: msg.content
|
|
84601
|
+
}, opts);
|
|
84602
|
+
} catch (error62) {
|
|
84603
|
+
if (!(error62 instanceof JobEndedError) && error62?.code !== "job_ended") throw error62;
|
|
84604
|
+
this.outgoingQueues.delete(job);
|
|
84605
|
+
await this.adoptDurableTerminal(job);
|
|
84606
|
+
return;
|
|
84607
|
+
}
|
|
83968
84608
|
if (msg.type === "payment-request" && pending && job.pendingPayment === pending) {
|
|
83969
84609
|
this.paymentAskSeqs.set(pending, stored);
|
|
83970
84610
|
}
|
|
@@ -84017,7 +84657,18 @@ var JobManager = class {
|
|
|
84017
84657
|
return;
|
|
84018
84658
|
}
|
|
84019
84659
|
if (current && isStreamableJobStore(this.jobStore)) {
|
|
84020
|
-
|
|
84660
|
+
let claimed;
|
|
84661
|
+
try {
|
|
84662
|
+
claimed = await this.jobStore.cancelStaleJob(job.id, current.lastActivityAt, "Job timed out (idle)", "cancelled");
|
|
84663
|
+
} catch (error62) {
|
|
84664
|
+
const open2 = paymentIntentOpen(error62);
|
|
84665
|
+
if (!open2) throw error62;
|
|
84666
|
+
const attempt = this.idleIntentWaits.get(job) ?? 0;
|
|
84667
|
+
this.idleIntentWaits.set(job, attempt + 1);
|
|
84668
|
+
this.startIdleTimer(job, Date.now() + paymentIntentRetryDelayMs(open2.retryAtMs, attempt));
|
|
84669
|
+
return;
|
|
84670
|
+
}
|
|
84671
|
+
this.idleIntentWaits.delete(job);
|
|
84021
84672
|
if (claimed) await this.finalizeStoredTerminal(job.id);
|
|
84022
84673
|
await this.adoptDurableTerminal(job);
|
|
84023
84674
|
if (!claimed && !isTerminal(job.status)) this.startIdleTimer(job, Date.now() + 1);
|
|
@@ -84137,12 +84788,18 @@ var JobManager = class {
|
|
|
84137
84788
|
});
|
|
84138
84789
|
continue;
|
|
84139
84790
|
}
|
|
84140
|
-
|
|
84141
|
-
|
|
84142
|
-
|
|
84143
|
-
|
|
84144
|
-
|
|
84145
|
-
|
|
84791
|
+
let claimed;
|
|
84792
|
+
try {
|
|
84793
|
+
claimed = await this.jobStore.cancelStaleJob(
|
|
84794
|
+
record2.id,
|
|
84795
|
+
expectedActivityBefore,
|
|
84796
|
+
reason,
|
|
84797
|
+
terminalStatus
|
|
84798
|
+
);
|
|
84799
|
+
} catch (error62) {
|
|
84800
|
+
if (paymentIntentOpen(error62)) continue;
|
|
84801
|
+
throw error62;
|
|
84802
|
+
}
|
|
84146
84803
|
if (claimed) {
|
|
84147
84804
|
swept++;
|
|
84148
84805
|
await this.finalizeStoredTerminal(record2.id);
|
|
@@ -84661,9 +85318,10 @@ var JobManager = class {
|
|
|
84661
85318
|
async reconcileTerminalDraw(ledger, draw, record2, nowMs) {
|
|
84662
85319
|
const args = this.drawResolutionArgs(draw.creditId, draw.drawId);
|
|
84663
85320
|
const bound = record2.creditId === draw.creditId && record2.drawId === draw.drawId;
|
|
84664
|
-
const
|
|
85321
|
+
const settleMicro = bound ? this.settleMicroFor(record2, draw) : 0;
|
|
84665
85322
|
try {
|
|
84666
|
-
const resolution =
|
|
85323
|
+
const resolution = await ledger.resolveDraw({ ...args, settleMicro });
|
|
85324
|
+
const settle2 = resolution.status === "settled";
|
|
84667
85325
|
const booked = settle2 && !resolution.replayed ? await this.bookRevenue(record2) : false;
|
|
84668
85326
|
diagnosticConsole.warn(
|
|
84669
85327
|
{
|
|
@@ -84768,7 +85426,14 @@ var JobManager = class {
|
|
|
84768
85426
|
async recordInboundPending(job, msgType, msgContent) {
|
|
84769
85427
|
const timestamp = Math.floor(Date.now() / 1e3);
|
|
84770
85428
|
let txSeq = null;
|
|
84771
|
-
|
|
85429
|
+
let disposition;
|
|
85430
|
+
if (msgType === "payment" && isStreamableJobStore(this.jobStore) && isPaymentArrivalStore(this.jobStore)) {
|
|
85431
|
+
({ seq: txSeq, disposition } = await this.jobStore.recordPaymentArrival(
|
|
85432
|
+
job.id,
|
|
85433
|
+
{ from: "requester", type: "payment", timestamp, content: msgContent },
|
|
85434
|
+
{ arrivedAtMs: Date.now(), leaseMs: PAYMENT_INTENT_LEASE_MS }
|
|
85435
|
+
));
|
|
85436
|
+
} else if (isStreamableJobStore(this.jobStore)) {
|
|
84772
85437
|
txSeq = await this.jobStore.recordInbound(job.id, {
|
|
84773
85438
|
from: "requester",
|
|
84774
85439
|
type: msgType,
|
|
@@ -84791,6 +85456,11 @@ var JobManager = class {
|
|
|
84791
85456
|
this.pendingPaymentMessages.set(job, pending);
|
|
84792
85457
|
}
|
|
84793
85458
|
pending.set(txSeq ?? msgContent, message);
|
|
85459
|
+
if (disposition) {
|
|
85460
|
+
let dispositions = this.paymentDispositions.get(job);
|
|
85461
|
+
if (!dispositions) this.paymentDispositions.set(job, dispositions = /* @__PURE__ */ new Map());
|
|
85462
|
+
dispositions.set(txSeq ?? msgContent, disposition);
|
|
85463
|
+
}
|
|
84794
85464
|
holdJobHistory(job, message.seq);
|
|
84795
85465
|
} else {
|
|
84796
85466
|
job.messages.push(message);
|
|
@@ -84907,27 +85577,44 @@ var JobManager = class {
|
|
|
84907
85577
|
const pending = this.pendingPaymentMessages.get(job);
|
|
84908
85578
|
const key = inboundSeq ?? body.content;
|
|
84909
85579
|
const message = pending?.get(key);
|
|
85580
|
+
const disposition = this.paymentDispositions.get(job)?.get(key) ?? decidePaymentDisposition({
|
|
85581
|
+
status: job.status,
|
|
85582
|
+
pendingPaymentMsats: job.pendingPaymentMsats,
|
|
85583
|
+
ask: job.messages?.findLast((m) => m.from === "provider" && m.type === "payment-request"),
|
|
85584
|
+
arrivedAtMs: Date.now()
|
|
85585
|
+
});
|
|
84910
85586
|
let accepted;
|
|
84911
85587
|
try {
|
|
84912
|
-
const outcome = await this.processPaymentAndCredit(job, body, inboundSeq, extra);
|
|
84913
|
-
if (!outcome.error && message && pending?.get(key) === message) {
|
|
85588
|
+
const outcome = await this.processPaymentAndCredit(job, body, inboundSeq, disposition, extra);
|
|
85589
|
+
if (!outcome.error && !outcome.landedAsBalance && message && pending?.get(key) === message) {
|
|
84914
85590
|
accepted = message;
|
|
84915
85591
|
}
|
|
84916
85592
|
return outcome;
|
|
85593
|
+
} catch (error62) {
|
|
85594
|
+
if (inboundSeq !== null && isStreamableJobStore(this.jobStore)) {
|
|
85595
|
+
await this.jobStore.markInboundFailed(job.id, inboundSeq, "verify_error").catch(() => void 0);
|
|
85596
|
+
}
|
|
85597
|
+
throw error62;
|
|
84917
85598
|
} finally {
|
|
84918
85599
|
pending?.delete(key);
|
|
84919
85600
|
if (message) releaseJobHistory(job, message.seq, accepted);
|
|
84920
85601
|
}
|
|
84921
85602
|
}
|
|
84922
|
-
async processPaymentAndCredit(job, body, inboundSeq, extra) {
|
|
85603
|
+
async processPaymentAndCredit(job, body, inboundSeq, disposition, extra) {
|
|
84923
85604
|
if (body.type !== "payment") return {};
|
|
85605
|
+
const landAsBalance = disposition.disposition === "balance" ? disposition.reason : void 0;
|
|
84924
85606
|
const devAuto = this.opts.devMode === true && body.content.dev_auto === true && !hasPaymentProof(body.content);
|
|
84925
85607
|
if (devAuto || devModeSkipsPaymentVerification(this.opts)) {
|
|
84926
85608
|
const hadPendingPayment2 = job.pendingPaymentMsats !== void 0;
|
|
84927
|
-
const delta = job.pendingPaymentMsats ?? 0;
|
|
85609
|
+
const delta = landAsBalance ? 0 : job.pendingPaymentMsats ?? 0;
|
|
84928
85610
|
if (inboundSeq !== null && isStreamableJobStore(this.jobStore)) {
|
|
84929
85611
|
const credit = delta ? { paidMsatsDelta: delta, clearPending: true } : null;
|
|
84930
|
-
const { counters } = await this.creditInbound(
|
|
85612
|
+
const { counters } = await this.creditInbound(
|
|
85613
|
+
job.id,
|
|
85614
|
+
inboundSeq,
|
|
85615
|
+
credit,
|
|
85616
|
+
landAsBalance ? { landedAsBalance: true } : void 0
|
|
85617
|
+
);
|
|
84931
85618
|
job.paidMsats = counters.paidMsats;
|
|
84932
85619
|
job.pendingPaymentMsats = counters.pendingPaymentMsats;
|
|
84933
85620
|
if (hadPendingPayment2 && delta > 0 && (counters.pendingPaymentMsats === void 0 || counters.pendingPaymentMsats === 0)) {
|
|
@@ -84942,7 +85629,7 @@ var JobManager = class {
|
|
|
84942
85629
|
if (hadPendingPayment2) job.reactivationPaymentApplied = true;
|
|
84943
85630
|
if (job.status === "awaiting-input" && job.pendingPrompts.size === 0) job.status = "processing";
|
|
84944
85631
|
}
|
|
84945
|
-
return {};
|
|
85632
|
+
return landAsBalance ? { landedAsBalance: landAsBalance } : {};
|
|
84946
85633
|
}
|
|
84947
85634
|
const verifyResult = await verifyIncomingPayment(
|
|
84948
85635
|
body,
|
|
@@ -84971,23 +85658,7 @@ var JobManager = class {
|
|
|
84971
85658
|
hostingPaymentSeq: inboundSeq ?? void 0,
|
|
84972
85659
|
creditTtlMs: this.opts.creditTtlMs
|
|
84973
85660
|
},
|
|
84974
|
-
{
|
|
84975
|
-
pendingPaymentMsats: job.pendingPaymentMsats,
|
|
84976
|
-
pendingMppChallengeIds: job.pendingMppChallengeIds,
|
|
84977
|
-
pendingX402Nonce: job.pendingX402Nonce,
|
|
84978
|
-
pendingX402AmountUsdcMicro: job.pendingX402AmountUsdcMicro,
|
|
84979
|
-
paymentRail: job.paymentRail,
|
|
84980
|
-
creditId: job.creditId,
|
|
84981
|
-
drawId: job.drawId,
|
|
84982
|
-
paymentTxHash: job.paymentTxHash,
|
|
84983
|
-
pendingPaymentFiatMicro: job.pendingPaymentFiatMicro,
|
|
84984
|
-
pendingPaymentFiatCurrency: job.pendingPaymentFiatCurrency,
|
|
84985
|
-
askedTopUpMicro: job.askedTopUpMicro,
|
|
84986
|
-
askedTopUpCurrency: job.askedTopUpCurrency,
|
|
84987
|
-
topUpCapUnenforcedReason: job.topUpCapUnenforcedReason,
|
|
84988
|
-
requesterPubkey: job.requesterPubkey,
|
|
84989
|
-
requesterId: job.requesterId
|
|
84990
|
-
}
|
|
85661
|
+
{ ...incomingPaymentSnapshot(job), ...landAsBalance && { landAsBalance } }
|
|
84991
85662
|
);
|
|
84992
85663
|
if (verifyResult.error) {
|
|
84993
85664
|
if (inboundSeq !== null && isStreamableJobStore(this.jobStore)) {
|
|
@@ -85008,7 +85679,8 @@ var JobManager = class {
|
|
|
85008
85679
|
if (!info) return { error: { status: 402, body: { error: "payment_invalid", message: "Payment was not accepted" } } };
|
|
85009
85680
|
const drawFundingReceipt = await this.drawFundingReceiptFor(info.drawFunding, info.funding?.currency);
|
|
85010
85681
|
let unappliedCredit;
|
|
85011
|
-
|
|
85682
|
+
let landing = landAsBalance ? { reason: landAsBalance } : info.landedAsBalance;
|
|
85683
|
+
let fullyUnapplied = landing !== void 0 || paymentFullyUnapplied(info);
|
|
85012
85684
|
const hadPendingPayment = job.pendingPaymentMsats !== void 0;
|
|
85013
85685
|
if (inboundSeq !== null && isStreamableJobStore(this.jobStore)) {
|
|
85014
85686
|
let result;
|
|
@@ -85028,8 +85700,10 @@ var JobManager = class {
|
|
|
85028
85700
|
accumulateNative: info.sameRail,
|
|
85029
85701
|
clearPendingX402Binding: info.paymentRail === "x402",
|
|
85030
85702
|
creditId: info.creditId,
|
|
85031
|
-
drawId: info.drawId
|
|
85032
|
-
|
|
85703
|
+
drawId: info.drawId,
|
|
85704
|
+
...info.piece && { piece: info.piece }
|
|
85705
|
+
},
|
|
85706
|
+
landing ? { landedAsBalance: true } : void 0
|
|
85033
85707
|
);
|
|
85034
85708
|
} catch (err) {
|
|
85035
85709
|
const unapplied = await this.reportUnappliedPayment(job, inboundSeq, info, err);
|
|
@@ -85041,12 +85715,24 @@ var JobManager = class {
|
|
|
85041
85715
|
};
|
|
85042
85716
|
}
|
|
85043
85717
|
const { counters } = result;
|
|
85718
|
+
if (result.creditRefused && !fullyUnapplied) {
|
|
85719
|
+
landing = { reason: result.creditRefused };
|
|
85720
|
+
fullyUnapplied = true;
|
|
85721
|
+
await this.releaseOrphanedDraw(job, info);
|
|
85722
|
+
unappliedCredit = this.unappliedCredit(info.funding, info.funding?.creditId, landing.reason);
|
|
85723
|
+
}
|
|
85044
85724
|
job.paidMsats = counters.paidMsats;
|
|
85045
85725
|
job.pendingPaymentMsats = counters.pendingPaymentMsats;
|
|
85726
|
+
if (counters.pieces) {
|
|
85727
|
+
job.pieces = counters.pieces;
|
|
85728
|
+
} else if (!fullyUnapplied && !result.creditRefused && job.pieces && info.piece && info.piece.amountMicro > 0 && (result.drawId ?? job.drawId ?? info.drawId) === info.piece.drawId) {
|
|
85729
|
+
job.pieces = appendPiece(job.pieces, info.piece.amountMicro, inboundSeq);
|
|
85730
|
+
}
|
|
85046
85731
|
if (!fullyUnapplied && hadPendingPayment && (counters.pendingPaymentMsats === void 0 || counters.pendingPaymentMsats === 0)) {
|
|
85047
85732
|
job.reactivationPaymentApplied = true;
|
|
85048
85733
|
}
|
|
85049
|
-
if (result.
|
|
85734
|
+
if (result.creditRefused) {
|
|
85735
|
+
} else if (result.creditId !== void 0 || result.drawId !== void 0) {
|
|
85050
85736
|
job.creditId = result.creditId;
|
|
85051
85737
|
job.drawId = result.drawId;
|
|
85052
85738
|
if (info.creditId && result.creditId !== info.creditId) {
|
|
@@ -85086,14 +85772,18 @@ var JobManager = class {
|
|
|
85086
85772
|
job.status = "processing";
|
|
85087
85773
|
}
|
|
85088
85774
|
} else {
|
|
85089
|
-
applyPaymentInfoToJob(job, info);
|
|
85775
|
+
if (!fullyUnapplied) applyPaymentInfoToJob(job, info);
|
|
85776
|
+
if (!fullyUnapplied && job.pieces && info.piece && info.piece.amountMicro > 0 && job.drawId === info.piece.drawId) {
|
|
85777
|
+
job.pieces = appendPiece(job.pieces, info.piece.amountMicro, job.seq);
|
|
85778
|
+
}
|
|
85090
85779
|
if (!fullyUnapplied && hadPendingPayment && (job.pendingPaymentMsats === void 0 || job.pendingPaymentMsats === 0)) {
|
|
85091
85780
|
job.reactivationPaymentApplied = true;
|
|
85092
85781
|
}
|
|
85093
85782
|
}
|
|
85094
85783
|
if (!unappliedCredit && info.unappliedMicro !== void 0 && info.unappliedMicro > 0) {
|
|
85095
|
-
unappliedCredit = this.unappliedCredit(info.funding, info.funding?.creditId, "over_ask", {
|
|
85096
|
-
creditedMicro: info.unappliedMicro
|
|
85784
|
+
unappliedCredit = this.unappliedCredit(info.funding, info.funding?.creditId, landing?.reason ?? "over_ask", {
|
|
85785
|
+
creditedMicro: info.unappliedMicro,
|
|
85786
|
+
jobRail: landing?.jobRail
|
|
85097
85787
|
});
|
|
85098
85788
|
diagnosticConsole.warn(
|
|
85099
85789
|
{
|
|
@@ -85110,7 +85800,8 @@ var JobManager = class {
|
|
|
85110
85800
|
this.reportCreditDeposit(info.funding);
|
|
85111
85801
|
return {
|
|
85112
85802
|
...unappliedCredit && { unappliedCredit },
|
|
85113
|
-
...drawFundingReceipt && { drawFundingReceipt }
|
|
85803
|
+
...drawFundingReceipt && { drawFundingReceipt },
|
|
85804
|
+
...landing && { landedAsBalance: landing.reason }
|
|
85114
85805
|
};
|
|
85115
85806
|
}
|
|
85116
85807
|
/** Issue (or reuse) the signed draw funding receipt for a committed funding row; never throws. */
|
|
@@ -85216,7 +85907,7 @@ var JobManager = class {
|
|
|
85216
85907
|
* separates "checked the row, nothing landed" from "couldn't check", both on
|
|
85217
85908
|
* the operator's log line and in the copy the caller acts on.
|
|
85218
85909
|
*/
|
|
85219
|
-
async creditInbound(jobId, seq, credit) {
|
|
85910
|
+
async creditInbound(jobId, seq, credit, opts) {
|
|
85220
85911
|
const store = this.jobStore;
|
|
85221
85912
|
if (!isStreamableJobStore(store)) {
|
|
85222
85913
|
throw new Error("creditInbound requires a streamable job store");
|
|
@@ -85224,7 +85915,7 @@ var JobManager = class {
|
|
|
85224
85915
|
let lastErr;
|
|
85225
85916
|
for (let attempt = 1; attempt <= CREDIT_INBOUND_ATTEMPTS; attempt++) {
|
|
85226
85917
|
try {
|
|
85227
|
-
return await store.verifyAndCredit(jobId, seq, credit);
|
|
85918
|
+
return await store.verifyAndCredit(jobId, seq, credit, opts);
|
|
85228
85919
|
} catch (err) {
|
|
85229
85920
|
lastErr = err;
|
|
85230
85921
|
if (attempt === CREDIT_INBOUND_ATTEMPTS) break;
|
|
@@ -85359,7 +86050,7 @@ var JobManager = class {
|
|
|
85359
86050
|
credit_id: creditId,
|
|
85360
86051
|
credited_micro: opts?.creditedMicro ?? funding.amountMicro,
|
|
85361
86052
|
credit_currency: funding.currency,
|
|
85362
|
-
...unappliedCopy(reason, creditId)
|
|
86053
|
+
...unappliedCopy(reason, creditId, opts?.jobRail)
|
|
85363
86054
|
};
|
|
85364
86055
|
}
|
|
85365
86056
|
/** Book a mid-job top-up's funding as a deposit (the deposit-accounting rule). */
|
|
@@ -85430,6 +86121,7 @@ var JobManager = class {
|
|
|
85430
86121
|
return jobStore.getCounters(job.id);
|
|
85431
86122
|
} : void 0,
|
|
85432
86123
|
drawPool: this.opts.creditLedger ? () => this.resolveDrawPool(job) : void 0,
|
|
86124
|
+
creditRail: this.opts.creditLedger ? () => this.payableCreditRail(job) : void 0,
|
|
85433
86125
|
pricingCurrency: this.pricingCurrency,
|
|
85434
86126
|
claimForProcessing: isStreamableJobStore(jobStore) ? (resume) => {
|
|
85435
86127
|
const pending = job.pendingPayment;
|
|
@@ -85455,33 +86147,10 @@ var JobManager = class {
|
|
|
85455
86147
|
};
|
|
85456
86148
|
}
|
|
85457
86149
|
/**
|
|
85458
|
-
* Internal:
|
|
85459
|
-
* job'
|
|
85460
|
-
*
|
|
85461
|
-
* The regime is read off the DRAW, never off the job. Implicit N=1 is exactly
|
|
85462
|
-
* `credit_id === imp:<rail>:<draw_id>`, because `fundAndDraw` derives both
|
|
85463
|
-
* from the same rail payment id — a fact about a row that was written once
|
|
85464
|
-
* and never moves. The tempting alternative, comparing `job.payment_tx_hash`
|
|
85465
|
-
* against `drawSettlementRef` (what the mid-job preflight does to inherit
|
|
85466
|
-
* `drawBasis`), silently rots: Tx C overwrites that column on every mid-job
|
|
85467
|
-
* credit, and a payment whose ledger leg was skipped — a cross-rail top-up,
|
|
85468
|
-
* an fx outage, a draw already resolved — leaves the rail's own reference
|
|
85469
|
-
* there, so an explicit-draw job would read as implicit from then on.
|
|
85470
|
-
*
|
|
85471
|
-
* Never throws, and never answers `rail` on a guess. `rail` is claimed only
|
|
85472
|
-
* where `withDrawBasis` demonstrably left `PaymentInfo.paidMsats` alone — no
|
|
85473
|
-
* draw at all, or a draw carrying no rail value to overlay it with. A job that
|
|
85474
|
-
* drew and whose pool this can't read or denominate answers `unpriced`, which
|
|
85475
|
-
* the gate declines to auto-credit from: the msat figure it would otherwise
|
|
85476
|
-
* fall back on is a slice of the credit's rail value at a ratio pinned
|
|
85477
|
-
* whenever that credit was funded, so it cannot safely fund a new ask.
|
|
86150
|
+
* Internal: the job's draw as `ctx.requestPayment` reads it for the currency a mid-job ask
|
|
86151
|
+
* is pinned in. Never rejects: a job that drew but whose draw can't be read answers
|
|
86152
|
+
* `unpriced`, and the ask falls back to the DVM's declared currency.
|
|
85478
86153
|
*/
|
|
85479
|
-
async hasAcceptedBalancePayment(jobId) {
|
|
85480
|
-
return this.jobStore instanceof PostgresJobStore && !!this.opts.db && !!(await this.opts.db.query(
|
|
85481
|
-
"SELECT 1 FROM credit_balance_payments WHERE job_id=$1 LIMIT 1",
|
|
85482
|
-
[jobId]
|
|
85483
|
-
)).rowCount;
|
|
85484
|
-
}
|
|
85485
86154
|
async resolveDrawPool(job) {
|
|
85486
86155
|
const ledger = this.opts.creditLedger;
|
|
85487
86156
|
if (!ledger || !job.creditId || !job.drawId) return { basis: "rail" };
|
|
@@ -85500,21 +86169,30 @@ var JobManager = class {
|
|
|
85500
86169
|
this.warnDrawPool(job, "draw_not_found");
|
|
85501
86170
|
return { basis: "unpriced" };
|
|
85502
86171
|
}
|
|
85503
|
-
const
|
|
85504
|
-
if (!rail || drawMsats <= 0) {
|
|
85505
|
-
const acceptedBalance = await this.hasAcceptedBalancePayment(job.id);
|
|
85506
|
-
if (!acceptedBalance) return { basis: "rail", creditCurrency: creditCurrency ?? void 0 };
|
|
85507
|
-
}
|
|
86172
|
+
const creditCurrency = draw.railValue.creditCurrency;
|
|
85508
86173
|
if (!creditCurrency) {
|
|
85509
86174
|
this.warnDrawPool(job, "credit_currency_missing");
|
|
85510
86175
|
return { basis: "unpriced" };
|
|
85511
86176
|
}
|
|
85512
|
-
const attachRail = ATTACH_RAILS.find((r) => r === rail);
|
|
85513
|
-
if (attachRail && draw.creditId === implicitCreditId(attachRail, draw.drawId)) {
|
|
85514
|
-
return { basis: "rail", creditCurrency };
|
|
85515
|
-
}
|
|
85516
86177
|
return { basis: "draw", amountMicro: draw.amountMicro, currency: creditCurrency };
|
|
85517
86178
|
}
|
|
86179
|
+
/**
|
|
86180
|
+
* The one rail a mid-job payment can pay into this job's credit on, if any.
|
|
86181
|
+
* Mirrors the top-up preflight: the credit must be active and bound to no
|
|
86182
|
+
* channel, and its rail must be one a mid-job ask offers. Any read failure
|
|
86183
|
+
* answers undefined, so the ask offers every rail rather than none.
|
|
86184
|
+
*/
|
|
86185
|
+
async payableCreditRail(job) {
|
|
86186
|
+
const ledger = this.opts.creditLedger;
|
|
86187
|
+
if (!ledger || !job.creditId || !job.drawId) return void 0;
|
|
86188
|
+
const [credit, draw] = await Promise.all([
|
|
86189
|
+
ledger.get(job.creditId).catch(() => void 0),
|
|
86190
|
+
ledger.getDraw({ creditId: job.creditId, drawId: job.drawId }).catch(() => void 0)
|
|
86191
|
+
]);
|
|
86192
|
+
if (!credit || !draw || credit.status !== "active" || credit.tempoChannelId || credit.x402ChannelId) return void 0;
|
|
86193
|
+
const rail = draw.railValue.rail;
|
|
86194
|
+
return rail === "cashu" || rail === "x402" || rail === "tempo" ? rail : void 0;
|
|
86195
|
+
}
|
|
85518
86196
|
/** Internal: structured warn for the one path that can't price a drawn job's pool. */
|
|
85519
86197
|
warnDrawPool(job, reason, error62) {
|
|
85520
86198
|
diagnosticConsole.warn(
|
|
@@ -85562,9 +86240,9 @@ var JobManager = class {
|
|
|
85562
86240
|
return record2.receipt;
|
|
85563
86241
|
}
|
|
85564
86242
|
if (!isReceiptableStatus(record2.status)) return void 0;
|
|
85565
|
-
let
|
|
86243
|
+
let resolved;
|
|
85566
86244
|
try {
|
|
85567
|
-
|
|
86245
|
+
resolved = await this.resolveCreditDraw(record2);
|
|
85568
86246
|
} catch (_err) {
|
|
85569
86247
|
diagnosticConsole.error(
|
|
85570
86248
|
{
|
|
@@ -85588,7 +86266,14 @@ var JobManager = class {
|
|
|
85588
86266
|
const store = this.jobStore;
|
|
85589
86267
|
try {
|
|
85590
86268
|
const seq = await store.claimReceiptSeq(record2.id);
|
|
85591
|
-
const receipt = issuer.issue(
|
|
86269
|
+
const receipt = issuer.issue(
|
|
86270
|
+
record2,
|
|
86271
|
+
seq,
|
|
86272
|
+
void 0,
|
|
86273
|
+
resolved?.credit,
|
|
86274
|
+
await this.deferredUnpaid(record2),
|
|
86275
|
+
resolved?.settlement
|
|
86276
|
+
);
|
|
85592
86277
|
const saved = await store.saveReceipt(record2.id, receipt);
|
|
85593
86278
|
if (!saved) return void 0;
|
|
85594
86279
|
await this.observePaidCompletion(record2);
|
|
@@ -85607,6 +86292,27 @@ var JobManager = class {
|
|
|
85607
86292
|
}
|
|
85608
86293
|
}
|
|
85609
86294
|
/** Build the common settle/release args, adding the hosted release outbox when wired. */
|
|
86295
|
+
/**
|
|
86296
|
+
* Release the draw a payment placed for a job that ended before the payment
|
|
86297
|
+
* was recorded. The job row never bound it; if this release fails, the
|
|
86298
|
+
* terminal-draw reconciler releases it as an unbound hold.
|
|
86299
|
+
*/
|
|
86300
|
+
async releaseOrphanedDraw(job, info) {
|
|
86301
|
+
const ledger = this.opts.creditLedger;
|
|
86302
|
+
if (!ledger || !info.creditId || !info.drawId) return;
|
|
86303
|
+
try {
|
|
86304
|
+
await ledger.release(this.drawResolutionArgs(info.creditId, info.drawId));
|
|
86305
|
+
} catch (err) {
|
|
86306
|
+
diagnosticConsole.warn({
|
|
86307
|
+
level: "warn",
|
|
86308
|
+
event: "credit_draw_reconcile_failed",
|
|
86309
|
+
jobId: job.id,
|
|
86310
|
+
creditId: info.creditId,
|
|
86311
|
+
drawId: info.drawId,
|
|
86312
|
+
code: err instanceof CreditLedgerError ? err.code : void 0
|
|
86313
|
+
});
|
|
86314
|
+
}
|
|
86315
|
+
}
|
|
85610
86316
|
drawResolutionArgs(creditId, drawId) {
|
|
85611
86317
|
const enqueue = this.opts.enqueueCreditDrawRelease;
|
|
85612
86318
|
const dvmId = this.opts.dvmId;
|
|
@@ -85617,34 +86323,22 @@ var JobManager = class {
|
|
|
85617
86323
|
};
|
|
85618
86324
|
}
|
|
85619
86325
|
/**
|
|
85620
|
-
*
|
|
85621
|
-
*
|
|
85622
|
-
*
|
|
85623
|
-
*
|
|
85624
|
-
*
|
|
85625
|
-
*
|
|
85626
|
-
* for the receipt: `balance_after` is the recorded draw trajectory for a
|
|
85627
|
-
* settled draw, and the restored available balance for a released one.
|
|
86326
|
+
* Resolve a terminal job's credit draw by the piece: settle the figure its terminal
|
|
86327
|
+
* transition froze (finished pieces, and on a cancel the stopped one) and release the rest,
|
|
86328
|
+
* in one `resolveDraw`. Idempotent — a replayed resolution returns the recorded state.
|
|
86329
|
+
* Returns the receipt's `credit` and `settlement` blocks: `credit.amount` is what the draw
|
|
86330
|
+
* charged and `balance_after` the recorded draw trajectory for a settled draw, the restored
|
|
86331
|
+
* available balance for a released one.
|
|
85628
86332
|
*/
|
|
85629
86333
|
async resolveCreditDraw(record2) {
|
|
85630
86334
|
const ledger = this.opts.creditLedger;
|
|
85631
86335
|
if (!ledger || !record2.creditId || !record2.drawId) return void 0;
|
|
85632
86336
|
const args = this.drawResolutionArgs(record2.creditId, record2.drawId);
|
|
85633
|
-
const existing = await ledger.getDraw(args);
|
|
85634
|
-
if (existing?.status === "settled" && this.settlesDraw(record2.status)) {
|
|
85635
|
-
return {
|
|
85636
|
-
credit_id: existing.creditId,
|
|
85637
|
-
draw_id: existing.drawId,
|
|
85638
|
-
amount: existing.amountMicro,
|
|
85639
|
-
balance_after: existing.balanceAfterMicro,
|
|
85640
|
-
ledger_seq: existing.ledgerSeq
|
|
85641
|
-
};
|
|
85642
|
-
}
|
|
85643
86337
|
const deferredIntent = deferredX402IntentId(record2.creditId);
|
|
85644
86338
|
if (deferredIntent) {
|
|
85645
86339
|
const deferred = this.opts.deferredX402;
|
|
85646
86340
|
if (!deferred) throw new Error(`no settler for deferred x402 intent ${deferredIntent}`);
|
|
85647
|
-
if (
|
|
86341
|
+
if (record2.status !== "completed") {
|
|
85648
86342
|
await deferred.release(deferredIntent, record2.status);
|
|
85649
86343
|
return void 0;
|
|
85650
86344
|
}
|
|
@@ -85658,14 +86352,16 @@ var JobManager = class {
|
|
|
85658
86352
|
return void 0;
|
|
85659
86353
|
}
|
|
85660
86354
|
}
|
|
86355
|
+
const existing = await ledger.getDraw(args);
|
|
86356
|
+
if (existing?.status === "settled") {
|
|
86357
|
+
return { credit: receiptCreditFor(existing, existing.balanceAfterMicro), settlement: receiptSettlementFor(record2, existing) };
|
|
86358
|
+
}
|
|
86359
|
+
const settleMicro = existing ? this.settleMicroFor(record2, existing) : 0;
|
|
85661
86360
|
try {
|
|
85662
|
-
const res =
|
|
86361
|
+
const res = await ledger.resolveDraw({ ...args, settleMicro });
|
|
85663
86362
|
return {
|
|
85664
|
-
|
|
85665
|
-
|
|
85666
|
-
amount: res.amountMicro,
|
|
85667
|
-
balance_after: res.status === "settled" ? res.balanceAfterMicro : res.availableMicro,
|
|
85668
|
-
ledger_seq: res.ledgerSeq
|
|
86363
|
+
credit: receiptCreditFor(res, res.status === "settled" ? res.balanceAfterMicro : res.availableMicro),
|
|
86364
|
+
settlement: receiptSettlementFor(record2, res)
|
|
85669
86365
|
};
|
|
85670
86366
|
} catch (err) {
|
|
85671
86367
|
if (err instanceof CreditLedgerError && err.code === "invalid_draw_state") {
|
|
@@ -85682,26 +86378,42 @@ var JobManager = class {
|
|
|
85682
86378
|
drawStatus: rec.status
|
|
85683
86379
|
}
|
|
85684
86380
|
);
|
|
85685
|
-
return {
|
|
85686
|
-
credit_id: rec.creditId,
|
|
85687
|
-
draw_id: rec.drawId,
|
|
85688
|
-
amount: rec.amountMicro,
|
|
85689
|
-
balance_after: rec.balanceAfterMicro,
|
|
85690
|
-
ledger_seq: rec.ledgerSeq
|
|
85691
|
-
};
|
|
86381
|
+
return { credit: receiptCreditFor(rec, rec.balanceAfterMicro), settlement: receiptSettlementFor(record2, rec) };
|
|
85692
86382
|
}
|
|
85693
86383
|
throw err;
|
|
85694
86384
|
}
|
|
85695
86385
|
}
|
|
85696
86386
|
/**
|
|
85697
|
-
* The
|
|
85698
|
-
*
|
|
85699
|
-
*
|
|
85700
|
-
*
|
|
85701
|
-
* disagree about what an outcome means for the caller's money.
|
|
86387
|
+
* The micro-units a terminal job's draw settles — the one place a terminal job becomes a
|
|
86388
|
+
* ledger figure. Read by the in-line funnel (`resolveCreditDraw`) and by the late
|
|
86389
|
+
* reconciler (`reconcileTerminalDraw`), two paths that must never disagree about what an
|
|
86390
|
+
* ending means for the caller's money.
|
|
85702
86391
|
*/
|
|
85703
|
-
|
|
85704
|
-
|
|
86392
|
+
settleMicroFor(record2, draw) {
|
|
86393
|
+
const { settleMicro, clamped } = frozenSettleMicro(record2, drawHeldMicro(draw));
|
|
86394
|
+
if (clamped) {
|
|
86395
|
+
diagnosticConsole.warn({
|
|
86396
|
+
level: "warn",
|
|
86397
|
+
event: "piece_settlement_exceeds_hold",
|
|
86398
|
+
jobId: record2.id,
|
|
86399
|
+
creditId: draw.creditId,
|
|
86400
|
+
drawId: draw.drawId,
|
|
86401
|
+
heldMicro: drawHeldMicro(draw),
|
|
86402
|
+
chargedMicro: record2.settlement?.chargedMicro
|
|
86403
|
+
});
|
|
86404
|
+
}
|
|
86405
|
+
return settleMicro;
|
|
86406
|
+
}
|
|
86407
|
+
/**
|
|
86408
|
+
* A completed deferred-x402 job whose authorization was never collected: its
|
|
86409
|
+
* output stays withheld and nothing it reports or signs may claim payment.
|
|
86410
|
+
* `settle` is idempotent once the intent is resolved, so this re-reads the
|
|
86411
|
+
* recorded outcome; it rejects while the outcome is still unknown.
|
|
86412
|
+
*/
|
|
86413
|
+
async deferredUnpaid(record2) {
|
|
86414
|
+
const intentId = deferredX402IntentId(record2.creditId);
|
|
86415
|
+
if (!intentId || record2.status !== "completed" || !this.opts.deferredX402) return false;
|
|
86416
|
+
return await this.opts.deferredX402.settle(intentId) === "unpaid";
|
|
85705
86417
|
}
|
|
85706
86418
|
/**
|
|
85707
86419
|
* Sign a locally-held terminal job's receipt and mirror it onto the
|
|
@@ -85806,9 +86518,15 @@ var JobManager = class {
|
|
|
85806
86518
|
if (!record2 || !isReceiptableStatus(record2.status) || record2.timingKnown === false || record2.terminalAtMs === void 0 || record2.status !== "completed" && !record2.endedBy) return;
|
|
85807
86519
|
const receipt = await this.issueReceipt(record2);
|
|
85808
86520
|
if (this.opts.receiptIssuer && !receipt) return;
|
|
85809
|
-
|
|
86521
|
+
const abandoned = deferredX402IntentId(record2.creditId) !== void 0 && record2.status !== "completed";
|
|
86522
|
+
const unpaid = abandoned || await this.deferredUnpaid(record2);
|
|
86523
|
+
let chargedMicro = 0;
|
|
86524
|
+
let currency = null;
|
|
86525
|
+
if (!unpaid && record2.creditId && record2.drawId && this.opts.creditLedger) {
|
|
85810
86526
|
const draw = await this.opts.creditLedger.getDraw({ creditId: record2.creditId, drawId: record2.drawId });
|
|
85811
86527
|
if (!draw || draw.status === "pending") return;
|
|
86528
|
+
chargedMicro = drawChargedMicro(draw);
|
|
86529
|
+
currency = draw.railValue.creditCurrency;
|
|
85812
86530
|
}
|
|
85813
86531
|
await callback({
|
|
85814
86532
|
dvmId,
|
|
@@ -85816,11 +86534,14 @@ var JobManager = class {
|
|
|
85816
86534
|
capability: record2.capability,
|
|
85817
86535
|
outcome: record2.status,
|
|
85818
86536
|
endedBy: record2.status === "completed" ? null : record2.endedBy ?? "provider",
|
|
85819
|
-
paid: record2.paidMsats > 0 || (record2.nativeAmount ?? 0) > 0 || !!record2.drawId,
|
|
86537
|
+
paid: !unpaid && (record2.paidMsats > 0 || (record2.nativeAmount ?? 0) > 0 || !!record2.drawId),
|
|
85820
86538
|
acceptedAtMs: record2.createdAt,
|
|
85821
86539
|
terminalAtMs: record2.terminalAtMs,
|
|
85822
86540
|
callerWaitMs: record2.callerWaitMs ?? 0,
|
|
85823
|
-
receiptSeq: receipt?.seq ?? null
|
|
86541
|
+
receiptSeq: receipt?.seq ?? null,
|
|
86542
|
+
chargedMicro,
|
|
86543
|
+
currency,
|
|
86544
|
+
stoppedPiece: record2.settlement?.stoppedPiece === true
|
|
85824
86545
|
});
|
|
85825
86546
|
if ("markTerminalReported" in this.jobStore) {
|
|
85826
86547
|
await this.jobStore.markTerminalReported(jobId);
|
|
@@ -85945,20 +86666,18 @@ var JobManager = class {
|
|
|
85945
86666
|
return true;
|
|
85946
86667
|
}
|
|
85947
86668
|
/**
|
|
85948
|
-
* Report a
|
|
86669
|
+
* Report a paid job's revenue under its durable job identity.
|
|
85949
86670
|
* Fire-and-forget — the `RevenueReporter` owns persistence and retry.
|
|
85950
86671
|
*
|
|
85951
86672
|
* For a **credit-backed** job the revenue event is the *settled draw* (spec
|
|
85952
|
-
* §10), and
|
|
85953
|
-
* draw
|
|
85954
|
-
*
|
|
85955
|
-
*
|
|
85956
|
-
*
|
|
85957
|
-
*
|
|
85958
|
-
*
|
|
85959
|
-
*
|
|
85960
|
-
* here, which is what makes "no debit on job failure" true in the books as
|
|
85961
|
-
* well as the ledger.
|
|
86673
|
+
* §10), and the amounts correct the job's mirror of that draw against the
|
|
86674
|
+
* draw itself (`settledDrawRevenue`): a Bitcoin credit's settle re-prices the
|
|
86675
|
+
* draw against the funding lots it consumed, and a partial settle charges
|
|
86676
|
+
* only part of the hold. The event is dated at settlement rather than at
|
|
86677
|
+
* report time. A settled draw books whatever the job's outcome, so a failed
|
|
86678
|
+
* or cancelled job charged for part of its work books that part; a released
|
|
86679
|
+
* draw books nothing, which is what makes "no debit on job failure" true in
|
|
86680
|
+
* the books as well as the ledger. Without a draw, only a completed job books.
|
|
85962
86681
|
*
|
|
85963
86682
|
* For everything else (free-then-paid jobs, isolate-shaped flows, a DVM
|
|
85964
86683
|
* whose price couldn't be fiat-denominated) nothing changes: the pre-credits
|
|
@@ -85991,14 +86710,17 @@ var JobManager = class {
|
|
|
85991
86710
|
const onJobCompleted = this.opts.onJobCompleted;
|
|
85992
86711
|
const onRevenueSkippedNoRail = this.opts.onRevenueSkippedNoRail;
|
|
85993
86712
|
if (!onJobCompleted && !onRevenueSkippedNoRail) return false;
|
|
85994
|
-
|
|
86713
|
+
const drawBacked = !!(job.creditId && job.drawId && this.opts.creditLedger);
|
|
86714
|
+
if (job.status !== "completed" && !(drawBacked && isTerminal(job.status))) return false;
|
|
85995
86715
|
let credit = {};
|
|
85996
86716
|
let creditRail;
|
|
85997
86717
|
let drawAmountMicro;
|
|
85998
86718
|
let bookedMsats = job.paidMsats;
|
|
86719
|
+
let bookedNative = job.nativeAmount;
|
|
85999
86720
|
if (job.creditId && job.drawId && this.opts.creditLedger) {
|
|
86000
86721
|
const args = { creditId: job.creditId, drawId: job.drawId };
|
|
86001
86722
|
const draw = await this.opts.creditLedger.getDraw(args).catch(() => void 0);
|
|
86723
|
+
if (draw?.status !== "settled" && job.status !== "completed") return false;
|
|
86002
86724
|
if (draw?.status !== "settled") {
|
|
86003
86725
|
diagnosticConsole.warn(
|
|
86004
86726
|
{
|
|
@@ -86014,11 +86736,7 @@ var JobManager = class {
|
|
|
86014
86736
|
}
|
|
86015
86737
|
creditRail = draw.railValue.rail;
|
|
86016
86738
|
drawAmountMicro = draw.amountMicro;
|
|
86017
|
-
|
|
86018
|
-
bookedMsats = Math.max(0, job.paidMsats - draw.allocatedMsats + draw.railValue.drawMsats);
|
|
86019
|
-
} else if (draw.railValue.drawMsats > 0) {
|
|
86020
|
-
bookedMsats = draw.railValue.drawMsats;
|
|
86021
|
-
}
|
|
86739
|
+
({ paidMsats: bookedMsats, nativeAmount: bookedNative } = settledDrawRevenue(job, draw));
|
|
86022
86740
|
credit = {
|
|
86023
86741
|
creditId: draw.creditId,
|
|
86024
86742
|
drawId: draw.drawId,
|
|
@@ -86090,7 +86808,7 @@ var JobManager = class {
|
|
|
86090
86808
|
paymentMint: job.paymentMint,
|
|
86091
86809
|
rail: job.paymentRail,
|
|
86092
86810
|
paymentTxHash: job.paymentTxHash,
|
|
86093
|
-
nativeAmount:
|
|
86811
|
+
nativeAmount: bookedNative,
|
|
86094
86812
|
nativeAsset: job.nativeAsset,
|
|
86095
86813
|
cashuFlow: job.cashuFlow,
|
|
86096
86814
|
// Absent unless the handler declared one, and absent is a fact: the
|
|
@@ -86198,7 +86916,8 @@ var CreditInboundExhaustedError = class extends Error {
|
|
|
86198
86916
|
function errText(err) {
|
|
86199
86917
|
return err instanceof Error ? err.message : String(err);
|
|
86200
86918
|
}
|
|
86201
|
-
function unappliedCopy(reason, creditId) {
|
|
86919
|
+
function unappliedCopy(reason, creditId, jobRail) {
|
|
86920
|
+
const payOn = jobRail ? `pay it with ${jobRail}, the method this job's credit holds` : "pay it with a method its payment request offers";
|
|
86202
86921
|
if (!creditId) {
|
|
86203
86922
|
const noLedger = `This service holds no prepaid balance, so anything this job doesn't charge for can only be recovered from the provider directly.`;
|
|
86204
86923
|
return {
|
|
@@ -86217,6 +86936,26 @@ function unappliedCopy(reason, creditId) {
|
|
|
86217
86936
|
over_ask: {
|
|
86218
86937
|
display: "The payment was received, but this job had already been paid for what it asked \u2014 so none of it was charged to this job.",
|
|
86219
86938
|
hint: `Don't re-send it: this job's payment request is already satisfied. ${noLedger}`
|
|
86939
|
+
},
|
|
86940
|
+
job_ended: {
|
|
86941
|
+
display: "The payment arrived after this job ended, so none of it was charged to this job.",
|
|
86942
|
+
hint: `Don't re-send it: the job is finished. ${noLedger}`
|
|
86943
|
+
},
|
|
86944
|
+
ask_expired: {
|
|
86945
|
+
display: "The payment arrived after this job's payment request expired, so none of it was charged to this job.",
|
|
86946
|
+
hint: `Don't re-send it: the expired request can no longer be paid. ${noLedger}`
|
|
86947
|
+
},
|
|
86948
|
+
no_open_ask: {
|
|
86949
|
+
display: "The payment arrived while this job had no payment request open, so none of it was charged to this job.",
|
|
86950
|
+
hint: `Don't re-send it. ${noLedger}`
|
|
86951
|
+
},
|
|
86952
|
+
rail_mismatch: {
|
|
86953
|
+
display: "The payment used a different method from the one this job's credit holds, so it wasn't applied to this job. The job's payment request is still outstanding.",
|
|
86954
|
+
hint: `To satisfy the request, ${payOn}. ${noLedger}`
|
|
86955
|
+
},
|
|
86956
|
+
credit_unavailable: {
|
|
86957
|
+
display: "The payment wasn't applied to this job because the job's credit could not take it. The job's payment request is still outstanding.",
|
|
86958
|
+
hint: `Read this job's status before paying again. ${noLedger}`
|
|
86220
86959
|
}
|
|
86221
86960
|
}[reason];
|
|
86222
86961
|
}
|
|
@@ -86237,6 +86976,26 @@ function unappliedCopy(reason, creditId) {
|
|
|
86237
86976
|
over_ask: {
|
|
86238
86977
|
display: "The payment was received, but this job had already been paid for what it asked \u2014 so the amount is prepaid balance with this service rather than a charge against this job.",
|
|
86239
86978
|
hint: `The balance is on credit ${creditId} and nothing is holding it. Don't re-send this payment: this job's payment request is already satisfied. Spend the balance on a later request, or reclaim it now with op "drain" at POST /v1/credit.`
|
|
86979
|
+
},
|
|
86980
|
+
job_ended: {
|
|
86981
|
+
display: "The payment arrived after this job ended, so it was not charged to the job. The amount is prepaid balance with this service.",
|
|
86982
|
+
hint: `The balance is on credit ${creditId} and nothing is holding it. Don't re-send this payment. A signed caller can spend the balance on a later request, or reclaim it with op "drain" at POST /v1/credit; an unsigned payment is final.`
|
|
86983
|
+
},
|
|
86984
|
+
ask_expired: {
|
|
86985
|
+
display: "The payment arrived after this job's payment request expired, so it was not charged to the job. The amount is prepaid balance with this service.",
|
|
86986
|
+
hint: `The balance is on credit ${creditId} and nothing is holding it. Don't re-send this payment: the expired request can no longer be paid. A signed caller can spend the balance on a later request, or reclaim it with op "drain" at POST /v1/credit; an unsigned payment is final.`
|
|
86987
|
+
},
|
|
86988
|
+
no_open_ask: {
|
|
86989
|
+
display: "The payment arrived while this job had no payment request open, so it was not charged to the job. The amount is prepaid balance with this service.",
|
|
86990
|
+
hint: `The balance is on credit ${creditId} and nothing is holding it. Don't re-send this payment. A signed caller can spend the balance on a later request, or reclaim it with op "drain" at POST /v1/credit; an unsigned payment is final.`
|
|
86991
|
+
},
|
|
86992
|
+
rail_mismatch: {
|
|
86993
|
+
display: "The payment used a different method from the one this job's credit holds, so it wasn't applied to this job. The amount is prepaid balance with this service, and the job's payment request is still outstanding.",
|
|
86994
|
+
hint: `The balance is on credit ${creditId} and nothing is holding it. To satisfy the request, ${payOn}. A signed caller can spend the balance on a later request, or reclaim the balance with op "drain" at POST /v1/credit; an unsigned payment is final.`
|
|
86995
|
+
},
|
|
86996
|
+
credit_unavailable: {
|
|
86997
|
+
display: "The payment wasn't applied to this job because the job's credit could not take it. The amount is prepaid balance with this service, and the job's payment request is still outstanding.",
|
|
86998
|
+
hint: `The balance is on credit ${creditId} and nothing is holding it. Read this job's status before paying again. A signed caller can reclaim the balance with op "drain" at POST /v1/credit; an unsigned payment is final.`
|
|
86240
86999
|
}
|
|
86241
87000
|
}[reason];
|
|
86242
87001
|
}
|
|
@@ -86941,6 +87700,7 @@ async function commitBalancePayment(args) {
|
|
|
86941
87700
|
[args.jobId]
|
|
86942
87701
|
);
|
|
86943
87702
|
const ask = asks.rows[0]?.data;
|
|
87703
|
+
if (ask?.seq === request_seq && askExpired(ask.content.expires_at_ms, Date.now())) conflict("ask_expired");
|
|
86944
87704
|
if (!ask || ask.seq !== request_seq || !ask.content.credit || ask.content.credit.amount_micro !== amount_micro || ask.content.credit.currency !== currency || Number(job.pending_payment_fiat_micro) !== amount_micro || job.pending_payment_fiat_currency !== currency || Number(job.pending_payment_msats) <= 0 || job.asked_topup_micro === null || Number(job.asked_topup_micro) < amount_micro) {
|
|
86945
87705
|
conflict("credit_payment_ask_mismatch");
|
|
86946
87706
|
}
|
|
@@ -86986,7 +87746,9 @@ async function commitBalancePayment(args) {
|
|
|
86986
87746
|
pending_payment_fiat_micro=NULL, pending_payment_fiat_currency=NULL,
|
|
86987
87747
|
pending_mpp_challenge_ids=NULL, pending_x402_nonce=NULL, pending_x402_amount_usdc_micro=NULL,
|
|
86988
87748
|
credit_id=$3, draw_id=$4, payment_rail=$5, payment_mint=$6, payment_tx_hash=$7,
|
|
86989
|
-
native_amount=$8, native_asset=$9, last_activity_at=$10
|
|
87749
|
+
native_amount=$8, native_asset=$9, last_activity_at=$10,
|
|
87750
|
+
-- The paid ask buys the next piece; a job with no piece list settles as one piece.
|
|
87751
|
+
pieces = CASE WHEN pieces IS NULL THEN NULL ELSE pieces || $11::jsonb END WHERE id=$1`,
|
|
86990
87752
|
[
|
|
86991
87753
|
args.jobId,
|
|
86992
87754
|
grown.addedRailValue.drawMsats,
|
|
@@ -86997,7 +87759,8 @@ async function commitBalancePayment(args) {
|
|
|
86997
87759
|
drawSettlementRef(args.dvmId, credit_id, draw_id),
|
|
86998
87760
|
basis.drawNative,
|
|
86999
87761
|
nativeAsset,
|
|
87000
|
-
Date.now()
|
|
87762
|
+
Date.now(),
|
|
87763
|
+
JSON.stringify(appendPiece([], amount_micro, seq))
|
|
87001
87764
|
]
|
|
87002
87765
|
);
|
|
87003
87766
|
await tx.query("UPDATE job_messages SET status='verified' WHERE job_id=$1 AND seq=$2", [args.jobId, seq]);
|
|
@@ -90326,6 +91089,21 @@ initSchemaForm();
|
|
|
90326
91089
|
</body>
|
|
90327
91090
|
</html>`;
|
|
90328
91091
|
}
|
|
91092
|
+
async function acceptLatePayment(args) {
|
|
91093
|
+
const job = fromJobRecord(args.record);
|
|
91094
|
+
const body = { type: "payment", content: args.content };
|
|
91095
|
+
const inboundSeq = await args.recorder.recordInboundPending(job, body.type, body.content);
|
|
91096
|
+
const outcome = await args.recorder.processPayment(job, body, inboundSeq, args.extra);
|
|
91097
|
+
if (outcome.error) return { status: outcome.error.status, body: outcome.error.body };
|
|
91098
|
+
return {
|
|
91099
|
+
status: 201,
|
|
91100
|
+
body: {
|
|
91101
|
+
seq: inboundSeq ?? job.seq,
|
|
91102
|
+
...outcome.unappliedCredit && { credit: outcome.unappliedCredit },
|
|
91103
|
+
...outcome.drawFundingReceipt && { draw_funding_receipt: outcome.drawFundingReceipt }
|
|
91104
|
+
}
|
|
91105
|
+
};
|
|
91106
|
+
}
|
|
90329
91107
|
function requestFingerprint(req, opts) {
|
|
90330
91108
|
const canonical = canonicalize({
|
|
90331
91109
|
capability: req.capability,
|
|
@@ -90456,7 +91234,7 @@ async function createDVMServer(descriptor, opts) {
|
|
|
90456
91234
|
}
|
|
90457
91235
|
}
|
|
90458
91236
|
if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
|
|
90459
|
-
const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-
|
|
91237
|
+
const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-CIG2MEDN-ZXMO6NWG.js");
|
|
90460
91238
|
const reporter = new RevenueReporter2(
|
|
90461
91239
|
opts.db,
|
|
90462
91240
|
platformUrl,
|
|
@@ -90466,7 +91244,7 @@ async function createDVMServer(descriptor, opts) {
|
|
|
90466
91244
|
revenueReporter = reporter;
|
|
90467
91245
|
await reporter.init();
|
|
90468
91246
|
reporter.startRetryLoop();
|
|
90469
|
-
const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-
|
|
91247
|
+
const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-Y6OW3FYD-K6MRWQXK.js");
|
|
90470
91248
|
payoutReporter = new PayoutReporter2({
|
|
90471
91249
|
dvmId,
|
|
90472
91250
|
db: opts.db,
|
|
@@ -90961,9 +91739,15 @@ var DVMServer = class {
|
|
|
90961
91739
|
const store = this.jobManager.store;
|
|
90962
91740
|
if (!(store instanceof PostgresJobStore)) return;
|
|
90963
91741
|
for (const jobId of status.activeJobIds) {
|
|
90964
|
-
if (await control.dispatchDeadlineReached(jobId)
|
|
90965
|
-
|
|
91742
|
+
if (!await control.dispatchDeadlineReached(jobId)) continue;
|
|
91743
|
+
let cancelled;
|
|
91744
|
+
try {
|
|
91745
|
+
cancelled = await store.cancelJobForHosting(jobId, "Hosting drain deadline reached");
|
|
91746
|
+
} catch (error62) {
|
|
91747
|
+
if (paymentIntentOpen(error62)) continue;
|
|
91748
|
+
throw error62;
|
|
90966
91749
|
}
|
|
91750
|
+
if (cancelled) await this.jobManager.finalizeStoredTerminal(jobId);
|
|
90967
91751
|
}
|
|
90968
91752
|
}
|
|
90969
91753
|
async handleHostingCommand(c, statusOnly) {
|
|
@@ -93334,19 +94118,46 @@ var DVMServer = class {
|
|
|
93334
94118
|
if (messages && fields.content_available !== false) fields.messages = messages;
|
|
93335
94119
|
return buildSubmitResponse(c, snapshot, jobToken, fields);
|
|
93336
94120
|
}
|
|
94121
|
+
/**
|
|
94122
|
+
* What a deferred-x402 job may show before its payment settles. The intent
|
|
94123
|
+
* is the durable, cross-machine record of settlement, so every read path
|
|
94124
|
+
* agrees without a flag on the job row. Output is held from admission
|
|
94125
|
+
* because a caller could otherwise read it and then cancel the nonce or drain
|
|
94126
|
+
* the wallet. A job that ended without completing keeps only its
|
|
94127
|
+
* cancellation message, so the caller still learns why.
|
|
94128
|
+
*/
|
|
94129
|
+
async outputGate(job) {
|
|
94130
|
+
const intentId = deferredX402IntentId(job.creditId);
|
|
94131
|
+
if (!intentId) return void 0;
|
|
94132
|
+
const intent = await this.x402ExactSettlement?.get(this.opts.dvmId ?? "", intentId);
|
|
94133
|
+
if (intent?.status === "complete") return void 0;
|
|
94134
|
+
if (job.status === "failed" || job.status === "cancelled") return { terminalOnly: true };
|
|
94135
|
+
return {
|
|
94136
|
+
reason: intent?.status === "released" || intent?.status === "rejected" ? "payment_unsettled" : "payment_pending"
|
|
94137
|
+
};
|
|
94138
|
+
}
|
|
93337
94139
|
async contentFields(job) {
|
|
93338
94140
|
const store = this.jobManager.store;
|
|
93339
94141
|
const responseStatus = job.status;
|
|
93340
94142
|
const evidence = isTerminal(job.status) && this.jobManager.receiptsEnabled && !job.receipt ? { receipt_pending: true } : {};
|
|
94143
|
+
const gate = await this.outputGate(job);
|
|
94144
|
+
const withheld = gate && "reason" in gate ? { content_available: false, content_withheld: gate.reason } : {};
|
|
93341
94145
|
if (isContentHoldStore(store)) {
|
|
93342
94146
|
const snapshot = await store.getContentSnapshot(job.id);
|
|
93343
|
-
if (snapshot) return { ...evidence, ...contentMetadata({ ...snapshot.job, status: responseStatus }, this.descriptor.jobRetentionDays, snapshot.history.holds) };
|
|
94147
|
+
if (snapshot) return { ...evidence, ...contentMetadata({ ...snapshot.job, status: responseStatus }, this.descriptor.jobRetentionDays, snapshot.history.holds), ...withheld };
|
|
93344
94148
|
}
|
|
93345
|
-
return isContentHoldStore(store) ? { ...evidence, ...contentMetadata(job, this.descriptor.jobRetentionDays) } : evidence;
|
|
94149
|
+
return isContentHoldStore(store) ? { ...evidence, ...contentMetadata(job, this.descriptor.jobRetentionDays), ...withheld } : { ...evidence, ...withheld };
|
|
94150
|
+
}
|
|
94151
|
+
/** The messages a caller may read now: none while withheld, only the cancellation once a job ended unpaid. */
|
|
94152
|
+
async releasableMessages(job, messages) {
|
|
94153
|
+
const gate = await this.outputGate(job);
|
|
94154
|
+
if (!gate) return messages;
|
|
94155
|
+
return "terminalOnly" in gate ? messages.filter((m) => m.type === "cancel") : [];
|
|
93346
94156
|
}
|
|
93347
94157
|
async messageFields(job, messages) {
|
|
93348
94158
|
const fields = await this.contentFields(job);
|
|
93349
|
-
|
|
94159
|
+
const releasable = await this.releasableMessages(job, messages);
|
|
94160
|
+
return { messages: fields.content_available === false ? [] : releasable, ...fields };
|
|
93350
94161
|
}
|
|
93351
94162
|
async handleGetJob(c) {
|
|
93352
94163
|
if (!jobCredential.presents(c.req)) return c.json(jobCredential.body(), 401);
|
|
@@ -93356,8 +94167,10 @@ var DVMServer = class {
|
|
|
93356
94167
|
if (!isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
|
|
93357
94168
|
const snapshot = await this.readJobSnapshot(job);
|
|
93358
94169
|
if ("listeners" in job && !isTerminal(snapshot.status) && !isTerminal(job.status)) snapshot.status = job.status;
|
|
93359
|
-
const
|
|
93360
|
-
|
|
94170
|
+
const content = await this.contentFields(snapshot);
|
|
94171
|
+
const status = withheldStatus(snapshot.status, content);
|
|
94172
|
+
const res = { job_id: snapshot.id, status };
|
|
94173
|
+
Object.assign(res, terminalResponseFields({ ...snapshot, status }), content);
|
|
93361
94174
|
Object.assign(res, await this.drawFundingFields(snapshot));
|
|
93362
94175
|
removeUnavailableContent(res);
|
|
93363
94176
|
return this.withDeferredSettlement(c.json(res), snapshot.creditId);
|
|
@@ -93393,6 +94206,9 @@ var DVMServer = class {
|
|
|
93393
94206
|
}
|
|
93394
94207
|
if (accept.includes("text/event-stream")) {
|
|
93395
94208
|
if (isStreamableJobStore(store) && !terminal) {
|
|
94209
|
+
if ((await this.contentFields(record2)).content_available === false) {
|
|
94210
|
+
return streamSSE(c, async () => void 0);
|
|
94211
|
+
}
|
|
93396
94212
|
return streamSSE(c, async (stream2) => {
|
|
93397
94213
|
let unsubFn;
|
|
93398
94214
|
await new Promise((resolve) => {
|
|
@@ -93448,9 +94264,10 @@ var DVMServer = class {
|
|
|
93448
94264
|
});
|
|
93449
94265
|
}
|
|
93450
94266
|
const fields = await this.contentFields(record2);
|
|
94267
|
+
const releasable = await this.releasableMessages(record2, filtered);
|
|
93451
94268
|
return streamSSE(c, async (stream2) => {
|
|
93452
94269
|
if (fields.content_available === false) return;
|
|
93453
|
-
for (const msg of
|
|
94270
|
+
for (const msg of releasable) {
|
|
93454
94271
|
await stream2.writeSSE({ data: JSON.stringify(msg), event: "message" });
|
|
93455
94272
|
}
|
|
93456
94273
|
});
|
|
@@ -93460,9 +94277,10 @@ var DVMServer = class {
|
|
|
93460
94277
|
if (!isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
|
|
93461
94278
|
if (accept.includes("text/event-stream")) {
|
|
93462
94279
|
const fields = await this.contentFields(job);
|
|
94280
|
+
const gated = await this.releasableMessages(job, visibleJobMessages(job));
|
|
93463
94281
|
return streamSSE(c, async (stream2) => {
|
|
93464
94282
|
if (fields.content_available === false) return;
|
|
93465
|
-
const existing =
|
|
94283
|
+
const existing = gated.filter((m) => m.seq > after);
|
|
93466
94284
|
let yielded = false;
|
|
93467
94285
|
for (const msg of existing) {
|
|
93468
94286
|
await stream2.writeSSE({ data: JSON.stringify(msg), event: "message" });
|
|
@@ -93492,6 +94310,57 @@ var DVMServer = class {
|
|
|
93492
94310
|
}
|
|
93493
94311
|
return c.json(await this.messageFields(job, visibleJobMessages(job).filter((m) => m.seq > after)));
|
|
93494
94312
|
}
|
|
94313
|
+
/**
|
|
94314
|
+
* A cancel or other ending write held past the request's wait by a payment
|
|
94315
|
+
* still being verified. Nothing changed; the same request succeeds once the
|
|
94316
|
+
* payment is recorded.
|
|
94317
|
+
*/
|
|
94318
|
+
paymentInProgressResponse(c) {
|
|
94319
|
+
c.header("Retry-After", "2");
|
|
94320
|
+
return c.json(
|
|
94321
|
+
{
|
|
94322
|
+
error: "payment_in_progress",
|
|
94323
|
+
message: "A payment for this job is being verified, and the job cannot end until its outcome is recorded.",
|
|
94324
|
+
hint: "Retry this request in a few seconds. The payment will either pay the job's request or be held as balance on your credit.",
|
|
94325
|
+
retryable: true
|
|
94326
|
+
},
|
|
94327
|
+
409
|
|
94328
|
+
);
|
|
94329
|
+
}
|
|
94330
|
+
noOpenAskResponse(c) {
|
|
94331
|
+
return c.json(
|
|
94332
|
+
{
|
|
94333
|
+
error: "no_open_ask",
|
|
94334
|
+
message: "The job has no open payment request or prompt to decline.",
|
|
94335
|
+
hint: "Decline answers an open ask. To stop a running job, cancel it with DELETE /v1/job/:id."
|
|
94336
|
+
},
|
|
94337
|
+
409
|
|
94338
|
+
);
|
|
94339
|
+
}
|
|
94340
|
+
/**
|
|
94341
|
+
* End a job its handler is not running here at the caller's decline. Same shape as the
|
|
94342
|
+
* DELETE route's store-only cancel; the store refuses unless an ask or prompt is open.
|
|
94343
|
+
*/
|
|
94344
|
+
async declineStoredJob(c, id, reason) {
|
|
94345
|
+
const jm = this.jobManager;
|
|
94346
|
+
const store = jm.store;
|
|
94347
|
+
if (!isStreamableJobStore(store) || !store.declineJob) {
|
|
94348
|
+
return c.json({ error: "decline_unavailable", message: "This job store cannot end a job at a decline." }, 409);
|
|
94349
|
+
}
|
|
94350
|
+
const decline = store.declineJob.bind(store);
|
|
94351
|
+
let outcome;
|
|
94352
|
+
try {
|
|
94353
|
+
outcome = await afterPaymentIntents(() => decline(id, reason), { maxWaitMs: PAYMENT_INTENT_REQUEST_WAIT_MS });
|
|
94354
|
+
} catch (error62) {
|
|
94355
|
+
if (paymentIntentOpen(error62)) return this.paymentInProgressResponse(c);
|
|
94356
|
+
throw error62;
|
|
94357
|
+
}
|
|
94358
|
+
if (outcome === "not_active") return this.jobNotActiveResponse(c);
|
|
94359
|
+
if (outcome === "no_open_ask") return this.noOpenAskResponse(c);
|
|
94360
|
+
await jm.finalizeStoredTerminal(id);
|
|
94361
|
+
const ended = await store.get(id);
|
|
94362
|
+
return c.json({ seq: ended?.seq ?? 0 }, 201);
|
|
94363
|
+
}
|
|
93495
94364
|
jobNotActiveResponse(c) {
|
|
93496
94365
|
return c.json(
|
|
93497
94366
|
{
|
|
@@ -93554,10 +94423,11 @@ var DVMServer = class {
|
|
|
93554
94423
|
throw error62;
|
|
93555
94424
|
}
|
|
93556
94425
|
}
|
|
94426
|
+
const latePayable = wire?.type === "payment" && !!wire.content && typeof wire.content === "object" && hasPaymentProof(wire.content);
|
|
93557
94427
|
if (activeJob) {
|
|
93558
94428
|
if (!isJobOwner(c, activeJob)) return c.json({ error: "Job not found" }, 404);
|
|
93559
94429
|
if (isTerminal(activeJob.status)) {
|
|
93560
|
-
return this.jobNotActiveResponse(c);
|
|
94430
|
+
return latePayable ? this.acceptPaymentOnEndedJob(c, id) : this.jobNotActiveResponse(c);
|
|
93561
94431
|
}
|
|
93562
94432
|
const parsed2 = await this.requireJsonBody(c);
|
|
93563
94433
|
if ("error" in parsed2) return parsed2.error;
|
|
@@ -93570,6 +94440,18 @@ var DVMServer = class {
|
|
|
93570
94440
|
if (contentErr2) return c.json({ error: "invalid_message", message: contentErr2 }, 400);
|
|
93571
94441
|
const railRefusal2 = this.unsignedJobRailRefusal(activeJob, body2);
|
|
93572
94442
|
if (railRefusal2) return railRefusal2;
|
|
94443
|
+
if (body2.type === "decline") {
|
|
94444
|
+
try {
|
|
94445
|
+
await waitForPaymentIntents(jm.store, id, { maxWaitMs: PAYMENT_INTENT_REQUEST_WAIT_MS });
|
|
94446
|
+
} catch (error62) {
|
|
94447
|
+
if (paymentIntentOpen(error62)) return this.paymentInProgressResponse(c);
|
|
94448
|
+
throw error62;
|
|
94449
|
+
}
|
|
94450
|
+
if (isTerminal(activeJob.status)) return this.jobNotActiveResponse(c);
|
|
94451
|
+
if (!activeJob.pendingPayment && activeJob.pendingPrompts.size === 0 && !hasOpenAsk(activeJob)) {
|
|
94452
|
+
return this.noOpenAskResponse(c);
|
|
94453
|
+
}
|
|
94454
|
+
}
|
|
93573
94455
|
const inboundSeq2 = await jm.recordInboundPending(activeJob, body2.type, body2.content);
|
|
93574
94456
|
const lockPubkeys2 = await this.resolveLockPubkeysForReceive();
|
|
93575
94457
|
let unappliedCredit2;
|
|
@@ -93583,6 +94465,13 @@ var DVMServer = class {
|
|
|
93583
94465
|
return c.json(outcome.error.body, outcome.error.status);
|
|
93584
94466
|
unappliedCredit2 = outcome.unappliedCredit;
|
|
93585
94467
|
drawFundingReceipt2 = outcome.drawFundingReceipt;
|
|
94468
|
+
if (outcome.landedAsBalance || isTerminal(activeJob.status)) {
|
|
94469
|
+
return c.json({
|
|
94470
|
+
seq: activeJob.messages[activeJob.messages.length - 1].seq,
|
|
94471
|
+
...unappliedCredit2 && { credit: unappliedCredit2 },
|
|
94472
|
+
...drawFundingReceipt2 && { draw_funding_receipt: drawFundingReceipt2 }
|
|
94473
|
+
}, 201);
|
|
94474
|
+
}
|
|
93586
94475
|
} else {
|
|
93587
94476
|
await jm.markInboundVerified(activeJob.id, inboundSeq2);
|
|
93588
94477
|
}
|
|
@@ -93605,19 +94494,29 @@ var DVMServer = class {
|
|
|
93605
94494
|
if (!record2) return c.json({ error: "Job not found" }, 404);
|
|
93606
94495
|
if (!isJobOwner(c, record2)) return c.json({ error: "Job not found" }, 404);
|
|
93607
94496
|
if (isTerminal(record2.status)) {
|
|
93608
|
-
return this.jobNotActiveResponse(c);
|
|
94497
|
+
return latePayable ? this.acceptPaymentOnEndedJob(c, id, record2) : this.jobNotActiveResponse(c);
|
|
93609
94498
|
}
|
|
93610
94499
|
const parsed = await this.requireJsonBody(c);
|
|
93611
94500
|
if ("error" in parsed) return parsed.error;
|
|
93612
94501
|
const body = parsed.body;
|
|
94502
|
+
if (body.type === "decline") {
|
|
94503
|
+
const reason = typeof body.content?.reason === "string" ? body.content.reason : "Job declined";
|
|
94504
|
+
return this.declineStoredJob(c, id, reason);
|
|
94505
|
+
}
|
|
93613
94506
|
if (!jm.hasCapability(record2.capability)) {
|
|
93614
94507
|
const summary = record2.capability ? `Capability "${record2.capability}" is no longer registered on this DVM` : "Job predates capability dispatch and cannot be resumed";
|
|
93615
|
-
|
|
93616
|
-
|
|
93617
|
-
|
|
93618
|
-
|
|
93619
|
-
|
|
93620
|
-
|
|
94508
|
+
try {
|
|
94509
|
+
await afterPaymentIntents(() => jm.store.save({
|
|
94510
|
+
...record2,
|
|
94511
|
+
status: "failed",
|
|
94512
|
+
summary,
|
|
94513
|
+
lastActivityAt: Date.now()
|
|
94514
|
+
}), { maxWaitMs: PAYMENT_INTENT_REQUEST_WAIT_MS });
|
|
94515
|
+
} catch (error62) {
|
|
94516
|
+
const open2 = paymentIntentOpen(error62);
|
|
94517
|
+
if (open2) return this.paymentInProgressResponse(c);
|
|
94518
|
+
throw error62;
|
|
94519
|
+
}
|
|
93621
94520
|
const infoUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
|
|
93622
94521
|
return c.json(
|
|
93623
94522
|
{
|
|
@@ -93677,6 +94576,14 @@ var DVMServer = class {
|
|
|
93677
94576
|
}
|
|
93678
94577
|
unappliedCredit = outcome.unappliedCredit;
|
|
93679
94578
|
drawFundingReceipt = outcome.drawFundingReceipt;
|
|
94579
|
+
if (outcome.landedAsBalance) {
|
|
94580
|
+
this.teardownReactivationScaffold(jm, job);
|
|
94581
|
+
return c.json({
|
|
94582
|
+
seq: job.messages[job.messages.length - 1].seq,
|
|
94583
|
+
...unappliedCredit && { credit: unappliedCredit },
|
|
94584
|
+
...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
|
|
94585
|
+
}, 201);
|
|
94586
|
+
}
|
|
93680
94587
|
} else {
|
|
93681
94588
|
await jm.markInboundVerified(job.id, inboundSeq);
|
|
93682
94589
|
}
|
|
@@ -93713,6 +94620,26 @@ var DVMServer = class {
|
|
|
93713
94620
|
const lastMsg = job.messages[job.messages.length - 1];
|
|
93714
94621
|
return c.json({ seq: lastMsg.seq, ...creditBlock }, 201);
|
|
93715
94622
|
}
|
|
94623
|
+
/** A paid message for an ended job: recorded, verified and landed as balance. */
|
|
94624
|
+
async acceptPaymentOnEndedJob(c, id, known) {
|
|
94625
|
+
const parsed = await this.requireJsonBody(c);
|
|
94626
|
+
if ("error" in parsed) return parsed.error;
|
|
94627
|
+
const body = parsed.body;
|
|
94628
|
+
const contentErr = validateMessageContent(body.type, body.content, this.opts.devMode === true);
|
|
94629
|
+
if (contentErr) return c.json({ error: "invalid_message", message: contentErr }, 400);
|
|
94630
|
+
const record2 = known ?? await this.jobManager.store.get(id);
|
|
94631
|
+
if (!record2) return c.json({ error: "Job not found" }, 404);
|
|
94632
|
+
if (record2.redactedAt !== void 0) return this.jobNotActiveResponse(c);
|
|
94633
|
+
const railRefusal = this.unsignedJobRailRefusal(record2, body);
|
|
94634
|
+
if (railRefusal) return railRefusal;
|
|
94635
|
+
const result = await acceptLatePayment({
|
|
94636
|
+
recorder: this.jobManager,
|
|
94637
|
+
record: record2,
|
|
94638
|
+
content: body.content,
|
|
94639
|
+
extra: { lockPubkeys: await this.resolveLockPubkeysForReceive(), mintHealthTracker: this.mintHealthTracker }
|
|
94640
|
+
});
|
|
94641
|
+
return c.json(result.body, result.status);
|
|
94642
|
+
}
|
|
93716
94643
|
async persistMessageSnapshot(jm, job, type) {
|
|
93717
94644
|
if (type === "payment") {
|
|
93718
94645
|
await retryJobSnapshot(() => jm.persistJob(job));
|
|
@@ -93804,19 +94731,35 @@ var DVMServer = class {
|
|
|
93804
94731
|
}
|
|
93805
94732
|
const store = jm.store;
|
|
93806
94733
|
if (isStreamableJobStore(store)) {
|
|
93807
|
-
|
|
94734
|
+
let cancelled;
|
|
94735
|
+
try {
|
|
94736
|
+
cancelled = await afterPaymentIntents(
|
|
94737
|
+
() => store.cancelJob(id, reason ?? "Job cancelled"),
|
|
94738
|
+
{ maxWaitMs: PAYMENT_INTENT_REQUEST_WAIT_MS }
|
|
94739
|
+
);
|
|
94740
|
+
} catch (error62) {
|
|
94741
|
+
if (paymentIntentOpen(error62)) return this.paymentInProgressResponse(c);
|
|
94742
|
+
throw error62;
|
|
94743
|
+
}
|
|
93808
94744
|
if (!cancelled) return this.jobNotActiveResponse(c);
|
|
93809
94745
|
await jm.finalizeStoredTerminal(id);
|
|
93810
94746
|
return c.json({ status: "cancelled" });
|
|
93811
94747
|
}
|
|
93812
94748
|
record2.endedBy = "caller";
|
|
93813
94749
|
record2.status = "cancelled";
|
|
94750
|
+
record2.pieceEnding = { kind: "stop" };
|
|
93814
94751
|
record2.lastActivityAt = Date.now();
|
|
93815
94752
|
await jm.store.save(record2);
|
|
93816
94753
|
await jm.finalizeStoredTerminal(id);
|
|
93817
94754
|
return c.json({ status: "cancelled" });
|
|
93818
94755
|
}
|
|
93819
94756
|
if (!isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
|
|
94757
|
+
try {
|
|
94758
|
+
await waitForPaymentIntents(jm.store, id, { maxWaitMs: PAYMENT_INTENT_REQUEST_WAIT_MS });
|
|
94759
|
+
} catch (error62) {
|
|
94760
|
+
if (paymentIntentOpen(error62)) return this.paymentInProgressResponse(c);
|
|
94761
|
+
throw error62;
|
|
94762
|
+
}
|
|
93820
94763
|
if (isTerminal(job.status)) {
|
|
93821
94764
|
return this.jobNotActiveResponse(c);
|
|
93822
94765
|
}
|
|
@@ -93843,13 +94786,14 @@ function timingSafeEqualHex(a, b2) {
|
|
|
93843
94786
|
return diff === 0;
|
|
93844
94787
|
}
|
|
93845
94788
|
function buildSubmitResponse(c, job, jobToken, contentFields) {
|
|
94789
|
+
const status = withheldStatus(job.status, contentFields);
|
|
93846
94790
|
const res = { job_id: job.id };
|
|
93847
94791
|
if (jobToken) res.job_token = jobToken;
|
|
93848
|
-
if (
|
|
93849
|
-
else if (
|
|
93850
|
-
Object.assign(res, terminalResponseFields(job), contentFields);
|
|
94792
|
+
if (status === "awaiting-input") res.status = "awaiting-input";
|
|
94793
|
+
else if (status === "completed") res.status = "completed";
|
|
94794
|
+
Object.assign(res, terminalResponseFields({ ...job, status }), contentFields);
|
|
93851
94795
|
removeUnavailableContent(res);
|
|
93852
|
-
return c.json(res,
|
|
94796
|
+
return c.json(res, status === "completed" ? 200 : 202, jobIdentityHeaders(job.id));
|
|
93853
94797
|
}
|
|
93854
94798
|
function requestRecoveryStore(store) {
|
|
93855
94799
|
return store.findJobByRequestId && store.claimRequestId && store.resumeRequestId && store.releaseRequestIdClaim ? store : void 0;
|
|
@@ -93906,7 +94850,8 @@ function requestNotAccepted(c, requestId) {
|
|
|
93906
94850
|
);
|
|
93907
94851
|
}
|
|
93908
94852
|
function buildRequestResultResponse(c, requestId, job, contentFields) {
|
|
93909
|
-
const
|
|
94853
|
+
const shown = withheldStatus(job.status, contentFields);
|
|
94854
|
+
const status = shown === "working" ? "processing" : shown;
|
|
93910
94855
|
const res = {
|
|
93911
94856
|
request_id: requestId,
|
|
93912
94857
|
job_id: job.id,
|
|
@@ -93914,9 +94859,9 @@ function buildRequestResultResponse(c, requestId, job, contentFields) {
|
|
|
93914
94859
|
};
|
|
93915
94860
|
if (job.requesterToken) res.job_token = job.requesterToken;
|
|
93916
94861
|
if (job.paymentTransactionHash) res.transaction_hash = job.paymentTransactionHash;
|
|
93917
|
-
Object.assign(res, terminalResponseFields(job), contentFields);
|
|
94862
|
+
Object.assign(res, terminalResponseFields({ ...job, status: shown }), contentFields);
|
|
93918
94863
|
removeUnavailableContent(res);
|
|
93919
|
-
return c.json(res, isTerminal(
|
|
94864
|
+
return c.json(res, isTerminal(shown) ? 200 : 202, jobIdentityHeaders(job.id));
|
|
93920
94865
|
}
|
|
93921
94866
|
function jobIdentityHeaders(jobId) {
|
|
93922
94867
|
return isJobIdentityValue(jobId) ? { [JOB_IDENTITY_HEADER]: jobId } : {};
|
|
@@ -93948,6 +94893,12 @@ async function awaitTerminalWork(work) {
|
|
|
93948
94893
|
clearTimeout(timer);
|
|
93949
94894
|
}
|
|
93950
94895
|
}
|
|
94896
|
+
function withheldStatus(status, fields) {
|
|
94897
|
+
if (status !== "completed") return status;
|
|
94898
|
+
if (fields.content_withheld === "payment_pending") return "processing";
|
|
94899
|
+
if (fields.content_withheld === "payment_unsettled") return "failed";
|
|
94900
|
+
return status;
|
|
94901
|
+
}
|
|
93951
94902
|
function removeUnavailableContent(fields) {
|
|
93952
94903
|
if (fields.content_available === false) {
|
|
93953
94904
|
delete fields.summary;
|
|
@@ -94635,11 +95586,11 @@ export {
|
|
|
94635
95586
|
providerMessage,
|
|
94636
95587
|
isTerminal,
|
|
94637
95588
|
isYieldMessage,
|
|
95589
|
+
isStaleJobReapable,
|
|
94638
95590
|
humanizeZodError,
|
|
94639
95591
|
SIGNED_ENVELOPE_TYPES,
|
|
94640
95592
|
SIGNED_ENVELOPE_FIELDS,
|
|
94641
95593
|
createDefaultReplayStore,
|
|
94642
|
-
isStaleJobReapable,
|
|
94643
95594
|
createInstrumentedFetch,
|
|
94644
95595
|
wrapMppx,
|
|
94645
95596
|
_testing,
|