vantyx-cli 0.0.0-stage → 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/src/agents.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // Online agents. Each has its own hot key, and can only spend what the offline vault allowed it (on chain:
2
+ // daily cap, total cap, expiry, optional fixed recipient). Losing an agent key loses at most its allowance.
3
+ // scheduled pays a fixed amount to a fixed address every N seconds
4
+ // x402 pays HTTP 402 invoices for an API it calls, within a per-invoice maximum
5
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
8
+ import { stringToHex, pad } from "viem";
9
+ import { CONFIG } from "./config.mjs";
10
+ import { pub, wallet, VAULT_ABI, remaining } from "./chain.mjs";
11
+
12
+ const FILE = join(CONFIG.dataDir, "agents.json");
13
+ const D = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : { agents: [] };
14
+ const load = () => D;
15
+ const save = () => writeFileSync(FILE, JSON.stringify(D, null, 1), { mode: 0o600 });
16
+ const pub_ = ({ key, ...rest }) => rest; // never send keys to the dashboard
17
+
18
+ export function listAgents() {
19
+ return load().agents.map(pub_);
20
+ }
21
+
22
+ export async function createAgent({ name, kind, vault, to, amount, everySeconds, maxPerInvoice }) {
23
+ if (!["scheduled", "x402"].includes(kind)) throw new Error("kind must be scheduled or x402");
24
+ if (!/^0x[0-9a-fA-F]{40}$/.test(vault || "")) throw new Error("vault address required");
25
+ await (await import("./hosted.mjs")).requirePro(vault);
26
+ const key = generatePrivateKey();
27
+ const a = {
28
+ id: crypto.randomUUID().slice(0, 8), name: name || kind, kind, vault, address: privateKeyToAccount(key).address, key,
29
+ to: to || null, amount: amount ? String(amount) : null, everySeconds: everySeconds ? Number(everySeconds) : null,
30
+ maxPerInvoice: maxPerInvoice ? String(maxPerInvoice) : null, paused: false, lastRun: 0, history: [],
31
+ };
32
+ const d = load();
33
+ d.agents.push(a);
34
+ save();
35
+ return pub_(a);
36
+ }
37
+
38
+ export function updateAgent(id, patch) {
39
+ const d = load();
40
+ const a = d.agents.find((x) => x.id === id);
41
+ if (!a) throw new Error("no such agent");
42
+ for (const k of ["paused", "name", "to", "amount", "everySeconds", "maxPerInvoice"]) if (k in patch) a[k] = patch[k];
43
+ save();
44
+ return pub_(a);
45
+ }
46
+
47
+ const memo = (s) => pad(stringToHex(String(s).slice(0, 31)), { size: 32, dir: "right" });
48
+
49
+ async function pay(a, to, amount, note) {
50
+ const w = wallet(a.key);
51
+ const hash = await w.writeContract({ address: a.vault, abi: VAULT_ABI, functionName: "agentPay", args: [to, BigInt(amount), memo(note)] });
52
+ const r = await pub.waitForTransactionReceipt({ hash });
53
+ if (r.status !== "success") throw new Error(`payment reverted (${hash})`);
54
+ return hash;
55
+ }
56
+
57
+ function record(id, entry) {
58
+ const d = load();
59
+ const a = d.agents.find((x) => x.id === id);
60
+ if (!a) return;
61
+ a.history.unshift({ at: Date.now(), ...entry });
62
+ a.history = a.history.slice(0, 50);
63
+ if (entry.ran) a.lastRun = Date.now();
64
+ save();
65
+ }
66
+
67
+ /// One pass of the scheduler: every scheduled agent that is due pays once, if its allowance still covers it.
68
+ export async function tick(log = console.log) {
69
+ const { requirePro } = await import("./hosted.mjs");
70
+ const pro = new Map();
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;
74
+ if (a.kind !== "scheduled" || a.paused || !a.everySeconds) continue;
75
+ if (Date.now() - a.lastRun < a.everySeconds * 1000) continue;
76
+ try {
77
+ const left = await remaining(a.vault, a.address);
78
+ if (BigInt(left.today) < BigInt(a.amount)) {
79
+ record(a.id, { ran: true, ok: false, note: "allowance does not cover this payment today" });
80
+ continue;
81
+ }
82
+ const tx = await pay(a, a.to, a.amount, `sched-${a.id}`);
83
+ record(a.id, { ran: true, ok: true, tx, amount: a.amount, to: a.to });
84
+ log(`agent ${a.name} paid ${a.amount} to ${a.to} (${tx})`);
85
+ } catch (e) {
86
+ record(a.id, { ran: true, ok: false, note: e.shortMessage || e.message });
87
+ }
88
+ }
89
+ }
90
+
91
+ /// x402-style fetch for an agent: on "402 Payment Required" with a JSON invoice
92
+ /// { "payTo": "0x…", "amount": "…", "asset": "<USDG address>", "invoice": "<id>" }
93
+ /// it pays through the vault (within maxPerInvoice and the on-chain allowance) and retries with
94
+ /// X-PAYMENT: <invoice>:<tx hash>
95
+ export async function agentFetch(id, url, init = {}) {
96
+ const a = load().agents.find((x) => x.id === id);
97
+ if (!a || a.kind !== "x402") throw new Error("not an x402 agent");
98
+ if (a.paused) throw new Error("agent is paused");
99
+ await (await import("./hosted.mjs")).requirePro(a.vault);
100
+ let res = await fetch(url, init);
101
+ if (res.status !== 402) return res;
102
+ const inv = await res.json();
103
+ if (String(inv.asset).toLowerCase() !== CONFIG.usdg.toLowerCase()) throw new Error("invoice is not in USDG");
104
+ if (a.maxPerInvoice && BigInt(inv.amount) > BigInt(a.maxPerInvoice)) throw new Error(`invoice ${inv.amount} is above this agent's limit ${a.maxPerInvoice}`);
105
+ const tx = await pay(a, inv.payTo, inv.amount, inv.invoice);
106
+ record(a.id, { ran: true, ok: true, tx, amount: inv.amount, to: inv.payTo, note: `x402 ${url}` });
107
+ return fetch(url, { ...init, headers: { ...(init.headers || {}), "X-PAYMENT": `${inv.invoice}:${tx}` } });
108
+ }
package/src/chain.mjs ADDED
@@ -0,0 +1,111 @@
1
+ // Chain access: reading a vault, deploying one, and putting the offline vault's signed actions on chain.
2
+ import { readFileSync } from "node:fs";
3
+ import { createPublicClient, createWalletClient, defineChain, getAddress, http, keccak256, parseAbi } from "viem";
4
+
5
+ /// Accepts an address in any letter case (people paste lowercase), rejects anything else.
6
+ export const addr = (a) => getAddress(String(a).toLowerCase());
7
+ import { privateKeyToAccount } from "viem/accounts";
8
+ import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";
9
+ import { CONFIG } from "./config.mjs";
10
+
11
+ const art = JSON.parse(readFileSync(new URL("../abi/VantyxVault.json", import.meta.url)));
12
+ export const VAULT_ABI = art.abi;
13
+ export const ERC20 = parseAbi(["function balanceOf(address) view returns (uint256)", "function transfer(address,uint256) returns (bool)", "event Transfer(address indexed from, address indexed to, uint256 value)"]);
14
+
15
+ export const chain = defineChain({
16
+ id: CONFIG.chainId,
17
+ name: CONFIG.chainId === 4663 ? "Robinhood Chain" : `chain ${CONFIG.chainId}`,
18
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
19
+ rpcUrls: { default: { http: [CONFIG.rpc] } },
20
+ });
21
+ export const pub = createPublicClient({ chain, transport: http(CONFIG.rpc) });
22
+
23
+ export function wallet(key) {
24
+ if (!key) throw new Error("no key configured for this role");
25
+ return createWalletClient({ account: privateKeyToAccount(key), chain, transport: http(CONFIG.rpc) });
26
+ }
27
+
28
+ const read = (vault, functionName, args = []) => pub.readContract({ address: vault, abi: VAULT_ABI, functionName, args });
29
+
30
+ /// The counters the offline vault needs to stay in step ("sync").
31
+ export async function vaultStatus(vault) {
32
+ const [mode, nonce, chainUsed, nextLeaf, epoch, identity, guardian, evacuateTo, chainLen, wotsHeight] = await Promise.all(
33
+ ["mode", "nonce", "chainUsed", "nextLeaf", "epoch", "identity", "guardian", "evacuateTo", "chainLen", "wotsHeight"].map((f) => read(vault, f)),
34
+ );
35
+ const usdg = await pub.readContract({ address: CONFIG.usdg, abi: ERC20, functionName: "balanceOf", args: [vault] });
36
+ return {
37
+ vault, mode: Number(mode), nonce: Number(nonce), chain_used: Number(chainUsed), next_leaf: Number(nextLeaf), epoch: Number(epoch),
38
+ identity, guardian, evacuateTo, chainLeft: Number(chainLen) - Number(chainUsed), oneTimeKeysLeft: 2 ** Number(wotsHeight) - Number(nextLeaf),
39
+ usdg: usdg.toString(),
40
+ };
41
+ }
42
+
43
+ export async function remaining(vault, agent) {
44
+ const [today, total] = await read(vault, "remaining", [agent]);
45
+ return { today: today.toString(), total: total.toString() };
46
+ }
47
+
48
+ /// Deploys a vault from the genesis data the offline app shows (by QR) on creation.
49
+ export async function deployVault(g, { guardian, evacuateTo }) {
50
+ const w = wallet(CONFIG.relayerKey);
51
+ const hash = await w.deployContract({
52
+ abi: VAULT_ABI,
53
+ bytecode: art.bytecode,
54
+ args: [g.identity, g.mode, g.chain_head, g.chain_len, g.wots_root, g.wots_height, w.account.address, addr(guardian || "0x0000000000000000000000000000000000000000"), addr(evacuateTo || "0x0000000000000000000000000000000000000000")],
55
+ });
56
+ const r = await pub.waitForTransactionReceipt({ hash });
57
+ if (r.status !== "success") throw new Error("deployment failed");
58
+ return { vault: r.contractAddress, tx: hash };
59
+ }
60
+
61
+ /// Checks the ML-DSA-65 identity signature in a signed bundle against the vault's registered identity.
62
+ export async function checkIdentity(bundle, mlDsaPublicHex) {
63
+ const pk = hexBytes(mlDsaPublicHex);
64
+ const onChain = await read(bundle.vault, "identity");
65
+ if (keccak256(pk) !== onChain) return { ok: false, reason: "this ML-DSA public key is not the vault's identity" };
66
+ const ok = ml_dsa65.verify(hexBytes(bundle.identity_sig), hexBytes(bundle.action_hash), pk, { context: new TextEncoder().encode("vantyx/v1") });
67
+ return ok ? { ok: true } : { ok: false, reason: "the ML-DSA-65 signature does not match the action" };
68
+ }
69
+
70
+ /// Puts a signed action on chain. Fast: commit, wait one block, reveal. Strict: one execute.
71
+ export async function submit(bundle, log = () => {}) {
72
+ const w = wallet(CONFIG.relayerKey);
73
+ const vault = bundle.vault;
74
+ const st = await vaultStatus(vault);
75
+ if (st.nonce !== bundle.nonce) throw new Error(`the vault is at nonce ${st.nonce}, this action is for nonce ${bundle.nonce}`);
76
+ const expected = await read(vault, "actionHash", [bundle.kind, bundle.data]);
77
+ if (expected !== bundle.action_hash) throw new Error("the contract hashes this action differently (wrong vault or chain?)");
78
+ if (bundle.mode === "fast") {
79
+ if (st.mode !== 0) throw new Error("the vault is in strict mode; sign the action again");
80
+ const c = await w.writeContract({ address: vault, abi: VAULT_ABI, functionName: "commit", args: [bundle.fast.commitment] });
81
+ const cr = await pub.waitForTransactionReceipt({ hash: c });
82
+ log(`committed in block ${cr.blockNumber}`);
83
+ // On Arbitrum chains (Robinhood Chain) block.number in a contract is the L1 block, about 12 s apart:
84
+ // retry until the contract accepts the reveal, i.e. until it sees a later block than the commit's.
85
+ for (let i = 0; ; i++) {
86
+ try { await pub.simulateContract({ address: vault, abi: VAULT_ABI, functionName: "reveal", args: [bundle.kind, bundle.data, bundle.fast.preimage], account: w.account }); break; }
87
+ catch (e) { if (i > 40 || !/NotCommitted/.test(e.message)) throw e; await new Promise((r) => setTimeout(r, 1500)); }
88
+ }
89
+ const h = await w.writeContract({ address: vault, abi: VAULT_ABI, functionName: "reveal", args: [bundle.kind, bundle.data, bundle.fast.preimage] });
90
+ return outcome(h, "reveal");
91
+ }
92
+ if (st.mode !== 1) throw new Error("the vault is in fast mode; sign the action again");
93
+ const s = bundle.strict;
94
+ const h = await w.writeContract({ address: vault, abi: VAULT_ABI, functionName: "execute", args: [bundle.kind, bundle.data, s.leaf, s.sig, s.path] });
95
+ return outcome(h, "execute");
96
+ }
97
+
98
+ async function outcome(hash, step) {
99
+ const r = await pub.waitForTransactionReceipt({ hash });
100
+ if (r.status !== "success") throw new Error(`${step} transaction reverted (${hash})`);
101
+ const ev = r.logs.map((l) => { try { return decodeVault(l); } catch { return null; } }).find((e) => e?.eventName === "Executed");
102
+ return { tx: hash, block: Number(r.blockNumber), ok: ev ? ev.args.ok : null, nonce: ev ? Number(ev.args.nonce) : null };
103
+ }
104
+
105
+ import { decodeEventLog } from "viem";
106
+ export const decodeVault = (l) => decodeEventLog({ abi: VAULT_ABI, data: l.data, topics: l.topics });
107
+
108
+ export function hexBytes(h) {
109
+ const s = h.startsWith("0x") ? h.slice(2) : h;
110
+ return Uint8Array.from(s.match(/../g).map((x) => parseInt(x, 16)));
111
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,19 @@
1
+ // Settings come from the environment. Keys here are online "hot" keys that can only pay gas (relayer), spend inside
2
+ // an allowance (agents) or evacuate to the owner's fixed address (guardian). The vault's own keys never come online.
3
+ import { mkdirSync } from "node:fs";
4
+ import { resolve, join } from "node:path";
5
+ import { homedir } from "node:os";
6
+
7
+ const env = process.env;
8
+ export const CONFIG = {
9
+ rpc: env.VANTYX_RPC || "https://rpc.mainnet.chain.robinhood.com",
10
+ chainId: Number(env.VANTYX_CHAIN_ID || 4663),
11
+ usdg: env.VANTYX_USDG || "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
12
+ port: Number(env.PORT || 5893),
13
+ host: env.HOST || "127.0.0.1",
14
+ dataDir: resolve(env.VANTYX_DATA || (env.VANTYX_CLI ? join(homedir(), ".vantyx") : "./data")),
15
+ relayerKey: env.VANTYX_RELAYER_KEY || "",
16
+ guardianKey: env.VANTYX_GUARDIAN_KEY || "",
17
+ pollMs: Number(env.VANTYX_POLL_MS || 4000),
18
+ };
19
+ mkdirSync(CONFIG.dataDir, { recursive: true, mode: 0o700 });
package/src/frames.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // Animated-QR frames "VX1/<i>/<n>/<crc32 hex>/<base32>", the same format as vantyx-core's qr module.
2
+ const ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
3
+ export const CHUNK = 480;
4
+
5
+ const CRC = (() => {
6
+ const t = new Uint32Array(256);
7
+ for (let n = 0; n < 256; n++) {
8
+ let c = n;
9
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
10
+ t[n] = c >>> 0;
11
+ }
12
+ return t;
13
+ })();
14
+ export function crc32(b) {
15
+ let c = 0xffffffff;
16
+ for (const x of b) c = CRC[(c ^ x) & 255] ^ (c >>> 8);
17
+ return (c ^ 0xffffffff) >>> 0;
18
+ }
19
+
20
+ export function b32encode(b) {
21
+ let out = "", bits = 0, v = 0;
22
+ for (const x of b) {
23
+ v = (v << 8) | x;
24
+ bits += 8;
25
+ while (bits >= 5) {
26
+ out += ALPHA[(v >>> (bits - 5)) & 31];
27
+ bits -= 5;
28
+ }
29
+ }
30
+ if (bits > 0) out += ALPHA[(v << (5 - bits)) & 31];
31
+ return out;
32
+ }
33
+
34
+ export function b32decode(s) {
35
+ const out = [];
36
+ let bits = 0, v = 0;
37
+ for (const ch of s) {
38
+ const i = ALPHA.indexOf(ch);
39
+ if (i < 0) throw new Error("bad base32");
40
+ v = (v << 5) | i;
41
+ bits += 5;
42
+ if (bits >= 8) {
43
+ out.push((v >>> (bits - 8)) & 255);
44
+ bits -= 8;
45
+ }
46
+ }
47
+ return Uint8Array.from(out);
48
+ }
49
+
50
+ export function frames(payload) {
51
+ const bytes = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
52
+ const crc = crc32(bytes).toString(16).padStart(8, "0").toUpperCase();
53
+ const body = b32encode(bytes);
54
+ const parts = [];
55
+ for (let i = 0; i < body.length; i += CHUNK) parts.push(body.slice(i, i + CHUNK));
56
+ return parts.map((p, i) => `VX1/${i + 1}/${parts.length}/${crc}/${p}`);
57
+ }
58
+
59
+ export class Joiner {
60
+ constructor() { this.n = 0; this.crc = ""; this.got = []; }
61
+ push(frame) {
62
+ const f = frame.trim().split("/");
63
+ if (f.length !== 5 || f[0] !== "VX1") throw new Error("not a Vantyx frame");
64
+ const i = +f[1], n = +f[2];
65
+ if (!(i >= 1 && i <= n)) throw new Error("bad frame number");
66
+ const crc = f[3].toUpperCase();
67
+ if (n !== this.n || crc !== this.crc) { this.n = n; this.crc = crc; this.got = new Array(n).fill(null); }
68
+ this.got[i - 1] = f[4];
69
+ if (this.got.every(Boolean)) {
70
+ const data = b32decode(this.got.join(""));
71
+ if (crc32(data).toString(16).padStart(8, "0").toUpperCase() !== this.crc) throw new Error("frames are from different payloads");
72
+ return data;
73
+ }
74
+ return null;
75
+ }
76
+ progress() { return [this.got.filter(Boolean).length, this.n]; }
77
+ }
@@ -0,0 +1,102 @@
1
+ // Guardian: watches each vault around the clock and calls evacuate() when a rule trips. evacuate() can only send
2
+ // everything to the address the offline vault fixed, and it cancels every agent allowance, so a stolen guardian key
3
+ // cannot steal; at worst it moves funds to the owner's own cold address early.
4
+ //
5
+ // Rules (per vault, all optional):
6
+ // maxSingle one outflow above this amount (USDG units)
7
+ // maxDaily total outflow in 24 h above this amount
8
+ // unknownOwner an owner action executed that this companion never relayed (someone else holds a proof)
9
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { CONFIG } from "./config.mjs";
12
+ import { pub, wallet, VAULT_ABI, ERC20, decodeVault } from "./chain.mjs";
13
+ import { parseAbiItem } from "viem";
14
+
15
+ const FILE = join(CONFIG.dataDir, "guardian.json");
16
+ // one in-memory copy, written through on every change (the scanner and the relayer share it)
17
+ const D = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : { vaults: {} };
18
+ const load = () => D;
19
+ const save = () => writeFileSync(FILE, JSON.stringify(D, null, 1), { mode: 0o600 });
20
+
21
+ export function watch(vault, rules) {
22
+ const d = load();
23
+ const v = d.vaults[vault] || { rules: {}, from: null, outflows: [], events: [], relayed: [], tripped: false };
24
+ v.rules = { maxSingle: rules.maxSingle ? String(rules.maxSingle) : null, maxDaily: rules.maxDaily ? String(rules.maxDaily) : null, unknownOwner: !!rules.unknownOwner };
25
+ d.vaults[vault] = v;
26
+ save();
27
+ return v;
28
+ }
29
+
30
+ export function guardianState(vault) {
31
+ return load().vaults[vault] || null;
32
+ }
33
+
34
+ /// The relayer tells the guardian about every action it put on chain, so "unknownOwner" can tell them apart.
35
+ export function noteRelayed(vault, actionHash) {
36
+ const d = load();
37
+ if (!d.vaults[vault]) return;
38
+ d.vaults[vault].relayed.push(actionHash.toLowerCase());
39
+ save();
40
+ }
41
+
42
+ function event(v, e) {
43
+ v.events.unshift({ at: Date.now(), ...e });
44
+ v.events = v.events.slice(0, 100);
45
+ }
46
+
47
+ async function evacuate(vault, v, why, log) {
48
+ if (v.tripped) return;
49
+ v.tripped = true;
50
+ if (v.pending !== why) event(v, { kind: "trip", note: why });
51
+ v.pending = why; // kept until an evacuation succeeds, so a failed attempt is retried on every pass
52
+ try {
53
+ const w = wallet(CONFIG.guardianKey);
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
+ const r = await pub.waitForTransactionReceipt({ hash });
56
+ event(v, { kind: "evacuated", ok: r.status === "success", tx: hash });
57
+ if (r.status === "success") v.pending = null;
58
+ else v.tripped = false;
59
+ log(`guardian evacuated ${vault}: ${why} (${hash})`);
60
+ } catch (e) {
61
+ v.tripped = false; // try again next pass
62
+ event(v, { kind: "evacuate-failed", note: e.shortMessage || e.message });
63
+ }
64
+ }
65
+
66
+ const TRANSFER = parseAbiItem("event Transfer(address indexed from, address indexed to, uint256 value)");
67
+
68
+ /// One pass over all watched vaults: read new logs since the last block seen, apply the rules.
69
+ export async function scan(log = console.log) {
70
+ const d = load();
71
+ const head = await pub.getBlockNumber();
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;
75
+ const from = v.from == null ? head : BigInt(v.from) + 1n;
76
+ if (from > head) continue;
77
+ const [outs, own] = await Promise.all([
78
+ pub.getLogs({ address: CONFIG.usdg, event: TRANSFER, args: { from: vault }, fromBlock: from, toBlock: head }),
79
+ pub.getLogs({ address: vault, fromBlock: from, toBlock: head }),
80
+ ]);
81
+ v.from = head.toString();
82
+ if (v.pending && !v.tripped) await evacuate(vault, v, v.pending, log);
83
+ const now = Date.now();
84
+ for (const o of outs) {
85
+ const amt = o.args.value;
86
+ v.outflows.push({ at: now, amount: amt.toString(), to: o.args.to, tx: o.transactionHash });
87
+ event(v, { kind: "outflow", amount: amt.toString(), to: o.args.to, tx: o.transactionHash });
88
+ if (v.rules.maxSingle && amt > BigInt(v.rules.maxSingle)) await evacuate(vault, v, `single outflow ${amt} above ${v.rules.maxSingle}`, log);
89
+ }
90
+ v.outflows = v.outflows.filter((o) => now - o.at < 86_400_000);
91
+ const day = v.outflows.reduce((s, o) => s + BigInt(o.amount), 0n);
92
+ if (v.rules.maxDaily && day > BigInt(v.rules.maxDaily)) await evacuate(vault, v, `24 h outflow ${day} above ${v.rules.maxDaily}`, log);
93
+ for (const l of own) {
94
+ let e;
95
+ try { e = decodeVault(l); } catch { continue; }
96
+ if (e.eventName === "Executed" && v.rules.unknownOwner && !v.relayed.includes(e.args.actionHash.toLowerCase()))
97
+ await evacuate(vault, v, `owner action ${e.args.actionHash} was not relayed by this companion`, log);
98
+ if (e.eventName === "Evacuated") event(v, { kind: "evacuated-onchain", tx: l.transactionHash });
99
+ }
100
+ }
101
+ save();
102
+ }
@@ -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
+ }