@flop-labs/sdk 0.7.1 → 0.8.0

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 (71) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +4 -4
  3. package/dist/bundle/index.esm.js +1 -1
  4. package/dist/bundle/index.esm.js.map +1 -1
  5. package/dist/bundle/index.umd.cjs +1 -1
  6. package/dist/bundle/index.umd.cjs.map +1 -1
  7. package/dist/compute-channel/capacity-reservation.d.ts +5 -3
  8. package/dist/compute-channel/capacity-reservation.d.ts.map +1 -1
  9. package/dist/compute-channel/capacity-reservation.js +7 -3
  10. package/dist/compute-channel/capacity-reservation.js.map +1 -1
  11. package/dist/compute-channel/deepseek-v41.d.ts +13 -6
  12. package/dist/compute-channel/deepseek-v41.d.ts.map +1 -1
  13. package/dist/compute-channel/deepseek-v41.js +19 -10
  14. package/dist/compute-channel/deepseek-v41.js.map +1 -1
  15. package/dist/compute-channel/flop-submitter.d.ts +53 -4
  16. package/dist/compute-channel/flop-submitter.d.ts.map +1 -1
  17. package/dist/compute-channel/flop-submitter.js +94 -4
  18. package/dist/compute-channel/flop-submitter.js.map +1 -1
  19. package/dist/compute-channel/forward-holdings.d.ts +32 -0
  20. package/dist/compute-channel/forward-holdings.d.ts.map +1 -0
  21. package/dist/compute-channel/forward-holdings.js +157 -0
  22. package/dist/compute-channel/forward-holdings.js.map +1 -0
  23. package/dist/compute-channel/index.d.ts +5 -0
  24. package/dist/compute-channel/index.d.ts.map +1 -1
  25. package/dist/compute-channel/index.js +5 -0
  26. package/dist/compute-channel/index.js.map +1 -1
  27. package/dist/compute-channel/long-session-chain.d.ts +16 -0
  28. package/dist/compute-channel/long-session-chain.d.ts.map +1 -0
  29. package/dist/compute-channel/long-session-chain.js +212 -0
  30. package/dist/compute-channel/long-session-chain.js.map +1 -0
  31. package/dist/compute-channel/long-session.d.ts +256 -0
  32. package/dist/compute-channel/long-session.d.ts.map +1 -0
  33. package/dist/compute-channel/long-session.js +623 -0
  34. package/dist/compute-channel/long-session.js.map +1 -0
  35. package/dist/compute-channel/miner-host.d.ts.map +1 -1
  36. package/dist/compute-channel/miner-host.js +5 -3
  37. package/dist/compute-channel/miner-host.js.map +1 -1
  38. package/dist/compute-channel/model-config.d.ts +16 -3
  39. package/dist/compute-channel/model-config.d.ts.map +1 -1
  40. package/dist/compute-channel/model-config.js +71 -2
  41. package/dist/compute-channel/model-config.js.map +1 -1
  42. package/dist/compute-channel/session-estimate.d.ts.map +1 -1
  43. package/dist/compute-channel/session-estimate.js +12 -1
  44. package/dist/compute-channel/session-estimate.js.map +1 -1
  45. package/dist/compute-channel/spend-journal.d.ts +172 -0
  46. package/dist/compute-channel/spend-journal.d.ts.map +1 -0
  47. package/dist/compute-channel/spend-journal.js +429 -0
  48. package/dist/compute-channel/spend-journal.js.map +1 -0
  49. package/dist/compute-channel/transcript.d.ts +3 -1
  50. package/dist/compute-channel/transcript.d.ts.map +1 -1
  51. package/dist/compute-channel/transcript.js +2 -0
  52. package/dist/compute-channel/transcript.js.map +1 -1
  53. package/dist/compute-channel/transport-http.d.ts +34 -1
  54. package/dist/compute-channel/transport-http.d.ts.map +1 -1
  55. package/dist/compute-channel/transport-http.js +66 -4
  56. package/dist/compute-channel/transport-http.js.map +1 -1
  57. package/dist/direct-swap/retained-runtime-releases.d.ts.map +1 -1
  58. package/dist/direct-swap/retained-runtime-releases.js +11 -1
  59. package/dist/direct-swap/retained-runtime-releases.js.map +1 -1
  60. package/dist/discovery/metered-pricing.d.ts.map +1 -1
  61. package/dist/discovery/metered-pricing.js +8 -1
  62. package/dist/discovery/metered-pricing.js.map +1 -1
  63. package/dist/faucet.d.ts +1 -1
  64. package/dist/faucet.js +1 -1
  65. package/dist/miner-admission.d.ts +1 -1
  66. package/dist/miner-admission.js +2 -2
  67. package/dist/runtime-compatibility.d.ts +1 -1
  68. package/dist/runtime-compatibility.d.ts.map +1 -1
  69. package/dist/runtime-compatibility.js +6 -2
  70. package/dist/runtime-compatibility.js.map +1 -1
  71. package/package.json +1 -1
