@antseed/buyer-core 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +24 -0
  3. package/dist/base-evm-client.d.ts +27 -0
  4. package/dist/base-evm-client.d.ts.map +1 -0
  5. package/dist/base-evm-client.js +116 -0
  6. package/dist/base-evm-client.js.map +1 -0
  7. package/dist/buyer-free-usage-manager.d.ts +44 -0
  8. package/dist/buyer-free-usage-manager.d.ts.map +1 -0
  9. package/dist/buyer-free-usage-manager.js +299 -0
  10. package/dist/buyer-free-usage-manager.js.map +1 -0
  11. package/dist/buyer-payment-manager.d.ts +309 -0
  12. package/dist/buyer-payment-manager.d.ts.map +1 -0
  13. package/dist/buyer-payment-manager.js +1246 -0
  14. package/dist/buyer-payment-manager.js.map +1 -0
  15. package/dist/buyer-payment-negotiator.d.ts +145 -0
  16. package/dist/buyer-payment-negotiator.d.ts.map +1 -0
  17. package/dist/buyer-payment-negotiator.js +1005 -0
  18. package/dist/buyer-payment-negotiator.js.map +1 -0
  19. package/dist/buyer-request-handler.d.ts +56 -0
  20. package/dist/buyer-request-handler.d.ts.map +1 -0
  21. package/dist/buyer-request-handler.js +491 -0
  22. package/dist/buyer-request-handler.js.map +1 -0
  23. package/dist/channel-session-state.d.ts +14 -0
  24. package/dist/channel-session-state.d.ts.map +1 -0
  25. package/dist/channel-session-state.js +26 -0
  26. package/dist/channel-session-state.js.map +1 -0
  27. package/dist/channel-store-types.d.ts +73 -0
  28. package/dist/channel-store-types.d.ts.map +1 -0
  29. package/dist/channel-store-types.js +20 -0
  30. package/dist/channel-store-types.js.map +1 -0
  31. package/dist/channel-usage-accounting.d.ts +18 -0
  32. package/dist/channel-usage-accounting.d.ts.map +1 -0
  33. package/dist/channel-usage-accounting.js +66 -0
  34. package/dist/channel-usage-accounting.js.map +1 -0
  35. package/dist/channels-client.d.ts +86 -0
  36. package/dist/channels-client.d.ts.map +1 -0
  37. package/dist/channels-client.js +194 -0
  38. package/dist/channels-client.js.map +1 -0
  39. package/dist/debug.d.ts +6 -0
  40. package/dist/debug.d.ts.map +1 -0
  41. package/dist/debug.js +57 -0
  42. package/dist/debug.js.map +1 -0
  43. package/dist/deposits-client.d.ts +30 -0
  44. package/dist/deposits-client.d.ts.map +1 -0
  45. package/dist/deposits-client.js +68 -0
  46. package/dist/deposits-client.js.map +1 -0
  47. package/dist/index.d.ts +23 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +23 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/interfaces.d.ts +62 -0
  52. package/dist/interfaces.d.ts.map +1 -0
  53. package/dist/interfaces.js +8 -0
  54. package/dist/interfaces.js.map +1 -0
  55. package/dist/payment-mux.d.ts +52 -0
  56. package/dist/payment-mux.d.ts.map +1 -0
  57. package/dist/payment-mux.js +160 -0
  58. package/dist/payment-mux.js.map +1 -0
  59. package/dist/pricing.d.ts +29 -0
  60. package/dist/pricing.d.ts.map +1 -0
  61. package/dist/pricing.js +39 -0
  62. package/dist/pricing.js.map +1 -0
  63. package/dist/proxy-mux.d.ts +70 -0
  64. package/dist/proxy-mux.d.ts.map +1 -0
  65. package/dist/proxy-mux.js +347 -0
  66. package/dist/proxy-mux.js.map +1 -0
  67. package/dist/response-auth.d.ts +31 -0
  68. package/dist/response-auth.d.ts.map +1 -0
  69. package/dist/response-auth.js +111 -0
  70. package/dist/response-auth.js.map +1 -0
  71. package/dist/response-usage.d.ts +10 -0
  72. package/dist/response-usage.d.ts.map +1 -0
  73. package/dist/response-usage.js +40 -0
  74. package/dist/response-usage.js.map +1 -0
  75. package/dist/seller-address-resolver.d.ts +50 -0
  76. package/dist/seller-address-resolver.d.ts.map +1 -0
  77. package/dist/seller-address-resolver.js +115 -0
  78. package/dist/seller-address-resolver.js.map +1 -0
  79. package/dist/unit-billing.d.ts +28 -0
  80. package/dist/unit-billing.d.ts.map +1 -0
  81. package/dist/unit-billing.js +80 -0
  82. package/dist/unit-billing.js.map +1 -0
  83. package/dist/usdc-utils.d.ts +9 -0
  84. package/dist/usdc-utils.d.ts.map +1 -0
  85. package/dist/usdc-utils.js +17 -0
  86. package/dist/usdc-utils.js.map +1 -0
  87. package/dist/verification-codec.d.ts +4 -0
  88. package/dist/verification-codec.d.ts.map +1 -0
  89. package/dist/verification-codec.js +38 -0
  90. package/dist/verification-codec.js.map +1 -0
  91. package/dist/verification-mux.d.ts +20 -0
  92. package/dist/verification-mux.d.ts.map +1 -0
  93. package/dist/verification-mux.js +100 -0
  94. package/dist/verification-mux.js.map +1 -0
  95. package/package.json +121 -0
