tryflop 0.0.1 → 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.
package/package.json CHANGED
@@ -1,10 +1,57 @@
1
1
  {
2
2
  "name": "tryflop",
3
- "version": "0.0.1",
4
- "description": "Try Flop's agent tool: let your AI agent use Flop's testnet AI from its own wallet. Not released yet — see https://tryflop.com. Independent app, not made by Flop Labs.",
3
+ "version": "0.1.0",
4
+ "description": "Try Flop for AI agents: your agent's own Flop wallet claims Flop's free test FLOP and pays real miners for AI answers, every day. An independent tool, not made by Flop Labs.",
5
5
  "license": "MIT",
6
+ "type": "module",
6
7
  "homepage": "https://tryflop.com",
7
- "bin": { "tryflop": "bin/tryflop.js" },
8
- "files": ["bin/", "README.md"],
9
- "engines": { "node": ">=18" }
8
+ "keywords": [
9
+ "flop",
10
+ "ai-agent",
11
+ "mcp",
12
+ "claude-code",
13
+ "testnet"
14
+ ],
15
+ "bin": {
16
+ "tryflop": "bin/tryflop.mjs",
17
+ "flop-mcp": "bin/flop-mcp.mjs"
18
+ },
19
+ "files": [
20
+ "bin/",
21
+ "src/",
22
+ "e2e/sandbox-smoke.mjs",
23
+ "README.md",
24
+ "npm-shrinkwrap.json"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22.15"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test test/*.test.js",
31
+ "typecheck": "tsc --noEmit -p tsconfig.json",
32
+ "verify": "npm run typecheck && npm test"
33
+ },
34
+ "dependencies": {
35
+ "@flop-labs/sdk": "0.13.1",
36
+ "@modelcontextprotocol/server": "2.4.0",
37
+ "@polkadot/api": "17.0.2",
38
+ "@polkadot/keyring": "14.0.3",
39
+ "@polkadot/util": "14.0.3",
40
+ "@polkadot/util-crypto": "14.0.3",
41
+ "zod": "4.6.7"
42
+ },
43
+ "devDependencies": {
44
+ "@modelcontextprotocol/client": "2.4.0",
45
+ "@types/node": "22.20.5",
46
+ "typescript": "7.0.2"
47
+ },
48
+ "overrides": {
49
+ "@solana/rpc-transport-http": {
50
+ "undici-types": "8.12.4"
51
+ },
52
+ "@modelcontextprotocol/client": {
53
+ "jose": "6.2.17",
54
+ "pkce-challenge": "5.0.1"
55
+ }
56
+ }
10
57
  }
