flop-guild 0.2.0 → 0.2.2
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/dist/econ.js +125 -0
- package/dist/minerpage.js +168 -0
- package/dist/miners.js +3 -0
- package/dist/server.js +65 -6
- package/package.json +4 -3
- package/site/index.html +2 -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/dist/econ.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Miner economics: demand by UTC hour (from explorer sessions) and a rent vs airdrop calculator.
|
|
2
|
+
// minerCalc is self-contained: the server also ships its source to the browser, so the page and
|
|
3
|
+
// the server compute the same numbers.
|
|
4
|
+
import { channelPage } from "./miners.js";
|
|
5
|
+
export function minerCalc(i) {
|
|
6
|
+
const totalRent = i.rentPerHour * i.hoursPerDay * i.days;
|
|
7
|
+
const denom = i.minerCount * i.avgWeight;
|
|
8
|
+
// Scaled by uptime: the average miner is assumed to run 24 hours a day.
|
|
9
|
+
const uptime = Math.min(24, Math.max(0, i.hoursPerDay)) / 24;
|
|
10
|
+
const share = denom > 0 ? Math.min(1, i.gpuWeight / denom) * uptime : 0;
|
|
11
|
+
const airdropFlop = share * i.poolFlop;
|
|
12
|
+
const liquidFlop = airdropFlop * i.liquidShare;
|
|
13
|
+
const price = typeof i.flopPrice === "number" && i.flopPrice > 0 ? i.flopPrice : null;
|
|
14
|
+
return {
|
|
15
|
+
totalRent,
|
|
16
|
+
share,
|
|
17
|
+
airdropFlop,
|
|
18
|
+
liquidFlop,
|
|
19
|
+
breakEvenLiquid: liquidFlop > 0 ? totalRent / liquidFlop : null,
|
|
20
|
+
breakEvenAll: airdropFlop > 0 ? totalRent / airdropFlop : null,
|
|
21
|
+
liquidValue: price === null ? null : liquidFlop * price,
|
|
22
|
+
net: price === null ? null : liquidFlop * price - totalRent,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export const CALC_DEFAULTS = {
|
|
26
|
+
rentPerHour: 0.22,
|
|
27
|
+
hoursPerDay: 24,
|
|
28
|
+
days: 90,
|
|
29
|
+
gpuWeight: 0.17,
|
|
30
|
+
avgWeight: 0.17,
|
|
31
|
+
poolFlop: 1_200_000_000,
|
|
32
|
+
liquidShare: 0.25,
|
|
33
|
+
};
|
|
34
|
+
const WEEK = 7 * 24 * 3600 * 1000;
|
|
35
|
+
const MAX_PAGES = 400;
|
|
36
|
+
const PAGE_SIZE = 100;
|
|
37
|
+
const DEADLINE_MS = 150_000;
|
|
38
|
+
/**
|
|
39
|
+
* Page through explorer sessions (newest first) until a session opened before the 7-day window.
|
|
40
|
+
* Pages are read four at a time but applied strictly in order; any error, short page, timeout or
|
|
41
|
+
* page cap marks the read as incomplete. Sessions are counted once per channelId.
|
|
42
|
+
*/
|
|
43
|
+
export async function loadDemand(network, explorer, now = Date.now()) {
|
|
44
|
+
const base = explorer.replace(/\/+$/, "");
|
|
45
|
+
const start = now - WEEK;
|
|
46
|
+
const deadline = Date.now() + DEADLINE_MS;
|
|
47
|
+
const byHour = new Array(24).fill(0);
|
|
48
|
+
const miners = new Set();
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
let sessions = 0;
|
|
51
|
+
let pagesRead = 0;
|
|
52
|
+
let rowsScanned = 0;
|
|
53
|
+
let explorerTotal;
|
|
54
|
+
let reachedCutoff = false;
|
|
55
|
+
let reachedEnd = false;
|
|
56
|
+
let stop;
|
|
57
|
+
let next = 0;
|
|
58
|
+
while (!reachedCutoff && !reachedEnd && !stop) {
|
|
59
|
+
if (next >= MAX_PAGES) {
|
|
60
|
+
stop = `page cap of ${MAX_PAGES} reached`;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (Date.now() > deadline) {
|
|
64
|
+
stop = `timed out after ${DEADLINE_MS / 1000} s`;
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
const batch = [0, 1, 2, 3].map((k) => next + k).filter((p) => p < MAX_PAGES);
|
|
68
|
+
next += batch.length;
|
|
69
|
+
const pages = await Promise.all(batch.map((p) => channelPage(base, p).then((r) => r, (e) => e)));
|
|
70
|
+
for (const p of pages) {
|
|
71
|
+
if (p instanceof Error) {
|
|
72
|
+
if (pagesRead === 0)
|
|
73
|
+
throw p;
|
|
74
|
+
stop = `page ${pagesRead + 1} failed: ${p.message}`;
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
pagesRead += 1;
|
|
78
|
+
rowsScanned += p.data.length;
|
|
79
|
+
explorerTotal ??= p.total;
|
|
80
|
+
for (const c of p.data) {
|
|
81
|
+
const t = c.openedAt;
|
|
82
|
+
const id = c.channelId;
|
|
83
|
+
if (typeof t !== "number")
|
|
84
|
+
continue;
|
|
85
|
+
if (t < start) {
|
|
86
|
+
reachedCutoff = true;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (t > now || (id && seen.has(id)))
|
|
90
|
+
continue;
|
|
91
|
+
if (id)
|
|
92
|
+
seen.add(id);
|
|
93
|
+
sessions += 1;
|
|
94
|
+
byHour[new Date(t).getUTCHours()] += 1;
|
|
95
|
+
if (c.miner)
|
|
96
|
+
miners.add(c.miner);
|
|
97
|
+
}
|
|
98
|
+
if (reachedCutoff)
|
|
99
|
+
break;
|
|
100
|
+
if (!p.hasMore) {
|
|
101
|
+
reachedEnd = true;
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
if (p.data.length < PAGE_SIZE) {
|
|
105
|
+
stop = `page ${pagesRead} returned ${p.data.length} rows, expected ${PAGE_SIZE}`;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// The end of the list counts as complete only if every row the explorer reported was read.
|
|
111
|
+
if (reachedEnd && explorerTotal !== undefined && rowsScanned < explorerTotal) {
|
|
112
|
+
stop = `read ${rowsScanned} of ${explorerTotal} rows before the list ended`;
|
|
113
|
+
}
|
|
114
|
+
const complete = !stop && (reachedCutoff || reachedEnd);
|
|
115
|
+
const hours = WEEK / 3600_000;
|
|
116
|
+
const busiest = byHour
|
|
117
|
+
.map((n, hour) => ({ hour, sessions: n }))
|
|
118
|
+
.sort((a, b) => b.sessions - a.sessions || a.hour - b.hour)
|
|
119
|
+
.slice(0, 3);
|
|
120
|
+
return {
|
|
121
|
+
network, explorer: base, fetchedAt: Date.now(), windowStart: start, windowEnd: now,
|
|
122
|
+
sessions, minerCount: miners.size, byHour, perHour: sessions / hours, busiest,
|
|
123
|
+
pagesRead, rowsScanned, explorerTotal, complete, note: stop,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
@@ -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
CHANGED
|
@@ -27,6 +27,9 @@ export function rank(channels) {
|
|
|
27
27
|
r.rate = r.settled + r.timedout ? r.settled / (r.settled + r.timedout) : 0;
|
|
28
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
29
|
}
|
|
30
|
+
export async function channelPage(base, pageIndex) {
|
|
31
|
+
return page(base, pageIndex * PAGE);
|
|
32
|
+
}
|
|
30
33
|
async function page(base, offset) {
|
|
31
34
|
const res = await fetch(`${base}/api/compute-channels?limit=${PAGE}&offset=${offset}`, {
|
|
32
35
|
headers: { "user-agent": UA, accept: "application/json" },
|
package/dist/server.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Public site + read-only MCP over streamable HTTP. No signing, no keys, nothing stored:
|
|
3
3
|
// request bodies are parsed in memory and dropped; there is no request logging.
|
|
4
4
|
import { createServer } from "node:http";
|
|
5
|
-
import { readFileSync, readdirSync } from "node:fs";
|
|
5
|
+
import { readFileSync, readdirSync, realpathSync } from "node:fs";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { GUILD_ROOM, GUILD_ROOM_URL, publicHost, render } from "./config.js";
|
|
@@ -78,7 +78,7 @@ function mdToHtml(md) {
|
|
|
78
78
|
flush();
|
|
79
79
|
return out.join("\n");
|
|
80
80
|
}
|
|
81
|
-
function page(title, body) {
|
|
81
|
+
function page(title, body, o = {}) {
|
|
82
82
|
return `<!doctype html>
|
|
83
83
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
84
84
|
<title>${esc(title)}</title>
|
|
@@ -91,10 +91,11 @@ a{color:var(--accent)}h1,h2,h3{line-height:1.25}
|
|
|
91
91
|
code{background:var(--code);padding:.1em .3em;border-radius:4px;font-size:.92em;overflow-wrap:anywhere}
|
|
92
92
|
pre{background:var(--code);padding:.8rem 1rem;border-radius:6px;overflow-x:auto}pre code{padding:0}
|
|
93
93
|
nav{font-size:.9rem;margin-bottom:1.5rem}footer{border-top:1px solid var(--line);margin-top:2.5rem;padding-top:1rem;color:var(--muted);font-size:.9rem}
|
|
94
|
-
|
|
94
|
+
${o.style ?? ""}
|
|
95
|
+
</style>${o.script ? `<script ${o.module ? 'type="module"' : "defer"} src="${o.script}"></script>` : ""}</head><body><main>
|
|
95
96
|
<nav><a href="/">flop-guild</a></nav>
|
|
96
97
|
${body}
|
|
97
|
-
<footer
|
|
98
|
+
<footer>${o.footerNote ? `<p>${esc(o.footerNote)}</p>` : ""}via flop-guild · <a href="${GUILD_ROOM_URL}">join the guild room ${GUILD_ROOM}</a></footer>
|
|
98
99
|
</main></body></html>`;
|
|
99
100
|
}
|
|
100
101
|
// ---------- read-only MCP tools ----------
|
|
@@ -253,6 +254,31 @@ async function handleRpc(req) {
|
|
|
253
254
|
return err(-32601, "method not found");
|
|
254
255
|
}
|
|
255
256
|
}
|
|
257
|
+
// ---------- /start (browser-only did:key starter) ----------
|
|
258
|
+
const START_FOOTER = "Unofficial community kit, not affiliated with Flop Labs. No airdrop promises.";
|
|
259
|
+
// The page may load only its own scripts and may connect only to technocore.chat.
|
|
260
|
+
const START_CSP = [
|
|
261
|
+
"default-src 'none'",
|
|
262
|
+
"script-src 'self'",
|
|
263
|
+
"style-src 'unsafe-inline'",
|
|
264
|
+
"img-src 'self'",
|
|
265
|
+
"connect-src https://technocore.chat",
|
|
266
|
+
"base-uri 'none'",
|
|
267
|
+
"form-action 'none'",
|
|
268
|
+
"frame-ancestors 'none'",
|
|
269
|
+
].join("; ");
|
|
270
|
+
const START_STYLE = `
|
|
271
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(14rem,1fr));gap:.6rem 1rem}
|
|
272
|
+
label{display:flex;flex-direction:column;font-size:.9rem;color:var(--muted)}label.inline{flex-direction:row;gap:.5rem;align-items:center}
|
|
273
|
+
input[type=text],input[type=password]{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:.4rem .5rem;margin-top:.2rem}
|
|
274
|
+
button{font:inherit;padding:.45rem .9rem;border-radius:6px;border:1px solid var(--accent);background:var(--accent);color:var(--bg);cursor:pointer}
|
|
275
|
+
.msg{color:var(--muted)}.msg.bad{color:#b3261e}#did,#signed-sig,#signed-msg{word-break:break-all}`;
|
|
276
|
+
const STATIC_JS = {
|
|
277
|
+
"/start.js": { file: "start.js", type: "text/javascript; charset=utf-8" },
|
|
278
|
+
"/start-core.js": { file: "start-core.js", type: "text/javascript; charset=utf-8" },
|
|
279
|
+
"/vendor/noble-ed25519-3.2.0.js": { file: "vendor/noble-ed25519-3.2.0.js", type: "text/javascript; charset=utf-8" },
|
|
280
|
+
"/vendor/noble-ed25519-LICENSE.txt": { file: "vendor/noble-ed25519-LICENSE.txt", type: "text/plain; charset=utf-8" },
|
|
281
|
+
};
|
|
256
282
|
// ---------- HTTP ----------
|
|
257
283
|
function send(res, status, type, body, extra = {}) {
|
|
258
284
|
res.writeHead(status, {
|
|
@@ -260,7 +286,7 @@ function send(res, status, type, body, extra = {}) {
|
|
|
260
286
|
"cache-control": "public, max-age=300",
|
|
261
287
|
"x-content-type-options": "nosniff",
|
|
262
288
|
"referrer-policy": "no-referrer",
|
|
263
|
-
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'",
|
|
289
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; script-src 'self'; connect-src 'self'",
|
|
264
290
|
...extra,
|
|
265
291
|
});
|
|
266
292
|
res.end(body);
|
|
@@ -326,6 +352,30 @@ export function startServer(port, host = "0.0.0.0") {
|
|
|
326
352
|
return send(res, 405, "text/plain", "method not allowed\n", { allow: "GET, HEAD" });
|
|
327
353
|
if (path === "/healthz")
|
|
328
354
|
return send(res, 200, "text/plain", "ok\n", { "cache-control": "no-store" });
|
|
355
|
+
if (path === "/start") {
|
|
356
|
+
return send(res, 200, "text/html; charset=utf-8", page("Start: your did:key", render(readFileSync(join(SITE, "start.html"), "utf8")), { footerNote: START_FOOTER, style: START_STYLE, script: "/start.js", module: true }), {
|
|
357
|
+
"content-security-policy": START_CSP,
|
|
358
|
+
"cache-control": "no-store",
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
if (STATIC_JS[path])
|
|
362
|
+
return send(res, 200, STATIC_JS[path].type, readFileSync(join(SITE, STATIC_JS[path].file), "utf8"), { "cache-control": "no-store" });
|
|
363
|
+
if (path === "/miner" || path === "/miner.js" || path === "/api/miner-stats") {
|
|
364
|
+
const mp = await import("./minerpage.js");
|
|
365
|
+
if (path === "/miner.js")
|
|
366
|
+
return send(res, 200, "text/javascript; charset=utf-8", mp.minerScript());
|
|
367
|
+
const v = await mp.demand();
|
|
368
|
+
const d = v?.shown;
|
|
369
|
+
const fresh = { "cache-control": "public, max-age=60" };
|
|
370
|
+
if (path === "/api/miner-stats") {
|
|
371
|
+
const { CALC_DEFAULTS, minerCalc } = await import("./econ.js");
|
|
372
|
+
const body = d
|
|
373
|
+
? { demand: d, partial: v.partial, latestRead: v.partial ? v.latest : undefined, defaults: CALC_DEFAULTS, defaultResult: minerCalc({ ...CALC_DEFAULTS, minerCount: d.minerCount }), disclaimer: mp.MINER_FOOTER }
|
|
374
|
+
: { error: mp.demandError() ?? "loading, try again in a minute", disclaimer: mp.MINER_FOOTER };
|
|
375
|
+
return send(res, d ? 200 : 503, "application/json", JSON.stringify(body, null, 2), fresh);
|
|
376
|
+
}
|
|
377
|
+
return send(res, 200, "text/html; charset=utf-8", page("Miner economics", mp.minerPage(v, mp.demandError()), { footerNote: mp.MINER_FOOTER, style: mp.MINER_STYLE, script: "/miner.js" }), fresh);
|
|
378
|
+
}
|
|
329
379
|
if (path === "/")
|
|
330
380
|
return send(res, 200, "text/html; charset=utf-8", page("flop-guild", render(readFileSync(join(SITE, "index.html"), "utf8"))));
|
|
331
381
|
if (path === "/llms.txt")
|
|
@@ -348,7 +398,16 @@ export function startServer(port, host = "0.0.0.0") {
|
|
|
348
398
|
server.listen(port, host);
|
|
349
399
|
return server;
|
|
350
400
|
}
|
|
351
|
-
|
|
401
|
+
/** True when this file is the entry point, including through an npm bin symlink. */
|
|
402
|
+
function isMain() {
|
|
403
|
+
try {
|
|
404
|
+
return !!process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (isMain()) {
|
|
352
411
|
const port = Number(process.env.PORT || 8080);
|
|
353
412
|
startServer(port, process.env.HOST || "0.0.0.0");
|
|
354
413
|
process.stdout.write(`flop-guild site on :${port} for ${publicHost()}\n`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flop-guild",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Technocore guild kit: Ed25519 did:key signing CLI for technocore.chat rooms, plus an agent identity scaffold.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -42,10 +42,11 @@
|
|
|
42
42
|
"@flop-labs/sdk": "0.7.1",
|
|
43
43
|
"@polkadot/api": "17.0.2",
|
|
44
44
|
"@polkadot/keyring": "14.0.3",
|
|
45
|
-
"@polkadot/util
|
|
46
|
-
"@polkadot/util": "14.0.3"
|
|
45
|
+
"@polkadot/util": "14.0.3",
|
|
46
|
+
"@polkadot/util-crypto": "14.0.3"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
+
"@noble/ed25519": "3.2.0",
|
|
49
50
|
"@types/node": "^22.9.0",
|
|
50
51
|
"typescript": "^5.6.3"
|
|
51
52
|
}
|
package/site/index.html
CHANGED
|
@@ -4,9 +4,11 @@ did:key chat, a devnet wallet, faucet claims, gateway enrollment and capped infe
|
|
|
4
4
|
Devnet FLOP is a test token with no value.</p>
|
|
5
5
|
<h2>Guides</h2>
|
|
6
6
|
<ul>
|
|
7
|
+
<li><a href="/start">Start</a>: make a did:key in your browser and say hello in the guild room</li>
|
|
7
8
|
<li><a href="/guides/join-guild">Join the guild</a></li>
|
|
8
9
|
<li><a href="/guides/agent-quickstart">Agent quick start</a></li>
|
|
9
10
|
<li><a href="/guides/autopilot">Autopilot</a></li>
|
|
11
|
+
<li><a href="/miner">Miner economics</a>: demand by hour and a rent vs airdrop calculator</li>
|
|
10
12
|
</ul>
|
|
11
13
|
<h2>For agents</h2>
|
|
12
14
|
<ul>
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// flop-guild /start core: Ed25519 did:key, Technocore signing and passphrase encryption.
|
|
2
|
+
// Pure functions, no network access except post(). Runs in browsers and in Node 22.
|
|
3
|
+
import * as ed from "./vendor/noble-ed25519-3.2.0.js";
|
|
4
|
+
|
|
5
|
+
export const ROOM = "d-flopguild";
|
|
6
|
+
export const TAG = "(via flop-guild)";
|
|
7
|
+
export const TECHNOCORE = "https://technocore.chat";
|
|
8
|
+
export const PBKDF2_ITERATIONS = 600000;
|
|
9
|
+
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
10
|
+
const enc = new TextEncoder();
|
|
11
|
+
|
|
12
|
+
export function base58btc(bytes) {
|
|
13
|
+
let n = 0n;
|
|
14
|
+
for (const b of bytes) n = (n << 8n) | BigInt(b);
|
|
15
|
+
let out = "";
|
|
16
|
+
while (n > 0n) {
|
|
17
|
+
out = B58[Number(n % 58n)] + out;
|
|
18
|
+
n /= 58n;
|
|
19
|
+
}
|
|
20
|
+
for (const b of bytes) {
|
|
21
|
+
if (b !== 0) break;
|
|
22
|
+
out = "1" + out;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function didFromPublicKey(pub) {
|
|
28
|
+
const buf = new Uint8Array(34);
|
|
29
|
+
buf[0] = 0xed;
|
|
30
|
+
buf[1] = 0x01;
|
|
31
|
+
buf.set(pub, 2);
|
|
32
|
+
return "did:key:z" + base58btc(buf);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function b64url(bytes) {
|
|
36
|
+
let s = "";
|
|
37
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
38
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function fromB64url(s) {
|
|
42
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
|
|
43
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Technocore's sweep: Cc, Cf, Cs, Co, Zl, Zp become spaces, then trim. No normalization. */
|
|
47
|
+
export function cleanText(text) {
|
|
48
|
+
return String(text).replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Zl}\p{Zp}]/gu, " ").trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function withTag(text) {
|
|
52
|
+
const t = cleanText(text);
|
|
53
|
+
return t.endsWith(TAG) ? t : cleanText(`${t} ${TAG}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function newKey() {
|
|
57
|
+
const secret = ed.utils.randomSecretKey();
|
|
58
|
+
const pub = await ed.getPublicKeyAsync(secret);
|
|
59
|
+
return { secret, pub, did: didFromPublicKey(pub) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Sign "<room>|<nonce>|<text>" and build the say-signed URL. Nothing is sent. */
|
|
63
|
+
export async function signIntro(key, text, nonce = Date.now(), room = ROOM) {
|
|
64
|
+
const clean = withTag(text);
|
|
65
|
+
if (!clean.replace(TAG, "").trim()) throw new Error("write an introduction first");
|
|
66
|
+
if ([...clean].length > 4096) throw new Error("introduction is longer than 4096 characters");
|
|
67
|
+
const n = String(nonce);
|
|
68
|
+
if (!/^\d{1,19}$/.test(n)) throw new Error("bad nonce");
|
|
69
|
+
const message = `${room}|${n}|${clean}`;
|
|
70
|
+
const sig = b64url(await ed.signAsync(enc.encode(message), key.secret));
|
|
71
|
+
const url = `${TECHNOCORE}/r/${room}/say-signed/${key.did}/${sig}/${n}/${encodeURIComponent(clean)}`;
|
|
72
|
+
return { room, nonce: n, text: clean, message, sig, url };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The only network call in this module. */
|
|
76
|
+
export async function post(signed) {
|
|
77
|
+
const res = await fetch(signed.url, { method: "GET", credentials: "omit", cache: "no-store", referrerPolicy: "no-referrer" });
|
|
78
|
+
return { status: res.status, body: (await res.text()).slice(0, 500) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** PKCS#8 PEM for an Ed25519 seed, the same format the flop-guild CLI stores. */
|
|
82
|
+
export function pkcs8Pem(secret) {
|
|
83
|
+
const prefix = [0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20];
|
|
84
|
+
const der = new Uint8Array(48);
|
|
85
|
+
der.set(prefix, 0);
|
|
86
|
+
der.set(secret, 16);
|
|
87
|
+
let s = "";
|
|
88
|
+
for (const b of der) s += String.fromCharCode(b);
|
|
89
|
+
return `-----BEGIN PRIVATE KEY-----\n${btoa(s)}\n-----END PRIVATE KEY-----\n`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function aesKey(passphrase, salt, iterations) {
|
|
93
|
+
const base = await crypto.subtle.importKey("raw", enc.encode(passphrase), "PBKDF2", false, ["deriveKey"]);
|
|
94
|
+
return crypto.subtle.deriveKey({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Encrypt the key with PBKDF2-SHA256 + AES-256-GCM. Passphrase: 12+ characters. */
|
|
98
|
+
export async function encryptKey(key, passphrase) {
|
|
99
|
+
if ([...String(passphrase)].length < 12) throw new Error("passphrase must be at least 12 characters");
|
|
100
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
101
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
102
|
+
const k = await aesKey(passphrase, salt, PBKDF2_ITERATIONS);
|
|
103
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(key.did) }, k, enc.encode(pkcs8Pem(key.secret))));
|
|
104
|
+
return {
|
|
105
|
+
format: "flop-guild-key/1",
|
|
106
|
+
did: key.did,
|
|
107
|
+
kdf: { name: "PBKDF2", hash: "SHA-256", iterations: PBKDF2_ITERATIONS, salt: b64url(salt) },
|
|
108
|
+
cipher: { name: "AES-256-GCM", iv: b64url(iv), aad: "did" },
|
|
109
|
+
ciphertext: b64url(ct),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function decryptKey(file, passphrase) {
|
|
114
|
+
const k = await aesKey(passphrase, fromB64url(file.kdf.salt), file.kdf.iterations);
|
|
115
|
+
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromB64url(file.cipher.iv), additionalData: enc.encode(file.did) }, k, fromB64url(file.ciphertext));
|
|
116
|
+
return new TextDecoder().decode(pt);
|
|
117
|
+
}
|
package/site/start.html
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
<h1>Start: your did:key in the browser</h1>
|
|
2
|
+
<p>Make an Ed25519 identity here, keep it, and say hello in the open guild room. The key is made by
|
|
3
|
+
code served from this site; nothing is fetched from anywhere else, and the page can only talk to
|
|
4
|
+
technocore.chat.</p>
|
|
5
|
+
|
|
6
|
+
<h2>1. Make a key</h2>
|
|
7
|
+
<p><button id="gen" type="button">Generate a new key</button></p>
|
|
8
|
+
<p id="gen-msg" class="msg" aria-live="polite"></p>
|
|
9
|
+
<p>Your did:key: <code id="did">none yet</code></p>
|
|
10
|
+
|
|
11
|
+
<section id="step2" hidden>
|
|
12
|
+
<h2>2. Download it, encrypted</h2>
|
|
13
|
+
<p>Pick a passphrase of at least 12 characters. The file is encrypted with PBKDF2 (SHA-256,
|
|
14
|
+
600,000 rounds) and AES-256-GCM before it leaves this page.</p>
|
|
15
|
+
<div class="grid">
|
|
16
|
+
<label>Passphrase<input id="pass" type="password" autocomplete="new-password" minlength="12"></label>
|
|
17
|
+
<label>Repeat passphrase<input id="pass2" type="password" autocomplete="new-password" minlength="12"></label>
|
|
18
|
+
</div>
|
|
19
|
+
<p><button id="save" type="button">Download encrypted key</button></p>
|
|
20
|
+
<p id="save-msg" class="msg" aria-live="polite"></p>
|
|
21
|
+
</section>
|
|
22
|
+
|
|
23
|
+
<section id="step3" hidden>
|
|
24
|
+
<h2>3. Introduce yourself (optional)</h2>
|
|
25
|
+
<p>One line, signed with your key as <code>{{ROOM}}|<nonce>|<text></code> and posted to
|
|
26
|
+
<a href="{{ROOM_URL}}">{{ROOM}}</a>. The kit adds <code>(via flop-guild)</code>. The room is public and has
|
|
27
|
+
no owner; this page never claims it.</p>
|
|
28
|
+
<label>Introduction<input id="intro" type="text" maxlength="400" placeholder="hi, I am building an agent for ..."></label>
|
|
29
|
+
<p><label class="inline"><input id="dry" type="checkbox"> Dry run: sign, but do not post</label></p>
|
|
30
|
+
<p><button id="sign" type="button">Sign and post</button></p>
|
|
31
|
+
<p id="sign-msg" class="msg" aria-live="polite"></p>
|
|
32
|
+
<div id="signed" hidden>
|
|
33
|
+
<p>Signed message: <code id="signed-msg"></code></p>
|
|
34
|
+
<p>Signature: <code id="signed-sig"></code></p>
|
|
35
|
+
</div>
|
|
36
|
+
</section>
|
|
37
|
+
|
|
38
|
+
<h2>Next step</h2>
|
|
39
|
+
<pre><code>npx flop-guild setup</code></pre>
|
|
40
|
+
<p>It sets up the wallet, faucet, enrollment and autopilot from your terminal. See the
|
|
41
|
+
<a href="/guides/agent-quickstart">agent quick start</a>.</p>
|