@antseed/buyer-core 0.1.5 → 0.1.7

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.
@@ -70,6 +70,8 @@ export class BuyerPaymentManager {
70
70
  _initialReserveAmount = new Map();
71
71
  /** sellerPeerId -> salt used in the current reserve */
72
72
  _reserveSalt = new Map();
73
+ /** Latest ReserveAuth awaiting seller acknowledgement, including top-ups. */
74
+ _pendingReserveAuth = new Map();
73
75
  /** Cached EIP-712 domain — static for the lifetime of this manager. */
74
76
  _channelsDomain;
75
77
  constructor(identity, config, channelStore, sellerAddressResolver) {
@@ -92,26 +94,84 @@ export class BuyerPaymentManager {
92
94
  /** Hydrate cumulative tracking maps from persisted active buyer sessions. */
93
95
  _hydrateFromStore() {
94
96
  const activeChannels = this._channelStore.getActiveChannelsByBuyer(CHANNEL_ROLE.BUYER, this._identity.wallet.address);
97
+ const latestByPeer = new Map();
95
98
  for (const channel of activeChannels) {
96
- const peerId = channel.peerId;
97
- const persistedCumulative = BigInt(channel.authMax);
98
- this._cumulativeAmount.set(peerId, persistedCumulative);
99
- const metadata = this._sanitizeMetadata(this._channelStore.getChannelMetadata(channel));
100
- this._metadata.set(peerId, metadata);
101
- if (!this._disableMetadataV2Services) {
102
- this._persistServiceMetadata(channel.sessionId, metadata);
99
+ const existing = latestByPeer.get(channel.peerId);
100
+ if (!existing
101
+ || channel.createdAt > existing.createdAt
102
+ || (channel.createdAt === existing.createdAt && channel.updatedAt > existing.updatedAt)) {
103
+ latestByPeer.set(channel.peerId, channel);
103
104
  }
104
- // Hydrate verifiedCost to authMax so _maxSignable can grow beyond maxPerRequestUsdc.
105
- // Without this, maxSignable = 0 + maxPerRequestUsdc after restart, permanently capping
106
- // the cumulative and causing non-monotonic SpendingAuth rejections on the seller.
107
- this._verifiedCost.set(peerId, persistedCumulative);
108
- this._responseTokenTotals.set(peerId, {
109
- input: Number(channel.tokensDelivered),
110
- output: Number(channel.previousConsumption),
111
- requests: channel.requestCount,
112
- });
105
+ }
106
+ for (const channel of latestByPeer.values()) {
107
+ this._hydrateChannel(channel, true);
113
108
  }
114
109
  }
110
+ /** Adopt an authorization durably written outside this manager. */
111
+ adoptPersistedAuthorization(channel) {
112
+ if (channel.role !== CHANNEL_ROLE.BUYER
113
+ || channel.buyerEvmAddr.toLowerCase() !== this._identity.wallet.address.toLowerCase()) {
114
+ throw buyerFault('Cannot adopt an authorization owned by another buyer', 'buyer-session-state');
115
+ }
116
+ this._hydrateChannel(channel, false);
117
+ }
118
+ _hydrateChannel(channel, persistServiceMetadata) {
119
+ const peerId = channel.peerId;
120
+ const persistedCumulative = BigInt(channel.authMax);
121
+ this._cumulativeAmount.set(peerId, persistedCumulative);
122
+ const metadata = this._sanitizeMetadata(this._channelStore.getChannelMetadata(channel));
123
+ this._metadata.set(peerId, metadata);
124
+ if (persistServiceMetadata && !this._disableMetadataV2Services) {
125
+ this._persistServiceMetadata(channel.sessionId, metadata);
126
+ }
127
+ // Hydrate verifiedCost to authMax so _maxSignable can grow beyond maxPerRequestUsdc.
128
+ // Without this, maxSignable = 0 + maxPerRequestUsdc after restart, permanently capping
129
+ // the cumulative and causing non-monotonic SpendingAuth rejections on the seller.
130
+ this._verifiedCost.set(peerId, persistedCumulative);
131
+ // Stores predating browser recovery (including the current sqlite node
132
+ // store) omit these optional fields. Preserve their historical default
133
+ // ceiling instead of interpreting missing recovery state as a confirmed
134
+ // zero reserve.
135
+ const hasReserveRecoveryState = channel.confirmedReserveAmount != null
136
+ || channel.reserveMaxAmount != null
137
+ || channel.reserveAuthPending != null;
138
+ if (hasReserveRecoveryState) {
139
+ let confirmedReserve = 0n;
140
+ if (channel.confirmedReserveAmount != null) {
141
+ confirmedReserve = BigInt(channel.confirmedReserveAmount);
142
+ }
143
+ else if (channel.reserveMaxAmount != null && channel.reserveAuthPending !== true) {
144
+ confirmedReserve = BigInt(channel.reserveMaxAmount);
145
+ }
146
+ this._currentReserveCeiling.set(peerId, confirmedReserve);
147
+ if (confirmedReserve > 0n)
148
+ this._confirmedPeers.add(peerId);
149
+ if (channel.reserveAuthPending === true
150
+ && channel.latestReserveAuthSig
151
+ && channel.reserveSalt
152
+ && channel.reserveMaxAmount != null
153
+ && channel.latestReserveDeadline != null) {
154
+ this._pendingReserveAuth.set(peerId, {
155
+ signature: channel.latestReserveAuthSig,
156
+ salt: channel.reserveSalt,
157
+ maxAmount: BigInt(channel.reserveMaxAmount),
158
+ deadline: channel.latestReserveDeadline,
159
+ confirmedAmount: confirmedReserve,
160
+ });
161
+ }
162
+ }
163
+ if (channel.initialReserveAmount != null) {
164
+ this._initialReserveAmount.set(peerId, BigInt(channel.initialReserveAmount));
165
+ }
166
+ if (channel.reserveSalt) {
167
+ this._reserveSalt.set(peerId, channel.reserveSalt);
168
+ }
169
+ this._responseTokenTotals.set(peerId, {
170
+ input: Number(channel.tokensDelivered),
171
+ output: Number(channel.previousConsumption),
172
+ requests: channel.requestCount,
173
+ });
174
+ }
115
175
  get signer() {
116
176
  return this._signer;
117
177
  }
@@ -154,6 +214,7 @@ export class BuyerPaymentManager {
154
214
  this._currentReserveCeiling.delete(sellerPeerId);
155
215
  this._initialReserveAmount.delete(sellerPeerId);
156
216
  this._reserveSalt.delete(sellerPeerId);
217
+ this._pendingReserveAuth.delete(sellerPeerId);
157
218
  this._confirmedPeers.delete(sellerPeerId);
158
219
  this._rejectedPeers.delete(sellerPeerId);
159
220
  this._responseTokenTotals.delete(sellerPeerId);
@@ -172,6 +233,9 @@ export class BuyerPaymentManager {
172
233
  canReplayReserveAuth(sellerPeerId) {
173
234
  return this._reserveSalt.has(sellerPeerId);
174
235
  }
236
+ hasPendingReserveAuth(sellerPeerId) {
237
+ return this._pendingReserveAuth.has(sellerPeerId);
238
+ }
175
239
  clearLockConfirmation(sellerPeerId) {
176
240
  this._confirmedPeers.delete(sellerPeerId);
177
241
  this._rejectedPeers.delete(sellerPeerId);
@@ -191,6 +255,13 @@ export class BuyerPaymentManager {
191
255
  metadataHash: metadataHashHex,
192
256
  };
193
257
  const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
258
+ await this._commitAuthorization({
259
+ ...session,
260
+ latestBuyerSig: spendingAuthSig,
261
+ latestSpendingAuthSig: spendingAuthSig,
262
+ latestMetadata: encodedMetadata,
263
+ updatedAt: Date.now(),
264
+ }, currentMeta);
194
265
  paymentMux.sendSpendingAuth({
195
266
  channelId: session.sessionId,
196
267
  cumulativeAmount: cumulativeAmount.toString(),
@@ -207,7 +278,8 @@ export class BuyerPaymentManager {
207
278
  }
208
279
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? BigInt(session.authMax);
209
280
  let maxSignable = this._maxSignable(sellerPeerId);
210
- maxSignable = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'extendCurrentSpendingAuth');
281
+ const reopened = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'extendCurrentSpendingAuth');
282
+ maxSignable = reopened.maxSignable;
211
283
  const ceiling = this._getCeiling(sellerPeerId);
212
284
  // Prefer the seller-supplied target when present — a raw
213
285
  // `currentCumulative + minBudgetPerRequest` advance may still fall short
@@ -228,7 +300,9 @@ export class BuyerPaymentManager {
228
300
  return session.sessionId;
229
301
  }
230
302
  const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
231
- await this._sendUpdatedSpendingAuth(session, sellerPeerId, nextCumulative, currentMeta, paymentMux);
303
+ const spendingAuth = await this._commitUpdatedSpendingAuth(session, sellerPeerId, nextCumulative, currentMeta);
304
+ this._verifiedCost.set(sellerPeerId, reopened.verifiedCost);
305
+ paymentMux.sendSpendingAuth(spendingAuth);
232
306
  // Send topUp AFTER the SpendingAuth so the seller processes the higher
233
307
  // cumulative first, meeting the on-chain settle threshold for topUp.
234
308
  if (extendNeedsTopUp) {
@@ -262,13 +336,22 @@ export class BuyerPaymentManager {
262
336
  cumulativeAmount,
263
337
  metadataHash,
264
338
  };
339
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
340
+ const encodedMetadata = encodeMetadata(currentMeta);
341
+ await this._commitAuthorization({
342
+ ...session,
343
+ latestBuyerSig: spendingAuthSig,
344
+ latestSpendingAuthSig: spendingAuthSig,
345
+ latestMetadata: encodedMetadata,
346
+ updatedAt: Date.now(),
347
+ }, currentMeta);
265
348
  return {
266
349
  version: 1,
267
350
  channelId: session.sessionId,
268
351
  cumulativeAmount: cumulativeAmount.toString(),
269
352
  metadataHash,
270
- metadata: encodeMetadata(currentMeta),
271
- spendingAuthSig: await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg),
353
+ metadata: encodedMetadata,
354
+ spendingAuthSig,
272
355
  };
273
356
  }
274
357
  async resendReserveAuth(sellerPeerId, paymentMux) {
@@ -292,19 +375,73 @@ export class BuyerPaymentManager {
292
375
  deadline: BigInt(deadline),
293
376
  };
294
377
  const reserveAuthSig = await signReserveAuth(this._signer, this._channelsDomain, reserveMsg);
295
- paymentMux.sendSpendingAuth({
296
- channelId: session.sessionId,
297
- cumulativeAmount: session.authMax,
298
- metadataHash: ZERO_METADATA_HASH,
299
- metadata: encodeMetadata(this._sanitizeMetadata(this._metadata.get(sellerPeerId))),
300
- spendingAuthSig: reserveAuthSig,
301
- reserveSalt: salt,
302
- reserveMaxAmount: maxAmount.toString(),
303
- reserveDeadline: deadline,
378
+ const pending = {
379
+ signature: reserveAuthSig,
380
+ salt,
381
+ maxAmount,
382
+ deadline,
383
+ confirmedAmount: 0n,
384
+ };
385
+ await this._commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux, {
386
+ initialReserveAmount: maxAmount.toString(),
304
387
  });
305
388
  return session.sessionId;
306
389
  }
307
- _reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, context) {
390
+ /** Replay the latest unacknowledged initial reserve or top-up authorization. */
391
+ async resendPendingReserveAuth(sellerPeerId, paymentMux) {
392
+ const session = this.getActiveSession(sellerPeerId);
393
+ const existing = this._pendingReserveAuth.get(sellerPeerId);
394
+ if (!session || !existing) {
395
+ throw new Error(`[BuyerPayment] No pending reserve for seller ${sellerPeerId.slice(0, 12)}...`);
396
+ }
397
+ // Replaying an initial reserve requires a fresh AuthAck. A top-up does not:
398
+ // current sellers only acknowledge the initial/recovered channel, while
399
+ // top-up confirmation comes from the authoritative on-chain read.
400
+ if (existing.confirmedAmount === 0n) {
401
+ this._confirmedPeers.delete(sellerPeerId);
402
+ }
403
+ let pending = existing;
404
+ const now = Math.floor(Date.now() / 1000);
405
+ if (pending.deadline <= now + 30) {
406
+ const deadline = now + this._config.defaultAuthDurationSecs;
407
+ const signature = await signReserveAuth(this._signer, this._channelsDomain, {
408
+ channelId: session.sessionId,
409
+ maxAmount: pending.maxAmount,
410
+ deadline: BigInt(deadline),
411
+ });
412
+ pending = { ...pending, signature, deadline };
413
+ }
414
+ await this._commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux);
415
+ return session.sessionId;
416
+ }
417
+ /** Reconcile the locally usable ceiling with an authoritative on-chain read. */
418
+ async reconcileReserveAmount(sellerPeerId, onChainAmount) {
419
+ const session = this.getActiveSession(sellerPeerId);
420
+ if (!session)
421
+ return;
422
+ const pending = this._pendingReserveAuth.get(sellerPeerId);
423
+ const applied = pending != null && onChainAmount >= pending.maxAmount;
424
+ // The chain is authoritative even when it is ahead of our latest locally
425
+ // persisted authorization (for example after recovery on another device).
426
+ this._currentReserveCeiling.set(sellerPeerId, onChainAmount);
427
+ if (applied) {
428
+ this._pendingReserveAuth.delete(sellerPeerId);
429
+ // An initial ReserveAuth can land on-chain immediately before the browser
430
+ // crashes and lose its AuthAck. The authoritative channel read is an
431
+ // equivalent confirmation and must reopen signing before the first
432
+ // post-reload request is allowed through.
433
+ if (pending.confirmedAmount === 0n)
434
+ this._confirmedPeers.add(sellerPeerId);
435
+ }
436
+ const metadata = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
437
+ await this._commitAuthorization({
438
+ ...session,
439
+ reserveAuthPending: pending != null && !applied,
440
+ confirmedReserveAmount: onChainAmount.toString(),
441
+ updatedAt: Date.now(),
442
+ }, metadata);
443
+ }
444
+ _reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, context, verifiedCost = this._verifiedCost.get(sellerPeerId) ?? 0n) {
308
445
  // Overdraft-window unblock: when the buyer has already signed up to
309
446
  // `verified + maxPerRequest` and the seller returned 402 because `spent`
310
447
  // caught up, advance `verifiedCost` to the current signed cumulative so
@@ -321,15 +458,13 @@ export class BuyerPaymentManager {
321
458
  // by `verifiedCost + maxPerRequestUsdc` and are never used to mint new
322
459
  // trust directly.
323
460
  if (maxSignable > currentCumulative)
324
- return maxSignable;
325
- const previousVerified = this._verifiedCost.get(sellerPeerId) ?? 0n;
326
- if (currentCumulative <= previousVerified)
327
- return maxSignable;
328
- this._verifiedCost.set(sellerPeerId, currentCumulative);
329
- const reopened = this._maxSignable(sellerPeerId);
330
- debugLog(`[BuyerPayment] ${context}: advanced verifiedCost ${previousVerified} → ${currentCumulative} ` +
461
+ return { maxSignable, verifiedCost };
462
+ if (currentCumulative <= verifiedCost)
463
+ return { maxSignable, verifiedCost };
464
+ const reopened = this._maxSignableForVerified(sellerPeerId, currentCumulative);
465
+ debugLog(`[BuyerPayment] ${context}: will advance verifiedCost ${verifiedCost} → ${currentCumulative} ` +
331
466
  `to unblock overdraft window for ${sellerPeerId.slice(0, 12)}...`);
332
- return reopened;
467
+ return { maxSignable: reopened, verifiedCost: currentCumulative };
333
468
  }
334
469
  _needsCeilingAdvance(requestedAmount, maxSignable, ceiling) {
335
470
  return requestedAmount > maxSignable && maxSignable >= ceiling;
@@ -386,7 +521,62 @@ export class BuyerPaymentManager {
386
521
  _persistServiceMetadata(sessionId, metadata) {
387
522
  this._channelStore.replaceMetadataServiceTotals(sessionId, this._sanitizeMetadata(metadata).services);
388
523
  }
389
- async _sendUpdatedSpendingAuth(session, sellerPeerId, cumulativeAmount, metadata, paymentMux) {
524
+ async _commitAuthorization(channel, metadata) {
525
+ const sanitized = this._sanitizeMetadata(metadata);
526
+ const services = sanitized.services;
527
+ const snapshot = {
528
+ ...channel,
529
+ tokensDelivered: sanitized.cumulativeInputTokens.toString(),
530
+ previousConsumption: sanitized.cumulativeOutputTokens.toString(),
531
+ requestCount: Number(sanitized.cumulativeRequestCount),
532
+ latestMetadata: channel.latestMetadata ?? encodeMetadata(sanitized),
533
+ };
534
+ if (this._channelStore.commitAuthorization) {
535
+ await this._channelStore.commitAuthorization(snapshot, services);
536
+ return;
537
+ }
538
+ this._channelStore.replaceMetadataServiceTotals(snapshot.sessionId, services);
539
+ this._channelStore.upsertChannel(snapshot);
540
+ await this._channelStore.flush?.();
541
+ }
542
+ /**
543
+ * Durably persist a pending ReserveAuth, then transmit it and adopt the new
544
+ * ceiling in memory. Shared by reserve replay, pending-reserve replay, and
545
+ * reserve top-ups.
546
+ */
547
+ async _commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux, options = {}) {
548
+ const metadata = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
549
+ const encodedMetadata = encodeMetadata(metadata);
550
+ await this._commitAuthorization({
551
+ ...session,
552
+ deadline: pending.deadline,
553
+ latestBuyerSig: pending.signature,
554
+ latestMetadata: encodedMetadata,
555
+ reserveSalt: pending.salt,
556
+ ...(options.initialReserveAmount !== undefined
557
+ ? { initialReserveAmount: options.initialReserveAmount }
558
+ : {}),
559
+ reserveMaxAmount: pending.maxAmount.toString(),
560
+ latestReserveAuthSig: pending.signature,
561
+ latestReserveDeadline: pending.deadline,
562
+ reserveAuthPending: true,
563
+ confirmedReserveAmount: pending.confirmedAmount.toString(),
564
+ updatedAt: Date.now(),
565
+ }, metadata);
566
+ this._pendingReserveAuth.set(sellerPeerId, pending);
567
+ paymentMux.sendSpendingAuth({
568
+ channelId: session.sessionId,
569
+ cumulativeAmount: options.cumulativeAmount ?? session.authMax,
570
+ metadataHash: computeMetadataHash(metadata),
571
+ metadata: encodedMetadata,
572
+ spendingAuthSig: pending.signature,
573
+ reserveSalt: pending.salt,
574
+ reserveMaxAmount: pending.maxAmount.toString(),
575
+ reserveDeadline: pending.deadline,
576
+ });
577
+ this._currentReserveCeiling.set(sellerPeerId, pending.maxAmount);
578
+ }
579
+ async _commitUpdatedSpendingAuth(session, sellerPeerId, cumulativeAmount, metadata) {
390
580
  const sanitizedMetadata = this._sanitizeMetadata(metadata);
391
581
  const metadataHashHex = computeMetadataHash(sanitizedMetadata);
392
582
  const encodedMetadata = encodeMetadata(sanitizedMetadata);
@@ -396,20 +586,22 @@ export class BuyerPaymentManager {
396
586
  metadataHash: metadataHashHex,
397
587
  };
398
588
  const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
399
- this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
400
- this._persistServiceMetadata(session.sessionId, sanitizedMetadata);
401
- this._channelStore.upsertChannel({
589
+ await this._commitAuthorization({
402
590
  ...session,
403
591
  authMax: cumulativeAmount.toString(),
592
+ latestBuyerSig: spendingAuthSig,
593
+ latestSpendingAuthSig: spendingAuthSig,
594
+ latestMetadata: encodedMetadata,
404
595
  updatedAt: Date.now(),
405
- });
406
- paymentMux.sendSpendingAuth({
596
+ }, sanitizedMetadata);
597
+ this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
598
+ return {
407
599
  channelId: session.sessionId,
408
600
  cumulativeAmount: cumulativeAmount.toString(),
409
601
  metadataHash: metadataHashHex,
410
602
  metadata: encodedMetadata,
411
603
  spendingAuthSig,
412
- });
604
+ };
413
605
  }
414
606
  async _topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, context) {
415
607
  try {
@@ -485,11 +677,20 @@ export class BuyerPaymentManager {
485
677
  this._cumulativeAmount.set(sellerPeerId, 0n);
486
678
  this._metadata.set(sellerPeerId, this._sanitizeMetadata({ ...ZERO_METADATA }));
487
679
  this._verifiedCost.set(sellerPeerId, 0n);
488
- this._currentReserveCeiling.set(sellerPeerId, maxAmount);
680
+ this._currentReserveCeiling.set(sellerPeerId, 0n);
489
681
  this._initialReserveAmount.set(sellerPeerId, maxAmount);
490
682
  this._reserveSalt.set(sellerPeerId, salt);
683
+ this._pendingReserveAuth.set(sellerPeerId, {
684
+ signature: reserveAuthSig,
685
+ salt,
686
+ maxAmount,
687
+ deadline,
688
+ confirmedAmount: 0n,
689
+ });
491
690
  // Store session
492
691
  const now = Date.now();
692
+ const initialMetadata = this._sanitizeMetadata({ ...ZERO_METADATA });
693
+ const encodedInitialMetadata = encodeMetadata(initialMetadata);
493
694
  const session = {
494
695
  sessionId: channelId,
495
696
  peerId: sellerPeerId,
@@ -507,28 +708,36 @@ export class BuyerPaymentManager {
507
708
  settledAt: null,
508
709
  settledAmount: null,
509
710
  status: CHANNEL_STATUS.ACTIVE,
510
- latestBuyerSig: null,
711
+ latestBuyerSig: reserveAuthSig,
511
712
  latestSpendingAuthSig: null,
512
- latestMetadata: null,
713
+ latestMetadata: encodedInitialMetadata,
714
+ reserveSalt: salt,
715
+ initialReserveAmount: maxAmount.toString(),
716
+ reserveMaxAmount: maxAmount.toString(),
717
+ latestReserveAuthSig: reserveAuthSig,
718
+ latestReserveDeadline: deadline,
719
+ reserveAuthPending: true,
720
+ confirmedReserveAmount: '0',
513
721
  createdAt: now,
514
722
  updatedAt: now,
515
723
  };
516
- this._channelStore.upsertChannel(session);
724
+ await this._commitAuthorization(session, initialMetadata);
517
725
  // Send SpendingAuth via PaymentMux — reserve carries ReserveAuth sig
518
726
  paymentMux.sendSpendingAuth({
519
727
  channelId,
520
728
  cumulativeAmount: '0',
521
729
  metadataHash: ZERO_METADATA_HASH,
522
- metadata: encodeMetadata(ZERO_METADATA),
730
+ metadata: encodedInitialMetadata,
523
731
  spendingAuthSig: reserveAuthSig,
524
732
  reserveSalt: salt,
525
733
  reserveMaxAmount: maxAmount.toString(),
526
734
  reserveDeadline: deadline,
527
735
  });
736
+ this._currentReserveCeiling.set(sellerPeerId, maxAmount);
528
737
  return channelId;
529
738
  }
530
739
  // ── AuthAck handler ───────────────────────────────────────────
531
- handleAuthAck(sellerPeerId, payload) {
740
+ async handleAuthAck(sellerPeerId, payload) {
532
741
  const session = this.getActiveSession(sellerPeerId);
533
742
  if (!session) {
534
743
  debugWarn(`[BuyerPayment] AuthAck for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
@@ -539,6 +748,21 @@ export class BuyerPaymentManager {
539
748
  return;
540
749
  }
541
750
  this._confirmedPeers.add(sellerPeerId);
751
+ const pending = this._pendingReserveAuth.get(sellerPeerId);
752
+ // Existing sellers acknowledge initial reserve/recovery, but top-ups have
753
+ // no dedicated acknowledgement. Top-ups remain pending until an on-chain
754
+ // session read observes their ceiling.
755
+ if (pending?.confirmedAmount === 0n) {
756
+ this._currentReserveCeiling.set(sellerPeerId, pending.maxAmount);
757
+ this._pendingReserveAuth.delete(sellerPeerId);
758
+ const metadata = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
759
+ await this._commitAuthorization({
760
+ ...session,
761
+ reserveAuthPending: false,
762
+ confirmedReserveAmount: pending.maxAmount.toString(),
763
+ updatedAt: Date.now(),
764
+ }, metadata);
765
+ }
542
766
  debugLog(`[BuyerPayment] AuthAck confirmed: channel=${session.sessionId.slice(0, 18)}...`);
543
767
  }
544
768
  // ── Buyer-side cost verification ──────────────────────────────
@@ -588,6 +812,9 @@ export class BuyerPaymentManager {
588
812
  */
589
813
  _maxSignable(sellerPeerId) {
590
814
  const verified = this._verifiedCost.get(sellerPeerId) ?? 0n;
815
+ return this._maxSignableForVerified(sellerPeerId, verified);
816
+ }
817
+ _maxSignableForVerified(sellerPeerId, verified) {
591
818
  const ceiling = this._getCeiling(sellerPeerId);
592
819
  const maxSignable = verified + this._config.maxPerRequestUsdc;
593
820
  return maxSignable < ceiling ? maxSignable : ceiling;
@@ -631,6 +858,7 @@ export class BuyerPaymentManager {
631
858
  let estimatedCachedInputTokens = 0n;
632
859
  let byteEstimatedTokens = false;
633
860
  let buyerEstimatedRequestCost;
861
+ let verifiedCostDelta = 0n;
634
862
  const requestBilling = responseStats.requestId != null
635
863
  ? this.getRequestBilling(responseStats.requestId)
636
864
  : undefined;
@@ -650,11 +878,7 @@ export class BuyerPaymentManager {
650
878
  : 0n;
651
879
  const unitCost = validateUnitNormalizedCost(unitBillingModel, requestBilling.context, responseStats.unitUsage);
652
880
  buyerEstimatedRequestCost = tokenCost + unitCost;
653
- this._accumulateVerifiedCost(sellerPeerId, {
654
- cost: buyerEstimatedRequestCost,
655
- inputTokens: Number(estimatedInputTokens),
656
- outputTokens: Number(estimatedOutputTokens),
657
- });
881
+ verifiedCostDelta += buyerEstimatedRequestCost;
658
882
  debugLog(`[BuyerPayment] Hybrid billing-estimated cost=${buyerEstimatedRequestCost} service=${responseStats.service ?? 'unknown'}`);
659
883
  }
660
884
  else if (hasReportedTokens) {
@@ -672,14 +896,14 @@ export class BuyerPaymentManager {
672
896
  if (pricing) {
673
897
  const cost = computeCostUsdc(Number(freshInputTokens), Number(estimatedOutputTokens), pricing, Number(cachedInputTokens));
674
898
  buyerEstimatedRequestCost = cost;
675
- this._accumulateVerifiedCost(sellerPeerId, { cost, inputTokens: Number(estimatedInputTokens), outputTokens: Number(estimatedOutputTokens) });
899
+ verifiedCostDelta += cost;
676
900
  }
677
901
  else if (responseStats.sellerClaimedCost != null && responseStats.sellerClaimedCost > 0n) {
678
902
  // No local pricing available (e.g. after buyer restart before session pricing is restored).
679
903
  // Use seller's claimed cost for verifiedCost accumulation so _maxSignable can grow.
680
904
  // The seller's claim is still validated against tolerance below.
681
905
  buyerEstimatedRequestCost = responseStats.sellerClaimedCost;
682
- this._accumulateVerifiedCost(sellerPeerId, { cost: responseStats.sellerClaimedCost, inputTokens: Number(estimatedInputTokens), outputTokens: Number(estimatedOutputTokens) });
906
+ verifiedCostDelta += responseStats.sellerClaimedCost;
683
907
  }
684
908
  else {
685
909
  buyerEstimatedRequestCost = 0n;
@@ -694,7 +918,7 @@ export class BuyerPaymentManager {
694
918
  estimatedOutputTokens = estimate ? BigInt(estimate.outputTokens) : 0n;
695
919
  buyerEstimatedRequestCost = estimate ? estimate.cost : 0n;
696
920
  if (estimate) {
697
- this._accumulateVerifiedCost(sellerPeerId, estimate);
921
+ verifiedCostDelta += estimate.cost;
698
922
  }
699
923
  debugLog(`[BuyerPayment] Byte-estimated tokens (no reported): in=${estimatedInputTokens} out=${estimatedOutputTokens} cost=${buyerEstimatedRequestCost}`);
700
924
  }
@@ -745,11 +969,16 @@ export class BuyerPaymentManager {
745
969
  // for the next request (so the seller has budget to serve it).
746
970
  // maxSignable already caps at reserve ceiling, so one cap is sufficient
747
971
  const prevAmount = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
748
- const maxSignable = this._maxSignable(sellerPeerId);
972
+ const previousVerifiedCost = this._verifiedCost.get(sellerPeerId) ?? 0n;
973
+ const nextVerifiedCost = previousVerifiedCost + verifiedCostDelta;
974
+ const maxSignable = this._maxSignableForVerified(sellerPeerId, nextVerifiedCost);
749
975
  let newAmount = prevAmount + acceptedCost;
750
976
  if (newAmount > maxSignable)
751
977
  newAmount = maxSignable;
752
- this._cumulativeAmount.set(sellerPeerId, newAmount);
978
+ // A conservative recovery ceiling may temporarily be below an amount we
979
+ // already signed. SpendingAuth is cumulative and must never move backward.
980
+ if (newAmount < prevAmount)
981
+ newAmount = prevAmount;
753
982
  const signedDelta = newAmount - prevAmount;
754
983
  // Update cumulative metadata. NeedAuth may have counted this response
755
984
  // first, so deduplicate the response's service amount and usage together.
@@ -762,19 +991,6 @@ export class BuyerPaymentManager {
762
991
  requests: 1n,
763
992
  outputImages: estimatedOutputImages,
764
993
  }, { deliveredResponse: true, alreadyCounted }));
765
- if (!alreadyCounted)
766
- this._serviceTokensCounted.mark(responseStats.requestId);
767
- this._metadata.set(sellerPeerId, newMeta);
768
- this._persistServiceMetadata(session.sessionId, newMeta);
769
- this._reportSpend({
770
- sellerPeerId,
771
- requestId: responseStats.requestId ?? null,
772
- amountUsdc: signedDelta.toString(),
773
- inputTokens: (alreadyCounted ? 0n : estimatedInputTokens).toString(),
774
- cachedInputTokens: (alreadyCounted ? 0n : estimatedCachedInputTokens).toString(),
775
- outputTokens: (alreadyCounted ? 0n : estimatedOutputTokens).toString(),
776
- outputImages: (alreadyCounted ? 0n : estimatedOutputImages).toString(),
777
- });
778
994
  debugLog(`[BuyerPayment] signPerRequestAuth #${newMeta.cumulativeRequestCount}: ` +
779
995
  `thisReq in=${estimatedInputTokens} out=${estimatedOutputTokens} | ` +
780
996
  `cumulative in=${newMeta.cumulativeInputTokens} out=${newMeta.cumulativeOutputTokens} | ` +
@@ -791,11 +1007,28 @@ export class BuyerPaymentManager {
791
1007
  };
792
1008
  const spendingAuthSig = await signSpendingAuth(this._signer, channelsDomain, metadataMsg);
793
1009
  // Persist updated cumulative values to BuyerChannelStore
794
- this._channelStore.upsertChannel({
1010
+ await this._commitAuthorization({
795
1011
  ...session,
796
1012
  authMax: newAmount.toString(),
797
1013
  requestCount: Number(newMeta.cumulativeRequestCount),
1014
+ latestBuyerSig: spendingAuthSig,
1015
+ latestSpendingAuthSig: spendingAuthSig,
1016
+ latestMetadata: encodedMetadata,
798
1017
  updatedAt: Date.now(),
1018
+ }, newMeta);
1019
+ this._cumulativeAmount.set(sellerPeerId, newAmount);
1020
+ this._verifiedCost.set(sellerPeerId, nextVerifiedCost);
1021
+ this._metadata.set(sellerPeerId, newMeta);
1022
+ if (!alreadyCounted)
1023
+ this._serviceTokensCounted.mark(responseStats.requestId);
1024
+ this._reportSpend({
1025
+ sellerPeerId,
1026
+ requestId: responseStats.requestId ?? null,
1027
+ amountUsdc: signedDelta.toString(),
1028
+ inputTokens: (alreadyCounted ? 0n : estimatedInputTokens).toString(),
1029
+ cachedInputTokens: (alreadyCounted ? 0n : estimatedCachedInputTokens).toString(),
1030
+ outputTokens: (alreadyCounted ? 0n : estimatedOutputTokens).toString(),
1031
+ outputImages: (alreadyCounted ? 0n : estimatedOutputImages).toString(),
799
1032
  });
800
1033
  const payload = {
801
1034
  channelId: session.sessionId,
@@ -833,6 +1066,7 @@ export class BuyerPaymentManager {
833
1066
  }
834
1067
  let acceptedServiceCost = 0n;
835
1068
  let acceptedOutputImages = 0n;
1069
+ let verifiedCostDelta = 0n;
836
1070
  const reportedInputTokens = BigInt(payload.inputTokens ?? '0');
837
1071
  const reportedCachedInputTokens = BigInt(payload.cachedInputTokens ?? '0');
838
1072
  const reportedOutputTokens = BigInt(payload.outputTokens ?? '0');
@@ -885,11 +1119,7 @@ export class BuyerPaymentManager {
885
1119
  throw new Error(`Seller total cost ${sellerTotalCost} exceeds buyer estimate ${buyerEstimate}`);
886
1120
  }
887
1121
  acceptedServiceCost = sellerTotalCost;
888
- this._accumulateVerifiedCost(sellerPeerId, {
889
- cost: acceptedServiceCost,
890
- inputTokens: Number(reportedInputTokens),
891
- outputTokens: Number(reportedOutputTokens),
892
- });
1122
+ verifiedCostDelta += acceptedServiceCost;
893
1123
  debugLog(`[BuyerPayment] NeedAuth hybrid billing: token=${tokenEstimate} unit=${acceptedUnitCost} sellerTotal=${sellerTotalCost} — validated`);
894
1124
  }
895
1125
  catch (err) {
@@ -937,19 +1167,19 @@ export class BuyerPaymentManager {
937
1167
  debugLog(`[BuyerPayment] NeedAuth: seller cost=${sellerCost} (no local pricing, accepting)`);
938
1168
  }
939
1169
  // Accumulate verified cost from the seller's report
940
- this._accumulateVerifiedCost(sellerPeerId, {
941
- cost: sellerCost,
942
- inputTokens: Number(sellerIn),
943
- outputTokens: Number(sellerOut),
944
- });
1170
+ verifiedCostDelta += sellerCost;
945
1171
  }
946
1172
  // Cap at overdraft limit: verifiedCost + maxPerRequestUsdc, then at reserve ceiling.
947
1173
  // This prevents a malicious seller from claiming a small cost but requesting the full reserve.
948
- let maxSignable = this._maxSignable(sellerPeerId);
1174
+ const previousVerifiedCost = this._verifiedCost.get(sellerPeerId) ?? 0n;
1175
+ let nextVerifiedCost = previousVerifiedCost + verifiedCostDelta;
1176
+ let maxSignable = this._maxSignableForVerified(sellerPeerId, nextVerifiedCost);
949
1177
  const ceiling = this._getCeiling(sellerPeerId);
950
1178
  let needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
951
1179
  if (maxSignable <= currentCumulative && !needsTopUp) {
952
- maxSignable = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'handleNeedAuth');
1180
+ const reopened = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'handleNeedAuth', nextVerifiedCost);
1181
+ maxSignable = reopened.maxSignable;
1182
+ nextVerifiedCost = reopened.verifiedCost;
953
1183
  needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
954
1184
  if (maxSignable <= currentCumulative && !needsTopUp) {
955
1185
  debugWarn(`[BuyerPayment] NeedAuth: maxSignable=${maxSignable} <= currentCumulative=${currentCumulative} — overdraft limit reached`);
@@ -1001,26 +1231,25 @@ export class BuyerPaymentManager {
1001
1231
  requests: 1n,
1002
1232
  outputImages: acceptedOutputImages,
1003
1233
  }, { deliveredResponse, alreadyCounted }));
1234
+ // Persistence and transport failures must propagate to the connection
1235
+ // owner. In particular, swallowing an IndexedDB failure leaves the browser
1236
+ // connected with advanced in-memory counters but no durable signature.
1237
+ const spendingAuth = await this._commitUpdatedSpendingAuth(session, sellerPeerId, effectiveAmount, newMeta);
1238
+ this._verifiedCost.set(sellerPeerId, nextVerifiedCost);
1239
+ this._metadata.set(sellerPeerId, newMeta);
1004
1240
  if (deliveredResponse && !alreadyCounted)
1005
1241
  this._serviceTokensCounted.mark(payload.requestId);
1006
- this._metadata.set(sellerPeerId, newMeta);
1007
- // Send via PaymentMux
1008
- try {
1009
- await this._sendUpdatedSpendingAuth(session, sellerPeerId, effectiveAmount, newMeta, paymentMux);
1010
- this._reportSpend({
1011
- sellerPeerId,
1012
- requestId: payload.requestId ?? null,
1013
- amountUsdc: signedDelta.toString(),
1014
- inputTokens: (deliveredResponse && !alreadyCounted ? attributedInputTokens : 0n).toString(),
1015
- cachedInputTokens: (deliveredResponse && !alreadyCounted ? reportedCachedInputTokens : 0n).toString(),
1016
- outputTokens: (deliveredResponse && !alreadyCounted ? attributedOutputTokens : 0n).toString(),
1017
- outputImages: (deliveredResponse && !alreadyCounted ? acceptedOutputImages : 0n).toString(),
1018
- });
1019
- debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
1020
- }
1021
- catch {
1022
- debugLog(`[BuyerPayment] NeedAuth: connection closed before SpendingAuth could be sent`);
1023
- }
1242
+ this._reportSpend({
1243
+ sellerPeerId,
1244
+ requestId: payload.requestId ?? null,
1245
+ amountUsdc: signedDelta.toString(),
1246
+ inputTokens: (deliveredResponse && !alreadyCounted ? attributedInputTokens : 0n).toString(),
1247
+ cachedInputTokens: (deliveredResponse && !alreadyCounted ? reportedCachedInputTokens : 0n).toString(),
1248
+ outputTokens: (deliveredResponse && !alreadyCounted ? attributedOutputTokens : 0n).toString(),
1249
+ outputImages: (deliveredResponse && !alreadyCounted ? acceptedOutputImages : 0n).toString(),
1250
+ });
1251
+ paymentMux.sendSpendingAuth(spendingAuth);
1252
+ debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
1024
1253
  // Send topUp AFTER the SpendingAuth so the seller processes the higher
1025
1254
  // cumulative first — this ensures the on-chain settle amount meets the
1026
1255
  // contract's TopUpThresholdNotMet requirement (85% of deposit must be
@@ -1073,30 +1302,21 @@ export class BuyerPaymentManager {
1073
1302
  };
1074
1303
  const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
1075
1304
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1076
- const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
1077
- const metadataHashHex = computeMetadataHash(currentMeta);
1078
- const encodedMetadata = encodeMetadata(currentMeta);
1079
1305
  const salt = this._reserveSalt.get(sellerPeerId) ?? '0x' + '00'.repeat(32);
1306
+ const pending = {
1307
+ signature: reserveAuthSig,
1308
+ salt,
1309
+ maxAmount: newCeiling,
1310
+ deadline,
1311
+ confirmedAmount: prevCeiling,
1312
+ };
1080
1313
  // Send ReserveAuth sig with reserve fields (same pattern as initial authorizeSpending).
1081
1314
  // The seller uses this to call topUp() on-chain with the new maxAmount.
1082
- try {
1083
- paymentMux.sendSpendingAuth({
1084
- channelId: session.sessionId,
1085
- cumulativeAmount: currentCumulative.toString(),
1086
- metadataHash: metadataHashHex,
1087
- metadata: encodedMetadata,
1088
- spendingAuthSig: reserveAuthSig,
1089
- reserveSalt: salt,
1090
- reserveMaxAmount: newCeiling.toString(),
1091
- reserveDeadline: deadline,
1092
- });
1093
- // Only commit the new ceiling after the message is delivered
1094
- this._currentReserveCeiling.set(sellerPeerId, newCeiling);
1095
- debugLog(`[BuyerPayment] topUpReserve sent: newCeiling=${newCeiling}`);
1096
- }
1097
- catch {
1098
- debugLog(`[BuyerPayment] topUpReserve: connection closed before ReserveAuth could be sent`);
1099
- }
1315
+ await this._commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux, {
1316
+ cumulativeAmount: currentCumulative.toString(),
1317
+ initialReserveAmount: session.initialReserveAmount ?? prevCeiling.toString(),
1318
+ });
1319
+ debugLog(`[BuyerPayment] topUpReserve sent: newCeiling=${newCeiling}`);
1100
1320
  }
1101
1321
  // ── Queries ───────────────────────────────────────────────────
1102
1322
  /** Max USDC overdraft (unverified exposure) from buyer config. */