@dvmkit/dvm-cli 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,18 @@ If the earlier `@dvmkit/cli` package is installed globally, remove it first with
13
13
 
14
14
  The bundled agent skill is exported as `@dvmkit/dvm-cli/skill`. Documentation lives at [dvmkit.ai](https://dvmkit.ai).
15
15
 
16
+ ## Portable job access
17
+
18
+ `status`, `messages`, `message`, and `cancel` can follow a job from another machine when both its provider endpoint and job token are available. Prefer environment variables so the bearer token does not enter shell history or the process list:
19
+
20
+ ```sh
21
+ DVM_JOB_ENDPOINT=https://provider.example \
22
+ DVM_JOB_TOKEN=<64-character-hex-token> \
23
+ dvm status <job-id>
24
+ ```
25
+
26
+ The same values are accepted as `--endpoint <url>` and `--job-token <hex>`. Each command resolves flags first, then `DVM_JOB_ENDPOINT` / `DVM_JOB_TOKEN`, then the local job record; overrides apply only to that invocation and are never saved. `pay` accepts the same overrides but still requires the submitting machine's local pending request and spending policy, so an endpoint and token alone can never authorize a payment.
27
+
16
28
  ## Protocol compatibility
17
29
 
18
30
  Every request to a DVM or the managed dvmkit platform identifies the caller version and protocol generation and advertises a sorted set of additive client capabilities. Servers gate behavior on those capabilities, not on SemVer alone: a numerically newer client does not imply support for a named behavior. An HTTP 426 response names the capabilities or minimum version the caller must add before retrying.
@@ -23,6 +35,8 @@ Use the exact Node.js release in `.nvmrc`. Install with `node scripts/pinned-npm
23
35
 
24
36
  `npm run verify` builds the CLI, runs ESLint, type-checks, runs unit and standalone mock-provider contract tests, verifies the packed package and bundled skill upgrade path, scans the repository/package/Git/optional pull-request body for public-safety violations, then proves a clean locked install can build, type-check, and pass the tests.
25
37
 
38
+ The repository scan leaves an ignored, untracked root `.kiln/` runtime directory in place. Git-tracked runtime files, nested directories with the same name, explicit scan roots, and packed-package contents remain subject to the public-safety checks.
39
+
26
40
  Release automation is documented in [docs/releasing.md](docs/releasing.md). It prepares a reviewed release pull request and only a separately signed immutable tag can enter the GitHub-hosted npm trusted-publishing path.
27
41
 
28
42
  ## License
@@ -5547,7 +5547,7 @@ function markerKey(args) {
5547
5547
  return `${args.dvmId}\0${args.rail}\0${args.paymentId}`;
5548
5548
  }
5549
5549
 
5550
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
5550
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
5551
5551
  import { createHash, randomUUID as randomUUID4 } from "crypto";
5552
5552
 
5553
5553
  // node_modules/@cashu/cashu-ts/node_modules/@noble/hashes/utils.js
@@ -11074,9 +11074,9 @@ function checksum(len, fn2) {
11074
11074
  }
11075
11075
  var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join(""));
11076
11076
  var base58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));
11077
- var createBase58check = (sha2564) => {
11078
- afn(sha2564);
11079
- const _sha256 = sha2564;
11077
+ var createBase58check = (sha2565) => {
11078
+ afn(sha2565);
11079
+ const _sha256 = sha2565;
11080
11080
  return /* @__PURE__ */ chain(checksum(4, (data) => _sha256(_sha256(data))), base58);
11081
11081
  };
11082
11082
 
@@ -16068,7 +16068,7 @@ function Xi(e14) {
16068
16068
  return `authA${fe(C.fromString(t))}`;
16069
16069
  }
16070
16070
 
16071
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
16071
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
16072
16072
  import { createHash as createHash2 } from "crypto";
16073
16073
  import { existsSync, readFileSync, writeFileSync } from "fs";
16074
16074
  import {
@@ -18645,7 +18645,7 @@ zero
18645
18645
  zone
18646
18646
  zoo`.split("\n");
18647
18647
 
18648
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
18648
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
18649
18649
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
18650
18650
  import { existsSync as existsSync3, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
18651
18651
  import { createHash as createHash4 } from "crypto";
@@ -24769,7 +24769,7 @@ var BatchSettlementEvmScheme3 = class {
24769
24769
  }
24770
24770
  };
24771
24771
 
24772
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
24772
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
24773
24773
  import { randomBytes as randomBytes7, randomUUID as randomUUID22 } from "crypto";
24774
24774
  import { randomBytes as randomBytes22 } from "crypto";
24775
24775
 
@@ -27177,7 +27177,7 @@ function expand(hash3, prk, info2, length = 32) {
27177
27177
  }
27178
27178
  var hkdf = (hash3, ikm, salt, info2, length) => expand(hash3, extract(hash3, ikm, salt), info2, length);
27179
27179
 
27180
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
27180
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
27181
27181
  import {
27182
27182
  chmodSync as chmodSync3,
27183
27183
  existsSync as existsSync5,
@@ -27252,18 +27252,43 @@ var compose = (middleware, onError, onNotFound) => {
27252
27252
  // node_modules/hono/dist/request/constants.js
27253
27253
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
27254
27254
 
27255
+ // node_modules/hono/dist/utils/buffer.js
27256
+ var bufferToFormData = (arrayBuffer, contentType) => {
27257
+ const response = new Response(arrayBuffer, {
27258
+ headers: {
27259
+ // Normalize the media type (case-insensitive) while keeping parameters like the boundary
27260
+ "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())
27261
+ }
27262
+ });
27263
+ return response.formData();
27264
+ };
27265
+
27255
27266
  // node_modules/hono/dist/utils/body.js
27267
+ var isRawRequest = (request) => "headers" in request;
27256
27268
  var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
27257
27269
  const { all = false, dot = false } = options;
27258
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
27270
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
27259
27271
  const contentType = headers.get("Content-Type");
27260
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
27272
+ const mediaType = contentType?.split(";")[0].trim().toLowerCase();
27273
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") {
27261
27274
  return parseFormData(request, { all, dot });
27262
27275
  }
27263
27276
  return {};
27264
27277
  };
27265
27278
  async function parseFormData(request, options) {
27266
- const formData = await request.formData();
27279
+ if (!isRawRequest(request) && request.bodyCache.formData) {
27280
+ return convertFormDataToBodyData(
27281
+ await request.bodyCache.formData,
27282
+ options
27283
+ );
27284
+ }
27285
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
27286
+ const arrayBuffer = await request.arrayBuffer();
27287
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
27288
+ if (!isRawRequest(request)) {
27289
+ request.bodyCache.formData = formDataPromise;
27290
+ }
27291
+ const formData = await formDataPromise;
27267
27292
  if (formData) {
27268
27293
  return convertFormDataToBodyData(formData, options);
27269
27294
  }
@@ -27481,7 +27506,7 @@ var _getQueryParam = (url2, key, multiple) => {
27481
27506
  return void 0;
27482
27507
  }
27483
27508
  }
27484
- const results = {};
27509
+ const results = /* @__PURE__ */ Object.create(null);
27485
27510
  encoded ??= /[%+]/.test(url2);
27486
27511
  let keyIndex = url2.indexOf("?", 8);
27487
27512
  while (keyIndex !== -1) {
@@ -27602,7 +27627,7 @@ var HonoRequest = class {
27602
27627
  if (name) {
27603
27628
  return this.raw.headers.get(name) ?? void 0;
27604
27629
  }
27605
- const headerData = {};
27630
+ const headerData = /* @__PURE__ */ Object.create(null);
27606
27631
  this.raw.headers.forEach((value, key) => {
27607
27632
  headerData[key] = value;
27608
27633
  });
@@ -29200,6 +29225,15 @@ var Node2 = class _Node2 {
29200
29225
  if (m) {
29201
29226
  params[name] = m[0];
29202
29227
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
29228
+ if (m[0].length === restPathString.length && child.#children["*"]) {
29229
+ this.#pushHandlerSets(
29230
+ handlerSets,
29231
+ child.#children["*"],
29232
+ method,
29233
+ node.#params,
29234
+ params
29235
+ );
29236
+ }
29203
29237
  if (hasChildren(child.#children)) {
29204
29238
  child.#params = params;
29205
29239
  const componentCount = m[0].match(/\//)?.length ?? 0;
@@ -29279,7 +29313,7 @@ var Hono2 = class extends Hono {
29279
29313
  };
29280
29314
 
29281
29315
  // node_modules/hono/dist/utils/cookie.js
29282
- var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
29316
+ var relaxedCookieNameRegEx = /^[!#-:<>-[\]-~]+$/;
29283
29317
  var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
29284
29318
  var trimCookieWhitespace = (value) => {
29285
29319
  let start = 0;
@@ -29312,7 +29346,7 @@ var parse2 = (cookie, name) => {
29312
29346
  continue;
29313
29347
  }
29314
29348
  const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
29315
- if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) {
29349
+ if (name && name !== cookieName || !relaxedCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) {
29316
29350
  continue;
29317
29351
  }
29318
29352
  let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
@@ -29412,7 +29446,7 @@ var cors = (options) => {
29412
29446
  if (!headers?.length) {
29413
29447
  const requestHeaders = c.req.header("Access-Control-Request-Headers");
29414
29448
  if (requestHeaders) {
29415
- headers = requestHeaders.split(/\s*,\s*/);
29449
+ headers = requestHeaders.split(",").map((h2) => h2.trim());
29416
29450
  }
29417
29451
  }
29418
29452
  if (headers?.length) {
@@ -29534,16 +29568,17 @@ var SSEStreamingApi = class extends StreamingApi {
29534
29568
  const dataLines = data.split(/\r\n|\r|\n/).map((line) => {
29535
29569
  return `data: ${line}`;
29536
29570
  }).join("\n");
29537
- for (const key of ["event", "id", "retry"]) {
29538
- if (message[key] && /[\r\n]/.test(message[key])) {
29571
+ for (const key of ["event", "id"]) {
29572
+ const value = message[key];
29573
+ if (value && /[\r\n]/.test(value)) {
29539
29574
  throw new Error(`${key} must not contain "\\r" or "\\n"`);
29540
29575
  }
29541
29576
  }
29542
29577
  const sseData = [
29543
29578
  message.event && `event: ${message.event}`,
29544
29579
  dataLines,
29545
- message.id && `id: ${message.id}`,
29546
- message.retry && `retry: ${message.retry}`
29580
+ message.id !== void 0 && `id: ${message.id}`,
29581
+ message.retry !== void 0 && `retry: ${message.retry}`
29547
29582
  ].filter(Boolean).join("\n") + "\n\n";
29548
29583
  await this.write(sseData);
29549
29584
  }
@@ -29585,7 +29620,7 @@ var streamSSE = (c, cb, onError) => {
29585
29620
  return c.newResponse(stream2.responseReadable);
29586
29621
  };
29587
29622
 
29588
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
29623
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
29589
29624
  import { createHash as createHash7 } from "crypto";
29590
29625
 
29591
29626
  // node_modules/@noble/ciphers/utils.js
@@ -31121,7 +31156,7 @@ var getPublicKey2 = i2.getPublicKey;
31121
31156
  var finalizeEvent2 = i2.finalizeEvent;
31122
31157
  var verifyEvent2 = i2.verifyEvent;
31123
31158
 
31124
- // node_modules/@dvmkit/sdk/dist/chunk-CMDI3ENK.js
31159
+ // node_modules/@dvmkit/sdk/dist/chunk-Y6W5ZZTW.js
31125
31160
  import { createHash as createHash9 } from "crypto";
31126
31161
  function toLockPubkey(raw3) {
31127
31162
  return raw3.trim().toLowerCase();
@@ -51678,7 +51713,7 @@ async function makeInvoice(conn, params, opts = {}) {
51678
51713
  throw new NwcError("missing_payment_hash", "Wallet did not return a payment hash");
51679
51714
  }
51680
51715
  callerLoggers.lightning.info("lightning.make_invoice.result", {
51681
- payment_hash: tx.paymentHash
51716
+ payment_hash_hash: sha256hex(tx.paymentHash).slice(0, 16)
51682
51717
  });
51683
51718
  return tx;
51684
51719
  }
@@ -51690,7 +51725,7 @@ async function lookupInvoice(conn, params, opts = {}) {
51690
51725
  {
51691
51726
  relays: conn.relays.join(","),
51692
51727
  wallet_pubkey: conn.walletPubkey,
51693
- payment_hash: params.paymentHash
51728
+ payment_hash_hash: params.paymentHash ? sha256hex(params.paymentHash).slice(0, 16) : void 0
51694
51729
  },
51695
51730
  async () => {
51696
51731
  const body = {};
@@ -51704,6 +51739,31 @@ async function lookupInvoice(conn, params, opts = {}) {
51704
51739
  }
51705
51740
  );
51706
51741
  }
51742
+ async function listTransactions(conn, options, opts = {}) {
51743
+ return callerLoggers.lightning.span(
51744
+ "lightning.list_transactions",
51745
+ {
51746
+ relays: conn.relays.join(","),
51747
+ wallet_pubkey: conn.walletPubkey,
51748
+ from: options.from,
51749
+ limit: options.limit
51750
+ },
51751
+ async () => {
51752
+ const body = {};
51753
+ if (options.from !== void 0) body.from = options.from;
51754
+ if (options.limit !== void 0) body.limit = options.limit;
51755
+ const result = await sendNwcRequest(conn, "list_transactions", body, opts);
51756
+ if (!Array.isArray(result.transactions)) {
51757
+ throw new NwcError("invalid_response", "Wallet did not return a transaction list.");
51758
+ }
51759
+ const transactions = result.transactions.map(toTransactionSnapshot);
51760
+ callerLoggers.lightning.info("lightning.list_transactions.result", {
51761
+ transaction_count: transactions.length
51762
+ });
51763
+ return transactions;
51764
+ }
51765
+ );
51766
+ }
51707
51767
  var VOLUNTEERED_BUDGET_KEYS = [
51708
51768
  "budget",
51709
51769
  "budget_renewal",
@@ -51753,6 +51813,7 @@ async function attemptPayment(conn, method, event, pool, timeoutMs) {
51753
51813
  async function reconcile(conn, bolt11, pool, timeoutMs) {
51754
51814
  try {
51755
51815
  const tx = await lookupInvoice(conn, { invoice: bolt11 }, { pool, timeoutMs });
51816
+ if (tx.invoice !== bolt11) return { kind: "unknown" };
51756
51817
  if (tx.settledAt != null && tx.preimage) {
51757
51818
  return {
51758
51819
  kind: "settled",
@@ -51892,7 +51953,46 @@ function toTransaction(raw3) {
51892
51953
  ...feesPaidMsats !== void 0 ? { feesPaidMsats } : {},
51893
51954
  createdAt: raw3.created_at ?? Math.floor(Date.now() / 1e3),
51894
51955
  expiresAt: raw3.expires_at,
51895
- settledAt: raw3.settled_at
51956
+ settledAt: raw3.settled_at ?? void 0
51957
+ };
51958
+ }
51959
+ function toTransactionSnapshot(value) {
51960
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
51961
+ throw new NwcError("invalid_response", "Wallet returned a malformed transaction.");
51962
+ }
51963
+ const raw3 = value;
51964
+ if (raw3.type !== "incoming" && raw3.type !== "outgoing") {
51965
+ throw new NwcError("invalid_response", "Wallet returned an invalid transaction type.");
51966
+ }
51967
+ const amountMsats = requiredNonNegativeInteger(raw3.amount, "amount");
51968
+ const createdAt = requiredNonNegativeInteger(raw3.created_at, "creation time");
51969
+ const feesPaidMsats = optionalFeeMsats(raw3.fees_paid);
51970
+ if (raw3.fees_paid != null && feesPaidMsats === void 0) {
51971
+ throw new NwcError("invalid_response", "Wallet returned an invalid transaction fee.");
51972
+ }
51973
+ const settledAt = optionalNonNegativeInteger(raw3.settled_at);
51974
+ if (raw3.settled_at != null && settledAt === void 0) {
51975
+ throw new NwcError("invalid_response", "Wallet returned an invalid settlement time.");
51976
+ }
51977
+ const invoice = optionalPrivateString(raw3.invoice, "invoice");
51978
+ const paymentHash = optionalPrivateString(raw3.payment_hash, "payment hash");
51979
+ const reducedIdentity = {
51980
+ type: raw3.type,
51981
+ invoice: invoice ?? null,
51982
+ paymentHash: paymentHash ?? null,
51983
+ amountMsats,
51984
+ feesPaidMsats: feesPaidMsats ?? null,
51985
+ createdAt,
51986
+ settledAt: settledAt ?? null
51987
+ };
51988
+ return {
51989
+ fingerprint: sha256hex(JSON.stringify(reducedIdentity)),
51990
+ ...invoice ? { invoiceHash: sha256hex(invoice) } : {},
51991
+ type: raw3.type,
51992
+ amountMsats,
51993
+ ...feesPaidMsats !== void 0 ? { feesPaidMsats } : {},
51994
+ createdAt,
51995
+ ...settledAt !== void 0 ? { settledAt } : {}
51896
51996
  };
51897
51997
  }
51898
51998
  function settledOutcome(payment, outcome) {
@@ -51905,6 +52005,23 @@ function settledOutcome(payment, outcome) {
51905
52005
  function optionalFeeMsats(value) {
51906
52006
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
51907
52007
  }
52008
+ function optionalNonNegativeInteger(value) {
52009
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
52010
+ }
52011
+ function requiredNonNegativeInteger(value, field) {
52012
+ const parsed = optionalNonNegativeInteger(value);
52013
+ if (parsed === void 0) {
52014
+ throw new NwcError("invalid_response", `Wallet returned an invalid transaction ${field}.`);
52015
+ }
52016
+ return parsed;
52017
+ }
52018
+ function optionalPrivateString(value, field) {
52019
+ if (value === void 0 || value === null) return void 0;
52020
+ if (typeof value !== "string" || value.length === 0) {
52021
+ throw new NwcError("invalid_response", `Wallet returned an invalid transaction ${field}.`);
52022
+ }
52023
+ return value;
52024
+ }
51908
52025
  async function publishEvent(pool, relays, event) {
51909
52026
  const connections = await Promise.allSettled(relays.map((url2) => pool.ensureRelay(url2)));
51910
52027
  const live = connections.flatMap((c) => c.status === "fulfilled" ? [c.value] : []);
@@ -51987,6 +52104,9 @@ var NwcBackend = class {
51987
52104
  expiresAt: tx.expiresAt != null ? tx.expiresAt * 1e3 : void 0
51988
52105
  };
51989
52106
  }
52107
+ async listTransactions(options) {
52108
+ return listTransactions(this.conn, options, this.opts);
52109
+ }
51990
52110
  };
51991
52111
  var TEMPO_OBSERVER_HEALTH_REFRESH_TTL_MS = 60 * 1e3;
51992
52112
  var TEMPO_OBSERVER_HEALTH_MAX_CURSOR_AGE_MS = 2 * 60 * 1e3;
@@ -52154,6 +52274,10 @@ function appendSpend(ledger, opts) {
52154
52274
  if (opts.kind !== void 0 && opts.kind !== "job") entry.kind = opts.kind;
52155
52275
  if (opts.principalMsats !== void 0) entry.principalMsats = opts.principalMsats;
52156
52276
  if (opts.routingFeeMsats !== void 0) entry.routingFeeMsats = opts.routingFeeMsats;
52277
+ if (opts.totalWalletFeeMsats !== void 0)
52278
+ entry.totalWalletFeeMsats = opts.totalWalletFeeMsats;
52279
+ if (opts.unitemizedWalletFeeMsats !== void 0)
52280
+ entry.unitemizedWalletFeeMsats = opts.unitemizedWalletFeeMsats;
52157
52281
  if (opts.walletDebitMsats !== void 0) entry.walletDebitMsats = opts.walletDebitMsats;
52158
52282
  if (opts.label !== void 0) entry.label = opts.label;
52159
52283
  if (opts.labelSource !== void 0) entry.labelSource = opts.labelSource;
@@ -52334,15 +52458,29 @@ function floatPaymentJson(payment) {
52334
52458
  outcome: payment.outcome,
52335
52459
  principal_sats: payment.principalMsats / 1e3,
52336
52460
  routing_fee_sats: payment.routingFeeMsats === null ? null : payment.routingFeeMsats / 1e3,
52461
+ total_wallet_fee_sats: payment.totalWalletFeeMsats === null ? null : payment.totalWalletFeeMsats / 1e3,
52462
+ unitemized_wallet_fee_sats: payment.unitemizedWalletFeeMsats === null ? null : payment.unitemizedWalletFeeMsats / 1e3,
52337
52463
  wallet_debit_sats: payment.walletDebitMsats === null ? null : payment.walletDebitMsats / 1e3
52338
52464
  };
52339
52465
  }
52340
52466
  function floatPaymentDisplay(payment) {
52341
52467
  const principal = formatSats2(payment.principalMsats);
52342
- if (payment.routingFeeMsats === null || payment.walletDebitMsats === null) {
52343
- return `Invoice principal ${principal}; the wallet did not report its routing fee, so the total wallet debit is unknown.`;
52468
+ if (payment.walletDebitMsats === null) {
52469
+ const routing2 = payment.routingFeeMsats === null ? "The wallet did not report its routing fee." : `The wallet reported ${formatSats2(payment.routingFeeMsats)} of routing fee.`;
52470
+ return `Invoice principal ${principal}; the total wallet debit and total wallet fee are unknown. ${routing2}`;
52471
+ }
52472
+ if (payment.totalWalletFeeMsats === null) {
52473
+ return `${formatSats2(payment.walletDebitMsats)} went out for invoice principal ${principal}; the total wallet fee is unknown.`;
52344
52474
  }
52345
- return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} plus ${formatSats2(payment.routingFeeMsats)} routing fee.`;
52475
+ const totalFee = formatSats2(payment.totalWalletFeeMsats);
52476
+ if (payment.routingFeeMsats === null) {
52477
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet did not report its routing fee, so the fee split is unknown.`;
52478
+ }
52479
+ const routing = formatSats2(payment.routingFeeMsats);
52480
+ if (payment.unitemizedWalletFeeMsats === null) {
52481
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet reported ${routing} of routing fee; the remaining fee split is unknown.`;
52482
+ }
52483
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee} (${routing} wallet-reported routing fee and ${formatSats2(payment.unitemizedWalletFeeMsats)} unitemized wallet fee).`;
52346
52484
  }
52347
52485
  function unrecordedFloatBudgetWarning(float) {
52348
52486
  if (float.statedBudget) return void 0;
@@ -52419,15 +52557,17 @@ async function assertFloatBudget(plannedMsats) {
52419
52557
  return enforceGlobalBudget({ plannedMsats });
52420
52558
  }
52421
52559
  function recordFloatSpend(params) {
52422
- const walletDebitMsats = params.routingFeeMsats === null ? null : params.principalMsats + params.routingFeeMsats;
52560
+ const walletDebitMsats = params.walletDebitMsats ?? null;
52423
52561
  recordSpend({
52424
52562
  kind: "float_fund",
52425
52563
  // The legacy `msats` field drives cap arithmetic. Use the exact debit when
52426
- // the wallet supplied its fee; otherwise retain the known principal and
52564
+ // read-only evidence proved it; otherwise retain the known principal and
52427
52565
  // mark the total unknown in the component fields below.
52428
52566
  msats: walletDebitMsats ?? params.principalMsats,
52429
52567
  principalMsats: params.principalMsats,
52430
52568
  routingFeeMsats: params.routingFeeMsats,
52569
+ totalWalletFeeMsats: params.totalWalletFeeMsats ?? null,
52570
+ unitemizedWalletFeeMsats: params.unitemizedWalletFeeMsats ?? null,
52431
52571
  walletDebitMsats,
52432
52572
  btcRate: params.btcRate,
52433
52573
  jobId: params.reference,
@@ -52437,21 +52577,127 @@ function recordFloatSpend(params) {
52437
52577
  }
52438
52578
  async function payViaFloat(params) {
52439
52579
  try {
52440
- const payment = await backendFor(params.float, { timeoutMs: params.timeoutMs }).payInvoice(
52441
- params.bolt11,
52442
- params.amountMsats
52580
+ return await withNwcPool(
52581
+ params.float.conn,
52582
+ (opts) => payViaLightningBackend({
52583
+ bolt11: params.bolt11,
52584
+ amountMsats: params.amountMsats,
52585
+ backend: backendFor(params.float, opts)
52586
+ }),
52587
+ params.timeoutMs
52443
52588
  );
52444
- const routingFeeMsats = payment.feesPaidMsats ?? null;
52445
- return {
52446
- outcome: payment.outcome,
52447
- principalMsats: params.amountMsats,
52448
- routingFeeMsats,
52449
- walletDebitMsats: routingFeeMsats === null ? null : params.amountMsats + routingFeeMsats
52450
- };
52451
52589
  } catch (err) {
52452
52590
  throw toFloatError(err);
52453
52591
  }
52454
52592
  }
52593
+ var FLOAT_TRANSACTION_LIMIT = 100;
52594
+ var FLOAT_HISTORY_LOOKBACK_SECONDS = 300;
52595
+ async function payViaLightningBackend(params) {
52596
+ const now = params.now ?? (() => Date.now());
52597
+ const historyFrom = Math.max(
52598
+ 0,
52599
+ Math.floor(now() / 1e3) - FLOAT_HISTORY_LOOKBACK_SECONDS
52600
+ );
52601
+ const before = await stableWalletSnapshot(params.backend, historyFrom);
52602
+ const payment = await params.backend.payInvoice(params.bolt11, params.amountMsats);
52603
+ const fallback = paymentWithoutAuthoritativeDebit(payment, params.amountMsats);
52604
+ if (!before) return fallback;
52605
+ const after = await stableWalletSnapshot(params.backend, historyFrom);
52606
+ if (!after) return fallback;
52607
+ return paymentFromEvidence(params, payment, before, after);
52608
+ }
52609
+ function paymentWithoutAuthoritativeDebit(payment, principalMsats) {
52610
+ return {
52611
+ outcome: payment.outcome,
52612
+ principalMsats,
52613
+ routingFeeMsats: payment.feesPaidMsats ?? null,
52614
+ totalWalletFeeMsats: null,
52615
+ unitemizedWalletFeeMsats: null,
52616
+ walletDebitMsats: null
52617
+ };
52618
+ }
52619
+ async function stableWalletSnapshot(backend, from) {
52620
+ if (!backend.listTransactions) return void 0;
52621
+ try {
52622
+ const first = await walletSnapshot(backend, from);
52623
+ const second = await walletSnapshot(backend, from);
52624
+ return sameWalletSnapshot(first, second) ? second : void 0;
52625
+ } catch {
52626
+ return void 0;
52627
+ }
52628
+ }
52629
+ async function walletSnapshot(backend, from) {
52630
+ const balanceMsats = await backend.getBalance();
52631
+ if (!Number.isSafeInteger(balanceMsats) || balanceMsats < 0) {
52632
+ throw new NwcError("invalid_response", "Wallet returned an invalid balance.");
52633
+ }
52634
+ const transactions = await backend.listTransactions({
52635
+ from,
52636
+ limit: FLOAT_TRANSACTION_LIMIT + 1
52637
+ });
52638
+ if (transactions.length > FLOAT_TRANSACTION_LIMIT) {
52639
+ throw new NwcError("invalid_response", "Wallet transaction snapshot exceeded its limit.");
52640
+ }
52641
+ return {
52642
+ balanceMsats,
52643
+ transactions: [...transactions].sort(
52644
+ (left, right) => left.fingerprint.localeCompare(right.fingerprint)
52645
+ )
52646
+ };
52647
+ }
52648
+ function sameWalletSnapshot(left, right) {
52649
+ return left.balanceMsats === right.balanceMsats && left.transactions.length === right.transactions.length && left.transactions.every(
52650
+ (transaction, index) => transaction.fingerprint === right.transactions[index]?.fingerprint
52651
+ );
52652
+ }
52653
+ function paymentFromEvidence(params, payment, before, after) {
52654
+ const fallback = paymentWithoutAuthoritativeDebit(payment, params.amountMsats);
52655
+ const appended = appendedTransactions(before.transactions, after.transactions);
52656
+ if (appended.length !== 1) return fallback;
52657
+ const transaction = appended[0];
52658
+ if (transaction.type !== "outgoing" || transaction.invoiceHash !== sha256hex(params.bolt11) || transaction.amountMsats !== params.amountMsats || transaction.settledAt === void 0) {
52659
+ return fallback;
52660
+ }
52661
+ const responseRoutingFee = payment.feesPaidMsats;
52662
+ const historyRoutingFee = transaction.feesPaidMsats;
52663
+ if (responseRoutingFee !== void 0 && historyRoutingFee !== void 0 && responseRoutingFee !== historyRoutingFee) {
52664
+ return fallback;
52665
+ }
52666
+ const routingFeeMsats = historyRoutingFee ?? responseRoutingFee ?? null;
52667
+ const walletDebitMsats = before.balanceMsats - after.balanceMsats;
52668
+ if (!Number.isSafeInteger(walletDebitMsats) || walletDebitMsats < params.amountMsats) {
52669
+ return fallback;
52670
+ }
52671
+ const totalWalletFeeMsats = walletDebitMsats - params.amountMsats;
52672
+ if (routingFeeMsats !== null && routingFeeMsats > totalWalletFeeMsats) return fallback;
52673
+ return {
52674
+ outcome: payment.outcome,
52675
+ principalMsats: params.amountMsats,
52676
+ routingFeeMsats,
52677
+ totalWalletFeeMsats,
52678
+ unitemizedWalletFeeMsats: routingFeeMsats === null ? null : totalWalletFeeMsats - routingFeeMsats,
52679
+ walletDebitMsats
52680
+ };
52681
+ }
52682
+ function appendedTransactions(before, after) {
52683
+ const remaining = /* @__PURE__ */ new Map();
52684
+ for (const transaction of before) {
52685
+ remaining.set(transaction.fingerprint, (remaining.get(transaction.fingerprint) ?? 0) + 1);
52686
+ }
52687
+ const nextCounts = /* @__PURE__ */ new Map();
52688
+ for (const transaction of after) {
52689
+ nextCounts.set(transaction.fingerprint, (nextCounts.get(transaction.fingerprint) ?? 0) + 1);
52690
+ }
52691
+ if ([...remaining].some(([fingerprint, count]) => (nextCounts.get(fingerprint) ?? 0) < count)) {
52692
+ return [];
52693
+ }
52694
+ return after.filter((transaction) => {
52695
+ const count = remaining.get(transaction.fingerprint) ?? 0;
52696
+ if (count === 0) return true;
52697
+ remaining.set(transaction.fingerprint, count - 1);
52698
+ return false;
52699
+ });
52700
+ }
52455
52701
  async function fundViaFloat(params) {
52456
52702
  const float = params.float ?? requireFloat();
52457
52703
  const btcRate = await assertFloatBudget(params.amountMsats);
@@ -52464,6 +52710,9 @@ async function fundViaFloat(params) {
52464
52710
  recordFloatSpend({
52465
52711
  principalMsats: payment.principalMsats,
52466
52712
  routingFeeMsats: payment.routingFeeMsats,
52713
+ totalWalletFeeMsats: payment.totalWalletFeeMsats,
52714
+ unitemizedWalletFeeMsats: payment.unitemizedWalletFeeMsats,
52715
+ walletDebitMsats: payment.walletDebitMsats,
52467
52716
  btcRate,
52468
52717
  reference: params.reference,
52469
52718
  counterparty: params.counterparty,
@@ -59691,6 +59940,8 @@ async function fundOverLightning(args, fundId, resumed) {
59691
59940
  ...pending,
59692
59941
  principalMsats: payment.principalMsats,
59693
59942
  routingFeeMsats: payment.routingFeeMsats,
59943
+ totalWalletFeeMsats: payment.totalWalletFeeMsats,
59944
+ unitemizedWalletFeeMsats: payment.unitemizedWalletFeeMsats,
59694
59945
  walletDebitMsats: payment.walletDebitMsats,
59695
59946
  paymentOutcome: payment.outcome
59696
59947
  };
@@ -59837,6 +60088,8 @@ function lightningSpend(payment) {
59837
60088
  ...walletDebitSats !== null ? { spentSats: walletDebitSats } : {},
59838
60089
  principalSats: payment.principalMsats / 1e3,
59839
60090
  routingFeeSats: payment.routingFeeMsats === null ? null : payment.routingFeeMsats / 1e3,
60091
+ totalWalletFeeSats: payment.totalWalletFeeMsats === null ? null : payment.totalWalletFeeMsats / 1e3,
60092
+ unitemizedWalletFeeSats: payment.unitemizedWalletFeeMsats === null ? null : payment.unitemizedWalletFeeMsats / 1e3,
59840
60093
  walletDebitSats,
59841
60094
  paymentOutcome: payment.outcome
59842
60095
  };
@@ -59849,16 +60102,28 @@ function lightningSpendFromPending(pending) {
59849
60102
  ...walletDebitSats !== null ? { spentSats: walletDebitSats } : {},
59850
60103
  principalSats: pending.principalMsats / 1e3,
59851
60104
  routingFeeSats: pending.routingFeeMsats == null ? null : pending.routingFeeMsats / 1e3,
60105
+ totalWalletFeeSats: pending.totalWalletFeeMsats == null ? null : pending.totalWalletFeeMsats / 1e3,
60106
+ unitemizedWalletFeeSats: pending.unitemizedWalletFeeMsats == null ? null : pending.unitemizedWalletFeeMsats / 1e3,
59852
60107
  walletDebitSats,
59853
60108
  paymentOutcome: pending.paymentOutcome
59854
60109
  };
59855
60110
  }
59856
60111
  function lightningSpendDisplay(spend) {
59857
60112
  const principal = spend.principalSats ?? 0;
59858
- if (spend.routingFeeSats == null || spend.walletDebitSats == null) {
59859
- return `Invoice principal ${String(principal)} sats; the wallet did not report its routing fee, so the total wallet debit is unknown.`;
60113
+ if (spend.walletDebitSats == null) {
60114
+ const routing = spend.routingFeeSats == null ? "The wallet did not report its routing fee." : `The wallet reported ${String(spend.routingFeeSats)} sats of routing fee.`;
60115
+ return `Invoice principal ${String(principal)} sats; the total wallet debit and total wallet fee are unknown. ${routing}`;
60116
+ }
60117
+ if (spend.totalWalletFeeSats == null) {
60118
+ return `${String(spend.walletDebitSats)} sats went out for invoice principal ${String(principal)} sats; the total wallet fee is unknown.`;
60119
+ }
60120
+ if (spend.routingFeeSats == null) {
60121
+ return `${String(spend.walletDebitSats)} sats went out: invoice principal ${String(principal)} sats and total wallet fee ${String(spend.totalWalletFeeSats)} sats. The wallet did not report its routing fee, so the fee split is unknown.`;
60122
+ }
60123
+ if (spend.unitemizedWalletFeeSats == null) {
60124
+ return `${String(spend.walletDebitSats)} sats went out: invoice principal ${String(principal)} sats and total wallet fee ${String(spend.totalWalletFeeSats)} sats. The wallet reported ${String(spend.routingFeeSats)} sats of routing fee; the remaining fee split is unknown.`;
59860
60125
  }
59861
- return `${String(spend.walletDebitSats)} sats went out: invoice principal ${String(principal)} sats plus ${String(spend.routingFeeSats)} sats routing fee.`;
60126
+ return `${String(spend.walletDebitSats)} sats went out: invoice principal ${String(principal)} sats and total wallet fee ${String(spend.totalWalletFeeSats)} sats (${String(spend.routingFeeSats)} sats wallet-reported routing fee and ${String(spend.unitemizedWalletFeeSats)} sats unitemized wallet fee).`;
59862
60127
  }
59863
60128
  function lightningCreditBody(pending) {
59864
60129
  return {
@@ -60937,6 +61202,7 @@ export {
60937
61202
  getInfo,
60938
61203
  makeInvoice,
60939
61204
  lookupInvoice,
61205
+ listTransactions,
60940
61206
  NwcBackend,
60941
61207
  loadLedger,
60942
61208
  saveLedger,