@antseed/node 0.2.178 → 0.2.180

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.
Files changed (50) hide show
  1. package/README.md +2 -2
  2. package/dist/gateway-process.d.ts +11 -0
  3. package/dist/gateway-process.d.ts.map +1 -0
  4. package/dist/gateway-process.js +20 -0
  5. package/dist/gateway-process.js.map +1 -0
  6. package/dist/health/gas-auto-refuel.d.ts +3 -2
  7. package/dist/health/gas-auto-refuel.d.ts.map +1 -1
  8. package/dist/health/gas-auto-refuel.js +6 -6
  9. package/dist/health/gas-auto-refuel.js.map +1 -1
  10. package/dist/health/stream-outcome.d.ts.map +1 -1
  11. package/dist/health/stream-outcome.js +1 -3
  12. package/dist/health/stream-outcome.js.map +1 -1
  13. package/dist/index.d.ts +2 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/model-identity.d.ts +10 -12
  18. package/dist/model-identity.d.ts.map +1 -1
  19. package/dist/model-identity.js +14 -71
  20. package/dist/model-identity.js.map +1 -1
  21. package/dist/node.d.ts.map +1 -1
  22. package/dist/node.js +12 -1
  23. package/dist/node.js.map +1 -1
  24. package/dist/p2p/identity.js +1 -1
  25. package/dist/p2p/identity.js.map +1 -1
  26. package/dist/payments/channel-store.d.ts +8 -0
  27. package/dist/payments/channel-store.d.ts.map +1 -1
  28. package/dist/payments/channel-store.js +21 -0
  29. package/dist/payments/channel-store.js.map +1 -1
  30. package/dist/payments/seller-payment-manager.d.ts +65 -2
  31. package/dist/payments/seller-payment-manager.d.ts.map +1 -1
  32. package/dist/payments/seller-payment-manager.js +215 -16
  33. package/dist/payments/seller-payment-manager.js.map +1 -1
  34. package/dist/proxy/request-path.d.ts +8 -0
  35. package/dist/proxy/request-path.d.ts.map +1 -0
  36. package/dist/proxy/request-path.js +15 -0
  37. package/dist/proxy/request-path.js.map +1 -0
  38. package/dist/requested-service.d.ts +38 -7
  39. package/dist/requested-service.d.ts.map +1 -1
  40. package/dist/requested-service.js +350 -13
  41. package/dist/requested-service.js.map +1 -1
  42. package/dist/retail-prices.d.ts +44 -0
  43. package/dist/retail-prices.d.ts.map +1 -0
  44. package/dist/retail-prices.js +86 -0
  45. package/dist/retail-prices.js.map +1 -0
  46. package/dist/seller-request-handler.d.ts +13 -0
  47. package/dist/seller-request-handler.d.ts.map +1 -1
  48. package/dist/seller-request-handler.js +126 -19
  49. package/dist/seller-request-handler.js.map +1 -1
  50. package/package.json +12 -4
@@ -57,6 +57,23 @@ export const ONE_OFF_CHANNEL_TTL_MS = 24 * 60 * 60_000;
57
57
  export const RESERVE_VISIBILITY_GRACE_MS = 5 * 60_000;
58
58
  /** A one-off channel whose request never started is closed after this long. */
59
59
  export const ONE_OFF_UNCLAIMED_TTL_MS = 10 * 60_000;
60
+ /**
61
+ * Most one-off channels a buyer may have earning the seller nothing: ended
62
+ * unpaid since it last paid for a video, or still without an accepted create.
63
+ * Each costs the seller a reserve and a close, so at this many the buyer waits
64
+ * for another. Plans it has not answered count too, so parallel creates cannot
65
+ * overshoot. Above the video plugins' default concurrency of 10.
66
+ */
67
+ const ONE_OFF_UNPAID_LIMIT = 16;
68
+ /** Earnings below this (USDC base units, $0.01: a fixed floor above the usual gas of a reserve and a close on Base) leave a channel unpaid. */
69
+ const ONE_OFF_MIN_EARNED_USDC = 10_000;
70
+ /** Wait for another channel once a buyer is at the limit. Doubles with each further unpaid channel. */
71
+ const ONE_OFF_BACKOFF_BASE_MS = 60_000;
72
+ const ONE_OFF_BACKOFF_MAX_MS = 60 * 60_000;
73
+ /** Channels that ended longer ago than this stop counting against the buyer. */
74
+ const ONE_OFF_UNPAID_WINDOW_MS = 24 * 60 * 60_000;
75
+ /** Retry-after while a buyer is held back only by creates still being decided, which end in seconds. */
76
+ const ONE_OFF_UNDECIDED_RETRY_SECONDS = 5;
60
77
  /** How often channels whose close was given up on are retried. */
