@dvmkit/dvm-cli 0.9.1 → 0.10.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.
@@ -4924,7 +4924,7 @@ function hexToBytes3(hex3) {
4924
4924
  return out;
4925
4925
  }
4926
4926
 
4927
- // node_modules/@dvmkit/sdk/dist/chunk-5H7P3ORL.js
4927
+ // node_modules/@dvmkit/sdk/dist/chunk-5UC7TOQC.js
4928
4928
  function computeResultHash(summary, artifactContents) {
4929
4929
  const artifactHashes = artifactContents.map(
4930
4930
  (content) => bytesToHex(sha256(canonicaliseForSigning(content)))
@@ -4982,6 +4982,25 @@ function verifyFundingReceipt(receipt) {
4982
4982
  return false;
4983
4983
  }
4984
4984
  }
4985
+ function signDrawFundingReceipt(unsigned2, secretHex) {
4986
+ const bytes = canonicaliseForSigning(unsigned2);
4987
+ const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
4988
+ return { ...unsigned2, signature };
4989
+ }
4990
+ function isDrawFundingReceipt(value) {
4991
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4992
+ const r = value;
4993
+ return r.v === 1 && r.kind === "credit_draw_funding" && typeof r.credit_id === "string" && typeof r.job_id === "string" && typeof r.draw_id === "string" && typeof r.fund_id === "string" && (r.payment_seq === void 0 || typeof r.payment_seq === "number") && typeof r.currency === "string" && typeof r.funded_micro === "number" && typeof r.balance_after_micro === "number" && typeof r.ledger_seq === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
4994
+ }
4995
+ function verifyDrawFundingReceipt(receipt) {
4996
+ try {
4997
+ const { signature, ...unsigned2 } = receipt;
4998
+ const bytes = canonicaliseForSigning(unsigned2);
4999
+ return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
5000
+ } catch {
5001
+ return false;
5002
+ }
5003
+ }
4985
5004
  function isDrainReceipt(value) {
4986
5005
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4987
5006
  const r = value;
@@ -4997,7 +5016,7 @@ function verifyDrainReceipt(receipt) {
4997
5016
  }
4998
5017
  }
4999
5018
 
5000
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
5019
+ // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
5001
5020
  import { homedir } from "os";
5002
5021
  import { join as join3 } from "path";
5003
5022
  import { chmodSync, mkdirSync, statSync } from "fs";
@@ -10240,7 +10259,7 @@ zero
10240
10259
  zone
10241
10260
  zoo`.split("\n");
10242
10261
 
10243
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
10262
+ // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
10244
10263
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
10245
10264
  import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
10246
10265
 
@@ -20214,7 +20233,7 @@ function expand(hash4, prk, info, length = 32) {
20214
20233
  }
20215
20234
  var hkdf = (hash4, ikm, salt, info, length) => expand(hash4, extract(hash4, ikm, salt), info, length);
20216
20235
 
20217
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
20236
+ // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
20218
20237
  import { randomBytes as randomBytes6 } from "crypto";
20219
20238
  import {
20220
20239
  chmodSync as chmodSync4,
@@ -20241,7 +20260,7 @@ function toLockPubkey(raw2) {
20241
20260
  function isX402SettlementReconciliationReason(value) {
20242
20261
  return value === "settlement_not_on_chain" || value === "chain_unreachable" || value === "settlement_unbookmarked" || value === "facilitator_channel_state_unavailable";
20243
20262
  }
20244
- var IMPLICIT_CREDIT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
20263
+ var IMPLICIT_CREDIT_TTL_MS = 90 * 24 * 60 * 60 * 1e3;
20245
20264
  var TEMPO_SESSION_UPDATED_REASON = "Tempo session updated; attach the next voucher to fund this credit.";
20246
20265
  var CONFIG_DIR = process.env.DVM_CONFIG_DIR ?? join3(homedir(), ".dvm");
20247
20266
  var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
@@ -21810,6 +21829,53 @@ function verifyFundingReceiptChain(args) {
21810
21829
  receipt: named
21811
21830
  };
21812
21831
  }
21832
+ function verifyDrawFundingReceiptChain(args) {
21833
+ const named = isDrawFundingReceipt(args.receipt) ? args.receipt : void 0;
21834
+ const check2 = (actual, expected) => expected === void 0 ? "unchecked" : actual === expected ? "ok" : "mismatch";
21835
+ const checks = {
21836
+ credit_id: check2(named?.credit_id, args.expectedCreditId),
21837
+ job_id: check2(named?.job_id, args.expectedJobId),
21838
+ draw_id: check2(named?.draw_id, args.expectedDrawId),
21839
+ fund_id: check2(named?.fund_id, args.expectedFundId),
21840
+ currency: check2(named?.currency, args.expectedCurrency),
21841
+ funded_micro: check2(named?.funded_micro, args.expectedFundedMicro),
21842
+ ledger_seq: check2(named?.ledger_seq, args.expectedLedgerSeq),
21843
+ caller_pubkey: check2(named?.caller_pubkey, args.expectedCallerPubkey),
21844
+ signature: named !== void 0 && verifyDrawFundingReceipt(named),
21845
+ attestation: "absent"
21846
+ };
21847
+ const mismatch = [
21848
+ ["credit_id", "credit_id_mismatch"],
21849
+ ["job_id", "job_id_mismatch"],
21850
+ ["draw_id", "draw_id_mismatch"],
21851
+ ["fund_id", "fund_id_mismatch"],
21852
+ ["currency", "funding_currency_mismatch"],
21853
+ ["funded_micro", "funding_amount_mismatch"],
21854
+ ["ledger_seq", "funding_ledger_seq_mismatch"],
21855
+ ["caller_pubkey", "caller_pubkey_mismatch"]
21856
+ ];
21857
+ for (const [field, reason] of mismatch) {
21858
+ if (checks[field] === "mismatch") return { status: "invalid", checks, reason, receipt: named };
21859
+ }
21860
+ if (!named || !checks.signature) {
21861
+ return { status: "invalid", checks, reason: "signature_invalid", receipt: named };
21862
+ }
21863
+ checks.attestation = checkReceiptAttestation(named, args.builder);
21864
+ if (checks.attestation === "invalid") {
21865
+ return { status: "invalid", checks, reason: "attestation_invalid", receipt: named };
21866
+ }
21867
+ if (checks.attestation === "identity_mismatch") {
21868
+ return { status: "invalid", checks, reason: "dvm_identity_mismatch", receipt: named };
21869
+ }
21870
+ if (checks.attestation === "key_mismatch") {
21871
+ return { status: "invalid", checks, reason: "receipt_key_mismatch", receipt: named };
21872
+ }
21873
+ return {
21874
+ status: checks.attestation === "ok" ? "verified" : "verified_unattested",
21875
+ checks,
21876
+ receipt: named
21877
+ };
21878
+ }
21813
21879
  function weakestReceiptVerdict(statuses) {
21814
21880
  if (statuses.length === 0) return "absent";
21815
21881
  if (statuses.includes("invalid")) return "invalid";
@@ -21872,7 +21938,7 @@ function createMonotonicClock() {
21872
21938
  };
21873
21939
  }
21874
21940
 
21875
- // node_modules/@dvmkit/sdk/dist/chunk-HW2UCOOC.js
21941
+ // node_modules/@dvmkit/sdk/dist/chunk-SXL44PL5.js
21876
21942
  function isZodSchema(value) {
21877
21943
  return typeof value === "object" && value !== null && "_zod" in value && "parse" in value && "safeParse" in value;
21878
21944
  }
@@ -21881,7 +21947,7 @@ var RAIL_REFUNDABLE = {
21881
21947
  x402: false,
21882
21948
  tempo: false
21883
21949
  };
21884
- var DEFAULT_CREDIT_TTL_SECONDS = 30 * 24 * 60 * 60;
21950
+ var DEFAULT_CREDIT_TTL_SECONDS = 90 * 24 * 60 * 60;
21885
21951
  var SIGNED_REQUEST_AUTH_ID = "secp256k1-schnorr-v2";
21886
21952
  var SIGNED_REQUEST_STATEMENT_VERSION = 2;
21887
21953
  function normalizeSignedRequestDomain(domain) {
@@ -26864,6 +26930,7 @@ function recordFundResponse(args) {
26864
26930
  record2.balanceMicro = args.credit.balance_micro;
26865
26931
  record2.remainingMicro = args.credit.remaining_micro;
26866
26932
  record2.ledgerSeq = Math.max(record2.ledgerSeq, args.credit.ledger_seq);
26933
+ pruneDrawFundings(record2, record2.ledgerSeq);
26867
26934
  record2.expiryMs = args.credit.expiry_ms;
26868
26935
  record2.targetMicro = args.targetMicro;
26869
26936
  record2.status = args.credit.status === "unbacked" ? "unbacked" : args.credit.expired ? "expired" : "active";
@@ -26946,15 +27013,42 @@ function applyReceiptCredit(args) {
26946
27013
  where: (c) => c.callerPubkey === args.callerPubkey && c.creditId === args.credit.credit_id
26947
27014
  });
26948
27015
  if (!record2) return {};
27016
+ let admitted = false;
27017
+ for (const evidence of args.drawFundings ?? []) {
27018
+ const verdict = admitDrawFunding(record2, {
27019
+ callerPubkey: args.callerPubkey,
27020
+ identity: args.identity,
27021
+ receipt: evidence.receipt,
27022
+ builder: evidence.builder,
27023
+ now
27024
+ });
27025
+ admitted ||= verdict.recorded;
27026
+ }
27027
+ if (args.credit.ledger_seq < record2.ledgerSeq) {
27028
+ if (admitted) {
27029
+ attachDvmLocation(record2, key, args.identity);
27030
+ record2.updatedAt = now;
27031
+ saveStore(store);
27032
+ }
27033
+ return { credit: record2 };
27034
+ }
26949
27035
  attachDvmLocation(record2, key, args.identity);
26950
27036
  let mismatch;
27037
+ let fundedMicro;
26951
27038
  const sequential = args.credit.ledger_seq === record2.ledgerSeq + 1;
26952
27039
  if (sequential && args.outcome === "completed" && record2.status === "active" && !record2.provisional && !record2.unsequencedBalance) {
26953
- const expected = record2.remainingMicro - args.credit.amount;
27040
+ const eligible = (record2.drawFundings ?? []).filter(
27041
+ (fact) => fact.drawId === args.credit.draw_id && fact.ledgerSeq === args.credit.ledger_seq
27042
+ );
27043
+ if (eligible.length > 0) {
27044
+ fundedMicro = eligible.reduce((sum, fact) => sum + fact.fundedMicro, 0);
27045
+ }
27046
+ const expected = record2.remainingMicro + (fundedMicro ?? 0) - args.credit.amount;
26954
27047
  if (args.credit.balance_after !== expected) {
26955
27048
  mismatch = {
26956
27049
  atMs: now,
26957
27050
  expectedMicro: expected,
27051
+ ...fundedMicro !== void 0 ? { fundedMicro } : {},
26958
27052
  reportedMicro: args.credit.balance_after,
26959
27053
  drawId: args.credit.draw_id,
26960
27054
  ledgerSeq: args.credit.ledger_seq,
@@ -26964,11 +27058,10 @@ function applyReceiptCredit(args) {
26964
27058
  record2.discrepancy = mismatch;
26965
27059
  }
26966
27060
  }
26967
- if (args.credit.ledger_seq >= record2.ledgerSeq) {
26968
- record2.remainingMicro = args.credit.balance_after;
26969
- record2.ledgerSeq = args.credit.ledger_seq;
26970
- delete record2.unsequencedBalance;
26971
- }
27061
+ record2.remainingMicro = args.credit.balance_after;
27062
+ record2.ledgerSeq = args.credit.ledger_seq;
27063
+ pruneDrawFundings(record2, record2.ledgerSeq, args.credit.draw_id);
27064
+ delete record2.unsequencedBalance;
26972
27065
  delete record2.provisional;
26973
27066
  if (args.outcome === "completed") record2.lastPriceMicro = args.credit.amount;
26974
27067
  if (!mismatch && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
@@ -26977,9 +27070,103 @@ function applyReceiptCredit(args) {
26977
27070
  record2.lastReceiptJobId = args.jobId;
26978
27071
  record2.updatedAt = now;
26979
27072
  saveStore(store);
26980
- return { credit: record2, ...mismatch ? { mismatch } : {} };
27073
+ return {
27074
+ credit: record2,
27075
+ ...mismatch ? { mismatch } : {},
27076
+ ...fundedMicro !== void 0 ? { fundedMicro } : {}
27077
+ };
27078
+ });
27079
+ }
27080
+ function recordDrawFunding(args) {
27081
+ const now = args.now ?? Date.now();
27082
+ return withCreditLock(() => {
27083
+ const store = loadStore();
27084
+ const key = normalizeCreditEndpoint(args.endpoint);
27085
+ if (!isDrawFundingReceipt(args.receipt)) {
27086
+ return { recorded: false, reason: "invalid", verifyReason: "signature_invalid" };
27087
+ }
27088
+ const named = args.receipt;
27089
+ const record2 = findDvmLocated(store.credits, {
27090
+ endpoint: key,
27091
+ ...args.identity ? { identity: args.identity } : {},
27092
+ where: (c) => c.callerPubkey === args.callerPubkey && c.creditId === named.credit_id
27093
+ });
27094
+ if (!record2) return { recorded: false, reason: "unknown_credit" };
27095
+ const verdict = admitDrawFunding(record2, {
27096
+ callerPubkey: args.callerPubkey,
27097
+ identity: args.identity,
27098
+ receipt: named,
27099
+ builder: args.builder,
27100
+ now
27101
+ });
27102
+ if (verdict.recorded) {
27103
+ attachDvmLocation(record2, key, args.identity);
27104
+ record2.updatedAt = now;
27105
+ saveStore(store);
27106
+ }
27107
+ return { credit: record2, ...verdict };
26981
27108
  });
26982
27109
  }
27110
+ function admitDrawFunding(record2, args) {
27111
+ const verdict = verifyDrawFundingReceiptChain({
27112
+ receipt: args.receipt,
27113
+ builder: args.builder,
27114
+ expectedCallerPubkey: args.callerPubkey,
27115
+ expectedCreditId: record2.creditId
27116
+ });
27117
+ const named = verdict.receipt;
27118
+ if (!named) return { recorded: false, reason: "invalid", verifyReason: "signature_invalid" };
27119
+ if (verdict.reason === "caller_pubkey_mismatch") return { recorded: false, reason: "caller_mismatch" };
27120
+ if (verdict.reason === "credit_id_mismatch") return { recorded: false, reason: "unknown_credit" };
27121
+ if (verdict.status === "invalid") {
27122
+ const provider = verdict.reason === "dvm_identity_mismatch" || verdict.reason === "receipt_key_mismatch" || verdict.reason === "attestation_invalid";
27123
+ return {
27124
+ recorded: false,
27125
+ reason: provider ? "provider_mismatch" : "invalid",
27126
+ ...verdict.reason ? { verifyReason: verdict.reason } : {}
27127
+ };
27128
+ }
27129
+ if (args.identity && named.dvm_id !== args.identity.dvmId) {
27130
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "dvm_identity_mismatch" };
27131
+ }
27132
+ if (record2.dvmId !== void 0 && named.dvm_id !== record2.dvmId) {
27133
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "dvm_identity_mismatch" };
27134
+ }
27135
+ const attested = dvmLocationIdentity(record2);
27136
+ if (attested) {
27137
+ const anchorPubkey = args.builder?.pubkey?.trim().toLowerCase();
27138
+ if (verdict.status !== "verified" || anchorPubkey !== attested.builderPubkey) {
27139
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "receipt_key_mismatch" };
27140
+ }
27141
+ }
27142
+ if (named.currency !== record2.currency) return { recorded: false, reason: "currency_mismatch" };
27143
+ if (named.ledger_seq <= record2.ledgerSeq) return { recorded: false, reason: "already_reflected" };
27144
+ const held = record2.drawFundings ?? [];
27145
+ if (held.some((fact) => fact.fundId === named.fund_id)) {
27146
+ return { recorded: false, reason: "duplicate" };
27147
+ }
27148
+ held.push({
27149
+ fundId: named.fund_id,
27150
+ jobId: named.job_id,
27151
+ drawId: named.draw_id,
27152
+ fundedMicro: named.funded_micro,
27153
+ ledgerSeq: named.ledger_seq,
27154
+ balanceAfterMicro: named.balance_after_micro,
27155
+ recordedAt: args.now,
27156
+ receipt: named
27157
+ });
27158
+ held.sort((a, b2) => a.ledgerSeq - b2.ledgerSeq || a.recordedAt - b2.recordedAt);
27159
+ record2.drawFundings = held;
27160
+ return { recorded: true };
27161
+ }
27162
+ function pruneDrawFundings(record2, ledgerSeq, drawId) {
27163
+ if (!record2.drawFundings) return;
27164
+ const kept = record2.drawFundings.filter(
27165
+ (fact) => fact.ledgerSeq > ledgerSeq && (drawId === void 0 || fact.drawId !== drawId)
27166
+ );
27167
+ if (kept.length === 0) delete record2.drawFundings;
27168
+ else record2.drawFundings = kept;
27169
+ }
26983
27170
  function applyImplicitReceiptCredit(args) {
26984
27171
  if (!args.credit.credit_id.startsWith("imp:")) return {};
26985
27172
  const now = args.now ?? Date.now();
@@ -27336,6 +27523,7 @@ function adoptCreditId(record2, creditId) {
27336
27523
  delete record2.refillDrainNoticed;
27337
27524
  delete record2.discrepancy;
27338
27525
  delete record2.lastReceiptJobId;
27526
+ delete record2.drawFundings;
27339
27527
  }
27340
27528
  var MAX_SETTLED_DRAIN_EVIDENCE = 8;
27341
27529
  var MAX_LOST_IMPLICIT_CREDITS = 8;
@@ -32208,7 +32396,7 @@ function isUniqueViolation(err) {
32208
32396
  return typeof err === "object" && err !== null && err.code === "23505";
32209
32397
  }
32210
32398
 
32211
- // node_modules/@dvmkit/sdk/dist/chunk-2VGMZ7VF.js
32399
+ // node_modules/@dvmkit/sdk/dist/chunk-A2YESDQM.js
32212
32400
  import { randomUUID as randomUUID3 } from "crypto";
32213
32401
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
32214
32402
  import { isDeepStrictEqual } from "util";
@@ -33526,7 +33714,11 @@ var CreditLedger = class {
33526
33714
  "caller_pubkey TEXT",
33527
33715
  "balance_after_micro BIGINT",
33528
33716
  "ledger_seq BIGINT",
33529
- "receipt JSONB"
33717
+ "receipt JSONB",
33718
+ // Mid-job draw funding bindings; null on opening and `/v1/credit` fundings.
33719
+ "job_id TEXT",
33720
+ "draw_id TEXT",
33721
+ "payment_seq BIGINT"
33530
33722
  ]) {
33531
33723
  await this.pool.query(`ALTER TABLE credit_fundings ADD COLUMN IF NOT EXISTS ${column}`);
33532
33724
  }
@@ -33727,8 +33919,8 @@ var CreditLedger = class {
33727
33919
  );
33728
33920
  }
33729
33921
  /**
33730
- * Funding adds balance and overwrites expiry, reviving an expired credit. It is additive,
33731
- * not idempotent: the caller’s rail marker or funding record must prevent replay. Owner and
33922
+ * Funding adds balance and extends expiry without shortening it, reviving an expired credit.
33923
+ * It is additive, not idempotent: the caller’s rail marker or funding record must prevent replay. Owner and
33732
33924
  * currency must match; rail and reusable-channel bindings cannot be mixed with other
33733
33925
  * instruments. A legacy NULL rail adopts its first typed top-up.
33734
33926
  *
@@ -33797,7 +33989,7 @@ var CreditLedger = class {
33797
33989
  ON CONFLICT (credit_id) DO UPDATE
33798
33990
  SET balance_micro = credits.balance_micro + EXCLUDED.balance_micro,
33799
33991
  last_funding_ledger_seq = credits.last_ledger_seq,
33800
- expiry_ms = EXCLUDED.expiry_ms,
33992
+ expiry_ms = GREATEST(credits.expiry_ms, EXCLUDED.expiry_ms),
33801
33993
  rail = COALESCE(credits.rail, EXCLUDED.rail),
33802
33994
  native_asset = COALESCE(EXCLUDED.native_asset, credits.native_asset),
33803
33995
  mint = COALESCE(EXCLUDED.mint, credits.mint),
@@ -34648,11 +34840,21 @@ var CreditLedger = class {
34648
34840
  });
34649
34841
  const nowMs = args.nowMs ?? Date.now();
34650
34842
  const { rows: rows2 } = await q2.query(
34651
- `INSERT INTO credit_fundings (credit_id, fund_id, amount_micro, rail, created_at)
34652
- VALUES ($1, $2, $3, $4, $5)
34843
+ `INSERT INTO credit_fundings
34844
+ (credit_id, fund_id, amount_micro, rail, created_at, job_id, draw_id, payment_seq)
34845
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
34653
34846
  ON CONFLICT (credit_id, fund_id) DO NOTHING
34654
34847
  RETURNING *`,
34655
- [args.creditId, args.fundId, args.amountMicro, args.rail ?? null, nowMs]
34848
+ [
34849
+ args.creditId,
34850
+ args.fundId,
34851
+ args.amountMicro,
34852
+ args.rail ?? null,
34853
+ nowMs,
34854
+ args.jobId ?? null,
34855
+ args.drawId ?? null,
34856
+ args.paymentSeq ?? null
34857
+ ]
34656
34858
  );
