@dvmkit/dvm-cli 0.2.1 → 0.3.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.
@@ -69,7 +69,7 @@ import {
69
69
  x402ResourceServer,
70
70
  x402SupportedNetworksHint,
71
71
  x402Version
72
- } from "./chunk-XJN5ZDAL.js";
72
+ } from "./chunk-R4MSO2GX.js";
73
73
  import {
74
74
  withSdkInitLock
75
75
  } from "./chunk-3SWX5BQP.js";
@@ -101,7 +101,7 @@ import {
101
101
  tempoSessionPriorCumulativeMicro,
102
102
  withTempoChannelLock,
103
103
  withholdsTempoCreditSession
104
- } from "./chunk-5GIU2LBJ.js";
104
+ } from "./chunk-YLWATJ7F.js";
105
105
  import {
106
106
  base,
107
107
  chains_exports
@@ -384,10 +384,10 @@ import {
384
384
  usdToMsats,
385
385
  usdcToMsats,
386
386
  withinAdvertisedTolerance
387
- } from "./chunk-6CC6JGEU.js";
387
+ } from "./chunk-VY277ROG.js";
388
388
  import {
389
389
  connectedTempoAccount
390
- } from "./chunk-JHUMURHA.js";
390
+ } from "./chunk-24VB7FR7.js";
391
391
  import {
392
392
  AGENT_MNEMONIC_FILE,
393
393
  BUDGET_FILE,
@@ -423,7 +423,7 @@ import {
423
423
  sha256,
424
424
  sha512,
425
425
  updateConfig
426
- } from "./chunk-EGY4KDBW.js";
426
+ } from "./chunk-SKKZ4OAA.js";
427
427
  import {
428
428
  privateKeyToAccount
429
429
  } from "./chunk-EVQERRCP.js";
@@ -2782,20 +2782,8 @@ var getPublicKey2 = i2.getPublicKey;
2782
2782
  var finalizeEvent2 = i2.finalizeEvent;
2783
2783
  var verifyEvent2 = i2.verifyEvent;
2784
2784
 
2785
- // node_modules/@dvmkit/sdk/dist/chunk-EDDYHZ6W.js
2785
+ // node_modules/@dvmkit/sdk/dist/chunk-CEOAHV2I.js
2786
2786
  import { createHash } from "crypto";
2787
- var RECOMMENDED_MINTS = [
2788
- {
2789
- name: "Coinos",
2790
- description: "Primary Cashu mint accepted by dvmkit DVMs",
2791
- url: "https://mint.coinos.io"
2792
- },
2793
- {
2794
- name: "Voltz Mint",
2795
- description: "Fallback Cashu mint accepted by dvmkit DVMs",
2796
- url: "https://mint.lnvoltz.com"
2797
- }
2798
- ];
2799
2787
  var X402_SELF_RELAY_KEY = "DVMKIT_X402_SELF_RELAY_KEY";
2800
2788
  var X402_RECEIVER_AUTHORIZER_KEY = "DVMKIT_X402_RECEIVER_AUTHORIZER_KEY";
2801
2789
  var X402_BATCH_SETTLEMENT_KEY = "DVMKIT_X402_BATCH_SETTLEMENT";
@@ -3746,7 +3734,7 @@ var MemoryKVStore = class {
3746
3734
  }
3747
3735
  };
3748
3736
 
3749
- // node_modules/@dvmkit/sdk/dist/chunk-VRQDX5P4.js
3737
+ // node_modules/@dvmkit/sdk/dist/chunk-KXCKFIJI.js
3750
3738
  import { existsSync, readFileSync, writeFileSync } from "fs";
