@antseed/buyer-core 0.1.36 → 0.1.38

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.
@@ -1,9 +1,11 @@
1
+ import { isHexString } from 'ethers';
1
2
  import { PaymentMux } from './payment-mux.js';
2
3
  import { ANTSEED_FAULT_ATTRIBUTION_HEADER, } from '@antseed/protocol/http';
3
4
  import { computeOneOffChannelPlan, PAYMENT_CODE_CHANNEL_EXHAUSTED, PAYMENT_CODE_ONE_OFF_CHANNEL_REQUIRED, } from '@antseed/protocol/messages';
4
5
  import { decodeOneOffChannelPlan } from '@antseed/protocol/payment-codec';
5
6
  import { CHANNEL_ROLE, CHANNEL_STATUS, } from './channel-store-types.js';
6
7
  import { classifyOnChainChannel } from './channel-session-state.js';
8
+ import { closedOnChain, reconcileStoredChannels } from './channel-reconcile.js';
7
9
  import { peerIdToAddress } from '@antseed/protocol/peer-id';
8
10
  import { debugLog, debugWarn } from './debug.js';
9
11
  import { SellerAuthorizationError } from './seller-address-resolver.js';
@@ -13,7 +15,7 @@ import { formatUsdc } from './usdc-utils.js';
13
15
  import { parseJsonObject, tryParseJsonObject } from '@antseed/protocol/json-codec';
14
16
  import { nativeVideoAcceptance, nativeVideoRoute } from '@antseed/api-adapter';
15
17
  import { captureUnitBillingContext, computeFinalUnitBilling, estimateUnitRequestCost, extractUnitResponseUsage, } from './unit-billing.js';
16
- import { buyerFault, peerFault } from './errors.js';
18
+ import { AntseedRequestError, buyerFault, peerFault } from './errors.js';
17
19
  /**
18
20
  * How long a resent authorization gets to reach the seller and release the
19
21
  * requests parked on it: the seller waits up to 5 s for a catch-up before it
@@ -69,6 +71,9 @@ function sameOneOffPlan(a, b) {
69
71
  * (402 handling, SpendingAuth negotiation, per-request auth, cost tracking)
70
72
  * from core node orchestration.
71
73
  */