34657
34859
  if (rows2.length === 0) {
34658
34860
  throw new CreditLedgerError(
@@ -34675,6 +34877,19 @@ var CreditLedger = class {
34675
34877
  );
34676
34878
  return rows2.length > 0 ? fundingRecordFromRow(rows2[0]) : void 0;
34677
34879
  }
34880
+ /**
34881
+ * Every funding accepted against one job's draw, oldest first. The order is
34882
+ * stable across reads so a job read lists the same evidence each time.
34883
+ */
34884
+ async listDrawFundings(args) {
34885
+ const { rows: rows2 } = await this.pool.query(
34886
+ `SELECT * FROM credit_fundings
34887
+ WHERE credit_id = $1 AND draw_id = $2
34888
+ ORDER BY created_at ASC, fund_id ASC`,
34889
+ [args.creditId, args.drawId]
34890
+ );
34891
+ return rows2.map(fundingRecordFromRow);
34892
+ }
34678
34893
  /** Fix the funding-time receipt tuple inside the rail's open transaction. */
34679
34894
  async completeFunding(args) {
34680
34895
  const q2 = args.tx ?? this.pool;
@@ -34874,7 +35089,10 @@ var CreditLedger = class {
34874
35089
  [args.creditId, args.fundId, settledAt]
34875
35090
  );
34876
35091
  if (args.depositOutbox) {
34877
- await args.depositOutbox.enqueue(client, args.depositOutbox.payload);
35092
+ await args.depositOutbox.enqueue(client, {
35093
+ ...args.depositOutbox.payload,
35094
+ expiryMs: credit.expiryMs
35095
+ });
34878
35096
  }
34879
35097
  await client.query("COMMIT");
34880
35098
  return {
@@ -35045,7 +35263,10 @@ var CreditLedger = class {
35045
35263
  ]
35046
35264
  );
35047
35265
  if (args.depositOutbox) {
35048
- await args.depositOutbox.enqueue(client, args.depositOutbox.payload);
35266
+ await args.depositOutbox.enqueue(client, {
35267
+ ...args.depositOutbox.payload,
35268
+ expiryMs: credit.expiryMs
35269
+ });
35049
35270
  }
35050
35271
  await client.query("COMMIT");
35051
35272
  return {
@@ -36511,7 +36732,10 @@ function fundingRecordFromRow(row) {
36511
36732
  callerPubkey: row.caller_pubkey,
36512
36733
  balanceAfterMicro: row.balance_after_micro === null ? null : toSafeInt(row.balance_after_micro),
36513
36734
  ledgerSeq: row.ledger_seq === null ? null : toSafeInt(row.ledger_seq),
36514
- receipt: row.receipt
36735
+ receipt: row.receipt,
36736
+ jobId: row.job_id ?? null,
36737
+ drawId: row.draw_id ?? null,
36738
+ paymentSeq: row.payment_seq === null || row.payment_seq === void 0 ? null : toSafeInt(row.payment_seq)
36515
36739
  };
36516
36740
  }
36517
36741
  function invoiceRecordFromRow(row) {
@@ -36568,7 +36792,7 @@ function expiryReleaseReport(dvmId, row) {
36568
36792
  };
36569
36793
  }
36570
36794
 
36571
- // node_modules/@dvmkit/sdk/dist/chunk-POYUX2NN.js
36795
+ // node_modules/@dvmkit/sdk/dist/chunk-TKJBUFYY.js
36572
36796
  import { randomUUID as randomUUID4 } from "crypto";
36573
36797
  var MemoryCreditLedger = class _MemoryCreditLedger {
36574
36798
  /**
@@ -36739,7 +36963,10 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
36739
36963
  callerPubkey: null,
36740
36964
  balanceAfterMicro: null,
36741
36965
  ledgerSeq: null,
36742
- receipt: null
36966
+ receipt: null,
36967
+ jobId: args.jobId ?? null,
36968
+ drawId: args.drawId ?? null,
36969
+ paymentSeq: args.paymentSeq ?? null
36743
36970
  };
36744
36971
  this.fundings.set(key, record2);
36745
36972
  return record2;
@@ -36748,6 +36975,11 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
36748
36975
  getFunding(args) {
36749
36976
  return run(() => this.fundings.get(fundingKey(args.creditId, args.fundId)));
36750
36977
  }
36978
+ listDrawFundings(args) {
36979
+ return run(
36980
+ () => [...this.fundings.values()].filter((funding) => funding.creditId === args.creditId && funding.drawId === args.drawId).sort((a, b2) => a.createdAt - b2.createdAt || a.fundId.localeCompare(b2.fundId))
36981
+ );
36982
+ }
36751
36983
  completeFunding(args) {
36752
36984
  return run(() => {
36753
36985
  const key = fundingKey(args.creditId, args.fundId);
@@ -37067,7 +37299,7 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
37067
37299
  }
37068
37300
  existing.lastFundingLedgerSeq = existing.lastLedgerSeq;
37069
37301
  existing.balanceMicro += args.amountMicro;
37070
- existing.expiryMs = args.expiryMs;
37302
+ existing.expiryMs = Math.max(existing.expiryMs, args.expiryMs);
37071
37303
  applyBasis(existing, b2);
37072
37304
  recordLot(existing, args.amountMicro, b2, nowMs);
37073
37305
  return this.snapshot(existing, nowMs);
@@ -39754,7 +39986,7 @@ function isTerminalStatus(status) {
39754
39986
  return status === "completed" || status === "failed" || status === "cancelled";
39755
39987
  }
39756
39988
 
39757
- // node_modules/@dvmkit/sdk/dist/chunk-WFCVS6QB.js
39989
+ // node_modules/@dvmkit/sdk/dist/chunk-HULU2UVM.js
39758
39990
  function humanizeZodError(err, opts) {
39759
39991
  return humanizeZodIssues(err.issues, opts);
39760
39992
  }
@@ -41785,7 +42017,7 @@ function isTempoCloseTransaction(reference) {
41785
42017
  return typeof reference === "string" && /^0x[0-9a-fA-F]{64}$/.test(reference);
41786
42018
  }
41787
42019
 
41788
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
42020
+ // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
41789
42021
  import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
41790
42022
  import { createHash as createHash23 } from "crypto";
41791
42023
  import { createHash as createHash33 } from "crypto";
@@ -45243,7 +45475,7 @@ var BatchSettlementEvmScheme3 = class {
45243
45475
  }
45244
45476
  };
45245
45477
 
45246
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
45478
+ // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
45247
45479
  import { createHash as createHash42, randomBytes as randomBytes8, randomUUID as randomUUID22 } from "crypto";
45248
45480
  import { randomBytes as randomBytes22 } from "crypto";
45249
45481
 
@@ -47614,7 +47846,7 @@ function date3(params) {
47614
47846
  // node_modules/zod/v4/classic/external.js
47615
47847
  config(en_default());
47616
47848
 
47617
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
47849
+ // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
47618
47850
  import { createHash as createHash52 } from "crypto";
47619
47851
  import { createHash as createHash62, randomUUID as randomUUID32 } from "crypto";
47620
47852
  import { isDeepStrictEqual as isDeepStrictEqual22 } from "util";
@@ -50007,7 +50239,7 @@ var streamSSE = (c, cb, onError) => {
50007
50239
  return c.newResponse(stream2.responseReadable);
50008
50240
  };
50009
50241
 
50010
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
50242
+ // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
50011
50243
  import { createHash as createHash10 } from "crypto";
50012
50244
  async function initLockPubkeyTable(db) {
50013
50245
  await withSdkInitLock(db, () => createLockPubkeyTable(db));
@@ -54640,7 +54872,13 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54640
54872
  const mapped = mapLedgerCommitError(err, void 0, true);
54641
54873
  if (mapped?.error) {
54642
54874
  logCredentialRejected("x402", "mid-job", err);
54643
- return { error: { body: mapped.error.body, status: mapped.error.status } };
54875
+ return {
54876
+ error: {
54877
+ body: mapped.error.body,
54878
+ status: mapped.error.status,
54879
+ ...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
54880
+ }
54881
+ };
54644
54882
  }
54645
54883
  throw err;
54646
54884
  }
@@ -54764,7 +55002,13 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54764
55002
  const mapped = mapLedgerCommitError(err, void 0, true);
54765
55003
  if (mapped?.error) {
54766
55004
  logCredentialRejected("tempo", "mid-job", err);
54767
- return { error: { body: mapped.error.body, status: mapped.error.status } };
55005
+ return {
55006
+ error: {
55007
+ body: mapped.error.body,
55008
+ status: mapped.error.status,
55009
+ ...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
55010
+ }
55011
+ };
54768
55012
  }
54769
55013
  throw err;
54770
55014
  }
@@ -54903,8 +55147,13 @@ async function acceptDurableExactIncoming(args) {
54903
55147
  drawId: replayedDrawId
54904
55148
  }) !== void 0;
54905
55149
  }
55150
+ const replayedDrawFunding = accepted.replayed && ledgerCtx?.topUp && accepted.receipt.txHash ? await ledgerCtx.ledger.getFunding({
55151
+ creditId: ledgerCtx.topUp.creditId,
55152
+ fundId: accepted.receipt.txHash
55153
+ }) : void 0;
54906
55154
  const info = withDrawBasis(
54907
55155
  {
55156
+ ...replayedDrawFunding && { drawFunding: replayedDrawFunding },
54908
55157
  paidMsats: args.snapshot.pendingPaymentMsats ?? accepted.receipt.amountMsats,
54909
55158
  paymentRail: "x402",
54910
55159
  receivedProofs: [],
@@ -54933,7 +55182,8 @@ function topUpBinding(info, snapshot) {
54933
55182
  return {
54934
55183
  ...fresh && { creditId: info.creditId, drawId: info.drawId },
54935
55184
  ...info.funding && { funding: info.funding },
54936
- ...info.unappliedMicro !== void 0 && { unappliedMicro: info.unappliedMicro }
55185
+ ...info.unappliedMicro !== void 0 && { unappliedMicro: info.unappliedMicro },
55186
+ ...info.drawFunding && { drawFunding: info.drawFunding }
54937
55187
  };
54938
55188
  }
54939
55189
  function applyPaymentInfoToJob(job, info) {
@@ -55253,7 +55503,11 @@ async function verifyAccumulatorReceipt(opts, mints, requiredMsats, ledgerCtx) {
55253
55503
  receivedProofs: [],
55254
55504
  error: {
55255
55505
  body: paymentErrorBody(result.code, { message: result.message, extra: { mints } }),
55256
- status
55506
+ status,
55507
+ // The accumulator keys replay on the request id, which is also the
55508
+ // funding id a mid-job top-up committed under, so the route can hand
55509
+ // back the original draw funding evidence beside the 409.
55510
+ ...status === 409 && requestId && { replayPaymentId: requestId }
55257
55511
  }
55258
55512
  };
55259
55513
  }
@@ -55449,7 +55703,7 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
55449
55703
  });
55450
55704
  return void 0;
55451
55705
  }
55452
- topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId };
55706
+ topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId, ledgerSeq: draw.ledgerSeq };
55453
55707
  callerId = credit.callerPubkey;
55454
55708
  currency = credit.currency;
55455
55709
  drawBasis = snapshot.paymentTxHash === drawSettlementRef(dvmId, snapshot.creditId, snapshot.drawId);
@@ -55599,7 +55853,8 @@ function withDrawBasis(info, ctx, committed) {
55599
55853
  ...committed.fundingCredit ? { fundingCredit: committed.fundingCredit } : {},
55600
55854
  ...committed.unappliedMicro !== void 0 && {
55601
55855
  unappliedMicro: committed.unappliedMicro
55602
- }
55856
+ },
55857
+ ...committed.drawFunding && { drawFunding: committed.drawFunding }
55603
55858
  };
55604
55859
  const draw = committed.draw;
55605
55860
  if (!draw) return base22;
@@ -55663,6 +55918,7 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55663
55918
  const instrument = credit.rail ? storedCreditBinding(credit).instrument : void 0;
55664
55919
  const report = {
55665
55920
  ...deposit,
55921
+ expiryMs: credit.expiryMs,
55666
55922
  callerPubkey: credit.callerPubkey,
55667
55923
  ...instrument && { instrument }
55668
55924
  };
@@ -55705,6 +55961,19 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55705
55961
  }
55706
55962
  if (ctx.topUp) {
55707
55963
  const { creditId: creditId2, drawId: drawId2 } = ctx.topUp;
55964
+ await ctx.ledger.recordFunding({
55965
+ creditId: creditId2,
55966
+ fundId: funding.paymentId,
55967
+ amountMicro: fundedMicro,
55968
+ rail: funding.rail,
55969
+ hostingAdmissionId: ctx.hostingAdmissionId,
55970
+ hostingJobId: ctx.jobId,
55971
+ hostingPaymentSeq: ctx.hostingPaymentSeq,
55972
+ jobId: ctx.jobId,
55973
+ drawId: drawId2,
55974
+ paymentSeq: ctx.hostingPaymentSeq,
55975
+ tx
55976
+ });
55708
55977
  const credit = await ctx.ledger.fund({
55709
55978
  creditId: creditId2,
55710
55979
  callerPubkey: ctx.callerId,
@@ -55717,10 +55986,23 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55717
55986
  basis,
55718
55987
  tx
55719
55988
  });
55989
+ const drawLedgerSeq = async () => ctx.topUp?.ledgerSeq ?? (await ctx.ledger.getDraw({ creditId: creditId2, drawId: drawId2 }))?.ledgerSeq;
55990
+ const completeDrawFunding = async (balanceAfterMicro, ledgerSeq) => ledgerSeq === void 0 ? void 0 : ctx.ledger.completeFunding({
55991
+ creditId: creditId2,
55992
+ fundId: funding.paymentId,
55993
+ callerPubkey: credit.callerPubkey,
55994
+ balanceAfterMicro,
55995
+ ledgerSeq,
55996
+ tx
55997
+ });
55720
55998
  if (ctx.askSatisfied) {
55721
- return commitDeposit({ creditId: creditId2, unappliedMicro: fundedMicro }, credit);
55999
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, await drawLedgerSeq());
56000
+ return commitDeposit({ creditId: creditId2, unappliedMicro: fundedMicro, drawFunding: drawFunding2 }, credit);
56001
+ }
56002
+ if (shortMidJob) {
56003
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, await drawLedgerSeq());
56004
+ return commitDeposit({ creditId: creditId2, drawFunding: drawFunding2 }, credit);
55722
56005
  }
55723
- if (shortMidJob) return commitDeposit({ creditId: creditId2 }, credit);
55724
56006
  const grown = await ctx.ledger.growDraw({
55725
56007
  creditId: creditId2,
55726
56008
  drawId: drawId2,
@@ -55741,14 +56023,17 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55741
56023
  tx
55742
56024
  });
55743
56025
  if (grown.addedAmountMicro <= 0) {
55744
- return commitDeposit({ creditId: creditId2, unappliedMicro: grown.cappedMicro }, credit);
56026
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, grown.ledgerSeq);
56027
+ return commitDeposit({ creditId: creditId2, unappliedMicro: grown.cappedMicro, drawFunding: drawFunding2 }, credit);
55745
56028
  }
56029
+ const drawFunding = await completeDrawFunding(grown.balanceAfterMicro, grown.ledgerSeq);
55746
56030
  return commitDeposit(
55747
56031
  {
55748
56032
  creditId: creditId2,
55749
56033
  draw: grown,
55750
56034
  added: { amountMicro: grown.addedAmountMicro, ...grown.addedRailValue },
55751
- ...grown.cappedMicro > 0 && { unappliedMicro: grown.cappedMicro }
56035
+ ...grown.cappedMicro > 0 && { unappliedMicro: grown.cappedMicro },
56036
+ drawFunding
55752
56037
  },
55753
56038
  credit
55754
56039
  );
@@ -56582,8 +56867,8 @@ function drainedAt(drain) {
56582
56867
  }
56583
56868
  async function fundingReceiptFor(ledger, issuer, funding) {
56584
56869
  if (!issuer) return void 0;
56585
- if (funding.receipt) return funding.receipt;
56586
- if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null) {
56870
+ if (funding.receipt) return isFundingReceipt(funding.receipt) ? funding.receipt : void 0;
56871
+ if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null || isDrawBound(funding)) {
56587
56872
  return void 0;
56588
56873
  }
56589
56874
  const receipt = issuer.issueFunding({
@@ -56595,11 +56880,43 @@ async function fundingReceiptFor(ledger, issuer, funding) {
56595
56880
  callerPubkey: funding.callerPubkey,
56596
56881
  issuedAt: Math.floor(funding.createdAt / 1e3)
56597
56882
  });
56598
- return ledger.saveFundingReceipt({
56883
+ const saved = await ledger.saveFundingReceipt({
56884
+ creditId: funding.creditId,
56885
+ fundId: funding.fundId,
56886
+ receipt
56887
+ });
56888
+ return isFundingReceipt(saved) ? saved : void 0;
56889
+ }
56890
+ function isDrawBound(funding) {
56891
+ return Boolean(funding.jobId) || Boolean(funding.drawId);
56892
+ }
56893
+ async function drawFundingReceiptFor(ledger, issuer, funding, currency) {
56894
+ if (!issuer) return void 0;
56895
+ if (funding.receipt) return isDrawFundingReceipt(funding.receipt) ? funding.receipt : void 0;
56896
+ if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null || !funding.jobId || !funding.drawId) {
56897
+ return void 0;
56898
+ }
56899
+ const receipt = issuer.issueDrawFunding({
56900
+ creditId: funding.creditId,
56901
+ jobId: funding.jobId,
56902
+ drawId: funding.drawId,
56903
+ fundId: funding.fundId,
56904
+ ...funding.paymentSeq !== null && funding.paymentSeq !== void 0 && {
56905
+ paymentSeq: funding.paymentSeq
56906
+ },
56907
+ currency,
56908
+ fundedMicro: funding.amountMicro,
56909
+ balanceAfterMicro: funding.balanceAfterMicro,
56910
+ ledgerSeq: funding.ledgerSeq,
56911
+ callerPubkey: funding.callerPubkey,
56912
+ issuedAt: Math.floor(funding.createdAt / 1e3)
56913
+ });
56914
+ const saved = await ledger.saveFundingReceipt({
56599
56915
  creditId: funding.creditId,
56600
56916
  fundId: funding.fundId,
56601
56917
  receipt
56602
56918
  });
56919
+ return isDrawFundingReceipt(saved) ? saved : void 0;
56603
56920
  }
56604
56921
  async function completeTempoChannelDrain(args) {
56605
56922
  if (!args.tx && args.refundedNative !== void 0 && /^\d{1,78}$/.test(String(args.refundedNative))) {
@@ -62611,6 +62928,34 @@ var ReceiptIssuer = class {
62611
62928
  this.secret
62612
62929
  );
62613
62930
  }
62931
+ /**
62932
+ * Countersign the immutable tuple captured when a mid-job payment funded a
62933
+ * job's credit against its pending draw. `ledgerSeq` is the draw's own
62934
+ * sequence so the artifact lines up with the terminal receipt's credit block.
62935
+ */
62936
+ issueDrawFunding(args) {
62937
+ return signDrawFundingReceipt(
62938
+ {
62939
+ v: 1,
62940
+ kind: "credit_draw_funding",
62941
+ credit_id: args.creditId,
62942
+ job_id: args.jobId,
62943
+ draw_id: args.drawId,
62944
+ fund_id: args.fundId,
62945
+ ...args.paymentSeq !== void 0 && { payment_seq: args.paymentSeq },
62946
+ currency: args.currency,
62947
+ funded_micro: args.fundedMicro,
62948
+ balance_after_micro: args.balanceAfterMicro,
62949
+ ledger_seq: args.ledgerSeq,
62950
+ issued_at: args.issuedAt ?? Math.floor(Date.now() / 1e3),
62951
+ caller_pubkey: args.callerPubkey,
62952
+ dvm_id: this.dvmId,
62953
+ dvm: this.dvm,
62954
+ receipt_pubkey: this.pubkey
62955
+ },
62956
+ this.secret
62957
+ );
62958
+ }
62614
62959
  };
62615
62960
  function isReceiptableStatus(status) {
62616
62961
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -64652,14 +64997,14 @@ var JobManager = class {
64652
64997
  if (hadPendingPayment2 && delta > 0 && (counters.pendingPaymentMsats === void 0 || counters.pendingPaymentMsats === 0)) {
64653
64998
  job.reactivationPaymentApplied = true;
64654
64999
  }
64655
- if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input") {
65000
+ if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input" && job.pendingPrompts.size === 0) {
64656
65001
  job.status = "processing";
64657
65002
  }
64658
65003
  } else if (delta) {
64659
65004
  job.paidMsats += delta;
64660
65005
  job.pendingPaymentMsats = void 0;
64661
65006
  if (hadPendingPayment2) job.reactivationPaymentApplied = true;
64662
- if (job.status === "awaiting-input") job.status = "processing";
65007
+ if (job.status === "awaiting-input" && job.pendingPrompts.size === 0) job.status = "processing";
64663
65008
  }
64664
65009
  return {};
64665
65010
  }
@@ -64714,10 +65059,17 @@ var JobManager = class {
64714
65059
  await this.jobStore.markInboundFailed(job.id, inboundSeq, code).catch(() => void 0);
64715
65060
  }
64716
65061
  this.reportCreditDeposit(verifyResult.error.funding);
64717
- return { error: { body: verifyResult.error.body, status: verifyResult.error.status } };
65062
+ const replayed = await this.replayedDrawFundingReceipt(job, verifyResult.error.replayPaymentId);
65063
+ return {
65064
+ error: {
65065
+ body: { ...verifyResult.error.body, ...replayed && { draw_funding_receipt: replayed } },
65066
+ status: verifyResult.error.status
65067
+ }
65068
+ };
64718
65069
  }
