vantyx-cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/admin-password.mjs +27 -0
- package/bin/vantyx.mjs +19 -2
- package/package.json +8 -1
- package/public/companion.js +19 -4
- package/public/index.html +8 -3
- package/public/studio.html +93 -0
- package/src/agents.mjs +7 -1
- package/src/guardian.mjs +3 -1
- package/src/holders.mjs +104 -0
- package/src/hosted.mjs +106 -0
- package/src/pq.mjs +56 -0
- package/src/server.mjs +75 -14
- package/src/studio.mjs +303 -0
- package/src/support.mjs +200 -0
- package/src/token.mjs +15 -0
- package/src/vaultkeys.mjs +42 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Sets the support-inbox password for the hosted server: asks for it without echoing, stores only a scrypt hash in .env.
|
|
3
|
+
// node bin/admin-password.mjs (run on the server, in /opt/vantyx-hosted)
|
|
4
|
+
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
5
|
+
import { randomBytes, scryptSync } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
const ask = (q) => new Promise((res) => {
|
|
8
|
+
process.stdout.write(q);
|
|
9
|
+
const input = process.stdin;
|
|
10
|
+
input.setRawMode?.(true); input.resume(); input.setEncoding("utf8");
|
|
11
|
+
let s = "";
|
|
12
|
+
input.on("data", function on(ch) {
|
|
13
|
+
if (ch === "\r" || ch === "\n") { input.setRawMode?.(false); input.pause(); input.removeListener("data", on); process.stdout.write("\n"); res(s); }
|
|
14
|
+
else if (ch === "\u0003") process.exit(1);
|
|
15
|
+
else if (ch === "\u007f") s = s.slice(0, -1);
|
|
16
|
+
else s += ch;
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
const pw = await ask("New support inbox password (at least 12 characters): ");
|
|
20
|
+
if (pw.length < 12) { console.error("too short"); process.exit(1); }
|
|
21
|
+
if ((await ask("Again: ")) !== pw) { console.error("they don't match"); process.exit(1); }
|
|
22
|
+
const salt = randomBytes(16);
|
|
23
|
+
const line = `VANTYX_ADMIN_HASH=${salt.toString("hex")}:${scryptSync(pw, salt, 32).toString("hex")}`;
|
|
24
|
+
const file = new URL("../.env", import.meta.url).pathname;
|
|
25
|
+
const env = existsSync(file) ? readFileSync(file, "utf8").split("\n").filter((l) => l && !l.startsWith("VANTYX_ADMIN_HASH=")) : [];
|
|
26
|
+
writeFileSync(file, [...env, line].join("\n") + "\n", { mode: 0o600 });
|
|
27
|
+
console.log("Saved. Apply it: pm2 restart ecosystem.config.cjs --update-env");
|
package/bin/vantyx.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// npx vantyx-cli companion dashboard + relayer + agents + guardian on http://127.0.0.1:5893
|
|
4
4
|
// npx vantyx-cli status <vault> a vault's mode, counters and balance, read from Robinhood Chain
|
|
5
5
|
// npx vantyx-cli submit <frames.txt> put an action signed by the offline vault on chain (fast or strict)
|
|
6
|
+
// npx vantyx-cli register <vault> <genesis.txt> learn a vault's keys from its deploy QR (once, if this companion did not deploy it)
|
|
6
7
|
// npx vantyx-cli agents list agents and what they may still spend
|
|
7
8
|
// npx vantyx-cli agent new <vault> scheduled|x402 [--to 0x… --amount 25 --every-hours 24 | --max 1]
|
|
8
9
|
// npx vantyx-cli guardian <vault> [--max-single 1000] [--max-daily 2500] [--unknown-owner]
|
|
@@ -48,11 +49,26 @@ evacuates to ${s.evacuateTo}`);
|
|
|
48
49
|
let bundle;
|
|
49
50
|
if (text.startsWith("{")) bundle = JSON.parse(text);
|
|
50
51
|
else { const j = new Joiner(); let d = null; for (const f of text.split(/\s+/)) if (f.startsWith("VX1/")) d = j.push(f) || d; if (!d) fail(`only ${j.progress().join(" of ")} frames`); bundle = JSON.parse(new TextDecoder().decode(d)); }
|
|
51
|
-
|
|
52
|
+
const { verifyBundle } = await import("../src/vaultkeys.mjs");
|
|
53
|
+
await verifyBundle(bundle);
|
|
54
|
+
console.log(`relaying #${bundle.nonce}: ${bundle.description} (ML-DSA-65 verified${bundle.kind === 7 ? ", SLH-DSA-128s verified" : ""})`);
|
|
52
55
|
const r = await submit(bundle, (m) => console.log(` ${m}`));
|
|
53
56
|
console.log(r.ok ? `done in block ${r.block}: ${r.tx}` : `proof spent but the action failed: ${r.tx}`);
|
|
54
57
|
break;
|
|
55
58
|
}
|
|
59
|
+
case "register": {
|
|
60
|
+
// once per vault this companion did not deploy: the deploy QR's frames (or the genesis JSON), saved to a file
|
|
61
|
+
const [vault, file] = rest;
|
|
62
|
+
if (!vault || !file) fail("usage: vantyx register <vault> <file with the deploy QR's VX1 frames>");
|
|
63
|
+
const text = readFileSync(file, "utf8").trim();
|
|
64
|
+
const { Joiner } = await import("../src/frames.mjs");
|
|
65
|
+
let g;
|
|
66
|
+
if (text.startsWith("{")) g = JSON.parse(text);
|
|
67
|
+
else { const j = new Joiner(); let d = null; for (const f of text.split(/\s+/)) if (f.startsWith("VX1/")) d = j.push(f) || d; if (!d) fail(`only ${j.progress().join(" of ")} frames`); g = JSON.parse(new TextDecoder().decode(d)); }
|
|
68
|
+
await (await import("../src/vaultkeys.mjs")).register(vault, g);
|
|
69
|
+
console.log(`registered ${vault}: ML-DSA-65, SLH-DSA-128s and ML-KEM-768 keys checked against the contract`);
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
56
72
|
case "agents": {
|
|
57
73
|
const { listAgents } = await import("../src/agents.mjs");
|
|
58
74
|
const { remaining } = await import("../src/chain.mjs");
|
|
@@ -68,13 +84,14 @@ evacuates to ${s.evacuateTo}`);
|
|
|
68
84
|
if (rest[0] !== "new") fail("usage: vantyx agent new <vault> scheduled|x402 …");
|
|
69
85
|
const [, vault, kind] = rest;
|
|
70
86
|
const { createAgent } = await import("../src/agents.mjs");
|
|
71
|
-
const a = createAgent({ vault, kind, name: flag("name") || kind, to: flag("to"), amount: flag("amount") && units(flag("amount")), everySeconds: flag("every-hours") && Number(flag("every-hours")) * 3600, maxPerInvoice: flag("max") && units(flag("max")) });
|
|
87
|
+
const a = await createAgent({ vault, kind, name: flag("name") || kind, to: flag("to"), amount: flag("amount") && units(flag("amount")), everySeconds: flag("every-hours") && Number(flag("every-hours")) * 3600, maxPerInvoice: flag("max") && units(flag("max")) });
|
|
72
88
|
console.log(`agent ${a.id} created: ${a.address}\nGive it an allowance in the vault app (Agents), and send it a little ETH for gas.`);
|
|
73
89
|
break;
|
|
74
90
|
}
|
|
75
91
|
case "guardian": {
|
|
76
92
|
const vault = rest[0] || fail("usage: vantyx guardian <vault> [--max-single N] [--max-daily N] [--unknown-owner]");
|
|
77
93
|
const { watch } = await import("../src/guardian.mjs");
|
|
94
|
+
await (await import("../src/hosted.mjs")).requirePro(vault);
|
|
78
95
|
watch(vault, { maxSingle: flag("max-single") && units(flag("max-single")), maxDaily: flag("max-daily") && units(flag("max-daily")), unknownOwner: !!flag("unknown-owner") });
|
|
79
96
|
console.log(`guardian rules saved for ${vault}. They run while \`vantyx companion\` is running with VANTYX_GUARDIAN_KEY set.`);
|
|
80
97
|
break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vantyx-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Vantyx on the command line: relayer, agents, guardian and dashboard for an offline post-quantum vault on Robinhood Chain",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -39,7 +39,14 @@
|
|
|
39
39
|
"e2e": "node test/e2e.mjs"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
+
"@anthropic-ai/sdk": "^1.17.0",
|
|
43
|
+
"@noble/ciphers": "^2.4.0",
|
|
44
|
+
"@noble/hashes": "^2.4.0",
|
|
42
45
|
"@noble/post-quantum": "^0.7.1",
|
|
46
|
+
"ethers": "6.13.4",
|
|
43
47
|
"viem": "^2.58.10"
|
|
48
|
+
},
|
|
49
|
+
"overrides": {
|
|
50
|
+
"ws": "^8.23.0"
|
|
44
51
|
}
|
|
45
52
|
}
|
package/public/companion.js
CHANGED
|
@@ -25,7 +25,7 @@ async function header() {
|
|
|
25
25
|
try {
|
|
26
26
|
CFG = await api("/api/config");
|
|
27
27
|
$("hdr").innerHTML = `<span>chain <b>${CFG.chainId}</b></span><span>block <b>${CFG.block}</b></span><span>relayer <b>${CFG.relayer || "not set"}</b></span><span>guardian <b>${CFG.guardian || "not set"}</b></span>`;
|
|
28
|
-
|
|
28
|
+
$("gGuard").textContent = CFG.guardian || "(no guardian key set in this companion)";
|
|
29
29
|
} catch (e) { $("hdr").textContent = "companion API not reachable: " + e.message; }
|
|
30
30
|
}
|
|
31
31
|
|
|
@@ -91,7 +91,13 @@ function read(frames) {
|
|
|
91
91
|
for (const f of frames) data = j.push(f) || data;
|
|
92
92
|
if (!data) throw new Error(`only ${j.progress().join(" of ")} frames`);
|
|
93
93
|
payload = JSON.parse(new TextDecoder().decode(data)); rawFrames = frames;
|
|
94
|
-
if (payload.type === "genesis") {
|
|
94
|
+
if (payload.type === "genesis") {
|
|
95
|
+
$("gFp").textContent = fp(payload.identity); $("genesisBox").hidden = false;
|
|
96
|
+
const zero = /^0x0{40}$/i.test(payload.guardian || "");
|
|
97
|
+
$("gFixed").textContent = !payload.dsa_sig ? "This deploy QR comes from an older Vantyx Vault. Update the app and show it again."
|
|
98
|
+
: zero ? "No guardian in this genesis. You can add one later from the vault app (Guardian page)."
|
|
99
|
+
: `Guardian ${payload.guardian}, evacuating to ${payload.evacuate_to}. Fixed by the vault's signature.`;
|
|
100
|
+
}
|
|
95
101
|
else if (payload.action_hash) {
|
|
96
102
|
$("aDesc").textContent = payload.description;
|
|
97
103
|
$("aMeta").textContent = `Action #${payload.nonce} · ${payload.mode} mode · vault ${payload.vault}`;
|
|
@@ -102,17 +108,26 @@ function read(frames) {
|
|
|
102
108
|
$("gDeploy").onclick = async () => {
|
|
103
109
|
$("gDeploy").disabled = true; $("gOk").textContent = "Deploying…";
|
|
104
110
|
try {
|
|
105
|
-
const r = await api("/api/deploy", { genesis: payload
|
|
111
|
+
const r = await api("/api/deploy", { genesis: payload });
|
|
106
112
|
$("gOk").textContent = `Deployed at ${r.vault}. Type this address into the vault app.`;
|
|
107
113
|
$("vAddr").value = r.vault; VAULT = r.vault; localStorage.setItem("vantyx.vault", r.vault);
|
|
108
114
|
} catch (e) { $("gOk").textContent = ""; $("scanErr").textContent = e.message; }
|
|
109
115
|
$("gDeploy").disabled = false;
|
|
110
116
|
};
|
|
117
|
+
$("gRegister").onclick = async () => {
|
|
118
|
+
const v = $("gExisting").value.trim();
|
|
119
|
+
$("gOk").textContent = ""; $("scanErr").textContent = "";
|
|
120
|
+
try {
|
|
121
|
+
await api(`/api/identity/${v}`, { genesis: payload });
|
|
122
|
+
$("gOk").textContent = `This companion now knows the keys of ${v}: it checks every ML-DSA-65 signature, every SLH-DSA-128s rotation, and encrypts the status QR to its ML-KEM-768 key.`;
|
|
123
|
+
$("vAddr").value = v; VAULT = v; localStorage.setItem("vantyx.vault", v);
|
|
124
|
+
} catch (e) { $("scanErr").textContent = e.message; }
|
|
125
|
+
};
|
|
111
126
|
$("aSubmit").onclick = async () => {
|
|
112
127
|
$("aSubmit").disabled = true; $("aOk").textContent = payload.mode === "fast" ? "Committing, then revealing in the next block…" : "Sending…";
|
|
113
128
|
try {
|
|
114
129
|
const r = await api("/api/submit", { frames: rawFrames });
|
|
115
|
-
$("aOk").textContent = r.ok ? `Done in block ${r.block} (${r.tx.slice(0, 12)}…). ML-DSA identity
|
|
130
|
+
$("aOk").textContent = r.ok ? `Done in block ${r.block} (${r.tx.slice(0, 12)}…). ML-DSA-65 identity verified.`
|
|
116
131
|
: `The proof was accepted but the action failed (for example, not enough balance). Tx ${r.tx}.`;
|
|
117
132
|
} catch (e) { $("aOk").textContent = ""; $("scanErr").textContent = e.message; }
|
|
118
133
|
$("aSubmit").disabled = false;
|
package/public/index.html
CHANGED
|
@@ -51,10 +51,15 @@
|
|
|
51
51
|
|
|
52
52
|
<div class="panel" id="genesisBox" hidden>
|
|
53
53
|
<h3>Deploy this vault</h3>
|
|
54
|
-
<p class="muted">Identity fingerprint <b class="mono" id="gFp"></b>. It must match the one in the vault app.</p>
|
|
55
|
-
<
|
|
56
|
-
<
|
|
54
|
+
<p class="muted">Identity fingerprint <b class="mono" id="gFp"></b>. It must match the one in the vault app. Signed by the vault with ML-DSA-65 and SLH-DSA-128s; this companion checks both before deploying.</p>
|
|
55
|
+
<p class="muted small" id="gFixed"></p>
|
|
56
|
+
<p class="muted small">To have this companion's guardian watch the vault, type <b class="mono" id="gGuard"></b> into the vault app as the guardian, with a cold address of yours, before showing the deploy QR.</p>
|
|
57
57
|
<div class="row end"><button class="btn primary" id="gDeploy">Deploy on Robinhood Chain</button></div>
|
|
58
|
+
<details><summary>I already have a vault</summary>
|
|
59
|
+
<p class="muted small">If the vault is already on chain (deployed by another companion), this companion only needs its keys. Enter its address and register.</p>
|
|
60
|
+
<label>Vault contract<input id="gExisting" placeholder="0x…" spellcheck="false"></label>
|
|
61
|
+
<div class="row end"><button class="btn" id="gRegister">Register this vault's keys</button></div>
|
|
62
|
+
</details>
|
|
58
63
|
<p class="ok" id="gOk"></p>
|
|
59
64
|
</div>
|
|
60
65
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
|
3
|
+
<title>Vantyx · studio</title><link rel="icon" href="/assets/mark-96.png"><link rel="apple-touch-icon" href="/assets/mark-96.png"><meta name="robots" content="noindex,nofollow">
|
|
4
|
+
<link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
|
5
|
+
<style>
|
|
6
|
+
:root{--bg:#08101f;--panel:#0f1c36;--fg:#e6edfb;--dim:#9aa9c6;--faint:#5a6b8c;--line:#1c2a47;--sig:#6e95d6;--warm:#d4e2f6;--bad:#f0a08c;--sans:"Inter",system-ui,sans-serif;--mono:"DM Mono",ui-monospace,Menlo,monospace}
|
|
7
|
+
*{box-sizing:border-box}html,body{margin:0;background:var(--bg);color:var(--fg);font:400 15px/1.55 var(--sans);-webkit-font-smoothing:antialiased}
|
|
8
|
+
body{background:radial-gradient(90% 60% at 80% -10%,rgba(76,127,208,.14),transparent 60%),var(--bg)}
|
|
9
|
+
a{color:var(--sig)}button,input{font:inherit;color:inherit}
|
|
10
|
+
.wrap{max-width:860px;margin:0 auto;padding:28px 18px 60px}
|
|
11
|
+
header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:26px}
|
|
12
|
+
.logo{display:flex;align-items:center;gap:10px;font:600 18px var(--sans);letter-spacing:-.02em;color:var(--fg);text-decoration:none}.logo img{width:30px;height:30px}
|
|
13
|
+
.tag{font-family:var(--mono);font-size:11.5px;color:var(--dim)}
|
|
14
|
+
.card{background:var(--panel);border:1px solid var(--line);border-radius:0;padding:22px;margin-bottom:16px;box-shadow:inset 0 1px 0 rgba(255,255,255,.04)}
|
|
15
|
+
h2{margin:0 0 4px;font:400 20px var(--mono);letter-spacing:-.03em}.sub{margin:0 0 16px;color:var(--dim);font-size:13.5px}
|
|
16
|
+
label{display:block;font-size:12.5px;color:var(--dim);margin:12px 0 6px}
|
|
17
|
+
input{width:100%;background:rgba(0,0,0,.35);border:1px solid var(--line);border-radius:0;padding:12px 13px;outline:0;font-family:var(--mono);font-size:13.5px}input:focus{border-color:var(--sig)}
|
|
18
|
+
.row{display:flex;gap:10px;flex-wrap:wrap;align-items:end}.row>*{flex:1;min-width:160px}
|
|
19
|
+
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:0 18px;border:0;border-radius:0;background:#4c7fd0;color:#fff;font-weight:600;cursor:pointer;white-space:nowrap}
|
|
20
|
+
.btn.sig{background:#4c7fd0}.btn.ghost{background:none;border:1px solid var(--line);color:var(--fg)}.btn:disabled{opacity:.45;cursor:default}.btn:focus-visible{outline:2px solid var(--sig);outline-offset:2px}
|
|
21
|
+
.kv{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:6px 0 2px}.kv div{border:1px solid var(--line);border-radius:12px;padding:12px 14px;background:rgba(0,0,0,.2)}.kv b{display:block;font-family:var(--mono);font-size:15px;font-weight:500;word-break:break-all}.kv span{font-size:12px;color:var(--dim)}
|
|
22
|
+
.msg{font-family:var(--mono);font-size:12.5px;margin-top:10px;min-height:18px;word-break:break-word}.msg.ok{color:var(--sig)}.msg.bad{color:var(--bad)}
|
|
23
|
+
table{width:100%;border-collapse:collapse;font-family:var(--mono);font-size:12px}td,th{padding:9px 6px;border-top:1px solid var(--line);text-align:left;vertical-align:top}th{color:var(--dim);font-weight:400}
|
|
24
|
+
.st{padding:2px 8px;border-radius:6px;border:1px solid var(--line)}.st.done{color:var(--sig);border-color:rgba(110,149,214,.5)}.st.failed{color:var(--bad)}
|
|
25
|
+
.scroll{overflow-x:auto}
|
|
26
|
+
#gate{max-width:420px;margin:12vh auto 0}
|
|
27
|
+
.note{font-size:12.5px;color:var(--dim);margin:10px 0 0}
|
|
28
|
+
</style></head><body>
|
|
29
|
+
<div class="wrap">
|
|
30
|
+
<header><a class="logo" href="/"><img src="/assets/mark-96.png" alt="">Vantyx</a><span class="tag">studio</span></header>
|
|
31
|
+
<div id="gate" class="card"><h2>Studio</h2><p class="sub">Owner only. The key is in the companion data folder on the server (studio/secrets.json), or STUDIO_KEY in the environment.</p>
|
|
32
|
+
<form id="gf"><label for="key">Studio key</label><input id="key" type="password" autocomplete="current-password"><div style="margin-top:14px"><button class="btn">Unlock</button></div><div class="msg bad" id="gm"></div></form></div>
|
|
33
|
+
|
|
34
|
+
<div id="app" hidden>
|
|
35
|
+
<section class="card"><h2>01 · Token</h2><p class="sub">The CA shows in the top bar of vantyxvault.com with a copy button and a Buy link as soon as you save it. It also switches on the holders gate (GitHub source access) and Guardian Pro for vaults that hold the minimum. Leave it empty to hide it.</p>
|
|
36
|
+
<form id="tf"><div class="row"><div style="flex:3"><label for="ca">Contract address</label><input id="ca" placeholder="0x…" spellcheck="false"></div><div><label for="sym">Ticker</label><input id="sym" maxlength="13"></div></div>
|
|
37
|
+
<div style="margin-top:14px"><button class="btn">Save token</button></div><div class="msg" id="tm"></div></form></section>
|
|
38
|
+
|
|
39
|
+
<section class="card"><h2>02 · Buyback wallet</h2><p class="sub">Use a fresh wallet that only holds the ETH for buybacks. The key is encrypted on the server and never shown again. Never paste your main wallet.</p>
|
|
40
|
+
<div class="kv" id="wkv"></div>
|
|
41
|
+
<form id="wf"><label for="pk">Private key of the buyback wallet</label><input id="pk" type="password" autocomplete="off" spellcheck="false" placeholder="0x…">
|
|
42
|
+
<div class="row" style="margin-top:14px"><div style="flex:0"><button class="btn">Save wallet</button></div><div style="flex:0"><button class="btn ghost" type="button" id="wrm">Remove wallet</button></div></div><div class="msg" id="wm"></div></form></section>
|
|
43
|
+
|
|
44
|
+
<section class="card"><h2>03 · Buyback and burn</h2><p class="sub">Enter dollars. The panel pays the matching ETH at the live price, buys the token (Pons curve before graduation, Uniswap v4 after), then sends exactly what it bought to the dead address. Two real transactions.</p>
|
|
45
|
+
<div class="kv" id="bkv"></div>
|
|
46
|
+
<form id="bf"><div class="row"><div><label for="usd">Dollars to spend</label><input id="usd" inputmode="decimal" placeholder="10"></div><div style="flex:0"><button class="btn sig" id="bgo">Buy back and burn</button></div></div><div class="note" id="bq"></div><div class="msg" id="bm"></div></form></section>
|
|
47
|
+
|
|
48
|
+
<section class="card"><h2>04 · Burn supply</h2><p class="sub">Burns tokens the burn wallet already holds, with no buy. Send the supply you want to burn to the burn wallet first, then enter a dollar amount or press Max to burn all of it. One real transaction.</p>
|
|
49
|
+
<div class="kv" id="skv"></div>
|
|
50
|
+
<form id="sf"><div class="row"><div><label for="susd">Dollars of supply to burn</label><input id="susd" inputmode="decimal" placeholder="25"></div><div style="flex:0"><button class="btn ghost" type="button" id="smax">Max</button></div><div style="flex:0"><button class="btn sig" id="sgo">Burn supply</button></div></div><div class="note" id="sq"></div><div class="msg" id="sm"></div></form>
|
|
51
|
+
<p class="note">Recovery: if a buyback bought but did not burn, <button class="btn ghost" type="button" id="held" style="min-height:34px;padding:0 14px;font-size:13px">burn what the wallet holds</button></p></section>
|
|
52
|
+
|
|
53
|
+
<section class="card"><h2>05 · History</h2><p class="sub">Every step is saved before the next wait, so a restart never loses a hash. Finished burns show on the site.</p><div class="scroll"><table id="ht"></table></div></section>
|
|
54
|
+
<section class="card"><h2>Log</h2><div class="scroll"><table id="lt"></table></div></section>
|
|
55
|
+
</div>
|
|
56
|
+
</div>
|
|
57
|
+
<script>
|
|
58
|
+
const $=(i)=>document.getElementById(i),esc=(s)=>String(s??"").replace(/[&<>"]/g,(c)=>({"&":"&","<":"<",">":">",'"':"""}[c]));
|
|
59
|
+
let KEY=sessionStorage.ckKey||"",S=null;
|
|
60
|
+
const api=async(p,o={})=>{const r=await fetch("/api/studio"+p,{...o,headers:{"x-studio-key":KEY,"content-type":"application/json"}});const j=await r.json().catch(()=>({}));if(!r.ok)throw Object.assign(new Error(j.error||"Request failed"),{status:r.status});return j};
|
|
61
|
+
const say=(id,t,ok)=>{const m=$(id);m.textContent=t;m.className="msg "+(ok?"ok":"bad")};
|
|
62
|
+
const usd=(v)=>v==null?"—":"$"+Number(v).toLocaleString("en-US",{maximumFractionDigits:2});
|
|
63
|
+
const num=(v,d=4)=>v==null?"—":Number(v).toLocaleString("en-US",{maximumFractionDigits:d});
|
|
64
|
+
const tx=(h)=>h?`<a href="${S.explorer}/tx/${esc(h)}" target="_blank" rel="noopener">${esc(h.slice(0,10))}…</a>`:"—";
|
|
65
|
+
function render(){const c=S.config;if(document.activeElement!==$("ca"))$("ca").value=c.ca||"";if(document.activeElement!==$("sym"))$("sym").value=c.symbol||"";
|
|
66
|
+
$("wkv").innerHTML=S.wallet?[[S.wallet,"buyback wallet"],[num(S.walletEth,5)+" ETH","balance"],[num(S.spendableEth,5)+" ETH","spendable (gas kept back)"],[S.tokenBal!=null?num(S.tokenBal,0)+" $"+esc(c.symbol):"—","token held"]].map(([b,s])=>`<div><b>${esc(b)}</b><span>${s}</span></div>`).join(""):`<div><b>none</b><span>no wallet saved yet</span></div>`;
|
|
67
|
+
$("bkv").innerHTML=[[usd(S.spendableUsd),"the wallet can spend"],[num(S.totals.bought,0)+" $"+esc(c.symbol),"burned by buybacks"],[`${num(S.totals.boughtEth,4)} ETH`+(S.ethUsd?` (≈ ${usd(Number(S.totals.boughtEth)*S.ethUsd)} now)`:""),"spent on buybacks"],[`${usd(S.todayUsd)} of ${usd(S.dayUsd)}`,"used in the last 24 h"],[usd(S.maxUsd),"max per buyback"],[S.onPons===false?"not on Pons":S.phase==null?"—":S.phase===0?"Pons curve":"Uniswap v4","where it buys"]].map(([b,s])=>`<div><b>${esc(b)}</b><span>${s}</span></div>`).join("");
|
|
68
|
+
$("skv").innerHTML=[[S.tokenBal!=null?num(S.tokenBal,0)+" $"+esc(c.symbol):"—","in the burn wallet"],[usd(S.tokenBalUsd),"worth now"],[S.tokenPriceUsd?"$"+Number(S.tokenPriceUsd).toPrecision(3):"—","price per token"],[num(S.totals.supply,0)+" $"+esc(c.symbol),"burned from supply"]].map(([b,s])=>`<div><b>${esc(b)}</b><span>${s}</span></div>`).join("");
|
|
69
|
+
quote();
|
|
70
|
+
if(S.error)say("bm","Chain read failed: "+S.error,false);
|
|
71
|
+
$("ht").innerHTML="<tr><th>when</th><th>type</th><th>status</th><th>dollars</th><th>burned</th><th>buy</th><th>burn</th></tr>"+(S.history.map(h=>`<tr><td>${esc(h.t.slice(0,16).replace("T"," "))}</td><td>${esc(h.kind||"buyback")}</td><td><span class="st ${esc(h.status)}">${esc(h.status)}</span></td><td>${h.usd!=null?usd(h.usd):"—"}</td><td>${h.burned?num(h.burned,0):"—"}</td><td>${tx(h.buyTx)}</td><td>${tx(h.burnTx)}</td></tr>`).join("")||'<tr><td colspan="7" style="color:var(--dim)">No burns yet.</td></tr>');
|
|
72
|
+
$("lt").innerHTML=S.logs.map(l=>`<tr><td style="white-space:nowrap">${esc(l.t.slice(5,19).replace("T"," "))}</td><td style="color:${l.level==="error"?"var(--bad)":l.level==="ok"?"var(--sig)":"var(--dim)"}">${esc(l.level)}</td><td>${esc(l.text)}</td></tr>`).join("")||'<tr><td style="color:var(--dim)">Nothing yet.</td></tr>';}
|
|
73
|
+
async function load(){S=await api("/status");render()}
|
|
74
|
+
async function enter(){try{await load();$("gate").hidden=true;$("app").hidden=false;setInterval(()=>load().catch(()=>{}),20000)}catch(e){sessionStorage.removeItem("ckKey");$("gm").textContent=e.message}}
|
|
75
|
+
$("gf").onsubmit=(e)=>{e.preventDefault();KEY=$("key").value.trim();sessionStorage.ckKey=KEY;enter()};if(KEY)enter();
|
|
76
|
+
$("tf").onsubmit=async(e)=>{e.preventDefault();try{const r=await api("/token",{method:"POST",body:JSON.stringify({ca:$("ca").value.trim(),symbol:$("sym").value.trim()})});say("tm",r.warn||(r.config.ca?"Saved. The CA is live in the hero within a minute.":"Saved. The CA is hidden on the site."),!r.warn);load()}catch(x){say("tm",x.message,false)}};
|
|
77
|
+
$("wf").onsubmit=async(e)=>{e.preventDefault();const pk=$("pk").value.trim();$("pk").value="";try{const r=await api("/wallet",{method:"POST",body:JSON.stringify({privateKey:pk})});say("wm","Saved: "+r.address,true);load()}catch(x){say("wm",x.message,false)}};
|
|
78
|
+
$("wrm").onclick=async()=>{if(!confirm("Remove the buyback wallet key from the server?"))return;try{await api("/wallet",{method:"DELETE"});say("wm","Removed.",true);load()}catch(x){say("wm",x.message,false)}};
|
|
79
|
+
// live previews: dollars to ETH for the buyback, dollars to tokens for the supply burn
|
|
80
|
+
let MAXED=false;
|
|
81
|
+
function quote(){if(!S)return;const b=+$("usd").value,s=$("susd").value.trim();
|
|
82
|
+
$("bq").textContent=b>0&&S.ethUsd?`≈ ${(b/S.ethUsd).toFixed(6)} ETH at $${Math.round(S.ethUsd).toLocaleString("en-US")} per ETH`:"";
|
|
83
|
+
$("sq").textContent=MAXED&&S.tokenBal?`All ${num(S.tokenBal,0)} $${S.config.symbol} in the wallet (≈ ${usd(S.tokenBalUsd)})`:(+s>0&&S.tokenPriceUsd?`≈ ${num(+s/S.tokenPriceUsd,0)} $${S.config.symbol}`:"")}
|
|
84
|
+
$("usd").oninput=quote;$("susd").oninput=()=>{MAXED=false;quote()};
|
|
85
|
+
$("smax").onclick=()=>{MAXED=true;$("susd").value=S&&S.tokenBalUsd!=null?String(S.tokenBalUsd):"";quote()};
|
|
86
|
+
$("bf").onsubmit=async(e)=>{e.preventDefault();const u=$("usd").value.trim();if(!u)return;if(!confirm(`Spend $${u} of ETH on $${S.config.symbol} and burn everything it buys? This sends two real transactions.`))return;const b=$("bgo");b.disabled=true;b.textContent="Working…";say("bm","Buying, then burning. Keep this tab open.",true);
|
|
87
|
+
try{const r=await api("/buyback",{method:"POST",body:JSON.stringify({usd:u})});say("bm",`Burned ${num(r.burned,0)} $${S.config.symbol} for $${r.usd}. Buy ${r.buyTx.slice(0,10)}…, burn ${r.burnTx.slice(0,10)}…`,true);$("usd").value=""}catch(x){say("bm",x.message,false)}finally{b.disabled=false;b.textContent="Buy back and burn";load()}};
|
|
88
|
+
$("sf").onsubmit=async(e)=>{e.preventDefault();const u=MAXED?"max":$("susd").value.trim();if(!u)return;const what=MAXED?`ALL ${num(S.tokenBal,0)} $${S.config.symbol} in the burn wallet`:`$${u} of $${S.config.symbol}`;
|
|
89
|
+
if(!confirm(`Burn ${what} from supply? Tokens sent to the dead address can never come back.`))return;if(MAXED&&!confirm("Last check: burn everything the burn wallet holds?"))return;
|
|
90
|
+
const b=$("sgo");b.disabled=true;b.textContent="Burning…";say("sm","Burning. Keep this tab open.",true);
|
|
91
|
+
try{const r=await api("/supply",{method:"POST",body:JSON.stringify({usd:u})});say("sm",`Burned ${num(r.burned,0)} $${S.config.symbol} (≈ $${r.usd}). Tx ${r.burnTx.slice(0,10)}…`,true);$("susd").value="";MAXED=false}catch(x){say("sm",x.message,false)}finally{b.disabled=false;b.textContent="Burn supply";load()}};
|
|
92
|
+
$("held").onclick=async()=>{if(!confirm("Burn every token the buyback wallet holds?"))return;try{const r=await api("/burn-held",{method:"POST"});say("bm",`Burned ${num(r.burned,0)} held tokens.`,true)}catch(x){say("bm",x.message,false)}load()};
|
|
93
|
+
</script></body></html>
|
package/src/agents.mjs
CHANGED
|
@@ -19,9 +19,10 @@ export function listAgents() {
|
|
|
19
19
|
return load().agents.map(pub_);
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export function createAgent({ name, kind, vault, to, amount, everySeconds, maxPerInvoice }) {
|
|
22
|
+
export async function createAgent({ name, kind, vault, to, amount, everySeconds, maxPerInvoice }) {
|
|
23
23
|
if (!["scheduled", "x402"].includes(kind)) throw new Error("kind must be scheduled or x402");
|
|
24
24
|
if (!/^0x[0-9a-fA-F]{40}$/.test(vault || "")) throw new Error("vault address required");
|
|
25
|
+
await (await import("./hosted.mjs")).requirePro(vault);
|
|
25
26
|
const key = generatePrivateKey();
|
|
26
27
|
const a = {
|
|
27
28
|
id: crypto.randomUUID().slice(0, 8), name: name || kind, kind, vault, address: privateKeyToAccount(key).address, key,
|
|
@@ -65,7 +66,11 @@ function record(id, entry) {
|
|
|
65
66
|
|
|
66
67
|
/// One pass of the scheduler: every scheduled agent that is due pays once, if its allowance still covers it.
|
|
67
68
|
export async function tick(log = console.log) {
|
|
69
|
+
const { requirePro } = await import("./hosted.mjs");
|
|
70
|
+
const pro = new Map();
|
|
68
71
|
for (const a of load().agents) {
|
|
72
|
+
if (!pro.has(a.vault)) pro.set(a.vault, await requirePro(a.vault).then(() => true, () => false));
|
|
73
|
+
if (!pro.get(a.vault)) continue;
|
|
69
74
|
if (a.kind !== "scheduled" || a.paused || !a.everySeconds) continue;
|
|
70
75
|
if (Date.now() - a.lastRun < a.everySeconds * 1000) continue;
|
|
71
76
|
try {
|
|
@@ -91,6 +96,7 @@ export async function agentFetch(id, url, init = {}) {
|
|
|
91
96
|
const a = load().agents.find((x) => x.id === id);
|
|
92
97
|
if (!a || a.kind !== "x402") throw new Error("not an x402 agent");
|
|
93
98
|
if (a.paused) throw new Error("agent is paused");
|
|
99
|
+
await (await import("./hosted.mjs")).requirePro(a.vault);
|
|
94
100
|
let res = await fetch(url, init);
|
|
95
101
|
if (res.status !== 402) return res;
|
|
96
102
|
const inv = await res.json();
|
package/src/guardian.mjs
CHANGED
|
@@ -51,7 +51,7 @@ async function evacuate(vault, v, why, log) {
|
|
|
51
51
|
v.pending = why; // kept until an evacuation succeeds, so a failed attempt is retried on every pass
|
|
52
52
|
try {
|
|
53
53
|
const w = wallet(CONFIG.guardianKey);
|
|
54
|
-
const hash = await w.writeContract({ address: vault, abi: VAULT_ABI, functionName: "evacuate", args: [[CONFIG.usdg]] });
|
|
54
|
+
const hash = await w.writeContract({ address: vault, abi: VAULT_ABI, functionName: "evacuate", args: [[CONFIG.usdg, ...(process.env.VANTYX_TOKEN ? [process.env.VANTYX_TOKEN] : [])]] }); // ETH goes too
|
|
55
55
|
const r = await pub.waitForTransactionReceipt({ hash });
|
|
56
56
|
event(v, { kind: "evacuated", ok: r.status === "success", tx: hash });
|
|
57
57
|
if (r.status === "success") v.pending = null;
|
|
@@ -70,6 +70,8 @@ export async function scan(log = console.log) {
|
|
|
70
70
|
const d = load();
|
|
71
71
|
const head = await pub.getBlockNumber();
|
|
72
72
|
for (const [vault, v] of Object.entries(d.vaults)) {
|
|
73
|
+
// hosted mode: only vaults with an active plan whose guardian is ours
|
|
74
|
+
if (process.env.VANTYX_HOSTED && !(await (await import("./hosted.mjs")).eligible(vault))) continue;
|
|
73
75
|
const from = v.from == null ? head : BigInt(v.from) + 1n;
|
|
74
76
|
if (from > head) continue;
|
|
75
77
|
const [outs, own] = await Promise.all([
|
package/src/holders.mjs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Holder access to the private GitHub repos: the source code (vantyxvault/vantyx) and the holders repo (vantyxvault/holders).
|
|
2
|
+
// A holder signs one message with their wallet that names their GitHub username. If the wallet holds at least the
|
|
3
|
+
// minimum of the Vantyx token, the server invites that username to the repo with read access. Every 30 minutes the
|
|
4
|
+
// server checks each wallet again and removes access when the balance drops below the minimum.
|
|
5
|
+
// One wallet unlocks one GitHub account; moving it to another username removes the old one.
|
|
6
|
+
//
|
|
7
|
+
// Settings (.env): VANTYX_TOKEN (ERC-20 address; else the CA saved in the studio; none = closed until launch), VANTYX_HOLDER_MIN (whole tokens),
|
|
8
|
+
// VANTYX_TOKEN_RPC (defaults to Robinhood Chain), GITHUB_HOLDERS_TOKEN (fine-grained token, collaborators on the repo),
|
|
9
|
+
// VANTYX_HOLDERS_REPO (comma-separated, default vantyxvault/vantyx,vantyxvault/holders; the token needs Administration on
|
|
10
|
+
// each), VANTYX_HOLDERS_RECHECK_MS (default 30 min).
|
|
11
|
+
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { createPublicClient, http, parseAbi, verifyMessage, getAddress, parseUnits, formatUnits } from "viem";
|
|
14
|
+
import { CONFIG } from "./config.mjs";
|
|
15
|
+
|
|
16
|
+
const FILE = join(CONFIG.dataDir, "holders.json");
|
|
17
|
+
const D = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : { wallets: {} };
|
|
18
|
+
const save = () => writeFileSync(FILE, JSON.stringify(D), { mode: 0o600 });
|
|
19
|
+
const ERC20 = parseAbi(["function balanceOf(address) view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)"]);
|
|
20
|
+
const REPOS = (process.env.VANTYX_HOLDERS_REPO || "vantyxvault/vantyx,vantyxvault/holders").split(",").map((r) => r.trim()).filter(Boolean);
|
|
21
|
+
const REPO = REPOS.join(" and "); // as it reads in the signed message
|
|
22
|
+
import { tokenAddress } from "./token.mjs";
|
|
23
|
+
const MIN = process.env.VANTYX_HOLDER_MIN || "0";
|
|
24
|
+
const GH = process.env.GITHUB_HOLDERS_TOKEN || "";
|
|
25
|
+
const client = createPublicClient({ transport: http(process.env.VANTYX_TOKEN_RPC || CONFIG.rpc) });
|
|
26
|
+
const log = (...a) => console.log(new Date().toISOString().slice(11, 19), "[holders]", ...a);
|
|
27
|
+
|
|
28
|
+
const GH_USER = /^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;
|
|
29
|
+
export const claimMessage = (github, wallet, ts) =>
|
|
30
|
+
`Vantyx holders\nGive this GitHub account read access to ${REPO}: ${github}\nWallet: ${String(wallet).toLowerCase()}\nTime: ${ts}`;
|
|
31
|
+
|
|
32
|
+
let meta = null;
|
|
33
|
+
async function token() {
|
|
34
|
+
const address = tokenAddress();
|
|
35
|
+
if (!address) return null;
|
|
36
|
+
if (meta?.address !== address) {
|
|
37
|
+
const [decimals, symbol] = await Promise.all([client.readContract({ address, abi: ERC20, functionName: "decimals" }), client.readContract({ address, abi: ERC20, functionName: "symbol" }).catch(() => "VANTYX")]);
|
|
38
|
+
meta = { address, decimals, symbol, min: parseUnits(MIN, decimals) };
|
|
39
|
+
}
|
|
40
|
+
return meta;
|
|
41
|
+
}
|
|
42
|
+
const balance = (wallet) => client.readContract({ address: tokenAddress(), abi: ERC20, functionName: "balanceOf", args: [wallet] });
|
|
43
|
+
|
|
44
|
+
async function gh(method, path, body) {
|
|
45
|
+
const r = await fetch(`${process.env.GITHUB_API || "https://api.github.com"}${path}`, {
|
|
46
|
+
method, headers: { authorization: `Bearer ${GH}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "vantyx-holders" },
|
|
47
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
48
|
+
});
|
|
49
|
+
if (r.status === 404 && method === "GET") return null;
|
|
50
|
+
if (!r.ok && r.status !== 204) throw new Error(`GitHub said ${r.status}`);
|
|
51
|
+
return r.status === 204 ? {} : r.json().catch(() => ({}));
|
|
52
|
+
}
|
|
53
|
+
async function invite(user) {
|
|
54
|
+
for (const repo of REPOS) await gh("PUT", `/repos/${repo}/collaborators/${user}`, { permission: "pull" });
|
|
55
|
+
}
|
|
56
|
+
async function revoke(user) {
|
|
57
|
+
for (const repo of REPOS) {
|
|
58
|
+
await gh("DELETE", `/repos/${repo}/collaborators/${user}`).catch(() => {});
|
|
59
|
+
const pending = (await gh("GET", `/repos/${repo}/invitations?per_page=100`)) || [];
|
|
60
|
+
for (const i of pending) if (i.invitee?.login?.toLowerCase() === user.toLowerCase()) await gh("DELETE", `/repos/${repo}/invitations/${i.id}`).catch(() => {});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function status() {
|
|
65
|
+
const t = await token().catch(() => null);
|
|
66
|
+
return { open: !!(t && GH), repo: REPO, symbol: t?.symbol || null, min: t ? formatUnits(t.min, t.decimals) : null, token: t?.address || null,
|
|
67
|
+
note: t && GH ? null : "Holder access opens at launch, when the token address is announced." };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function claim({ github, wallet, ts, signature }) {
|
|
71
|
+
const t = await token();
|
|
72
|
+
if (!t || !GH) throw new Error("Holder access opens at launch.");
|
|
73
|
+
github = String(github || "").trim().replace(/^@/, "");
|
|
74
|
+
if (!GH_USER.test(github)) throw new Error("That is not a valid GitHub username.");
|
|
75
|
+
wallet = getAddress(wallet);
|
|
76
|
+
if (!Number.isFinite(+ts) || Math.abs(Date.now() - +ts) > 10 * 60_000) throw new Error("The signature is too old. Sign again.");
|
|
77
|
+
if (!(await verifyMessage({ address: wallet, message: claimMessage(github, wallet, ts), signature }))) throw new Error("The signature does not match this wallet.");
|
|
78
|
+
const bal = await balance(wallet);
|
|
79
|
+
if (bal < t.min) throw new Error(`This wallet holds ${formatUnits(bal, t.decimals)} ${t.symbol}; access needs at least ${formatUnits(t.min, t.decimals)}.`);
|
|
80
|
+
const user = await gh("GET", `/users/${github}`);
|
|
81
|
+
if (!user || user.type !== "User") throw new Error("No GitHub user with that name.");
|
|
82
|
+
const prev = D.wallets[wallet];
|
|
83
|
+
if (prev && prev.github.toLowerCase() !== user.login.toLowerCase() && !prev.revoked) await revoke(prev.github);
|
|
84
|
+
await invite(user.login);
|
|
85
|
+
D.wallets[wallet] = { github: user.login, at: Date.now(), checked: Date.now(), revoked: false };
|
|
86
|
+
save(); log("access", user.login, wallet);
|
|
87
|
+
return { ok: true, github: user.login, repo: REPO, repos: REPOS, invite: "https://github.com/notifications", invites: REPOS.map((r) => `https://github.com/${r}/invitations`) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// re-check every holder; remove access below the minimum, give it back if they hold again
|
|
91
|
+
export async function recheck() {
|
|
92
|
+
const t = await token().catch(() => null);
|
|
93
|
+
if (!t || !GH) return;
|
|
94
|
+
for (const [wallet, w] of Object.entries(D.wallets)) {
|
|
95
|
+
try {
|
|
96
|
+
const ok = (await balance(wallet)) >= t.min;
|
|
97
|
+
if (!ok && !w.revoked) { await revoke(w.github); w.revoked = true; log("revoked", w.github, wallet); }
|
|
98
|
+
else if (ok && w.revoked) { await invite(w.github); w.revoked = false; log("restored", w.github, wallet); }
|
|
99
|
+
w.checked = Date.now();
|
|
100
|
+
} catch (e) { log("check failed", wallet, e.message); }
|
|
101
|
+
}
|
|
102
|
+
save();
|
|
103
|
+
}
|
|
104
|
+
if (GH) setInterval(() => recheck().catch(() => {}), +(process.env.VANTYX_HOLDERS_RECHECK_MS || 30 * 60_000)).unref();
|
package/src/hosted.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Hosted Guardian (Guardian Pro). Vantyx runs one guardian key for every vault that has Pro (a plan active in
|
|
2
|
+
// VantyxPlans, or the vault holding the token minimum) and whose on-chain guardian is that key. Rules for a vault can
|
|
3
|
+
// only be set by a wallet that paid for its plan or by the vault's own cold address, proven by a wallet signature. A wrong rule can at worst move funds early to the owner's own fixed cold address.
|
|
4
|
+
import { parseAbi, parseAbiItem, verifyMessage, getAddress, parseUnits, formatUnits } from "viem";
|
|
5
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
6
|
+
import { CONFIG } from "./config.mjs";
|
|
7
|
+
import { pub, VAULT_ABI } from "./chain.mjs";
|
|
8
|
+
import { watch, guardianState } from "./guardian.mjs";
|
|
9
|
+
|
|
10
|
+
export const PLANS = process.env.VANTYX_PLANS || "0x3C4cF3E1bc45CD44E24C0Ca9F77Bf5e89b9804F7";
|
|
11
|
+
const PLANS_FROM = BigInt(process.env.VANTYX_PLANS_FROM || "130747648");
|
|
12
|
+
const PLANS_ABI = parseAbi(["function active(address vault) view returns (uint8 plan, uint64 until)"]);
|
|
13
|
+
const SUBSCRIBED = parseAbiItem("event Subscribed(address indexed vault, address indexed payer, uint8 plan, bool yearly, uint256 periods, uint256 amount, uint64 until)");
|
|
14
|
+
const NAME = { 0: "none", 1: "Guardian Pro", 2: "Team" };
|
|
15
|
+
|
|
16
|
+
export const hostedGuardian = () => (CONFIG.guardianKey ? privateKeyToAccount(CONFIG.guardianKey).address : null);
|
|
17
|
+
|
|
18
|
+
// Holding the Vantyx token also gives Guardian Pro: the vault itself must hold at least VANTYX_HOLDER_MIN whole tokens
|
|
19
|
+
// of VANTYX_TOKEN. Read on chain every time, so there is nothing to claim, and it ends when the balance drops.
|
|
20
|
+
import { tokenAddress } from "./token.mjs";
|
|
21
|
+
const ERC20 = parseAbi(["function balanceOf(address) view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)"]);
|
|
22
|
+
let tokenMeta = null;
|
|
23
|
+
export async function holder(vault) {
|
|
24
|
+
const TOKEN = tokenAddress();
|
|
25
|
+
if (!TOKEN) return { holds: false, reason: "the token launches soon" };
|
|
26
|
+
if (tokenMeta?.address !== TOKEN) {
|
|
27
|
+
const [decimals, symbol] = await Promise.all([
|
|
28
|
+
pub.readContract({ address: TOKEN, abi: ERC20, functionName: "decimals" }),
|
|
29
|
+
pub.readContract({ address: TOKEN, abi: ERC20, functionName: "symbol" }).catch(() => "VANTYX"),
|
|
30
|
+
]);
|
|
31
|
+
tokenMeta = { address: TOKEN, decimals, symbol, min: parseUnits(process.env.VANTYX_HOLDER_MIN || "0", decimals) };
|
|
32
|
+
}
|
|
33
|
+
const bal = await pub.readContract({ address: TOKEN, abi: ERC20, functionName: "balanceOf", args: [vault] });
|
|
34
|
+
return { holds: tokenMeta.min > 0n && bal >= tokenMeta.min, balance: formatUnits(bal, tokenMeta.decimals), min: formatUnits(tokenMeta.min, tokenMeta.decimals), symbol: tokenMeta.symbol, token: TOKEN };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function plan(vault) {
|
|
38
|
+
const [p, until] = await pub.readContract({ address: PLANS, abi: PLANS_ABI, functionName: "active", args: [vault] });
|
|
39
|
+
return { plan: Number(p), name: NAME[Number(p)], until: Number(until) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// Wallets that have paid for this vault, read from the contract's own events.
|
|
43
|
+
export async function payers(vault) {
|
|
44
|
+
const head = await pub.getBlockNumber();
|
|
45
|
+
const out = new Set();
|
|
46
|
+
const STEP = 2_000_000n;
|
|
47
|
+
for (let from = PLANS_FROM; from <= head; from += STEP) {
|
|
48
|
+
const to = from + STEP - 1n > head ? head : from + STEP - 1n;
|
|
49
|
+
const logs = await pub.getLogs({ address: PLANS, event: SUBSCRIBED, args: { vault }, fromBlock: from, toBlock: to });
|
|
50
|
+
for (const l of logs) out.add(l.args.payer.toLowerCase());
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const rulesMessage = (vault, r, ts) =>
|
|
56
|
+
`Vantyx hosted Guardian rules\nvault: ${vault.toLowerCase()}\nmax single: ${r.maxSingle || "none"}\nmax daily: ${r.maxDaily || "none"}\ntime: ${ts}`;
|
|
57
|
+
|
|
58
|
+
export async function setRules({ vault, maxSingle, maxDaily, ts, signature }) {
|
|
59
|
+
vault = getAddress(String(vault).toLowerCase());
|
|
60
|
+
if (Math.abs(Date.now() / 1000 - Number(ts)) > 600) throw new Error("the signed message is too old; sign again");
|
|
61
|
+
const p = await plan(vault);
|
|
62
|
+
const h = p.plan ? { holds: false } : await holder(vault).catch(() => ({ holds: false }));
|
|
63
|
+
if (!p.plan && !h.holds) throw new Error("this vault has no Guardian Pro: no active plan, and it doesn't hold the token minimum");
|
|
64
|
+
const message = rulesMessage(vault, { maxSingle, maxDaily }, ts);
|
|
65
|
+
// who may set rules: a wallet that paid for the plan, or the vault's own cold address (fixed by the vault's
|
|
66
|
+
// signature and held by the owner), which is how token holders, who paid nobody, set theirs
|
|
67
|
+
const cold = await pub.readContract({ address: vault, abi: VAULT_ABI, functionName: "evacuateTo" }).catch(() => null);
|
|
68
|
+
const allowed = new Set(await payers(vault));
|
|
69
|
+
if (cold && !/^0x0{40}$/i.test(cold)) allowed.add(cold.toLowerCase());
|
|
70
|
+
let signer = null;
|
|
71
|
+
for (const a of allowed) if (await verifyMessage({ address: a, message, signature })) signer = a;
|
|
72
|
+
if (!signer) throw new Error("rules can only be set by a wallet that paid for this vault's plan, or by the vault's cold address");
|
|
73
|
+
watch(vault, { maxSingle: maxSingle || null, maxDaily: maxDaily || null, unknownOwner: false });
|
|
74
|
+
return status(vault);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function status(vault) {
|
|
78
|
+
vault = getAddress(String(vault).toLowerCase());
|
|
79
|
+
const [p, guardian, h] = await Promise.all([plan(vault), pub.readContract({ address: vault, abi: VAULT_ABI, functionName: "guardian" }).catch(() => null), holder(vault).catch(() => ({ holds: false }))]);
|
|
80
|
+
const g = guardianState(vault);
|
|
81
|
+
const hg = hostedGuardian();
|
|
82
|
+
return {
|
|
83
|
+
vault, ...p, holder: h, pro: !!(p.plan || h.holds), hostedGuardian: hg, vaultGuardian: guardian,
|
|
84
|
+
guardianIsHosted: !!(hg && guardian && guardian.toLowerCase() === hg.toLowerCase()),
|
|
85
|
+
rules: g?.rules || null, events: (g?.events || []).slice(0, 20),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Only vaults with an active plan and the hosted guardian set get watched.
|
|
90
|
+
export async function eligible(vault) {
|
|
91
|
+
const s = await status(vault).catch(() => null);
|
|
92
|
+
return !!(s && s.pro && s.guardianIsHosted);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Agents and the Guardian are part of Guardian Pro: a paid plan, or the vault holding the token minimum.
|
|
96
|
+
/// Core (free) is the offline vault and its post-quantum keys.
|
|
97
|
+
/// Set VANTYX_REQUIRE_PLAN=0 only for local test chains, where the plan contract does not exist.
|
|
98
|
+
export async function requirePro(vault) {
|
|
99
|
+
if (process.env.VANTYX_REQUIRE_PLAN === "0") return;
|
|
100
|
+
vault = getAddress(String(vault).toLowerCase());
|
|
101
|
+
const p = await plan(vault).catch(() => ({ plan: 0 }));
|
|
102
|
+
if (p.plan) return;
|
|
103
|
+
const h = await holder(vault).catch(() => ({ holds: false }));
|
|
104
|
+
if (h.holds) return;
|
|
105
|
+
throw new Error(`agents and the Guardian need Guardian Pro for this vault: subscribe at https://vantyxvault.com/subscribe/?vault=${vault}${tokenAddress() ? `, or keep at least ${h.min} ${h.symbol} in the vault` : ""}`);
|
|
106
|
+
}
|
package/src/pq.mjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// The vault's three post-quantum keys on the online side, mirroring vantyx-core:
|
|
2
|
+
// ML-DSA-65 (FIPS 204) identity signature on every action, and on the genesis statement
|
|
3
|
+
// SLH-DSA-SHAKE-128s (205) conservative hash-based signature on the genesis statement and on every key rotation
|
|
4
|
+
// ML-KEM-768 (FIPS 203) the status QR (sync) is encrypted to it, so only that vault can read it
|
|
5
|
+
import { keccak256, getAddress } from "viem";
|
|
6
|
+
import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";
|
|
7
|
+
import { slh_dsa_shake_128s } from "@noble/post-quantum/slh-dsa.js";
|
|
8
|
+
import { ml_kem768 } from "@noble/post-quantum/ml-kem.js";
|
|
9
|
+
import { shake256 } from "@noble/hashes/sha3.js";
|
|
10
|
+
import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
|
|
13
|
+
const CTX = new TextEncoder().encode("vantyx/v1");
|
|
14
|
+
export const bytes = (h) => Uint8Array.from(Buffer.from(String(h).replace(/^0x/, ""), "hex"));
|
|
15
|
+
const hex = (b) => "0x" + Buffer.from(b).toString("hex");
|
|
16
|
+
const be = (n, len) => { const b = new Uint8Array(len); let v = BigInt(n); for (let i = len - 1; i >= 0; i--) { b[i] = Number(v & 0xffn); v >>= 8n; } return b; };
|
|
17
|
+
|
|
18
|
+
/// Same as vantyx-core hash::shake: SHAKE-256("vantyx/" || label || 0x00 || for each part: u32 length || part).
|
|
19
|
+
export function shake(label, parts, n = 32) {
|
|
20
|
+
const chunks = [new TextEncoder().encode("vantyx/" + label), new Uint8Array([0])];
|
|
21
|
+
for (const p of parts) chunks.push(be(p.length, 4), p);
|
|
22
|
+
return shake256(Buffer.concat(chunks.map((c) => Buffer.from(c))), { dkLen: n });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function genesisStatement(g) {
|
|
26
|
+
return shake("genesis", [
|
|
27
|
+
be(g.chain_id, 8), bytes(g.identity), bytes(g.chain_head), be(g.chain_len, 4), bytes(g.wots_root),
|
|
28
|
+
new Uint8Array([g.wots_height]), new Uint8Array([g.mode]), bytes(g.guardian), bytes(g.evacuate_to),
|
|
29
|
+
bytes(g.ml_dsa_public), bytes(g.slh_dsa_public), bytes(g.ml_kem_public),
|
|
30
|
+
]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Checks a genesis from the offline app: the identity is the hash of its ML-DSA key, and both ML-DSA-65 and
|
|
34
|
+
/// SLH-DSA-128s signed exactly these values (including the guardian and the cold address).
|
|
35
|
+
export function verifyGenesis(g, chainId) {
|
|
36
|
+
for (const k of ["identity", "chain_head", "wots_root", "guardian", "evacuate_to", "ml_dsa_public", "slh_dsa_public", "ml_kem_public", "statement", "dsa_sig", "slh_sig"])
|
|
37
|
+
if (!g?.[k]) throw new Error(`genesis is missing ${k}: update Vantyx Vault and show the deploy QR again`);
|
|
38
|
+
if (Number(g.chain_id) !== Number(chainId)) throw new Error(`this genesis is for chain ${g.chain_id}, the companion is on ${chainId}`);
|
|
39
|
+
if (keccak256(bytes(g.ml_dsa_public)) !== g.identity.toLowerCase()) throw new Error("the identity is not the hash of the ML-DSA-65 key");
|
|
40
|
+
const stm = genesisStatement(g);
|
|
41
|
+
if (hex(stm) !== g.statement.toLowerCase()) throw new Error("the genesis statement does not match its fields");
|
|
42
|
+
if (!ml_dsa65.verify(bytes(g.dsa_sig), stm, bytes(g.ml_dsa_public), { context: CTX })) throw new Error("the ML-DSA-65 signature on the genesis is wrong");
|
|
43
|
+
if (!slh_dsa_shake_128s.verify(bytes(g.slh_sig), stm, bytes(g.slh_dsa_public), { context: CTX })) throw new Error("the SLH-DSA-128s signature on the genesis is wrong");
|
|
44
|
+
return { guardian: getAddress(g.guardian), evacuateTo: getAddress(g.evacuate_to) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const verifySlh = (sigHex, msgHex, pkHex) => slh_dsa_shake_128s.verify(bytes(sigHex), bytes(msgHex), bytes(pkHex), { context: CTX });
|
|
48
|
+
|
|
49
|
+
/// Encrypts the vault's status to its ML-KEM-768 key: shared secret -> SHAKE-256 key -> XChaCha20-Poly1305.
|
|
50
|
+
export function sealSync(view, kemPublicHex) {
|
|
51
|
+
const { cipherText, sharedSecret } = ml_kem768.encapsulate(bytes(kemPublicHex));
|
|
52
|
+
const key = shake("sync", [sharedSecret]);
|
|
53
|
+
const nonce = new Uint8Array(randomBytes(24));
|
|
54
|
+
const sealed = xchacha20poly1305(key, nonce, new TextEncoder().encode("vantyx/sync")).encrypt(new TextEncoder().encode(JSON.stringify(view)));
|
|
55
|
+
return { type: "sync-kem", ct: hex(cipherText), nonce: hex(nonce), sealed: hex(sealed) };
|
|
56
|
+
}
|