@@ -0,0 +1,1246 @@
1
+ import { hexlify, randomBytes } from 'ethers';
2
+ import { DepositsClient } from './deposits-client.js';
3
+ import { signSpendingAuth, signReserveAuth, makeChannelsDomain, computeMetadataHash, encodeMetadata, ZERO_METADATA, ZERO_METADATA_HASH, computeChannelId, } from '@antseed/protocol/signatures';
4
+ import { debugLog, debugWarn } from './debug.js';
5
+ import { peerIdToAddress } from '@antseed/protocol/peer-id';
6
+ import { CHANNEL_ROLE, CHANNEL_STATUS } from './channel-store-types.js';
7
+ import { advanceUsageMetadata, CountedRequestTracker, RequestServiceTracker } from './channel-usage-accounting.js';
8
+ import { estimateCostFromBytes, computeCostUsdc, } from './pricing.js';
9
+ import { evaluateUnitBilling, validateUnitBillingUsage } from '@antseed/protocol/billing';
10
+ /** Default tolerance: accept seller claims up to 1.4x buyer's estimate. */
11
+ const DEFAULT_COST_TOLERANCE = 1.4;
12
+ /** Fraction of reserve ceiling at which to signal a top-up is needed.
13
+ * Trigger well before the contract's TOP_UP_SETTLED_THRESHOLD_BPS (85%)
14
+ * so that by the time the seller calls topUp() on-chain, enough has been
15
+ * settled to pass the threshold check. */
16
+ const DEFAULT_TOPUP_THRESHOLD = 0.65;
17
+ const REQUEST_BILLING_TTL_MS = 5 * 60_000;
18
+ const MAX_REQUEST_BILLING_ENTRIES = 512;
19
+ /** How long NeedAuth validation waits for the buyer's own response processing
20
+ * to record delivered unit usage before rejecting a positive claim. */
21
+ const OBSERVED_UNIT_USAGE_WAIT_MS = 5_000;
22
+ function validateUnitNormalizedCost(model, context, usage) {
23
+ return evaluateUnitBilling(model, context, usage);
24
+ }
25
+ /**
26
+ * Manages buyer-side payment sessions using EIP-712 SpendingAuth
27
+ * with cumulative authorization, bytes/4 cost verification, and overdraft control.
28
+ */
29
+ export class BuyerPaymentManager {
30
+ _identity;
31
+ _signer;
32
+ _depositsClient;
33
+ _config;
34
+ _channelStore;
35
+ /** In-memory map of active confirmed sessions by seller peerId for fast lookups. */
36
+ _confirmedPeers = new Set();
37
+ /** Peers that explicitly rejected our spending auth. */
38
+ _rejectedPeers = new Set();
39
+ _sellerAddressResolver;
40
+ /** sellerPeerId -> cumulative USDC amount in the latest SpendingAuth */
41
+ _cumulativeAmount = new Map();
42
+ /** sellerPeerId -> cumulative metadata for SpendingAuth */
43
+ _metadata = new Map();
44
+ /** sellerPeerId -> buyer-verified cumulative cost from bytes/4 */
45
+ _verifiedCost = new Map();
46
+ /** requestId -> service/model the buyer requested (from its own request body).
47
+ * Used in handleNeedAuth to validate cost with the correct pricing tier
48
+ * without trusting the seller's claim of which service was used. */
49
+ _requestService = new RequestServiceTracker();
50
+ /**
51
+ * requestId -> trusted buyer-owned billing identity, request facts, and mode.
52
+ *
53
+ * Used by NeedAuth validation so seller-reported billingUsage cannot choose
54
+ * the provider, protocol, service, billing model, or size/quality tier after
55
+ * the fact.
56
+ */
57
+ _requestBillingEntries = new Map();
58
+ _observedUsageWaiters = new Map();
59
+ /** sellerPeerId -> full pricing map (defaults + per-service overrides from peer metadata / 402) */
60
+ _sessionPricing = new Map();
61
+ /** Cumulative response token totals per seller, tracked independently of signing metadata. */
62
+ _responseTokenTotals = new Map();
63
+ /** sellerPeerId -> current on-chain reserve ceiling (can grow with top-ups) */
64
+ _currentReserveCeiling = new Map();
65
+ /** sellerPeerId -> original first-reserve amount for replaying reserve() safely. */
66
+ _initialReserveAmount = new Map();
67
+ /** sellerPeerId -> salt used in the current reserve */
68
+ _reserveSalt = new Map();
69
+ /** Cached EIP-712 domain — static for the lifetime of this manager. */
70
+ _channelsDomain;
71
+ constructor(identity, config, channelStore, sellerAddressResolver) {
72
+ this._identity = identity;
73
+ this._config = config;
74
+ this._sellerAddressResolver = sellerAddressResolver;
75
+ this._signer = identity.wallet;
76
+ this._depositsClient = new DepositsClient({
77
+ rpcUrl: config.rpcUrl,
78
+ ...(config.fallbackRpcUrls ? { fallbackRpcUrls: config.fallbackRpcUrls } : {}),
79
+ contractAddress: config.depositsContractAddress,
80
+ usdcAddress: config.usdcAddress,
81
+ evmChainId: config.chainId,
82
+ });
83
+ this._channelStore = channelStore;
84
+ this._channelsDomain = makeChannelsDomain(config.chainId, config.channelsContractAddress);
85
+ // Hydrate cumulative maps from persisted active sessions
86
+ this._hydrateFromStore();
87
+ }
88
+ /** Hydrate cumulative tracking maps from persisted active buyer sessions. */
89
+ _hydrateFromStore() {
90
+ const activeChannels = this._channelStore.getActiveChannelsByBuyer(CHANNEL_ROLE.BUYER, this._identity.wallet.address);
91
+ for (const channel of activeChannels) {
92
+ const peerId = channel.peerId;
93
+ const persistedCumulative = BigInt(channel.authMax);
94
+ this._cumulativeAmount.set(peerId, persistedCumulative);
95
+ const metadata = this._sanitizeMetadata(this._channelStore.getChannelMetadata(channel));
96
+ this._metadata.set(peerId, metadata);
97
+ if (!this._disableMetadataV2Services) {
98
+ this._persistServiceMetadata(channel.sessionId, metadata);
99
+ }
100
+ // Hydrate verifiedCost to authMax so _maxSignable can grow beyond maxPerRequestUsdc.
101
+ // Without this, maxSignable = 0 + maxPerRequestUsdc after restart, permanently capping
102
+ // the cumulative and causing non-monotonic SpendingAuth rejections on the seller.
103
+ this._verifiedCost.set(peerId, persistedCumulative);
104
+ this._responseTokenTotals.set(peerId, {
105
+ input: Number(channel.tokensDelivered),
106
+ output: Number(channel.previousConsumption),
107
+ requests: channel.requestCount,
108
+ });
109
+ }
110
+ }
111
+ get signer() {
112
+ return this._signer;
113
+ }
114
+ setSigner(signer) {
115
+ this._signer = signer;
116
+ }
117
+ get depositsClient() {
118
+ return this._depositsClient;
119
+ }
120
+ get _costTolerance() {
121
+ return this._config.costToleranceMultiplier ?? DEFAULT_COST_TOLERANCE;
122
+ }
123
+ get _disableMetadataV2Services() {
124
+ return this._config.disableMetadataV2Services === true;
125
+ }
126
+ _sanitizeMetadata(metadata) {
127
+ const current = metadata ?? ZERO_METADATA;
128
+ if (!this._disableMetadataV2Services)
129
+ return current;
130
+ return {
131
+ cumulativeInputTokens: current.cumulativeInputTokens,
132
+ cumulativeOutputTokens: current.cumulativeOutputTokens,
133
+ cumulativeRequestCount: current.cumulativeRequestCount,
134
+ services: [],
135
+ };
136
+ }
137
+ _advanceUsageMetadata(previous, service, delta) {
138
+ return advanceUsageMetadata(this._sanitizeMetadata(previous), this._disableMetadataV2Services ? undefined : service, delta);
139
+ }
140
+ _getCeiling(sellerPeerId) {
141
+ return this._currentReserveCeiling.get(sellerPeerId) ?? this._config.maxReserveAmountUsdc;
142
+ }
143
+ /** Clean up all in-memory state for a seller when the session ends. */
144
+ cleanupSession(sellerPeerId) {
145
+ this._cumulativeAmount.delete(sellerPeerId);
146
+ this._metadata.delete(sellerPeerId);
147
+ this._verifiedCost.delete(sellerPeerId);
148
+ this._sessionPricing.delete(sellerPeerId);
149
+ this._currentReserveCeiling.delete(sellerPeerId);
150
+ this._initialReserveAmount.delete(sellerPeerId);
151
+ this._reserveSalt.delete(sellerPeerId);
152
+ this._confirmedPeers.delete(sellerPeerId);
153
+ this._rejectedPeers.delete(sellerPeerId);
154
+ this._responseTokenTotals.delete(sellerPeerId);
155
+ this._clearRequestBillingForSeller(sellerPeerId);
156
+ }
157
+ getActiveSession(sellerPeerId) {
158
+ return this._channelStore.getActiveChannelByPeerAndBuyer(sellerPeerId, CHANNEL_ROLE.BUYER, this._identity.wallet.address);
159
+ }
160
+ retireSession(sellerPeerId, status, settledAmount) {
161
+ const session = this.getActiveSession(sellerPeerId);
162
+ if (session) {
163
+ this._channelStore.updateChannelStatus(session.sessionId, status, settledAmount !== undefined ? settledAmount.toString() : undefined);
164
+ }
165
+ this.cleanupSession(sellerPeerId);
166
+ }
167
+ canReplayReserveAuth(sellerPeerId) {
168
+ return this._reserveSalt.has(sellerPeerId);
169
+ }
170
+ clearLockConfirmation(sellerPeerId) {
171
+ this._confirmedPeers.delete(sellerPeerId);
172
+ this._rejectedPeers.delete(sellerPeerId);
173
+ }
174
+ async resendCurrentSpendingAuth(sellerPeerId, paymentMux) {
175
+ const session = this.getActiveSession(sellerPeerId);
176
+ if (!session) {
177
+ throw new Error(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`);
178
+ }
179
+ const cumulativeAmount = this._cumulativeAmount.get(sellerPeerId) ?? BigInt(session.authMax);
180
+ const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
181
+ const metadataHashHex = computeMetadataHash(currentMeta);
182
+ const encodedMetadata = encodeMetadata(currentMeta);
183
+ const metadataMsg = {
184
+ channelId: session.sessionId,
185
+ cumulativeAmount,
186
+ metadataHash: metadataHashHex,
187
+ };
188
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
189
+ paymentMux.sendSpendingAuth({
190
+ channelId: session.sessionId,
191
+ cumulativeAmount: cumulativeAmount.toString(),
192
+ metadataHash: metadataHashHex,
193
+ metadata: encodedMetadata,
194
+ spendingAuthSig,
195
+ });
196
+ return session.sessionId;
197
+ }
198
+ async extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative) {
199
+ const session = this.getActiveSession(sellerPeerId);
200
+ if (!session) {
201
+ throw new Error(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`);
202
+ }
203
+ const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? BigInt(session.authMax);
204
+ let maxSignable = this._maxSignable(sellerPeerId);
205
+ maxSignable = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'extendCurrentSpendingAuth');
206
+ const ceiling = this._getCeiling(sellerPeerId);
207
+ // Prefer the seller-supplied target when present — a raw
208
+ // `currentCumulative + minBudgetPerRequest` advance may still fall short
209
+ // of what the seller has already spent, producing an infinite 402 loop.
210
+ const minAdvance = currentCumulative + minBudgetPerRequest;
211
+ const requestedAmount = targetCumulative != null && targetCumulative > minAdvance
212
+ ? targetCumulative
213
+ : minAdvance;
214
+ const nextCumulative = requestedAmount < maxSignable ? requestedAmount : maxSignable;
215
+ const extendNeedsTopUp = this._needsCeilingAdvance(requestedAmount, maxSignable, ceiling);
216
+ if (nextCumulative <= currentCumulative) {
217
+ // Nothing to sign at current ceiling — try topUp anyway for next round
218
+ if (extendNeedsTopUp) {
219
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'extendCurrentSpendingAuth');
220
+ }
221
+ debugWarn(`[BuyerPayment] Cannot extend active session for ${sellerPeerId.slice(0, 12)}... ` +
222
+ `(current=${currentCumulative} maxSignable=${maxSignable} target=${targetCumulative ?? 'n/a'})`);
223
+ return session.sessionId;
224
+ }
225
+ const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
226
+ await this._sendUpdatedSpendingAuth(session, sellerPeerId, nextCumulative, currentMeta, paymentMux);
227
+ // Send topUp AFTER the SpendingAuth so the seller processes the higher
228
+ // cumulative first, meeting the on-chain settle threshold for topUp.
229
+ if (extendNeedsTopUp) {
230
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'extendCurrentSpendingAuth');
231
+ }
232
+ return session.sessionId;
233
+ }
234
+ /**
235
+ * Build a CloseChannelRequest for an active session.
236
+ *
237
+ * With `includeAuth` (the default) the buyer signs its current cumulative so
238
+ * a seller that lost the last SpendingAuth can still close at the full
239
+ * amount owed. Signing costs nothing extra: the cumulative is unchanged, so
240
+ * this authorizes no more than the seller could already claim. Pass
241
+ * `includeAuth: false` to send a bare request and let the seller close using
242
+ * whatever auth it already holds.
243
+ */
244
+ async buildCloseChannelRequest(sellerPeerId, { includeAuth = true } = {}) {
245
+ const session = this.getActiveSession(sellerPeerId);
246
+ if (!session) {
247
+ throw new Error(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`);
248
+ }
249
+ const cumulativeAmount = this._cumulativeAmount.get(sellerPeerId) ?? BigInt(session.authMax);
250
+ if (!includeAuth || cumulativeAmount <= 0n) {
251
+ return { version: 1, channelId: session.sessionId };
252
+ }
253
+ const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
254
+ const metadataHash = computeMetadataHash(currentMeta);
255
+ const metadataMsg = {
256
+ channelId: session.sessionId,
257
+ cumulativeAmount,
258
+ metadataHash,
259
+ };
260
+ return {
261
+ version: 1,
262
+ channelId: session.sessionId,
263
+ cumulativeAmount: cumulativeAmount.toString(),
264
+ metadataHash,
265
+ metadata: encodeMetadata(currentMeta),
266
+ spendingAuthSig: await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg),
267
+ };
268
+ }
269
+ async resendReserveAuth(sellerPeerId, paymentMux) {
270
+ const session = this.getActiveSession(sellerPeerId);
271
+ const salt = this._reserveSalt.get(sellerPeerId);
272
+ if (!session || !salt) {
273
+ throw new Error(`[BuyerPayment] No replayable reserve for seller ${sellerPeerId.slice(0, 12)}...`);
274
+ }
275
+ // Force a fresh AuthAck after replaying the reserve path.
276
+ this._confirmedPeers.delete(sellerPeerId);
277
+ const replayAmount = this._initialReserveAmount.get(sellerPeerId)
278
+ ?? this._currentReserveCeiling.get(sellerPeerId)
279
+ ?? this._config.maxReserveAmountUsdc;
280
+ const maxAmount = replayAmount > this._config.maxReserveAmountUsdc
281
+ ? this._config.maxReserveAmountUsdc
282
+ : replayAmount;
283
+ const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
284
+ const reserveMsg = {
285
+ channelId: session.sessionId,
286
+ maxAmount,
287
+ deadline: BigInt(deadline),
288
+ };
289
+ const reserveAuthSig = await signReserveAuth(this._signer, this._channelsDomain, reserveMsg);
290
+ paymentMux.sendSpendingAuth({
291
+ channelId: session.sessionId,
292
+ cumulativeAmount: session.authMax,
293
+ metadataHash: ZERO_METADATA_HASH,
294
+ metadata: encodeMetadata(this._sanitizeMetadata(this._metadata.get(sellerPeerId))),
295
+ spendingAuthSig: reserveAuthSig,
296
+ reserveSalt: salt,
297
+ reserveMaxAmount: maxAmount.toString(),
298
+ reserveDeadline: deadline,
299
+ });
300
+ return session.sessionId;
301
+ }
302
+ _reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, context) {
303
+ // Overdraft-window unblock: when the buyer has already signed up to
304
+ // `verified + maxPerRequest` and the seller returned 402 because `spent`
305
+ // caught up, advance `verifiedCost` to the current signed cumulative so
306
+ // the window reopens. The buyer has already committed to pay
307
+ // `currentCumulative` via the signed SpendingAuth, so the seller can
308
+ // already claim that much on-chain — advancing verified to match doesn't
309
+ // expose new funds, it just reclaims overdraft headroom.
310
+ //
311
+ // SECURITY: the trust anchor here is `currentCumulative`, NOT any
312
+ // seller-supplied target. A malicious seller could overstate required
313
+ // spend in a 402 / NeedAuth path in an attempt to drain the reserve. We
314
+ // defend by only advancing verifiedCost to the amount the buyer has
315
+ // already signed. Seller-provided values remain destination hints bounded
316
+ // by `verifiedCost + maxPerRequestUsdc` and are never used to mint new
317
+ // trust directly.
318
+ if (maxSignable > currentCumulative)
319
+ return maxSignable;
320
+ const previousVerified = this._verifiedCost.get(sellerPeerId) ?? 0n;
321
+ if (currentCumulative <= previousVerified)
322
+ return maxSignable;
323
+ this._verifiedCost.set(sellerPeerId, currentCumulative);
324
+ const reopened = this._maxSignable(sellerPeerId);
325
+ debugLog(`[BuyerPayment] ${context}: advanced verifiedCost ${previousVerified} → ${currentCumulative} ` +
326
+ `to unblock overdraft window for ${sellerPeerId.slice(0, 12)}...`);
327
+ return reopened;
328
+ }
329
+ _needsCeilingAdvance(requestedAmount, maxSignable, ceiling) {
330
+ return requestedAmount > maxSignable && maxSignable >= ceiling;
331
+ }
332
+ /**
333
+ * Both signPerRequestAuth (buyer-initiated) and handleNeedAuth (seller-initiated)
334
+ * can fire for the same request when the proactive auth doesn't fully cover the
335
+ * seller's required cumulative. Whichever path counts a request's tokens first
336
+ * records its requestId here so the other path attributes only the amount delta.
337
+ */
338
+ _serviceTokensCounted = new CountedRequestTracker();
339
+ _spendListener = null;
340
+ /**
341
+ * Observe per-request spend as it is signed. Used to attribute cost to the
342
+ * caller's own unit of work (a tool conversation, say), which only the layer
343
+ * that issued the request can know.
344
+ */
345
+ setSpendListener(listener) {
346
+ this._spendListener = listener;
347
+ }
348
+ _reportSpend(event) {
349
+ if (!this._spendListener)
350
+ return;
351
+ try {
352
+ this._spendListener(event);
353
+ }
354
+ catch (err) {
355
+ // Accounting is a bystander here — never let it break the payment path.
356
+ debugWarn(`[BuyerPayment] spend listener threw: ${err instanceof Error ? err.message : err}`);
357
+ }
358
+ }
359
+ _cleanupRequestBillingCache(now = Date.now()) {
360
+ for (const [requestId, entry] of this._requestBillingEntries) {
361
+ if (now - entry.createdAtMs > REQUEST_BILLING_TTL_MS) {
362
+ this.clearRequestBilling(requestId);
363
+ }
364
+ }
365
+ }
366
+ _trimRequestBillingCache() {
367
+ while (this._requestBillingEntries.size > MAX_REQUEST_BILLING_ENTRIES) {
368
+ const oldest = this._requestBillingEntries.keys().next().value;
369
+ if (oldest === undefined)
370
+ break;
371
+ this.clearRequestBilling(oldest);
372
+ }
373
+ }
374
+ _clearRequestBillingForSeller(sellerPeerId) {
375
+ for (const [requestId, entry] of this._requestBillingEntries) {
376
+ if (entry.context.sellerPeerId === sellerPeerId) {
377
+ this.clearRequestBilling(requestId);
378
+ }
379
+ }
380
+ }
381
+ _persistServiceMetadata(sessionId, metadata) {
382
+ this._channelStore.replaceMetadataServiceTotals(sessionId, this._sanitizeMetadata(metadata).services);
383
+ }
384
+ async _sendUpdatedSpendingAuth(session, sellerPeerId, cumulativeAmount, metadata, paymentMux) {
385
+ const sanitizedMetadata = this._sanitizeMetadata(metadata);
386
+ const metadataHashHex = computeMetadataHash(sanitizedMetadata);
387
+ const encodedMetadata = encodeMetadata(sanitizedMetadata);
388
+ const metadataMsg = {
389
+ channelId: session.sessionId,
390
+ cumulativeAmount,
391
+ metadataHash: metadataHashHex,
392
+ };
393
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
394
+ this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
395
+ this._persistServiceMetadata(session.sessionId, sanitizedMetadata);
396
+ this._channelStore.upsertChannel({
397
+ ...session,
398
+ authMax: cumulativeAmount.toString(),
399
+ updatedAt: Date.now(),
400
+ });
401
+ paymentMux.sendSpendingAuth({
402
+ channelId: session.sessionId,
403
+ cumulativeAmount: cumulativeAmount.toString(),
404
+ metadataHash: metadataHashHex,
405
+ metadata: encodedMetadata,
406
+ spendingAuthSig,
407
+ });
408
+ }
409
+ async _topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, context) {
410
+ try {
411
+ await this.topUpReserve(sellerPeerId, paymentMux);
412
+ }
413
+ catch (err) {
414
+ debugWarn(`[BuyerPayment] ${context}: topUpReserve failed: ${err instanceof Error ? err.message : err}`);
415
+ }
416
+ }
417
+ // ── Spending Authorization ────────────────────────────────────
418
+ /**
419
+ * Sign and send an initial EIP-712 SpendingAuth to a seller.
420
+ * The initial cumulativeAmount is set to the seller's minBudgetPerRequest.
421
+ *
422
+ * @param pricing Token pricing from the seller's 402 / peer metadata.
423
+ * @param pricingMap Full pricing map (defaults + per-service) from peer metadata. If provided,
424
+ * merges with existing session pricing. The `pricing` arg is used as the service-specific
425
+ * override for the service that triggered the 402.
426
+ */
427
+ async authorizeSpending(sellerPeerId, paymentMux, minBudgetPerRequest, reserveAmountOrPricing, pricingArg, pricingMap, metadataArg) {
428
+ const sellerEvmAddr = this._sellerAddressResolver
429
+ ? await this._sellerAddressResolver.resolveSellerAddress(sellerPeerId, metadataArg)
430
+ : peerIdToAddress(sellerPeerId);
431
+ const reserveAmount = typeof reserveAmountOrPricing === 'bigint'
432
+ ? reserveAmountOrPricing
433
+ : this._config.maxReserveAmountUsdc;
434
+ const pricing = typeof reserveAmountOrPricing === 'bigint'
435
+ ? pricingArg
436
+ : reserveAmountOrPricing;
437
+ // Budget validation: reject if seller demands more than buyer's overdraft limit
438
+ if (minBudgetPerRequest > this._config.maxPerRequestUsdc) {
439
+ debugWarn(`[BuyerPayment] Seller ${sellerPeerId.slice(0, 12)}... minBudgetPerRequest=${minBudgetPerRequest} exceeds maxPerRequestUsdc=${this._config.maxPerRequestUsdc} — not authorizing`);
440
+ return '';
441
+ }
442
+ // Clear confirmation state so we wait for a fresh AuthAck on the new session
443
+ this._confirmedPeers.delete(sellerPeerId);
444
+ // Store full pricing map (defaults + all per-service overrides).
445
+ // Merge 402-negotiated pricing on top of peer-metadata defaults so
446
+ // the seller's live rate takes precedence over cached peer metadata.
447
+ if (pricingMap) {
448
+ const mergedDefaults = pricing
449
+ ? { ...pricingMap.defaults, ...pricing }
450
+ : pricingMap.defaults;
451
+ this._sessionPricing.set(sellerPeerId, { defaults: mergedDefaults, services: pricingMap.services });
452
+ }
453
+ else if (pricing) {
454
+ // Legacy: single pricing, store as defaults
455
+ const existing = this._sessionPricing.get(sellerPeerId);
456
+ this._sessionPricing.set(sellerPeerId, {
457
+ defaults: pricing,
458
+ services: existing?.services ?? {},
459
+ });
460
+ }
461
+ // Generate random salt and compute deterministic channelId
462
+ const salt = hexlify(randomBytes(32));
463
+ const buyerEvmAddr = this._identity.wallet.address;
464
+ const channelId = computeChannelId(buyerEvmAddr, sellerEvmAddr, salt);
465
+ const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
466
+ debugLog(`[BuyerPayment] authorizeSpending: channel=${channelId.slice(0, 18)}... seller=${sellerPeerId.slice(0, 12)}... amount=${minBudgetPerRequest}`);
467
+ // Sign ReserveAuth — binds channelId, maxAmount, deadline on-chain
468
+ const channelsDomain = this._channelsDomain;
469
+ const maxAmount = reserveAmount;
470
+ const reserveMsg = {
471
+ channelId,
472
+ maxAmount,
473
+ deadline: BigInt(deadline),
474
+ };
475
+ const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
476
+ // Initialize state for this session.
477
+ // Start cumulative at 0 — the initial message is a ReserveAuth (not a SpendingAuth).
478
+ // The first real SpendingAuth will be sent by handleNeedAuth after the seller serves
479
+ // the first request and reports its cost.
480
+ this._cumulativeAmount.set(sellerPeerId, 0n);
481
+ this._metadata.set(sellerPeerId, this._sanitizeMetadata({ ...ZERO_METADATA }));
482
+ this._verifiedCost.set(sellerPeerId, 0n);
483
+ this._currentReserveCeiling.set(sellerPeerId, maxAmount);
484
+ this._initialReserveAmount.set(sellerPeerId, maxAmount);
485
+ this._reserveSalt.set(sellerPeerId, salt);
486
+ // Store session
487
+ const now = Date.now();
488
+ const session = {
489
+ sessionId: channelId,
490
+ peerId: sellerPeerId,
491
+ role: CHANNEL_ROLE.BUYER,
492
+ sellerEvmAddr,
493
+ buyerEvmAddr: this._identity.wallet.address,
494
+ nonce: 0,
495
+ authMax: '0',
496
+ deadline,
497
+ previousSessionId: '0x' + '0'.repeat(64),
498
+ previousConsumption: '0',
499
+ tokensDelivered: '0',
500
+ requestCount: 0,
501
+ reservedAt: now,
502
+ settledAt: null,
503
+ settledAmount: null,
504
+ status: CHANNEL_STATUS.ACTIVE,
505
+ latestBuyerSig: null,
506
+ latestSpendingAuthSig: null,
507
+ latestMetadata: null,
508
+ createdAt: now,
509
+ updatedAt: now,
510
+ };
511
+ this._channelStore.upsertChannel(session);
512
+ // Send SpendingAuth via PaymentMux — reserve carries ReserveAuth sig
513
+ paymentMux.sendSpendingAuth({
514
+ channelId,
515
+ cumulativeAmount: '0',
516
+ metadataHash: ZERO_METADATA_HASH,
517
+ metadata: encodeMetadata(ZERO_METADATA),
518
+ spendingAuthSig: reserveAuthSig,
519
+ reserveSalt: salt,
520
+ reserveMaxAmount: maxAmount.toString(),
521
+ reserveDeadline: deadline,
522
+ });
523
+ return channelId;
524
+ }
525
+ // ── AuthAck handler ───────────────────────────────────────────
526
+ handleAuthAck(sellerPeerId, payload) {
527
+ const session = this.getActiveSession(sellerPeerId);
528
+ if (!session) {
529
+ debugWarn(`[BuyerPayment] AuthAck for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
530
+ return;
531
+ }
532
+ if (session.sessionId !== payload.channelId) {
533
+ debugWarn(`[BuyerPayment] AuthAck channel mismatch: expected=${session.sessionId.slice(0, 18)}... got=${payload.channelId.slice(0, 18)}...`);
534
+ return;
535
+ }
536
+ this._confirmedPeers.add(sellerPeerId);
537
+ debugLog(`[BuyerPayment] AuthAck confirmed: channel=${session.sessionId.slice(0, 18)}...`);
538
+ }
539
+ // ── Buyer-side cost verification ──────────────────────────────
540
+ /**
541
+ * Estimate tokens and cost from response content without updating state.
542
+ */
543
+ _estimateResponseCost(sellerPeerId, inputBytes, outputBytes, service) {
544
+ const pricing = this.getSessionPricing(sellerPeerId, service);
545
+ if (!pricing)
546
+ return null;
547
+ return estimateCostFromBytes(inputBytes, outputBytes, pricing);
548
+ }
549
+ /**
550
+ * Accumulate a cost estimate into verifiedCost.
551
+ */
552
+ _accumulateVerifiedCost(sellerPeerId, estimate) {
553
+ const prev = this._verifiedCost.get(sellerPeerId) ?? 0n;
554
+ const newVerified = prev + estimate.cost;
555
+ this._verifiedCost.set(sellerPeerId, newVerified);
556
+ return newVerified;
557
+ }
558
+ /**
559
+ * Record response content and update the buyer's verified cost.
560
+ * Call this after receiving each response from the seller.
561
+ *
562
+ * NOTE: Do not call this AND signPerRequestAuth for the same response —
563
+ * signPerRequestAuth already updates verifiedCost internally.
564
+ *
565
+ * @returns The updated verified cost and estimated tokens, or null if no pricing is available.
566
+ */
567
+ recordResponseBytes(sellerPeerId, inputBytes, outputBytes) {
568
+ const estimate = this._estimateResponseCost(sellerPeerId, inputBytes, outputBytes);
569
+ if (!estimate)
570
+ return null;
571
+ const newVerified = this._accumulateVerifiedCost(sellerPeerId, estimate);
572
+ const inSize = inputBytes.length;
573
+ const outSize = outputBytes.length;
574
+ debugLog(`[BuyerPayment] recordResponseBytes: seller=${sellerPeerId.slice(0, 12)}... ` +
575
+ `in=${inSize}B→${estimate.inputTokens}tok out=${outSize}B→${estimate.outputTokens}tok ` +
576
+ `requestCost=${estimate.cost} verifiedCost=${newVerified}`);
577
+ return { verifiedCost: newVerified, inputTokens: estimate.inputTokens, outputTokens: estimate.outputTokens };
578
+ }
579
+ // ── Per-request authorization (overdraft model) ─────────────
580
+ /**
581
+ * Compute the max signable cumulative amount based on the overdraft model:
582
+ * maxSignable = verifiedCost + maxPerRequestUsdc, capped at reserve ceiling.
583
+ */
584
+ _maxSignable(sellerPeerId) {
585
+ const verified = this._verifiedCost.get(sellerPeerId) ?? 0n;
586
+ const ceiling = this._getCeiling(sellerPeerId);
587
+ const maxSignable = verified + this._config.maxPerRequestUsdc;
588
+ return maxSignable < ceiling ? maxSignable : ceiling;
589
+ }
590
+ /**
591
+ * Check whether the current cumulative amount is approaching the reserve ceiling
592
+ * and a top-up should be triggered.
593
+ */
594
+ _needsTopUp(sellerPeerId) {
595
+ const ceiling = this._getCeiling(sellerPeerId);
596
+ const current = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
597
+ const threshold = BigInt(Math.floor(Number(ceiling) * DEFAULT_TOPUP_THRESHOLD));
598
+ return current >= threshold;
599
+ }
600
+ /**
601
+ * Sign an updated SpendingAuth after receiving a response.
602
+ *
603
+ * The buyer uses the seller's claimed cost to advance the cumulative amount,
604
+ * but validates it against the buyer's bytes/4 estimate. If the seller's claim
605
+ * exceeds the buyer's estimate by more than the configured tolerance, the buyer
606
+ * caps at tolerance * buyerEstimate. The cumulative is also capped at the
607
+ * overdraft limit (verifiedCost + maxPerRequestUsdc) and the reserve ceiling.
608
+ *
609
+ * @param sellerPeerId Seller peer ID.
610
+ * @param responseStats Byte counts from the last response and seller's claimed cost.
611
+ * @returns The signed payload and whether a reserve top-up is needed.
612
+ */
613
+ async signPerRequestAuth(sellerPeerId, responseStats) {
614
+ const session = this.getActiveSession(sellerPeerId);
615
+ if (!session) {
616
+ throw new Error(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}... — call authorizeSpending() first`);
617
+ }
618
+ // Prefer reported token counts (from seller headers or buyer's parsed response usage)
619
+ // over byte-based estimation. Byte estimation inflates tokens due to JSON/SSE overhead.
620
+ // Also treat seller-claimed cost of 0 as authoritative — don't fall back to byte estimation.
621
+ const hasReportedTokens = (responseStats.reportedInputTokens != null && responseStats.reportedInputTokens > 0n) ||
622
+ (responseStats.reportedOutputTokens != null && responseStats.reportedOutputTokens > 0n) ||
623
+ (responseStats.sellerClaimedCost != null && responseStats.sellerClaimedCost === 0n);
624
+ let estimatedInputTokens;
625
+ let estimatedOutputTokens;
626
+ let estimatedCachedInputTokens = 0n;
627
+ let buyerEstimatedRequestCost;
628
+ const requestBilling = responseStats.requestId != null
629
+ ? this.getRequestBilling(responseStats.requestId)
630
+ : undefined;
631
+ const unitBillingModel = requestBilling?.unitModel;
632
+ if (responseStats.unitUsage && unitBillingModel && requestBilling) {
633
+ // Hybrid image path: token cost is still computed from the token
634
+ // counts; unit billing only validates non-token unit cost.
635
+ estimatedInputTokens = responseStats.reportedInputTokens ?? 0n;
636
+ estimatedCachedInputTokens = responseStats.reportedCachedInputTokens ?? 0n;
637
+ estimatedOutputTokens = responseStats.reportedOutputTokens ?? 0n;
638
+ const freshInputTokens = estimatedCachedInputTokens > 0n
639
+ ? BigInt(Math.max(0, Number(estimatedInputTokens) - Number(estimatedCachedInputTokens)))
640
+ : estimatedInputTokens;
641
+ const pricing = requestBilling.tokenPricing ?? this.getSessionPricing(sellerPeerId, responseStats.service);
642
+ const tokenCost = pricing
643
+ ? computeCostUsdc(Number(freshInputTokens), Number(estimatedOutputTokens), pricing, Number(estimatedCachedInputTokens))
644
+ : 0n;
645
+ const unitCost = validateUnitNormalizedCost(unitBillingModel, requestBilling.context, responseStats.unitUsage);
646
+ buyerEstimatedRequestCost = tokenCost + unitCost;
647
+ this._accumulateVerifiedCost(sellerPeerId, {
648
+ cost: buyerEstimatedRequestCost,
649
+ inputTokens: Number(estimatedInputTokens),
650
+ outputTokens: Number(estimatedOutputTokens),
651
+ });
652
+ debugLog(`[BuyerPayment] Hybrid billing-estimated cost=${buyerEstimatedRequestCost} service=${responseStats.service ?? 'unknown'}`);
653
+ }
654
+ else if (hasReportedTokens) {
655
+ estimatedInputTokens = responseStats.reportedInputTokens ?? 0n;
656
+ estimatedOutputTokens = responseStats.reportedOutputTokens ?? 0n;
657
+ const cachedInputTokens = responseStats.reportedCachedInputTokens ?? 0n;
658
+ estimatedCachedInputTokens = cachedInputTokens;
659
+ // For cost estimation, reportedInputTokens is normalized to total logical
660
+ // input tokens (fresh + cached), so split fresh by subtracting cached.
661
+ const freshInputTokens = cachedInputTokens > 0n
662
+ ? BigInt(Math.max(0, Number(estimatedInputTokens) - Number(cachedInputTokens)))
663
+ : estimatedInputTokens;
664
+ // Compute cost from reported tokens using service-specific pricing
665
+ const pricing = this.getSessionPricing(sellerPeerId, responseStats.service);
666
+ if (pricing) {
667
+ const cost = computeCostUsdc(Number(freshInputTokens), Number(estimatedOutputTokens), pricing, Number(cachedInputTokens));
668
+ buyerEstimatedRequestCost = cost;
669
+ this._accumulateVerifiedCost(sellerPeerId, { cost, inputTokens: Number(estimatedInputTokens), outputTokens: Number(estimatedOutputTokens) });
670
+ }
671
+ else if (responseStats.sellerClaimedCost != null && responseStats.sellerClaimedCost > 0n) {
672
+ // No local pricing available (e.g. after buyer restart before session pricing is restored).
673
+ // Use seller's claimed cost for verifiedCost accumulation so _maxSignable can grow.
674
+ // The seller's claim is still validated against tolerance below.
675
+ buyerEstimatedRequestCost = responseStats.sellerClaimedCost;
676
+ this._accumulateVerifiedCost(sellerPeerId, { cost: responseStats.sellerClaimedCost, inputTokens: Number(estimatedInputTokens), outputTokens: Number(estimatedOutputTokens) });
677
+ }
678
+ else {
679
+ buyerEstimatedRequestCost = 0n;
680
+ }
681
+ debugLog(`[BuyerPayment] Using reported tokens: in=${estimatedInputTokens} cached=${cachedInputTokens} out=${estimatedOutputTokens} cost=${buyerEstimatedRequestCost}`);
682
+ }
683
+ else {
684
+ // Fall back to byte-based estimation
685
+ const estimate = this._estimateResponseCost(sellerPeerId, responseStats.inputBytes, responseStats.outputBytes, responseStats.service);
686
+ estimatedInputTokens = estimate ? BigInt(estimate.inputTokens) : 0n;
687
+ estimatedOutputTokens = estimate ? BigInt(estimate.outputTokens) : 0n;
688
+ buyerEstimatedRequestCost = estimate ? estimate.cost : 0n;
689
+ if (estimate) {
690
+ this._accumulateVerifiedCost(sellerPeerId, estimate);
691
+ }
692
+ debugLog(`[BuyerPayment] Byte-estimated tokens (no reported): in=${estimatedInputTokens} out=${estimatedOutputTokens} cost=${buyerEstimatedRequestCost}`);
693
+ }
694
+ // Determine the accepted cost for this request:
695
+ // When the seller reports a cost within tolerance, accept the seller's claim so the
696
+ // buyer doesn't underpay due to minor parsing differences. Only cap when the seller's
697
+ // claim exceeds the tolerance threshold.
698
+ let acceptedCost;
699
+ if (responseStats.sellerClaimedCost != null && responseStats.sellerClaimedCost > 0n) {
700
+ if (buyerEstimatedRequestCost > 0n) {
701
+ const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimatedRequestCost) * this._costTolerance));
702
+ if (responseStats.sellerClaimedCost > maxAcceptable) {
703
+ debugWarn(`[BuyerPayment] Seller claimed ${responseStats.sellerClaimedCost} exceeds ${this._costTolerance}x buyer estimate ${buyerEstimatedRequestCost} — capping at ${maxAcceptable}`);
704
+ acceptedCost = maxAcceptable;
705
+ }
706
+ else {
707
+ // Seller's claim is within tolerance — accept it as-is
708
+ acceptedCost = responseStats.sellerClaimedCost;
709
+ }
710
+ }
711
+ else {
712
+ // No buyer estimate available — accept seller's claim
713
+ acceptedCost = responseStats.sellerClaimedCost;
714
+ }
715
+ }
716
+ else {
717
+ acceptedCost = buyerEstimatedRequestCost;
718
+ }
719
+ // If cost is 0, the cumulative amount stays the same — no spending auth needed
720
+ // but we still sign one to keep the seller's session alive.
721
+ // Advance cumulative amount by the accepted cost, then add overdraft headroom
722
+ // for the next request (so the seller has budget to serve it).
723
+ // maxSignable already caps at reserve ceiling, so one cap is sufficient
724
+ const prevAmount = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
725
+ const maxSignable = this._maxSignable(sellerPeerId);
726
+ let newAmount = prevAmount + acceptedCost;
727
+ if (newAmount > maxSignable)
728
+ newAmount = maxSignable;
729
+ this._cumulativeAmount.set(sellerPeerId, newAmount);
730
+ const signedDelta = newAmount - prevAmount;
731
+ // Update cumulative metadata
732
+ // If handleNeedAuth already counted this request (seller-initiated NeedAuth
733
+ // raced ahead), skip service attribution entirely: service totals are
734
+ // documented as lower bounds, so undercounting beats double-counting.
735
+ const alreadyCounted = this._serviceTokensCounted.has(responseStats.requestId);
736
+ const newMeta = this._advanceUsageMetadata(this._metadata.get(sellerPeerId), alreadyCounted ? undefined : responseStats.service, {
737
+ amount: signedDelta,
738
+ inputTokens: estimatedInputTokens,
739
+ cachedInputTokens: estimatedCachedInputTokens,
740
+ outputTokens: estimatedOutputTokens,
741
+ requests: 1n,
742
+ });
743
+ if (!alreadyCounted)
744
+ this._serviceTokensCounted.mark(responseStats.requestId);
745
+ this._metadata.set(sellerPeerId, newMeta);
746
+ this._persistServiceMetadata(session.sessionId, newMeta);
747
+ this._reportSpend({
748
+ sellerPeerId,
749
+ requestId: responseStats.requestId ?? null,
750
+ amountUsdc: signedDelta.toString(),
751
+ inputTokens: (alreadyCounted ? 0n : estimatedInputTokens).toString(),
752
+ cachedInputTokens: (alreadyCounted ? 0n : estimatedCachedInputTokens).toString(),
753
+ outputTokens: (alreadyCounted ? 0n : estimatedOutputTokens).toString(),
754
+ });
755
+ debugLog(`[BuyerPayment] signPerRequestAuth #${newMeta.cumulativeRequestCount}: ` +
756
+ `thisReq in=${estimatedInputTokens} out=${estimatedOutputTokens} | ` +
757
+ `cumulative in=${newMeta.cumulativeInputTokens} out=${newMeta.cumulativeOutputTokens} | ` +
758
+ `acceptedCost=${acceptedCost} cumulativeAmount=${newAmount}`);
759
+ // Compute metadata hash and encode metadata
760
+ const metadataHashHex = computeMetadataHash(newMeta);
761
+ const encodedMetadata = encodeMetadata(newMeta);
762
+ // Sign EIP-712 SpendingAuth
763
+ const channelsDomain = this._channelsDomain;
764
+ const metadataMsg = {
765
+ channelId: session.sessionId,
766
+ cumulativeAmount: newAmount,
767
+ metadataHash: metadataHashHex,
768
+ };
769
+ const spendingAuthSig = await signSpendingAuth(this._signer, channelsDomain, metadataMsg);
770
+ // Persist updated cumulative values to BuyerChannelStore
771
+ this._channelStore.upsertChannel({
772
+ ...session,
773
+ authMax: newAmount.toString(),
774
+ requestCount: Number(newMeta.cumulativeRequestCount),
775
+ updatedAt: Date.now(),
776
+ });
777
+ const payload = {
778
+ channelId: session.sessionId,
779
+ cumulativeAmount: newAmount.toString(),
780
+ metadataHash: metadataHashHex,
781
+ metadata: encodedMetadata,
782
+ spendingAuthSig,
783
+ };
784
+ const topUpNeeded = this._needsTopUp(sellerPeerId);
785
+ return { payload, topUpNeeded };
786
+ }
787
+ // ── NeedAuth handler ───────────────────────────────────────────
788
+ /**
789
+ * Handle seller-initiated NeedAuth messages sent after every served request.
790
+ * The seller includes the cost of the last request; the buyer validates it
791
+ * against its own token count and signs a new SpendingAuth for the required
792
+ * cumulative amount, capped at the reserve ceiling.
793
+ */
794
+ async handleNeedAuth(sellerPeerId, payload, paymentMux) {
795
+ const session = this.getActiveSession(sellerPeerId);
796
+ if (!session) {
797
+ debugWarn(`[BuyerPayment] NeedAuth for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
798
+ return;
799
+ }
800
+ const requestBilling = payload.requestId ? this.getRequestBilling(payload.requestId) : undefined;
801
+ const buyerService = requestBilling?.context.service
802
+ ?? this._requestService.get(payload.requestId);
803
+ const buyerBillingContext = requestBilling?.context;
804
+ const requiredCumulativeAmount = BigInt(payload.requiredCumulativeAmount);
805
+ const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
806
+ // Reject stale/lower NeedAuth (monotonicity guard)
807
+ if (requiredCumulativeAmount <= currentCumulative) {
808
+ debugLog(`[BuyerPayment] NeedAuth stale: required=${requiredCumulativeAmount} <= current=${currentCumulative} — ignoring`);
809
+ return;
810
+ }
811
+ let acceptedServiceCost = 0n;
812
+ const reportedInputTokens = BigInt(payload.inputTokens ?? '0');
813
+ const reportedCachedInputTokens = BigInt(payload.cachedInputTokens ?? '0');
814
+ const reportedOutputTokens = BigInt(payload.outputTokens ?? '0');
815
+ const unitBillingModel = requestBilling?.unitModel;
816
+ // Validate the seller's claimed cost if reported
817
+ if (payload.billingUsage) {
818
+ // Image billingUsage is surcharge evidence only. Token cost is still
819
+ // recomputed from the token fields and service pricing below.
820
+ try {
821
+ const sellerTotalCost = BigInt(payload.lastRequestCost ?? '0');
822
+ const sellerFreshExplicit = payload.freshInputTokens != null
823
+ ? BigInt(payload.freshInputTokens)
824
+ : null;
825
+ const freshIn = sellerFreshExplicit ?? (reportedCachedInputTokens > 0n
826
+ ? BigInt(Math.max(0, Number(reportedInputTokens) - Number(reportedCachedInputTokens)))
827
+ : reportedInputTokens);
828
+ const pricing = requestBilling?.tokenPricing ?? this.getSessionPricing(sellerPeerId, buyerService);
829
+ const tokenEstimate = pricing
830
+ ? computeCostUsdc(Number(freshIn), Number(reportedOutputTokens), pricing, Number(reportedCachedInputTokens))
831
+ : 0n;
832
+ let acceptedUnitCost = 0n;
833
+ if (!requestBilling || !unitBillingModel) {
834
+ if (sellerTotalCost > 0n) {
835
+ throw new Error("Positive unit billing cost is unverifiable without a unit billing model");
836
+ }
837
+ debugLog(`[BuyerPayment] NeedAuth zero unit billing accepted without unit model`);
838
+ }
839
+ else {
840
+ // The seller's NeedAuth can legitimately race ahead of the buyer's
841
+ // own response processing (different muxes). Give the response path
842
+ // a moment to record what was actually delivered before judging the
843
+ // claim; a seller claiming delivery that never happens still gets
844
+ // rejected once the wait expires.
845
+ const observedUnitUsage = requestBilling.observedUnitUsage
846
+ ?? (sellerTotalCost > 0n && payload.requestId
847
+ ? await this._waitForObservedUnitUsage(payload.requestId, OBSERVED_UNIT_USAGE_WAIT_MS)
848
+ : undefined);
849
+ const claimedUnitCost = sellerTotalCost > tokenEstimate
850
+ ? sellerTotalCost - tokenEstimate
851
+ : 0n;
852
+ acceptedUnitCost = validateUnitBillingUsage(unitBillingModel, requestBilling.context, payload.billingUsage, claimedUnitCost, this._costTolerance, observedUnitUsage);
853
+ }
854
+ const buyerEstimate = tokenEstimate + acceptedUnitCost;
855
+ if (sellerTotalCost > 0n && buyerEstimate <= 0n) {
856
+ throw new Error("Positive NeedAuth total cost recomputed to zero");
857
+ }
858
+ const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimate) * this._costTolerance));
859
+ if (sellerTotalCost > maxAcceptable) {
860
+ throw new Error(`Seller total cost ${sellerTotalCost} exceeds buyer estimate ${buyerEstimate}`);
861
+ }
862
+ acceptedServiceCost = sellerTotalCost;
863
+ this._accumulateVerifiedCost(sellerPeerId, {
864
+ cost: acceptedServiceCost,
865
+ inputTokens: Number(reportedInputTokens),
866
+ outputTokens: Number(reportedOutputTokens),
867
+ });
868
+ debugLog(`[BuyerPayment] NeedAuth hybrid billing: token=${tokenEstimate} unit=${acceptedUnitCost} sellerTotal=${sellerTotalCost} — validated`);
869
+ }
870
+ catch (err) {
871
+ debugWarn(`[BuyerPayment] NeedAuth billingUsage rejected: ${err instanceof Error ? err.message : err}`);
872
+ return;
873
+ }
874
+ }
875
+ else if (payload.lastRequestCost) {
876
+ const sellerCost = BigInt(payload.lastRequestCost);
877
+ if (sellerCost > 0n && unitBillingModel && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
878
+ debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost omitted verifiable billingUsage`);
879
+ return;
880
+ }
881
+ const sellerIn = reportedInputTokens;
882
+ const sellerOut = reportedOutputTokens;
883
+ const sellerCached = reportedCachedInputTokens;
884
+ acceptedServiceCost = sellerCost;
885
+ // Prefer seller-supplied freshInputTokens to avoid OpenAI-vs-Anthropic
886
+ // cached-semantics ambiguity (OpenAI: prompt_tokens includes cached;
887
+ // Anthropic: input_tokens excludes cached). Fall back to OpenAI-style
888
+ // subtraction for older sellers that don't emit the field.
889
+ const sellerFreshExplicit = payload.freshInputTokens != null
890
+ ? BigInt(payload.freshInputTokens)
891
+ : null;
892
+ // Use the buyer's own knowledge of which service it requested, not the seller's claim.
893
+ // A malicious seller could set service to a more expensive model to inflate the ceiling.
894
+ const pricing = requestBilling?.tokenPricing ?? this.getSessionPricing(sellerPeerId, buyerService);
895
+ if (pricing && sellerCost > 0n) {
896
+ const freshIn = sellerFreshExplicit ?? (sellerCached > 0n
897
+ ? BigInt(Math.max(0, Number(sellerIn) - Number(sellerCached)))
898
+ : sellerIn);
899
+ const buyerEstimate = computeCostUsdc(Number(freshIn), Number(sellerOut), pricing, Number(sellerCached));
900
+ const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimate) * this._costTolerance));
901
+ if (buyerEstimate <= 0n && sellerCost > 0n && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
902
+ debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost recomputed to zero`);
903
+ return;
904
+ }
905
+ if (buyerEstimate > 0n && sellerCost > maxAcceptable) {
906
+ debugWarn(`[BuyerPayment] NeedAuth: seller claimed cost ${sellerCost} exceeds ${this._costTolerance}x buyer estimate ${buyerEstimate} — rejecting`);
907
+ return;
908
+ }
909
+ debugLog(`[BuyerPayment] NeedAuth: seller cost=${sellerCost} buyer estimate=${buyerEstimate} (in=${sellerIn} cached=${sellerCached} out=${sellerOut}) — validated`);
910
+ }
911
+ else {
912
+ debugLog(`[BuyerPayment] NeedAuth: seller cost=${sellerCost} (no local pricing, accepting)`);
913
+ }
914
+ // Accumulate verified cost from the seller's report
915
+ this._accumulateVerifiedCost(sellerPeerId, {
916
+ cost: sellerCost,
917
+ inputTokens: Number(sellerIn),
918
+ outputTokens: Number(sellerOut),
919
+ });
920
+ }
921
+ // Cap at overdraft limit: verifiedCost + maxPerRequestUsdc, then at reserve ceiling.
922
+ // This prevents a malicious seller from claiming a small cost but requesting the full reserve.
923
+ let maxSignable = this._maxSignable(sellerPeerId);
924
+ const ceiling = this._getCeiling(sellerPeerId);
925
+ let needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
926
+ if (maxSignable <= currentCumulative && !needsTopUp) {
927
+ maxSignable = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'handleNeedAuth');
928
+ needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
929
+ if (maxSignable <= currentCumulative && !needsTopUp) {
930
+ debugWarn(`[BuyerPayment] NeedAuth: maxSignable=${maxSignable} <= currentCumulative=${currentCumulative} — overdraft limit reached`);
931
+ return;
932
+ }
933
+ }
934
+ // When a topUp is needed, first sign at the current ceiling so the seller
935
+ // has a high-enough settled amount to pass the on-chain TopUpThresholdNotMet
936
+ // check (contract requires 85% of deposit to be settleable before topUp).
937
+ // We cap at the old ceiling here; the topUp is sent AFTER so the seller
938
+ // processes the SpendingAuth first, then the topUp with adequate settle amount.
939
+ const effectiveAmount = needsTopUp
940
+ ? (maxSignable > currentCumulative ? maxSignable : currentCumulative)
941
+ : (requiredCumulativeAmount < maxSignable ? requiredCumulativeAmount : maxSignable);
942
+ if (effectiveAmount <= currentCumulative) {
943
+ // Nothing to sign — trigger topUp anyway to extend ceiling for next round
944
+ if (needsTopUp) {
945
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'handleNeedAuth');
946
+ }
947
+ debugWarn(`[BuyerPayment] NeedAuth: effectiveAmount=${effectiveAmount} <= currentCumulative=${currentCumulative} — cannot advance`);
948
+ return;
949
+ }
950
+ debugLog(`[BuyerPayment] NeedAuth: channel=${session.sessionId.slice(0, 18)}... required=${requiredCumulativeAmount} effective=${effectiveAmount}`);
951
+ // Advance cumulative metadata. requestCount always increments so the
952
+ // on-chain metadata stays consistent even when older sellers omit token
953
+ // fields; absent token fields contribute 0 to the running totals.
954
+ const signedDelta = effectiveAmount - currentCumulative;
955
+ const serviceAmountDelta = acceptedServiceCost > 0n
956
+ ? (acceptedServiceCost < signedDelta ? acceptedServiceCost : signedDelta)
957
+ : 0n;
958
+ // If signPerRequestAuth already counted this request (buyer-initiated auth
959
+ // raced ahead but didn't fully cover the seller's required cumulative), skip
960
+ // service attribution entirely: service totals are documented as lower
961
+ // bounds, so undercounting beats double-counting.
962
+ const alreadyCounted = this._serviceTokensCounted.has(payload.requestId);
963
+ const newMeta = this._advanceUsageMetadata(this._metadata.get(sellerPeerId), alreadyCounted ? undefined : buyerService, {
964
+ amount: serviceAmountDelta,
965
+ inputTokens: reportedInputTokens,
966
+ cachedInputTokens: reportedCachedInputTokens,
967
+ outputTokens: reportedOutputTokens,
968
+ requests: 1n,
969
+ });
970
+ if (!alreadyCounted)
971
+ this._serviceTokensCounted.mark(payload.requestId);
972
+ this._metadata.set(sellerPeerId, newMeta);
973
+ // Send via PaymentMux
974
+ try {
975
+ await this._sendUpdatedSpendingAuth(session, sellerPeerId, effectiveAmount, newMeta, paymentMux);
976
+ this._reportSpend({
977
+ sellerPeerId,
978
+ requestId: payload.requestId ?? null,
979
+ amountUsdc: signedDelta.toString(),
980
+ inputTokens: (alreadyCounted ? 0n : reportedInputTokens).toString(),
981
+ cachedInputTokens: (alreadyCounted ? 0n : reportedCachedInputTokens).toString(),
982
+ outputTokens: (alreadyCounted ? 0n : reportedOutputTokens).toString(),
983
+ });
984
+ debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
985
+ }
986
+ catch {
987
+ debugLog(`[BuyerPayment] NeedAuth: connection closed before SpendingAuth could be sent`);
988
+ }
989
+ // Send topUp AFTER the SpendingAuth so the seller processes the higher
990
+ // cumulative first — this ensures the on-chain settle amount meets the
991
+ // contract's TopUpThresholdNotMet requirement (85% of deposit must be
992
+ // settleable before topUp is allowed). Also proactively send the top-up
993
+ // once the signed cumulative reaches the buyer's 65% threshold; the seller
994
+ // may defer the on-chain topUp until the contract's 85% gate is satisfied.
995
+ if (needsTopUp || this._needsTopUp(sellerPeerId)) {
996
+ await this._topUpAfterSpendAuthBestEffort(sellerPeerId, paymentMux, 'handleNeedAuth');
997
+ }
998
+ if (payload.requestId) {
999
+ this.clearRequestBilling(payload.requestId);
1000
+ }
1001
+ }
1002
+ // ── Reserve top-up ─────────────────────────────────────────────
1003
+ /**
1004
+ * Sign a new ReserveAuth with a higher maxAmount to extend the session's reserve ceiling.
1005
+ * The seller must call reserve() on-chain again with the new signature.
1006
+ * Note: requires contract support for top-up (increaseDeposit on existing channelId).
1007
+ */
1008
+ async topUpReserve(sellerPeerId, paymentMux) {
1009
+ const session = this.getActiveSession(sellerPeerId);
1010
+ if (!session) {
1011
+ debugWarn(`[BuyerPayment] topUpReserve: no active session for ${sellerPeerId.slice(0, 12)}...`);
1012
+ return;
1013
+ }
1014
+ const prevCeiling = this._getCeiling(sellerPeerId);
1015
+ const newCeiling = prevCeiling + this._config.maxReserveAmountUsdc;
1016
+ const additionalReserve = newCeiling - prevCeiling;
1017
+ const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
1018
+ try {
1019
+ const balance = await this.getBalance();
1020
+ if (balance.available < additionalReserve) {
1021
+ throw new Error(`Insufficient buyer deposits for reserve top-up: available=${balance.available} required=${additionalReserve}`);
1022
+ }
1023
+ }
1024
+ catch (err) {
1025
+ if (err instanceof Error && err.message.startsWith('Insufficient buyer deposits')) {
1026
+ throw err;
1027
+ }
1028
+ debugWarn(`[BuyerPayment] topUpReserve: unable to verify buyer deposits before signing top-up: ` +
1029
+ `${err instanceof Error ? err.message : err}`);
1030
+ }
1031
+ debugLog(`[BuyerPayment] topUpReserve: channel=${session.sessionId.slice(0, 18)}... ceiling ${prevCeiling} → ${newCeiling}`);
1032
+ // Sign ReserveAuth with new maxAmount
1033
+ const channelsDomain = this._channelsDomain;
1034
+ const reserveMsg = {
1035
+ channelId: session.sessionId,
1036
+ maxAmount: newCeiling,
1037
+ deadline: BigInt(deadline),
1038
+ };
1039
+ const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
1040
+ const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1041
+ const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
1042
+ const metadataHashHex = computeMetadataHash(currentMeta);
1043
+ const encodedMetadata = encodeMetadata(currentMeta);
1044
+ const salt = this._reserveSalt.get(sellerPeerId) ?? '0x' + '00'.repeat(32);
1045
+ // Send ReserveAuth sig with reserve fields (same pattern as initial authorizeSpending).
1046
+ // The seller uses this to call topUp() on-chain with the new maxAmount.
1047
+ try {
1048
+ paymentMux.sendSpendingAuth({
1049
+ channelId: session.sessionId,
1050
+ cumulativeAmount: currentCumulative.toString(),
1051
+ metadataHash: metadataHashHex,
1052
+ metadata: encodedMetadata,
1053
+ spendingAuthSig: reserveAuthSig,
1054
+ reserveSalt: salt,
1055
+ reserveMaxAmount: newCeiling.toString(),
1056
+ reserveDeadline: deadline,
1057
+ });
1058
+ // Only commit the new ceiling after the message is delivered
1059
+ this._currentReserveCeiling.set(sellerPeerId, newCeiling);
1060
+ debugLog(`[BuyerPayment] topUpReserve sent: newCeiling=${newCeiling}`);
1061
+ }
1062
+ catch {
1063
+ debugLog(`[BuyerPayment] topUpReserve: connection closed before ReserveAuth could be sent`);
1064
+ }
1065
+ }
1066
+ // ── Queries ───────────────────────────────────────────────────
1067
+ /** Max USDC overdraft (unverified exposure) from buyer config. */
1068
+ get maxPerRequestUsdc() {
1069
+ return this._config.maxPerRequestUsdc;
1070
+ }
1071
+ /** Max USDC per ReserveAuth signature from buyer config. */
1072
+ get maxReserveAmountUsdc() {
1073
+ return this._config.maxReserveAmountUsdc;
1074
+ }
1075
+ /** Current buyer-verified cost for a seller. */
1076
+ getVerifiedCost(sellerPeerId) {
1077
+ return this._verifiedCost.get(sellerPeerId) ?? 0n;
1078
+ }
1079
+ /** Current reserve ceiling for a seller (may be higher than initial after top-ups). */
1080
+ getReserveCeiling(sellerPeerId) {
1081
+ return this._currentReserveCeiling.get(sellerPeerId) ?? this._config.maxReserveAmountUsdc;
1082
+ }
1083
+ /** Current cumulative signed amount for a seller. */
1084
+ getCumulativeAmount(sellerPeerId) {
1085
+ return this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1086
+ }
1087
+ /** Live cumulative token counts for a seller (in-memory, always up-to-date). */
1088
+ getCumulativeTokens(sellerPeerId) {
1089
+ const meta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
1090
+ return { inputTokens: meta.cumulativeInputTokens, outputTokens: meta.cumulativeOutputTokens };
1091
+ }
1092
+ /**
1093
+ * Accumulate response token counts and persist to the channel store.
1094
+ * Tracks its own running totals independently of signPerRequestAuth metadata,
1095
+ * so the persisted data is always up-to-date after each response.
1096
+ */
1097
+ recordAndPersistTokens(sellerPeerId, inputTokens, outputTokens) {
1098
+ const session = this.getActiveSession(sellerPeerId);
1099
+ if (!session)
1100
+ return;
1101
+ const prev = this._responseTokenTotals.get(sellerPeerId) ?? {
1102
+ input: Number(session.tokensDelivered),
1103
+ output: Number(session.previousConsumption),
1104
+ requests: session.requestCount,
1105
+ };
1106
+ debugLog(`[BuyerPayment] recordTokens: thisReq in=${inputTokens} out=${outputTokens} | ` +
1107
+ `prevTotal in=${prev.input} out=${prev.output} reqs=${prev.requests}`);
1108
+ const totals = {
1109
+ input: prev.input + inputTokens,
1110
+ output: prev.output + outputTokens,
1111
+ requests: prev.requests + 1,
1112
+ };
1113
+ this._responseTokenTotals.set(sellerPeerId, totals);
1114
+ this._channelStore.upsertChannel({
1115
+ ...session,
1116
+ tokensDelivered: String(totals.input),
1117
+ previousConsumption: String(totals.output),
1118
+ requestCount: totals.requests,
1119
+ updatedAt: Date.now(),
1120
+ });
1121
+ }
1122
+ /** Register which service the buyer requested for a given requestId. */
1123
+ trackRequestService(requestId, service) {
1124
+ this._requestService.track(requestId, service);
1125
+ }
1126
+ trackRequestBilling(requestId, entry) {
1127
+ this._cleanupRequestBillingCache();
1128
+ this._requestService.track(requestId, entry.context.service);
1129
+ this._requestBillingEntries.set(requestId, {
1130
+ ...entry,
1131
+ createdAtMs: Date.now(),
1132
+ });
1133
+ this._trimRequestBillingCache();
1134
+ }
1135
+ /** Record unit usage extracted from the response the buyer received, so
1136
+ * NeedAuth validation can cap seller claims at what was actually delivered. */
1137
+ recordObservedUnitUsage(requestId, usage) {
1138
+ const entry = this._requestBillingEntries.get(requestId);
1139
+ if (entry)
1140
+ entry.observedUnitUsage = usage;
1141
+ const waiters = this._observedUsageWaiters.get(requestId);
1142
+ if (waiters) {
1143
+ this._observedUsageWaiters.delete(requestId);
1144
+ for (const waiter of waiters)
1145
+ waiter(usage);
1146
+ }
1147
+ }
1148
+ /** Wait for observed unit usage while the buyer's response path catches up. */
1149
+ _waitForObservedUnitUsage(requestId, timeoutMs) {
1150
+ const existing = this._requestBillingEntries.get(requestId)?.observedUnitUsage;
1151
+ if (existing)
1152
+ return Promise.resolve(existing);
1153
+ return new Promise((resolve) => {
1154
+ const onUsage = (usage) => {
1155
+ clearTimeout(timer);
1156
+ resolve(usage);
1157
+ };
1158
+ const timer = setTimeout(() => {
1159
+ const waiters = this._observedUsageWaiters.get(requestId);
1160
+ if (waiters) {
1161
+ const index = waiters.indexOf(onUsage);
1162
+ if (index >= 0)
1163
+ waiters.splice(index, 1);
1164
+ if (waiters.length === 0)
1165
+ this._observedUsageWaiters.delete(requestId);
1166
+ }
1167
+ resolve(this._requestBillingEntries.get(requestId)?.observedUnitUsage);
1168
+ }, timeoutMs);
1169
+ timer.unref?.();
1170
+ const waiters = this._observedUsageWaiters.get(requestId) ?? [];
1171
+ waiters.push(onUsage);
1172
+ this._observedUsageWaiters.set(requestId, waiters);
1173
+ });
1174
+ }
1175
+ getRequestBilling(requestId) {
1176
+ this._cleanupRequestBillingCache();
1177
+ const entry = this._requestBillingEntries.get(requestId);
1178
+ if (!entry)
1179
+ return undefined;
1180
+ const { createdAtMs: _createdAtMs, ...publicEntry } = entry;
1181
+ return publicEntry;
1182
+ }
1183
+ clearRequestBilling(requestId) {
1184
+ this._requestBillingEntries.delete(requestId);
1185
+ this._requestService.take(requestId);
1186
+ }
1187
+ trackRequestBillingContext(requestId, context) {
1188
+ this.trackRequestBilling(requestId, {
1189
+ context,
1190
+ requestFacts: {},
1191
+ });
1192
+ }
1193
+ /** Get the live response token totals for a seller, or null if none recorded this session. */
1194
+ getResponseTokenTotals(sellerPeerId) {
1195
+ return this._responseTokenTotals.get(sellerPeerId) ?? null;
1196
+ }
1197
+ /** Get the session pricing for a seller+service. Resolves service-specific pricing first, then defaults. */
1198
+ getSessionPricing(sellerPeerId, service) {
1199
+ const map = this._sessionPricing.get(sellerPeerId);
1200
+ if (!map)
1201
+ return null;
1202
+ if (service) {
1203
+ const servicePricing = map.services[service];
1204
+ if (servicePricing)
1205
+ return servicePricing;
1206
+ }
1207
+ return map.defaults;
1208
+ }
1209
+ /** Check if a session has been confirmed via AuthAck. */
1210
+ isAuthorized(sellerPeerId) {
1211
+ return this._confirmedPeers.has(sellerPeerId);
1212
+ }
1213
+ /** Alias for isAuthorized (used by polling loop). */
1214
+ isLockConfirmed(sellerPeerId) {
1215
+ return this.isAuthorized(sellerPeerId);
1216
+ }
1217
+ /** Check if the lock was explicitly rejected (not just never-contacted). */
1218
+ isLockRejected(sellerPeerId) {
1219
+ return this._rejectedPeers.has(sellerPeerId);
1220
+ }
1221
+ /** Mark a peer as having rejected our spending auth. */
1222
+ markRejected(sellerPeerId) {
1223
+ this._rejectedPeers.add(sellerPeerId);
1224
+ debugLog(`[BuyerPayment] Peer ${sellerPeerId.slice(0, 12)}... marked as rejected`);
1225
+ }
1226
+ getSessionHistory(sellerPeerId) {
1227
+ const session = this._channelStore.getLatestChannelByPeerAndBuyer(sellerPeerId, 'buyer', this._identity.wallet.address);
1228
+ return session ? [session] : [];
1229
+ }
1230
+ // ── Deposit operations ──────────────────────────────────────────
1231
+ async deposit(amount) {
1232
+ debugLog(`[BuyerPayment] Depositing ${amount} to deposits`);
1233
+ const buyer = this._identity.wallet.address;
1234
+ return this._depositsClient.deposit(this._signer, buyer, amount);
1235
+ }
1236
+ async withdraw(amount) {
1237
+ debugLog(`[BuyerPayment] Withdrawing ${amount} from deposits`);
1238
+ return this._depositsClient.withdraw(this._signer, this._identity.wallet.address, amount);
1239
+ }
1240
+ async getBalance() {
1241
+ const buyerAddr = this._identity.wallet.address;
1242
+ const info = await this._depositsClient.getBuyerBalance(buyerAddr);
1243
+ return { available: info.available, reserved: info.reserved };
1244
+ }
1245
+ }
1246
+ //# sourceMappingURL=buyer-payment-manager.js.map