@@ -0,0 +1,623 @@
1
+ import { hexToU8a, u8aToHex } from "@polkadot/util";
2
+ import { decodeAddress, randomAsU8a } from "@polkadot/util-crypto";
3
+ import { CircuitBreakerTrippedError } from "../errors.js";
4
+ import { FinalizedTransactionError } from "../watch-transaction.js";
5
+ import { ComputeChannelChainClient } from "./chain.js";
6
+ import { CAPACITY_INCLUSION_MARGIN_BLOCKS } from "./capacity-reservation.js";
7
+ import { ready, SessionKey, verify } from "./crypto.js";
8
+ import { computeChannelSpend } from "./flop-submitter.js";
9
+ import { createLongSessionRuntime } from "./long-session-chain.js";
10
+ import { sessionOfferMessage, signOfferAcceptance } from "./offers.js";
11
+ import { encodeChatTurnEnvelope, u8aEq } from "./protocol.js";
12
+ import { ChannelSession } from "./session.js";
13
+ import { decodeJournalValue, encodeJournalValue, spendEventMatches, SpendingFrozenError, unresolvedSpends, } from "./spend-journal.js";
14
+ import { channelIdV1, forceSettlePayable } from "./transcript.js";
15
+ import { MAX_SESSION_TURN_BODY_BYTES, MinerTurnRejectedError, sessionTurnBodyBytes, } from "./transport-http.js";
16
+ /** The turn's `/session/turn` body would exceed what the miner worker reads; nothing was bought or sent. */
17
+ export class TurnTooLargeError extends Error {
18
+ bytes;
19
+ limit;
20
+ code = "TURN_TOO_LARGE";
21
+ constructor(bytes, limit = MAX_SESSION_TURN_BODY_BYTES) {
22
+ super(`the encoded turn is ${bytes} bytes; the miner accepts at most ${limit}`);
23
+ this.bytes = bytes;
24
+ this.limit = limit;
25
+ }
26
+ }
27
+ export class TariffExceedsEscrowError extends Error {
28
+ payable;
29
+ escrow;
30
+ code = "TARIFF_EXCEEDS_ESCROW";
31
+ constructor(payable, escrow) {
32
+ super(`cumulative tariff ${payable} exceeds the finalized escrow ${escrow}`);
33
+ this.payable = payable;
34
+ this.escrow = escrow;
35
+ }
36
+ }
37
+ /**
38
+ * The miner's calibrated allowance cannot settle the work asked of a channel. The pallet settles
39
+ * at most `min(pinned reservation rate, current cap) x max_duration` G_n per channel
40
+ * (`validate_calibration_allowance`), so verified work past it can only end in a timeout refund.
41
+ * Raised before anything is bought or served.
42
+ */
43
+ export class CalibratedAllowanceError extends Error {
44
+ miner;
45
+ rateGnPerSec;
46
+ windowBlocks;
47
+ allowanceGn;
48
+ neededGn;
49
+ code = "CALIBRATED_ALLOWANCE_TOO_SMALL";
50
+ constructor(miner, rateGnPerSec, windowBlocks, allowanceGn, neededGn) {
51
+ super(`miner ${miner} reserves ${rateGnPerSec} G_n/s per channel (its capacity-reservation rate), so a `
52
+ + `${windowBlocks}-block channel settles at most ${allowanceGn} G_n; this needs ${neededGn} G_n. `
53
+ + "The miner must raise its rate (`flop miner capacity-rate`) before this session can be paid.");
54
+ this.miner = miner;
55
+ this.rateGnPerSec = rateGnPerSec;
56
+ this.windowBlocks = windowBlocks;
57
+ this.allowanceGn = allowanceGn;
58
+ this.neededGn = neededGn;
59
+ }
60
+ }
61
+ /** What the pallet will let a channel settle at its end: `min(snapshot, current cap) x max_duration`. */
62
+ export function settleableAllowance(channel) {
63
+ if (channel.snapshotCap === null || channel.currentCap === null)
64
+ return 0n;
65
+ const cap = channel.snapshotCap < channel.currentCap ? channel.snapshotCap : channel.currentCap;
66
+ return cap > 0n && channel.maxDuration > 0n ? cap * channel.maxDuration : 0n;
67
+ }
68
+ /** Signs, journals and debits each armed spend before broadcasting it. */
69
+ class JournaledSubmitter {
70
+ submitter;
71
+ journal;
72
+ budget;
73
+ armed;
74
+ constructor(submitter, journal, budget) {
75
+ this.submitter = submitter;
76
+ this.journal = journal;
77
+ this.budget = budget;
78
+ }
79
+ arm(kind, channel, amount) {
80
+ this.armed = { kind, channel, amount };
81
+ }
82
+ async submit(pallet, method, args) {
83
+ const armed = this.armed;
84
+ this.armed = undefined;
85
+ if (!armed)
86
+ throw new Error(`${pallet}.${method} is not a journaled spend`);
87
+ const expected = armed.kind === "open" ? ["openChannel", "openChannelWithOffer", "openChannelWithProfiledOffer"] : ["topUpEscrow"];
88
+ if (pallet !== "computeChannel" || !expected.includes(method))
89
+ throw new Error(`${pallet}.${method} is not the armed ${armed.kind}`);
90
+ const amount = computeChannelSpend(pallet, method, args);
91
+ if (amount !== armed.amount)
92
+ throw new Error(`call moves ${amount}, not the armed ${armed.amount}`);
93
+ const prepared = await this.submitter.prepare(pallet, method, args);
94
+ await this.journal.reserve({
95
+ kind: armed.kind, genesis: this.journal.genesis, owner: this.journal.owner, signer: prepared.signer,
96
+ channel: armed.channel, accountNonce: prepared.accountNonce.toString(), amount: amount.toString(),
97
+ txHash: prepared.txHash, eraBirth: prepared.eraBirth.toString(), eraPeriod: prepared.eraPeriod.toString(),
98
+ }, this.budget);
99
+ let result;
100
+ try {
101
+ result = await prepared.send();
102
+ }
103
+ catch (error) {
104
+ // Only a finalized failure is an outcome; everything else may still land.
105
+ const definite = error instanceof FinalizedTransactionError || error instanceof CircuitBreakerTrippedError;
106
+ await this.journal.resolve(prepared.txHash, definite ? "failed" : "ambiguous", String(error?.message ?? error));
107
+ throw error;
108
+ }
109
+ const ok = spendEventMatches(armed.kind, armed.channel, amount, result.events);
110
+ await this.journal.resolve(prepared.txHash, ok ? "succeeded" : "failed", ok ? undefined : "finalized without the expected event");
111
+ if (!ok)
112
+ throw new Error(`${method} finalized without its ${armed.kind === "open" ? "ChannelOpened" : "EscrowToppedUp"} event`);
113
+ return result;
114
+ }
115
+ }
116
+ const ceilDiv = (a, b) => (a + b - 1n) / b;
117
+ const min = (...v) => v.reduce((a, b) => (b < a ? b : a));
118
+ const max = (...v) => v.reduce((a, b) => (b > a ? b : a));
119
+ const sameAccount = (a, b) => {
120
+ try {
121
+ return u8aEq(typeof a === "string" ? decodeAddress(a) : a, typeof b === "string" ? decodeAddress(b) : b);
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ };
127
+ function positiveInt(name, value) {
128
+ if (!Number.isSafeInteger(value) || value <= 0)
129
+ throw new Error(`${name} must be a positive safe integer`);
130
+ }
131
+ export class LongSession {
132
+ cfg;
133
+ rt;
134
+ windowBlocks;
135
+ maxLockBlocks;
136
+ live;
137
+ queue = Promise.resolve();
138
+ closed = false;
139
+ onText;
140
+ decoder = new TextDecoder();
141
+ /** Stream frames the miner sent for the running turn. */
142
+ framesSeen = 0;
143
+ journaled;
144
+ chain;
145
+ constructor(cfg, rt, windowBlocks, maxLockBlocks) {
146
+ this.cfg = cfg;
147
+ this.rt = rt;
148
+ this.windowBlocks = windowBlocks;
149
+ this.maxLockBlocks = maxLockBlocks;
150
+ this.journaled = new JournaledSubmitter(cfg.submitter, cfg.journal, cfg.budgetPlanck);
151
+ this.chain = new ComputeChannelChainClient(this.journaled);
152
+ }
153
+ /** Verify the miner and model and take the journal lock. Buys nothing until a turn needs it. */
154
+ static async open(cfg) {
155
+ positiveInt("windowSeconds", cfg.windowSeconds);
156
+ positiveInt("maxLockSeconds", cfg.maxLockSeconds);
157
+ positiveInt("maxTurns", cfg.maxTurns);
158
+ positiveInt("turnTimeoutSeconds", cfg.turnTimeoutSeconds);
159
+ for (const [name, v] of [["maxChannelPlanck", cfg.maxChannelPlanck], ["topUpPlanck", cfg.topUpPlanck], ["budgetPlanck", cfg.budgetPlanck]]) {
160
+ if (typeof v !== "bigint" || v <= 0n)
161
+ throw new Error(`${name} must be a positive bigint`);
162
+ }
163
+ if (cfg.windowSeconds > cfg.maxLockSeconds)
164
+ throw new Error("windowSeconds exceeds maxLockSeconds");
165
+ if (typeof cfg.worstCaseTurnPlanck !== "function")
166
+ throw new Error("worstCaseTurnPlanck is required");
167
+ if (cfg.beforeSpend !== undefined && typeof cfg.beforeSpend !== "function")
168
+ throw new Error("beforeSpend must be a function");
169
+ if (!cfg.submitter.waitsForFinality)
170
+ throw new Error("the submitter must wait for finality");
171
+ if (cfg.journal.owner !== cfg.submitter.payer)
172
+ throw new Error("the journal belongs to another payer");
173
+ await ready();
174
+ const rt = cfg.runtime ?? await createLongSessionRuntime(cfg);
175
+ if (cfg.journal.genesis !== u8aToHex(rt.genesisHash))
176
+ throw new Error("the journal belongs to another chain");
177
+ if (rt.blockMs <= 0n)
178
+ throw new Error("invalid chain block time");
179
+ const windowBlocks = ceilDiv(BigInt(cfg.windowSeconds) * 1000n, rt.blockMs);
180
+ const maxLockBlocks = BigInt(cfg.maxLockSeconds) * 1000n / rt.blockMs;
181
+ if (windowBlocks > maxLockBlocks)
182
+ throw new Error("the requested window rounds past maxLockSeconds");
183
+ await cfg.journal.acquire();
184
+ try {
185
+ await rt.assertModelIdentity(cfg.modelIdentity);
186
+ await rt.assertMinerAdmitted(cfg.miner);
187
+ const session = new LongSession(cfg, rt, windowBlocks, maxLockBlocks);
188
+ await session.reconcile();
189
+ return session;
190
+ }
191
+ catch (error) {
192
+ await cfg.journal.release();
193
+ throw error;
194
+ }
195
+ }
196
+ /** Serve one request, buying, topping up or rolling over only as this request requires. */
197
+ turn(envelope, options) {
198
+ const run = this.queue.then(() => this.runTurn(envelope, options));
199
+ this.queue = run.catch(() => undefined);
200
+ return run;
201
+ }
202
+ /** Reconcile the journal against finalized chain state. Submits nothing. */
203
+ recover() {
204
+ const run = this.queue.then(() => this.reconcile());
205
+ this.queue = run.catch(() => undefined);
206
+ return run;
207
+ }
208
+ /** Stop new turns, settle the live channel cooperatively, reconcile, and release the lock. */
209
+ async close() {
210
+ this.closed = true;
211
+ await this.queue;
212
+ try {
213
+ if (this.live)
214
+ await this.retire(this.live);
215
+ return await this.reconcile();
216
+ }
217
+ finally {
218
+ await this.cfg.journal.release();
219
+ }
220
+ }
221
+ async runTurn(envelope, { onText, requestId, acceptReceipt }) {
222
+ if (typeof requestId !== "string" || requestId.length === 0)
223
+ throw new Error("requestId is required");
224
+ const prior = this.cfg.journal.state().requests[requestId];
225
+ if (prior?.status === "done") {
226
+ const saved = decodeJournalValue(prior.result);
227
+ return { requestId, channelId: saved.channelId, receipt: saved.receipt, replayed: true };
228
+ }
229
+ if (this.closed)
230
+ throw new Error("long session is closed");
231
+ if (envelope.model !== this.cfg.modelIdentity.requestedSlug)
232
+ throw new Error("request model differs from the session model");
233
+ const bodyBytes = sessionTurnBodyBytes(encodeChatTurnEnvelope(envelope).length);
234
+ if (bodyBytes > MAX_SESSION_TURN_BODY_BYTES)
235
+ throw new TurnTooLargeError(bodyBytes);
236
+ const worst = this.cfg.worstCaseTurnPlanck(envelope);
237
+ if (typeof worst !== "bigint" || worst <= 0n)
238
+ throw new Error("worst-case turn tariff must be a positive bigint");
239
+ if (worst > this.cfg.maxChannelPlanck)
240
+ throw new Error("one worst-case turn exceeds maxChannelPlanck");
241
+ // The tariff is `BasePerTurn` plus one atom per G_n (`forceSettlePayable`), so this is the turn's largest G_n.
242
+ const worstGn = worst - this.rt.basePerTurn;
243
+ if (worstGn <= 0n)
244
+ throw new Error("worst-case turn tariff must exceed BasePerTurn");
245
+ const live = await this.servable(worst, worstGn);
246
+ await this.cfg.journal.beginRequest(requestId, live.record.channel);
247
+ let persisted = false;
248
+ let receiptSeen = false;
249
+ this.onText = onText;
250
+ this.decoder = new TextDecoder();
251
+ this.framesSeen = 0;
252
+ try {
253
+ const receipt = await live.session.chatTurn(envelope, async (candidate) => {
254
+ receiptSeen = true;
255
+ const { channel } = await this.rt.channel(live.channelId);
256
+ if (!channel || channel.state !== "Open")
257
+ throw new Error("channel is not Open at finality");
258
+ const payable = forceSettlePayable(this.rt.basePerTurn, live.session.turnsVerified() + 1, live.session.aggregateGn() + candidate.gN);
259
+ const escrow = channel.escrow < live.escrow ? channel.escrow : live.escrow;
260
+ if (payable > escrow)
261
+ throw new TariffExceedsEscrowError(payable, escrow);
262
+ await acceptReceipt?.(candidate);
263
+ }, async (verified) => {
264
+ live.record = { ...live.record, turns: live.session.turnsVerified(),
265
+ claim: encodeJournalValue(live.session.forceSettlement()) };
266
+ await this.cfg.journal.commitTurn(live.record, requestId, encodeJournalValue({ channelId: live.record.channel, receipt: verified }));
267
+ persisted = true;
268
+ });
269
+ return { requestId, channelId: live.record.channel, receipt, replayed: false };
270
+ }
271
+ catch (error) {
272
+ if (!persisted)
273
+ await this.cfg.journal.dropRequest(requestId);
274
+ // Refused before serving (HTTP 400/413, no frame, no receipt): the miner signed no leaf and its
275
+ // turn index and fence are unchanged, so the channel serves on. Anything else retires it.
276
+ if (error instanceof MinerTurnRejectedError && !persisted && !receiptSeen && this.framesSeen === 0)
277
+ throw error;
278
+ // The miner's turn index and unacked fence are unknown after a failed turn, and a miner whose
279
+ // receipt or tariff just failed must not be co-signed the whole escrow: leave it for timeout.
280
+ live.retire ??= `turn failed: ${String(error?.message ?? error)}`;
281
+ live.noCooperative = true;
282
+ throw error;
283
+ }
284
+ finally {
285
+ this.onText = undefined;
286
+ }
287
+ }
288
+ frame(frame) {
289
+ this.framesSeen += 1;
290
+ if (frame.type !== "chunk" || frame.kind !== "output" || !this.onText)
291
+ return;
292
+ this.onText(this.decoder.decode(hexToU8a(frame.data), { stream: true }));
293
+ }
294
+ /**
295
+ * The live channel if it can serve `worst` (`worstGn` of work), topped up if needed; otherwise
296
+ * roll over. A channel whose calibrated allowance cannot settle another worst-case turn is
297
+ * replaced only when a new channel could settle it; otherwise the request is refused and the
298
+ * channel kept for smaller requests.
299
+ */
300
+ async servable(worst, worstGn) {
301
+ const live = this.live;
302
+ if (live && !live.retire) {
303
+ const block = await this.rt.finalizedBlock();
304
+ const turnBlocks = ceilDiv(BigInt(this.cfg.turnTimeoutSeconds) * 1000n, this.rt.blockMs);
305
+ if (live.session.turnsVerified() >= live.maxTurns)
306
+ live.retire = "turn limit reached";
307
+ else if (live.endBlock - block < turnBlocks)
308
+ live.retire = "window too short for another turn";
309
+ else if (live.session.aggregateGn() + worstGn > settleableAllowance(await this.liveSnapshot(live))) {
310
+ await this.assertNewChannelCovers(worstGn);
311
+ live.retire = "calibrated allowance cannot settle another worst-case turn";
312
+ }
313
+ else {
314
+ const committed = forceSettlePayable(this.rt.basePerTurn, live.session.turnsVerified(), live.session.aggregateGn());
315
+ const unspent = live.escrow - committed;
316
+ if (unspent >= 2n * worst)
317
+ return live;
318
+ const room = this.topUpRoom(live);
319
+ if (unspent + room >= worst) {
320
+ if (room > 0n)
321
+ await this.topUp(live, room);
322
+ return live;
323
+ }
324
+ live.retire = "escrow cannot fund another turn within limits";
325
+ }
326
+ }
327
+ if (this.live)
328
+ await this.retire(this.live);
329
+ return this.buy(worst, worstGn);
330
+ }
331
+ /** The live channel's finalized allowance inputs; a channel no longer Open settles nothing more. */
332
+ async liveSnapshot(live) {
333
+ const { channel } = await this.rt.channel(live.channelId);
334
+ return channel && channel.state === "Open" ? channel : { snapshotCap: null, currentCap: null, maxDuration: 0n };
335
+ }
336
+ /**
337
+ * The G_n/s a channel opened now would pin: the miner's reservation rate (the whole cap when
338
+ * unset, or on a runtime without reservations), never above the current cap.
339
+ */
340
+ async reservedRate(capacity, admittedCap) {
341
+ if (capacity)
342
+ return min(capacity.rate, capacity.cap);
343
+ return admittedCap ?? await this.rt.assertMinerAdmitted(this.cfg.miner);
344
+ }
345
+ /** Refuse, before retiring anything, when even a new channel of the requested window could not settle the turn. */
346
+ async assertNewChannelCovers(worstGn) {
347
+ const rate = await this.reservedRate(await this.rt.capacity(this.cfg.miner));
348
+ if (rate * this.windowBlocks < worstGn) {
349
+ throw new CalibratedAllowanceError(this.cfg.miner, rate, this.windowBlocks, rate * this.windowBlocks, worstGn);
350
+ }
351
+ }
352
+ topUpRoom(live) {
353
+ const left = this.cfg.budgetPlanck - BigInt(this.cfg.journal.state().debited);
354
+ return max(0n, min(this.cfg.topUpPlanck, this.cfg.maxChannelPlanck - live.escrow, left));
355
+ }
356
+ assertSpendable() {
357
+ const open = unresolvedSpends(this.cfg.journal.state());
358
+ if (open.length > 0)
359
+ throw new SpendingFrozenError(open.map((e) => e.txHash));
360
+ }
361
+ async topUp(live, amount) {
362
+ this.assertSpendable();
363
+ await this.cfg.beforeSpend?.("topUp");
364
+ this.journaled.arm("topUp", live.record.channel, amount);
365
+ try {
366
+ await live.session.topUp(amount);
367
+ }
368
+ catch (error) {
369
+ // Escrow on chain may now differ from what a cooperative receipt would co-sign.
370
+ live.retire = "top-up failed or outcome unknown";
371
+ live.noCooperative = true;
372
+ throw error;
373
+ }
374
+ live.escrow += amount;
375
+ live.record = { ...live.record, escrow: live.escrow.toString() };
376
+ await this.cfg.journal.putChannel(live.record);
377
+ }
378
+ /** Signature-valid, unexpired, unused offers from this miner for this model and precision. */
379
+ async verifiedOffers(block) {
380
+ const identity = this.cfg.modelIdentity;
381
+ const [raw, profile] = await Promise.all([this.rt.offers(identity), this.rt.offerFeeProfile()]);
382
+ const valid = [];
383
+ for (const signed of raw) {
384
+ try {
385
+ const o = signed.offer;
386
+ if (o.forward || o.feeProfile !== profile || !sameAccount(o.miner, this.cfg.miner)
387
+ || !u8aEq(o.modelHash, identity.modelHash) || o.precision !== identity.precision
388
+ || o.expiry <= block + CAPACITY_INCLUSION_MARGIN_BLOCKS
389
+ || !Number.isSafeInteger(o.maxTurns) || o.maxTurns < 1 || o.maxTurns > this.rt.maxSettlementTurns
390
+ || o.maxDuration <= 0n || o.minEscrow < 0n || o.enclaveKey.length !== 32
391
+ || !verify(decodeAddress(this.cfg.miner), sessionOfferMessage(this.rt.genesisHash, o), signed.minerSignature))
392
+ continue;
393
+ if (await this.rt.offerNonceUsed(this.cfg.miner, o.nonce))
394
+ continue;
395
+ valid.push(signed);
396
+ }
397
+ catch { /* an untrusted listing cannot make a malformed row usable */ }
398
+ }
399
+ return valid;
400
+ }
401
+ /** Wait at finality until the miner can take one more reservation. */
402
+ async waitCapacity() {
403
+ for (let attempt = 0;; attempt++) {
404
+ const capacity = await this.rt.capacity(this.cfg.miner);
405
+ if (!capacity || capacity.fits)
406
+ return capacity;
407
+ if (capacity.reason === "no_cap")
408
+ throw new Error("miner has no live calibrated capacity");
409
+ if (attempt >= this.cfg.turnTimeoutSeconds)
410
+ throw new Error(`miner capacity still ${capacity.reason} at finality`);
411
+ await this.rt.pause();
412
+ }
413
+ }
414
+ async buy(worst, worstGn) {
415
+ this.assertSpendable();
416
+ const cfg = this.cfg;
417
+ const identity = cfg.modelIdentity;
418
+ await this.rt.assertModelIdentity(identity);
419
+ const admittedCap = await this.rt.assertMinerAdmitted(cfg.miner);
420
+ const capacity = await this.waitCapacity();
421
+ // What the pallet will pin as this channel's snapshot cap; its allowance is that times the window.
422
+ const rate = await this.reservedRate(capacity, admittedCap);
423
+ const block = await this.rt.finalizedBlock();
424
+ const offers = await this.verifiedOffers(block);
425
+ const fitting = offers
426
+ .filter(({ offer }) => offer.maxDuration >= this.windowBlocks && offer.maxDuration <= this.maxLockBlocks
427
+ && offer.minEscrow <= cfg.maxChannelPlanck && rate * offer.maxDuration >= worstGn)
428
+ .sort((a, b) => (a.offer.minEscrow < b.offer.minEscrow ? -1 : a.offer.minEscrow > b.offer.minEscrow ? 1 : b.offer.maxTurns - a.offer.maxTurns));
429
+ const chosen = fitting[0];
430
+ let enclaveKey;
431
+ let escrow;
432
+ let nonce;
433
+ let maxTurns;
434
+ let window;
435
+ if (chosen) {
436
+ enclaveKey = chosen.offer.enclaveKey;
437
+ escrow = max(chosen.offer.minEscrow, worst);
438
+ nonce = chosen.offer.nonce;
439
+ maxTurns = chosen.offer.maxTurns;
440
+ window = chosen.offer.maxDuration;
441
+ }
442
+ else {
443
+ if (!this.rt.unconsented)
444
+ throw new Error("runtime has no unconsented open constants to price a bare open");
445
+ if (!capacity)
446
+ throw new Error("runtime has no capacity reservations to price a bare open");
447
+ window = min(this.windowBlocks, this.rt.unconsented.maxBlocks, this.maxLockBlocks);
448
+ if (window < 1n)
449
+ throw new Error("no bare open window fits the limits");
450
+ if (capacity.rate <= 0n || this.rt.unconsented.tariff <= 0n)
451
+ throw new Error("bare open floor is not positive");
452
+ const floor = capacity.rate * window * this.rt.unconsented.tariff;
453
+ const pinned = cfg.enclaveKey ?? offers[0]?.offer.enclaveKey;
454
+ if (!pinned)
455
+ throw new Error("no miner-signed offer or pinned enclave key to bind a bare open");
456
+ enclaveKey = pinned;
457
+ escrow = max(floor, worst);
458
+ nonce = BigInt(u8aToHex(randomAsU8a(8)));
459
+ maxTurns = Math.min(cfg.maxTurns, this.rt.maxSettlementTurns);
460
+ }
461
+ if (rate * window < worstGn)
462
+ throw new CalibratedAllowanceError(cfg.miner, rate, window, rate * window, worstGn);
463
+ if (escrow > cfg.maxChannelPlanck)
464
+ throw new Error(`opening escrow ${escrow} exceeds maxChannelPlanck`);
465
+ const debited = BigInt(cfg.journal.state().debited);
466
+ if (debited + escrow > cfg.budgetPlanck)
467
+ throw new Error(`opening escrow ${escrow} would pass the lifetime budget`);
468
+ // Prove the peer before funding: its enclave signs a fresh challenge for this identity.
469
+ const info = await this.rt.infoProof(enclaveKey, identity);
470
+ if (!sameAccount(info.minerAddress, cfg.miner) || !u8aEq(info.enclaveKey, enclaveKey))
471
+ throw new Error("info proof is for another miner or key");
472
+ await cfg.beforeSpend?.("open");
473
+ const seed = randomAsU8a(32);
474
+ const key = SessionKey.fromSeed(seed);
475
+ const channelId = channelIdV1(this.rt.genesisHash, decodeAddress(cfg.submitter.payer), decodeAddress(cfg.miner), nonce);
476
+ const channel = u8aToHex(channelId);
477
+ let record = { channel, miner: cfg.miner, sessionSeed: u8aToHex(seed), state: "opening",
478
+ escrow: escrow.toString(), maxTurns, turns: 0 };
479
+ await cfg.journal.putChannel(record);
480
+ this.journaled.arm("open", channel, escrow);
481
+ if (chosen) {
482
+ const accepted = { agent: cfg.submitter.payer, offer: chosen.offer, measuredRoot: identity.measuredRoot,
483
+ decodePolicyHash: identity.decodePolicyHash, agentKey: key.publicKey, escrow };
484
+ await this.chain.openChannelWithOffer({ ...accepted, minerSignature: chosen.minerSignature,
485
+ agentSignature: signOfferAcceptance(this.rt.genesisHash, accepted, key) });
486
+ }
487
+ else {
488
+ await this.chain.openChannel({ miner: cfg.miner, modelHash: identity.modelHash, measuredRoot: identity.measuredRoot,
489
+ decodePolicyHash: identity.decodePolicyHash, precision: identity.precision, enclaveKey, agentKey: key.publicKey,
490
+ maxTurns, maxDuration: window, reattestEvery: 1, escrow, nonce });
491
+ }
492
+ try {
493
+ const { channel: opened } = await this.rt.channel(channelId);
494
+ if (!opened || opened.state !== "Open" || !sameAccount(opened.miner, cfg.miner) || !u8aEq(opened.agentKey, key.publicKey)
495
+ || !u8aEq(opened.enclaveKey, enclaveKey) || !u8aEq(opened.modelHash, identity.modelHash)
496
+ || !u8aEq(opened.measuredRoot, identity.measuredRoot) || !u8aEq(opened.decodePolicyHash, identity.decodePolicyHash)
497
+ || opened.precision !== identity.precision || opened.escrow !== escrow) {
498
+ throw new Error("finalized channel does not match the purchase");
499
+ }
500
+ // The rate may have changed before inclusion: the pinned snapshot decides what can settle.
501
+ const allowance = settleableAllowance(opened);
502
+ if (allowance < worstGn) {
503
+ const pinned = opened.snapshotCap === null || opened.currentCap === null ? 0n : min(opened.snapshotCap, opened.currentCap);
504
+ throw new CalibratedAllowanceError(cfg.miner, pinned, opened.maxDuration, allowance, worstGn);
505
+ }
506
+ const endBlock = opened.openedAt + opened.maxDuration;
507
+ record = { ...record, state: "open", endBlock: endBlock.toString() };
508
+ await cfg.journal.putChannel(record);
509
+ const transport = await this.rt.connect(channelId, key, info, (frame) => this.frame(frame));
510
+ const session = ChannelSession.fromOpenChannel({
511
+ chain: this.chain, transport, enclaveKey, agentKey: key, measuredRoot: identity.measuredRoot,
512
+ modelIdentity: identity, maxUnackedGn: info.maxUnackedGn, basePerTurn: this.rt.basePerTurn,
513
+ }, { channelId, decodePolicyHash: identity.decodePolicyHash, escrow });
514
+ this.live = { channelId, key, session, record, escrow, endBlock, maxTurns };
515
+ return this.live;
516
+ }
517
+ catch (error) {
518
+ await cfg.journal.putChannel({ ...record, state: "orphaned", note: `unusable after open: ${String(error?.message ?? error)}` });
519
+ throw error;
520
+ }
521
+ }
522
+ /**
523
+ * Wait until the pallet's calibrated allowance covers the verified work. False past the window
524
+ * or after `turnTimeoutSeconds` pauses, so a request never waits on it for hours.
525
+ */
526
+ async settleAllowed(live) {
527
+ const gn = live.session.aggregateGn();
528
+ for (let attempt = 0; attempt <= this.cfg.turnTimeoutSeconds; attempt++) {
529
+ const { block, channel } = await this.rt.channel(live.channelId);
530
+ if (!channel || channel.state !== "Open")
531
+ return false;
532
+ if (block > channel.openedAt + channel.maxDuration)
533
+ return false;
534
+ const cap = channel.snapshotCap === null || channel.currentCap === null ? 0n : min(channel.snapshotCap, channel.currentCap);
535
+ if (gn > 0n && (cap <= 0n || gn > cap * channel.maxDuration))
536
+ return false;
537
+ const elapsed = block > channel.authoredOpenedAt ? block - channel.authoredOpenedAt : 1n;
538
+ if (gn <= cap * min(elapsed, channel.maxDuration))
539
+ return true;
540
+ await this.rt.pause();
541
+ }
542
+ return false;
543
+ }
544
+ /** Wait at finality for the channel to close; false after `turnTimeoutSeconds` pauses. */
545
+ async closedAtFinality(live) {
546
+ for (let attempt = 0; attempt <= this.cfg.turnTimeoutSeconds; attempt++) {
547
+ const { channel } = await this.rt.channel(live.channelId);
548
+ if (channel?.state === "Closed")
549
+ return true;
550
+ await this.rt.pause();
551
+ }
552
+ return false;
553
+ }
554
+ /**
555
+ * Drain is implicit (turns are serialized). Settle cooperatively, wait for the close at
556
+ * finality; anything uncertain is recorded and left for the permissionless timeout refund.
557
+ */
558
+ async retire(live) {
559
+ this.live = undefined;
560
+ live.retire ??= "closing";
561
+ const orphan = (note) => this.cfg.journal.putChannel({ ...live.record, state: "orphaned", note });
562
+ if (live.session.turnsVerified() === 0)
563
+ return orphan("no verified turns to settle; left for timeout refund");
564
+ if (live.noCooperative)
565
+ return orphan(`${live.retire}; left for timeout refund or the miner's force settlement`);
566
+ await this.cfg.journal.putChannel({ ...live.record, state: "closing" });
567
+ try {
568
+ if (!await this.settleAllowed(live))
569
+ return orphan("calibrated allowance cannot cover the verified work; left for timeout refund");
570
+ await live.session.closeCooperative(async (claim) => {
571
+ await this.rt.closeCooperative(claim, live.key);
572
+ if (!await this.closedAtFinality(live))
573
+ throw new Error("cooperative settlement not finalized within the window and grace");
574
+ // Internal only: the finalized Closed state is the evidence, not these fields.
575
+ const settled = { channelId: claim.channelId, minerPaid: claim.payable, burned: 0n,
576
+ aggregateGn: claim.aggregateGn, cooperative: true, txHash: "" };
577
+ return settled;
578
+ });
579
+ }
580
+ catch (error) {
581
+ return orphan(`cooperative close outcome unknown (${String(error?.message ?? error)}); left for timeout refund`);
582
+ }
583
+ await this.cfg.journal.putChannel({ ...live.record, state: "closed" });
584
+ }
585
+ reconcile() {
586
+ return reconcileSpendJournal(this.cfg.journal, this.rt, this.live?.record.channel);
587
+ }
588
+ }
589
+ /**
590
+ * Reconcile a locked journal against finalized chain state: resolve unresolved spends by finalized
591
+ * evidence for their exact hash, mark channels closed on chain (or never opened) as closed, and
592
+ * every other channel except `liveChannel` as orphaned for the timeout refund. Submits nothing and
593
+ * needs no admitted miner or listed model, so recovery, timeout refunds and drains are not blocked
594
+ * by them; purchases still check both.
595
+ */
596
+ export async function reconcileSpendJournal(journal, reader, liveChannel) {
597
+ for (const entry of unresolvedSpends(journal.state())) {
598
+ const outcome = await reader.txOutcome(entry);
599
+ if (outcome !== "unknown")
600
+ await journal.resolve(entry.txHash, outcome, "finalized evidence");
601
+ }
602
+ for (const record of journal.state().channels) {
603
+ if (record.state === "closed" || record.channel === liveChannel)
604
+ continue;
605
+ const { channel } = await reader.channel(hexToU8a(record.channel));
606
+ if (!channel) {
607
+ const open = journal.state().entries.find((e) => e.kind === "open" && e.channel === record.channel);
608
+ if (record.state === "opening" && (!open || open.status === "failed" || open.status === "dead")) {
609
+ await journal.putChannel({ ...record, state: "closed", note: "never opened" });
610
+ }
611
+ continue;
612
+ }
613
+ if (channel.state === "Closed")
614
+ await journal.putChannel({ ...record, state: "closed" });
615
+ else if (record.state !== "orphaned") {
616
+ await journal.putChannel({ ...record, state: "orphaned", endBlock: (channel.openedAt + channel.maxDuration).toString(),
617
+ note: "not live in this process; left for timeout refund or the miner's force settlement" });
618
+ }
619
+ }
620
+ const state = journal.state();
621
+ return { debited: BigInt(state.debited), unresolved: unresolvedSpends(state).map((e) => e.txHash), channels: state.channels };
622
+ }
623
+ //# sourceMappingURL=long-session.js.map