@@ -0,0 +1,76 @@
1
+ // tryflop's settings (<wallet folder>/settings.json, 0600): the daily brief's topic, the daily run's time, whether the
2
+ // scheduler is installed, and when the human last looked at the backup. Written by setup (outside the sandbox) and read
3
+ // by every command. Node built-ins only.
4
+ import { readFileSync } from 'node:fs';
5
+ import { ensurePrivateDir, writePrivateFile } from './files.js';
6
+ import { cleanTopic, DEFAULT_TOPIC } from './questions.js';
7
+
8
+ /**
9
+ * @typedef {{ version: 1, topic: string, hour: number, minute: number, daily: 'on'|'off', scheduler?: string,
10
+ * backupShownAt?: number, createdAt: string }} AgentSettings
11
+ * daily: 'on' once setup installed the scheduler (the human said yes); scheduler: which one (launchd, schtasks,
12
+ * systemd, cron)
13
+ */
14
+
15
+ /** @param {unknown} n @param {number} max */
16
+ const intIn = (n, max) => Number.isInteger(n) && /** @type {number} */ (n) >= 0 && /** @type {number} */ (n) <= max;
17
+
18
+ /**
19
+ * The settings, or null when there are none yet. A damaged file reads as null too: setup writes a fresh one, and a
20
+ * daily run without settings uses the defaults (nothing about money lives here).
21
+ * @param {string} file @returns {AgentSettings | null}
22
+ */
23
+ export function readAgentSettings(file) {
24
+ let json;
25
+ try {
26
+ json = JSON.parse(readFileSync(file, 'utf8'));
27
+ } catch {
28
+ return null;
29
+ }
30
+ return settingsFrom(json);
31
+ }
32
+
33
+ /** Settings from parsed JSON, every field checked; null when they are not settings. @param {any} json @returns {AgentSettings | null} */
34
+ export function settingsFrom(json) {
35
+ if (!json || typeof json !== 'object' || json.version !== 1 || !intIn(json.hour, 23) || !intIn(json.minute, 59)) return null;
36
+ return {
37
+ version: 1, topic: cleanTopic(json.topic), hour: json.hour, minute: json.minute, daily: json.daily === 'on' ? 'on' : 'off',
38
+ ...(typeof json.scheduler === 'string' ? { scheduler: json.scheduler.slice(0, 20) } : {}),
39
+ ...(Number.isSafeInteger(json.backupShownAt) ? { backupShownAt: json.backupShownAt } : {}),
40
+ createdAt: typeof json.createdAt === 'string' ? json.createdAt.slice(0, 40) : new Date(0).toISOString(),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Written only by the SANDBOXED process (setup's outer side hands them over: `settings-set`). The data folder is
46
+ * writable from inside the sandbox, so an unsandboxed write there could be sent elsewhere by a folder swapped for a
47
+ * link between any check and the write (security reviews, 27 Nov); inside the sandbox a link can only lead inside it.
48
+ * @param {string} dir @param {string} file @param {AgentSettings} settings
49
+ */
50
+ export function writeAgentSettings(dir, file, settings) {
51
+ ensurePrivateDir(dir);
52
+ writePrivateFile(file, `${JSON.stringify(settings, null, 2)}\n`);
53
+ }
54
+
55
+ /**
56
+ * New settings: the topic given (or the default) and a random minute of the day for the daily run, so that every
57
+ * Try Flop on the network does not ask Flop's faucet and miners at the same moment.
58
+ * @param {{ topic?: string, random?: () => number, now?: () => number }} [o] @returns {AgentSettings}
59
+ */
60
+ export function newAgentSettings({ topic = DEFAULT_TOPIC, random = Math.random, now = Date.now } = {}) {
61
+ const minuteOfDay = Math.floor(random() * 24 * 60) % (24 * 60);
62
+ return { version: 1, topic: cleanTopic(topic), hour: Math.floor(minuteOfDay / 60), minute: minuteOfDay % 60, daily: 'off', createdAt: new Date(now()).toISOString() };
63
+ }
64
+
65
+ /**
66
+ * Whether Flop's testnet faucet page says its verified-human grant is open. Read 27 Nov 2026: "Verified human
67
+ * Unavailable on Testnet". True only when the page names the verified-human grant and no longer says it is
68
+ * unavailable; a page that does not mention it at all (moved, down, another layout) is NOT taken as open.
69
+ * @param {string} html @returns {boolean}
70
+ */
71
+ export function verifiedGrantOpen(html) {
72
+ const text = String(html ?? '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ');
73
+ const at = text.search(/verified human/i);
74
+ if (at < 0) return false;
75
+ return !/unavailable|not available|coming soon|disabled/i.test(text.slice(at, at + 60));
76
+ }
package/src/claim.js ADDED
@@ -0,0 +1,516 @@
1
+ // `flop-mcp claim` (SPEC.md, the claim diagram). On a network whose faucet grants a claim signed by the receiving
2
+ // key (testnet's agent lane), the connector's own key claims FLOP for itself, keeps 0.5 FLOP for its network fees and
3
+ // passes the rest to the owner's wallet: a brand-new owner wallet holds nothing, not even the fee to grant a limit.
4
+ // SDK-free: cli.js wires src/flop-node.js in as `chain` and `faucet`, so tests drive every edge with stand-ins.
5
+ // Rules: never a second claim inside the faucet's 24 h, never re-send anything, judge a grant and a transfer from the
6
+ // chain only, and record each request in claim.json (flushed) BEFORE it is sent.
7
+ import { readFileSync } from 'node:fs';
8
+ import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
9
+ import { APP, DIRECT } from './shared/config.js';
10
+ import { formatFlop } from './shared/units.js';
11
+ import { SS58_PREFIX, writePrivateFile } from './home.js';
12
+
13
+ export const CLAIM = Object.freeze({
14
+ /** The faucet's window: one grant per key (and, seen on 26 Nov 2026, per internet address) per rolling 24 h. */
15
+ windowMs: APP.quickGrantCooldownMs,
16
+ /** How long one run waits for an unclear claim to show on chain (a queued testnet grant took ~13 min, 26 Nov). */
17
+ grantWaitMs: 20 * 60_000,
18
+ /** How long one run waits for a transfer's era to pass at finality before reading its blocks. */
19
+ eraWaitMs: 5 * 60_000,
20
+ pollMs: 10_000,
21
+ /** A grant counts as arrived when the key's balance rose by this much (the agent app's rule). */
22
+ arrivedPlanck: APP.minUsablePlanck,
23
+ /** Kept on the key for its own network fees: what the owner sends it on devnet. */
24
+ keepPlanck: DIRECT.feeFloatPlanck,
25
+ /** A smaller transfer is not worth its own fee (the agent app's sweep floor). */
26
+ minForwardPlanck: DIRECT.sweepMinPlanck,
27
+ });
28
+
29
+ const CLAIM_STATUSES = new Set(['sending', 'unavailable', 'refused', 'unknown', 'granted']);
30
+ const FORWARD_STATUSES = new Set(['prepared', 'unknown', 'landed', 'failed', 'not_landed']);
31
+ /** A transfer whose outcome is still open: nothing new is signed until the chain has settled it. */
32
+ const OPEN_FORWARD = new Set(['prepared', 'unknown']);
33
+ const DIGITS = /^[0-9]+$/;
34
+ /** A time this program could have written (a millisecond clock reading): anything else could not be shown as a date. */
35
+ const TIME = (/** @type {unknown} */ ms) => Number.isSafeInteger(ms) && /** @type {number} */ (ms) >= Date.UTC(2024, 0, 1) && /** @type {number} */ (ms) <= Date.UTC(2100, 0, 1);
36
+ /**
37
+ * Flop's faucet answers 503 `faucet_busy` when its queue is too long: "The faucet has more grants queued than it can
38
+ * send within this request's wait; nothing was reserved. Retry later" (27 Nov 2026 18:31 UTC, 3,000 grants queued). Not
39
+ * an unknown outcome: the faucet says no grant exists (unlike 503 `grant_pending` on 26 Nov, "Grant queued while
40
+ * signing is held", which DID land 13 minutes later), and its per-wallet 24 h cap would refuse a second grant anyway.
41
+ * Recorded as refused, tried again after this long; holding it for 24 h as "unknown" held every busy day's claim.
42
+ */
43
+ export const BUSY_RETRY_MS = 30 * 60_000;
44
+ /** The faucet's own words that nothing was reserved for a claim. */
45
+ const NOTHING_RESERVED = new Set(['faucet_busy']);
46
+
47
+ /** Longest wait a faucet's Retry-After may set: the SDK takes any string of digits, and a lie would hold claims for ever. */
48
+ const MAX_RETRY_SECONDS = 7 * 86_400;
49
+
50
+ /**
51
+ * @typedef {{ status: 'sending'|'unavailable'|'refused'|'unknown'|'granted', at: number, nonce: string, beforePlanck: string,
52
+ * httpStatus?: number, reason?: string, message?: string, retryAt?: number, grantedPlanck?: string, grantedAt?: number }} ClaimEntry
53
+ * @typedef {{ status: 'prepared'|'unknown'|'landed'|'failed'|'not_landed', at: number, to: string, amountPlanck: string,
54
+ * txHash: string, eraBirth: string, eraPeriod: string, block?: string, message?: string }} ForwardEntry
55
+ * @typedef {{ version: 1, claim?: ClaimEntry, forward?: ForwardEntry }} ClaimRecord
56
+ */
57
+
58
+ export class ClaimRecordError extends Error {
59
+ /** @param {string} message */
60
+ constructor(message) {
61
+ super(message);
62
+ this.name = 'ClaimRecordError';
63
+ this.code = 'CLAIM_RECORD';
64
+ }
65
+ }
66
+
67
+ /** A reason code the faucet sent (ip_cooldown); free text never passes as one. */
68
+ const REASON_CODE = /^[a-z0-9_.-]{1,48}$/i;
69
+
70
+ /** @param {any} claim */
71
+ function claimWellFormed(claim) {
72
+ return claim && typeof claim === 'object' && CLAIM_STATUSES.has(claim.status) && TIME(claim.at)
73
+ && typeof claim.nonce === 'string' && DIGITS.test(claim.beforePlanck ?? '')
74
+ && (claim.retryAt === undefined || TIME(claim.retryAt)) && (claim.grantedAt === undefined || TIME(claim.grantedAt))
75
+ && (claim.grantedPlanck === undefined || DIGITS.test(claim.grantedPlanck))
76
+ // status shows these to Claude: the reason as a code only, the HTTP status as a status number (claim.js records nothing
77
+ // else there; an edited file must not put free text in front of Claude)
78
+ && (claim.reason === undefined || (typeof claim.reason === 'string' && REASON_CODE.test(claim.reason)))
79
+ && (claim.httpStatus === undefined || HTTP_STATUS(claim.httpStatus));
80
+ }
81
+
82
+ /** An HTTP status as a server can send one. @param {unknown} status */
83
+ const HTTP_STATUS = (status) => Number.isInteger(status) && /** @type {number} */ (status) >= 100 && /** @type {number} */ (status) <= 599;
84
+
85
+ /** A Flop address in the one form the connector writes (the owner as init saved it). @param {unknown} address */
86
+ function ss58(address) {
87
+ try {
88
+ return typeof address === 'string' && encodeAddress(decodeAddress(address), SS58_PREFIX) === address;
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+
94
+ /** @param {any} forward */
95
+ function forwardWellFormed(forward) {
96
+ return forward && typeof forward === 'object' && FORWARD_STATUSES.has(forward.status) && TIME(forward.at)
97
+ && ss58(forward.to) && /^0x[0-9a-f]{64}$/.test(forward.txHash ?? '')
98
+ && [forward.amountPlanck, forward.eraBirth, forward.eraPeriod].every((v) => DIGITS.test(v ?? ''))
99
+ && (forward.block === undefined || DIGITS.test(forward.block));
100
+ }
101
+
102
+ /**
103
+ * claim.json: the last claim and the last transfer to the owner. A missing file is a record with neither; a damaged
104
+ * one stops the run (fail closed): reading it as "never claimed" could send a second claim, or a second transfer
105
+ * while one is still open.
106
+ * @param {string} file @returns {ClaimRecord}
107
+ */
108
+ export function readClaimRecord(file) {
109
+ let text;
110
+ try {
111
+ text = readFileSync(file, 'utf8');
112
+ } catch (error) {
113
+ if (/** @type {any} */ (error).code === 'ENOENT') return { version: 1 };
114
+ throw error;
115
+ }
116
+ let record;
117
+ try {
118
+ record = JSON.parse(text);
119
+ } catch {
120
+ record = undefined;
121
+ }
122
+ if (!record || typeof record !== 'object' || record.version !== 1
123
+ || (record.claim !== undefined && !claimWellFormed(record.claim))
124
+ || (record.forward !== undefined && !forwardWellFormed(record.forward))) {
125
+ throw new ClaimRecordError(`${file} is damaged. It records this key's last faucet claim and transfer; check them on Flop's explorer, then delete the file to start over.`);
126
+ }
127
+ return record;
128
+ }
129
+
130
+ /** @param {string} file @param {ClaimRecord} record */
131
+ const writeClaimRecord = (file, record) => writePrivateFile(file, `${JSON.stringify(record, null, 2)}\n`);
132
+
133
+ /** A time as people read it here: "2026-11-27 19:31 UTC". @param {number} ms */
134
+ /**
135
+ * A claim record as the decision reads it: one recorded "unknown" although the faucet said nothing was reserved
136
+ * (written before BUSY_RETRY_MS existed) is the refusal it was, retried 30 minutes later. Everything that works out when
137
+ * the faucet can be asked next uses this same reading (proof run, 28 Nov 03:45 UTC: the daily run saved +24 h from the
138
+ * raw record while the decision had already asked the faucet again).
139
+ * @template {{ status: string, at: number, reason?: string } | undefined} T @param {T} claim @returns {T}
140
+ */
141
+ export function decidedClaim(claim) {
142
+ return claim && claim.status === 'unknown' && NOTHING_RESERVED.has(claim.reason ?? '')
143
+ ? /** @type {T} */ ({ ...claim, status: 'refused', retryAt: claim.at + BUSY_RETRY_MS })
144
+ : claim;
145
+ }
146
+
147
+ /**
148
+ * When the faucet may be asked next for this claim record (read the way the decision reads it, decidedClaim): a refusal's
149
+ * retry time; at once for a claim that never reached the faucet; otherwise 24 h after the claim (a grant, or a claim
150
+ * still unknown: it is never re-sent). Undefined with no record.
151
+ * @param {{ status: string, at: number, retryAt?: number, reason?: string } | undefined} claim @returns {number | undefined}
152
+ */
153
+ export function nextClaimAt(claim) {
154
+ const c = decidedClaim(claim);
155
+ if (!c) return undefined;
156
+ if (c.status === 'refused') return /** @type {any} */ (c).retryAt;
157
+ if (c.status === 'unavailable') return c.at;
158
+ return c.at + CLAIM.windowMs;
159
+ }
160
+
161
+ export const utc = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
162
+
163
+ /** Text from outside (the faucet, an RPC node) for a terminal: printable characters only, one line, short. @param {unknown} text */
164
+ const clean = (text) => String(text ?? '').replace(/[^\x20-\x7E]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200);
165
+
166
+ /** @param {unknown} error */
167
+ const brief = (error) => clean(/** @type {any} */ (error)?.message ?? error);
168
+
169
+ /** A reason code the faucet sent, or nothing. @param {unknown} reason */
170
+ const reasonCode = (reason) => (typeof reason === 'string' && REASON_CODE.test(reason) ? reason : undefined);
171
+
172
+ /**
173
+ * @typedef {{
174
+ * freeBalance(address: string): Promise<bigint>,
175
+ * finalizedNumber(): Promise<bigint>,
176
+ * findExtrinsic(txHash: string, fromBlock: bigint, toBlock: bigint): Promise<null | { block: bigint, success: boolean }>,
177
+ * transferFee(to: string, amountPlanck: bigint): Promise<bigint>,
178
+ * prepareTransfer(to: string, amountPlanck: bigint): Promise<{ txHash: string, eraBirth: bigint, eraPeriod: bigint,
179
+ * send(): Promise<{ outcome: 'ok'|'failed'|'unknown', txHash?: string, message?: string }> }>,
180
+ * lock(): Promise<() => Promise<void>>,
181
+ * }} ClaimChain freeBalance: at the finalized head (Flop: a grant is spendable once it is in a finalized block);
182
+ * lock: the payer lock (throws code JOURNAL_LOCKED when a Claude session holds it), returning its release
183
+ * @typedef {{ ready(): Promise<{ open: boolean, status: string }>,
184
+ * claim(nonce: string): Promise<{ status: 'refused'|'unavailable'|'unknown', httpStatus?: number, reason?: string,
185
+ * retryAfterSeconds?: number, txHash?: string, error?: string }> }} ClaimFaucet
186
+ * ready: the faucet's /limits (open, and serving the agent claim); claim: what grants-core.js signedClaimOutcome returns
187
+ */
188
+
189
+ /**
190
+ * Settle a transfer whose outcome is open: once the finalized head is past its era, read every block of the era for
191
+ * its hash (SPEC.md SETTLE_LAST_FORWARD). "open" when the era has not passed within the wait or the chain cannot be read.
192
+ * @param {ForwardEntry} forward @param {{ chain: ClaimChain, clock: { now(): number, sleep(ms: number): Promise<unknown> } }} deps
193
+ * @returns {Promise<{ status: 'landed'|'failed'|'not_landed'|'open', block?: string, message?: string }>}
194
+ */
195
+ async function settleForward(forward, { chain, clock }) {
196
+ const birth = BigInt(forward.eraBirth);
197
+ const eraEnd = birth + BigInt(forward.eraPeriod);
198
+ const deadline = clock.now() + CLAIM.eraWaitMs;
199
+ for (;;) {
200
+ let finalized;
201
+ try {
202
+ finalized = await chain.finalizedNumber();
203
+ } catch {
204
+ finalized = undefined; // a failed read never decides; the wait goes on
205
+ }
206
+ if (finalized !== undefined && finalized > eraEnd) break;
207
+ if (clock.now() >= deadline) return { status: 'open' };
208
+ await clock.sleep(CLAIM.pollMs);
209
+ }
210
+ let found;
211
+ try {
212
+ found = await chain.findExtrinsic(forward.txHash, birth, eraEnd);
213
+ } catch (error) {
214
+ return { status: 'open', message: brief(error) };
215
+ }
216
+ if (!found) return { status: 'not_landed' };
217
+ return { status: found.success ? 'landed' : 'failed', block: String(found.block) };
218
+ }
219
+
220
+ /**
221
+ * @typedef {'granted_now'|'granted_earlier'|'held'|'not_arrived'|'refused'|'refused_earlier'|'not_sent'|'unreadable'|'damaged'} ClaimOutcome
222
+ * what this run's claim step came to: granted_now (seen arriving now), granted_earlier (a grant under 24 h old),
223
+ * held (an unclear claim under 24 h old: only the balance is read, the claim is never re-sent), not_arrived (an
224
+ * unclear claim still not on chain after the wait), refused (the faucet refused it now), refused_earlier (its retry
225
+ * time is still ahead), not_sent (the faucet's /limits did not say open, or the SDK refused before posting),
226
+ * unreadable (the chain could not be read before claiming), damaged (claim.json could not be read)
227
+ */
228
+
229
+ /**
230
+ * Run `flop-mcp claim` once (SPEC.md, the claim diagram), or tryflop's claim for its own wallet (`own`: SPEC.md
231
+ * "tryflop daily"): the same CLAIM_DECISION, CLAIMING and WAIT_FOR_GRANT, and no transfer at all, since the wallet that
232
+ * claims is the wallet that pays (never move FLOP between wallets).
233
+ * @param {{ network: { name: string, faucet: string, quickGrant: { flop: number, signed: boolean } }, keyAddress: string,
234
+ * owner: string, recordFile: string, chain: ClaimChain, faucet: ClaimFaucet, yes: boolean,
235
+ * clock: { now(): number, sleep(ms: number): Promise<unknown> }, confirm: (question: string) => Promise<boolean>,
236
+ * say: (line: string) => void, own?: boolean, onResult?: (result: { outcome: ClaimOutcome, claim?: ClaimEntry }) => void }} deps
237
+ * own: keyAddress is tryflop's wallet (owner is the same address); onResult: told what the claim step came to
238
+ * @returns {Promise<number>} exit code: 0 when the key holds a grant and its FLOP reached the wallet, nothing was left to
239
+ * send, or the user chose to keep it on the key for now (own: when the wallet holds a grant under 24 h old); 1 otherwise
240
+ */
241
+ export async function runClaimFlow({ network, keyAddress, owner, recordFile, chain, faucet, yes, clock, confirm, say, own = false, onResult = () => {} }) {
242
+ if (own && owner !== keyAddress) throw new Error('tryflop claims for its own wallet: the owner must be the wallet');
243
+ const it = own ? 'this wallet' : 'this key';
244
+ const It = own ? 'This wallet' : 'This key';
245
+ /** @type {ClaimRecord} */
246
+ let record;
247
+ try {
248
+ record = readClaimRecord(recordFile);
249
+ } catch (error) {
250
+ say(brief(error));
251
+ onResult({ outcome: 'damaged' });
252
+ return 1;
253
+ }
254
+ const save = () => writeClaimRecord(recordFile, record);
255
+ const describe = (/** @type {ForwardEntry} */ f) => ({
256
+ landed: `It landed in block ${f.block}: ${formatFlop(BigInt(f.amountPlanck))} FLOP reached your wallet ${f.to}.`,
257
+ failed: `It failed on Flop's chain${f.block ? ` (block ${f.block})` : ''}, so nothing moved. Run claim again to send a new one.`,
258
+ not_landed: 'It never reached Flop\'s chain (its window has passed), so nothing moved. Run claim again to send a new one.',
259
+ })[/** @type {'landed'|'failed'|'not_landed'} */ (f.status)];
260
+
261
+ // SETTLE_LAST_FORWARD: a transfer an earlier run left open is settled before anything new is signed. (Never on the
262
+ // wallet route: it never sends one.)
263
+ if (!own && record.forward && OPEN_FORWARD.has(record.forward.status)) {
264
+ say(`Checking the transfer to your wallet that an earlier run sent (transaction ${record.forward.txHash})…`);
265
+ const settled = await settleForward(record.forward, { chain, clock });
266
+ if (settled.status === 'open') {
267
+ say('It is still being confirmed on Flop\'s chain. Nothing new was sent; run claim again in a few minutes to finish.');
268
+ return 1;
269
+ }
270
+ record.forward = { ...record.forward, status: settled.status, ...(settled.block ? { block: settled.block } : {}) };
271
+ save();
272
+ say(describe(record.forward));
273
+ }
274
+
275
+ // CLAIM_DECISION, then CLAIMING.
276
+ const last = decidedClaim(record.claim);
277
+ const now = clock.now();
278
+ const recent = last !== undefined && now - last.at < CLAIM.windowMs;
279
+ let claimOk = false;
280
+ let wait = false;
281
+ /** @type {ClaimOutcome} */
282
+ let outcome;
283
+ if (recent && last.status === 'granted') {
284
+ claimOk = true;
285
+ outcome = 'granted_earlier';
286
+ say(`${It} already got its ${network.name} FLOP at ${utc(last.grantedAt ?? last.at)}; Flop's faucet gives one claim a day, so the next is possible from ${utc(last.at + CLAIM.windowMs)}.`);
287
+ } else if (recent && (last.status === 'unknown' || last.status === 'sending')) {
288
+ wait = true;
289
+ outcome = 'held';
290
+ say(`The claim sent at ${utc(last.at)} is not confirmed yet. It is never sent again (the faucet would refuse it, or pay twice); checking ${it}'s balance on Flop's chain instead…`);
291
+ } else if (last?.status === 'refused' && last.retryAt !== undefined && now < last.retryAt) {
292
+ outcome = 'refused_earlier';
293
+ say(`Flop's faucet refused the last claim at ${utc(last.at)} (${last.reason ?? `HTTP ${last.httpStatus ?? '?'}`}) and asked to wait until ${utc(last.retryAt)}, so nothing was sent now.`);
294
+ } else {
295
+ const sent = await claimOnce();
296
+ outcome = sent === 'unknown' ? 'held' : sent;
297
+ if (sent === 'unreadable') {
298
+ onResult({ outcome, claim: record.claim });
299
+ return 1;
300
+ }
301
+ wait = sent === 'unknown';
302
+ }
303
+
304
+ // WAIT_FOR_GRANT: the chain decides; a failed read never ends the wait early.
305
+ if (wait) {
306
+ const claim = /** @type {ClaimEntry} */ (record.claim);
307
+ const before = BigInt(claim.beforePlanck);
308
+ const deadline = clock.now() + CLAIM.grantWaitMs;
309
+ const started = clock.now();
310
+ let shownMinute = 0;
311
+ let arrived;
312
+ for (;;) {
313
+ try {
314
+ const balance = await chain.freeBalance(keyAddress);
315
+ if (balance - before >= CLAIM.arrivedPlanck) {
316
+ arrived = balance;
317
+ break;
318
+ }
319
+ } catch {
320
+ // the next read decides
321
+ }
322
+ if (clock.now() >= deadline) break;
323
+ await clock.sleep(CLAIM.pollMs);
324
+ const minute = Math.floor((clock.now() - started) / 60_000);
325
+ if (minute > shownMinute) {
326
+ shownMinute = minute;
327
+ say(` still waiting (${minute} min)…`);
328
+ }
329
+ }
330
+ if (arrived === undefined) {
331
+ say(`The FLOP has not arrived yet. The claim was not sent again; run claim later to check (until ${utc(claim.at + CLAIM.windowMs)} it only reads ${it}'s balance).`);
332
+ onResult({ outcome: 'not_arrived', claim: record.claim });
333
+ return 1;
334
+ }
335
+ record.claim = { ...claim, status: 'granted', grantedPlanck: String(arrived - before), grantedAt: clock.now() };
336
+ save();
337
+ claimOk = true;
338
+ outcome = 'granted_now';
339
+ say(`Granted: Flop's chain shows ${formatFlop(arrived - before)} FLOP more on ${it} (it holds ${formatFlop(arrived)} FLOP).`);
340
+ }
341
+ onResult({ outcome, claim: record.claim });
342
+ // The wallet route ends here: the wallet that claimed is the wallet that pays, so nothing is ever sent on.
343
+ if (own) return claimOk ? 0 : 1;
344
+
345
+ const nextStep = `Next: give this connector a spending limit from your wallet, for compute only (ComputeChannel), for example 5 FLOP for 7 days, to its key ${keyAddress}. Then use it in Claude Code; "flop-mcp status --network ${network.name}" shows where things stand.`;
346
+ const forwardOk = await forwardSurplus();
347
+ // The spending limit comes next only once the wallet holds the FLOP (sent now, or nothing was left to send).
348
+ if (claimOk && forwardOk === 'done') say(nextStep);
349
+ return claimOk && (forwardOk === 'done' || forwardOk === 'declined') ? 0 : 1;
350
+
351
+ /**
352
+ * CLAIMING: one claim, recorded (flushed) before it is sent, never sent again.
353
+ * @returns {Promise<'not_sent'|'unreadable'|'refused'|'unknown'>} unreadable: the chain could not be read first
354
+ */
355
+ async function claimOnce() {
356
+ // Flop's own procedure (flop.network/llms.txt, "Get Testnet FLOP"): /limits must show the faucet open before a
357
+ // claim is signed. A faucet low on FLOP refuses every grant, with a 503 that reads as "unknown" and would hold
358
+ // this key's claims for a day.
359
+ let state;
360
+ try {
361
+ state = await faucet.ready();
362
+ } catch (error) {
363
+ state = { open: false, status: `unreadable: ${brief(error)}` };
364
+ }
365
+ if (!state.open) {
366
+ say(`Flop's ${network.name} faucet is not serving grants right now (its status: ${clean(state.status)}), so nothing was sent. Try again later.`);
367
+ return 'not_sent';
368
+ }
369
+ let before;
370
+ try {
371
+ before = await chain.freeBalance(keyAddress);
372
+ } catch (error) {
373
+ say(`Flop's chain could not be read (${brief(error)}), so nothing was sent. Try again later.`);
374
+ return 'unreadable';
375
+ }
376
+ const nonce = String(clock.now());
377
+ record.claim = { status: 'sending', at: clock.now(), nonce, beforePlanck: String(before) };
378
+ save();
379
+ say(`Asking Flop's ${network.name} faucet for ${network.quickGrant.flop} FLOP for ${own ? 'this wallet' : 'this connector\'s key'} ${keyAddress}…`);
380
+ let answer;
381
+ try {
382
+ answer = await faucet.claim(nonce);
383
+ } catch (error) {
384
+ answer = { status: /** @type {const} */ ('unknown'), error: brief(error) }; // it may have left: never assume it did not
385
+ }
386
+ const code = reasonCode(answer.reason);
387
+ const message = answer.error ? clean(answer.error) : undefined;
388
+ // Only what readClaimRecord accepts back: a record a real run wrote must never read as damaged.
389
+ const facts = { ...(HTTP_STATUS(answer.httpStatus) ? { httpStatus: answer.httpStatus } : {}), ...(code ? { reason: code } : {}), ...(message ? { message } : {}) };
390
+ if (answer.status === 'unavailable') {
391
+ record.claim = { ...record.claim, status: 'unavailable', ...facts };
392
+ save();
393
+ say(`The claim was not sent${message ? ` (${message})` : ''}. Nothing was sent; try again later.`);
394
+ return 'not_sent';
395
+ }
396
+ if (answer.status === 'refused') {
397
+ const seconds = answer.retryAfterSeconds;
398
+ const retryAt = Number.isFinite(seconds) && /** @type {number} */ (seconds) >= 0 && /** @type {number} */ (seconds) <= MAX_RETRY_SECONDS
399
+ ? record.claim.at + Math.ceil(/** @type {number} */ (seconds)) * 1000 : undefined;
400
+ record.claim = { ...record.claim, status: 'refused', ...facts, ...(retryAt !== undefined ? { retryAt } : {}) };
401
+ save();
402
+ say(`Flop's faucet refused the claim (${code ?? 'no reason code'}, HTTP ${answer.httpStatus ?? '?'}${message ? `: ${message}` : ''}).`);
403
+ say(retryAt !== undefined
404
+ ? `Try again after ${utc(retryAt)}.`
405
+ : 'It did not say when to try again; it grants one claim per key, and in practice one per internet address, every 24 hours.');
406
+ return 'refused';
407
+ }
408
+ if (NOTHING_RESERVED.has(code ?? '')) {
409
+ record.claim = { ...record.claim, status: 'refused', ...facts, retryAt: record.claim.at + BUSY_RETRY_MS };
410
+ save();
411
+ say(`Flop's faucet is busy: it has more grants queued than it can send, and says nothing was reserved for this claim. Nothing more was sent; it can be asked again after ${utc(record.claim.retryAt)}.`);
412
+ return 'refused';
413
+ }
414
+ record.claim = { ...record.claim, status: 'unknown', ...facts };
415
+ save();
416
+ say(`Flop's faucet answered${answer.httpStatus ? ` (HTTP ${answer.httpStatus})` : ' nothing clear'}, but only Flop's chain can confirm a grant. The claim is never sent again; waiting up to ${CLAIM.grantWaitMs / 60_000} minutes for the FLOP to arrive (the faucet queues grants)…`);
417
+ return 'unknown';
418
+ }
419
+
420
+ /**
421
+ * FORWARD_DECISION and FORWARDING: what is above the key's fee money goes to the owner, once agreed.
422
+ * @returns {Promise<'done'|'declined'|'problem'>} declined: the user said no, so the FLOP is still on the key
423
+ */
424
+ async function forwardSurplus() {
425
+ let balance;
426
+ let fee;
427
+ try {
428
+ balance = await chain.freeBalance(keyAddress);
429
+ fee = balance > CLAIM.keepPlanck ? await chain.transferFee(owner, balance - CLAIM.keepPlanck) : 0n;
430
+ } catch (error) {
431
+ say(`Flop's chain could not be read (${brief(error)}), so nothing was sent to your wallet. Run claim again later.`);
432
+ return 'problem';
433
+ }
434
+ const agreed = balance - CLAIM.keepPlanck - fee;
435
+ if (agreed < CLAIM.minForwardPlanck) {
436
+ say(`This key holds ${formatFlop(balance)} FLOP and keeps up to ${formatFlop(CLAIM.keepPlanck)} FLOP of it for its network fees, so there is nothing to send to your wallet.`);
437
+ return 'done';
438
+ }
439
+ if (!yes) {
440
+ const ok = await confirm(`This key keeps ${formatFlop(CLAIM.keepPlanck)} FLOP for its network fees. Send the other ${formatFlop(agreed)} FLOP to your wallet ${owner} (the owner saved by init)? [y/N] `);
441
+ if (!ok) {
442
+ say('Nothing was sent. To send it later, run claim again (add --yes to skip this question). Your wallet needs that FLOP before it can give this connector a spending limit.');
443
+ return 'declined';
444
+ }
445
+ }
446
+ let release;
447
+ try {
448
+ release = await chain.lock();
449
+ } catch (error) {
450
+ say(/** @type {any} */ (error)?.code === 'JOURNAL_LOCKED'
451
+ ? 'A Claude session is paying with this key right now, so nothing was sent to your wallet. Run claim again once it has finished.'
452
+ : `The payer lock could not be taken (${brief(error)}), so nothing was sent to your wallet.`);
453
+ return 'problem';
454
+ }
455
+ let sent;
456
+ try {
457
+ let amount;
458
+ try {
459
+ // Read again under the lock: a Claude session may have paid fees meanwhile. Never more than agreed.
460
+ const now = await chain.freeBalance(keyAddress) - CLAIM.keepPlanck - fee;
461
+ amount = now < agreed ? now : agreed;
462
+ } catch (error) {
463
+ say(`Flop's chain could not be read (${brief(error)}), so nothing was sent to your wallet.`);
464
+ return 'problem';
465
+ }
466
+ if (amount < CLAIM.minForwardPlanck) {
467
+ say('This key holds no more than its fee money now, so there is nothing to send to your wallet.');
468
+ return 'done';
469
+ }
470
+ let prepared;
471
+ try {
472
+ prepared = await chain.prepareTransfer(owner, amount);
473
+ } catch (error) {
474
+ say(`The transfer could not be signed (${brief(error)}), so nothing was sent. Run claim again in a minute.`);
475
+ return 'problem';
476
+ }
477
+ record.forward = {
478
+ status: 'prepared', at: clock.now(), to: owner, amountPlanck: String(amount), txHash: prepared.txHash,
479
+ eraBirth: String(prepared.eraBirth), eraPeriod: String(prepared.eraPeriod),
480
+ };
481
+ save();
482
+ try {
483
+ sent = await prepared.send();
484
+ } catch (error) {
485
+ sent = { outcome: /** @type {const} */ ('unknown'), message: brief(error) };
486
+ }
487
+ } finally {
488
+ await release();
489
+ }
490
+ const forward = /** @type {ForwardEntry} */ (record.forward);
491
+ if (sent.outcome === 'ok') {
492
+ record.forward = { ...forward, status: 'landed' };
493
+ save();
494
+ say(`Sent ${formatFlop(BigInt(forward.amountPlanck))} FLOP to your wallet ${owner} (transaction ${forward.txHash}); this key keeps about ${formatFlop(CLAIM.keepPlanck)} FLOP for its network fees.`);
495
+ return 'done';
496
+ }
497
+ if (sent.outcome === 'failed') {
498
+ record.forward = { ...forward, status: 'failed', ...(sent.message ? { message: clean(sent.message) } : {}) };
499
+ save();
500
+ say(`The transfer to your wallet failed, so nothing moved${sent.message ? ` (${clean(sent.message)})` : ''}. Run claim again to try once more.`);
501
+ return 'problem';
502
+ }
503
+ record.forward = { ...forward, status: 'unknown', ...(sent.message ? { message: clean(sent.message) } : {}) };
504
+ save();
505
+ say('The transfer was sent, but its outcome is not confirmed yet: checking Flop\'s chain (it is never sent twice)…');
506
+ const settled = await settleForward(record.forward, { chain, clock });
507
+ if (settled.status === 'open') {
508
+ say('It is still being confirmed on Flop\'s chain. Nothing new was sent; run claim again in a few minutes to finish.');
509
+ return 'problem';
510
+ }
511
+ record.forward = { ...record.forward, status: settled.status, ...(settled.block ? { block: settled.block } : {}) };
512
+ save();
513
+ say(describe(record.forward));
514
+ return settled.status === 'landed' ? 'done' : 'problem';
515
+ }
516
+ }