3751
3739
  import {
3752
3740
  chmodSync,
@@ -8984,7 +8972,7 @@ zero
8984
8972
  zone
8985
8973
  zoo`.split("\n");
8986
8974
 
8987
- // node_modules/@dvmkit/sdk/dist/chunk-VRQDX5P4.js
8975
+ // node_modules/@dvmkit/sdk/dist/chunk-KXCKFIJI.js
8988
8976
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8989
8977
  import { existsSync as existsSync3, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
8990
8978
 
@@ -18958,7 +18946,7 @@ function expand(hash3, prk, info2, length = 32) {
18958
18946
  }
18959
18947
  var hkdf = (hash3, ikm, salt, info2, length) => expand(hash3, extract(hash3, ikm, salt), info2, length);
18960
18948
 
18961
- // node_modules/@dvmkit/sdk/dist/chunk-VRQDX5P4.js
18949
+ // node_modules/@dvmkit/sdk/dist/chunk-KXCKFIJI.js
18962
18950
  import {
18963
18951
  chmodSync as chmodSync3,
18964
18952
  existsSync as existsSync5,
@@ -18985,6 +18973,32 @@ function toLockPubkey(raw3) {
18985
18973
  function isX402SettlementReconciliationReason(value) {
18986
18974
  return value === "settlement_not_on_chain" || value === "chain_unreachable" || value === "settlement_unbookmarked" || value === "facilitator_channel_state_unavailable";
18987
18975
  }
18976
+ var RECOMMENDED_MINTS = [
18977
+ {
18978
+ name: "Coinos",
18979
+ description: "Primary Cashu mint accepted by dvmkit DVMs",
18980
+ url: "https://mint.coinos.io"
18981
+ },
18982
+ {
18983
+ name: "Voltz Mint",
18984
+ description: "Fallback Cashu mint accepted by dvmkit DVMs",
18985
+ url: "https://mint.lnvoltz.com"
18986
+ }
18987
+ ];
18988
+ function isTestMintUrl(url2) {
18989
+ let host;
18990
+ try {
18991
+ host = new URL(url2).hostname.toLowerCase();
18992
+ } catch {
18993
+ return false;
18994
+ }
18995
+ if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
18996
+ if (LOOPBACK_HOSTS.has(host)) return true;
18997
+ if (host.endsWith(".localhost")) return true;
18998
+ return TEST_MINT_HOSTS.has(host);
18999
+ }
19000
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
19001
+ var TEST_MINT_HOSTS = /* @__PURE__ */ new Set(["testnut.cashu.space", "dvmkit-testmint.fly.dev"]);
18988
19002
  function backupSecretFile(file2, nextContent) {
18989
19003
  const content = existsSync(file2) ? readFileSync(file2) : null;
18990
19004
  if (content === null) return null;
@@ -32551,7 +32565,7 @@ async function probeX402(x402, timeoutMs) {
32551
32565
  let network;
32552
32566
  let address;
32553
32567
  try {
32554
- const { loadX402Wallet: loadX402Wallet2, getX402Balance: getX402Balance2, ensureAddress: ensureAddress2, usdcContractByCaip2: usdcContractByCaip22 } = await import("./x402-T2C5MX3T-CMGC2CLF.js");
32568
+ const { loadX402Wallet: loadX402Wallet2, getX402Balance: getX402Balance2, ensureAddress: ensureAddress2, usdcContractByCaip2: usdcContractByCaip22 } = await import("./x402-5H27DCBE-UEQQQ5UY.js");
32555
32569
  const wallet = loadX402Wallet2();
32556
32570
  if (!wallet) {
32557
32571
  const storedKey = x402.privateKey;
@@ -32609,7 +32623,7 @@ async function probeMpp(mpp, timeoutMs) {
32609
32623
  if (!mpp) return null;
32610
32624
  if (mpp.method === "tempo") {
32611
32625
  try {
32612
- const { connectedTempoAccount: connectedTempoAccount2, getTempoUsdcBalance: getTempoUsdcBalance2, TEMPO_CHAIN_ID: TEMPO_CHAIN_ID2 } = await import("./tempo-wallet-QOLEIPCV-A6BUUBJS.js");
32626
+ const { connectedTempoAccount: connectedTempoAccount2, getTempoUsdcBalance: getTempoUsdcBalance2, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./tempo-wallet-4QKSV65O-J6ZZQAD7.js");
32613
32627
  const account = await connectedTempoAccount2();
32614
32628
  if (!account) {
32615
32629
  return {
@@ -32634,7 +32648,7 @@ async function probeMpp(mpp, timeoutMs) {
32634
32648
  // against — a zero here only means "none of *this* token".
32635
32649
  details: {
32636
32650
  address: account.address,
32637
- chain_id: TEMPO_CHAIN_ID2,
32651
+ chain_id: balance.chainId,
32638
32652
  token: balance.tokenAddress,
32639
32653
  // internal-review: as on x402 above — which endpoint the number came from.
32640
32654
  ...rpcDetails(balance.rpcUrlRedacted, balance.rpcSource)
@@ -32646,7 +32660,11 @@ async function probeMpp(mpp, timeoutMs) {
32646
32660
  configured: true,
32647
32661
  reachable: false,
32648
32662
  balanceUsdc: void 0,
32649
- details: { address: account.address, chain_id: TEMPO_CHAIN_ID2, balance_unknown: true },
32663
+ details: {
32664
+ address: account.address,
32665
+ chain_id: resolveTempoNetwork2(account.network ?? "mainnet").chainId,
32666
+ balance_unknown: true
32667
+ },
32650
32668
  error: classifyError("tempo_unreachable", err)
32651
32669
  };
32652
32670
  }
@@ -34385,9 +34403,9 @@ function x402SettlementPending(creditId, refund) {
34385
34403
  );
34386
34404
  }
34387
34405
 
34388
- // node_modules/@dvmkit/sdk/dist/chunk-DBCLBYHP.js
34406
+ // node_modules/@dvmkit/sdk/dist/chunk-KVEHHC7W.js
34389
34407
  import { randomUUID as randomUUID4 } from "crypto";
34390
- var MemoryCreditLedger = class {
34408
+ var MemoryCreditLedger = class _MemoryCreditLedger {
34391
34409
  /**
34392
34410
  * Per-process and lost on restart, so a DVM backed by this ledger never
34393
34411
  * advertises the funding menu outside devMode (internal-review) — funding on one
@@ -34400,6 +34418,16 @@ var MemoryCreditLedger = class {
34400
34418
  tempoLosses = /* @__PURE__ */ new Map();
34401
34419
  x402Losses = /* @__PURE__ */ new Map();
34402
34420
  x402Settlements;
34421
+ /** Internal disposable transaction snapshot. The caller must serialize every ledger access. */
34422
+ forkForTransaction() {
34423
+ const fork = new _MemoryCreditLedger();
34424
+ for (const name of ["credits", "fundings", "invoices", "tempoLosses", "x402Losses"]) {
34425
+ const target = fork[name];
34426
+ for (const [key, value] of this[name]) target.set(key, structuredClone(value));
34427
+ }
34428
+ fork.x402Settlements = this.x402Settlements;
34429
+ return fork;
34430
+ }
34403
34431
  /** See {@link CreditLedger.useX402SettlementGate} — same contract (internal-review). */
34404
34432
  useX402SettlementGate(gate) {
34405
34433
  this.x402Settlements = gate;
@@ -36451,7 +36479,7 @@ function mergeSignals(a, b2) {
36451
36479
  return AbortSignal.any([a, b2]);
36452
36480
  }
36453
36481
 
36454
- // node_modules/@dvmkit/sdk/dist/chunk-5GFED3GJ.js
36482
+ // node_modules/@dvmkit/sdk/dist/chunk-NPIW5VR5.js
36455
36483
  import { randomUUID as randomUUID5 } from "crypto";
36456
36484
  var TEMPO_SETTLEMENT_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
36457
36485
  function isTempoInsufficientFundsError(error) {
@@ -36475,14 +36503,16 @@ function challengeMeta(challenge2) {
36475
36503
  }
36476
36504
  function wrapMppx(mppx) {
36477
36505
  const dispatcher = mppx.challenge;
36506
+ const server = mppx;
36478
36507
  const issueChallenge = (method, intent, o) => {
36479
36508
  const handler = dispatcher[method][intent];
36480
36509
  if (!handler) {
36481
36510
  throw new Error(`Mppx: no challenge handler registered for ${method}/${intent}`);
36482
36511
  }
36483
- return handler(o);
36512
+ const chainId = method === "tempo" ? server.tempoConfiguration?.chainId : void 0;
36513
+ return handler(chainId === void 0 ? o : { chainId, ...o });
36484
36514
  };
36485
- return Object.assign(mppx, { issueChallenge });
36515
+ return Object.assign(server, { issueChallenge });
36486
36516
  }
36487
36517
  var DEFAULT_TEMPO_SESSION_CHAIN_OPS = {
36488
36518
  getChannelStatesBatch: session_exports.Precompile.Chain.getChannelStatesBatch,
@@ -36914,7 +36944,7 @@ var _testing = {
36914
36944
  attachTempoSessionRuntime
36915
36945
  };
36916
36946
 
36917
- // node_modules/@dvmkit/sdk/dist/chunk-QK3VJNCK.js
36947
+ // node_modules/@dvmkit/sdk/dist/chunk-NJFOV36R.js
36918
36948
  import { createHash as createHash5, randomUUID as randomUUID6 } from "crypto";
36919
36949
  import { createHash as createHash23 } from "crypto";
36920
36950
  import { createHash as createHash33 } from "crypto";
@@ -40372,7 +40402,7 @@ var BatchSettlementEvmScheme3 = class {
40372
40402
  }
40373
40403
  };
40374
40404
 
40375
- // node_modules/@dvmkit/sdk/dist/chunk-QK3VJNCK.js
40405
+ // node_modules/@dvmkit/sdk/dist/chunk-NJFOV36R.js
40376
40406
  import { randomBytes as randomBytes8, randomUUID as randomUUID23 } from "crypto";
40377
40407
  import { randomBytes as randomBytes22 } from "crypto";
40378
40408
 
@@ -42743,7 +42773,7 @@ function date3(params) {
42743
42773
  // node_modules/zod/v4/classic/external.js
42744
42774
  config(en_default());
42745
42775
 
42746
- // node_modules/@dvmkit/sdk/dist/chunk-QK3VJNCK.js
42776
+ // node_modules/@dvmkit/sdk/dist/chunk-NJFOV36R.js
42747
42777
  import { createHash as createHash42 } from "crypto";
42748
42778
  import { randomBytes as randomBytes42 } from "crypto";
42749
42779
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
@@ -45167,7 +45197,7 @@ var streamSSE = (c, cb, onError) => {
45167
45197
  return c.newResponse(stream2.responseReadable);
45168
45198
  };
45169
45199
 
45170
- // node_modules/@dvmkit/sdk/dist/chunk-QK3VJNCK.js
45200
+ // node_modules/@dvmkit/sdk/dist/chunk-NJFOV36R.js
45171
45201
  import { createHash as createHash6 } from "crypto";
45172
45202
  async function initLockPubkeyTable(db) {
45173
45203
  await withSdkInitLock(db, () => createLockPubkeyTable(db));
@@ -47968,6 +47998,9 @@ function valueCashuFunding(wallet, proofs) {
47968
47998
  };
47969
47999
  }
47970
48000
  async function acceptAccumulatorPayment(opts) {
48001
+ if (opts.disposable && !opts.mints.every(isTestMintUrl)) {
48002
+ throw new Error("Disposable Cashu accepts only known test or loopback mints.");
48003
+ }
47971
48004
  if (!opts.requestId) {
47972
48005
  return {
47973
48006
  kind: "rejected",
@@ -47992,6 +48025,16 @@ async function acceptAccumulatorPayment(opts) {
47992
48025
  const walletProvider = opts.walletProvider ?? getWallet;
47993
48026
  const wallet = await walletProvider(mintUrl);
47994
48027
  proofs = wallet.decodeToken(opts.cashuToken).proofs;
48028
+ if (meta3.unit !== "sat" || proofs.length === 0) {
48029
+ throw new Error("Cashu payment requires nonempty sat proofs.");
48030
+ }
48031
+ for (const proof of proofs) {
48032
+ if (!proof.dleq || !Yi(proof, wallet.getKeyset(proof.id))) {
48033
+ throw new Error(
48034
+ "Cashu payment requires valid mint-provided NUT-12 DLEQ evidence for every proof. Request a fresh token from a compatible mint."
48035
+ );
48036
+ }
48037
+ }
47995
48038
  valuation = valueCashuFunding(wallet, proofs);
47996
48039
  } catch (err) {
47997
48040
  return {
@@ -48026,6 +48069,9 @@ async function acceptAccumulatorPayment(opts) {
48026
48069
  };
48027
48070
  }
48028
48071
  const allowedNormalised = allowed.map(toLockPubkey);
48072
+ if (opts.disposable && (allowedNormalised.length !== 1 || (F(p.secret, "n_sigs") ?? 1) !== 1)) {
48073
+ return { kind: "rejected", code: "not_p2pk_locked", message: "Disposable Cashu requires an exclusive single-signature P2PK lock." };
48074
+ }
48029
48075
  const match2 = accepted.find((pk) => allowedNormalised.includes(pk));
48030
48076
  if (!match2) {
48031
48077
  return {
@@ -48062,6 +48108,9 @@ async function acceptAccumulatorPayment(opts) {
48062
48108
  message: "One or more proofs are pending at the mint \u2014 retry shortly."
48063
48109
  };
48064
48110
  }
48111
+ if (states.some((state) => state.state !== la.UNSPENT)) {
48112
+ return { kind: "rejected", code: "mint_unreachable", message: "Mint returned an unknown proof state." };
48113
+ }
48065
48114
  } catch (err) {
48066
48115
  return {
48067
48116
  kind: "rejected",
@@ -48079,7 +48128,13 @@ async function acceptAccumulatorPayment(opts) {
48079
48128
  tExpireMsByIndex
48080
48129
  };
48081
48130
  try {
48082
- if (opts.withCommitTx) {
48131
+ if (opts.disposable) {
48132
+ const account = opts.withDisposableLedger;
48133
+ if (!account) throw new Error("Disposable Cashu requires atomic credit accounting.");
48134
+ await opts.disposable.commit(opts.requestId, proofs, (ledger) => account(ledger, acceptedValue));
48135
+ } else if (!opts.db) {
48136
+ throw new Error("Cashu accumulator requires a storage backend.");
48137
+ } else if (opts.withCommitTx) {
48083
48138
  const withCommitTx = opts.withCommitTx;
48084
48139
  const client = await opts.db.connect();
48085
48140
  try {
@@ -48129,7 +48184,7 @@ function parseNut11LocktimeMs(secret) {
48129
48184
  var UPFRONT_CHALLENGE_TTL_MS = 5 * 60 * 1e3;
48130
48185
  var CONSUMED_CREDENTIAL_TTL_MS = 2 * UPFRONT_CHALLENGE_TTL_MS;
48131
48186
  function devModeSkipsPaymentVerification(opts) {
48132
- return Boolean(opts.devMode) && !opts.mints;
48187
+ return Boolean(opts.devMode) && !opts.mints && !opts.x402 && !opts.mpp && !opts.paymentMethods?.some((method) => method === "cashu" || method === "x402" || method === "tempo");
48133
48188
  }
48134
48189
  var PAYMENT_PROOF_KEYS = ["cashu_token", "x402_payment", "tempo_credential"];
48135
48190
  function hasPaymentProof(content) {
@@ -48332,7 +48387,7 @@ async function verifyUpfrontPayment(opts) {
48332
48387
  }
48333
48388
  };
48334
48389
  }
48335
- if (opts.cashuMode === "p2pk-accumulator" && opts.accumulatorDb && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
48390
+ if (opts.cashuMode === "p2pk-accumulator" && (opts.accumulatorDb || opts.disposableCashu) && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
48336
48391
  return verifyAccumulatorReceipt(opts, mints, requiredMsats, ledgerCtx);
48337
48392
  }
48338
48393
  return {
@@ -48480,7 +48535,7 @@ async function verifyUpfrontPayment(opts) {
48480
48535
  x402Requirements
48481
48536
  });
48482
48537
  }
48483
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-T2C5MX3T-CMGC2CLF.js");
48538
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-5H27DCBE-UEQQQ5UY.js");
48484
48539
  const receipt = await verifyX402Payment2(
48485
48540
  x402Payment,
48486
48541
  x402Config,
@@ -49329,7 +49384,7 @@ function buildPaymentErrorResponse(body, challenges, x402Requirements, status, x
49329
49384
  async function verifyIncomingPayment(body, opts, snapshot) {
49330
49385
  if (body.type !== "payment") return {};
49331
49386
  if (body.content.cashu_token) {
49332
- if (opts.cashuMode === "p2pk-accumulator" && opts.accumulatorDb && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
49387
+ if (opts.cashuMode === "p2pk-accumulator" && (opts.accumulatorDb || opts.disposableCashu) && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
49333
49388
  const mints = opts.mints ?? [];
49334
49389
  if (mints.length === 0) {
49335
49390
  return {
@@ -49347,6 +49402,7 @@ async function verifyIncomingPayment(body, opts, snapshot) {
49347
49402
  {
49348
49403
  cashuToken: body.content.cashu_token,
49349
49404
  accumulatorDb: opts.accumulatorDb,
49405
+ disposableCashu: opts.disposableCashu,
49350
49406
  dvmId: opts.dvmId,
49351
49407
  lockPubkeys: opts.lockPubkeys,
49352
49408
  requestId,
@@ -49408,7 +49464,7 @@ async function verifyIncomingPayment(body, opts, snapshot) {
49408
49464
  snapshot
49409
49465
  });
49410
49466
  }
49411
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-T2C5MX3T-CMGC2CLF.js");
49467
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-5H27DCBE-UEQQQ5UY.js");
49412
49468
  const receipt = await verifyX402Payment2(
49413
49469
  body.content.x402_payment,
49414
49470
  opts.x402Config,
@@ -49772,7 +49828,7 @@ function applyPaymentInfoToJob(job, info2) {
49772
49828
  async function processIncomingPayment(job, body, opts) {
49773
49829
  if (body.type !== "payment") return null;
49774
49830
  if (body.content.cashu_token) {
49775
- if (opts.cashuMode === "p2pk-accumulator" && opts.accumulatorDb && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
49831
+ if (opts.cashuMode === "p2pk-accumulator" && (opts.accumulatorDb || opts.disposableCashu) && opts.dvmId && opts.lockPubkeys && opts.lockPubkeys.length > 0) {
49776
49832
  const mints = opts.mints ?? [];
49777
49833
  if (mints.length === 0) {
49778
49834
  return {
@@ -49787,6 +49843,7 @@ async function processIncomingPayment(job, body, opts) {
49787
49843
  {
49788
49844
  cashuToken: body.content.cashu_token,
49789
49845
  accumulatorDb: opts.accumulatorDb,
49846
+ disposableCashu: opts.disposableCashu,
49790
49847
  dvmId: opts.dvmId,
49791
49848
  lockPubkeys: opts.lockPubkeys,
49792
49849
  requestId,
@@ -49821,7 +49878,7 @@ async function processIncomingPayment(job, body, opts) {
49821
49878
  try {
49822
49879
  const requiredMsats = job.pendingPaymentMsats ?? 0;
49823
49880
  const requiredUsdcMicro = job.pendingX402AmountUsdcMicro !== void 0 ? BigInt(job.pendingX402AmountUsdcMicro) : BigInt(msatsToUsdc(requiredMsats, rate));
49824
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-T2C5MX3T-CMGC2CLF.js");
49881
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-5H27DCBE-UEQQQ5UY.js");
49825
49882
  const receipt = await verifyX402Payment2(
49826
49883
  body.content.x402_payment,
49827
49884
  opts.x402Config,
@@ -49941,7 +49998,7 @@ function creditPendingPayment(job) {
49941
49998
  }
49942
49999
  async function verifyAccumulatorReceipt(opts, mints, requiredMsats, ledgerCtx) {
49943
50000
  const { cashuToken, accumulatorDb, dvmId, lockPubkeys, mintHealthTracker } = opts;
49944
- if (!cashuToken || !accumulatorDb || !dvmId || !lockPubkeys || lockPubkeys.length === 0) {
50001
+ if (!cashuToken || !accumulatorDb && !opts.disposableCashu || !dvmId || !lockPubkeys || lockPubkeys.length === 0) {
49945
50002
  return {
49946
50003
  paidMsats: 0,
49947
50004
  receivedProofs: [],
@@ -50020,6 +50077,17 @@ async function verifyAccumulatorReceipt(opts, mints, requiredMsats, ledgerCtx) {
50020
50077
  requestId: opts.requestId,
50021
50078
  mints,
50022
50079
  db: accumulatorDb,
50080
+ disposable: opts.disposableCashu,
50081
+ withDisposableLedger: ledgerCtx && requestId ? async (ledger, accepted) => {
50082
+ credited = await fundAndDraw({ ...ledgerCtx, ledger }, {
50083
+ rail: "cashu",
50084
+ paymentId: requestId,
50085
+ paidMsats: accepted.paidMsats,
50086
+ grossPaidMsats: accepted.grossMsats,
50087
+ cashuInputFeeMsats: accepted.inputFeeMsats,
50088
+ mint: tokenMint
50089
+ });
50090
+ } : void 0,
50023
50091
  dvmId,
50024
50092
  lockPubkeys,
50025
50093
  beforeCommit,
@@ -56515,6 +56583,7 @@ var JobManager = class {
56515
56583
  resourcePath: `/v1/job/${job.id}/messages`,
56516
56584
  cashuMode: this.opts.cashuMode,
56517
56585
  accumulatorDb: this.opts.cashuMode === "p2pk-accumulator" ? this.opts.db : void 0,
56586
+ disposableCashu: this.opts.disposableCashu,
56518
56587
  dvmId: this.opts.dvmId,
56519
56588
  lockPubkeys: extra?.lockPubkeys,
56520
56589
  mintHealthTracker: extra?.mintHealthTracker,
@@ -56953,8 +57022,25 @@ var JobManager = class {
56953
57022
  * `context.ts`). The gap is visible to callers — the `seq` series skips a
56954
57023
  * number — which is precisely the completeness signal receipts exist for.
56955
57024
  */
57025
+ async observePaidCompletion(record2) {
57026
+ const callback = this.opts.onPaidJobCompleted;
57027
+ if (!callback || record2.status !== "completed" || !record2.paymentRail || !record2.creditId || !record2.drawId || !this.opts.creditLedger) return;
57028
+ const draw = await this.opts.creditLedger.getDraw({ creditId: record2.creditId, drawId: record2.drawId }).catch(() => void 0);
57029
+ const rail = draw?.railValue.rail;
57030
+ const currency = draw?.railValue.creditCurrency;
57031
+ if (draw?.status !== "settled" || draw.amountMicro <= 0 || !currency || !rail || !isFundingRail(rail)) return;
57032
+ const testFunds = rail === "lightning" ? null : this.opts.paymentMode?.rails[rail].testFunds ?? null;
57033
+ try {
57034
+ await callback({ jobId: record2.id, rail, amountMicro: draw.amountMicro, currency, testFunds });
57035
+ } catch (error) {
57036
+ console.error(`[${record2.id}] Paid completion observer failed:`, error);
57037
+ }
57038
+ }
56956
57039
  async issueReceipt(record2) {
56957
- if (record2.receipt) return record2.receipt;
57040
+ if (record2.receipt) {
57041
+ await this.observePaidCompletion(record2);
57042
+ return record2.receipt;
57043
+ }
56958
57044
  if (!isReceiptableStatus(record2.status)) return void 0;
56959
57045
  let credit;
56960
57046
  try {
@@ -56974,13 +57060,18 @@ var JobManager = class {
56974
57060
  return void 0;
56975
57061
  }
56976
57062
  const issuer = this.opts.receiptIssuer;
56977
- if (!issuer) return void 0;
57063
+ if (!issuer) {
57064
+ await this.observePaidCompletion(record2);
57065
+ return void 0;
57066
+ }
56978
57067
  if (!isReceiptIssuingStore(this.jobStore)) return void 0;
56979
57068
  const store = this.jobStore;
56980
57069
  try {
56981
57070
  const seq = await store.claimReceiptSeq(record2.id);
56982
57071
  const receipt = issuer.issue(record2, seq, void 0, credit);
56983
- return await store.saveReceipt(record2.id, receipt) ?? receipt;
57072
+ const saved = await store.saveReceipt(record2.id, receipt) ?? receipt;
57073
+ await this.observePaidCompletion(record2);
57074
+ return saved;
56984
57075
  } catch (err) {
56985
57076
  console.error(
56986
57077
  JSON.stringify({
@@ -58311,7 +58402,7 @@ var X402FacilitatorHealth = class {
58311
58402
  facilitator: support.facilitator,
58312
58403
  network: support.network,
58313
58404
  reason: support.reason,
58314
- message: "x402 omitted because the configured facilitator advertises no supported exact generation on this network. Other rails are unaffected."
58405
+ message: "Exact x402 is unavailable because the configured facilitator advertises no supported exact generation on this network. Configured batch settlement is evaluated separately; other rails are unaffected."
58315
58406
  })
58316
58407
  );
58317
58408
  } else if (!support.exact.v1 || !support.exact.v2 || this.config.batchSettlement && !support.batchSettlement) {
@@ -61227,197 +61318,236 @@ function revenueReporterBannerState(s) {
61227
61318
  return s.devMode ? "(dev \u2014 not reporting)" : "misconfigured";
61228
61319
  }
61229
61320
  async function createDVMServer(descriptor, opts) {
61230
- if (process.env.DVMKIT_CASHU_MINTS && opts.cashuMode === void 0) {
61231
- console.warn(
61232
- JSON.stringify({
61233
- level: "cashu_opts_env_ignored",
61234
- message: "DVMKIT_CASHU_MINTS is set in env but cashuMode opt is undefined \u2014 cashu is NOT active. Pass cashuMode, lockPubkey, and db via createDVMHost to enable it."
61235
- })
61236
- );
61237
- }
61238
- const envMaybe = opts.env;
61239
- const platformToken = opts.platformToken ?? envMaybe.DVMKIT_PLATFORM_TOKEN;
61240
- const platformUrl = opts.platformUrl ?? envMaybe.DVMKIT_PLATFORM_URL;
61241
- const dvmId = opts.dvmId;
61242
61321
  let revenueReporter;
61243
61322
  let payoutReporter;
61244
- if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
61245
- const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-ASZ7SHHH-ISAMJDZQ.js");
61246
- const reporter = new RevenueReporter2(opts.db, platformUrl, platformToken);
61247
- await reporter.init();
61248
- reporter.startRetryLoop();
61249
- revenueReporter = reporter;
61250
- const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-RG6XNGPI-KNY74HLM.js");
61251
- payoutReporter = new PayoutReporter2({
61252
- dvmId,
61253
- db: opts.db,
61254
- transport: reporter,
61255
- // The same condition the admin routes and the accumulator monitor mount on.
61256
- cashu: opts.cashuMode === "p2pk-accumulator" && !!opts.lockPubkey,
61257
- ...typeof opts.db.connect === "function" ? {} : { batchStore: new MemoryX402BatchStore() }
61258
- });
61259
- await payoutReporter.init();
61260
- payoutReporter.start();
61261
- }
61262
- assertRevenueReporterReady({
61263
- failFast: opts.failFast ?? false,
61264
- devMode: opts.devMode,
61265
- platformToken,
61266
- platformUrl,
61267
- dvmId,
61268
- hasPgPool: !!opts.db
61269
- });
61270
- const effectiveOnJobCompleted = opts.onJobCompleted ?? (revenueReporter ? (info2) => revenueReporter.report(info2) : void 0);
61271
- const effectiveOnJobCost = opts.onJobCost ?? (revenueReporter ? (info2) => revenueReporter.reportCost(info2) : void 0);
61272
- const effectiveOnPaidJobDeath = opts.onPaidJobDeath ?? (revenueReporter ? (info2) => revenueReporter.reportPaidJobDeath(info2) : void 0);
61273
- const effectiveOnRevenueSkippedNoRail = opts.onRevenueSkippedNoRail ?? (revenueReporter ? (info2) => revenueReporter.reportRevenueSkippedNoRail(info2) : void 0);
61274
- const enqueueCreditDeposit = !opts.onCreditFunded && revenueReporter ? revenueReporter.enqueueDeposit.bind(revenueReporter) : void 0;
61275
- const enqueueCreditDrain = revenueReporter ? revenueReporter.enqueueCreditDrain.bind(revenueReporter) : void 0;
61276
- const enqueueCreditDrawRelease = revenueReporter ? revenueReporter.enqueueCreditDrawRelease.bind(revenueReporter) : void 0;
61277
- const unsubscribeTempoSettlementReadiness = opts.tempoSettlementReadiness?.subscribe({
61278
- onBalance: (observation) => revenueReporter && dvmId ? revenueReporter.reportTempoSettlementBalance({
61279
- dvmId,
61280
- address: observation.address,
61281
- network: observation.network,
61282
- token: observation.token,
61283
- balanceMicro: observation.balanceMicro.toString(),
61284
- lowBalanceMicro: observation.lowBalanceMicro.toString(),
61285
- checkedAt: observation.checkedAt,
61286
- ready: observation.ready
61287
- }) : void 0,
61288
- onFailure: (observation) => revenueReporter && dvmId ? revenueReporter.reportTempoSettlementFailure({
61289
- dvmId,
61290
- address: observation.address,
61291
- network: observation.network,
61292
- token: observation.token,
61293
- operation: observation.operation,
61294
- errorClass: observation.errorClass,
61295
- checkedAt: observation.checkedAt,
61296
- ...observation.balanceMicro !== void 0 ? { balanceMicro: observation.balanceMicro.toString() } : {},
61297
- ...observation.channelId ? { channelId: observation.channelId } : {},
61298
- ...observation.creditId ? { creditId: observation.creditId } : {},
61299
- ...observation.drainId ? { drainId: observation.drainId } : {}
61300
- }) : void 0
61301
- });
61302
- opts.tempoSettlementReadiness?.start();
61303
- const creditLedger = opts.creditLedger ?? new MemoryCreditLedger();
61304
- if (revenueReporter && dvmId) {
61305
- creditLedger.useCreditExpiryReleaseOutbox?.({
61306
- dvmId,
61307
- enqueue: revenueReporter.enqueueCreditExpiryRelease.bind(revenueReporter)
61308
- });
61309
- }
61310
- const creditExpirySweep = startCreditExpirySweep(creditLedger, opts.creditExpirySweep);
61311
- const processedPayments = opts.processedPayments ?? new MemoryProcessedPaymentStore();
61312
- const bootX402Support = opts.x402 ? opts.x402FacilitatorHealth?.support() ?? configuredX402FacilitatorSupport(opts.x402) : void 0;
61313
- const x402Config = opts.x402;
61314
- const x402BatchConfig = x402Config?.batchSettlement;
61315
- const selfRelayEnabled = !!x402BatchConfig?.selfRelay;
61316
- const effectiveX402BatchConfig = x402BatchConfig?.selfRelay ? {
61317
- ...x402BatchConfig,
61318
- selfRelay: {
61319
- ...x402BatchConfig.selfRelay,
61320
- onBalance: async (observation) => {
61321
- if (revenueReporter && dvmId) {
61322
- await revenueReporter.reportX402SelfRelayGasBalance({
61323
- dvmId,
61324
- address: observation.address,
61325
- network: observation.network,
61326
- balanceWei: observation.balanceWei.toString(),
61327
- lowBalanceWei: observation.lowBalanceWei.toString(),
61328
- checkedAt: observation.checkedAt
61329
- });
61330
- }
61331
- await x402BatchConfig.selfRelay?.onBalance?.(observation);
61332
- },
61333
- onRpcHealth: async (observation) => {
61334
- if (revenueReporter && dvmId) {
61335
- await revenueReporter.reportX402SelfRelayRpcHealth({
61336
- dvmId,
61337
- ...observation
61338
- });
61339
- }
61340
- await x402BatchConfig.selfRelay?.onRpcHealth?.(observation);
61323
+ let unsubscribeTempoSettlementReadiness;
61324
+ let creditExpirySweep;
61325
+ let x402ChannelStorage;
61326
+ let x402BatchSettlement;
61327
+ let server;
61328
+ let shutdownPromise;
61329
+ const shutdown = () => shutdownPromise ??= (async () => {
61330
+ const errors = [];
61331
+ const capture = async (operation) => {
61332
+ try {
61333
+ await operation();
61334
+ } catch (error) {
61335
+ errors.push(error);
61336
+ }
61337
+ };
61338
+ let settlementStopped;
61339
+ if (server) {
61340
+ try {
61341
+ settlementStopped = server.shutdown();
61342
+ } catch (error) {
61343
+ errors.push(error);
61344
+ }
61345
+ } else if (x402BatchSettlement) {
61346
+ try {
61347
+ settlementStopped = x402BatchSettlement.stop();
61348
+ } catch (error) {
61349
+ errors.push(error);
61341
61350
  }
61342
61351
  }
61343
- } : x402BatchConfig;
61344
- const x402ChannelStorage = opts.db && x402Config && effectiveX402BatchConfig && !effectiveX402BatchConfig.storage ? new PostgresX402ChannelStorage(opts.db, {
61345
- terminalizeUnbackedCredit: (evidence, tx) => creditLedger.terminalizeX402Credit(evidence, tx)
61346
- }) : void 0;
61347
- if (x402ChannelStorage) {
61348
- await x402ChannelStorage.init();
61349
- creditLedger.useX402SettlementGate?.(x402ChannelStorage);
61350
- }
61351
- const x402BatchSettlementFactory = x402Config && effectiveX402BatchConfig ? () => createX402BatchSettlementServer({
61352
- channelStorage: x402ChannelStorage,
61353
- network: x402Config.network,
61354
- payTo: x402Config.payTo,
61355
- facilitator: x402Config.facilitator,
61356
- ...x402Config.facilitatorAuth ? { facilitatorAuth: x402Config.facilitatorAuth } : {},
61357
- config: effectiveX402BatchConfig,
61358
- db: opts.db,
61359
- allowInMemory: opts.devMode,
61360
- earnedNative: (channelId) => creditLedger.earnedNativeForX402Channel(channelId),
61361
- supportedResponse: selfRelayEnabled ? void 0 : opts.x402FacilitatorHealth?.supportedResponse?.(),
61362
- payout: payoutReporter?.x402Observer()
61363
- }) : void 0;
61364
- const x402BatchSettlement = x402BatchSettlementFactory && (bootX402Support?.batchSettlement || selfRelayEnabled) ? await x402BatchSettlementFactory() : void 0;
61365
- const x402ExactStore = x402Config && opts.db && typeof opts.db.connect === "function" ? new PostgresX402ExactSettlementStore(opts.db) : void 0;
61366
- await x402ExactStore?.init();
61367
- const x402ExactEvidence = x402Config && x402ExactStore ? await createX402SettlementEvidenceReader({
61368
- network: x402Config.network,
61369
- ...x402BatchConfig?.rpcUrl ? { rpcUrl: x402BatchConfig.rpcUrl } : {}
61370
- }) : void 0;
61371
- const x402ExactSettlement = x402Config && x402ExactStore ? new X402ExactSettlementServer({
61372
- store: x402ExactStore,
61373
- evidence: x402ExactEvidence,
61374
- repair: async (effect, receipt, tx) => {
61375
- if (!receipt.txHash) throw new Error("settled exact x402 intent has no transaction");
61376
- await repairX402ExactSettlementEffect({
61377
- effect,
61378
- paymentId: receipt.txHash,
61379
- ledger: creditLedger,
61380
- processedPayments,
61381
- enqueueCreditDeposit,
61382
- tx
61352
+ await capture(() => payoutReporter?.stop());
61353
+ await capture(() => revenueReporter?.stop());
61354
+ await capture(() => creditExpirySweep?.stop());
61355
+ await capture(() => unsubscribeTempoSettlementReadiness?.());
61356
+ if (settlementStopped) await capture(() => settlementStopped);
61357
+ if (x402ChannelStorage) {
61358
+ await capture(() => x402ChannelStorage?.close());
61359
+ }
61360
+ if (errors.length === 1) throw errors[0];
61361
+ if (errors.length > 1) {
61362
+ throw new AggregateError(errors, `${String(errors.length)} DVM shutdown operations failed`);
61363
+ }
61364
+ })();
61365
+ try {
61366
+ if (process.env.DVMKIT_CASHU_MINTS && opts.cashuMode === void 0) {
61367
+ console.warn(
61368
+ JSON.stringify({
61369
+ level: "cashu_opts_env_ignored",
61370
+ message: "DVMKIT_CASHU_MINTS is set in env but cashuMode opt is undefined \u2014 cashu is NOT active. Pass cashuMode, lockPubkey, and db via createDVMHost to enable it."
61371
+ })
61372
+ );
61373
+ }
61374
+ const envMaybe = opts.env;
61375
+ const platformToken = opts.platformToken ?? envMaybe.DVMKIT_PLATFORM_TOKEN;
61376
+ const platformUrl = opts.platformUrl ?? envMaybe.DVMKIT_PLATFORM_URL;
61377
+ const dvmId = opts.dvmId;
61378
+ if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
61379
+ const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-ASZ7SHHH-ISAMJDZQ.js");
61380
+ const reporter = new RevenueReporter2(opts.db, platformUrl, platformToken);
61381
+ revenueReporter = reporter;
61382
+ await reporter.init();
61383
+ reporter.startRetryLoop();
61384
+ const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-RG6XNGPI-KNY74HLM.js");
61385
+ payoutReporter = new PayoutReporter2({
61386
+ dvmId,
61387
+ db: opts.db,
61388
+ transport: reporter,
61389
+ // The same condition the admin routes and the accumulator monitor mount on.
61390
+ cashu: opts.cashuMode === "p2pk-accumulator" && !!opts.lockPubkey,
61391
+ ...typeof opts.db.connect === "function" ? {} : { batchStore: new MemoryX402BatchStore() }
61383
61392
  });
61393
+ await payoutReporter.init();
61394
+ payoutReporter.start();
61384
61395
  }
61385
- }) : void 0;
61386
- const server = new DVMServer(descriptor, {
61387
- ...opts,
61388
- creditLedger,
61389
- processedPayments,
61390
- onJobCompleted: effectiveOnJobCompleted,
61391
- onJobCost: effectiveOnJobCost,
61392
- onPaidJobDeath: effectiveOnPaidJobDeath,
61393
- onRevenueSkippedNoRail: effectiveOnRevenueSkippedNoRail,
61394
- onCreditFunded: opts.onCreditFunded,
61395
- enqueueCreditDeposit,
61396
- enqueueCreditDrain,
61397
- enqueueCreditDrawRelease,
61398
- x402BatchSettlement,
61399
- x402BatchSettlementFactory,
61400
- x402ExactSettlement,
61401
- payoutReporter
61402
- });
61403
- await server.jobManager.recoverTerminalCosts();
61404
- return {
61405
- app: server.app,
61406
- authAudience: server.authAudience,
61407
- shutdown() {
61408
- const settlementStopped = server.shutdown();
61409
- payoutReporter?.stop();
61410
- revenueReporter?.stop();
61411
- creditExpirySweep?.stop();
61412
- unsubscribeTempoSettlementReadiness?.();
61413
- if (x402ChannelStorage) {
61414
- void settlementStopped.then(() => x402ChannelStorage.close()).catch(() => void 0);
61396
+ assertRevenueReporterReady({
61397
+ failFast: opts.failFast ?? false,
61398
+ devMode: opts.devMode,
61399
+ platformToken,
61400
+ platformUrl,
61401
+ dvmId,
61402
+ hasPgPool: !!opts.db
61403
+ });
61404
+ const activeRevenueReporter = revenueReporter;
61405
+ const effectiveOnJobCompleted = opts.onJobCompleted ?? (activeRevenueReporter ? (info2) => activeRevenueReporter.report(info2) : void 0);
61406
+ const effectiveOnJobCost = opts.onJobCost ?? (activeRevenueReporter ? (info2) => activeRevenueReporter.reportCost(info2) : void 0);
61407
+ const effectiveOnPaidJobDeath = opts.onPaidJobDeath ?? (activeRevenueReporter ? (info2) => activeRevenueReporter.reportPaidJobDeath(info2) : void 0);
61408
+ const effectiveOnRevenueSkippedNoRail = opts.onRevenueSkippedNoRail ?? (activeRevenueReporter ? (info2) => activeRevenueReporter.reportRevenueSkippedNoRail(info2) : void 0);
61409
+ const enqueueCreditDeposit = !opts.onCreditFunded && activeRevenueReporter ? activeRevenueReporter.enqueueDeposit.bind(activeRevenueReporter) : void 0;
61410
+ const enqueueCreditDrain = activeRevenueReporter ? activeRevenueReporter.enqueueCreditDrain.bind(activeRevenueReporter) : void 0;
61411
+ const enqueueCreditDrawRelease = activeRevenueReporter ? activeRevenueReporter.enqueueCreditDrawRelease.bind(activeRevenueReporter) : void 0;
61412
+ unsubscribeTempoSettlementReadiness = opts.tempoSettlementReadiness?.subscribe({
61413
+ onBalance: (observation) => activeRevenueReporter && dvmId ? activeRevenueReporter.reportTempoSettlementBalance({
61414
+ dvmId,
61415
+ address: observation.address,
61416
+ network: observation.network,
61417
+ token: observation.token,
61418
+ balanceMicro: observation.balanceMicro.toString(),
61419
+ lowBalanceMicro: observation.lowBalanceMicro.toString(),
61420
+ checkedAt: observation.checkedAt,
61421
+ ready: observation.ready
61422
+ }) : void 0,
61423
+ onFailure: (observation) => activeRevenueReporter && dvmId ? activeRevenueReporter.reportTempoSettlementFailure({
61424
+ dvmId,
61425
+ address: observation.address,
61426
+ network: observation.network,
61427
+ token: observation.token,
61428
+ operation: observation.operation,
61429
+ errorClass: observation.errorClass,
61430
+ checkedAt: observation.checkedAt,
61431
+ ...observation.balanceMicro !== void 0 ? { balanceMicro: observation.balanceMicro.toString() } : {},
61432
+ ...observation.channelId ? { channelId: observation.channelId } : {},
61433
+ ...observation.creditId ? { creditId: observation.creditId } : {},
61434
+ ...observation.drainId ? { drainId: observation.drainId } : {}
61435
+ }) : void 0
61436
+ });
61437
+ opts.tempoSettlementReadiness?.start();
61438
+ const creditLedger = opts.creditLedger ?? new MemoryCreditLedger();
61439
+ if (activeRevenueReporter && dvmId) {
61440
+ creditLedger.useCreditExpiryReleaseOutbox?.({
61441
+ dvmId,
61442
+ enqueue: activeRevenueReporter.enqueueCreditExpiryRelease.bind(activeRevenueReporter)
61443
+ });
61444
+ }
61445
+ creditExpirySweep = startCreditExpirySweep(creditLedger, opts.creditExpirySweep);
61446
+ const processedPayments = opts.processedPayments ?? new MemoryProcessedPaymentStore();
61447
+ const bootX402Support = opts.x402 ? opts.x402FacilitatorHealth?.support() ?? configuredX402FacilitatorSupport(opts.x402) : void 0;
61448
+ const x402Config = opts.x402;
61449
+ const x402BatchConfig = x402Config?.batchSettlement;
61450
+ const selfRelayEnabled = !!x402BatchConfig?.selfRelay;
61451
+ const effectiveX402BatchConfig = x402BatchConfig?.selfRelay ? {
61452
+ ...x402BatchConfig,
61453
+ selfRelay: {
61454
+ ...x402BatchConfig.selfRelay,
61455
+ onBalance: async (observation) => {
61456
+ if (activeRevenueReporter && dvmId) {
61457
+ await activeRevenueReporter.reportX402SelfRelayGasBalance({
61458
+ dvmId,
61459
+ address: observation.address,
61460
+ network: observation.network,
61461
+ balanceWei: observation.balanceWei.toString(),
61462
+ lowBalanceWei: observation.lowBalanceWei.toString(),
61463
+ checkedAt: observation.checkedAt
61464
+ });
61465
+ }
61466
+ await x402BatchConfig.selfRelay?.onBalance?.(observation);
61467
+ },
61468
+ onRpcHealth: async (observation) => {
61469
+ if (activeRevenueReporter && dvmId) {
61470
+ await activeRevenueReporter.reportX402SelfRelayRpcHealth({
61471
+ dvmId,
61472
+ ...observation
61473
+ });
61474
+ }
61475
+ await x402BatchConfig.selfRelay?.onRpcHealth?.(observation);
61476
+ }
61415
61477
  }
61416
- },
61417
- jobManager: server.jobManager,
61418
- revenueReporterActive: !!revenueReporter,
61419
- payoutReporter
61420
- };
61478
+ } : x402BatchConfig;
61479
+ x402ChannelStorage = opts.db && x402Config && effectiveX402BatchConfig && !effectiveX402BatchConfig.storage ? new PostgresX402ChannelStorage(opts.db, {
61480
+ terminalizeUnbackedCredit: (evidence, tx) => creditLedger.terminalizeX402Credit(evidence, tx)
61481
+ }) : void 0;
61482
+ if (x402ChannelStorage) {
61483
+ await x402ChannelStorage.init();
61484
+ creditLedger.useX402SettlementGate?.(x402ChannelStorage);
61485
+ }
61486
+ const x402BatchSettlementFactory = x402Config && effectiveX402BatchConfig ? () => createX402BatchSettlementServer({
61487
+ channelStorage: x402ChannelStorage,
61488
+ network: x402Config.network,
61489
+ payTo: x402Config.payTo,
61490
+ facilitator: x402Config.facilitator,
61491
+ ...x402Config.facilitatorAuth ? { facilitatorAuth: x402Config.facilitatorAuth } : {},
61492
+ config: effectiveX402BatchConfig,
61493
+ db: opts.db,
61494
+ allowInMemory: opts.devMode,
61495
+ earnedNative: (channelId) => creditLedger.earnedNativeForX402Channel(channelId),
61496
+ supportedResponse: selfRelayEnabled ? void 0 : opts.x402FacilitatorHealth?.supportedResponse?.(),
61497
+ payout: payoutReporter?.x402Observer()
61498
+ }) : void 0;
61499
+ x402BatchSettlement = x402BatchSettlementFactory && (bootX402Support?.batchSettlement || selfRelayEnabled) ? await x402BatchSettlementFactory() : void 0;
61500
+ const x402ExactStore = x402Config && opts.db && typeof opts.db.connect === "function" ? new PostgresX402ExactSettlementStore(opts.db) : void 0;
61501
+ await x402ExactStore?.init();
61502
+ const x402ExactEvidence = x402Config && x402ExactStore ? await createX402SettlementEvidenceReader({
61503
+ network: x402Config.network,
61504
+ ...x402BatchConfig?.rpcUrl ? { rpcUrl: x402BatchConfig.rpcUrl } : {}
61505
+ }) : void 0;
61506
+ const x402ExactSettlement = x402Config && x402ExactStore ? new X402ExactSettlementServer({
61507
+ store: x402ExactStore,
61508
+ evidence: x402ExactEvidence,
61509
+ repair: async (effect, receipt, tx) => {
61510
+ if (!receipt.txHash) throw new Error("settled exact x402 intent has no transaction");
61511
+ await repairX402ExactSettlementEffect({
61512
+ effect,
61513
+ paymentId: receipt.txHash,
61514
+ ledger: creditLedger,
61515
+ processedPayments,
61516
+ enqueueCreditDeposit,
61517
+ tx
61518
+ });
61519
+ }
61520
+ }) : void 0;
61521
+ server = new DVMServer(descriptor, {
61522
+ ...opts,
61523
+ creditLedger,
61524
+ processedPayments,
61525
+ onJobCompleted: effectiveOnJobCompleted,
61526
+ onJobCost: effectiveOnJobCost,
61527
+ onPaidJobDeath: effectiveOnPaidJobDeath,
61528
+ onRevenueSkippedNoRail: effectiveOnRevenueSkippedNoRail,
61529
+ onCreditFunded: opts.onCreditFunded,
61530
+ enqueueCreditDeposit,
61531
+ enqueueCreditDrain,
61532
+ enqueueCreditDrawRelease,
61533
+ x402BatchSettlement,
61534
+ x402BatchSettlementFactory,
61535
+ x402ExactSettlement,
61536
+ payoutReporter
61537
+ });
61538
+ await server.jobManager.recoverTerminalCosts();
61539
+ return {
61540
+ app: server.app,
61541
+ authAudience: server.authAudience,
61542
+ shutdown,
61543
+ jobManager: server.jobManager,
61544
+ revenueReporterActive: !!activeRevenueReporter,
61545
+ payoutReporter
61546
+ };
61547
+ } catch (initializationError) {
61548
+ await shutdown().catch(() => void 0);
61549
+ throw initializationError;
61550
+ }
61421
61551
  }
61422
61552
  function unknownRouteNotFound(c) {
61423
61553
  c.set("unknownRoute", true);
@@ -61493,7 +61623,6 @@ var DVMServer = class {
61493
61623
  this.ownsMintHealthTracker = false;
61494
61624
  } else if (opts.mints && opts.mints.length > 0) {
61495
61625
  this.mintHealthTracker = new MintHealthTracker({ mints: opts.mints });
61496
- this.mintHealthTracker.start();
61497
61626
  this.ownsMintHealthTracker = true;
61498
61627
  } else {
61499
61628
  this.ownsMintHealthTracker = false;
@@ -61506,12 +61635,6 @@ var DVMServer = class {
61506
61635
  this.creditLedger = opts.creditLedger ?? new MemoryCreditLedger();
61507
61636
  this.opts.mpp?.useTempoCreditLedger?.(this.creditLedger);
61508
61637
  this.processedPayments = opts.processedPayments ?? new MemoryProcessedPaymentStore();
61509
- if (this.opts.tempoObserverHealth?.declareSessionCapability) {
61510
- this.undeclareSessionCapability = this.opts.tempoObserverHealth.declareSessionCapability(
61511
- () => this.tempoSessionCapability()
61512
- );
61513
- void this.opts.tempoObserverHealth.refresh?.();
61514
- }
61515
61638
  this.jobManager = new JobManager(descriptor, {
61516
61639
  receiptIssuer: this.receiptIssuer,
61517
61640
  creditLedger: this.creditLedger,
@@ -61540,6 +61663,7 @@ var DVMServer = class {
61540
61663
  mpp: opts.mpp,
61541
61664
  cashuMode: opts.cashuMode,
61542
61665
  lockPubkey: opts.lockPubkey,
61666
+ disposableCashu: opts.disposableCashu,
61543
61667
  db: opts.db,
61544
61668
  dvmId: opts.dvmId,
61545
61669
  authAudience: this.authAudience,
@@ -61556,6 +61680,8 @@ var DVMServer = class {
61556
61680
  pricingCurrency: this.pricingCurrency,
61557
61681
  onCreditFunded: opts.onCreditFunded,
61558
61682
  onJobCompleted: opts.onJobCompleted,
61683
+ onPaidJobCompleted: opts.onPaidJobCompleted,
61684
+ paymentMode: opts.paymentMode,
61559
61685
  onJobCost: opts.onJobCost,
61560
61686
  onPaidJobDeath: opts.onPaidJobDeath,
61561
61687
  onRevenueSkippedNoRail: opts.onRevenueSkippedNoRail,
@@ -61564,19 +61690,44 @@ var DVMServer = class {
61564
61690
  reactivationClaimGraceMs: opts.reactivationClaimGraceMs
61565
61691
  });
61566
61692
  this.app = new Hono2();
61567
- this.registerRoutes();
61693
+ try {
61694
+ this.registerRoutes();
61695
+ if (this.ownsMintHealthTracker) this.mintHealthTracker?.start();
61696
+ if (this.opts.tempoObserverHealth?.declareSessionCapability) {
61697
+ this.undeclareSessionCapability = this.opts.tempoObserverHealth.declareSessionCapability(
61698
+ () => this.tempoSessionCapability()
61699
+ );
61700
+ void this.opts.tempoObserverHealth.refresh?.();
61701
+ }
61702
+ } catch (error) {
61703
+ try {
61704
+ this.jobManager.shutdown();
61705
+ } catch {
61706
+ }
61707
+ try {
61708
+ if (this.ownsMintHealthTracker) this.mintHealthTracker?.stop();
61709
+ } catch {
61710
+ }
61711
+ try {
61712
+ this.undeclareSessionCapability?.();
61713
+ } catch {
61714
+ }
61715
+ this.undeclareSessionCapability = void 0;
61716
+ throw error;
61717
+ }
61568
61718
  }
61569
61719
  /**
61570
61720
  * Tear down this mount. Every leg is synchronous except the batch-settlement
61571
61721
  * server's own `stop()`; the returned promise settles once that has finished,
61572
61722
  * so a caller holding a resource behind it — the settlement pool the spend
61573
61723
  * gate's store owns (internal-review) — can sequence its close instead of pulling it
61574
- * out from under an in-flight stop. It never rejects, so ignoring it is safe.
61724
+ * out from under an in-flight stop. A rejection remains observable so the app
61725
+ * and host teardown layers can finish later cleanup before surfacing it.
61575
61726
  */
61576
61727
  shutdown() {
61577
61728
  this.jobManager.shutdown();
61578
61729
  const settlement = this.x402BatchSettlementInit ?? Promise.resolve(this.x402BatchSettlement);
61579
- const stopped = settlement.then((s) => s?.stop()).catch(() => void 0);
61730
+ const stopped = settlement.then((s) => s?.stop());
61580
61731
  if (this.ownsMintHealthTracker) this.mintHealthTracker?.stop();
61581
61732
  this.undeclareSessionCapability?.();
61582
61733
  this.undeclareSessionCapability = void 0;
@@ -61773,6 +61924,7 @@ var DVMServer = class {
61773
61924
  * `cashu_not_p2pk_locked`).
61774
61925
  */
61775
61926
  async resolveLockPubkeysForReceive() {
61927
+ if (this.opts.disposableCashu && this.opts.lockPubkey) return [toLockPubkey(this.opts.lockPubkey)];
61776
61928
  if (this.opts.cashuMode !== "p2pk-accumulator" || !this.opts.db || !this.opts.dvmId || !this.opts.lockPubkey) {
61777
61929
  return void 0;
61778
61930
  }
@@ -62091,7 +62243,7 @@ var DVMServer = class {
62091
62243
  defaultPaymentMethods() {
62092
62244
  const methods = [];
62093
62245
  if (this.opts.mints?.length) {
62094
- const accumulatorReady = this.opts.cashuMode === "p2pk-accumulator" && !!this.opts.lockPubkey && !!this.opts.db;
62246
+ const accumulatorReady = this.opts.cashuMode === "p2pk-accumulator" && !!this.opts.lockPubkey && (!!this.opts.db || !!this.opts.disposableCashu);
62095
62247
  if (accumulatorReady) methods.push("cashu");
62096
62248
  }
62097
62249
  if (this.opts.x402 && this.x402CurrencySupported()) methods.push("x402");
@@ -62276,7 +62428,7 @@ var DVMServer = class {
62276
62428
  const authHeader = c.req.header("Authorization");
62277
62429
  const { Credential } = await import("./dist-2G3QBGID.js");
62278
62430
  const mppCredential = authHeader ? Credential.extractPaymentScheme(authHeader) ?? void 0 : void 0;
62279
- let lockPubkeys;
62431
+ let lockPubkeys = this.opts.disposableCashu && this.opts.lockPubkey ? [toLockPubkey(this.opts.lockPubkey)] : void 0;
62280
62432
  if (this.opts.cashuMode === "p2pk-accumulator" && this.opts.db && this.opts.dvmId && this.opts.lockPubkey) {
62281
62433
  const active = await this.lockPubkeyStateForRead(this.opts.db, this.opts.dvmId);
62282
62434
  lockPubkeys = activePubkeySet(active);
@@ -62310,6 +62462,7 @@ var DVMServer = class {
62310
62462
  consumedCredentialStore: this.consumedCredentialStore,
62311
62463
  cashuMode: this.opts.cashuMode,
62312
62464
  accumulatorDb: this.opts.cashuMode === "p2pk-accumulator" ? this.opts.db : void 0,
62465
+ disposableCashu: this.opts.disposableCashu,
62313
62466
  dvmId: this.opts.dvmId,
62314
62467
  lockPubkeys,
62315
62468
  requestId: c.req.header("X-Cashu-Request-Id"),
@@ -62496,6 +62649,7 @@ var DVMServer = class {
62496
62649
  ...this.opts.mpp.tempoConfiguration && {
62497
62650
  recipient: this.opts.mpp.tempoConfiguration.recipient,
62498
62651
  payment_token: this.opts.mpp.tempoConfiguration.paymentToken,
62652
+ chain_id: this.opts.mpp.tempoConfiguration.chainId,
62499
62653
  ...this.opts.mpp.tempoConfiguration.operator && {
62500
62654
  operator: this.opts.mpp.tempoConfiguration.operator
62501
62655
  },
@@ -64330,7 +64484,6 @@ export {
64330
64484
  generateSecretKey2 as generateSecretKey,
64331
64485
  getPublicKey2 as getPublicKey,
64332
64486
  verifyEvent2 as verifyEvent,
64333
- RECOMMENDED_MINTS,
64334
64487
  X402_SELF_RELAY_KEY,
64335
64488
  X402_RECEIVER_AUTHORIZER_KEY,
64336
64489
  X402_BATCH_SETTLEMENT_KEY,
@@ -64360,6 +64513,7 @@ export {
64360
64513
  extract,
64361
64514
  expand,
64362
64515
  toLockPubkey,
64516
+ RECOMMENDED_MINTS,
64363
64517
  backupSecretFile,
64364
64518
  assertAgentMnemonicReplaceable,
64365
64519
  writeAgentMnemonic,