@antseed/buyer-core 0.1.30 → 0.1.32

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.
@@ -16,6 +16,14 @@ const INITIAL_TOPUP_HEADROOM_PERCENT = 35n;
16
16
  /** Fixed remaining headroom that triggers every later top-up ($0.50). */
17
17
  const SUBSEQUENT_TOPUP_HEADROOM_USDC = 500000n;
18
18
  const PERCENT_DENOMINATOR = 100n;
19
+ /**
20
+ * Paid requests still in flight cost about the channel's average request
21
+ * each, and are charged after they finish: keep twice that much headroom so
22
+ * a top-up lands before the work in flight passes the locked reserve.
23
+ */
24
+ const IN_FLIGHT_HEADROOM_FACTOR = 2n;
25
+ /** Largest load-sized top-up, in multiples of the configured reserve step. */
26
+ const MAX_LOAD_TOPUP_MULTIPLE = 10n;
19
27
  /** Default max price of one video generation ($5.00). */
20
28
  export const DEFAULT_MAX_VIDEO_REQUEST_USDC = 5000000n;
21
29
  const REQUEST_BILLING_TTL_MS = 5 * 60_000;
@@ -42,6 +50,30 @@ function countVideoSeconds(usage) {
42
50
  function validateUnitNormalizedCost(model, context, usage) {
43
51
  return evaluateUnitBilling(model, context, usage);
44
52
  }
53
+ /** A wire cost that is a positive integer; malformed values are judged later, where they are caught. */
54
+ function hasPositiveCost(cost) {
55
+ try {
56
+ return BigInt(cost ?? '0') > 0n;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /**
63
+ * Run `run` after everything queued under `key` has finished, whether it
64
+ * succeeded or not. The queue entry removes itself once it is the last.
65
+ */
66
+ function runQueued(queues, key, run) {
67
+ const previous = queues.get(key) ?? Promise.resolve();
68
+ const next = previous.then(run, run);
69
+ const tail = next.catch(() => undefined);
70
+ queues.set(key, tail);
71
+ void tail.then(() => {
72
+ if (queues.get(key) === tail)
73
+ queues.delete(key);
74
+ });
75
+ return next;
76
+ }
45
77
  /**
46
78
  * Manages buyer-side payment sessions using EIP-712 SpendingAuth
47
79
  * with cumulative authorization, bytes/4 cost verification, and overdraft control.
@@ -63,6 +95,21 @@ export class BuyerPaymentManager {
63
95
  _metadata = new Map();
64
96
  /** sellerPeerId -> buyer-verified cumulative cost from bytes/4 */
65
97
  _verifiedCost = new Map();
98
+ /** sellerPeerId -> paid requests dispatched and not yet answered */
99
+ _inFlightPaidRequests = new Map();
100
+ /** Per seller: the tail of the queue of reserve top-ups (see topUpReserve). */
101
+ _topUpLocks = new Map();
102
+ /** Per seller: top-ups queued or running, so one that waited can tell. */
103
+ _topUpsQueued = new Map();
104
+ /** Reads a channel's locked deposit on-chain (set by the negotiator when it has a channels client). */
105
+ _readChannelDeposit = null;
106
+ /**
107
+ * Per seller: the tail of the queue of signing steps. Reading the signed
108
+ * amount and verified cost, signing and committing happen one at a time
109
+ * per seller, so concurrent requests can neither lose a cost nor commit a
110
+ * lower cumulative after a higher one.
111
+ */
112
+ _sellerLocks = new Map();
66
113
  /** requestId -> service/model the buyer requested (from its own request body).
67
114
  * Used in handleNeedAuth to validate cost with the correct pricing tier
68
115
  * without trusting the seller's claim of which service was used. */
@@ -296,7 +343,10 @@ export class BuyerPaymentManager {
296
343
  this._confirmedPeers.delete(sellerPeerId);
297
344
  this._rejectedPeers.delete(sellerPeerId);
298
345
  }
299
- async resendCurrentSpendingAuth(sellerPeerId, paymentMux) {
346
+ resendCurrentSpendingAuth(sellerPeerId, paymentMux) {
347
+ return this._withSellerLock(sellerPeerId, () => this._resendCurrentSpendingAuth(sellerPeerId, paymentMux));
348
+ }
349
+ async _resendCurrentSpendingAuth(sellerPeerId, paymentMux) {
300
350
  const session = this.getActiveSession(sellerPeerId);
301
351
  if (!session) {
302
352
  throw buyerFault(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`, 'buyer-session-state');
@@ -328,6 +378,14 @@ export class BuyerPaymentManager {
328
378
  return session.sessionId;
329
379
  }
330
380
  async extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative, requestId, inFlightRequests = 1) {
381
+ const { sessionId, topUp } = await this._withSellerLock(sellerPeerId, () => this._extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative, requestId, inFlightRequests));
382
+ // Sent after the SpendingAuth so the seller processes the higher cumulative
383
+ // first, meeting the on-chain settle threshold for topUp.
384
+ if (topUp)
385
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'extendCurrentSpendingAuth');
386
+ return sessionId;
387
+ }
388
+ async _extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative, requestId, inFlightRequests) {
331
389
  const session = this.getActiveSession(sellerPeerId);
332
390
  if (!session) {
333
391
  throw buyerFault(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`, 'buyer-session-state');
@@ -355,13 +413,10 @@ export class BuyerPaymentManager {
355
413
  const nextCumulative = requestedAmount < maxSignable ? requestedAmount : maxSignable;
356
414
  const extendNeedsTopUp = this._needsCeilingAdvance(requestedAmount, maxSignable, ceiling);
357
415
  if (nextCumulative <= currentCumulative) {
358
- // Nothing to sign at current ceiling — try topUp anyway for next round
359
- if (extendNeedsTopUp) {
360
- await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'extendCurrentSpendingAuth');
361
- }
416
+ // Nothing to sign at current ceiling; a top-up still extends it for the next round.
362
417
  debugWarn(`[BuyerPayment] Cannot extend active session for ${sellerPeerId.slice(0, 12)}... ` +
363
418
  `(current=${currentCumulative} maxSignable=${maxSignable} target=${targetCumulative ?? 'n/a'})`);
364
- return session.sessionId;
419
+ return { sessionId: session.sessionId, topUp: extendNeedsTopUp };
365
420
  }
366
421
  const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
367
422
  const spendingAuth = await this._commitUpdatedSpendingAuth(session, sellerPeerId, nextCumulative, currentMeta);
@@ -376,12 +431,7 @@ export class BuyerPaymentManager {
376
431
  outputImages: '0',
377
432
  });
378
433
  paymentMux.sendSpendingAuth(spendingAuth);
379
- // Send topUp AFTER the SpendingAuth so the seller processes the higher
380
- // cumulative first, meeting the on-chain settle threshold for topUp.
381
- if (extendNeedsTopUp) {
382
- await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'extendCurrentSpendingAuth');
383
- }
384
- return session.sessionId;
434
+ return { sessionId: session.sessionId, topUp: extendNeedsTopUp };
385
435
  }
386
436
  /**
387
437
  * Build a CloseChannelRequest for an active session.
@@ -949,12 +999,75 @@ export class BuyerPaymentManager {
949
999
  const current = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
950
1000
  const initialReserve = this._initialReserveAmount.get(sellerPeerId)
951
1001
  ?? this._config.maxReserveAmountUsdc;
952
- const threshold = ceiling <= initialReserve
1002
+ const fixedThreshold = ceiling <= initialReserve
953
1003
  ? initialReserve * INITIAL_TOPUP_HEADROOM_PERCENT / PERCENT_DENOMINATOR
954
1004
  : SUBSEQUENT_TOPUP_HEADROOM_USDC;
1005
+ const loadThreshold = this._inFlightHeadroom(sellerPeerId);
1006
+ const threshold = loadThreshold > fixedThreshold ? loadThreshold : fixedThreshold;
955
1007
  const remaining = ceiling > current ? ceiling - current : 0n;
956
1008
  return remaining <= threshold;
957
1009
  }
1010
+ setChannelDepositReader(reader) {
1011
+ this._readChannelDeposit = reader;
1012
+ }
1013
+ /** Count a paid request to this seller as in flight until endPaidRequest. */
1014
+ beginPaidRequest(sellerPeerId) {
1015
+ this._inFlightPaidRequests.set(sellerPeerId, (this._inFlightPaidRequests.get(sellerPeerId) ?? 0) + 1);
1016
+ }
1017
+ endPaidRequest(sellerPeerId) {
1018
+ const remaining = (this._inFlightPaidRequests.get(sellerPeerId) ?? 0) - 1;
1019
+ if (remaining > 0)
1020
+ this._inFlightPaidRequests.set(sellerPeerId, remaining);
1021
+ else
1022
+ this._inFlightPaidRequests.delete(sellerPeerId);
1023
+ }
1024
+ /**
1025
+ * How much of the current ceiling is a top-up not yet locked on-chain. A
1026
+ * landed top-up the buyer has not heard about is reconciled first, so it is
1027
+ * not counted against the available balance twice. Without a chain read,
1028
+ * the whole pending increase counts. Null when the channel was replaced
1029
+ * during the read.
1030
+ */
1031
+ async _outstandingTopUp(sellerPeerId, channelId, ceiling) {
1032
+ const pending = this._pendingReserveAuth.get(sellerPeerId);
1033
+ if (!pending || pending.confirmedAmount <= 0n || ceiling <= pending.confirmedAmount)
1034
+ return 0n;
1035
+ let locked = pending.confirmedAmount;
1036
+ if (this._readChannelDeposit) {
1037
+ try {
1038
+ const deposit = await this._readChannelDeposit(channelId);
1039
+ // Only act on the read if nothing replaced the channel or the authorization meanwhile.
1040
+ if (this.getActiveSession(sellerPeerId)?.sessionId !== channelId)
1041
+ return null;
1042
+ if (this._pendingReserveAuth.get(sellerPeerId) !== pending) {
1043
+ return this._outstandingTopUp(sellerPeerId, channelId, this._getCeiling(sellerPeerId));
1044
+ }
1045
+ if (deposit >= pending.maxAmount) {
1046
+ await this.reconcileReserveAmount(sellerPeerId, deposit);
1047
+ return 0n;
1048
+ }
1049
+ if (deposit > locked)
1050
+ locked = deposit;
1051
+ }
1052
+ catch (err) {
1053
+ debugWarn(`[BuyerPayment] topUpReserve: could not read the channel deposit: ${err instanceof Error ? err.message : err}`);
1054
+ }
1055
+ }
1056
+ return ceiling > locked ? ceiling - locked : 0n;
1057
+ }
1058
+ /**
1059
+ * Headroom the paid requests in flight to this seller need: their count
1060
+ * times the channel's average verified cost per request, doubled. Zero until
1061
+ * the channel has served a request, so a fresh channel keeps the fixed rules.
1062
+ */
1063
+ _inFlightHeadroom(sellerPeerId) {
1064
+ const inFlight = BigInt(this._inFlightPaidRequests.get(sellerPeerId) ?? 0);
1065
+ const requests = this._metadata.get(sellerPeerId)?.cumulativeRequestCount ?? 0n;
1066
+ if (inFlight <= 0n || requests <= 0n)
1067
+ return 0n;
1068
+ const averageCost = (this._verifiedCost.get(sellerPeerId) ?? 0n) / requests;
1069
+ return inFlight * averageCost * IN_FLIGHT_HEADROOM_FACTOR;
1070
+ }
958
1071
  /**
959
1072
  * Sign an updated SpendingAuth after receiving a response.
960
1073
  *
@@ -968,7 +1081,10 @@ export class BuyerPaymentManager {
968
1081
  * @param responseStats Byte counts from the last response and seller's claimed cost.
969
1082
  * @returns The signed payload and whether a reserve top-up is needed.
970
1083
  */
971
- async signPerRequestAuth(sellerPeerId, responseStats) {
1084
+ signPerRequestAuth(sellerPeerId, responseStats) {
1085
+ return this._withSellerLock(sellerPeerId, () => this._signPerRequestAuth(sellerPeerId, responseStats));
1086
+ }
1087
+ async _signPerRequestAuth(sellerPeerId, responseStats) {
972
1088
  const session = this.getActiveSession(sellerPeerId);
973
1089
  if (!session) {
974
1090
  throw buyerFault(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}... — call authorizeSpending() first`, 'buyer-session-state');
@@ -1191,23 +1307,46 @@ export class BuyerPaymentManager {
1191
1307
  * against its own token count and signs a new SpendingAuth for the required
1192
1308
  * cumulative amount, capped at the reserve ceiling.
1193
1309
  */
1310
+ _withSellerLock(sellerPeerId, run) {
1311
+ return runQueued(this._sellerLocks, sellerPeerId, run);
1312
+ }
1194
1313
  async handleNeedAuth(sellerPeerId, payload, paymentMux) {
1195
1314
  if (this._oneOffChannels.has(payload.channelId)) {
1196
1315
  await this._handleOneOffNeedAuth(sellerPeerId, payload, paymentMux);
1197
1316
  return;
1198
1317
  }
1318
+ const topUp = await this._withSellerLock(sellerPeerId, () => this._signForNeedAuth(sellerPeerId, payload, paymentMux));
1319
+ if (topUp)
1320
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'handleNeedAuth');
1321
+ }
1322
+ /**
1323
+ * Validates a NeedAuth and signs the next cumulative authorization. Runs
1324
+ * under the seller lock, so it reads the latest signed amount and verified
1325
+ * cost. Returns whether a reserve top-up should follow.
1326
+ */
1327
+ async _signForNeedAuth(sellerPeerId, payload, paymentMux) {
1328
+ // The seller's NeedAuth can legitimately race ahead of the buyer's own
1329
+ // response processing (different muxes). Give the response path a moment
1330
+ // to record a unit-billed delivery before judging the claim. This waits
1331
+ // inside the lock on purpose: NeedAuths must be judged in arrival order,
1332
+ // or a later one signs past this request's cost and this one is dropped
1333
+ // as stale, never counted, and charged again at close.
1334
+ if (payload.billingUsage && payload.requestId && hasPositiveCost(payload.lastRequestCost)
1335
+ && this.getRequestBilling(payload.requestId)?.unitModel) {
1336
+ await this._waitForObservedUnitUsage(payload.requestId, OBSERVED_UNIT_USAGE_WAIT_MS);
1337
+ }
1199
1338
  const session = this.getActiveSession(sellerPeerId);
1200
1339
  if (!session) {
1201
1340
  debugWarn(`[BuyerPayment] NeedAuth for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
1202
- return;
1341
+ return false;
1203
1342
  }
1204
1343
  if (session.sessionId !== payload.channelId) {
1205
1344
  debugWarn(`[BuyerPayment] NeedAuth for unknown channel ${payload.channelId.slice(0, 18)}... — ignoring`);
1206
- return;
1345
+ return false;
1207
1346
  }
1208
1347
  if (this.isRequestCovered(sellerPeerId, payload.requestId)) {
1209
1348
  debugWarn(`[BuyerPayment] Refusing NeedAuth from ${sellerPeerId.slice(0, 12)}... for request ${payload.requestId} it served from a free allowance`);
1210
- return;
1349
+ return false;
1211
1350
  }
1212
1351
  const requestBilling = payload.requestId ? this.getRequestBilling(payload.requestId) : undefined;
1213
1352
  const buyerService = requestBilling?.context.service
@@ -1217,8 +1356,18 @@ export class BuyerPaymentManager {
1217
1356
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1218
1357
  // Reject stale/lower NeedAuth (monotonicity guard)
1219
1358
  if (requiredCumulativeAmount <= currentCumulative) {
1359
+ // A catch-up prompt (no response cost) for what is already signed but
1360
+ // not accepted (lost on the wire, or the seller restarted): resend the
1361
+ // same authorization, no higher. A post-response NeedAuth is not
1362
+ // answered this way: its authorization is usually still in flight.
1363
+ const catchUpPrompt = payload.lastRequestCost == null && payload.billingUsage == null;
1364
+ if (catchUpPrompt && payload.currentAcceptedCumulative != null && BigInt(payload.currentAcceptedCumulative) < currentCumulative) {
1365
+ debugLog(`[BuyerPayment] NeedAuth stale but seller accepted ${payload.currentAcceptedCumulative} < signed ${currentCumulative} — resending`);
1366
+ await this._resendCurrentSpendingAuth(sellerPeerId, paymentMux);
1367
+ return false;
1368
+ }
1220
1369
  debugLog(`[BuyerPayment] NeedAuth stale: required=${requiredCumulativeAmount} <= current=${currentCumulative} — ignoring`);
1221
- return;
1370
+ return false;
1222
1371
  }
1223
1372
  let acceptedServiceCost = 0n;
1224
1373
  let acceptedOutputImages = 0n;
@@ -1258,10 +1407,8 @@ export class BuyerPaymentManager {
1258
1407
  // a moment to record what was actually delivered before judging the
1259
1408
  // claim; a seller claiming delivery that never happens still gets
1260
1409
  // rejected once the wait expires.
1261
- const observedUnitUsage = requestBilling.observedUnitUsage
1262
- ?? (sellerTotalCost > 0n && payload.requestId
1263
- ? await this._waitForObservedUnitUsage(payload.requestId, OBSERVED_UNIT_USAGE_WAIT_MS)
1264
- : undefined);
1410
+ // Waited for at the top of _signForNeedAuth.
1411
+ const observedUnitUsage = requestBilling.observedUnitUsage;
1265
1412
  const claimedUnitCost = sellerTotalCost > tokenEstimate
1266
1413
  ? sellerTotalCost - tokenEstimate
1267
1414
  : 0n;
@@ -1285,14 +1432,14 @@ export class BuyerPaymentManager {
1285
1432
  }
1286
1433
  catch (err) {
1287
1434
  debugWarn(`[BuyerPayment] NeedAuth billingUsage rejected: ${err instanceof Error ? err.message : err}`);
1288
- return;
1435
+ return false;
1289
1436
  }
1290
1437
  }
1291
1438
  else if (payload.lastRequestCost) {
1292
1439
  const sellerCost = BigInt(payload.lastRequestCost);
1293
1440
  if (sellerCost > 0n && unitBillingModel && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1294
1441
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost omitted verifiable billingUsage`);
1295
- return;
1442
+ return false;
1296
1443
  }
1297
1444
  const sellerIn = reportedInputTokens;
1298
1445
  const sellerOut = reportedOutputTokens;
@@ -1316,11 +1463,11 @@ export class BuyerPaymentManager {
1316
1463
  const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimate) * this._costTolerance));
1317
1464
  if (buyerEstimate <= 0n && sellerCost > 0n && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1318
1465
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost recomputed to zero`);
1319
- return;
1466
+ return false;
1320
1467
  }
1321
1468
  if (buyerEstimate > 0n && sellerCost > maxAcceptable) {
1322
1469
  debugWarn(`[BuyerPayment] NeedAuth: seller claimed cost ${sellerCost} exceeds ${this._costTolerance}x buyer estimate ${buyerEstimate} — rejecting`);
1323
- return;
1470
+ return false;
1324
1471
  }
1325
1472
  debugLog(`[BuyerPayment] NeedAuth: seller cost=${sellerCost} buyer estimate=${buyerEstimate} (in=${sellerIn} cached=${sellerCached} out=${sellerOut}) — validated`);
1326
1473
  }
@@ -1344,7 +1491,7 @@ export class BuyerPaymentManager {
1344
1491
  needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
1345
1492
  if (maxSignable <= currentCumulative && !needsTopUp) {
1346
1493
  debugWarn(`[BuyerPayment] NeedAuth: maxSignable=${maxSignable} <= currentCumulative=${currentCumulative} — overdraft limit reached`);
1347
- return;
1494
+ return false;
1348
1495
  }
1349
1496
  }
1350
1497
  // When a topUp is needed, first sign at the current ceiling so the seller
@@ -1356,12 +1503,9 @@ export class BuyerPaymentManager {
1356
1503
  ? (maxSignable > currentCumulative ? maxSignable : currentCumulative)
1357
1504
  : (requiredCumulativeAmount < maxSignable ? requiredCumulativeAmount : maxSignable);
1358
1505
  if (effectiveAmount <= currentCumulative) {
1359
- // Nothing to sign — trigger topUp anyway to extend ceiling for next round
1360
- if (needsTopUp) {
1361
- await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'handleNeedAuth');
1362
- }
1506
+ // Nothing to sign; a top-up still extends the ceiling for the next round.
1363
1507
  debugWarn(`[BuyerPayment] NeedAuth: effectiveAmount=${effectiveAmount} <= currentCumulative=${currentCumulative} — cannot advance`);
1364
- return;
1508
+ return needsTopUp;
1365
1509
  }
1366
1510
  debugLog(`[BuyerPayment] NeedAuth: channel=${session.sessionId.slice(0, 18)}... required=${requiredCumulativeAmount} effective=${effectiveAmount}`);
1367
1511
  // Only NeedAuth frames with response cost/usage evidence represent a
@@ -1420,12 +1564,13 @@ export class BuyerPaymentManager {
1420
1564
  // settleable before topUp is allowed). Also proactively send the top-up
1421
1565
  // once the signed cumulative reaches the buyer's remaining-headroom
1422
1566
  // threshold; the seller may defer it until the contract gate is satisfied.
1423
- if (needsTopUp || this._needsTopUp(sellerPeerId)) {
1424
- await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'handleNeedAuth');
1425
- }
1426
- if (payload.requestId) {
1567
+ // Only a NeedAuth that reports a request's delivered cost is done with its
1568
+ // billing context; a catch-up or headroom prompt may name a request that is
1569
+ // still being served.
1570
+ if (payload.requestId && deliveredResponse) {
1427
1571
  this.clearRequestBilling(payload.requestId);
1428
1572
  }
1573
+ return needsTopUp || this._needsTopUp(sellerPeerId);
1429
1574
  }
1430
1575
  // ── Reserve top-up ─────────────────────────────────────────────
1431
1576
  /**
@@ -1433,20 +1578,78 @@ export class BuyerPaymentManager {
1433
1578
  * The seller must call reserve() on-chain again with the new signature.
1434
1579
  * Note: requires contract support for top-up (increaseDeposit on existing channelId).
1435
1580
  */
1436
- async topUpReserve(sellerPeerId, paymentMux) {
1581
+ /**
1582
+ * Top-ups for one seller run one at a time: each reads the chain and the
1583
+ * pending authorization before signing, and a parallel one would budget or
1584
+ * reconcile against state the other is about to replace. Kept apart from the
1585
+ * signing lock so authorizations never wait on these chain reads.
1586
+ */
1587
+ topUpReserve(sellerPeerId, paymentMux) {
1588
+ // A top-up that waited behind another is asked for again only if the
1589
+ // channel still needs one: the earlier top-up usually restored headroom.
1590
+ const ahead = this._topUpsQueued.get(sellerPeerId) ?? 0;
1591
+ this._topUpsQueued.set(sellerPeerId, ahead + 1);
1592
+ return runQueued(this._topUpLocks, sellerPeerId, async () => {
1593
+ try {
1594
+ if (ahead > 0 && !this._needsTopUp(sellerPeerId))
1595
+ return;
1596
+ await this._topUpReserve(sellerPeerId, paymentMux);
1597
+ }
1598
+ finally {
1599
+ const left = (this._topUpsQueued.get(sellerPeerId) ?? 1) - 1;
1600
+ if (left > 0)
1601
+ this._topUpsQueued.set(sellerPeerId, left);
1602
+ else
1603
+ this._topUpsQueued.delete(sellerPeerId);
1604
+ }
1605
+ });
1606
+ }
1607
+ async _topUpReserve(sellerPeerId, paymentMux) {
1437
1608
  const session = this.getActiveSession(sellerPeerId);
1438
1609
  if (!session) {
1439
1610
  debugWarn(`[BuyerPayment] topUpReserve: no active session for ${sellerPeerId.slice(0, 12)}...`);
1440
1611
  return;
1441
1612
  }
1613
+ // A top-up still waiting on-chain will lock its increase from the same
1614
+ // deposits: budget only what is left after it, so stacked top-ups never
1615
+ // authorize more than the buyer holds. One that already landed is out of
1616
+ // the available balance already, so read the deposit before counting it.
1617
+ const firstOutstanding = await this._outstandingTopUp(sellerPeerId, session.sessionId, this._getCeiling(sellerPeerId));
1618
+ if (firstOutstanding === null) {
1619
+ debugWarn(`[BuyerPayment] topUpReserve: channel for ${sellerPeerId.slice(0, 12)}... was replaced; skipping the top-up`);
1620
+ return;
1621
+ }
1622
+ let outstanding = firstOutstanding;
1442
1623
  const prevCeiling = this._getCeiling(sellerPeerId);
1443
- const newCeiling = prevCeiling + this._config.maxReserveAmountUsdc;
1444
- const additionalReserve = newCeiling - prevCeiling;
1624
+ // Under parallel load one configured step can be smaller than the work in
1625
+ // flight, which then runs past the locked reserve before the next top-up
1626
+ // is allowed: grow by enough to cover it, up to a bound.
1627
+ const step = this._config.maxReserveAmountUsdc;
1628
+ const maxStep = step * MAX_LOAD_TOPUP_MULTIPLE;
1629
+ const loadHeadroom = this._inFlightHeadroom(sellerPeerId);
1630
+ let additionalReserve = step;
1631
+ if (loadHeadroom > step)
1632
+ additionalReserve = loadHeadroom < maxStep ? loadHeadroom : maxStep;
1445
1633
  const deadline = this._authDeadline();
1446
1634
  try {
1447
- const balance = await this.getBalance();
1448
- if (balance.available < additionalReserve) {
1449
- throw buyerFault(`Insufficient buyer deposits for reserve top-up: available=${balance.available} required=${additionalReserve}`, 'buyer-deposits-insufficient');
1635
+ let balance = await this.getBalance();
1636
+ let budget = balance.available > outstanding ? balance.available - outstanding : 0n;
1637
+ // The pending top-up may have landed between the two reads, which counts
1638
+ // it twice: read both again before calling the budget short.
1639
+ if (outstanding > 0n && budget < additionalReserve) {
1640
+ const reread = await this._outstandingTopUp(sellerPeerId, session.sessionId, this._getCeiling(sellerPeerId));
1641
+ if (reread === null)
1642
+ return;
1643
+ outstanding = reread;
1644
+ balance = await this.getBalance();
1645
+ budget = balance.available > outstanding ? balance.available - outstanding : 0n;
1646
+ }
1647
+ // A load-sized step shrinks to the budget; the configured step is the floor.
1648
+ if (additionalReserve > step && budget < additionalReserve) {
1649
+ additionalReserve = budget > step ? budget : step;
1650
+ }
1651
+ if (budget < additionalReserve) {
1652
+ throw buyerFault(`Insufficient buyer deposits for reserve top-up: available=${balance.available} pending=${outstanding} required=${additionalReserve}`, 'buyer-deposits-insufficient');
1450
1653
  }
1451
1654
  }
1452
1655
  catch (err) {
@@ -1456,6 +1659,7 @@ export class BuyerPaymentManager {
1456
1659
  debugWarn(`[BuyerPayment] topUpReserve: unable to verify buyer deposits before signing top-up: ` +
1457
1660
  `${err instanceof Error ? err.message : err}`);
1458
1661
  }
1662
+ const newCeiling = prevCeiling + additionalReserve;
1459
1663
  debugLog(`[BuyerPayment] topUpReserve: channel=${session.sessionId.slice(0, 18)}... ceiling ${prevCeiling} → ${newCeiling}`);
1460
1664
  const reserveAuthSig = await this._signReserveAuth(session.sessionId, newCeiling, deadline);
1461
1665
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
@@ -1465,7 +1669,8 @@ export class BuyerPaymentManager {
1465
1669
  salt,
1466
1670
  maxAmount: newCeiling,
1467
1671
  deadline,
1468
- confirmedAmount: prevCeiling,
1672
+ // Stacked on a top-up still pending: the chain has confirmed only what that one had.
1673
+ confirmedAmount: prevCeiling - outstanding,
1469
1674
  };
1470
1675
  // Send ReserveAuth sig with reserve fields (same pattern as initial authorizeSpending).
1471
1676
  // The seller uses this to call topUp() on-chain with the new maxAmount.