64719
65070
  const info = verifyResult.verified;
64720
65071
  if (!info) return {};
65072
+ const drawFundingReceipt = await this.drawFundingReceiptFor(info.drawFunding, info.funding?.currency);
64721
65073
  let unappliedCredit;
64722
65074
  const fullyUnapplied = info.unappliedMicro !== void 0 && info.funding !== void 0 && info.unappliedMicro >= info.funding.amountMicro;
64723
65075
  const hadPendingPayment = job.pendingPaymentMsats !== void 0;
@@ -64743,7 +65095,13 @@ var JobManager = class {
64743
65095
  }
64744
65096
  );
64745
65097
  } catch (err) {
64746
- return { error: await this.reportUnappliedPayment(job, inboundSeq, info, err) };
65098
+ const unapplied = await this.reportUnappliedPayment(job, inboundSeq, info, err);
65099
+ return {
65100
+ error: {
65101
+ body: { ...unapplied.body, ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt } },
65102
+ status: unapplied.status
65103
+ }
65104
+ };
64747
65105
  }
64748
65106
  const { counters } = result;
64749
65107
  job.paidMsats = counters.paidMsats;
@@ -64787,7 +65145,7 @@ var JobManager = class {
64787
65145
  job.pendingX402AmountUsdcMicro = void 0;
64788
65146
  }
