tryflop 0.0.1 → 0.2.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.
- package/README.md +66 -2
- package/bin/flop-mcp.mjs +22 -0
- package/bin/tryflop.mjs +36 -0
- package/e2e/sandbox-smoke.mjs +136 -0
- package/npm-shrinkwrap.json +2648 -0
- package/package.json +52 -5
- package/src/agent-settings.js +76 -0
- package/src/claim.js +516 -0
- package/src/cli.js +428 -0
- package/src/daily.js +363 -0
- package/src/files.js +104 -0
- package/src/flop-core.js +189 -0
- package/src/flop-node.js +346 -0
- package/src/format.js +180 -0
- package/src/gate.js +19 -0
- package/src/guard.js +231 -0
- package/src/home.js +96 -0
- package/src/install.js +110 -0
- package/src/keyfile.js +70 -0
- package/src/layout.js +55 -0
- package/src/miners.js +65 -0
- package/src/moments.js +50 -0
- package/src/outcome.js +128 -0
- package/src/outer.js +969 -0
- package/src/payer.js +834 -0
- package/src/questions.js +47 -0
- package/src/requests.js +178 -0
- package/src/roots.js +48 -0
- package/src/sandbox.js +223 -0
- package/src/scheduler.js +221 -0
- package/src/scoring.js +67 -0
- package/src/secrets.js +41 -0
- package/src/server.js +13 -0
- package/src/shared/config.js +393 -0
- package/src/shared/direct-core.js +226 -0
- package/src/shared/grants-core.js +69 -0
- package/src/shared/units.js +47 -0
- package/src/statusfile.js +70 -0
- package/src/tools.js +107 -0
- package/src/tryflop.js +622 -0
- package/src/wallet.js +123 -0
- package/bin/tryflop.js +0 -5
|
@@ -0,0 +1,393 @@
|
|
|
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.14.0 admits runtimes up to 1014042 (1014036 never existed) and refuses 1014043 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). Miners registered from 26 Nov 2026 (66 in Flop's explorer at 17:33 UTC); none
|
|
135
|
+
* publishes a web address on chain or in the explorer, so `miners` lists ones whose operator published
|
|
136
|
+
* one, each added after a paid run on testnet through this app passed;
|
|
137
|
+
* `gateway.testnet.flop.network` answers since 26 Nov (this app uses no gateway); there is still no
|
|
138
|
+
* session-offer indexer.
|
|
139
|
+
*/
|
|
140
|
+
testnet: Object.freeze({
|
|
141
|
+
name: 'testnet',
|
|
142
|
+
label: 'Testnet',
|
|
143
|
+
status: 'live',
|
|
144
|
+
/**
|
|
145
|
+
* Testnet runs runtime 1014042 (`flop-testnet`, read on the node 30 Nov 2026; 1014040 from 28 Nov at block
|
|
146
|
+
* 301,826, 1014039 on 26–27 Nov, 1014035 on 24–25 Nov), which the pinned SDK 0.14.0 admits. 0.13.1 stopped
|
|
147
|
+
* at 1014040, so from the 30 Nov switch (block 447,306, the one that turned vouchers on) it read nothing; 0.12.1 stopped at 1014039, so
|
|
148
|
+
* from the upgrade on 28 Nov until this bump the app connected, passed the genesis check and then read
|
|
149
|
+
* nothing here ("runs a newer chain version"), as 0.9.0 did from 24 to 26 Nov. `e2e/drive.mjs testnet`
|
|
150
|
+
* decides which of the two this flag must be from what the app actually reaches, so a stale flag fails
|
|
151
|
+
* that run.
|
|
152
|
+
*/
|
|
153
|
+
readable: true,
|
|
154
|
+
/** Published on Flop's operator page (as `wss://testnet.flop.network/`); same host, no path. */
|
|
155
|
+
rpc: 'wss://testnet.flop.network',
|
|
156
|
+
/** The same nodes over HTTPS JSON-RPC (server side only: Cloudflare's stats code), no path. */
|
|
157
|
+
rpcHttp: 'https://testnet.flop.network',
|
|
158
|
+
/**
|
|
159
|
+
* No (checked 27 Nov 2026): a pre-check from Origin https://tryflop.com answers 404, and a POST's answer carries no
|
|
160
|
+
* access-control-allow-origin, so a browser on another site cannot read it (checked again 27 Nov 2026 17:19 UTC: the
|
|
161
|
+
* same 404 for 127.0.0.1, localhost and tryflop.com). The home page shows no live block for testnet.
|
|
162
|
+
*/
|
|
163
|
+
rpcHttpFromPages: false,
|
|
164
|
+
/**
|
|
165
|
+
* Live since 25 Nov 2026 (GET <faucet>/chain: `{"network":"testnet","chain":"FLOP Testnet",genesis
|
|
166
|
+
* 0x918abd58…}`, /health `status:"ok"`, /limits `faucet.status:"open"`), named as testnet's own faucet on
|
|
167
|
+
* Flop's official links page (https://flop.finance/official/), and SDK 0.11.0 on carries the same host.
|
|
168
|
+
*
|
|
169
|
+
* It does not serve the anonymous lane: `POST /fund` answers 404, and SDK 0.11.0 on refuses this host for
|
|
170
|
+
* `fundFromFaucetDetailed` before sending anything ("Public Testnet funding is unavailable"). Its one
|
|
171
|
+
* grant is the AGENT lane, a claim the recipient's own key signs: `POST /v1/testnet/agent-claims`, which
|
|
172
|
+
* SDK 0.12.0 on sends as `claimTestnetAgentFunds` (it checks /chain against testnet's genesis first, then
|
|
173
|
+
* signs "flop-faucet-agent/v1|<genesis>|<address>|<nonce>"). Its /limits (26 Nov 2026 10:56 UTC):
|
|
174
|
+
* `agent.grantFlop` 10, `rolling24HourCapFlop` 10, `cooldownSeconds` 86400, `rolloverRequiresSpend`
|
|
175
|
+
* true; per client IP 3 grants a day. Its own page (the root, to a browser) says "Agent claim 10 FLOP per
|
|
176
|
+
* 24 hours" and "Verified human: Unavailable on Testnet", so this app offers no verified grant here.
|
|
177
|
+
*
|
|
178
|
+
* `browserClaim: false` since 26 Nov 2026 evening: the faucet answers the CORS preflight of
|
|
179
|
+
* `POST /v1/testnet/agent-claims` with 404 and no Access-Control-Allow-Origin (checked 19:34 and 20:12
|
|
180
|
+
* UTC), so every browser blocks the claim before it is sent. Until Flop fixes that, the app sends no claim
|
|
181
|
+
* here; its screen walks the user through Flop's own faucet page (a browser wallet extension claims there)
|
|
182
|
+
* and a transfer to this app's wallet. `node e2e/drive.mjs testnet` fails once a real browser gets through.
|
|
183
|
+
*/
|
|
184
|
+
faucet: 'https://faucet.flop.network',
|
|
185
|
+
quickGrant: Object.freeze({ flop: 10, signed: true, verified: false, browserClaim: false }),
|
|
186
|
+
gateway: '',
|
|
187
|
+
/** Flop's own explorer, linked from the announcement ("Follow the chain on FLOPScan"). */
|
|
188
|
+
explorer: 'https://testnet.flopscan.io',
|
|
189
|
+
indexer: '',
|
|
190
|
+
genesis: '0x918abd58fb16306b30ef3886514cfaebffecb4de43e82b6f8ec4795c43cfd800',
|
|
191
|
+
miners: Object.freeze([
|
|
192
|
+
// Operator-published (#1651, the same account and host in #1562). Paid through this app on 28 Nov 2026 and
|
|
193
|
+
// judged from the chain: channel 0xa9c2be7f…f669 settled cooperatively at block 336,243 (three answers,
|
|
194
|
+
// 0.3999 of a 0.4704 FLOP escrow to the miner); it settled small channels with other buyers that day too.
|
|
195
|
+
Object.freeze({
|
|
196
|
+
id: 'ariabrain-m1',
|
|
197
|
+
address: '5EZ1QVRE3gbSxupfYMreegFAgvmL4mhe5pCgHJaRUFvaZUTW',
|
|
198
|
+
endpoint: 'https://m1.flop.ariabrain.com',
|
|
199
|
+
model: 'qwen/qwen3-8b',
|
|
200
|
+
modelHash: '0x2dc476dabd39fb86d216e04f3c50313a22fa9e5bfa65f8e236557c30ddfaba55',
|
|
201
|
+
source: 'https://github.com/flop-labs/network/issues/1651',
|
|
202
|
+
checked: '2026-11-28',
|
|
203
|
+
}),
|
|
204
|
+
// Operator-published (#935, the comment that corrects the account; the host is named in it). Paid through this
|
|
205
|
+
// app on 28 Nov 2026 and judged from the chain: channel 0x63934132…2fa9 settled cooperatively at block 337,870
|
|
206
|
+
// (two answers, 0.8034 of a 0.9452 FLOP escrow to the miner).
|
|
207
|
+
Object.freeze({
|
|
208
|
+
id: 'ecamli-testnet',
|
|
209
|
+
address: '5Gjy2TuHGNkojLggYFMcXVrZvWq8hx9qt2bQKYfW9MomYWgn',
|
|
210
|
+
endpoint: 'https://testnet.ecamliflop.fyi',
|
|
211
|
+
model: 'qwen/qwen3-8b',
|
|
212
|
+
modelHash: '0x2dc476dabd39fb86d216e04f3c50313a22fa9e5bfa65f8e236557c30ddfaba55',
|
|
213
|
+
source: 'https://github.com/flop-labs/network/issues/935#issuecomment-7198236370',
|
|
214
|
+
checked: '2026-11-28',
|
|
215
|
+
}),
|
|
216
|
+
]),
|
|
217
|
+
}),
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The network a page address without `?network=` gets: testnet since 27 Nov 2026, now that Flop's public testnet
|
|
222
|
+
* is the network that counts; devnet before. Devnet stays one link away (`app?network=devnet`),
|
|
223
|
+
* and each network keeps its own saved wallet (src/storage.js storageKey), so changing this moves nobody's
|
|
224
|
+
* wallet: a devnet wallet made before the switch is still at `app?network=devnet`.
|
|
225
|
+
*/
|
|
226
|
+
export const DEFAULT_NETWORK = 'testnet';
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Every endpoint of every live network, once: the CSP connect-src of the server header and of
|
|
230
|
+
* public/app.html's own tag (test/csp.test.js keeps the two in step). It includes each network's HTTPS
|
|
231
|
+
* RPC: the header covers every static file, and the home page (public/index.html) reads the default
|
|
232
|
+
* network's latest block over HTTPS, so the header must allow it as well as the home page's own tag.
|
|
233
|
+
* @returns {string[]}
|
|
234
|
+
*/
|
|
235
|
+
export function connectSources() {
|
|
236
|
+
const live = Object.values(NETWORKS).filter((n) => n.status === 'live');
|
|
237
|
+
return [...new Set(live.flatMap((n) => [n.rpc, n.rpcHttp, n.faucet, n.gateway, n.explorer, n.indexer]).filter(Boolean))];
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The network named by `?network=` in the page address, if Flop has opened it; otherwise the default,
|
|
242
|
+
* with a notice that says why.
|
|
243
|
+
* @param {string} search e.g. location.search
|
|
244
|
+
* @param {Readonly<Record<string, NetworkConfig>>} [networks] the table to read; it must hold DEFAULT_NETWORK
|
|
245
|
+
* @returns {{ network: NetworkConfig, notice: string|null }}
|
|
246
|
+
*/
|
|
247
|
+
export function selectNetwork(search, networks = NETWORKS) {
|
|
248
|
+
const fallback = networks[DEFAULT_NETWORK];
|
|
249
|
+
const wanted = new URLSearchParams(search ?? '').get('network');
|
|
250
|
+
if (!wanted) return { network: fallback, notice: null };
|
|
251
|
+
const found = Object.hasOwn(networks, wanted) ? networks[wanted] : null;
|
|
252
|
+
// Never repeat the name: anyone can send a link, and the notice shows on every screen of this page
|
|
253
|
+
// (security audit, 24 Nov 2026: "?network=" could put fake instructions next to the recovery words).
|
|
254
|
+
if (!found) return { network: fallback, notice: `There is no network with that name, so this is ${fallback.name}.` };
|
|
255
|
+
if (found.status !== 'live') return { network: fallback, notice: `Flop has not opened ${found.name} yet, so this is ${fallback.name}.` };
|
|
256
|
+
return { network: found, notice: null };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Outside a browser there is no page address: Node (the unit tests, the browser drivers, the connector) and
|
|
260
|
+
// Cloudflare's functions get devnet, the network the money-path tests describe, whatever the default is.
|
|
261
|
+
const selected = globalThis.location ? selectNetwork(globalThis.location.search ?? '') : { network: NETWORKS.devnet, notice: null };
|
|
262
|
+
/** The network this page uses (devnet outside a browser). */
|
|
263
|
+
export const NETWORK = selected.network;
|
|
264
|
+
/** Why the page is not on the network its address asked for, or null. */
|
|
265
|
+
export const NETWORK_NOTICE = selected.notice;
|
|
266
|
+
|
|
267
|
+
export const APP = Object.freeze({
|
|
268
|
+
/** Kept back from the session cap: pays the owner's own transaction fees (session, fee money, revoke). */
|
|
269
|
+
feeReservePlanck: 1n * PLANCK_PER_FLOP,
|
|
270
|
+
/**
|
|
271
|
+
* A faucet grant counts as arrived when the balance rose by this much, and "Use my FLOP" is offered
|
|
272
|
+
* from it. (Setting up needs more: 1 FLOP kept + 0.5 FLOP fee money + a limit of at least 2 FLOP.)
|
|
273
|
+
*/
|
|
274
|
+
minUsablePlanck: 1n * PLANCK_PER_FLOP,
|
|
275
|
+
/** Default session limit offered on screen (security review 13 Nov: not the whole balance). */
|
|
276
|
+
defaultCapPlanck: 10n * PLANCK_PER_FLOP,
|
|
277
|
+
/** Per-transaction ceiling for session spends (SDK CALIBRATED_LIMITS uses 5 FLOP). */
|
|
278
|
+
perTxLimitPlanck: 5n * PLANCK_PER_FLOP,
|
|
279
|
+
sessionDays: 7,
|
|
280
|
+
/** Session calls may only touch compute channels (runtime pallet name, checked on devnet 13 Nov). */
|
|
281
|
+
allowedPallets: Object.freeze(['ComputeChannel']),
|
|
282
|
+
/** MINER_UNAVAILABLE waits: 1, 2, 5, 5, 5 minutes, then PAUSED (SPEC diagram). */
|
|
283
|
+
backoffSeconds: Object.freeze([60, 120, 300, 300, 300]),
|
|
284
|
+
/**
|
|
285
|
+
* A tap opens at most this many batches (each buys at most one channel), counting every follow-up batch
|
|
286
|
+
* and every retry after a wait: the per-tap bound on spend (review of a28c8d9, 24 Nov).
|
|
287
|
+
*/
|
|
288
|
+
maxBatchesPerTap: 6,
|
|
289
|
+
/** While PAUSED, how often the health check runs again. */
|
|
290
|
+
healthRetryMs: 30_000,
|
|
291
|
+
/** How long one WAIT_FOR_BALANCE check waits for a faucet grant to show up. */
|
|
292
|
+
balanceWaitMs: 90_000,
|
|
293
|
+
/** Browser connect: measured 8.6–9.5 s on 13 Nov (951 KB of metadata); the SDK's own limit is 10 s. */
|
|
294
|
+
connectTimeoutMs: 60_000,
|
|
295
|
+
/** Faucet /chain took 2–3.5 s on 13 Nov; the SDK default is 5 s. */
|
|
296
|
+
faucetTimeoutMs: 30_000,
|
|
297
|
+
/**
|
|
298
|
+
* The devnet faucet's /limits on 13 Nov (its own host since 25 Nov): anonymous
|
|
299
|
+
* addressCooldownSeconds = 86400. Testnet's agent lane: cooldownSeconds 86400 per wallet (its /limits,
|
|
300
|
+
* 26 Nov 2026), plus 3 grants a day per client IP.
|
|
301
|
+
*/
|
|
302
|
+
quickGrantCooldownMs: 24 * 3600 * 1000,
|
|
303
|
+
/** Verified grants: identityCooldownSeconds = 86400, at most 2,000 FLOP per rolling 7 days. */
|
|
304
|
+
verifiedGrantCooldownMs: 24 * 3600 * 1000,
|
|
305
|
+
/** Answer length per task, in tokens (measured 23 Nov: G_n 438–481 per answer at 400). */
|
|
306
|
+
maxTokens: 400,
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Paying a miner directly (SDK computeChannel.LongSession through the capped session key).
|
|
311
|
+
* Measured by the devnet probe on 23 Nov 2026 (channel 0x14ed7879…c2b0 on miner ecamli: opened at block
|
|
312
|
+
* 4,470,018 through flopSessionKeys.executeViaSession, two turns, settled cooperatively at 4,470,434,
|
|
313
|
+
* minerPaid 0.757 FLOP; e2e/verify-channel.mjs passed on finalized state).
|
|
314
|
+
*/
|
|
315
|
+
export const DIRECT = Object.freeze({
|
|
316
|
+
/** 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). */
|
|
317
|
+
windowSeconds: 900,
|
|
318
|
+
/** Longest one channel may lock the user's FLOP. */
|
|
319
|
+
maxLockSeconds: 1800,
|
|
320
|
+
/**
|
|
321
|
+
* The miner settles ~380 blocks after the batch closes (probe: close at ~4,470,054, settle at 4,470,434;
|
|
322
|
+
* flop-labs/network#229 saw 260–450 after open). A batch stops starting new turns early enough for that.
|
|
323
|
+
*/
|
|
324
|
+
settleAllowanceSeconds: 450,
|
|
325
|
+
/** One channel's escrow ceiling, top-ups included (below the session's 5 FLOP per-payment limit). */
|
|
326
|
+
maxChannelPlanck: 2n * PLANCK_PER_FLOP,
|
|
327
|
+
topUpPlanck: PLANCK_PER_FLOP / 2n,
|
|
328
|
+
/**
|
|
329
|
+
* SLA turn limit of a bare open (the outside app's settled bare open on 23 Nov used 64). The machine stops
|
|
330
|
+
* a batch after this many answers. An offer may set a lower limit; reaching it ends the batch into the
|
|
331
|
+
* counted miner waits, never an extra purchase (onePurchasePerBatch).
|
|
332
|
+
*/
|
|
333
|
+
maxTurns: 64,
|
|
334
|
+
/** Longest one answer may take before the turn counts as lost (probe: 38 s with the channel purchase, then 12 s). */
|
|
335
|
+
turnTimeoutSeconds: 120,
|
|
336
|
+
/**
|
|
337
|
+
* Worst-case G_n of one turn. Probe: 438–439 G_n per turn at max_tokens 400 (short prompts); kept at
|
|
338
|
+
* 20,000 so a 12,000-character summary fits too. The channel's settleable allowance is ~10^7 G_n, so
|
|
339
|
+
* the overestimate costs nothing.
|
|
340
|
+
*/
|
|
341
|
+
worstTurnGn: 20_000n,
|
|
342
|
+
/** Fee money sent to the session key: ~45 wrapped payments at the measured 0.0109 FLOP each (ED 0.01 FLOP). */
|
|
343
|
+
feeFloatPlanck: PLANCK_PER_FLOP / 2n,
|
|
344
|
+
/** Below this the session key asks for a top-up: ED + 3 measured fees ≈ 0.043 FLOP. */
|
|
345
|
+
feeMinPlanck: PLANCK_PER_FLOP / 20n,
|
|
346
|
+
/** A retired session key holding less than this keeps it: the transfer's own fee would eat it. */
|
|
347
|
+
sweepMinPlanck: PLANCK_PER_FLOP / 50n,
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
/** How long a batch may keep starting turns: the rest of the window is the miner's to settle in. */
|
|
351
|
+
export const MAX_BATCH_SECONDS = DIRECT.windowSeconds - DIRECT.settleAllowanceSeconds - DIRECT.turnTimeoutSeconds;
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Giving an outside AI agent (first of all the Claude connector, apps/flop-mcp/) its own capped limit.
|
|
355
|
+
* What the form offers by default lives in `AGENT_DEFAULTS` (`src/agents-core.js`): the connector's own
|
|
356
|
+
* reference grant of 24 Nov.
|
|
357
|
+
*/
|
|
358
|
+
export const AGENT = Object.freeze({
|
|
359
|
+
/**
|
|
360
|
+
* The chain's own ceilings, read from devnet's metadata on 24 Nov. This app's own limit counts
|
|
361
|
+
* towards `maxSessionsPerOwner`. `maxSessionDays` is the fallback for when the live read fails:
|
|
362
|
+
* without it the form would accept a length the chain then silently shortens, so the confirm
|
|
363
|
+
* screen could promise more days than the limit gets. The live read always wins.
|
|
364
|
+
*/
|
|
365
|
+
maxSessionsPerOwner: 10,
|
|
366
|
+
maxSessionDays: 10,
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* How a turn is sent for each model a listed miner serves.
|
|
371
|
+
* - `chatTemplate`: false sends a flop.chat-turn.v1 turn, which the miner hands to the model as plain text
|
|
372
|
+
* (the messages' text, one per line, with no chat template). true sends flop.chat-turn.v2: the miner renders
|
|
373
|
+
* the messages with the model's own chat template, with Qwen3's thinking switched off, and refuses an answer
|
|
374
|
+
* that still holds a thinking block. Qwen3 given plain text keeps writing on from the question, then
|
|
375
|
+
* reasons aloud until the token limit; through its template it answers.
|
|
376
|
+
* - `worstTurnGn`: the most G_n one turn can meter (G_n = 2 × active parameters × tokens + the attention
|
|
377
|
+
* term, divided by 10^9). Qwen2.5-0.5B: ~1 G_n per token, measured 438–481 per short answer at 400 tokens.
|
|
378
|
+
* Qwen3-14B: ~29.5 G_n per token, measured 12,925 for a 35-token prompt and 400 tokens; its worst case is a
|
|
379
|
+
* prompt filling its whole 40,960-token context, 1,896,996 G_n, which at the devnet price of 2·10^10
|
|
380
|
+
* atoms per G_n is 0.038 FLOP.
|
|
381
|
+
* @typedef {{ chatTemplate: boolean, worstTurnGn: bigint }} ModelProfile
|
|
382
|
+
* @type {Readonly<Record<string, ModelProfile>>}
|
|
383
|
+
*/
|
|
384
|
+
export const MODELS = Object.freeze({
|
|
385
|
+
'qwen/qwen2.5-0.5b-instruct': Object.freeze({ chatTemplate: false, worstTurnGn: DIRECT.worstTurnGn }),
|
|
386
|
+
'qwen/qwen3-14b': Object.freeze({ chatTemplate: true, worstTurnGn: 1_900_000n }),
|
|
387
|
+
// Qwen3-8B (served on testnet): 36 layers, hidden 4096, 32 heads of 128, 8 KV heads, gated MLP 12288 (its
|
|
388
|
+
// config.json); a prompt filling its 40,960-token context meters 1,165,752 G_n by the SDK's own meter.
|
|
389
|
+
'qwen/qwen3-8b': Object.freeze({ chatTemplate: true, worstTurnGn: 1_200_000n }),
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
/** @param {string} model a miner's model name @returns {ModelProfile} */
|
|
393
|
+
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
|
+
}
|