tryflop 0.0.0-stage → 0.1.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.
@@ -0,0 +1,366 @@
1
+ // Network endpoints and app settings. Imported by Node tests, so it must not import the SDK;
2
+ // src/flop.js checks at runtime that a live network's endpoints still match the SDK's own profile.
3
+ import { PLANCK_PER_FLOP } from './units.js';
4
+
5
+ /**
6
+ * A miner the app may pay directly. Miners publish no web address on-chain or in their signed
7
+ * offers, so each entry names where its address was published and when it was last checked. Its `id`
8
+ * must be unique across EVERY network: one relay serves all live networks by id (test/config.test.js).
9
+ * `model` is the model name a turn asks for; `modelHash` is that model's id in the chain's model registry,
10
+ * which is what a channel is pinned to and priced by: a miner whose readiness proof names another name or
11
+ * another hash is not paid (effects.js readyMiner).
12
+ * @typedef {{ id: string, address: string, endpoint: string, model: string, modelHash: string, source: string, checked: string }} Miner
13
+ * The free grant this app can ask the network's faucet for, once per 24 h per wallet. `signed: false` is
14
+ * the anonymous lane (`POST <faucet>/fund`, nothing signed; SDK fundFromFaucetDetailed); `signed: true` is
15
+ * a claim the wallet's own key signs (testnet's agent lane, `POST <faucet>/v1/testnet/agent-claims`; SDK
16
+ * claimTestnetAgentFunds), so the screen asks for the passphrase first. `flop` is the amount the faucet
17
+ * publishes for that lane, shown on screen. `verified`: whether the faucet's own page offers a
18
+ * verified-human grant on this network (the app only links to it). `browserClaim`: whether the faucet
19
+ * accepts that request from this web page at all (a browser sends it only after the faucet's CORS preflight
20
+ * allows it). False means the app never sends it: the screen shows the route through the faucet's own page
21
+ * instead, and `e2e/drive.mjs testnet` fails once the faucet lets browsers in, so the flag cannot go stale.
22
+ * @typedef {{ flop: number, signed: boolean, verified: boolean, browserClaim: boolean }} QuickGrant
23
+ * `rpcHttpFromPages`: whether a page on another site (tryflop.com) may read `rpcHttp` from the browser, i.e. the node
24
+ * answers a CORS pre-check. Cloudflare's functions read it server to server either way, and the app itself reads the
25
+ * chain over `rpc` (a WebSocket, which needs no CORS); only the home page's status pill reads `rpcHttp` from a page.
26
+ * @typedef {{ name: 'devnet'|'testnet', label: string, status: 'live'|'unpublished', readable: boolean, rpc: string, rpcHttp: string, rpcHttpFromPages: boolean, faucet: string,
27
+ * quickGrant: QuickGrant, gateway: string, explorer: string, indexer: string, genesis: string, miners: readonly Miner[] }} NetworkConfig
28
+ */
29
+
30
+ /**
31
+ * `status: 'live'` means "Flop has opened this network: the app may connect to it", not "every service is
32
+ * there". A live network always has rpc, rpcHttp, explorer and genesis; `faucet`, `gateway`, `indexer` and
33
+ * `miners` stay empty until Flop publishes them, and every screen that would use one says so instead of
34
+ * offering a dead link (24 Nov 2026: testnet opened with no faucet, gateway or miner).
35
+ *
36
+ * `readable` is a different fact: whether THIS BUILD can read that network's chain. Flop's networks run
37
+ * ahead of the pinned SDK's known runtimes, and the SDK refuses a runtime it does not know (code
38
+ * RUNTIME_INCOMPATIBLE, thrown by FlopClient's constructor, so it lands right after connect's genesis
39
+ * check). Nothing on a network the build cannot read works — no balance, no faucet claim (the claim is a
40
+ * chain read first) — so the screens may offer only what is readable there. The browser test in
41
+ * `e2e/drive.mjs testnet` asserts the outcome this flag predicts, so a stale flag fails that run.
42
+ * The pinned SDK 0.13.1 admits runtimes up to 1014040 (1014036 never existed) and refuses 1014041 on:
43
+ * the day Flop upgrades past that, the app refuses that network until the SDK is bumped again (testnet
44
+ * moved to 1014040 on 28 Nov 2026, which 0.12.1 refused).
45
+ */
46
+
47
+ /** @type {Readonly<Record<'devnet'|'testnet', NetworkConfig>>} */
48
+ export const NETWORKS = Object.freeze({
49
+ /** As listed in @flop-labs/sdk FLOP_NETWORK_PROFILES.devnet (rpc and gateway the same from 0.6.0 to 0.13.1; the faucet moved in 0.11.0, as here; checked 28 Nov 2026). */
50
+ devnet: Object.freeze({
51
+ name: 'devnet',
52
+ label: 'Devnet',
53
+ status: 'live',
54
+ /**
55
+ * Devnet runs runtime 1014038 (`tzkv-runtime`, read on the node 26 Nov 2026 10:42 UTC and again 28 Nov
56
+ * 11:55 UTC), which the pinned SDK 0.13.1 admits. It moved there from 1014034 between 25 and 26 Nov, and
57
+ * SDK 0.9.0 refused it: until the 0.12.1 bump the live app showed every devnet visitor "runs a newer chain
58
+ * version than this build".
59
+ */
60
+ readable: true,
61
+ rpc: 'wss://rpc.devnet.flop.network',
62
+ /**
63
+ * The same nodes over HTTPS JSON-RPC (server side only: Cloudflare's stats code). Checked 23 Nov 2026:
64
+ * batch requests answered; state_queryStorageAt took ~1.6 s for 200 keys, up to 16 s for 500, and
65
+ * every key at once (18,016 sessions) failed.
66
+ */
67
+ rpcHttp: 'https://rpc.devnet.flop.network',
68
+ /** Answers `access-control-allow-origin: *` (checked 23 Nov 2026; the home page's pill read it from tryflop.com). */
69
+ rpcHttpFromPages: true,
70
+ /**
71
+ * Moved here on 25 Nov 2026: `faucet.flop.network` was devnet's until the night of 24–25 Nov, when it
72
+ * began answering `{"network":"testnet"}` and devnet's faucet appeared at its own host. Both hosts are
73
+ * listed on Flop's official links page (https://flop.finance/official/, checked 25 Nov 2026), and
74
+ * GET <faucet>/chain answers devnet's genesis `0x99c172c0…` from here. The old host answers testnet's
75
+ * chain, so `fundFromFaucetDetailed`'s identity check refuses it ("faucet/RPC chain identity
76
+ * differs") — the app's devnet grant was broken from the flip until this line changed.
77
+ */
78
+ faucet: 'https://faucet.devnet.flop.network',
79
+ /** Its /limits: anonymous grantFlop 25, addressCooldownSeconds 86400 (13 Nov 2026; the same on 24 Nov). */
80
+ quickGrant: Object.freeze({ flop: 25, signed: false, verified: true, browserClaim: true }),
81
+ gateway: 'https://api.flop.network',
82
+ explorer: 'https://explorer.devnet.flop.network',
83
+ /** Signed session offers: GET <indexer>/api/session-offers (33 offers, none with a web address, 23 Nov). */
84
+ indexer: 'https://explorer.devnet.flop.network',
85
+ /** Genesis served by the RPC on 13 Nov 2026, and by faucet.devnet.flop.network/chain on 25 Nov 2026. */
86
+ genesis: '0x99c172c095340ace980631f9123544c6bebd4839f3437e463533422d8be2d631',
87
+ miners: Object.freeze([
88
+ // Operator-published endpoint; serves outside buyers with channel-key signed requests. On 23 Nov
89
+ // it answered its info proof "ready" and an outside app settled a bare openChannel on it.
90
+ Object.freeze({
91
+ id: 'ecamli',
92
+ address: '5HdTbhVY9jZCsfJVFENYF89hRfkBvoby2YxPest3XLLRhnrt',
93
+ endpoint: 'https://miner.ecamliflop.fyi',
94
+ model: 'qwen/qwen2.5-0.5b-instruct',
95
+ // modelRegistry.models on devnet, read 26 Nov 2026: "Qwen/Qwen2.5-0.5B-Instruct" version 1, Active;
96
+ // the same hash as the miner's 23 Nov readiness proof (test/fixtures/miner/info-proof.live.json).
97
+ modelHash: '0x1a52c1abe781db051e70ae357f72bb70161ca0c092df0b618f22a9292ba63306',
98
+ source: 'https://github.com/flop-labs/network/issues/229',
99
+ checked: '2026-11-23',
100
+ }),
101
+ // The app tries these in this order and takes the first that proves it is ready; one that refuses
102
+ // before anything is bought sits out until the next wait (SPEC: NEXT MINER).
103
+ // Operator-published: "Our existing Devnet miner runs in Docker and serves HTTPS at
104
+ // flop.leccaventures.com", next to this account. On 26 Nov 2026 its signed proof said ready for this
105
+ // account and model, and it was registered, calibrated and had settled a channel with another buyer.
106
+ Object.freeze({
107
+ id: 'lecca',
108
+ address: '5DJ4UUcwYEsSaJojzAjVqsXyiXD27dCYqVpm5n2LP26ZfLd3',
109
+ endpoint: 'https://flop.leccaventures.com',
110
+ model: 'qwen/qwen2.5-0.5b-instruct',
111
+ modelHash: '0x1a52c1abe781db051e70ae357f72bb70161ca0c092df0b618f22a9292ba63306',
112
+ source: 'https://github.com/flop-labs/network/issues/726',
113
+ checked: '2026-11-26',
114
+ }),
115
+ // The issue names this devnet account and its operator's comment names the host. On 26 Nov 2026 its
116
+ // signed proof said ready on devnet for this account and model, and it was registered, calibrated and
117
+ // had settled channels with other buyers. A larger model: one channel's escrow is ~1.43 FLOP.
118
+ Object.freeze({
119
+ id: 'noeud',
120
+ address: '5D53hgvm44fnL2CxR1GhgfGeBgmapycqj6so6fUGv5rirGfh',
121
+ endpoint: 'https://s1.noeud-inference.fr',
122
+ model: 'qwen/qwen3-14b',
123
+ // modelRegistry.models on devnet, read 26 Nov 2026: "Qwen/Qwen3-14B", Verified.
124
+ modelHash: '0x4f8fcb1427199f8eaeaab751b6df123366a5792d021a695223c2c78e9e2634ce',
125
+ source: 'https://github.com/flop-labs/network/issues/319#issuecomment-7198068424',
126
+ checked: '2026-11-26',
127
+ }),
128
+ ]),
129
+ }),
130
+ /**
131
+ * Flop opened its public testnet on 24 Nov 2026 ("FLOP Testnet is live! … We'll be activating features
132
+ * over the coming hours", https://docs.flop.network/operators?network=testnet). Its faucet followed on
133
+ * the night of 24–25 Nov: `faucet.flop.network` began serving testnet (devnet's moved to its own host —
134
+ * see devnet above). Checked 26 Nov 2026 11:00 UTC: Flop's testnet explorer now lists 8 miners
135
+ * (`/api/miners`; one ran a paid job at block 161,459; it answered `total: 0` on 25 Nov), but none
136
+ * publishes a web address this app could reach it at, so `miners` stays empty; `gateway.testnet.flop.network`
137
+ * answers since 26 Nov (this app uses no gateway); there is still no session-offer indexer.
138
+ */
139
+ testnet: Object.freeze({
140
+ name: 'testnet',
141
+ label: 'Testnet',
142
+ status: 'live',
143
+ /**
144
+ * Testnet runs runtime 1014040 (`flop-testnet`, read on the node 28 Nov 2026 11:55 UTC; 1014039 on
145
+ * 26–27 Nov, 1014035 on 24–25 Nov), which the pinned SDK 0.13.1 admits. 0.12.1 stopped at 1014039, so
146
+ * from the upgrade on 28 Nov until this bump the app connected, passed the genesis check and then read
147
+ * nothing here ("runs a newer chain version"), as 0.9.0 did from 24 to 26 Nov. `e2e/drive.mjs testnet`
148
+ * decides which of the two this flag must be from what the app actually reaches, so a stale flag fails
149
+ * that run.
150
+ */
151
+ readable: true,
152
+ /** Published on Flop's operator page (as `wss://testnet.flop.network/`); same host, no path. */
153
+ rpc: 'wss://testnet.flop.network',
154
+ /** The same nodes over HTTPS JSON-RPC (server side only: Cloudflare's stats code), no path. */
155
+ rpcHttp: 'https://testnet.flop.network',
156
+ /**
157
+ * No (checked 27 Nov 2026): a pre-check from Origin https://tryflop.com answers 404, and a POST's answer carries no
158
+ * access-control-allow-origin, so a browser on another site cannot read it (a page on 127.0.0.1 can: the node's
159
+ * default CORS allows localhost, which is why local runs pass). The home page shows no live block for testnet.
160
+ */
161
+ rpcHttpFromPages: false,
162
+ /**
163
+ * Live since 25 Nov 2026 (GET <faucet>/chain: `{"network":"testnet","chain":"FLOP Testnet",genesis
164
+ * 0x918abd58…}`, /health `status:"ok"`, /limits `faucet.status:"open"`), named as testnet's own faucet on
165
+ * Flop's official links page (https://flop.finance/official/), and SDK 0.11.0 on carries the same host.
166
+ *
167
+ * It does not serve the anonymous lane: `POST /fund` answers 404, and SDK 0.11.0 on refuses this host for
168
+ * `fundFromFaucetDetailed` before sending anything ("Public Testnet funding is unavailable"). Its one
169
+ * grant is the AGENT lane, a claim the recipient's own key signs: `POST /v1/testnet/agent-claims`, which
170
+ * SDK 0.12.0 on sends as `claimTestnetAgentFunds` (it checks /chain against testnet's genesis first, then
171
+ * signs "flop-faucet-agent/v1|<genesis>|<address>|<nonce>"). Its /limits (26 Nov 2026 10:56 UTC):
172
+ * `agent.grantFlop` 10, `rolling24HourCapFlop` 10, `cooldownSeconds` 86400, `rolloverRequiresSpend`
173
+ * true; per client IP 3 grants a day. Its own page (the root, to a browser) says "Agent claim 10 FLOP per
174
+ * 24 hours" and "Verified human: Unavailable on Testnet", so this app offers no verified grant here.
175
+ *
176
+ * `browserClaim: false` since 26 Nov 2026 evening: the faucet answers the CORS preflight of
177
+ * `POST /v1/testnet/agent-claims` with 404 and no Access-Control-Allow-Origin (checked 19:34 and 20:12
178
+ * UTC), so every browser blocks the claim before it is sent. Until Flop fixes that, the app sends no claim
179
+ * here; its screen walks the user through Flop's own faucet page (a browser wallet extension claims there)
180
+ * and a transfer to this app's wallet. `node e2e/drive.mjs testnet` fails once a real browser gets through.
181
+ */
182
+ faucet: 'https://faucet.flop.network',
183
+ quickGrant: Object.freeze({ flop: 10, signed: true, verified: false, browserClaim: false }),
184
+ gateway: '',
185
+ /** Flop's own explorer, linked from the announcement ("Follow the chain on FLOPScan"). */
186
+ explorer: 'https://testnet.flopscan.io',
187
+ indexer: '',
188
+ genesis: '0x918abd58fb16306b30ef3886514cfaebffecb4de43e82b6f8ec4795c43cfd800',
189
+ miners: Object.freeze([]),
190
+ }),
191
+ });
192
+
193
+ /**
194
+ * The network a page address without `?network=` gets: testnet since 27 Nov 2026, now that Flop's public testnet
195
+ * is the network that counts; devnet before. Devnet stays one link away (`app?network=devnet`),
196
+ * and each network keeps its own saved wallet (src/storage.js storageKey), so changing this moves nobody's
197
+ * wallet: a devnet wallet made before the switch is still at `app?network=devnet`.
198
+ */
199
+ export const DEFAULT_NETWORK = 'testnet';
200
+
201
+ /**
202
+ * Every endpoint of every live network, once: the CSP connect-src of the server header and of
203
+ * public/app.html's own tag (test/csp.test.js keeps the two in step). It includes each network's HTTPS
204
+ * RPC: the header covers every static file, and the home page (public/index.html) reads the default
205
+ * network's latest block over HTTPS, so the header must allow it as well as the home page's own tag.
206
+ * @returns {string[]}
207
+ */
208
+ export function connectSources() {
209
+ const live = Object.values(NETWORKS).filter((n) => n.status === 'live');
210
+ return [...new Set(live.flatMap((n) => [n.rpc, n.rpcHttp, n.faucet, n.gateway, n.explorer, n.indexer]).filter(Boolean))];
211
+ }
212
+
213
+ /**
214
+ * The network named by `?network=` in the page address, if Flop has opened it; otherwise the default,
215
+ * with a notice that says why.
216
+ * @param {string} search e.g. location.search
217
+ * @param {Readonly<Record<string, NetworkConfig>>} [networks] the table to read; it must hold DEFAULT_NETWORK
218
+ * @returns {{ network: NetworkConfig, notice: string|null }}
219
+ */
220
+ export function selectNetwork(search, networks = NETWORKS) {
221
+ const fallback = networks[DEFAULT_NETWORK];
222
+ const wanted = new URLSearchParams(search ?? '').get('network');
223
+ if (!wanted) return { network: fallback, notice: null };
224
+ const found = Object.hasOwn(networks, wanted) ? networks[wanted] : null;
225
+ // Never repeat the name: anyone can send a link, and the notice shows on every screen of this page
226
+ // (security audit, 24 Nov 2026: "?network=" could put fake instructions next to the recovery words).
227
+ if (!found) return { network: fallback, notice: `There is no network with that name, so this is ${fallback.name}.` };
228
+ if (found.status !== 'live') return { network: fallback, notice: `Flop has not opened ${found.name} yet, so this is ${fallback.name}.` };
229
+ return { network: found, notice: null };
230
+ }
231
+
232
+ // Outside a browser there is no page address: Node (the unit tests, the browser drivers, the connector) and
233
+ // Cloudflare's functions get devnet, the network the money-path tests describe, whatever the default is.
234
+ const selected = globalThis.location ? selectNetwork(globalThis.location.search ?? '') : { network: NETWORKS.devnet, notice: null };
235
+ /** The network this page uses (devnet outside a browser). */
236
+ export const NETWORK = selected.network;
237
+ /** Why the page is not on the network its address asked for, or null. */
238
+ export const NETWORK_NOTICE = selected.notice;
239
+
240
+ export const APP = Object.freeze({
241
+ /** Kept back from the session cap: pays the owner's own transaction fees (session, fee money, revoke). */
242
+ feeReservePlanck: 1n * PLANCK_PER_FLOP,
243
+ /**
244
+ * A faucet grant counts as arrived when the balance rose by this much, and "Use my FLOP" is offered
245
+ * from it. (Setting up needs more: 1 FLOP kept + 0.5 FLOP fee money + a limit of at least 2 FLOP.)
246
+ */
247
+ minUsablePlanck: 1n * PLANCK_PER_FLOP,
248
+ /** Default session limit offered on screen (security review 13 Nov: not the whole balance). */
249
+ defaultCapPlanck: 10n * PLANCK_PER_FLOP,
250
+ /** Per-transaction ceiling for session spends (SDK CALIBRATED_LIMITS uses 5 FLOP). */
251
+ perTxLimitPlanck: 5n * PLANCK_PER_FLOP,
252
+ sessionDays: 7,
253
+ /** Session calls may only touch compute channels (runtime pallet name, checked on devnet 13 Nov). */
254
+ allowedPallets: Object.freeze(['ComputeChannel']),
255
+ /** MINER_UNAVAILABLE waits: 1, 2, 5, 5, 5 minutes, then PAUSED (SPEC diagram). */
256
+ backoffSeconds: Object.freeze([60, 120, 300, 300, 300]),
257
+ /**
258
+ * A tap opens at most this many batches (each buys at most one channel), counting every follow-up batch
259
+ * and every retry after a wait: the per-tap bound on spend (review of a28c8d9, 24 Nov).
260
+ */
261
+ maxBatchesPerTap: 6,
262
+ /** While PAUSED, how often the health check runs again. */
263
+ healthRetryMs: 30_000,
264
+ /** How long one WAIT_FOR_BALANCE check waits for a faucet grant to show up. */
265
+ balanceWaitMs: 90_000,
266
+ /** Browser connect: measured 8.6–9.5 s on 13 Nov (951 KB of metadata); the SDK's own limit is 10 s. */
267
+ connectTimeoutMs: 60_000,
268
+ /** Faucet /chain took 2–3.5 s on 13 Nov; the SDK default is 5 s. */
269
+ faucetTimeoutMs: 30_000,
270
+ /**
271
+ * The devnet faucet's /limits on 13 Nov (its own host since 25 Nov): anonymous
272
+ * addressCooldownSeconds = 86400. Testnet's agent lane: cooldownSeconds 86400 per wallet (its /limits,
273
+ * 26 Nov 2026), plus 3 grants a day per client IP.
274
+ */
275
+ quickGrantCooldownMs: 24 * 3600 * 1000,
276
+ /** Verified grants: identityCooldownSeconds = 86400, at most 2,000 FLOP per rolling 7 days. */
277
+ verifiedGrantCooldownMs: 24 * 3600 * 1000,
278
+ /** Answer length per task, in tokens (measured 23 Nov: G_n 438–481 per answer at 400). */
279
+ maxTokens: 400,
280
+ });
281
+
282
+ /**
283
+ * Paying a miner directly (SDK computeChannel.LongSession through the capped session key).
284
+ * Measured by the devnet probe on 23 Nov 2026 (channel 0x14ed7879…c2b0 on miner ecamli: opened at block
285
+ * 4,470,018 through flopSessionKeys.executeViaSession, two turns, settled cooperatively at 4,470,434,
286
+ * minerPaid 0.757 FLOP; e2e/verify-channel.mjs passed on finalized state).
287
+ */
288
+ export const DIRECT = Object.freeze({
289
+ /** Channel window. The bare-open escrow is set by the miner's rate: on ecamli ~0.00099 FLOP per second of window (900 s: 0.8907 FLOP). */
290
+ windowSeconds: 900,
291
+ /** Longest one channel may lock the user's FLOP. */
292
+ maxLockSeconds: 1800,
293
+ /**
294
+ * The miner settles ~380 blocks after the batch closes (probe: close at ~4,470,054, settle at 4,470,434;
295
+ * flop-labs/network#229 saw 260–450 after open). A batch stops starting new turns early enough for that.
296
+ */
297
+ settleAllowanceSeconds: 450,
298
+ /** One channel's escrow ceiling, top-ups included (below the session's 5 FLOP per-payment limit). */
299
+ maxChannelPlanck: 2n * PLANCK_PER_FLOP,
300
+ topUpPlanck: PLANCK_PER_FLOP / 2n,
301
+ /**
302
+ * SLA turn limit of a bare open (the outside app's settled bare open on 23 Nov used 64). The machine stops
303
+ * a batch after this many answers. An offer may set a lower limit; reaching it ends the batch into the
304
+ * counted miner waits, never an extra purchase (onePurchasePerBatch).
305
+ */
306
+ maxTurns: 64,
307
+ /** Longest one answer may take before the turn counts as lost (probe: 38 s with the channel purchase, then 12 s). */
308
+ turnTimeoutSeconds: 120,
309
+ /**
310
+ * Worst-case G_n of one turn. Probe: 438–439 G_n per turn at max_tokens 400 (short prompts); kept at
311
+ * 20,000 so a 12,000-character summary fits too. The channel's settleable allowance is ~10^7 G_n, so
312
+ * the overestimate costs nothing.
313
+ */
314
+ worstTurnGn: 20_000n,
315
+ /** Fee money sent to the session key: ~45 wrapped payments at the measured 0.0109 FLOP each (ED 0.01 FLOP). */
316
+ feeFloatPlanck: PLANCK_PER_FLOP / 2n,
317
+ /** Below this the session key asks for a top-up: ED + 3 measured fees ≈ 0.043 FLOP. */
318
+ feeMinPlanck: PLANCK_PER_FLOP / 20n,
319
+ /** A retired session key holding less than this keeps it: the transfer's own fee would eat it. */
320
+ sweepMinPlanck: PLANCK_PER_FLOP / 50n,
321
+ });
322
+
323
+ /** How long a batch may keep starting turns: the rest of the window is the miner's to settle in. */
324
+ export const MAX_BATCH_SECONDS = DIRECT.windowSeconds - DIRECT.settleAllowanceSeconds - DIRECT.turnTimeoutSeconds;
325
+
326
+ /**
327
+ * Giving an outside AI agent (first of all the Claude connector, apps/flop-mcp/) its own capped limit.
328
+ * What the form offers by default lives in `AGENT_DEFAULTS` (`src/agents-core.js`): the connector's own
329
+ * reference grant of 24 Nov.
330
+ */
331
+ export const AGENT = Object.freeze({
332
+ /**
333
+ * The chain's own ceilings, read from devnet's metadata on 24 Nov. This app's own limit counts
334
+ * towards `maxSessionsPerOwner`. `maxSessionDays` is the fallback for when the live read fails:
335
+ * without it the form would accept a length the chain then silently shortens, so the confirm
336
+ * screen could promise more days than the limit gets. The live read always wins.
337
+ */
338
+ maxSessionsPerOwner: 10,
339
+ maxSessionDays: 10,
340
+ });
341
+
342
+ /**
343
+ * How a turn is sent for each model a listed miner serves.
344
+ * - `chatTemplate`: false sends a flop.chat-turn.v1 turn, which the miner hands to the model as plain text
345
+ * (the messages' text, one per line, with no chat template). true sends flop.chat-turn.v2: the miner renders
346
+ * the messages with the model's own chat template, with Qwen3's thinking switched off, and refuses an answer
347
+ * that still holds a thinking block. Qwen3 given plain text keeps writing on from the question, then
348
+ * reasons aloud until the token limit; through its template it answers.
349
+ * - `worstTurnGn`: the most G_n one turn can meter (G_n = 2 × active parameters × tokens + the attention
350
+ * term, divided by 10^9). Qwen2.5-0.5B: ~1 G_n per token, measured 438–481 per short answer at 400 tokens.
351
+ * Qwen3-14B: ~29.5 G_n per token, measured 12,925 for a 35-token prompt and 400 tokens; its worst case is a
352
+ * prompt filling its whole 40,960-token context, 1,896,996 G_n, which at the devnet price of 2·10^10
353
+ * atoms per G_n is 0.038 FLOP.
354
+ * @typedef {{ chatTemplate: boolean, worstTurnGn: bigint }} ModelProfile
355
+ * @type {Readonly<Record<string, ModelProfile>>}
356
+ */
357
+ export const MODELS = Object.freeze({
358
+ 'qwen/qwen2.5-0.5b-instruct': Object.freeze({ chatTemplate: false, worstTurnGn: DIRECT.worstTurnGn }),
359
+ 'qwen/qwen3-14b': Object.freeze({ chatTemplate: true, worstTurnGn: 1_900_000n }),
360
+ // Qwen3-8B (served on testnet): 36 layers, hidden 4096, 32 heads of 128, 8 KV heads, gated MLP 12288 (its
361
+ // config.json); a prompt filling its 40,960-token context meters 1,165,752 G_n by the SDK's own meter.
362
+ 'qwen/qwen3-8b': Object.freeze({ chatTemplate: true, worstTurnGn: 1_200_000n }),
363
+ });
364
+
365
+ /** @param {string} model a miner's model name @returns {ModelProfile} */
366
+ export const modelProfile = (model) => (Object.hasOwn(MODELS, model) ? MODELS[model] : Object.freeze({ chatTemplate: false, worstTurnGn: DIRECT.worstTurnGn }));
@@ -0,0 +1,226 @@
1
+ // SDK-free helpers of the direct-pay path (src/direct.js uses them), so Node tests cover them.
2
+ // - identityFromInfoProof: read a miner's unauthenticated, enclave-signed info proof
3
+ // (POST /session/info-proof) into the enclave key and model identity a bare channel open needs.
4
+ // It mirrors the SDK's internal modelIdentityFromWire (dist/miner-admission.js). Before buying,
5
+ // LongSession checks a fresh proof signed by this same enclave key, the miner's registration and
6
+ // capacity, and the model against Flop's registry, at finality. The key is only as trustworthy as
7
+ // the allowlisted miner and the path to it (security audit, 24 Nov).
8
+ // - classifyDirectError: sort what a payment can end in, so the state machine knows whether
9
+ // anything may have been spent (only "unknown" means it might have).
10
+ import { hexToU8a, u8aToHex } from '@polkadot/util';
11
+ import { decodeAddress } from '@polkadot/util-crypto';
12
+
13
+ /** @typedef {import('@flop-labs/sdk').computeChannel.VerifiedModelIdentity} VerifiedModelIdentity */
14
+
15
+ /** @param {unknown} value @param {number} bytes @returns {Uint8Array|undefined} */
16
+ function hexField(value, bytes) {
17
+ if (typeof value !== 'string' || value.length !== bytes * 2 || !/^[0-9a-f]*$/.test(value)) return undefined;
18
+ return hexToU8a(`0x${value}`);
19
+ }
20
+
21
+ /**
22
+ * @param {any} proof the parsed JSON of POST <endpoint>/session/info-proof
23
+ * @param {{ genesis: string, minerAddress: string }} expected this network's genesis (0x…) and the allowlisted miner
24
+ * @returns {{ enclaveKey: Uint8Array, modelIdentity: VerifiedModelIdentity }}
25
+ */
26
+ export function identityFromInfoProof(proof, { genesis, minerAddress }) {
27
+ if (!proof || typeof proof !== 'object' || proof.ready !== true) throw new Error('the miner says it is not ready');
28
+ if (`0x${proof.genesis_hash}` !== genesis.toLowerCase()) throw new Error('the miner\'s proof is for another network');
29
+ if (`0x${proof.account_id}` !== u8aToHex(decodeAddress(minerAddress))) throw new Error('the proof is signed for another miner account');
30
+ const enclaveKey = hexField(proof.enclave_key, 32);
31
+ if (!enclaveKey) throw new Error('the miner\'s enclave key is malformed');
32
+ const wire = proof.model_identity;
33
+ const modelHash = hexField(wire?.model_hash, 32);
34
+ const decodePolicyHash = hexField(wire?.decode_policy_hash, 32);
35
+ const measuredRoot = hexField(wire?.measured_root, 32);
36
+ const strings = [wire?.requested_slug, wire?.registry_model, wire?.registry_version, wire?.backend_model_name];
37
+ if (!modelHash || !decodePolicyHash || !measuredRoot || !strings.every((s) => typeof s === 'string')
38
+ || !Number.isInteger(wire.precision) || wire.precision < 0 || wire.precision > 255) {
39
+ throw new Error('the miner\'s model identity is malformed');
40
+ }
41
+ return {
42
+ enclaveKey,
43
+ modelIdentity: {
44
+ requestedSlug: wire.requested_slug, registryModel: wire.registry_model, registryVersion: wire.registry_version,
45
+ modelHash, precision: wire.precision, decodePolicyHash, measuredRoot, backendModelName: wire.backend_model_name,
46
+ },
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Session-module errors (devnet runtime 1014034 metadata, flopSessionKeys) and what they mean here.
52
+ * The SDK words a chain refusal "<section>.<name>: <docs>" (watch-transaction.js), so each pattern is
53
+ * anchored at the start: text a miner wrote can never be mistaken for one (see classifyDirectError).
54
+ */
55
+ const SESSION_ENDED = /^flopSessionKeys\.(SessionNotFound|SessionExpired|SessionRevoked|NotDelegate|SessionNonceExhausted|RetiredSessionRecordMissing)\b/;
56
+ const OUT_OF_BUDGET = /^(flopSessionKeys\.(SpendingCapExceeded|DailyCapExceeded)|[a-zA-Z]+\.CircuitBreakerTripped)\b/;
57
+ const LIMITS = /^flopSessionKeys\.(PerTxLimitExceeded|PalletNotAllowed)\b/;
58
+ const REFUSED = /^flopSessionKeys\.(InvalidSessionNonce|SpendExceedsDeclared)\b/;
59
+
60
+ /**
61
+ * What a direct-pay error means for the money:
62
+ * frozen/locked — an earlier payment's outcome is unresolved, nothing new was bought;
63
+ * budget/limits/session_ended/fees/stale_head/refused/network — refused before or without spending;
64
+ * too_large — this one task is too large for any channel, nothing bought or sent for it;
65
+ * allowance — the channel cannot serve this task: it goes back unanswered, the batch ends (the counted
66
+ * waits, or the next miner when nothing was bought), and escrow left in a channel comes back by the
67
+ * timeout refund;
68
+ * miner_rejected — the miner refused the turn before serving it (not charged);
69
+ * unknown — the outcome is unknown: never re-run automatically.
70
+ * @param {unknown} error
71
+ * @returns {'frozen'|'budget'|'limits'|'locked'|'too_large'|'allowance'|'miner_rejected'|'turn_refused'|'fees'|'session_ended'|'stale_head'|'refused'|'network'|'unknown'}
72
+ */
73
+ export function classifyDirectError(error) {
74
+ if (!(error instanceof Error)) return 'unknown';
75
+ const e = /** @type {any} */ (error);
76
+ switch (e.code) {
77
+ case 'SPENDING_FROZEN': return 'frozen';
78
+ case 'BUDGET_EXCEEDED':
79
+ // "Session circuit breaker tripped: the delegated call was not executed" (errors.js 0.9.0 to 0.12.1).
80
+ case 'CIRCUIT_BREAKER_TRIPPED': return 'budget';
81
+ case 'JOURNAL_LOCKED': return 'locked';
82
+ case 'TURN_TOO_LARGE': return 'too_large';
83
+ case 'CALIBRATED_ALLOWANCE_TOO_SMALL':
84
+ case 'TARIFF_EXCEEDS_ESCROW': return 'allowance';
85
+ // Our own guard (onePurchasePerBatch): a second channel in one batch, refused before signing.
86
+ case 'ONE_CHANNEL_PER_BATCH': return 'miner_rejected';
87
+ // A channel purchase in this turn ended unconfirmed (SDK 0.9.0 to 0.12.1 journal it as ambiguous, which
88
+ // freezes spending until the chain settles it); the turn itself was never sent, so its task goes
89
+ // back: NEEDS_FEES when the pool refused for fees (refusedForFees), else CHAIN_PENDING.
90
+ case 'TRANSACTION_UNCONFIRMED': return refusedForFees(error) ? 'fees' : 'frozen';
91
+ default: break;
92
+ }
93
+ // FenceBreachError carries the miner's own message, word for word (transport-http.js 0.9.0 to
94
+ // 0.12.1): nothing in it may decide anything.
95
+ if (e.name === 'FenceBreachError') return 'unknown';
96
+ // HTTP 400/413 before serving: the miner's turn index did not move and the SDK keeps the channel
97
+ // (long-session.js 0.9.0 to 0.12.1: "the channel serves on"). Only this question fails, and the batch goes on
98
+ // in the same channel (automated review, 24 Nov).
99
+ if (e.name === 'MinerTurnRejectedError') return 'turn_refused';
100
+ if (e.name === 'TurnTimeoutError' || e.kind === 'TurnTimeout') return 'unknown';
101
+ const message = String(e.message ?? '');
102
+ // A miner's response text rides in SDK errors after "<url> → <status> " (transport-http.js), so no
103
+ // such error ever means "nothing was sent".
104
+ if (/^\S+ → \d{3}\b/.test(message)) return 'unknown';
105
+ // Every pattern below is anchored at the start of the SDK's (or the chain's) own wording.
106
+ if (SESSION_ENDED.test(message)) return 'session_ended';
107
+ if (OUT_OF_BUDGET.test(message)) return 'budget';
108
+ // LongSession's own checks before it signs an open (long-session.js 0.9.0 to 0.12.1): less of the cap
109
+ // left than one escrow is a used-up limit; a miner pricing a channel above maxChannelPlanck cannot be
110
+ // paid by this app right now (wait and retry, like a miner that refused). Nothing was sent.
111
+ if (/^opening escrow \d+ would pass the lifetime budget/.test(message)) return 'budget';
112
+ if (/^opening escrow \d+ exceeds maxChannelPlanck/.test(message)) return 'miner_rejected';
113
+ // One worst-case turn priced above maxChannelPlanck. SDK 0.12.1 words it "one worst-case turn (<n>
114
+ // atoms) exceeds maxChannelPlanck" (0.9.0 had no number). It is "allowance": the task goes back and the
115
+ // batch ends.
116
+ if (/^one worst-case turn (\(\d+ atoms\) )?exceeds maxChannelPlanck/.test(message)) return 'allowance';
117
+ // The model's chain price, read before signing an open (channel-price.js readModelPricePerGn, SDK
118
+ // 0.10.0 on): no market state for the model, or a zero price, refuses before anything is sent.
119
+ if (/^model has no market price at this block|^model market price is zero/.test(message)) return 'miner_rejected';
120
+ if (LIMITS.test(message)) return 'limits';
121
+ if (REFUSED.test(message)) return 'refused';
122
+ if (/^1010\b.*Inability to pay some fees/i.test(message)) return 'fees';
123
+ // The SDK refuses while signing, before anything is sent (flop-submitter.js signMortal): "the RPC
124
+ // node's finalized head is 17.4 s old … Refusing to sign a spend" (met live 23 Nov), "finality lags
125
+ // too far behind the best block to sign a spend", and two "… is unreadable …; refusing to sign".
126
+ if (/^(the RPC node's finalized head is |finality lags too far behind|babe\.expectedBlockTime is unreadable|system\.blockHashCount is unreadable|the finalized block's timestamp is unreadable)/.test(message)) return 'stale_head';
127
+ // Refused before an open is signed because the miner cannot take a reservation now
128
+ // (long-session.js waitCapacity, long-session-chain.js): wait and retry, like a busy miner.
129
+ if (/^(miner capacity still \S+ at finality|miner has no live calibrated capacity|miner registration is not active at finality)/.test(message)) return 'miner_rejected';
130
+ // The other checks buy() makes before it signs an open (0.9.0 to 0.12.1: assertModelIdentity, assertMinerAdmitted,
131
+ // the fresh info proof): nothing was sent for this turn, so it waits and retries too (security audit,
132
+ // 24 Nov: as "unknown" the task showed "may have been paid" and was never re-run).
133
+ if (/^(miner is not registered at finality|miner has no finalized calibrated capacity|model is not registered at finality|model is \S+, not Verified$|registry model name or version differs at finality|model does not support this precision|measured root differs at finality|decode policy is not allowed at finality|invalid model precision \d+$|miner has no valid ready info proof for its pinned identity|info proof is for another miner or key|info proof refused: HTTP \d{3}$|info proof has no body$|info proof larger than \d+ bytes$)/.test(message)) return 'miner_rejected';
134
+ if (e instanceof TypeError && /fetch/i.test(message)) return 'network';
135
+ if (/^(disconnected from|WebSocket is not|No answer from)\b/.test(message)) return 'network';
136
+ // A channel purchase the chain included and failed (FinalizedTransactionError, watch-transaction.js):
137
+ // nothing was bought (the SDK journals it as failed) and the question was never sent; its message is
138
+ // the chain's own error. The session's own refusals above keep their meaning (review of a28c8d9, 24 Nov).
139
+ if (e.code === 'TRANSACTION_FINALIZED_FAILED') return 'refused';
140
+ return 'unknown';
141
+ }
142
+
143
+ /**
144
+ * The reasons kept in `error.cause` (up to 3 deep), for logs: the SDK's TransactionUnconfirmedError
145
+ * has a fixed message ("Transaction outcome unconfirmed (SubmissionError, …)") and keeps the node's
146
+ * own reason ("1010: Invalid Transaction: …") only as its cause. Never used to decide an outcome.
147
+ * @param {unknown} error @returns {string} "" when there is none
148
+ */
149
+ export function causeText(error) {
150
+ const parts = [];
151
+ // Never throws: it runs before a send's outcome is reported. An unreadable cause (a throwing
152
+ // getter, a revoked Proxy, an object String() cannot convert) ends the list there.
153
+ try {
154
+ const seen = new Set([error]);
155
+ let cause = error instanceof Error ? error.cause : undefined;
156
+ while (cause != null && !seen.has(cause) && parts.length < 3) {
157
+ seen.add(cause);
158
+ parts.push(typeof cause === 'object' && 'message' in cause ? String(/** @type {any} */ (cause).message) : String(cause));
159
+ cause = typeof cause === 'object' ? /** @type {any} */ (cause).cause : undefined;
160
+ }
161
+ } catch { /* keep what could be read */ }
162
+ return parts.join(' ← ');
163
+ }
164
+
165
+ /**
166
+ * The pool refused a send because its signer cannot pay the fee: definite, nothing was sent. SDK
167
+ * 0.9.0 to 0.12.1 wrap every refusal at submit time as TransactionUnconfirmedError("SubmissionError") with the
168
+ * node's own "1010: Invalid Transaction: Inability to pay some fees …" only in `cause`. Every other
169
+ * reason stays unknown: "Transaction is outdated" can mean this very transaction already landed.
170
+ * The cause comes from the RPC node, never from a miner. Never throws.
171
+ * @param {unknown} error @returns {boolean}
172
+ */
173
+ export function refusedForFees(error) {
174
+ try {
175
+ const e = /** @type {any} */ (error);
176
+ if (!e || e.code !== 'TRANSACTION_UNCONFIRMED' || e.status !== 'SubmissionError') return false;
177
+ return /^1010\b.*Inability to pay some fees/i.test(String(e.cause?.message ?? ''));
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * What to do with an orphaned channel, from one finalized read of it (`channel` null when the node
185
+ * cannot see it): "refund" once its window has passed while still Open; "closed" when it is closed,
186
+ * or unseen although the node is past its end block; otherwise "not_yet". A node running behind does
187
+ * not show a channel opened moments ago, so "unseen" alone never means closed (the escrow would stay
188
+ * locked with no refund ever asked; automated review, 24 Nov).
189
+ * @param {{ block: bigint, channel: { state: string, openedAt: bigint, maxDuration: bigint } | null, endBlock?: string }} read
190
+ * @returns {'refund'|'closed'|'not_yet'}
191
+ */
192
+ export function orphanAction({ block, channel, endBlock }) {
193
+ if (!channel) return endBlock != null && block > BigInt(endBlock) ? 'closed' : 'not_yet';
194
+ if (channel.state === 'Closed') return 'closed';
195
+ // Any other state (e.g. force-settled, waiting for its challenge window) is not ours to time out.
196
+ if (channel.state !== 'Open') return 'not_yet';
197
+ return block > channel.openedAt + channel.maxDuration ? 'refund' : 'not_yet';
198
+ }
199
+
200
+ /** Thrown by onePurchasePerBatch: this batch already bought its channel. */
201
+ export class SecondPurchaseError extends Error {
202
+ constructor() {
203
+ super('this batch already bought its channel; a second purchase is refused before signing');
204
+ this.name = 'SecondPurchaseError';
205
+ this.code = 'ONE_CHANNEL_PER_BATCH';
206
+ }
207
+ }
208
+
209
+ /**
210
+ * LongSession's `beforeSpend` hook for one batch: at most one channel open per batch (security audit
211
+ * review, 24 Nov). A further open is refused before signing, and the batch ends into the counted miner
212
+ * waits. Top-ups are bounded per channel by maxChannelPlanck and pass.
213
+ * `record.opened` turns true once an open passed `check`: the SDK calls this hook after every one of
214
+ * its own checks, right before it journals and signs the open (long-session.js buy(), 0.12.1). So
215
+ * while it is false, this batch has bought nothing, and the machine may try the next allowlisted miner.
216
+ * @param {() => Promise<void>} check runs before every purchase (the session must still be active)
217
+ * @param {{ opened: boolean }} [record] shared with the caller
218
+ * @returns {(kind: string) => Promise<void>}
219
+ */
220
+ export function onePurchasePerBatch(check, record = { opened: false }) {
221
+ return async (kind) => {
222
+ if (kind === 'open' && record.opened) throw new SecondPurchaseError();
223
+ await check();
224
+ if (kind === 'open') record.opened = true;
225
+ };
226
+ }