64789
65147
  }
64790
- if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input") {
65148
+ if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input" && job.pendingPrompts.size === 0) {
64791
65149
  job.status = "processing";
64792
65150
  }
64793
65151
  } else {
@@ -64813,7 +65171,81 @@ var JobManager = class {
64813
65171
  );
64814
65172
  }
64815
65173
  this.reportCreditDeposit(info.funding);
64816
- return { ...unappliedCredit && { unappliedCredit } };
65174
+ return {
65175
+ ...unappliedCredit && { unappliedCredit },
65176
+ ...drawFundingReceipt && { drawFundingReceipt }
65177
+ };
65178
+ }
65179
+ /** Issue (or reuse) the signed draw funding receipt for a committed funding row; never throws. */
65180
+ async drawFundingReceiptFor(funding, currency) {
65181
+ const ledger = this.opts.creditLedger;
65182
+ if (!funding || !ledger || currency === void 0) return void 0;
65183
+ try {
65184
+ return await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, currency);
65185
+ } catch (err) {
65186
+ diagnosticConsole.error({
65187
+ level: "error",
65188
+ event: "draw_funding_receipt_unavailable",
65189
+ credit_id: funding.creditId,
65190
+ fund_id: funding.fundId,
65191
+ error: errText(err)
65192
+ });
65193
+ return void 0;
65194
+ }
65195
+ }
65196
+ /**
65197
+ * Every signed draw funding receipt for a job's draw, oldest first, reissuing
65198
+ * any the acknowledgement never carried. Empty when the ledger cannot list
65199
+ * draw fundings or the job holds no draw; a lookup failure is logged and
65200
+ * answered as empty rather than failing the read.
65201
+ */
65202
+ async drawFundingReceipts(job) {
65203
+ const ledger = this.opts.creditLedger;
65204
+ if (!ledger?.listDrawFundings || !this.opts.receiptIssuer || !job.creditId || !job.drawId) {
65205
+ return [];
65206
+ }
65207
+ try {
65208
+ const fundings = (await ledger.listDrawFundings({ creditId: job.creditId, drawId: job.drawId })).filter((funding) => funding.jobId === job.id);
65209
+ if (fundings.length === 0) return [];
65210
+ const credit = await ledger.get(job.creditId);
65211
+ if (!credit) return [];
65212
+ const receipts = [];
65213
+ for (const funding of fundings) {
65214
+ const receipt = await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, credit.currency);
65215
+ if (receipt) receipts.push(receipt);
65216
+ }
65217
+ return receipts;
65218
+ } catch (err) {
65219
+ diagnosticConsole.error({
65220
+ level: "error",
65221
+ event: "draw_funding_receipts_unavailable",
65222
+ job_id: job.id,
65223
+ error: errText(err)
65224
+ });
65225
+ return [];
65226
+ }
65227
+ }
65228
+ /** The stored evidence for a replayed mid-job payment, looked up by the payment id the marker collided on. */
65229
+ async replayedDrawFundingReceipt(job, replayPaymentId) {
65230
+ const ledger = this.opts.creditLedger;
65231
+ if (!replayPaymentId || !ledger || !job.creditId) return void 0;
65232
+ try {
65233
+ const [credit, funding] = await Promise.all([
65234
+ ledger.get(job.creditId),
65235
+ ledger.getFunding({ creditId: job.creditId, fundId: replayPaymentId })
65236
+ ]);
65237
+ if (!credit || !funding || funding.jobId !== job.id) return void 0;
65238
+ return await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, credit.currency);
65239
+ } catch (err) {
65240
+ diagnosticConsole.error({
65241
+ level: "error",
65242
+ event: "draw_funding_receipt_unavailable",
65243
+ job_id: job.id,
65244
+ fund_id: replayPaymentId,
65245
+ error: errText(err)
65246
+ });
65247
+ return void 0;
65248
+ }
64817
65249
  }
