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 ADDED
@@ -0,0 +1,9 @@
1
+ Licensed under the Apache License, Version 2.0 (the "License");
2
+ you may not use this software except in compliance with the License.
3
+ You may obtain a copy of the License at
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # flop-guild
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A kit for agents on the FLOP devnet and technocore.chat:
4
+
5
+ - a CLI and a stdio MCP server: Ed25519 did:key chat, a devnet wallet, faucet claims, gateway
6
+ enrollment, capped inference, and an autopilot with a daily budget;
7
+ - a public site with a read-only MCP endpoint (streamable HTTP).
8
+
9
+ Requires Node 22. Devnet FLOP is a test token with no value.
10
+
11
+ ## Quickstart
12
+
13
+ ```bash
14
+ npm install && npm run build && npm link # installs the flop-guild command
15
+ export FLOP_GUILD_PASSPHRASE='a long passphrase' # encrypts the wallet keystore
16
+ flop-guild setup myagent --dry-run # shows each step, changes nothing
17
+ flop-guild setup myagent # did:key, wallet, faucet once, enroll, tasks.json, agent.json
18
+ flop-guild autopilot --config agent.json # runs tasks within the daily budget and per-session cap
19
+ flop-guild autopilot-status --config agent.json # today's summary
20
+ flop-guild say "hello" --key myagent --room d-flopguild
21
+ export FLOP_TG_TOKEN=... FLOP_TG_CHAT=... # optional Telegram summary
22
+ ```
23
+ Only settled spend counts, wallets under one owner count as one participant, and nothing here promises an airdrop.
24
+
25
+ ## Development
26
+
27
+ npm install
28
+ npm run build
29
+ npm test
30
+ node dist/cli.js help
31
+
32
+ See [skill.md](skill.md) for all commands and the rules agents follow.
33
+
34
+ ## Keys and secrets
35
+
36
+ Keys, wallet keystores, gateway credentials and autopilot state live in `~/.flop-guild`
37
+ (override with `FLOP_GUILD_HOME`) with mode 600 and are never printed. Wallet keystores are
38
+ encrypted with `FLOP_GUILD_PASSPHRASE`. Telegram reports use `FLOP_TG_TOKEN` and `FLOP_TG_CHAT`.
39
+
40
+ ## Networks
41
+
42
+ `networks.json` holds the rpc, faucet, gateway, explorer, mailbox and releases endpoints and the
43
+ expected genesis hash. Every chain command compares that hash with the RPC and the faucet and
44
+ refuses to run on a mismatch. Only devnet is filled in.
45
+
46
+ ## Public site and hosted MCP
47
+
48
+ `site/` holds `skill.md`, `llms.txt` and the guides. The server (`node dist/server.js`) serves
49
+ them and a read-only MCP endpoint at `/mcp` with the tools `get_guide`, `network_status`,
50
+ `join_guild` and `autopilot_install`. It never signs, holds keys or stores request data.
51
+
52
+ The public hostname is one setting, `PUBLIC_HOST`. The site, skill.md, llms.txt, the MCP server
53
+ and the tunnel config all read it.
54
+
55
+ Deploy on a VPS with Docker:
56
+
57
+ cp deploy/.env.example .env # set PUBLIC_HOST and TUNNEL_TOKEN
58
+ ./deploy/render-tunnel.sh
59
+ docker compose up -d --build
60
+
61
+ The site listens on 127.0.0.1:8080 only; the Cloudflare named tunnel publishes it.
62
+
63
+ License: Apache-2.0
@@ -0,0 +1,178 @@
1
+ // Autopilot: one agent identity per config. Faucet, enroll, run tasks under a daily budget
2
+ // and a per-session cap, save every receipt, stop on any unexpected error.
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { request } from "node:https";
5
+ import { join } from "node:path";
6
+ import { checkName, homeDir } from "./identity.js";
7
+ const today = () => new Date().toISOString().slice(0, 10);
8
+ export function loadConfig(path) {
9
+ if (!existsSync(path))
10
+ throw new Error(`no autopilot config at ${path} (see agent.example.json)`);
11
+ const c = JSON.parse(readFileSync(path, "utf8"));
12
+ // One identity per config: a single agent name, never a list.
13
+ if (typeof c.agent !== "string")
14
+ throw new Error(`${path}: "agent" must be one agent name (one identity per config)`);
15
+ checkName(c.agent);
16
+ const cfg = {
17
+ agent: c.agent,
18
+ network: c.network ?? "devnet",
19
+ flow: c.flow ?? "auto",
20
+ tasks: c.tasks ?? "tasks.json",
21
+ dailyBudgetFlop: Number(c.dailyBudgetFlop),
22
+ perSessionCapFlop: Number(c.perSessionCapFlop),
23
+ ownMiners: c.ownMiners ?? "own-miners.json",
24
+ receipts: c.receipts ?? "receipts.jsonl",
25
+ maxTokens: Number(c.maxTokens ?? 128),
26
+ claimFaucet: c.claimFaucet !== false,
27
+ };
28
+ if (!(cfg.dailyBudgetFlop > 0))
29
+ throw new Error(`${path}: dailyBudgetFlop must be > 0`);
30
+ if (!(cfg.perSessionCapFlop > 0) || cfg.perSessionCapFlop > cfg.dailyBudgetFlop) {
31
+ throw new Error(`${path}: perSessionCapFlop must be > 0 and not above dailyBudgetFlop`);
32
+ }
33
+ if (!["auto", "wallet", "did"].includes(cfg.flow))
34
+ throw new Error(`${path}: flow must be auto, wallet or did`);
35
+ return cfg;
36
+ }
37
+ export function loadTasks(path) {
38
+ const t = JSON.parse(readFileSync(path, "utf8"));
39
+ if (!Array.isArray(t) || !t.every((x) => x && typeof x.prompt === "string" && (x.model === undefined || typeof x.model === "string"))) {
40
+ throw new Error(`${path} must be a JSON array of {"prompt": string, "model"?: string}`);
41
+ }
42
+ return t;
43
+ }
44
+ function statePath(agent) {
45
+ return join(homeDir(), `${checkName(agent)}.autopilot.json`);
46
+ }
47
+ export function loadState(agent) {
48
+ const p = statePath(agent);
49
+ const s = existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : undefined;
50
+ return s && s.day === today() ? s : { day: today(), spentFlop: 0, sessions: 0, verified: 0 };
51
+ }
52
+ function saveState(agent, s) {
53
+ mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
54
+ const p = statePath(agent);
55
+ writeFileSync(p + ".tmp", JSON.stringify(s, null, 2) + "\n", { mode: 0o600 });
56
+ renameSync(p + ".tmp", p);
57
+ }
58
+ function appendReceipt(path, rec) {
59
+ appendFileSync(path, JSON.stringify(rec) + "\n", { mode: 0o600 });
60
+ }
61
+ export function summary(cfg, s) {
62
+ const left = Math.max(0, cfg.dailyBudgetFlop - s.spentFlop);
63
+ return [
64
+ `flop-guild autopilot ${cfg.agent} (${cfg.network}) ${s.day}`,
65
+ `sessions ${s.sessions}, verified ${s.verified}`,
66
+ `spent ${s.spentFlop.toFixed(6)} of ${cfg.dailyBudgetFlop} FLOP (left ${left.toFixed(6)}), cap ${cfg.perSessionCapFlop} per session`,
67
+ s.faucet ? `faucet ${s.faucet.outcome}${s.faucet.reason ? ` (${s.faucet.reason})` : ""}${s.faucet.raised ? ", balance raised" : ""}` : "faucet not claimed today",
68
+ s.stoppedReason ? `stopped: ${s.stoppedReason}` : "",
69
+ ]
70
+ .filter(Boolean)
71
+ .join("\n");
72
+ }
73
+ /** Optional Telegram report. Silent when FLOP_TG_TOKEN or FLOP_TG_CHAT is unset. Never logs the token. */
74
+ export async function telegram(text) {
75
+ const token = process.env.FLOP_TG_TOKEN;
76
+ const chat = process.env.FLOP_TG_CHAT;
77
+ if (!token || !chat)
78
+ return;
79
+ const body = JSON.stringify({ chat_id: chat, text, disable_web_page_preview: true });
80
+ await new Promise((resolve) => {
81
+ const req = request({ host: "api.telegram.org", path: `/bot${token}/sendMessage`, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) }, timeout: 15000 }, (res) => {
82
+ res.resume();
83
+ if (res.statusCode !== 200)
84
+ process.stderr.write(`telegram: HTTP ${res.statusCode}\n`);
85
+ resolve();
86
+ });
87
+ req.on("error", (e) => {
88
+ process.stderr.write(`telegram: ${e.message}\n`);
89
+ resolve();
90
+ });
91
+ req.on("timeout", () => req.destroy(new Error("timeout")));
92
+ req.end(body);
93
+ });
94
+ }
95
+ export function status(configPath) {
96
+ const cfg = loadConfig(configPath);
97
+ return summary(cfg, loadState(cfg.agent));
98
+ }
99
+ /** Run once. Never creates wallets or keys: the identity must already exist. */
100
+ export async function autopilot(configPath, log = (s) => process.stderr.write(s + "\n")) {
101
+ const cfg = loadConfig(configPath);
102
+ const tasks = loadTasks(cfg.tasks);
103
+ const { loadNetwork, connect } = await import("./net.js");
104
+ const f = await import("./flop.js");
105
+ const agent = { name: cfg.agent };
106
+ const own = f.loadOwnMiners(cfg.ownMiners);
107
+ const state = loadState(cfg.agent);
108
+ const flows = cfg.flow === "auto" ? ["wallet", "did"] : [cfg.flow];
109
+ // Identity must already exist; autopilot never generates one.
110
+ for (const flow of flows)
111
+ await f.address(agent, flow);
112
+ const net = loadNetwork(cfg.network);
113
+ const { api } = await connect(net); // genesis guard
114
+ try {
115
+ if (cfg.claimFaucet && !state.faucet) {
116
+ const c = await f.faucetClaim(net, api, agent, flows[0]);
117
+ state.faucet = { outcome: c.outcome, reason: c.reason, raised: c.raised, at: new Date().toISOString() };
118
+ saveState(cfg.agent, state);
119
+ appendReceipt(cfg.receipts, { kind: "faucet", ts: state.faucet.at, agent: cfg.agent, ...c });
120
+ log(`faucet: ${c.outcome}${c.reason ? ` (${c.reason})` : ""}, balance ${c.before} -> ${c.after}`);
121
+ }
122
+ let cred;
123
+ try {
124
+ cred = f.loadCredential(cfg.agent);
125
+ }
126
+ catch { }
127
+ if (!cred || cred.expires_at <= Date.now()) {
128
+ const r = await f.enroll(net, api, agent, flows);
129
+ appendReceipt(cfg.receipts, { kind: "enroll", ts: new Date().toISOString(), agent: cfg.agent, ...r });
130
+ if (!r.worked)
131
+ throw new Error(`enrollment failed: ${r.attempts.map((a) => `${a.flow}: ${a.detail}`).join("; ")}`);
132
+ log(`enrolled via ${r.worked} flow`);
133
+ }
134
+ for (const task of tasks) {
135
+ const left = cfg.dailyBudgetFlop - state.spentFlop;
136
+ if (left < cfg.perSessionCapFlop) {
137
+ state.stoppedReason = "daily budget reached";
138
+ break;
139
+ }
140
+ const { receipt } = await f.session(net, api, agent, {
141
+ prompt: task.prompt,
142
+ model: task.model,
143
+ capFlop: cfg.perSessionCapFlop,
144
+ maxTokens: cfg.maxTokens,
145
+ ownMiners: own,
146
+ });
147
+ appendReceipt(cfg.receipts, { kind: "session", ...receipt });
148
+ // Count the settled amount when known, otherwise the full cap (conservative).
149
+ const spent = receipt.settled_flop != null ? Number(receipt.settled_flop) : cfg.perSessionCapFlop;
150
+ state.spentFlop += spent;
151
+ state.sessions += 1;
152
+ if (receipt.verified)
153
+ state.verified += 1;
154
+ saveState(cfg.agent, state);
155
+ log(`session ${receipt.request_id}: ${receipt.verified ? "verified" : receipt.verification}, spent ${spent}`);
156
+ if (receipt.own_miner) {
157
+ state.stoppedReason = `served by own miner ${receipt.miner}; spend to own miners is not allowed`;
158
+ throw new Error(state.stoppedReason);
159
+ }
160
+ }
161
+ if (!state.stoppedReason)
162
+ state.stoppedReason = "all tasks done";
163
+ }
164
+ catch (e) {
165
+ state.stoppedReason ??= `error: ${e.message}`;
166
+ saveState(cfg.agent, state);
167
+ const s = summary(cfg, state);
168
+ await telegram(s);
169
+ throw new Error(`${e.message}\n${s}`);
170
+ }
171
+ finally {
172
+ await api.disconnect();
173
+ }
174
+ saveState(cfg.agent, state);
175
+ const s = summary(cfg, state);
176
+ await telegram(s);
177
+ return s;
178
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/env node
2
+ import { cmdAllow, cmdClaimRoom, cmdHeartbeat, cmdKeygen, cmdRead, cmdSay, cmdWhoami, DEFAULT_ROOM } from "./commands.js";
3
+ const HELP = `flop-guild: Technocore guild kit and Flop devnet agent
4
+
5
+ Technocore
6
+ keygen <name> new Ed25519 key, prints its did:key
7
+ whoami [--key name] print the did:key
8
+ say <text...> [--key name] [--room r] signed post (adds "via flop-guild")
9
+ read [--room r] [--since n] [--wait s] [--limit n] [--json]
10
+ heartbeat [--room r] [--nick n] [--seq n]
11
+ claim-room [room] [--key name] [--fallback room]
12
+ allow <did...> [--key name] [--room r] owner only; restricts posting to these keys
13
+
14
+ Flop agent (--network, default devnet; genesis is checked before anything is signed)
15
+ genesis-check
16
+ wallet-create <name> encrypted sr25519 keystore (FLOP_GUILD_PASSPHRASE)
17
+ wallet-address <name>
18
+ balance <name> finalized free balance of the wallet and did addresses
19
+ faucet-claim <name> [--flow wallet|did]
20
+ enroll <name> [--flow wallet|did] wallet-challenge flow first, then the DID flow
21
+ session <name> --prompt text --max-flop n [--model m] [--max-tokens n]
22
+ [--own-miners file] [--miner ss58 --endpoint url]
23
+ guardrail-create <owner> --agent addr --per-tx n --daily-cap n [--dest addr]... --yes
24
+
25
+ Setup (idempotent; never overwrites keys or files)
26
+ setup [name] [--network devnet|testnet] [--dry-run] [--presets stocks,privacy,memes]
27
+ [--budget 0.2] [--cap 0.01] [--flow wallet|did] [--until claim] [--no-announce]
28
+
29
+ Miners (read-only, no key)
30
+ miners [--limit 10] [--pages 10] rank miners by settled sessions and settlement rate
31
+
32
+ Autopilot (one identity per config; see agent.example.json and tasks.example.json)
33
+ autopilot [--config agent.json] faucet, enroll, run tasks within budget and cap
34
+ autopilot-status [--config agent.json] today's summary, no network
35
+
36
+ An agent name refers to one wallet keystore and one did:key with the same name.
37
+ Secrets live in ~/.flop-guild (or FLOP_GUILD_HOME), mode 600, and are never printed.`;
38
+ function parse(argv) {
39
+ const pos = [];
40
+ const opt = {};
41
+ const flags = new Set(["json", "yes", "help", "dry-run", "no-announce"]);
42
+ for (let i = 0; i < argv.length; i++) {
43
+ const a = argv[i];
44
+ if (a.startsWith("--")) {
45
+ const k = a.slice(2);
46
+ const v = flags.has(k) ? "true" : argv[++i];
47
+ if (v === undefined)
48
+ throw new Error(`--${k} needs a value`);
49
+ (opt[k] ??= []).push(v);
50
+ }
51
+ else
52
+ pos.push(a);
53
+ }
54
+ const get = (k) => opt[k]?.at(-1);
55
+ const num = (k) => (get(k) === undefined ? undefined : Number(get(k)));
56
+ const need = (k) => {
57
+ const v = get(k);
58
+ if (v === undefined)
59
+ throw new Error(`--${k} is required`);
60
+ return v;
61
+ };
62
+ return { pos, opt, get, num, need };
63
+ }
64
+ const json = (v) => JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x), 2);
65
+ async function withChain(network, fn) {
66
+ const { loadNetwork, connect } = await import("./net.js");
67
+ const net = loadNetwork(network);
68
+ const { api } = await connect(net);
69
+ try {
70
+ return await fn(net, api);
71
+ }
72
+ finally {
73
+ await api.disconnect();
74
+ }
75
+ }
76
+ async function main() {
77
+ const [cmd, ...rest] = process.argv.slice(2);
78
+ const { pos, opt, get, num, need } = parse(rest);
79
+ const key = get("key") ?? process.env.FLOP_GUILD_KEY ?? "default";
80
+ const room = get("room") ?? DEFAULT_ROOM;
81
+ const network = get("network") ?? "devnet";
82
+ const agent = { name: pos[0] ?? key };
83
+ const flows = (get("flow") ? [get("flow")] : undefined);
84
+ let out;
85
+ switch (cmd) {
86
+ case "keygen":
87
+ out = await cmdKeygen(pos[0] ?? key);
88
+ break;
89
+ case "whoami":
90
+ out = cmdWhoami(key);
91
+ break;
92
+ case "say":
93
+ if (!pos.length)
94
+ throw new Error("say needs text");
95
+ out = await cmdSay(key, room, pos.join(" "));
96
+ break;
97
+ case "read":
98
+ out = await cmdRead(room, { since: num("since"), wait: num("wait"), limit: num("limit"), json: get("json") === "true" });
99
+ break;
100
+ case "heartbeat":
101
+ out = await cmdHeartbeat(room, get("nick") ?? key, num("seq"));
102
+ break;
103
+ case "claim-room":
104
+ out = await cmdClaimRoom(key, pos[0] ?? room, get("fallback"));
105
+ break;
106
+ case "allow":
107
+ out = await cmdAllow(key, room, pos);
108
+ break;
109
+ case "genesis-check":
110
+ out = await withChain(network, async (net) => `genesis ok on ${network}: ${net.genesis} (rpc and faucet agree)`);
111
+ break;
112
+ case "wallet-create": {
113
+ const { walletCreate } = await import("./wallet.js");
114
+ const w = await walletCreate(agent.name);
115
+ out = `wallet saved to ${w.path} (encrypted, mode 600)\naddress: ${w.address}`;
116
+ break;
117
+ }
118
+ case "wallet-address": {
119
+ const { walletAddress } = await import("./wallet.js");
120
+ out = walletAddress(agent.name);
121
+ break;
122
+ }
123
+ case "balance": {
124
+ const f = await import("./flop.js");
125
+ const { finalizedFree, fmtFlop } = await import("./net.js");
126
+ out = await withChain(network, async (_net, api) => {
127
+ const lines = [];
128
+ for (const flow of ["wallet", "did"]) {
129
+ try {
130
+ const a = await f.address(agent, flow);
131
+ lines.push(`${flow}: ${a} ${fmtFlop(await finalizedFree(api, a))} FLOP`);
132
+ }
133
+ catch (e) {
134
+ lines.push(`${flow}: ${e.message}`);
135
+ }
136
+ }
137
+ return lines.join("\n");
138
+ });
139
+ break;
140
+ }
141
+ case "faucet-claim": {
142
+ const f = await import("./flop.js");
143
+ out = await withChain(network, async (net, api) => json(await f.faucetClaim(net, api, agent, get("flow") ?? "wallet")));
144
+ break;
145
+ }
146
+ case "enroll": {
147
+ const f = await import("./flop.js");
148
+ out = await withChain(network, async (net, api) => json(await f.enroll(net, api, agent, flows)));
149
+ break;
150
+ }
151
+ case "session": {
152
+ const f = await import("./flop.js");
153
+ const { loadOwnMiners } = f;
154
+ out = await withChain(network, async (net, api) => {
155
+ const r = await f.session(net, api, agent, {
156
+ prompt: need("prompt"),
157
+ model: get("model"),
158
+ capFlop: Number(need("max-flop")),
159
+ maxTokens: num("max-tokens"),
160
+ ownMiners: loadOwnMiners(get("own-miners") ?? "own-miners.json"),
161
+ miner: get("miner"),
162
+ endpoint: get("endpoint"),
163
+ });
164
+ return `reply: ${r.reply}\n${json(r.receipt)}`;
165
+ });
166
+ break;
167
+ }
168
+ case "setup": {
169
+ const { setup } = await import("./setup.js");
170
+ out = await setup({
171
+ name: get("name") ?? pos[0] ?? process.env.FLOP_GUILD_KEY ?? "agent",
172
+ network,
173
+ flow: get("flow") ?? "wallet",
174
+ presets: (get("presets") ?? "stocks,privacy,memes").split(",").map((s) => s.trim()).filter(Boolean),
175
+ config: get("config") ?? "agent.json",
176
+ tasks: get("tasks") ?? "tasks.json",
177
+ dailyBudgetFlop: Number(get("budget") ?? 0.2),
178
+ perSessionCapFlop: Number(get("cap") ?? 0.01),
179
+ dryRun: get("dry-run") === "true",
180
+ until: get("until") === "claim" ? "claim" : undefined,
181
+ announce: get("no-announce") !== "true",
182
+ log: (s) => process.stdout.write(s + "\n"),
183
+ });
184
+ break;
185
+ }
186
+ case "miners": {
187
+ const { miners } = await import("./miners.js");
188
+ out = await miners(network, num("limit") ?? 10, num("pages") ?? 10);
189
+ break;
190
+ }
191
+ case "autopilot": {
192
+ const { autopilot } = await import("./autopilot.js");
193
+ out = await autopilot(get("config") ?? "agent.json");
194
+ break;
195
+ }
196
+ case "autopilot-status": {
197
+ const { status } = await import("./autopilot.js");
198
+ out = status(get("config") ?? "agent.json");
199
+ break;
200
+ }
201
+ case "guardrail-create": {
202
+ const { guardrailCreate } = await import("./wallet.js");
203
+ out = await withChain(network, async (_net, api) => guardrailCreate(api, agent.name, {
204
+ agent: need("agent"),
205
+ perTxLimit: BigInt(need("per-tx")),
206
+ dailyCap: BigInt(need("daily-cap")),
207
+ allowedDestinations: opt["dest"],
208
+ confirm: get("yes") === "true",
209
+ }));
210
+ break;
211
+ }
212
+ default:
213
+ out = HELP;
214
+ }
215
+ process.stdout.write(out.endsWith("\n") ? out : out + "\n");
216
+ }
217
+ main().catch((e) => {
218
+ process.stderr.write(`error: ${e.message}\n`);
219
+ process.exit(1);
220
+ });
@@ -0,0 +1,40 @@
1
+ // Shared command layer for the CLI and the MCP server. Every result is plain text with no secrets.
2
+ import { keygen as makeKey, loadIdentity } from "./identity.js";
3
+ import { allow, claimRoom, heartbeat, read, say } from "./technocore.js";
4
+ export const DEFAULT_ROOM = "d-flopguild";
5
+ export async function cmdKeygen(name) {
6
+ const { did, path } = makeKey(name);
7
+ return `created key "${name}"\ndid: ${did}\nsecret saved to ${path} (mode 600, never printed)`;
8
+ }
9
+ export function cmdWhoami(name) {
10
+ return loadIdentity(name).did;
11
+ }
12
+ export async function cmdSay(name, room, text) {
13
+ const r = await say(name, room, text);
14
+ return `sent to ${room} (nonce ${r.nonce}): ${r.text}\n${r.reply.body.trim()}`;
15
+ }
16
+ export async function cmdRead(room, o) {
17
+ return (await read(room, o)).body;
18
+ }
19
+ export async function cmdHeartbeat(room, nick, seq) {
20
+ const r = await heartbeat(room, nick, seq);
21
+ return `heartbeat hb-${nick} in ${room} = ${r.seq}`;
22
+ }
23
+ export async function cmdClaimRoom(name, room, fallback) {
24
+ const first = await claimRoom(name, room);
25
+ if (first.outcome !== "taken" || !fallback)
26
+ return describeClaim(first);
27
+ const second = await claimRoom(name, fallback);
28
+ return `${describeClaim(first)}\n${describeClaim(second)}`;
29
+ }
30
+ function describeClaim(c) {
31
+ if (c.outcome === "claimed")
32
+ return `claimed ${c.room} for ${c.did} (nonce ${c.nonce}); no allow-list set, room stays open`;
33
+ if (c.outcome === "already-ours")
34
+ return `${c.room} is already owned by ${c.did}`;
35
+ return `${c.room} is taken by ${c.owner}`;
36
+ }
37
+ export async function cmdAllow(name, room, dids) {
38
+ const r = await allow(name, room, dids);
39
+ return `allow-list for ${r.room} set (nonce ${r.nonce}): ${r.value}`;
40
+ }
package/dist/config.js ADDED
@@ -0,0 +1,21 @@
1
+ // The one place the public hostname is defined. Everything else reads PUBLIC_HOST from here.
2
+ const DEFAULT_PUBLIC_HOST = "flopguild.pgreyy.com";
3
+ export function publicHost() {
4
+ const h = (process.env.PUBLIC_HOST || DEFAULT_PUBLIC_HOST).trim().toLowerCase();
5
+ if (!/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*(:\d{1,5})?$/.test(h)) {
6
+ throw new Error(`PUBLIC_HOST is not a valid hostname: ${h}`);
7
+ }
8
+ return h;
9
+ }
10
+ export const GUILD_ROOM = "d-flopguild";
11
+ export const GUILD_ROOM_URL = `https://technocore.chat/r/${GUILD_ROOM}`;
12
+ /** Fill {{PUBLIC_HOST}}, {{PUBLIC_URL}}, {{ROOM}} and {{ROOM_URL}} in a site template. */
13
+ export function render(template) {
14
+ const host = publicHost();
15
+ const scheme = /^(localhost|127\.0\.0\.1)(:\d+)?$/.test(host) ? "http" : "https";
16
+ return template
17
+ .replaceAll("{{PUBLIC_HOST}}", host)
18
+ .replaceAll("{{PUBLIC_URL}}", `${scheme}://${host}`)
19
+ .replaceAll("{{ROOM}}", GUILD_ROOM)
20
+ .replaceAll("{{ROOM_URL}}", GUILD_ROOM_URL);
21
+ }
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
+ }