61
78
  export const TIMED_OUT_CLOSE_RETRY_INTERVAL_MS = 10 * 60_000;
62
79
  /** Most timed-out channels retried in one pass. */
@@ -87,6 +104,7 @@ export class SellerPaymentManager {
87
104
  */
88
105
  _activeBuyers = new Set();
89
106
  _buyerDisconnectMarkers = new Map();
107
+ _paymentMuxFor;
90
108
  /** Channels restored from disk before the buyer has proven it reconnected. */
91
109
  _hydratedChannelIds = new Set();
92
110
  /** Per-buyer mutex to prevent concurrent handleSpendingAuth for the same buyer. */
@@ -127,8 +145,12 @@ export class SellerPaymentManager {
127
145
  * before a retry succeeds, we keep the most recent higher ceiling because it
128
146
  * subsumes the older request. */
129
147
  _pendingTopUp = new Map();
148
+ /** Channels whose stored top-up could not be checked at startup (RPC failed): the periodic check restores it. */
149
+ _topUpRestoreDeferred = new Set();
130
150
  /** Channels with a background topUp() running, and those asked for another meanwhile. */
131
151
  _topUpsRunning = new Map();
152
+ /** Set once a stopping node closed its connections: nothing finished after it reaches a buyer. */
153
+ _connectionsClosed = false;
132
154
  _topUpsWanted = new Set();
133
155
  /** channelId -> ceiling of the topUp() being submitted now. */
134
156
  _topUpInFlight = new Map();
@@ -164,6 +186,8 @@ export class SellerPaymentManager {
164
186
  * closed on disconnect, and never supersede the buyer's session channel.
165
187
  */
166
188
  _oneOffChannelIds = new Set();
189
+ /** One-off channel -> buyer, from the reserve until its create is accepted or the channel ends. */
190
+ _unacceptedOneOffs = new Map();
167
191
  _minSettleDelta;
168
192
  _serveWhileClosePending;
169
193
  /** Max close() retries before giving up (buyer must requestClose on-chain) */
@@ -172,8 +196,11 @@ export class SellerPaymentManager {
172
196
  _lastTimedOutCloseRetryAt = 0;
173
197
  /** Slow-cadence close attempts per timed-out channel, using the buyer's latest auth. */
174
198
  _timedOutCloseAttempts = new Map();
175
- constructor(identity, config, channelStore) {
199
+ constructor(identity, config, channelStore,
200
+ /** The buyer's live payment connection, if it is connected; the node owns these. */
201
+ paymentMuxFor) {
176
202
  this._config = config;
203
+ this._paymentMuxFor = paymentMuxFor;
177
204
  this._signer = identity.wallet;
178
205
  const channelsClient = new ChannelsClient({
179
206
  rpcUrl: config.rpcUrl,
@@ -223,6 +250,9 @@ export class SellerPaymentManager {
223
250
  }
224
251
  for (const channel of this._channelStore.getActiveChannels(CHANNEL_ROLE.SELLER, CHANNEL_KIND.ONE_OFF)) {
225
252
  this._oneOffChannelIds.add(channel.sessionId);
253
+ // A channel whose create has started may be a running job, which must not count: nothing here tells them apart.
254
+ if (channel.requestCount === 0)
255
+ this._unacceptedOneOffs.set(channel.sessionId, channel.peerId);
226
256
  this._acceptedCumulative.set(channel.sessionId, BigInt(channel.authMax || '0'));
227
257
  this._spent.set(channel.sessionId, BigInt(channel.tokensDelivered || '0'));
228
258
  this._reserveMax.set(channel.sessionId, BigInt(channel.previousConsumption || '0'));
@@ -288,10 +318,13 @@ export class SellerPaymentManager {
288
318
  debugLog(`[SellerPayment] Reconciled spent for ${channel.sessionId.slice(0, 18)}...: local=${localSpent} → on-chain=${onChainSettled}`);
289
319
  }
290
320
  }
321
+ this._restorePendingTopUp(channel, onChainState.channel.deposit);
291
322
  }
292
323
  catch (err) {
293
324
  debugWarn(`[SellerPayment] Failed to validate channel ${channel.sessionId.slice(0, 18)}...: ${err instanceof Error ? err.message : err}`);
294
325
  // Keep channel hydrated on RPC failure — periodic check will retry
326
+ if (channel.latestReserveAuthSig)
327
+ this._topUpRestoreDeferred.add(channel.sessionId);
295
328
  }
296
329
  }
297
330
  if (evicted > 0) {
@@ -302,8 +335,8 @@ export class SellerPaymentManager {
302
335
  _mayNotBeVisibleYet(channel) {
303
336
  return Date.now() - channel.reservedAt < RESERVE_VISIBILITY_GRACE_MS;
304
337
  }
305
- _evictStaleChannel(channelId, peerId, reason, status = CHANNEL_STATUS.SETTLED) {
306
- this._channelStore.updateChannelStatus(channelId, status);
338
+ _evictStaleChannel(channelId, peerId, reason, status = CHANNEL_STATUS.SETTLED, settledAmount) {
339
+ this._channelStore.updateChannelStatus(channelId, status, settledAmount);
307
340
  this._acceptedCumulative.delete(channelId);
308
341
  this._spent.delete(channelId);
309
342
  this._latestAuth.delete(channelId);
@@ -313,6 +346,7 @@ export class SellerPaymentManager {
313
346
  this._pendingTopUp.delete(channelId);
314
347
  this._blockedChannels.delete(channelId);
315
348
  this._lastSettledCumulative.delete(channelId);
349
+ this._unacceptedOneOffs.delete(channelId);
316
350
  this._releaseAcceptedWaiters(channelId);
317
351
  if (!this._oneOffChannelIds.delete(channelId))
318
352
  this._deactivateBuyerForChannel(peerId, channelId);
@@ -789,19 +823,57 @@ export class SellerPaymentManager {
789
823
  * Offer a one-off channel for a single request (a video create). The plan is
790
824
  * what the buyer must sign; the opening SpendingAuth is only accepted when it
791
825
  * matches a plan this seller offered for the same buyer and requestId.
826
+ * Returns null once offered, or, offering nothing, the seconds the buyer must
827
+ * wait (see oneOffRetryAfterSeconds).
792
828
  */
793
829
  registerOneOffPlan(buyerPeerId, requestId, plan) {
794
- const now = Date.now();
795
- for (const [key, pending] of this._pendingOneOffPlans) {
796
- if (pending.expiresAt <= now)
797
- this._pendingOneOffPlans.delete(key);
798
- }
830
+ const retryAfterSeconds = this.oneOffRetryAfterSeconds(buyerPeerId, requestId);
831
+ if (retryAfterSeconds !== null)
832
+ return retryAfterSeconds;
799
833
  this._pendingOneOffPlans.set(oneOffPlanKey(buyerPeerId, requestId), {
800
834
  openingReserveAmount: BigInt(plan.openingReserveAmount),
801
835
  requiredCumulativeAmount: BigInt(plan.requiredCumulativeAmount),
802
836
  requestCost: BigInt(plan.requestCost),
803
- expiresAt: now + ONE_OFF_PLAN_TTL_MS,
837
+ expiresAt: Date.now() + ONE_OFF_PLAN_TTL_MS,
804
838
  });
839
+ return null;
840
+ }
841
+ /**
842
+ * Seconds this buyer must wait for another one-off channel, or null when it
843
+ * may have one now. The seller pays for every channel before its provider
844
+ * sees the create, so a buyer whose creates keep ending without a job would
845
+ * otherwise spend the seller's gas for nothing. Offering a request its own
846
+ * plan again adds nothing, so `requestId` is left out of the count.
847
+ */
848
+ oneOffRetryAfterSeconds(buyerPeerId, requestId) {
849
+ const now = Date.now();
850
+ const buyerPlans = oneOffPlanKey(buyerPeerId, '');
851
+ const thisPlan = oneOffPlanKey(buyerPeerId, requestId);
852
+ let undecided = 0;
853
+ for (const [key, pending] of this._pendingOneOffPlans) {
854
+ if (pending.expiresAt <= now)
855
+ this._pendingOneOffPlans.delete(key);
856
+ else if (key.startsWith(buyerPlans) && key !== thisPlan)
857
+ undecided += 1;
858
+ }
859
+ for (const buyer of this._unacceptedOneOffs.values()) {
860
+ if (buyer === buyerPeerId)
861
+ undecided += 1;
862
+ }
863
+ const { count, lastEndedAt } = this._channelStore.getUnpaidOneOffChannels(buyerPeerId, CHANNEL_ROLE.SELLER, now - ONE_OFF_UNPAID_WINDOW_MS, ONE_OFF_MIN_EARNED_USDC);
864
+ if (count + undecided < ONE_OFF_UNPAID_LIMIT)
865
+ return null;
866
+ // At the limit a buyer gets one channel at a time, each after a longer wait.
867
+ const waitMs = count < ONE_OFF_UNPAID_LIMIT
868
+ ? 0
869
+ : lastEndedAt + Math.min(ONE_OFF_BACKOFF_BASE_MS * 2 ** (count + undecided - ONE_OFF_UNPAID_LIMIT), ONE_OFF_BACKOFF_MAX_MS) - now;
870
+ if (waitMs > 0)
871
+ return Math.ceil(waitMs / 1_000);
872
+ return undecided > 0 ? ONE_OFF_UNDECIDED_RETRY_SECONDS : null;
873
+ }
874
+ /** This channel's create was accepted: the channel is in use, so it stops counting against the buyer. */
875
+ markOneOffCreateAccepted(channelId) {
876
+ this._unacceptedOneOffs.delete(channelId);
805
877
  }
806
878
  /** The active one-off channel opened for this buyer's request, or null. */
807
879
  getOneOffChannelForRequest(buyerPeerId, requestId) {
@@ -879,6 +951,9 @@ export class SellerPaymentManager {
879
951
  }
880
952
  catch (err) {
881
953
  debugWarn(`[SellerPayment] Failed to process one-off SpendingAuth: ${this._formatError(err)}`);
954
+ // A channel that never opened costs nothing. One that did stays counted until it ends.
955
+ if (!this._oneOffChannelIds.has(payload.channelId))
956
+ this._unacceptedOneOffs.delete(payload.channelId);
882
957
  return 'rejected';
883
958
  }
884
959
  }
@@ -945,6 +1020,8 @@ export class SellerPaymentManager {
945
1020
  return 'rejected';
946
1021
  }
947
1022
  this._pendingOneOffPlans.delete(planKey);
1023
+ // Counted before the reserve goes out, so a parallel create sees it.
1024
+ this._unacceptedOneOffs.set(channelId, buyerPeerId);
948
1025
  await this._reserveWithBackpressureRetry(channelId, () => this._channelsClient.reserve(this._signer, buyerEvmAddr, payload.reserveSalt, openingReserve, BigInt(reserveDeadline), payload.spendingAuthSig));
949
1026
  const now = Date.now();
950
1027
  const { seller: sellerEvmAddr } = await this._resolvedAddresses;
@@ -1085,7 +1162,8 @@ export class SellerPaymentManager {
1085
1162
  if (!state.exists && this._mayNotBeVisibleYet(channel))
1086
1163
  continue;
1087
1164
  if (!state.exists || (state.status !== 'active' && state.status !== 'unknown')) {
1088
- this._evictStaleChannel(channel.sessionId, channel.peerId, `one-off on-chain status=${state.exists ? state.status : 'missing'}`);
1165
+ // What the chain settled is what the channel earned, even if its close was never recorded here.
1166
+ this._evictStaleChannel(channel.sessionId, channel.peerId, `one-off on-chain status=${state.exists ? state.status : 'missing'}`, CHANNEL_STATUS.SETTLED, state.exists ? state.channel.settled.toString() : undefined);
1089
1167
  continue;
1090
1168
  }
1091
1169
  this._oneOffChannelIds.add(channel.sessionId);
@@ -1208,7 +1286,76 @@ export class SellerPaymentManager {
1208
1286
  const existing = this._pendingTopUp.get(channelId);
1209
1287
  if (!existing || pending.newMaxAmount >= existing.newMaxAmount) {
1210
1288
  this._pendingTopUp.set(channelId, pending);
1289
+ this._persistPendingTopUp(channelId, pending);
1290
+ }
1291
+ }
1292
+ /**
1293
+ * Keep the buyer's top-up ReserveAuth in the store. Requests admitted while
1294
+ * the topUp() mines can take the spend past the on-chain deposit; if the
1295
+ * seller stops before it lands, only this signature can still lift the
1296
+ * ceiling so the buyer's auths for that work become settleable.
1297
+ */
1298
+ _persistPendingTopUp(channelId, pending) {
1299
+ const session = this._channelStore.getChannel(channelId);
1300
+ if (!session || BigInt(session.reserveMaxAmount ?? '0') >= pending.newMaxAmount)
1301
+ return;
1302
+ session.reserveMaxAmount = pending.newMaxAmount.toString();
1303
+ session.latestReserveAuthSig = pending.reserveAuthSig;
1304
+ session.latestReserveDeadline = pending.deadline;
1305
+ session.updatedAt = Date.now();
1306
+ this._channelStore.upsertChannel(session);
1307
+ }
1308
+ /**
1309
+ * Forget the stored top-up once it landed or can no longer land. One stored
1310
+ * since for a higher ceiling (`upTo` below it) is kept. A failed submission
1311
+ * keeps it: that channel is closed, and if the seller stops first, the next
1312
+ * start tries it once more (a timeout may not have been a revert).
1313
+ */
1314
+ _clearPersistedTopUp(channelId, upTo) {
1315
+ const session = this._channelStore.getChannel(channelId);
1316
+ if (!session?.latestReserveAuthSig || BigInt(session.reserveMaxAmount ?? '0') > upTo)
1317
+ return;
1318
+ session.reserveMaxAmount = null;
1319
+ session.latestReserveAuthSig = null;
1320
+ session.latestReserveDeadline = null;
1321
+ session.updatedAt = Date.now();
1322
+ this._channelStore.upsertChannel(session);
1323
+ }
1324
+ /**
1325
+ * After a restart: re-queue a stored top-up the chain has not applied, so
1326
+ * spend served above the deposit before the stop can still be signed for
1327
+ * and settled. Anything at or below the on-chain deposit has landed, and an
1328
+ * expired one would only revert: both are forgotten.
1329
+ */
1330
+ _restorePendingTopUp(channel, onChainDeposit) {
1331
+ const channelId = channel.sessionId;
1332
+ if (onChainDeposit > (this._reserveMax.get(channelId) ?? 0n)) {
1333
+ this._updateReserveCeiling(channelId, onChainDeposit);
1334
+ }
1335
+ if (!channel.latestReserveAuthSig)
1336
+ return;
1337
+ const newMaxAmount = BigInt(channel.reserveMaxAmount ?? '0');
1338
+ const deadline = channel.latestReserveDeadline ?? 0;
1339
+ if (newMaxAmount <= onChainDeposit || deadline <= Math.floor(Date.now() / 1000)) {
1340
+ this._clearPersistedTopUp(channelId, newMaxAmount);
1341
+ return;
1211
1342
  }
1343
+ // The buyer may have sent it again meanwhile: one queued or being submitted is not queued twice.
1344
+ if (this._topUpsRunning.has(channelId) || (this._pendingTopUp.get(channelId)?.newMaxAmount ?? 0n) >= newMaxAmount)
1345
+ return;
1346
+ this._pendingTopUp.set(channelId, { newMaxAmount, deadline, reserveAuthSig: channel.latestReserveAuthSig });
1347
+ debugLog(`[SellerPayment] Restored pending topUp: channel=${channelId.slice(0, 18)}... deposit=${onChainDeposit} newMax=${newMaxAmount}`);
1348
+ this._scheduleTopUp(channel.peerId, channelId);
1349
+ }
1350
+ /**
1351
+ * Resolves once no background topUp() is running, or after `timeoutMs`:
1352
+ * a stop waits briefly so one being mined can land before the process exits.
1353
+ * One that does not is kept in the store and resubmitted on the next start.
1354
+ */
1355
+ async waitForRunningTopUps(timeoutMs) {
1356
+ const deadline = Date.now() + timeoutMs;
1357
+ const results = await Promise.all([...this._topUpsRunning.keys()].map((channelId) => this.waitForTopUp(channelId, Math.max(0, deadline - Date.now()))));
1358
+ return results.every(Boolean);
1212
1359
  }
1213
1360
  _formatError(err) {
1214
1361
  const text = this._flattenErrorText(err);
@@ -1363,6 +1510,8 @@ export class SellerPaymentManager {
1363
1510
  }
1364
1511
  if (outcome === 'permanent-failure')
1365
1512
  break;
1513
+ if (outcome === 'succeeded')
1514
+ this._promptCatchUpAfterTopUp(buyerPeerId, channelId);
1366
1515
  // After a success, a higher top-up queued meanwhile goes next; after
1367
1516
  // a retryable failure, only a newer request retries it.
1368
1517
  if (outcome === 'succeeded' ? !this._pendingTopUp.has(channelId) : !this._topUpsWanted.has(channelId))
@@ -1380,6 +1529,33 @@ export class SellerPaymentManager {
1380
1529
  });
1381
1530
  this._topUpsRunning.set(channelId, run);
1382
1531
  }
1532
+ /**
1533
+ * After a top-up lands, ask the buyer to sign any spend above what it has
1534
+ * signed. While the top-up was pending the buyer signed only up to the
1535
+ * confirmed deposit, and it can't see the top-up land: without this prompt
1536
+ * the rest stays unsigned until the next request, or the close, asks.
1537
+ */
1538
+ _promptCatchUpAfterTopUp(buyerPeerId, channelId) {
1539
+ const paymentMux = this._paymentMuxFor?.(buyerPeerId);
1540
+ if (!paymentMux || this._connectionsClosed)
1541
+ return;
1542
+ const spent = this._spent.get(channelId) ?? 0n;
1543
+ const accepted = this._acceptedCumulative.get(channelId) ?? 0n;
1544
+ if (spent <= accepted || spent > (this._reserveMax.get(channelId) ?? 0n))
1545
+ return;
1546
+ try {
1547
+ paymentMux.sendNeedAuth({
1548
+ channelId,
1549
+ requiredCumulativeAmount: spent.toString(),
1550
+ currentAcceptedCumulative: accepted.toString(),
1551
+ deposit: this._channelStore.getChannel(channelId)?.authMax ?? '0',
1552
+ });
1553
+ debugLog(`[SellerPayment] Asked for the catch-up auth after topUp: channel=${channelId.slice(0, 18)}... spent=${spent} accepted=${accepted}`);
1554
+ }
1555
+ catch (err) {
1556
+ debugWarn(`[SellerPayment] Failed to send catch-up NeedAuth after topUp: ${this._formatError(err)}`);
1557
+ }
1558
+ }
1383
1559
  /**
1384
1560
  * Resolves once no background topUp() is running for the channel: false if
1385
1561
  * one still is at the timeout. With `covering`, an amount above the current
@@ -1452,6 +1628,7 @@ export class SellerPaymentManager {
1452
1628
  try {
1453
1629
  await this._channelsClient.topUp(this._signer, channelId, settleAmount, settleMetadata, settleSig, pendingTopUp.newMaxAmount, BigInt(pendingTopUp.deadline), pendingTopUp.reserveAuthSig);
1454
1630
  this._updateReserveCeiling(channelId, pendingTopUp.newMaxAmount, pendingTopUp.deadline);
1631
+ this._clearPersistedTopUp(channelId, pendingTopUp.newMaxAmount);
1455
1632
  debugLog(`[SellerPayment] Deferred topUp succeeded: channel=${channelId.slice(0, 18)}... new ceiling=${pendingTopUp.newMaxAmount}`);
1456
1633
  return 'succeeded';
1457
1634
  }
@@ -1550,10 +1727,26 @@ export class SellerPaymentManager {
1550
1727
  this._activeBuyers.add(buyerPeerId);
1551
1728
  }
1552
1729
  // ── Spend tracking ──────────────────────────────────────────
1730
+ /**
1731
+ * A stopping node closed every connection: a request that finishes after
1732
+ * this cannot deliver its response, so its cost is not billed. Without it, a
1733
+ * stop that waits (for a top-up being mined) bills in-flight work the buyer
1734
+ * never received, and after the restart demands it before serving anything.
1735
+ */
1736
+ markConnectionsClosed() {
1737
+ this._connectionsClosed = true;
1738
+ }
1739
+ get connectionsClosed() {
1740
+ return this._connectionsClosed;
1741
+ }
1553
1742
  /**
1554
1743
  * Record USDC consumption after serving a request.
1555
1744
  */
1556
1745
  recordSpend(sessionId, costUsdc) {
1746
+ if (this._connectionsClosed) {
1747
+ debugLog(`[SellerPayment] recordSpend skipped after connections closed: channel=${sessionId.slice(0, 18)}... cost=${costUsdc}`);
1748
+ return;
1749
+ }
1557
1750
  const current = this._spent.get(sessionId);
1558
1751
  if (current === undefined) {
1559
1752
  debugWarn(`[SellerPayment] recordSpend: unknown channelId ${sessionId.slice(0, 18)}...`);
@@ -1711,6 +1904,7 @@ export class SellerPaymentManager {
1711
1904
  this._blockedChannels.delete(channelId);
1712
1905
  this._lastSettledCumulative.delete(channelId);
1713
1906
  this._hydratedChannelIds.delete(channelId);
1907
+ this._unacceptedOneOffs.delete(channelId);
1714
1908
  this._releaseAcceptedWaiters(channelId);
1715
1909
  }
1716
1910
  // ── In-flight request tracking ────────────────────────────────
@@ -1811,6 +2005,9 @@ export class SellerPaymentManager {
1811
2005
  this._evictStaleChannel(channel.sessionId, channel.peerId, `periodic check: on-chain status=${onChainState.exists ? onChainState.status : 'missing'}`);
1812
2006
  continue;
1813
2007
  }
2008
+ if (this._topUpRestoreDeferred.delete(channel.sessionId)) {
2009
+ this._restorePendingTopUp(channel, onChainState.channel.deposit);
2010
+ }
1814
2011
  const buyerDisconnected = !this._activeBuyers.has(channel.peerId);
1815
2012
  const hydratedZeroAuthExpired = accepted === 0n
1816
2013
  && this._hydratedChannelIds.has(channel.sessionId)
@@ -2241,14 +2438,11 @@ export class SellerPaymentManager {
2241
2438
  }
2242
2439
  }
2243
2440
  // Anything served but not yet signed for is unclaimable — ask for the
2244
- // catch-up auth rather than closing at a loss.
2441
+ // catch-up auth rather than closing at a loss. Ask before waiting: the
2442
+ // buyer may not know about the spend (e.g. its NeedAuth was lost to a
2443
+ // seller restart), so without the request the wait can only time out.
2245
2444
  let spent = this._spent.get(channelId) ?? 0n;
2246
2445
  let best = this._getSettleParams(channelId);
2247
- if (spent > best.amount) {
2248
- await this.awaitAcceptedAtLeast(channelId, spent, CLOSE_CATCH_UP_WAIT_MS);
2249
- spent = this._spent.get(channelId) ?? 0n;
2250
- best = this._getSettleParams(channelId);
2251
- }
2252
2446
  if (spent > best.amount) {
2253
2447
  const accepted = this._acceptedCumulative.get(channelId) ?? 0n;
2254
2448
  try {
@@ -2262,6 +2456,11 @@ export class SellerPaymentManager {
2262
2456
  catch (err) {
2263
2457
  debugWarn(`[SellerPayment] Failed to send catch-up NeedAuth before close: ${this._formatError(err)}`);
2264
2458
  }
2459
+ await this.awaitAcceptedAtLeast(channelId, spent, CLOSE_CATCH_UP_WAIT_MS);
2460
+ spent = this._spent.get(channelId) ?? 0n;
2461
+ best = this._getSettleParams(channelId);
2462
+ }
2463
+ if (spent > best.amount) {
2265
2464
  return reject('pending_auth', `unsigned spend outstanding (spent=${spent} signed=${best.amount})`, {
2266
2465
  retryAfterMs: CLOSE_RETRY_AFTER_MS,
2267
2466
  requiredCumulativeAmount: spent.toString(),