64818
65250
  /**
64819
65251
  * Tx C with a bounded retry.
@@ -72643,6 +73075,7 @@ var DVMServer = class {
72643
73075
  await this.jobManager.ensureReceipt(job);
72644
73076
  const res2 = { job_id: job.id, status: job.status };
72645
73077
  Object.assign(res2, terminalResponseFields(job), await this.contentFields(job));
73078
+ Object.assign(res2, await this.drawFundingFields(job));
72646
73079
  removeUnavailableContent(res2);
72647
73080
  return c.json(res2);
72648
73081
  }
@@ -72652,9 +73085,20 @@ var DVMServer = class {
72652
73085
  await this.jobManager.ensureReceipt(record2);
72653
73086
  const res = { job_id: record2.id, status: record2.status };
72654
73087
  Object.assign(res, terminalResponseFields(record2), await this.contentFields(record2));
73088
+ Object.assign(res, await this.drawFundingFields(record2));
72655
73089
  removeUnavailableContent(res);
72656
73090
  return c.json(res);
72657
73091
  }
73092
+ /**
73093
+ * Recoverable mid-job funding evidence for an authenticated job read: every
73094
+ * signed draw funding receipt the ledger holds for the job's draw, reissued
73095
+ * from the committed rows when an acknowledgement was lost or the process
73096
+ * restarted. Omitted entirely when the job holds no draw or none exist.
73097
+ */
73098
+ async drawFundingFields(job) {
73099
+ const receipts = await this.jobManager.drawFundingReceipts(job);
73100
+ return receipts.length > 0 ? { draw_funding_receipts: receipts } : {};
73101
+ }
72658
73102
  async handleGetMessages(c) {
72659
73103
  if (!jobCredential.presents(c.req)) return c.json(jobCredential.body(), 401);
72660
73104
  const id = c.req.param("id") ?? "";
@@ -72851,6 +73295,7 @@ var DVMServer = class {
72851
73295
  const inboundSeq2 = await jm.recordInboundPending(activeJob, body2.type, body2.content);
72852
73296
  const lockPubkeys2 = await this.resolveLockPubkeysForReceive();
72853
73297
  let unappliedCredit2;
73298
+ let drawFundingReceipt2;
72854
73299
  if (body2.type === "payment") {
72855
73300
  const outcome = await jm.processPayment(activeJob, body2, inboundSeq2, {
72856
73301
  lockPubkeys: lockPubkeys2,
@@ -72859,6 +73304,7 @@ var DVMServer = class {
72859
73304
  if (outcome.error)
72860
73305
  return c.json(outcome.error.body, outcome.error.status);
72861
73306
  unappliedCredit2 = outcome.unappliedCredit;
73307
+ drawFundingReceipt2 = outcome.drawFundingReceipt;
72862
73308
  } else {
72863
73309
  await jm.markInboundVerified(activeJob.id, inboundSeq2);
72864
73310
  }
@@ -72867,12 +73313,16 @@ var DVMServer = class {
72867
73313
  await jm.dispatchMessage(activeJob, body2.type, body2.content);
72868
73314
  await this.persistMessageSnapshot(jm, activeJob, body2.type);
72869
73315
  } catch (error) {
72870
- const response = this.postPaymentSnapshotFailure(c, error, activeJob, body2.type, inboundSeq2, unappliedCredit2);
73316
+ const response = this.postPaymentSnapshotFailure(c, error, activeJob, body2.type, inboundSeq2, unappliedCredit2, drawFundingReceipt2);
72871
73317
  if (response) return response;
72872
73318
  throw error;
72873
73319
  }
72874
73320
  const lastMsg2 = activeJob.messages[activeJob.messages.length - 1];
72875
- return c.json({ seq: lastMsg2.seq, ...unappliedCredit2 && { credit: unappliedCredit2 } }, 201);
73321
+ return c.json({
73322
+ seq: lastMsg2.seq,
73323
+ ...unappliedCredit2 && { credit: unappliedCredit2 },
73324
+ ...drawFundingReceipt2 && { draw_funding_receipt: drawFundingReceipt2 }
73325
+ }, 201);
72876
73326
  }
72877
73327
  const record2 = await jm.store.get(id);
72878
73328
  if (!record2) return c.json({ error: "Job not found" }, 404);
@@ -72936,6 +73386,7 @@ var DVMServer = class {
72936
73386
  const inboundSeq = await jm.recordInboundPending(job, body.type, body.content);
72937
73387
  const lockPubkeys = await this.resolveLockPubkeysForReceive();
72938
73388
  let unappliedCredit;
73389
+ let drawFundingReceipt;
72939
73390
  if (body.type === "payment") {
72940
73391
  const outcome = await jm.processPayment(job, body, inboundSeq, {
72941
73392
  lockPubkeys,
@@ -72946,10 +73397,14 @@ var DVMServer = class {
72946
73397
  return c.json(outcome.error.body, outcome.error.status);
72947
73398
  }
72948
73399
  unappliedCredit = outcome.unappliedCredit;
73400
+ drawFundingReceipt = outcome.drawFundingReceipt;
72949
73401
  } else {
72950
73402
  await jm.markInboundVerified(job.id, inboundSeq);
72951
73403
  }
72952
- const creditBlock = unappliedCredit ? { credit: unappliedCredit } : {};
73404
+ const creditBlock = {
73405
+ ...unappliedCredit && { credit: unappliedCredit },
73406
+ ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
73407
+ };
72953
73408
  const elapsed = Date.now() - record2.lastActivityAt;
72954
73409
  if (elapsed >= this.descriptor.idleTimeout * 1e3) {
72955
73410
  await jm.cancelJobIdle(job);
@@ -72970,7 +73425,7 @@ var DVMServer = class {
72970
73425
  await this.runReactivation(jm, job, body, record2.status);
72971
73426
  }
72972
73427
  } catch (error) {
72973
- const response = this.postPaymentSnapshotFailure(c, error, job, body.type, inboundSeq, unappliedCredit);
73428
+ const response = this.postPaymentSnapshotFailure(c, error, job, body.type, inboundSeq, unappliedCredit, drawFundingReceipt);
72974
73429
  if (response) return response;
72975
73430
  throw error;
72976
73431
  }
@@ -72984,7 +73439,7 @@ var DVMServer = class {
72984
73439
  await jm.persistJob(job);
72985
73440
  }
72986
73441
  }
72987
- postPaymentSnapshotFailure(c, error, job, type, inboundSeq, unappliedCredit) {
73442
+ postPaymentSnapshotFailure(c, error, job, type, inboundSeq, unappliedCredit, drawFundingReceipt) {
72988
73443
  if (!(error instanceof JobSnapshotPersistenceError) || type !== "payment" || inboundSeq === null || !isStreamableJobStore(this.jobManager.store)) return void 0;
72989
73444
  diagnosticConsole.error({ level: "job_snapshot_unavailable", job_id: job.id, seq: inboundSeq });
72990
73445
  return c.json({
@@ -72996,7 +73451,8 @@ var DVMServer = class {
72996
73451
  payment_status: "recorded",
72997
73452
  job_id: job.id,
72998
73453
  seq: inboundSeq,
72999
- ...unappliedCredit && { credit: unappliedCredit }
73454
+ ...unappliedCredit && { credit: unappliedCredit },
73455
+ ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
73000
73456
  }, 503);
73001
73457
  }
73002
73458
  /**
@@ -73479,6 +73935,9 @@ export {
73479
73935
  signFundingReceipt,
73480
73936
  isFundingReceipt,
73481
73937
  verifyFundingReceipt,
73938
+ signDrawFundingReceipt,
73939
+ isDrawFundingReceipt,
73940
+ verifyDrawFundingReceipt,
73482
73941
  isDrainReceipt,
73483
73942
  verifyDrainReceipt,
73484
73943
  require_proper_lockfile,
@@ -73580,6 +74039,7 @@ export {
73580
74039
  checkReceiptAttestation,
73581
74040
  verifyDrainReceiptChain,
73582
74041
  verifyFundingReceiptChain,
74042
+ verifyDrawFundingReceiptChain,
73583
74043
  weakestReceiptVerdict,
73584
74044
  isPublicRequestId,
73585
74045
  parseTraceparent,
@@ -73676,6 +74136,7 @@ export {
73676
74136
  recordFundResponse,
73677
74137
  recordBalanceResponse,
73678
74138
  applyReceiptCredit,
74139
+ recordDrawFunding,
73679
74140
  applyImplicitReceiptCredit,
73680
74141
  ensureProvisionalCredit,
73681
74142
  markCredit,