@infernetprotocol/cli 0.1.22

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.
Files changed (50) hide show
  1. package/LICENSE +15 -0
  2. package/commands/chat.js +268 -0
  3. package/commands/console.js +229 -0
  4. package/commands/debug.js +222 -0
  5. package/commands/deploy.js +524 -0
  6. package/commands/doctor.js +501 -0
  7. package/commands/firewall.js +39 -0
  8. package/commands/gpu.js +130 -0
  9. package/commands/help.js +54 -0
  10. package/commands/init.js +304 -0
  11. package/commands/login.js +305 -0
  12. package/commands/logs.js +93 -0
  13. package/commands/model.js +359 -0
  14. package/commands/payments.js +92 -0
  15. package/commands/payout.js +128 -0
  16. package/commands/pubkey.js +116 -0
  17. package/commands/register.js +304 -0
  18. package/commands/remove.js +230 -0
  19. package/commands/service.js +255 -0
  20. package/commands/setup.js +869 -0
  21. package/commands/start.js +903 -0
  22. package/commands/stats.js +85 -0
  23. package/commands/status.js +116 -0
  24. package/commands/stop.js +81 -0
  25. package/commands/train.js +563 -0
  26. package/commands/tui.js +285 -0
  27. package/commands/uncensored.js +222 -0
  28. package/commands/update.js +80 -0
  29. package/commands/upgrade.js +2 -0
  30. package/examples/app.js +153 -0
  31. package/index.js +207 -0
  32. package/lib/chat-executor.js +232 -0
  33. package/lib/config.js +148 -0
  34. package/lib/daemonize.js +46 -0
  35. package/lib/firewall.js +190 -0
  36. package/lib/hf-model.js +166 -0
  37. package/lib/identity.js +18 -0
  38. package/lib/ipc.js +114 -0
  39. package/lib/model-fit.js +67 -0
  40. package/lib/model-key.js +52 -0
  41. package/lib/network.js +240 -0
  42. package/lib/nip44.js +130 -0
  43. package/lib/node-client.js +152 -0
  44. package/lib/peers.js +133 -0
  45. package/lib/prompt.js +49 -0
  46. package/lib/remote-chat.js +115 -0
  47. package/lib/route.js +44 -0
  48. package/lib/runtime-config.js +130 -0
  49. package/lib/version.js +32 -0
  50. package/package.json +57 -0
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `infernet logs` — print (or tail) the daemon log file.
3
+ */
4
+
5
+ import fs from 'node:fs';
6
+ import fsp from 'node:fs/promises';
7
+ import readline from 'node:readline';
8
+ import ora from 'ora';
9
+
10
+ import { resolveLiveDaemonLogPath } from '../lib/config.js';
11
+
12
+ const HELP = `infernet logs — show the daemon log
13
+
14
+ Usage:
15
+ infernet logs [flags]
16
+
17
+ Flags:
18
+ -f, --follow Tail the log file (Ctrl-C to exit)
19
+ --lines <n> Print the last N lines (default 200)
20
+ --help Show this help
21
+ `;
22
+
23
+ async function tailLines(path, n) {
24
+ const stream = fs.createReadStream(path, { encoding: 'utf8' });
25
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
26
+ const buf = [];
27
+ for await (const line of rl) {
28
+ buf.push(line);
29
+ if (buf.length > n) buf.shift();
30
+ }
31
+ return buf;
32
+ }
33
+
34
+ export default async function logs(args) {
35
+ if (args.has('help') || args.has('h')) {
36
+ process.stdout.write(HELP);
37
+ return 0;
38
+ }
39
+
40
+ const logPath = resolveLiveDaemonLogPath();
41
+
42
+ const spinner = ora({ text: 'Looking for daemon log…', color: 'cyan' }).start();
43
+ try { await fsp.access(logPath); }
44
+ catch {
45
+ spinner.fail(`No daemon log at ${logPath}. Run \`infernet start\` first.`);
46
+ return 1;
47
+ }
48
+ spinner.stop();
49
+
50
+ const n = Number.parseInt(args.get('lines') ?? '200', 10) || 200;
51
+ const follow = args.has('follow') || args.has('f');
52
+
53
+ const lines = await tailLines(logPath, n);
54
+ for (const line of lines) process.stdout.write(line + '\n');
55
+
56
+ if (!follow) return 0;
57
+
58
+ // Follow mode: spin while idle, clear spinner when a line arrives.
59
+ const tail = ora({ text: 'Following daemon log… (Ctrl-C to stop)', color: 'cyan' }).start();
60
+
61
+ let lastSize = (await fsp.stat(logPath)).size;
62
+ return new Promise((resolve) => {
63
+ const watcher = fs.watch(logPath, { persistent: true }, async () => {
64
+ try {
65
+ const st = await fsp.stat(logPath);
66
+ if (st.size > lastSize) {
67
+ const fd = await fsp.open(logPath, 'r');
68
+ const length = st.size - lastSize;
69
+ const buf = Buffer.alloc(length);
70
+ await fd.read(buf, 0, length, lastSize);
71
+ await fd.close();
72
+ tail.clear();
73
+ process.stdout.write(buf.toString('utf8'));
74
+ tail.render();
75
+ lastSize = st.size;
76
+ } else if (st.size < lastSize) {
77
+ lastSize = 0;
78
+ }
79
+ } catch {
80
+ // ignore transient errors
81
+ }
82
+ });
83
+ const cleanup = () => {
84
+ tail.stop();
85
+ try { watcher.close(); } catch { /* ignore */ }
86
+ resolve(0);
87
+ };
88
+ process.on('SIGINT', cleanup);
89
+ process.on('SIGTERM', cleanup);
90
+ });
91
+ }
92
+
93
+ export { HELP };
@@ -0,0 +1,359 @@
1
+ /**
2
+ * `infernet model` — model lifecycle (Ollama + HuggingFace).
3
+ *
4
+ * Distinct from the node-lifecycle `infernet update` / `infernet remove`:
5
+ * those manage how this node is registered with the control plane.
6
+ * This command manages which models the node has on disk and which one
7
+ * the engine uses by default.
8
+ *
9
+ * infernet model list
10
+ * infernet model pull <name> Ollama name or hf:org/repo
11
+ * infernet model remove <name>
12
+ * infernet model use <name>
13
+ * infernet model show
14
+ *
15
+ * Ollama models go through the local Ollama daemon.
16
+ * HuggingFace models (hf: prefix) are downloaded via huggingface-cli
17
+ * and are intended for vLLM / SGLang serving.
18
+ */
19
+
20
+ import { spawn } from "node:child_process";
21
+ import { loadConfig, saveConfig, getConfigPath } from "../lib/config.js";
22
+ import { checkModelFits } from "../lib/model-fit.js";
23
+ import {
24
+ resolveHfToken,
25
+ fetchHfModelInfo,
26
+ downloadHfModel,
27
+ } from "../lib/hf-model.js";
28
+
29
+ const HELP = `infernet model — manage models served by this node
30
+
31
+ Usage:
32
+ infernet model list List models pulled locally.
33
+ infernet model pull <name> Pull an Ollama model (e.g. qwen2.5:7b).
34
+ infernet model pull hf:<org>/<repo> Download a HuggingFace model (vLLM/SGLang).
35
+ infernet model remove <name> Delete a pulled model.
36
+ infernet model use <name> Set this as the default for the engine.
37
+ infernet model show Show the engine default + Ollama host.
38
+
39
+ Examples:
40
+ infernet model pull qwen2.5:7b
41
+ infernet model pull hf:NousResearch/Hermes-3-Llama-3.1-8B
42
+ infernet model use qwen2.5:7b
43
+ infernet model list
44
+
45
+ Defaults are stored in ~/.config/infernet/config.json under engine.*
46
+ and consumed by the daemon and \`infernet chat\`.
47
+ `;
48
+
49
+ const DEFAULT_HOST = "http://localhost:11434";
50
+
51
+ function resolveHost(config) {
52
+ return (
53
+ config?.engine?.ollamaHost ??
54
+ process.env.OLLAMA_HOST ??
55
+ DEFAULT_HOST
56
+ );
57
+ }
58
+
59
+ async function fetchTags(host) {
60
+ const ctrl = new AbortController();
61
+ const t = setTimeout(() => ctrl.abort(), 3000);
62
+ try {
63
+ const res = await fetch(new URL("/api/tags", host), { signal: ctrl.signal });
64
+ clearTimeout(t);
65
+ if (!res.ok) throw new Error(`Ollama HTTP ${res.status}`);
66
+ return await res.json();
67
+ } catch (err) {
68
+ clearTimeout(t);
69
+ throw new Error(
70
+ `Ollama not reachable at ${host} (${err?.message ?? err}). Run \`infernet setup\` first.`
71
+ );
72
+ }
73
+ }
74
+
75
+ async function deleteModel(host, name) {
76
+ const res = await fetch(new URL("/api/delete", host), {
77
+ method: "DELETE",
78
+ headers: { "content-type": "application/json" },
79
+ body: JSON.stringify({ name })
80
+ });
81
+ if (!res.ok) {
82
+ const detail = await res.text().catch(() => "");
83
+ throw new Error(`Ollama HTTP ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ""}`);
84
+ }
85
+ }
86
+
87
+
88
+
89
+ function streamPull(name) {
90
+ return new Promise((resolve, reject) => {
91
+ // Use the local `ollama` CLI for the pull because it gives a much
92
+ // nicer progress UI than streaming JSON from /api/pull. The
93
+ // /api/pull endpoint is fine for programmatic use; for an
94
+ // interactive operator, ollama's own bar is the right tool.
95
+ const child = spawn("ollama", ["pull", name], { stdio: "inherit" });
96
+ child.on("exit", (code) => {
97
+ if (code === 0) resolve();
98
+ else reject(new Error(`ollama pull exited ${code}`));
99
+ });
100
+ child.on("error", reject);
101
+ });
102
+ }
103
+
104
+ async function cmdList(host) {
105
+ const cfg = await loadConfig();
106
+ const active = cfg?.engine?.model ?? null;
107
+ const hfModels = cfg?.engine?.hfModels ?? [];
108
+
109
+ // Ollama models
110
+ let ollamaModels = [];
111
+ try {
112
+ const tags = await fetchTags(host);
113
+ ollamaModels = tags.models ?? [];
114
+ } catch {
115
+ // Ollama not running — still show HF models
116
+ }
117
+
118
+ const allEmpty = ollamaModels.length === 0 && hfModels.length === 0;
119
+ if (allEmpty) {
120
+ process.stdout.write("(no models pulled — try `infernet model pull qwen2.5:7b` or `infernet model pull hf:org/repo`)\n");
121
+ return 0;
122
+ }
123
+
124
+ const allNames = [
125
+ ...ollamaModels.map(m => m.name ?? ""),
126
+ ...hfModels.map(m => m.repoId),
127
+ ];
128
+ const nameWidth = Math.max(4, ...allNames.map(n => n.length));
129
+ process.stdout.write(`${"NAME".padEnd(nameWidth)} SIZE BACKEND ACTIVE\n`);
130
+
131
+ for (const m of ollamaModels) {
132
+ const size = typeof m.size === "number"
133
+ ? `${(m.size / 1024 / 1024 / 1024).toFixed(1)} GB`
134
+ : "?";
135
+ const isActive = m.name === active ? " *" : "";
136
+ process.stdout.write(`${(m.name ?? "").padEnd(nameWidth)} ${size.padEnd(10)} ollama ${isActive}\n`);
137
+ }
138
+
139
+ for (const m of hfModels) {
140
+ const size = m.sizeGb ? `${m.sizeGb} GB` : "?";
141
+ const isActive = m.repoId === active ? " *" : "";
142
+ process.stdout.write(`${m.repoId.padEnd(nameWidth)} ${size.padEnd(10)} vllm ${isActive}\n`);
143
+ }
144
+
145
+ if (active) {
146
+ process.stdout.write(`\nactive: ${active}\n`);
147
+ }
148
+ return 0;
149
+ }
150
+
151
+ async function cmdHfPull(repoId, opts = {}) {
152
+ const token = await resolveHfToken();
153
+
154
+ process.stdout.write(`\nFetching metadata for ${repoId}…\n`);
155
+ let info;
156
+ try {
157
+ info = await fetchHfModelInfo(repoId, token);
158
+ } catch (err) {
159
+ process.stderr.write(`error: ${err?.message ?? err}\n`);
160
+ return 1;
161
+ }
162
+
163
+ process.stdout.write(`\n repo: ${info.repoId}\n`);
164
+ process.stdout.write(` type: ${info.modelType ?? 'unknown'}\n`);
165
+ process.stdout.write(` size: ${info.sizeGb != null ? info.sizeGb + ' GB' : 'unknown'}\n`);
166
+ process.stdout.write(` pipeline: ${info.pipeline}\n`);
167
+ process.stdout.write(` backend: ${info.recommendedBackend === 'vllm_or_sglang' ? 'vLLM / SGLang (Ollama not supported)' : 'Ollama or vLLM'}\n`);
168
+ if (info.isMoe) process.stdout.write(` ⚠ MoE model — requires vLLM or SGLang (not Ollama)\n`);
169
+ process.stdout.write('\n');
170
+
171
+ let localPath;
172
+ try {
173
+ localPath = await downloadHfModel(repoId, token, {});
174
+ } catch (err) {
175
+ process.stderr.write(`error: ${err?.message ?? err}\n`);
176
+ return 1;
177
+ }
178
+
179
+ // Save to config under engine.hfModels
180
+ const cfg = (await loadConfig()) ?? {};
181
+ const hfModels = cfg.engine?.hfModels ?? [];
182
+ const existing = hfModels.findIndex(m => m.repoId === repoId);
183
+ const entry = { repoId, localPath, sizeGb: info.sizeGb, pulledAt: new Date().toISOString() };
184
+ if (existing >= 0) hfModels[existing] = entry;
185
+ else hfModels.push(entry);
186
+ await saveConfig({ ...cfg, engine: { ...(cfg.engine ?? {}), hfModels } });
187
+
188
+ process.stdout.write(`\nSaved to config. To serve with vLLM:\n`);
189
+ process.stdout.write(` vllm serve ${repoId} --host 0.0.0.0 --port 8000\n`);
190
+ process.stdout.write(`\nThen set as active:\n`);
191
+ process.stdout.write(` infernet model use ${repoId}\n\n`);
192
+ return 0;
193
+ }
194
+
195
+ async function cmdPull(host, name, opts = {}) {
196
+ if (!name) {
197
+ process.stderr.write("error: pull requires a model name (e.g. qwen2.5:7b or hf:org/repo)\n");
198
+ return 2;
199
+ }
200
+
201
+ // HuggingFace path
202
+ if (name.startsWith('hf:')) {
203
+ return cmdHfPull(name.slice(3), opts);
204
+ }
205
+
206
+ // Quick reachability check before spawning ollama, so we get a friendly
207
+ // error rather than a confusing CLI-not-found if Ollama isn't installed.
208
+ await fetchTags(host);
209
+
210
+ // Capacity check — always enforced unless --force is passed.
211
+ if (!opts.force) {
212
+ const fits = await checkModelFits(name);
213
+ if (fits && !fits.ok) {
214
+ process.stderr.write(
215
+ `\n${name} (≈${fits.size_gb} GB) likely won't fit on this host:\n` +
216
+ ` detected: ${fits.mode} with ${fits.have_gb} GB available\n` +
217
+ ` ceiling: ~${fits.ceiling_gb} GB (${fits.mode === "gpu" ? "85% of VRAM" : "60% of RAM"})\n` +
218
+ `\nRefusing to pull. To override:\n` +
219
+ ` infernet model pull ${name} --force\n` +
220
+ `\nOr pick a smaller model — see https://ollama.com/library\n`
221
+ );
222
+ return 1;
223
+ }
224
+ }
225
+
226
+ try {
227
+ await streamPull(name);
228
+ } catch (err) {
229
+ process.stderr.write(`error: ${err?.message ?? err}\n`);
230
+ process.stderr.write(
231
+ `\nNothing pulled. Common causes:\n` +
232
+ ` - typo in the model spec (try \`ollama list\` on the registry: https://ollama.com/library)\n` +
233
+ ` - missing tag — try the bare model name (e.g. qwen2.5 → qwen2.5:latest)\n` +
234
+ ` - private / gated model — pull manually with \`ollama pull ${name}\` to see the raw error\n`
235
+ );
236
+ return 1;
237
+ }
238
+ return 0;
239
+ }
240
+
241
+ async function cmdRemove(host, name) {
242
+ if (!name) {
243
+ process.stderr.write("error: remove requires a model name\n");
244
+ return 2;
245
+ }
246
+ await deleteModel(host, name);
247
+ process.stdout.write(`removed ${name}\n`);
248
+
249
+ // If the removed one was the active default, clear it so the daemon
250
+ // doesn't keep pointing at a missing model.
251
+ const cfg = (await loadConfig()) ?? {};
252
+ if (cfg.engine?.model === name) {
253
+ const updated = { ...cfg, engine: { ...cfg.engine, model: null } };
254
+ delete updated.engine.model;
255
+ await saveConfig(updated);
256
+ process.stdout.write(`(cleared engine.model in ${getConfigPath()} — set a new one with \`infernet model use <name>\`)\n`);
257
+ }
258
+ return 0;
259
+ }
260
+
261
+ async function cmdUse(host, name) {
262
+ if (!name) {
263
+ process.stderr.write("error: use requires a model name\n");
264
+ return 2;
265
+ }
266
+ const cfg = (await loadConfig()) ?? {};
267
+
268
+ // HuggingFace model path — verify it's in config
269
+ if (name.includes('/') || name.startsWith('hf:')) {
270
+ const repoId = name.startsWith('hf:') ? name.slice(3) : name;
271
+ const hfModels = cfg.engine?.hfModels ?? [];
272
+ if (!hfModels.some(m => m.repoId === repoId)) {
273
+ process.stderr.write(
274
+ `error: ${repoId} not found in local HF models. Pull it first:\n` +
275
+ ` infernet model pull hf:${repoId}\n`
276
+ );
277
+ return 1;
278
+ }
279
+ await saveConfig({ ...cfg, engine: { ...(cfg.engine ?? {}), model: repoId, backend: 'vllm' } });
280
+ process.stdout.write(`engine.model = ${repoId} (backend: vllm)\n`);
281
+ process.stdout.write(`Serve it with: vllm serve ${repoId} --host 0.0.0.0 --port 8000\n`);
282
+ return 0;
283
+ }
284
+
285
+ // Ollama model — verify it's actually pulled
286
+ const tags = await fetchTags(host);
287
+ const have = (tags.models ?? []).map((m) => m.name).includes(name);
288
+ if (!have) {
289
+ process.stderr.write(
290
+ `error: ${name} is not pulled locally. Pull it first: infernet model pull ${name}\n`
291
+ );
292
+ return 1;
293
+ }
294
+ const updated = {
295
+ ...cfg,
296
+ engine: { ...(cfg.engine ?? {}), model: name, backend: 'ollama' }
297
+ };
298
+ await saveConfig(updated);
299
+ process.stdout.write(`engine.model = ${name} (saved to ${getConfigPath()})\n`);
300
+ return 0;
301
+ }
302
+
303
+ async function cmdShow(host) {
304
+ const cfg = (await loadConfig()) ?? {};
305
+ const model = cfg.engine?.model ?? null;
306
+ const backend = cfg.engine?.backend ?? "auto";
307
+ process.stdout.write(`backend: ${backend}\n`);
308
+ process.stdout.write(`ollama host: ${host}\n`);
309
+ process.stdout.write(`model: ${model ?? "(unset — use \`infernet model use <name>\`)"}\n`);
310
+ return 0;
311
+ }
312
+
313
+ export default async function model(args) {
314
+ if (args.has("help") || args.has("h")) {
315
+ process.stdout.write(HELP);
316
+ return 0;
317
+ }
318
+ const positional = args.positional ?? [];
319
+ const sub = positional[0];
320
+ const arg = positional[1];
321
+
322
+ const cfg = (await loadConfig()) ?? {};
323
+ const host = resolveHost(cfg);
324
+
325
+ try {
326
+ switch (sub) {
327
+ case "list":
328
+ case "ls":
329
+ return await cmdList(host);
330
+ case "pull":
331
+ case "add":
332
+ return await cmdPull(host, arg, {
333
+ force: args.has("force") || args.has("f"),
334
+ yes: args.has("yes") || args.has("y") || process.env.INFERNET_NONINTERACTIVE === "1"
335
+ });
336
+ case "remove":
337
+ case "rm":
338
+ case "delete":
339
+ return await cmdRemove(host, arg);
340
+ case "use":
341
+ case "set":
342
+ return await cmdUse(host, arg);
343
+ case "show":
344
+ case "current":
345
+ return await cmdShow(host);
346
+ default:
347
+ process.stderr.write(
348
+ sub
349
+ ? `unknown subcommand: ${sub}\n\n`
350
+ : "error: missing subcommand\n\n"
351
+ );
352
+ process.stderr.write(HELP);
353
+ return 2;
354
+ }
355
+ } catch (err) {
356
+ process.stderr.write(`error: ${err?.message ?? err}\n`);
357
+ return 1;
358
+ }
359
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `infernet payments list [--limit N]`
3
+ *
4
+ * Prints the last N payment_transactions rows involving this node, fetched
5
+ * via signed POST to /api/v1/node/payments/list.
6
+ */
7
+
8
+ const HELP = `infernet payments — show recent payment transactions
9
+
10
+ Usage:
11
+ infernet payments list [--limit N]
12
+ infernet payments --help
13
+
14
+ Flags:
15
+ --limit N Number of rows to show (default 20)
16
+ `;
17
+
18
+ function formatDate(ts) {
19
+ if (!ts) return '(no date)';
20
+ try {
21
+ return new Date(ts).toISOString().replace('T', ' ').replace(/\.\d+Z$/, 'Z');
22
+ } catch {
23
+ return String(ts);
24
+ }
25
+ }
26
+
27
+ function tableRows(rows) {
28
+ const header = ['created', 'dir', 'coin', 'amount', 'usd', 'status', 'tx/invoice'];
29
+ const body = rows.map((r) => [
30
+ formatDate(r.created_at),
31
+ r.direction ?? '',
32
+ r.coin ?? '',
33
+ String(r.amount ?? ''),
34
+ r.amount_usd != null ? `$${Number.parseFloat(r.amount_usd).toFixed(2)}` : '',
35
+ r.status ?? '',
36
+ r.tx_hash ?? r.invoice_id ?? ''
37
+ ]);
38
+ const all = [header, ...body];
39
+ const widths = header.map((_, i) =>
40
+ all.reduce((w, row) => Math.max(w, String(row[i] ?? '').length), 0)
41
+ );
42
+ return all
43
+ .map((row) => row.map((cell, i) => String(cell ?? '').padEnd(widths[i])).join(' '))
44
+ .join('\n');
45
+ }
46
+
47
+ async function runList(args, ctx) {
48
+ const { config, client } = ctx;
49
+ const node = config.node ?? {};
50
+ if (node.role !== 'provider' && node.role !== 'client') {
51
+ process.stderr.write('Only provider/client nodes have payment transactions.\n');
52
+ return 1;
53
+ }
54
+
55
+ const limit = Math.max(1, Number.parseInt(args.get('limit') ?? '20', 10) || 20);
56
+ let result;
57
+ try {
58
+ result = await client.listPayments(limit);
59
+ } catch (err) {
60
+ process.stderr.write(`payments list failed: ${err?.message ?? err}\n`);
61
+ return 1;
62
+ }
63
+
64
+ const rows = result?.rows ?? [];
65
+ if (!rows.length) {
66
+ process.stdout.write('(no payment transactions)\n');
67
+ return 0;
68
+ }
69
+ process.stdout.write(tableRows(rows) + '\n');
70
+ return 0;
71
+ }
72
+
73
+ export default async function payments(args, ctx) {
74
+ if (args.has('help') || args.has('h')) {
75
+ process.stdout.write(HELP);
76
+ return 0;
77
+ }
78
+
79
+ const positional = args.positional ?? [];
80
+ const sub = positional[0] ?? 'list';
81
+
82
+ switch (sub) {
83
+ case 'list':
84
+ return runList(args, ctx);
85
+ default:
86
+ process.stderr.write(`Unknown payments subcommand "${sub}".\n`);
87
+ process.stderr.write(HELP);
88
+ return 1;
89
+ }
90
+ }
91
+
92
+ export { HELP };
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `infernet payout` — manage this provider's payout coin/address via the
3
+ * signed node API.
4
+ *
5
+ * Subcommands:
6
+ * infernet payout set <coin> <address> [--network <name>]
7
+ * infernet payout list
8
+ */
9
+
10
+ import { PAYMENT_COINS, PAYMENT_COIN_CODES } from '@infernetprotocol/config/payment-coins';
11
+
12
+ const HELP = `infernet payout — manage payout coin/address
13
+
14
+ Usage:
15
+ infernet payout set <coin> <address> [--network <name>]
16
+ infernet payout list
17
+ infernet payout --help
18
+
19
+ Supported coins: ${PAYMENT_COIN_CODES.join(', ')}
20
+ `;
21
+
22
+ function pickNetwork(coin, requestedNetwork) {
23
+ const upper = String(coin).toUpperCase();
24
+ const matches = PAYMENT_COINS.filter((c) => c.code === upper);
25
+ if (matches.length === 0) return null;
26
+ if (requestedNetwork) {
27
+ const hit = matches.find((c) => c.network === requestedNetwork);
28
+ return hit ? hit.network : null;
29
+ }
30
+ return matches[0].network;
31
+ }
32
+
33
+ async function runList(args, ctx) {
34
+ const { config, client } = ctx;
35
+ const node = config.node ?? {};
36
+ if (node.role !== 'provider') {
37
+ process.stderr.write('Payouts are only configurable for providers.\n');
38
+ return 1;
39
+ }
40
+
41
+ let result;
42
+ try {
43
+ result = await client.listPayouts();
44
+ } catch (err) {
45
+ process.stderr.write(`payout list failed: ${err?.message ?? err}\n`);
46
+ return 1;
47
+ }
48
+ const rows = result?.rows ?? [];
49
+ if (!rows.length) {
50
+ process.stdout.write('(no payout addresses configured)\n');
51
+ process.stdout.write('Use `infernet payout set <coin> <address>` to add one.\n');
52
+ return 0;
53
+ }
54
+ for (const row of rows) {
55
+ const marker = row.is_default ? '* ' : ' ';
56
+ const net = row.network ? ` (${row.network})` : '';
57
+ process.stdout.write(`${marker}${row.coin}${net} ${row.address}\n`);
58
+ }
59
+ return 0;
60
+ }
61
+
62
+ async function runSet(args, ctx, positional) {
63
+ const [coinArg, addressArg] = positional;
64
+ if (!coinArg || !addressArg) {
65
+ process.stderr.write('Usage: infernet payout set <coin> <address> [--network <name>]\n');
66
+ return 1;
67
+ }
68
+ const coin = coinArg.toUpperCase();
69
+ if (!PAYMENT_COIN_CODES.includes(coin)) {
70
+ process.stderr.write(
71
+ `Unsupported coin "${coin}". Supported: ${PAYMENT_COIN_CODES.join(', ')}\n`
72
+ );
73
+ return 1;
74
+ }
75
+ const requestedNetwork = args.get('network');
76
+ const network = pickNetwork(coin, requestedNetwork);
77
+ if (!network) {
78
+ process.stderr.write(
79
+ `Coin "${coin}" has no network "${requestedNetwork}". Check config/payment-coins.js.\n`
80
+ );
81
+ return 1;
82
+ }
83
+
84
+ const { config, client } = ctx;
85
+ if ((config.node?.role) !== 'provider') {
86
+ process.stderr.write('Payouts are only configurable for providers.\n');
87
+ return 1;
88
+ }
89
+
90
+ try {
91
+ await client.setPayout({ coin, network, address: addressArg });
92
+ } catch (err) {
93
+ process.stderr.write(`payout set failed: ${err?.message ?? err}\n`);
94
+ return 1;
95
+ }
96
+ process.stdout.write(`Set default payout: ${coin} (${network}) ${addressArg}\n`);
97
+ return 0;
98
+ }
99
+
100
+ export default async function payout(args, ctx) {
101
+ if (args.has('help') || args.has('h')) {
102
+ process.stdout.write(HELP);
103
+ return 0;
104
+ }
105
+
106
+ const positional = args.positional ?? [];
107
+ const sub = positional[0];
108
+
109
+ if (!sub) {
110
+ process.stderr.write(HELP);
111
+ return 1;
112
+ }
113
+
114
+ const rest = positional.slice(1);
115
+
116
+ switch (sub) {
117
+ case 'list':
118
+ return runList(args, ctx);
119
+ case 'set':
120
+ return runSet(args, ctx, rest);
121
+ default:
122
+ process.stderr.write(`Unknown payout subcommand "${sub}".\n`);
123
+ process.stderr.write(HELP);
124
+ return 1;
125
+ }
126
+ }
127
+
128
+ export { HELP };