74
+ /** The session a payment call started on was retired or replaced while it awaited. */
75
+ class SessionReplacedError extends AntseedRequestError {
76
+ }
72
77
  export class BuyerPaymentNegotiator {
73
78
  _bpm;
74
79
  _depositsClient;
@@ -107,6 +112,9 @@ export class BuyerPaymentNegotiator {
107
112
  _pendingNeedAuth = new Set();
108
113
  /** In-flight cooperative-close requests keyed by seller peerId. */
109
114
  _pendingCloseRequests = new Map();
115
+ /** Payment calls in flight per seller peerId, counted by `_withPaymentWork`. */
116
+ _paymentWork = new Map();
117
+ _reconciling = null;
110
118
  constructor(identity, bpm, depositsClient, channelsClient, channelStore, _config, emitter, sellerAddressResolver, freeUsageManager) {
111
119
  this._identity = identity;
112
120
  this._bpm = bpm;
@@ -159,7 +167,7 @@ export class BuyerPaymentNegotiator {
159
167
  return undefined;
160
168
  });
161
169
  pmux.onNeedAuth((payload) => {
162
- const p = this._bpm.handleNeedAuth(peerId, payload, pmux);
170
+ const p = this._withPaymentWork(peerId, () => this._bpm.handleNeedAuth(peerId, payload, pmux));
163
171
  this._pendingNeedAuth.add(p);
164
172
  return p.finally(() => {
165
173
  this._pendingNeedAuth.delete(p);
@@ -273,7 +281,7 @@ export class BuyerPaymentNegotiator {
273
281
  // Skip if cost data was already consumed by post-response auth
274
282
  if (!this._lastResponseCost.has(peer.peerId))
275
283
  return;
276
- await this._sendPerRequestAuth(peer.peerId, conn);
284
+ await this._withPaymentWork(peer.peerId, () => this._sendPerRequestAuth(peer.peerId, conn));
277
285
  }
278
286
  /**
279
287
  * Open the one-off channel a seller requires for a video create. The
@@ -421,7 +429,7 @@ export class BuyerPaymentNegotiator {
421
429
  if (!this._channelsClient) {
422
430
  throw buyerFault(`Cannot recover pending reserve for ${peer.peerId.slice(0, 12)}... without an on-chain channels client`, 'buyer-session-state');
423
431
  }
424
- const recovered = await this._recoverExistingSession(peer, conn);
432
+ const recovered = await this._withPaymentWork(peer.peerId, () => this._recoverExistingSession(peer, conn, this._bpm.getActiveSession(peer.peerId)));
425
433
  if (!recovered && this._bpm.hasPendingReserveAuth(peer.peerId)) {
426
434
  throw buyerFault(`Unable to reconcile pending reserve for ${peer.peerId.slice(0, 12)}...`, 'buyer-session-state');
427
435
  }
@@ -440,7 +448,7 @@ export class BuyerPaymentNegotiator {
440
448
  return;
441
449
  if (!this._lastResponseCost.has(peerId))
442
450
  return;
443
- await this._sendPerRequestAuth(peerId, conn);
451
+ await this._withPaymentWork(peerId, () => this._sendPerRequestAuth(peerId, conn));
444
452
  }
445
453
  async _sendPerRequestAuth(peerId, conn) {
446
454
  const peer = { peerId };
@@ -461,7 +469,7 @@ export class BuyerPaymentNegotiator {
461
469
  // Release held content to free memory — no longer needed after signing
462
470
  this._lastResponseCost.delete(peer.peerId);
463
471
  debugLog(`[BuyerNegotiator] Per-request SpendingAuth sent to ${peer.peerId.slice(0, 12)}... cumulative=${payload.cumulativeAmount}`);
464
- if (topUpNeeded) {
472
+ if (topUpNeeded && this._isLiveChannel(peer.peerId, payload.channelId)) {
465
473
  debugLog(`[BuyerNegotiator] Reserve top-up needed for ${peer.peerId.slice(0, 12)}...`);
466
474
  await this._bpm.topUpReserve(peer.peerId, pmux);
467
475
  }
@@ -480,7 +488,10 @@ export class BuyerPaymentNegotiator {
480
488
  * serving requests, or be owed for work the buyer hasn't signed for), so it
481
489
  * resolves rather than throws; only "we never got an answer" throws.
482
490
  */
483
- async requestChannelClose(peerId, conn, { includeAuth = true, timeoutMs = CLOSE_REQUEST_TIMEOUT_MS, maxCumulative, channelId } = {}) {
491
+ requestChannelClose(peerId, conn, options = {}) {
492
+ return this._withPaymentWork(peerId, () => this._requestChannelClose(peerId, conn, options));
493
+ }
494
+ async _requestChannelClose(peerId, conn, { includeAuth = true, timeoutMs = CLOSE_REQUEST_TIMEOUT_MS, maxCumulative, channelId } = {}) {
484
495
  if (this._pendingCloseRequests.has(peerId)) {
485
496
  throw new Error(`A channel close request is already in flight for ${peerId.slice(0, 12)}...`);
486
497
  }
@@ -499,6 +510,9 @@ export class BuyerPaymentNegotiator {
499
510
  // outstanding response authorization fails, abort rather than signing and
500
511
  // transmitting another authorization from non-durable in-memory state.
501
512
  await this.sendPostResponseAuthTo(peerId, conn);
513
+ if (!this._isLiveChannel(peerId, session.sessionId)) {
514
+ throw buyerFault(`Payment channel ${session.sessionId.slice(0, 18)}... with seller ${peerId.slice(0, 12)}... was retired before it could be closed`, 'buyer-session-state');
515
+ }
502
516
  const pmux = this.getOrCreatePaymentMux(peerId, conn);
503
517
  const payload = await this._bpm.buildCloseChannelRequest(peerId, { includeAuth, maxCumulative });
504
518
  const result = await new Promise((resolve, reject) => {
@@ -518,12 +532,25 @@ export class BuyerPaymentNegotiator {
518
532
  reject(err instanceof Error ? err : new Error(String(err)));
519
533
  }
520
534
  });
535
+ // The answer can arrive after the session was retired and replaced: only
536
+ // the channel this request asked about is the caller's to end.
537
+ const stillLive = this._isLiveChannel(peerId, session.sessionId);
521
538
  if (result.status === 'closed') {
522
539
  const finalAmount = result.finalAmount != null ? safeBigInt(result.finalAmount) : null;
523
- this._bpm.retireSession(peerId, CHANNEL_STATUS.SETTLED, finalAmount ?? undefined);
524
- this._lockedPeers.delete(peerId);
525
- this._firstRequestSent.delete(peerId);
526
- this._lastResponseCost.delete(peerId);
540
+ if (stillLive) {
541
+ this._bpm.retireSession(peerId, CHANNEL_STATUS.SETTLED, finalAmount ?? undefined);
542
+ this._forgetSellerSession(peerId);
543
+ }
544
+ else {
545
+ // A row that already ended with an amount (the chain's, for example) keeps it.
546
+ const store = this._channelStore;
547
+ const asked = store?.getChannel(session.sessionId);
548
+ const endedWithAmount = asked?.settledAmount != null
549
+ && (asked.status === CHANNEL_STATUS.SETTLED || asked.status === CHANNEL_STATUS.TIMEOUT);
550
+ if (store && asked && !endedWithAmount) {
551
+ store.updateChannelStatus(session.sessionId, CHANNEL_STATUS.SETTLED, finalAmount?.toString());
552
+ }
553
+ }
527
554
  debugLog(`[BuyerNegotiator] Seller ${peerId.slice(0, 12)}... closed channel ` +
528
555
  `${result.channelId.slice(0, 18)}... at ${result.finalAmount ?? '?'} (tx=${result.txHash ?? '?'})`);
529
556
  this._emit.emit('payment:channel-closed', {
@@ -539,15 +566,16 @@ export class BuyerPaymentNegotiator {
539
566
  // The seller has no record of this channel. Drop ours as well once the
540
567
  // chain confirms it is no longer open; a channel that is still open
541
568
  // holds a reserve and is kept.
542
- if (result.code === 'no_channel' && await this._retireSessionsClosedOnChain(peerId)) {
543
- this._lockedPeers.delete(peerId);
544
- this._firstRequestSent.delete(peerId);
545
- this._lastResponseCost.delete(peerId);
569
+ if (result.code === 'no_channel' && stillLive && await this._retireSessionsClosedOnChain(peerId)) {
570
+ this._forgetSellerSession(peerId);
546
571
  }
547
572
  }
548
573
  return result;
549
574
  }
550
- async handle402(response, peer, conn, req, inFlightRequests = 1) {
575
+ handle402(response, peer, conn, req, inFlightRequests = 1) {
576
+ return this._withPaymentWork(peer.peerId, () => this._handle402(response, peer, conn, req, inFlightRequests));
577
+ }
578
+ async _handle402(response, peer, conn, req, inFlightRequests = 1) {
551
579
  const hadLockedSession = this._lockedPeers.has(peer.peerId);
552
580
  const directPaymentBody = parsePaymentRequiredBody(response.body);
553
581
  const responseAlreadyHasRequirements = Boolean(directPaymentBody?.minBudgetPerRequest);
@@ -697,20 +725,21 @@ export class BuyerPaymentNegotiator {
697
725
  const channelExhausted = buffered?.code === PAYMENT_CODE_CHANNEL_EXHAUSTED
698
726
  || (responseAlreadyHasRequirements && directPaymentBody?.code === PAYMENT_CODE_CHANNEL_EXHAUSTED)
699
727
  || (requiredCumulativeTarget != null && sellerReserveMax != null && requiredCumulativeTarget > sellerReserveMax);
700
- const hasActiveSession = hadLockedSession || this._bpm.getActiveSession(peer.peerId) != null;
701
- // With requests in parallel, an exhausted 402 for the old channel can
702
- // arrive after another request already replaced it. Retiring then would
703
- // ghost the replacement: wait for its negotiation and retry on it instead.
704
- const exhaustedChannelId = channelExhausted
705
- ? buffered?.channelId ?? (responseAlreadyHasRequirements && typeof directPaymentBody?.channelId === 'string' ? directPaymentBody.channelId : null)
706
- : null;
707
- const activeChannelId = exhaustedChannelId ? this._bpm.getActiveSession(peer.peerId)?.sessionId : undefined;
708
- if (exhaustedChannelId && activeChannelId && exhaustedChannelId.toLowerCase() !== activeChannelId.toLowerCase()) {
709
- debugLog(`[BuyerNegotiator] Exhausted 402 for replaced channel ${exhaustedChannelId.slice(0, 18)}... from ${peer.peerId.slice(0, 12)}... — ` +
710
- `retrying on ${activeChannelId.slice(0, 18)}...`);
728
+ // A 402 about a channel the buyer has since replaced describes that
729
+ // channel: its target and exhaustion say nothing about the live one.
730
+ // Retiring on it would ghost the replacement (with requests in parallel,
731
+ // an exhausted 402 for the old channel often lands after another request
732
+ // replaced it): wait for the replacement's negotiation and retry on it.
733
+ const paymentChannelId = buffered?.channelId
734
+ ?? (responseAlreadyHasRequirements && typeof directPaymentBody?.channelId === 'string' ? directPaymentBody.channelId : null);
735
+ const session = this._bpm.getActiveSession(peer.peerId);
736
+ if (session && paymentChannelId != null && paymentChannelId.toLowerCase() !== session.sessionId.toLowerCase()) {
737
+ debugLog(`[BuyerNegotiator] ${channelExhausted ? 'Exhausted ' : ''}402 from ${peer.peerId.slice(0, 12)}... is about channel ` +
738
+ `${paymentChannelId.slice(0, 18)}..., not the live ${session.sessionId.slice(0, 18)}... — retrying on it`);
711
739
  await this._negotiationLocks.get(peer.peerId)?.catch(() => undefined);
712
740
  return { action: 'retry' };
713
741
  }
742
+ const hasActiveSession = hadLockedSession || session != null;
714
743
  if (channelExhausted && hasActiveSession) {
715
744
  debugLog(`[BuyerNegotiator] Channel exhausted for ${peer.peerId.slice(0, 12)}... ` +
716
745
  `(required=${requiredCumulativeTarget ?? 'n/a'} > reserveMax=${sellerReserveMax ?? 'n/a'}) — ` +
@@ -718,29 +747,42 @@ export class BuyerPaymentNegotiator {
718
747
  // 'ghost' rather than 'settled' — buyer hasn't observed the on-chain
719
748
  // settle land. Matches the other buyer-side give-up-locally callsites.
720
749
  this._bpm.retireSession(peer.peerId, CHANNEL_STATUS.GHOST);
721
- this._lockedPeers.delete(peer.peerId);
722
- this._firstRequestSent.delete(peer.peerId);
750
+ this._forgetSellerSession(peer.peerId);
723
751
  }
724
752
  else if (hasActiveSession) {
725
- const recovered = await this._recoverExistingSession(peer, conn, existingSessionBudgetRequest, requiredCumulativeTarget, requiredCumulativeTarget == null, req.requestId, inFlightRequests);
753
+ let recovered;
754
+ try {
755
+ recovered = await this._recoverExistingSession(peer, conn, session, existingSessionBudgetRequest, requiredCumulativeTarget, requiredCumulativeTarget == null, req.requestId, inFlightRequests);
756
+ }
757
+ catch (err) {
758
+ if (!(err instanceof SessionReplacedError))
759
+ throw err;
760
+ // After a restart every parked request's 402 recovers the same
761
+ // channel. One of them found it closed and retired it while this one
762
+ // read the chain: join that request's replacement instead of failing.
763
+ debugLog(`[BuyerNegotiator] ${err.message} by a parallel request — joining its replacement`);
764
+ if (this._bpm.getActiveSession(peer.peerId)) {
765
+ await this._negotiationLocks.get(peer.peerId)?.catch(() => undefined);
766
+ return { action: 'retry' };
767
+ }
768
+ recovered = false;
769
+ }
726
770
  if (recovered) {
727
771
  return { action: 'retry' };
728
772
  }
729
773
  // Older stored sessions for this seller (e.g. from a reserve that never
730
774
  // locked) would each block a fresh reserve; check every one on-chain.
731
775
  await this._retireSessionsClosedOnChain(peer.peerId);
732
- if (this._bpm.getActiveSession(peer.peerId)) {
733
- if (await this._canRetireStaleSessionWithoutOnChainProof()) {
734
- this._bpm.retireSession(peer.peerId, CHANNEL_STATUS.GHOST);
735
- }
776
+ const stale = this._bpm.getActiveSession(peer.peerId);
777
+ if (stale && await this._canRetireStaleSessionWithoutOnChainProof() && this._isLiveChannel(peer.peerId, stale.sessionId)) {
778
+ this._bpm.retireSession(peer.peerId, CHANNEL_STATUS.GHOST);
736
779
  }
737
780
  if (this._bpm.getActiveSession(peer.peerId)) {
738
781
  // Usually transient (the seller was busy, or a chain read failed): a
739
782
  // retryable 503 lets routers fail over and clients retry.
740
783
  return returnNegotiationFailure('existing_channel_still_active', 'An existing payment channel could not be recovered automatically. Close or recover the channel and retry.', 503);
741
784
  }
742
- this._lockedPeers.delete(peer.peerId);
743
- this._firstRequestSent.delete(peer.peerId);
785
+ this._forgetSellerSession(peer.peerId);
744
786
  }
745
787
  // Check if we can pay before attempting negotiation
746
788
  if (!this._depositsClient) {
@@ -875,7 +917,10 @@ export class BuyerPaymentNegotiator {
875
917
  });
876
918
  }
877
919
  }
878
- async applyExternalSpendingAuth(peer, conn, headerValue) {
920
+ applyExternalSpendingAuth(peer, conn, headerValue) {
921
+ return this._withPaymentWork(peer.peerId, () => this._applyExternalSpendingAuth(peer, conn, headerValue));
922
+ }
923
+ async _applyExternalSpendingAuth(peer, conn, headerValue) {
879
924
  const pmux = this.getOrCreatePaymentMux(peer.peerId, conn);
880
925
  let payload;
881
926
  try {
@@ -886,6 +931,10 @@ export class BuyerPaymentNegotiator {
886
931
  catch {
887
932
  throw buyerFault('Invalid x-antseed-spending-auth header: failed to decode', 'invalid-spending-auth-header');
888
933
  }
934
+ // The channelId becomes a stored channel row's key, read back by every reconcile pass.
935
+ if (!isHexString(payload.channelId, 32)) {
936
+ throw buyerFault('Invalid x-antseed-spending-auth header: channelId is not a 32-byte hex string', 'invalid-spending-auth-header');
937
+ }
889
938
  debugLog(`[BuyerNegotiator] External SpendingAuth: channel=${payload.channelId.slice(0, 18)}... amount=${payload.cumulativeAmount}`);
890
939
  const sellerEvmAddrExternal = await this._resolveSellerAddr(peer);
891
940
  // Store session so handleAuthAck can find it
@@ -974,6 +1023,70 @@ export class BuyerPaymentNegotiator {
974
1023
  this._firstRequestSent.delete(peerId);
975
1024
  this._lastResponseCost.delete(peerId);
976
1025
  }
1026
+ /**
1027
+ * Retire this buyer's stored channels the chain shows can never move money
1028
+ * again, for every seller. A seller with payment work in flight (a 402, a
1029
+ * close request, a NeedAuth, a SpendingAuth being signed, a paid request or
1030
+ * a reserve top-up still running, a channel being replaced) keeps its current
1031
+ * channel, and a connected seller keeps a never-opened one: the 402 and close
1032
+ * paths own those. Concurrent calls share one pass. Never throws on chain errors.
1033
+ */
1034
+ reconcileChannelsWithChain() {
1035
+ this._reconciling ??= this._reconcileOnce().finally(() => {
1036
+ this._reconciling = null;
1037
+ });
1038
+ return this._reconciling;
1039
+ }
1040
+ async _reconcileOnce() {
1041
+ if (!this._channelStore)
1042
+ return { retired: [], unchecked: 0 };
1043
+ const chainReadable = !this._isChainReachable || this._isChainReachable();
1044
+ const result = await reconcileStoredChannels({
1045
+ store: this._channelStore,
1046
+ channels: chainReadable ? this._channelsClient : null,
1047
+ buyerEvmAddr: this._identity.wallet.address,
1048
+ sessions: {
1049
+ mayEndSession: (peerId, closure) => !this._paymentWork.has(peerId)
1050
+ // A paid request or a reserve top-up still running owns the session.
1051
+ && !this._bpm.hasPaymentInFlight(peerId)
1052
+ // A connected seller can still be sent a replayed ReserveAuth, the one way a missing channel opens.
1053
+ && (closure.status !== CHANNEL_STATUS.GHOST || !this._muxes.has(peerId)),
1054
+ sessionEnded: (peerId) => {
1055
+ this._bpm.cleanupSession(peerId);
1056
+ this._forgetSellerSession(peerId);
1057
+ },
1058
+ oneOffEnded: (channelId) => this._bpm.forgetOneOffChannel(channelId),
1059
+ },
1060
+ });
1061
+ if (result.readError !== undefined)
1062
+ this._onChainReadFailure?.();
1063
+ return result;
1064
+ }
1065
+ /**
1066
+ * Count payment work for a seller while it runs, so the reconcile pass does
1067
+ * not end the session under it. Work whose session ends during an await
1068
+ * stops with nothing written, so the work would fail instead of finishing.
1069
+ */
1070
+ async _withPaymentWork(peerId, work) {
1071
+ this._paymentWork.set(peerId, (this._paymentWork.get(peerId) ?? 0) + 1);
1072
+ try {
1073
+ return await work();
1074
+ }
1075
+ finally {
1076
+ const left = (this._paymentWork.get(peerId) ?? 1) - 1;
1077
+ if (left > 0)
1078
+ this._paymentWork.set(peerId, left);
1079
+ else
1080
+ this._paymentWork.delete(peerId);
1081
+ }
1082
+ }
1083
+ /** Drop what this negotiator holds for a seller's session once that session is retired. */
1084
+ _forgetSellerSession(peerId) {
1085
+ this._lockedPeers.delete(peerId);
1086
+ this._firstRequestSent.delete(peerId);
1087
+ this._lastResponseCost.delete(peerId);
1088
+ this._resentForTarget.delete(peerId);
1089
+ }
977
1090
  /** Wait for in-flight NeedAuth handlers to complete (settlement safety). */
978
1091
  async drainPendingNeedAuth() {
979
1092
  // Handlers can enqueue more work while an earlier snapshot is settling.
@@ -1205,8 +1318,8 @@ export class BuyerPaymentNegotiator {
1205
1318
  });
1206
1319
  });
1207
1320
  }
1208
- async _recoverExistingSession(peer, conn, minBudgetPerRequest = null, targetCumulative = null, requireFreshAck = false, requestId, inFlightRequests = 1) {
1209
- const session = this._bpm.getActiveSession(peer.peerId);
1321
+ /** Recover `session`, the seller's live channel when this is called. */
1322
+ async _recoverExistingSession(peer, conn, session, minBudgetPerRequest = null, targetCumulative = null, requireFreshAck = false, requestId, inFlightRequests = 1) {
1210
1323
  if (!session) {
1211
1324
  return false;
1212
1325
  }
@@ -1218,6 +1331,7 @@ export class BuyerPaymentNegotiator {
1218
1331
  if (onChain === null) {
1219
1332
  return false;
1220
1333
  }
1334
+ this._assertLiveChannel(peer.peerId, session.sessionId);
1221
1335
  if (!onChain.exists) {
1222
1336
  if (this._bpm.canReplayReserveAuth(peer.peerId)) {
1223
1337
  const pmux = this.getOrCreatePaymentMux(peer.peerId, conn);
@@ -1236,6 +1350,7 @@ export class BuyerPaymentNegotiator {
1236
1350
  }
1237
1351
  const pmux = this.getOrCreatePaymentMux(peer.peerId, conn);
1238
1352
  await this._bpm.reconcileReserveAmount(peer.peerId, onChain.channel.deposit);
1353
+ this._assertLiveChannel(peer.peerId, session.sessionId);
1239
1354
  const hasPendingReserve = this._bpm.hasPendingReserveAuth(peer.peerId);
1240
1355
  let recoveredBeforeTopUp = false;
1241
1356
  if (requireFreshAck) {
@@ -1255,6 +1370,7 @@ export class BuyerPaymentNegotiator {
1255
1370
  }
1256
1371
  if (hasPendingReserve) {
1257
1372
  await this._bpm.resendPendingReserveAuth(peer.peerId, pmux);
1373
+ this._assertLiveChannel(peer.peerId, session.sessionId);
1258
1374
  }
1259
1375
  const signedCumulative = this._bpm.getCumulativeAmount(peer.peerId);
1260
1376
  const deposit = onChain.channel.deposit;
@@ -1265,6 +1381,12 @@ export class BuyerPaymentNegotiator {
1265
1381
  // anything new: resend the highest authorization unchanged. An
1266
1382
  // authorization above the on-chain deposit can never be accepted, so
1267
1383
  // such a channel goes straight to a close capped at the deposit.
1384
+ if (this._bpm.getSellerAcceptedCumulative(peer.peerId) >= targetCumulative) {
1385
+ // The seller has since reported accepting this target: the 402 was
1386
+ // waiting behind other work while the channel moved on. Retry, even
1387
+ // with more signed than the deposit (a top-up on its way).
1388
+ return true;
1389
+ }
1268
1390
  const resendable = deposit <= 0n || signedCumulative <= deposit;
1269
1391
  const resent = this._resentForTarget.get(peer.peerId);
1270
1392
  if (resendable && resent?.target === targetCumulative && Date.now() - resent.at < RESEND_SETTLE_MS) {
@@ -1299,14 +1421,19 @@ export class BuyerPaymentNegotiator {
1299
1421
  this._resentForTarget.delete(peer.peerId);
1300
1422
  const cumulativeBefore = signedCumulative;
1301
1423
  const extend = () => this._bpm.extendCurrentSpendingAuth(peer.peerId, minBudgetPerRequest, pmux, targetCumulative != null && targetCumulative > 0n ? targetCumulative : undefined, requestId, inFlightRequests);
1302
- await extend();
1303
- let cumulativeAfter = this._bpm.getCumulativeAmount(peer.peerId);
1424
+ // A higher SpendingAuth committed while the catch-up was signed counts
1425
+ // too, though its writer may not have adopted it in memory yet.
1426
+ const signedAfterExtend = async () => {
1427
+ await extend();
1428
+ this._assertLiveChannel(peer.peerId, session.sessionId);
1429
+ return this._bpm.getHighestSignedAmount(session);
1430
+ };
1431
+ let cumulativeAfter = await signedAfterExtend();
1304
1432
  if (cumulativeAfter <= cumulativeBefore && this._bpm.hasPendingReserveAuth(peer.peerId)) {
1305
1433
  // Stopped at the old ceiling and sent a top-up for it: sign against the
1306
1434
  // new ceiling. The seller holds that authorization until the topUp()
1307
1435
  // lands, instead of the channel being retired with a top-up on its way.
1308
- await extend();
1309
- cumulativeAfter = this._bpm.getCumulativeAmount(peer.peerId);
1436
+ cumulativeAfter = await signedAfterExtend();
1310
1437
  }
1311
1438
  if (cumulativeAfter <= cumulativeBefore) {
1312
1439
  // extendCurrentSpendingAuth was a no-op — the overdraft window and reserve ceiling
@@ -1315,8 +1442,7 @@ export class BuyerPaymentNegotiator {
1315
1442
  debugWarn(`[BuyerNegotiator] extendCurrentSpendingAuth made no progress for ${peer.peerId.slice(0, 12)}... ` +
1316
1443
  `(cumulative=${cumulativeAfter}); retiring session`);
1317
1444
  this._bpm.retireSession(peer.peerId, CHANNEL_STATUS.GHOST);
1318
- this._lockedPeers.delete(peer.peerId);
1319
- this._firstRequestSent.delete(peer.peerId);
1445
+ this._forgetSellerSession(peer.peerId);
1320
1446
  return false;
1321
1447
  }
1322
1448
  }
@@ -1329,6 +1455,20 @@ export class BuyerPaymentNegotiator {
1329
1455
  this._lockedPeers.add(peer.peerId);
1330
1456
  return true;
1331
1457
  }
1458
+ /**
1459
+ * Whether `channelId` is still the seller's live session. Work that read the
1460
+ * session and awaited must not act on a channel that replaced it: the
1461
+ * seller's 402 target, a chain read and a close answer all describe the old one.
1462
+ */
1463
+ _isLiveChannel(peerId, channelId) {
1464
+ return this._bpm.getActiveSession(peerId)?.sessionId === channelId;
1465
+ }
1466
+ /** Fails the way a vanished session fails a payment call. */
1467
+ _assertLiveChannel(peerId, channelId) {
1468
+ if (!this._isLiveChannel(peerId, channelId)) {
1469
+ throw new SessionReplacedError(`[BuyerNegotiator] Session ${channelId.slice(0, 18)}... with ${peerId.slice(0, 12)}... was retired during recovery`, 'buyer-session-state', 'buyer');
1470
+ }
1471
+ }
1332
1472
  /**
1333
1473
  * Retire the seller's stored session when the chain shows its channel is no
1334
1474
  * longer open, recording how it ended. Returns whether it was retired.
@@ -1337,11 +1477,9 @@ export class BuyerPaymentNegotiator {
1337
1477
  if (onChain.status === CHANNEL_STATUS.ACTIVE) {
1338
1478
  return false;
1339
1479
  }
1340
- if (onChain.status === CHANNEL_STATUS.SETTLED) {
1341
- this._bpm.retireSession(peerId, CHANNEL_STATUS.SETTLED, onChain.channel.settled);
1342
- }
1343
- else if (onChain.status === CHANNEL_STATUS.TIMEOUT) {
1344
- this._bpm.retireSession(peerId, CHANNEL_STATUS.TIMEOUT);
1480
+ const closure = closedOnChain(onChain);
1481
+ if (closure) {
1482
+ this._bpm.retireSession(peerId, closure.status, closure.settledAmount);
1345
1483
  }
1346
1484
  else {
1347
1485
  this._bpm.retireSession(peerId, CHANNEL_STATUS.GHOST);
@@ -1361,7 +1499,7 @@ export class BuyerPaymentNegotiator {
1361
1499
  if (!session)
1362
1500
  break;
1363
1501
  const onChain = await this._getOnChainSessionState(session.sessionId);
1364
- if (onChain === null || !this._retireIfNotOpenOnChain(peerId, onChain))
1502
+ if (onChain === null || !this._isLiveChannel(peerId, session.sessionId) || !this._retireIfNotOpenOnChain(peerId, onChain))
1365
1503
  break;
1366
1504
  retired = true;
1367
1505
  }