flop-guild 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +62 -2
- package/dist/autopilot.js +178 -0
- package/dist/cli.js +220 -0
- package/dist/commands.js +40 -0
- package/dist/config.js +21 -0
- package/dist/econ.js +125 -0
- package/dist/flop.js +322 -0
- package/dist/identity.js +110 -0
- package/dist/mcp.js +124 -0
- package/dist/minerpage.js +168 -0
- package/dist/miners.js +107 -0
- package/dist/net.js +64 -0
- package/dist/nonce.js +36 -0
- package/dist/server.js +405 -0
- package/dist/setup.js +222 -0
- package/dist/technocore.js +134 -0
- package/dist/wallet.js +66 -0
- package/networks.json +13 -0
- package/package.json +51 -4
- package/site/guides/agent-quickstart.md +42 -0
- package/site/guides/autopilot.md +45 -0
- package/site/guides/join-guild.md +33 -0
- package/site/index.html +18 -0
- package/site/llms.txt +31 -0
- package/site/skill.md +48 -0
- package/site/start-core.js +117 -0
- package/site/start.html +41 -0
- package/site/start.js +66 -0
- package/site/vendor/noble-ed25519-3.2.0.js +933 -0
- package/site/vendor/noble-ed25519-LICENSE.txt +21 -0
- package/skill.md +73 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// /miner: demand by UTC hour (7 days, cached 10 min) and a rent vs airdrop calculator.
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { CALC_DEFAULTS, loadDemand, minerCalc } from "./econ.js";
|
|
4
|
+
import { networksPath } from "./net.js";
|
|
5
|
+
export const TESTNET_NOTE = "Testnet is not live yet. This page reads devnet data until testnet endpoints are published.";
|
|
6
|
+
export const MINER_FOOTER = "Unofficial community tool. Estimates only. Draft Flop rules may change. No airdrop promises.";
|
|
7
|
+
const TTL = 10 * 60 * 1000;
|
|
8
|
+
export const PARTIAL_NOTE = "Partial data, showing last complete read";
|
|
9
|
+
const PARTIAL_RETRY = 2 * 60 * 1000;
|
|
10
|
+
let lastComplete; // never replaced by a partial read
|
|
11
|
+
let lastAttempt;
|
|
12
|
+
let lastAttemptAt = 0;
|
|
13
|
+
let inflight;
|
|
14
|
+
let lastError;
|
|
15
|
+
function explorerFor(network) {
|
|
16
|
+
const n = JSON.parse(readFileSync(networksPath(), "utf8"))[network];
|
|
17
|
+
if (!n?.explorer)
|
|
18
|
+
throw new Error(`no explorer configured for ${network}`);
|
|
19
|
+
return n.explorer;
|
|
20
|
+
}
|
|
21
|
+
function view() {
|
|
22
|
+
const latest = lastAttempt;
|
|
23
|
+
if (!latest)
|
|
24
|
+
return undefined;
|
|
25
|
+
return { shown: lastComplete ?? latest, latest, partial: !latest.complete };
|
|
26
|
+
}
|
|
27
|
+
/** Cached demand: refresh after 10 minutes (2 after a partial read); a partial read never replaces a complete one. */
|
|
28
|
+
export async function demand(network = process.env.MINER_NETWORK || "devnet", waitMs = 25_000) {
|
|
29
|
+
const age = Date.now() - lastAttemptAt;
|
|
30
|
+
const stale = !lastAttempt || age > (lastAttempt.complete ? TTL : PARTIAL_RETRY);
|
|
31
|
+
if (stale && !inflight) {
|
|
32
|
+
lastAttemptAt = Date.now();
|
|
33
|
+
inflight = loadDemand(network, explorerFor(network))
|
|
34
|
+
.then((d) => {
|
|
35
|
+
lastAttempt = d;
|
|
36
|
+
if (d.complete)
|
|
37
|
+
lastComplete = d;
|
|
38
|
+
lastError = undefined;
|
|
39
|
+
return d;
|
|
40
|
+
})
|
|
41
|
+
.catch((e) => {
|
|
42
|
+
lastError = e.message;
|
|
43
|
+
throw e;
|
|
44
|
+
})
|
|
45
|
+
.finally(() => {
|
|
46
|
+
inflight = undefined;
|
|
47
|
+
});
|
|
48
|
+
inflight.catch(() => { });
|
|
49
|
+
}
|
|
50
|
+
if (lastAttempt)
|
|
51
|
+
return view();
|
|
52
|
+
const timeout = new Promise((r) => setTimeout(() => r(undefined), waitMs));
|
|
53
|
+
await Promise.race([inflight.catch(() => undefined), timeout]);
|
|
54
|
+
return view();
|
|
55
|
+
}
|
|
56
|
+
export function demandError() {
|
|
57
|
+
return lastError;
|
|
58
|
+
}
|
|
59
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
60
|
+
const hh = (h) => `${String(h).padStart(2, "0")}:00`;
|
|
61
|
+
const usd = (n) => `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
62
|
+
const flop = (n) => `${Math.round(n).toLocaleString("en-US")} FLOP`;
|
|
63
|
+
const price = (n) => (n === null ? "n/a" : `$${n < 0.01 ? n.toPrecision(3) : n.toFixed(4)}`);
|
|
64
|
+
const pct = (n) => `${(n * 100).toPrecision(3)}%`;
|
|
65
|
+
function chart(byHour) {
|
|
66
|
+
const max = Math.max(1, ...byHour);
|
|
67
|
+
const W = 480, H = 180, pad = 22, bw = (W - 2 * 4) / 24;
|
|
68
|
+
const bars = byHour
|
|
69
|
+
.map((n, h) => {
|
|
70
|
+
const bh = Math.round(((H - pad - 6) * n) / max);
|
|
71
|
+
const x = 4 + h * bw;
|
|
72
|
+
return `<rect x="${(x + 1.5).toFixed(1)}" y="${H - pad - bh}" width="${(bw - 3).toFixed(1)}" height="${bh}" rx="2" class="bar"><title>${hh(h)} UTC: ${n} sessions</title></rect>`;
|
|
73
|
+
})
|
|
74
|
+
.join("");
|
|
75
|
+
const ticks = [0, 6, 12, 18, 23]
|
|
76
|
+
.map((h) => `<text x="${(4 + h * bw + bw / 2).toFixed(1)}" y="${H - 6}" text-anchor="middle" class="tick">${hh(h)}</text>`)
|
|
77
|
+
.join("");
|
|
78
|
+
return `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Sessions opened per UTC hour over the last 7 days" class="chart">${bars}${ticks}</svg>`;
|
|
79
|
+
}
|
|
80
|
+
function calcRows(o) {
|
|
81
|
+
const rows = [
|
|
82
|
+
["out-rent", "Total rent", usd(o.totalRent)],
|
|
83
|
+
["out-share", "Your share of the miner pool (estimate)", pct(o.share)],
|
|
84
|
+
["out-airdrop", "Airdrop FLOP (estimate)", flop(o.airdropFlop)],
|
|
85
|
+
["out-liquid", "Liquid FLOP at launch (estimate)", flop(o.liquidFlop)],
|
|
86
|
+
["out-be-liquid", "Break-even FLOP price, liquid FLOP only", price(o.breakEvenLiquid)],
|
|
87
|
+
["out-be-all", "Break-even FLOP price, if all airdrop FLOP unlocked", price(o.breakEvenAll)],
|
|
88
|
+
["out-net", "Liquid value minus rent, at your FLOP price", o.net === null ? "enter a FLOP price" : usd(o.net)],
|
|
89
|
+
];
|
|
90
|
+
return rows.map(([id, label, v]) => `<tr><th scope="row">${label}</th><td id="${id}">${v}</td></tr>`).join("");
|
|
91
|
+
}
|
|
92
|
+
export const MINER_STYLE = `
|
|
93
|
+
.chart{width:100%;height:auto;margin:.5rem 0}.chart .bar{fill:var(--accent)}.chart .tick{fill:var(--muted);font-size:11px}
|
|
94
|
+
table{border-collapse:collapse;width:100%;margin:.5rem 0}th,td{text-align:left;padding:.35rem .4rem;border-bottom:1px solid var(--line);vertical-align:top}
|
|
95
|
+
td{text-align:right;font-variant-numeric:tabular-nums}
|
|
96
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(14rem,1fr));gap:.6rem 1rem}
|
|
97
|
+
label{display:flex;flex-direction:column;font-size:.9rem;color:var(--muted)}
|
|
98
|
+
input{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:.35rem .5rem;margin-top:.2rem}
|
|
99
|
+
.note{color:var(--muted);font-size:.9rem}`;
|
|
100
|
+
export function minerPage(v, err) {
|
|
101
|
+
const d = v?.shown;
|
|
102
|
+
const minerCount = d?.minerCount ?? 0;
|
|
103
|
+
const utc = (t) => new Date(t).toISOString().slice(0, 16).replace("T", " ");
|
|
104
|
+
const partialHtml = v?.partial
|
|
105
|
+
? `<p><strong>${v.shown.complete ? PARTIAL_NOTE : "Partial data, no complete read yet"}</strong> (latest read ${utc(v.latest.fetchedAt)} UTC stopped early: ${esc(v.latest.note ?? "incomplete")}; ${v.latest.pagesRead} pages, ${v.latest.sessions.toLocaleString("en-US")} sessions).</p>`
|
|
106
|
+
: "";
|
|
107
|
+
const readInfo = d
|
|
108
|
+
? ` <span class="note">(${d.sessions.toLocaleString("en-US")} sessions read since ${utc(d.windowStart)} UTC, ${d.pagesRead} explorer pages, ${d.complete ? "complete read" : "partial read"})</span>`
|
|
109
|
+
: "";
|
|
110
|
+
const out = minerCalc({ ...CALC_DEFAULTS, minerCount });
|
|
111
|
+
const demandHtml = d
|
|
112
|
+
? `<p>${d.sessions.toLocaleString("en-US")} sessions opened on ${esc(d.network)} between ${new Date(d.windowStart).toISOString().slice(0, 16).replace("T", " ")} and ${new Date(d.windowEnd).toISOString().slice(0, 16).replace("T", " ")} UTC, about <strong>${d.perHour.toFixed(1)} sessions per hour</strong>.</p>
|
|
113
|
+
${partialHtml}
|
|
114
|
+
${chart(d.byHour)}
|
|
115
|
+
<p>Busiest UTC hours: ${d.busiest.map((b) => `<strong>${hh(b.hour)}</strong> (${b.sessions.toLocaleString("en-US")})`).join(", ")}.</p>
|
|
116
|
+
<p class="note">Source: ${esc(d.explorer)}/api/compute-channels, bucketed by the hour each session opened. Updated ${new Date(d.fetchedAt).toISOString().slice(11, 16)} UTC, refreshed every 10 minutes.</p>`
|
|
117
|
+
: `<p>${err ? `The explorer did not answer (${esc(err)}).` : "Loading demand data."} Refresh in a minute.</p>`;
|
|
118
|
+
return `<h1>Miner economics</h1>
|
|
119
|
+
<p>What miners are paid for: how much inference demand there is, by hour, and what renting a GPU costs against an estimated airdrop share.</p>
|
|
120
|
+
<h2>Demand by UTC hour, last 7 days</h2>
|
|
121
|
+
${d?.network === "devnet" ? `<p><strong>${TESTNET_NOTE}</strong></p>` : ""}
|
|
122
|
+
${demandHtml}
|
|
123
|
+
<h2>Rent vs airdrop calculator</h2>
|
|
124
|
+
<form id="calc" class="grid" data-miners="${minerCount}" onsubmit="return false">
|
|
125
|
+
<label>Rent, $ per hour<input id="in-rent" type="number" step="0.01" min="0" value="${CALC_DEFAULTS.rentPerHour}"></label>
|
|
126
|
+
<label>Hours per day<input id="in-hours" type="number" step="1" min="0" max="24" value="${CALC_DEFAULTS.hoursPerDay}"></label>
|
|
127
|
+
<label>Days<input id="in-days" type="number" step="1" min="0" value="${CALC_DEFAULTS.days}"></label>
|
|
128
|
+
<label>Your GPU weight vs H100<input id="in-weight" type="number" step="0.01" min="0" value="${CALC_DEFAULTS.gpuWeight}"></label>
|
|
129
|
+
<label>Average miner weight vs H100 (assumed)<input id="in-avg" type="number" step="0.01" min="0.0001" value="${CALC_DEFAULTS.avgWeight}"></label>
|
|
130
|
+
<label>FLOP price, $ (your guess)<input id="in-price" type="number" step="any" min="0" placeholder="no price yet"></label>
|
|
131
|
+
<label>Miner pool, FLOP<input id="in-pool" type="number" step="1" min="0" value="${CALC_DEFAULTS.poolFlop}"></label>
|
|
132
|
+
<label>Liquid share, %<input id="in-liquid" type="number" step="1" min="0" max="100" value="${CALC_DEFAULTS.liquidShare * 100}"></label>
|
|
133
|
+
</form>
|
|
134
|
+
<p>Miners active in the last 7 days (live from the explorer): <strong id="miner-count">${minerCount.toLocaleString("en-US")}</strong>${readInfo}</p>
|
|
135
|
+
<table><tbody>${calcRows(out)}</tbody></table>
|
|
136
|
+
<p class="note">Share estimate = your weight / (miner count × average weight) × (hours per day / 24). The share assumes the average miner runs 24 hours a day.</p>
|
|
137
|
+
<p class="note">The real share is your verified compute divided by all verified compute, which nobody can know in advance. No FLOP token or price exists yet.</p>`;
|
|
138
|
+
}
|
|
139
|
+
/** Browser script: the same minerCalc as the server, plus input wiring. */
|
|
140
|
+
export function minerScript() {
|
|
141
|
+
return `"use strict";
|
|
142
|
+
${minerCalc.toString()}
|
|
143
|
+
(function () {
|
|
144
|
+
var f = document.getElementById("calc");
|
|
145
|
+
if (!f) return;
|
|
146
|
+
var miners = Number(f.getAttribute("data-miners")) || 0;
|
|
147
|
+
function v(id) { var x = document.getElementById(id).value; return x === "" ? undefined : Number(x); }
|
|
148
|
+
function usd(n) { return "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
|
|
149
|
+
function fl(n) { return Math.round(n).toLocaleString("en-US") + " FLOP"; }
|
|
150
|
+
function pr(n) { return n === null ? "n/a" : "$" + (n < 0.01 ? n.toPrecision(3) : n.toFixed(4)); }
|
|
151
|
+
function set(id, t) { document.getElementById(id).textContent = t; }
|
|
152
|
+
function run() {
|
|
153
|
+
var o = minerCalc({ rentPerHour: v("in-rent") || 0, hoursPerDay: v("in-hours") || 0, days: v("in-days") || 0,
|
|
154
|
+
gpuWeight: v("in-weight") || 0, avgWeight: v("in-avg") || 0, minerCount: miners,
|
|
155
|
+
poolFlop: v("in-pool") || 0, liquidShare: (v("in-liquid") || 0) / 100, flopPrice: v("in-price") });
|
|
156
|
+
set("out-rent", usd(o.totalRent));
|
|
157
|
+
set("out-share", (o.share * 100).toPrecision(3) + "%");
|
|
158
|
+
set("out-airdrop", fl(o.airdropFlop));
|
|
159
|
+
set("out-liquid", fl(o.liquidFlop));
|
|
160
|
+
set("out-be-liquid", pr(o.breakEvenLiquid));
|
|
161
|
+
set("out-be-all", pr(o.breakEvenAll));
|
|
162
|
+
set("out-net", o.net === null ? "enter a FLOP price" : usd(o.net));
|
|
163
|
+
}
|
|
164
|
+
f.addEventListener("input", run);
|
|
165
|
+
run();
|
|
166
|
+
})();
|
|
167
|
+
`;
|
|
168
|
+
}
|
package/dist/miners.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Read-only miner ranking from the explorer's compute-channel list. No keys, no signing.
|
|
2
|
+
// Ranking is neutral: settled sessions, then settlement rate, then address. No miner is favored.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { networksPath } from "./net.js";
|
|
5
|
+
const UA = "flop-guild/miners";
|
|
6
|
+
const PAGE = 100;
|
|
7
|
+
export function rank(channels) {
|
|
8
|
+
const by = new Map();
|
|
9
|
+
for (const c of channels) {
|
|
10
|
+
if (!c.miner)
|
|
11
|
+
continue;
|
|
12
|
+
const r = by.get(c.miner) ?? { miner: c.miner, settled: 0, timedout: 0, open: 0, rate: 0 };
|
|
13
|
+
if (c.status === "settled") {
|
|
14
|
+
r.settled += 1;
|
|
15
|
+
const t = c.settlement?.timestamp;
|
|
16
|
+
if (t && (!r.lastSettled || t > r.lastSettled))
|
|
17
|
+
r.lastSettled = t;
|
|
18
|
+
}
|
|
19
|
+
else if (c.status === "timedout")
|
|
20
|
+
r.timedout += 1;
|
|
21
|
+
else if (c.status === "open")
|
|
22
|
+
r.open += 1;
|
|
23
|
+
by.set(c.miner, r);
|
|
24
|
+
}
|
|
25
|
+
const rows = [...by.values()];
|
|
26
|
+
for (const r of rows)
|
|
27
|
+
r.rate = r.settled + r.timedout ? r.settled / (r.settled + r.timedout) : 0;
|
|
28
|
+
return rows.sort((a, b) => b.settled - a.settled || b.rate - a.rate || (a.miner < b.miner ? -1 : a.miner > b.miner ? 1 : 0));
|
|
29
|
+
}
|
|
30
|
+
export async function channelPage(base, pageIndex) {
|
|
31
|
+
return page(base, pageIndex * PAGE);
|
|
32
|
+
}
|
|
33
|
+
async function page(base, offset) {
|
|
34
|
+
const res = await fetch(`${base}/api/compute-channels?limit=${PAGE}&offset=${offset}`, {
|
|
35
|
+
headers: { "user-agent": UA, accept: "application/json" },
|
|
36
|
+
signal: AbortSignal.timeout(20_000),
|
|
37
|
+
});
|
|
38
|
+
if (!res.ok)
|
|
39
|
+
throw new Error(`HTTP ${res.status}`);
|
|
40
|
+
const j = await res.json();
|
|
41
|
+
if (!Array.isArray(j?.data))
|
|
42
|
+
throw new Error("unexpected response shape (no data array)");
|
|
43
|
+
return { data: j.data, total: j.pagination?.total, hasMore: !!j.pagination?.hasMore };
|
|
44
|
+
}
|
|
45
|
+
export async function miners(network, limit, pages) {
|
|
46
|
+
const all = JSON.parse(readFileSync(networksPath(), "utf8"));
|
|
47
|
+
const explorer = all[network]?.explorer;
|
|
48
|
+
if (!explorer)
|
|
49
|
+
return `No explorer is configured for "${network}" in networks.json, so there is nothing to rank.`;
|
|
50
|
+
const base = explorer.replace(/\/+$/, "");
|
|
51
|
+
const channels = [];
|
|
52
|
+
let total;
|
|
53
|
+
let note = "";
|
|
54
|
+
for (let i = 0; i < pages; i++) {
|
|
55
|
+
try {
|
|
56
|
+
const p = await page(base, i * PAGE);
|
|
57
|
+
total ??= p.total;
|
|
58
|
+
channels.push(...p.data);
|
|
59
|
+
if (!p.hasMore)
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (i === 0)
|
|
64
|
+
return `The explorer did not answer (${base}/api/compute-channels: ${e.message}). No ranking this time; try again later.`;
|
|
65
|
+
note = `Stopped after ${i} page(s): ${e.message}. The ranking uses what was read.`;
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const rows = rank(channels);
|
|
70
|
+
const lines = [];
|
|
71
|
+
lines.push(`Miners on ${network}, from the ${channels.length} most recent compute sessions${total ? ` of ${total}` : ""} (${base}).`);
|
|
72
|
+
lines.push(`Ranked by settled sessions, then settlement rate = settled / (settled + timed out). Open sessions are not counted in the rate.`);
|
|
73
|
+
if (note)
|
|
74
|
+
lines.push(note);
|
|
75
|
+
if (!rows.length)
|
|
76
|
+
return [...lines, "No sessions with a miner were found."].join("\n");
|
|
77
|
+
lines.push("");
|
|
78
|
+
const head = ["#", "miner", "settled", "timed out", "open", "rate", "last settled (UTC)"];
|
|
79
|
+
const body = rows.slice(0, limit).map((r, i) => [
|
|
80
|
+
String(i + 1),
|
|
81
|
+
r.miner,
|
|
82
|
+
String(r.settled),
|
|
83
|
+
String(r.timedout),
|
|
84
|
+
String(r.open),
|
|
85
|
+
r.settled + r.timedout ? `${(r.rate * 100).toFixed(0)}%` : "-",
|
|
86
|
+
r.lastSettled ? new Date(r.lastSettled).toISOString().slice(0, 16).replace("T", " ") : "-",
|
|
87
|
+
]);
|
|
88
|
+
const w = head.map((h, c) => Math.max(h.length, ...body.map((b) => b[c].length)));
|
|
89
|
+
const fmt = (cells) => cells.map((x, c) => (c === 1 ? x.padEnd(w[c]) : x.padStart(w[c]))).join(" ");
|
|
90
|
+
lines.push(fmt(head), fmt(w.map((n) => "-".repeat(n))), ...body.map(fmt));
|
|
91
|
+
const top = rows[0];
|
|
92
|
+
lines.push("");
|
|
93
|
+
if (!top.settled) {
|
|
94
|
+
lines.push("No miner has a settled session in this window, so there is no top pick.");
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
lines.push(`Run a session on the top miner (${top.miner}):`);
|
|
98
|
+
lines.push(` flop --network ${network} --keystore agent.json --password-env FLOP_KEY_PASSWORD session run --miner '${top.miner}' --model qwen/qwen2.5-0.5b-instruct --prompt 'Say hi in five words.' --max-flop 0.01 --via auto --json`);
|
|
99
|
+
lines.push(" Add --endpoint <url> if the miner has no live signed offer.");
|
|
100
|
+
const own = existsSync("own-miners.json") ? JSON.parse(readFileSync("own-miners.json", "utf8")) : [];
|
|
101
|
+
if (Array.isArray(own) && own.includes(top.miner)) {
|
|
102
|
+
lines.push(" Note: this miner is listed in your own-miners.json. Spend routed to your own miner is not credited.");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
lines.push("", "Past settlement is not a promise of future service. Read-only: no key was used.");
|
|
106
|
+
return lines.join("\n");
|
|
107
|
+
}
|
package/dist/net.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Network profiles and the genesis guard. Nothing signs before verifyGenesis passes.
|
|
2
|
+
import { setDefaultResultOrder } from "node:dns";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
// Hosts with a broken IPv6 route time out before falling back; try IPv4 first.
|
|
7
|
+
setDefaultResultOrder("ipv4first");
|
|
8
|
+
export const FLOP = 10n ** 18n;
|
|
9
|
+
export function networksPath() {
|
|
10
|
+
return process.env.FLOP_GUILD_NETWORKS || join(dirname(fileURLToPath(import.meta.url)), "..", "networks.json");
|
|
11
|
+
}
|
|
12
|
+
export function loadNetwork(name) {
|
|
13
|
+
const all = JSON.parse(readFileSync(networksPath(), "utf8"));
|
|
14
|
+
const n = all[name];
|
|
15
|
+
if (!n)
|
|
16
|
+
throw new Error(`no network "${name}" in networks.json`);
|
|
17
|
+
for (const k of ["rpc", "faucet", "gateway", "genesis"]) {
|
|
18
|
+
if (!n[k])
|
|
19
|
+
throw new Error(`networks.json: "${name}.${k}" is empty; fill it in first`);
|
|
20
|
+
}
|
|
21
|
+
if (!/^0x[0-9a-f]{64}$/.test(n.genesis))
|
|
22
|
+
throw new Error(`networks.json: "${name}.genesis" is not a 32-byte hex hash`);
|
|
23
|
+
return { name, ...n };
|
|
24
|
+
}
|
|
25
|
+
/** Compare the expected genesis with what the RPC and the faucet report. */
|
|
26
|
+
export async function checkGenesis(net, api) {
|
|
27
|
+
const rpc = api.genesisHash.toHex();
|
|
28
|
+
const res = await fetch(`${net.faucet}/chain`, { headers: { "user-agent": "flop-guild/0.2" } });
|
|
29
|
+
const faucet = res.ok ? String((await res.json()).genesisHash ?? "") : `HTTP ${res.status}`;
|
|
30
|
+
return { expected: net.genesis, rpc, faucet, ok: rpc === net.genesis && faucet === net.genesis };
|
|
31
|
+
}
|
|
32
|
+
/** Connect and refuse to continue unless the genesis matches everywhere. */
|
|
33
|
+
export async function connect(net) {
|
|
34
|
+
const { ApiPromise, WsProvider } = await import("@polkadot/api");
|
|
35
|
+
const provider = new WsProvider(net.rpc, 2500, {}, 30000);
|
|
36
|
+
const api = await ApiPromise.create({ provider, noInitWarn: true, throwOnConnect: true });
|
|
37
|
+
const genesis = await checkGenesis(net, api);
|
|
38
|
+
if (!genesis.ok) {
|
|
39
|
+
await api.disconnect();
|
|
40
|
+
throw new Error(`genesis mismatch on ${net.name}: expected ${genesis.expected}, rpc ${genesis.rpc}, faucet ${genesis.faucet}. Refusing to run.`);
|
|
41
|
+
}
|
|
42
|
+
return { api, genesis };
|
|
43
|
+
}
|
|
44
|
+
/** Free balance at the finalized head, in raw units. */
|
|
45
|
+
export async function finalizedFree(api, address) {
|
|
46
|
+
const head = await api.rpc.chain.getFinalizedHead();
|
|
47
|
+
const at = await api.at(head);
|
|
48
|
+
const acct = await at.query.system.account(address);
|
|
49
|
+
return BigInt(acct.data.free.toString());
|
|
50
|
+
}
|
|
51
|
+
export function fmtFlop(raw) {
|
|
52
|
+
const neg = raw < 0n;
|
|
53
|
+
const v = neg ? -raw : raw;
|
|
54
|
+
const whole = v / FLOP;
|
|
55
|
+
const frac = (v % FLOP).toString().padStart(18, "0").replace(/0+$/, "").slice(0, 6);
|
|
56
|
+
return `${neg ? "-" : ""}${whole}${frac ? "." + frac : ""}`;
|
|
57
|
+
}
|
|
58
|
+
export function toRaw(flop) {
|
|
59
|
+
if (!Number.isFinite(flop) || flop < 0)
|
|
60
|
+
throw new Error(`bad FLOP amount: ${flop}`);
|
|
61
|
+
const [w, f = ""] = flop.toFixed(18).split(".");
|
|
62
|
+
return BigInt(w) * FLOP + BigInt(f.padEnd(18, "0").slice(0, 18));
|
|
63
|
+
}
|
|
64
|
+
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
package/dist/nonce.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Per-key, per-scope increasing nonces: microsecond time, bumped past a persisted counter.
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { checkName, homeDir } from "./identity.js";
|
|
5
|
+
function statePath(name) {
|
|
6
|
+
return join(homeDir(), `${checkName(name)}.nonces.json`);
|
|
7
|
+
}
|
|
8
|
+
function nowMicros() {
|
|
9
|
+
// Wall clock in ms, refined with the monotonic clock's sub-ms part.
|
|
10
|
+
const ms = BigInt(Date.now());
|
|
11
|
+
const sub = process.hrtime.bigint() % 1000n;
|
|
12
|
+
return ms * 1000n + sub;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Next nonce for this key in this scope (a room, or a kv scope such as "kv:d-flopguild").
|
|
16
|
+
* floor: a value the nonce must exceed (for example the server's room-nonce counter).
|
|
17
|
+
*/
|
|
18
|
+
export function nextNonce(name, scope, floor = 0n) {
|
|
19
|
+
mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
|
|
20
|
+
const path = statePath(name);
|
|
21
|
+
const state = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
|
|
22
|
+
const last = BigInt(state[scope] ?? "0");
|
|
23
|
+
let n = nowMicros();
|
|
24
|
+
if (n <= last)
|
|
25
|
+
n = last + 1n;
|
|
26
|
+
if (n <= floor)
|
|
27
|
+
n = floor + 1n;
|
|
28
|
+
const s = n.toString();
|
|
29
|
+
if (!/^\d{1,19}$/.test(s))
|
|
30
|
+
throw new Error("nonce out of range");
|
|
31
|
+
state[scope] = s;
|
|
32
|
+
const tmp = path + ".tmp";
|
|
33
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
|
|
34
|
+
renameSync(tmp, path);
|
|
35
|
+
return s;
|
|
36
|
+
}
|