vantyx-cli 0.0.0-stage → 0.1.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,102 @@
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 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
+ const key = generatePrivateKey();
26
+ const a = {
27
+ id: crypto.randomUUID().slice(0, 8), name: name || kind, kind, vault, address: privateKeyToAccount(key).address, key,
28
+ to: to || null, amount: amount ? String(amount) : null, everySeconds: everySeconds ? Number(everySeconds) : null,
29
+ maxPerInvoice: maxPerInvoice ? String(maxPerInvoice) : null, paused: false, lastRun: 0, history: [],
30
+ };
31
+ const d = load();
32
+ d.agents.push(a);
33
+ save();
34
+ return pub_(a);
35
+ }
36
+
37
+ export function updateAgent(id, patch) {
38
+ const d = load();
39
+ const a = d.agents.find((x) => x.id === id);
40
+ if (!a) throw new Error("no such agent");
41
+ for (const k of ["paused", "name", "to", "amount", "everySeconds", "maxPerInvoice"]) if (k in patch) a[k] = patch[k];
42
+ save();
43
+ return pub_(a);
44
+ }
45
+
46
+ const memo = (s) => pad(stringToHex(String(s).slice(0, 31)), { size: 32, dir: "right" });
47
+
48
+ async function pay(a, to, amount, note) {
49
+ const w = wallet(a.key);
50
+ const hash = await w.writeContract({ address: a.vault, abi: VAULT_ABI, functionName: "agentPay", args: [to, BigInt(amount), memo(note)] });
51
+ const r = await pub.waitForTransactionReceipt({ hash });
52
+ if (r.status !== "success") throw new Error(`payment reverted (${hash})`);
53
+ return hash;
54
+ }
55
+
56
+ function record(id, entry) {
57
+ const d = load();
58
+ const a = d.agents.find((x) => x.id === id);
59
+ if (!a) return;
60
+ a.history.unshift({ at: Date.now(), ...entry });
61
+ a.history = a.history.slice(0, 50);
62
+ if (entry.ran) a.lastRun = Date.now();
63
+ save();
64
+ }
65
+
66
+ /// One pass of the scheduler: every scheduled agent that is due pays once, if its allowance still covers it.
67
+ export async function tick(log = console.log) {
68
+ for (const a of load().agents) {
69
+ if (a.kind !== "scheduled" || a.paused || !a.everySeconds) continue;
70
+ if (Date.now() - a.lastRun < a.everySeconds * 1000) continue;
71
+ try {
72
+ const left = await remaining(a.vault, a.address);
73
+ if (BigInt(left.today) < BigInt(a.amount)) {
74
+ record(a.id, { ran: true, ok: false, note: "allowance does not cover this payment today" });
75
+ continue;
76
+ }
77
+ const tx = await pay(a, a.to, a.amount, `sched-${a.id}`);
78
+ record(a.id, { ran: true, ok: true, tx, amount: a.amount, to: a.to });
79
+ log(`agent ${a.name} paid ${a.amount} to ${a.to} (${tx})`);
80
+ } catch (e) {
81
+ record(a.id, { ran: true, ok: false, note: e.shortMessage || e.message });
82
+ }
83
+ }
84
+ }
85
+
86
+ /// x402-style fetch for an agent: on "402 Payment Required" with a JSON invoice
87
+ /// { "payTo": "0x…", "amount": "…", "asset": "<USDG address>", "invoice": "<id>" }
88
+ /// it pays through the vault (within maxPerInvoice and the on-chain allowance) and retries with
89
+ /// X-PAYMENT: <invoice>:<tx hash>
90
+ export async function agentFetch(id, url, init = {}) {
91
+ const a = load().agents.find((x) => x.id === id);
92
+ if (!a || a.kind !== "x402") throw new Error("not an x402 agent");
93
+ if (a.paused) throw new Error("agent is paused");
94
+ let res = await fetch(url, init);
95
+ if (res.status !== 402) return res;
96
+ const inv = await res.json();
97
+ if (String(inv.asset).toLowerCase() !== CONFIG.usdg.toLowerCase()) throw new Error("invoice is not in USDG");
98
+ if (a.maxPerInvoice && BigInt(inv.amount) > BigInt(a.maxPerInvoice)) throw new Error(`invoice ${inv.amount} is above this agent's limit ${a.maxPerInvoice}`);
99
+ const tx = await pay(a, inv.payTo, inv.amount, inv.invoice);
100
+ record(a.id, { ran: true, ok: true, tx, amount: inv.amount, to: inv.payTo, note: `x402 ${url}` });
101
+ return fetch(url, { ...init, headers: { ...(init.headers || {}), "X-PAYMENT": `${inv.invoice}:${tx}` } });
102
+ }
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,100 @@
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]] });
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
+ const from = v.from == null ? head : BigInt(v.from) + 1n;
74
+ if (from > head) continue;
75
+ const [outs, own] = await Promise.all([
76
+ pub.getLogs({ address: CONFIG.usdg, event: TRANSFER, args: { from: vault }, fromBlock: from, toBlock: head }),
77
+ pub.getLogs({ address: vault, fromBlock: from, toBlock: head }),
78
+ ]);
79
+ v.from = head.toString();
80
+ if (v.pending && !v.tripped) await evacuate(vault, v, v.pending, log);
81
+ const now = Date.now();
82
+ for (const o of outs) {
83
+ const amt = o.args.value;
84
+ v.outflows.push({ at: now, amount: amt.toString(), to: o.args.to, tx: o.transactionHash });
85
+ event(v, { kind: "outflow", amount: amt.toString(), to: o.args.to, tx: o.transactionHash });
86
+ if (v.rules.maxSingle && amt > BigInt(v.rules.maxSingle)) await evacuate(vault, v, `single outflow ${amt} above ${v.rules.maxSingle}`, log);
87
+ }
88
+ v.outflows = v.outflows.filter((o) => now - o.at < 86_400_000);
89
+ const day = v.outflows.reduce((s, o) => s + BigInt(o.amount), 0n);
90
+ if (v.rules.maxDaily && day > BigInt(v.rules.maxDaily)) await evacuate(vault, v, `24 h outflow ${day} above ${v.rules.maxDaily}`, log);
91
+ for (const l of own) {
92
+ let e;
93
+ try { e = decodeVault(l); } catch { continue; }
94
+ if (e.eventName === "Executed" && v.rules.unknownOwner && !v.relayed.includes(e.args.actionHash.toLowerCase()))
95
+ await evacuate(vault, v, `owner action ${e.args.actionHash} was not relayed by this companion`, log);
96
+ if (e.eventName === "Evacuated") event(v, { kind: "evacuated-onchain", tx: l.transactionHash });
97
+ }
98
+ }
99
+ save();
100
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,130 @@
1
+ // Vantyx Companion: the online half. Serves the dashboard and an API on localhost.
2
+ // It never holds the vault's keys: it relays what the offline vault signed, runs agents inside their allowances,
3
+ // and runs the guardian.
4
+ import { createServer } from "node:http";
5
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
6
+ import { join, extname } from "node:path";
7
+ import { CONFIG } from "./config.mjs";
8
+ import { pub, vaultStatus, deployVault, submit, checkIdentity, remaining, decodeVault } from "./chain.mjs";
9
+ import { frames, Joiner } from "./frames.mjs";
10
+ import { listAgents, createAgent, updateAgent, tick, agentFetch } from "./agents.mjs";
11
+ import { watch, guardianState, noteRelayed, scan } from "./guardian.mjs";
12
+ import { privateKeyToAccount } from "viem/accounts";
13
+
14
+ const IDS = join(CONFIG.dataDir, "identities.json");
15
+ const ids = existsSync(IDS) ? JSON.parse(readFileSync(IDS, "utf8")) : {};
16
+ const saveIds = () => writeFileSync(IDS, JSON.stringify(ids), { mode: 0o600 });
17
+ const PUBLIC = new URL("../public/", import.meta.url).pathname;
18
+ const MIME = { ".mjs": "text/javascript", ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon" };
19
+ const isAddr = (s) => /^0x[0-9a-fA-F]{40}$/.test(s || "");
20
+ const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
21
+
22
+ function bundleFrom(body) {
23
+ if (body.bundle) return body.bundle;
24
+ if (Array.isArray(body.frames)) {
25
+ const j = new Joiner();
26
+ let data = null;
27
+ for (const f of body.frames) data = j.push(f) || data;
28
+ if (!data) throw new Error(`incomplete: ${j.progress().join(" of ")} frames`);
29
+ return JSON.parse(new TextDecoder().decode(data));
30
+ }
31
+ throw new Error("send { bundle } or { frames: [...] }");
32
+ }
33
+
34
+ const routes = [
35
+ ["GET", /^\/api\/config$/, async () => ({
36
+ chainId: CONFIG.chainId, rpc: CONFIG.rpc, usdg: CONFIG.usdg,
37
+ relayer: CONFIG.relayerKey ? privateKeyToAccount(CONFIG.relayerKey).address : null,
38
+ guardian: CONFIG.guardianKey ? privateKeyToAccount(CONFIG.guardianKey).address : null,
39
+ block: Number(await pub.getBlockNumber()),
40
+ })],
41
+ ["GET", /^\/api\/vault\/(0x[0-9a-fA-F]{40})$/, async (m) => vaultStatus(m[1])],
42
+ // what the offline vault scans to catch up: its counters as animated-QR frames
43
+ ["GET", /^\/api\/vault\/(0x[0-9a-fA-F]{40})\/sync$/, async (m) => {
44
+ const s = await vaultStatus(m[1]);
45
+ const view = { vault: s.vault, nonce: s.nonce, chain_used: s.chain_used, next_leaf: s.next_leaf, mode: s.mode };
46
+ return { view, frames: frames(JSON.stringify({ type: "sync", ...view })) };
47
+ }],
48
+ ["POST", /^\/api\/deploy$/, async (_, b) => {
49
+ const g = b.genesis || (b.frames && bundleFrom({ frames: b.frames }));
50
+ if (!g?.identity || !g?.chain_head || !g?.wots_root) throw new Error("genesis data missing (scan it from the vault app)");
51
+ const r = await deployVault(g, b);
52
+ if (g.ml_dsa_public) { ids[r.vault.toLowerCase()] = g.ml_dsa_public; saveIds(); }
53
+ log(`deployed vault ${r.vault}`);
54
+ return r;
55
+ }],
56
+ ["POST", /^\/api\/submit$/, async (_, b) => {
57
+ const bundle = bundleFrom(b);
58
+ if (bundle.chain !== CONFIG.chainId) throw new Error(`signed for chain ${bundle.chain}, this companion is on ${CONFIG.chainId}`);
59
+ const pk = b.ml_dsa_public || ids[bundle.vault.toLowerCase()];
60
+ const identity = pk ? await checkIdentity(bundle, pk) : { ok: null, reason: "no ML-DSA public key on file for this vault" };
61
+ if (identity.ok === false) throw new Error(identity.reason);
62
+ noteRelayed(bundle.vault, bundle.action_hash);
63
+ const r = await submit(bundle, log);
64
+ log(`relayed nonce ${bundle.nonce} (${bundle.description}): ${r.ok ? "done" : "proof spent, action failed"}`);
65
+ return { ...r, identity, description: bundle.description };
66
+ }],
67
+ ["GET", /^\/api\/agents$/, async () => {
68
+ const list = listAgents();
69
+ return Promise.all(list.map(async (a) => ({ ...a, remaining: await remaining(a.vault, a.address).catch(() => null) })));
70
+ }],
71
+ ["POST", /^\/api\/agents$/, async (_, b) => createAgent(b)],
72
+ ["PATCH", /^\/api\/agents\/([\w-]+)$/, async (m, b) => updateAgent(m[1], b)],
73
+ ["POST", /^\/api\/agents\/([\w-]+)\/fetch$/, async (m, b) => {
74
+ const r = await agentFetch(m[1], b.url);
75
+ return { status: r.status, body: (await r.text()).slice(0, 2000) };
76
+ }],
77
+ ["GET", /^\/api\/guardian\/(0x[0-9a-fA-F]{40})$/, async (m) => guardianState(m[1])],
78
+ ["POST", /^\/api\/guardian\/(0x[0-9a-fA-F]{40})$/, async (m, b) => watch(m[1], b)],
79
+ // a paid API for trying x402 agents: costs 0.25 USDG per call, paid to DEMO_PAYEE (or the relayer)
80
+ ["GET", /^\/demo\/premium$/, async (_, __, req) => {
81
+ const payTo = process.env.VANTYX_DEMO_PAYEE || (CONFIG.relayerKey && privateKeyToAccount(CONFIG.relayerKey).address);
82
+ const p = req.headers["x-payment"];
83
+ if (p) {
84
+ const [invoice, tx] = String(p).split(":");
85
+ const r = await pub.getTransactionReceipt({ hash: tx }).catch(() => null);
86
+ const paid = r?.logs.map((l) => { try { return decodeVault(l); } catch { return null; } }).find((e) => e?.eventName === "AgentPaid"
87
+ && e.args.to.toLowerCase() === payTo.toLowerCase() && e.args.amount >= 250000n && Buffer.from(e.args.memo.slice(2), "hex").toString().replace(/\0+$/, "") === invoice);
88
+ if (paid) return { ok: true, data: "premium answer, paid on chain", tx };
89
+ }
90
+ return { $status: 402, payTo, amount: "250000", asset: CONFIG.usdg, invoice: `inv-${Date.now().toString(36)}` };
91
+ }],
92
+ ];
93
+
94
+ const server = createServer(async (req, res) => {
95
+ const url = new URL(req.url, "http://x");
96
+ // the API only answers this machine's own pages
97
+ const origin = req.headers.origin;
98
+ if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) { res.writeHead(403).end(); return; }
99
+ for (const [method, re, fn] of routes) {
100
+ const m = url.pathname.match(re);
101
+ if (!m || req.method !== method) continue;
102
+ let body = {};
103
+ if (method !== "GET") {
104
+ const chunks = [];
105
+ for await (const c of req) chunks.push(c);
106
+ try { body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : {}; } catch { body = {}; }
107
+ }
108
+ try {
109
+ const out = await fn(m, body, req);
110
+ const status = out?.$status || 200;
111
+ if (out?.$status) delete out.$status;
112
+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(out ?? null, (_, v) => (typeof v === "bigint" ? v.toString() : v)));
113
+ } catch (e) {
114
+ res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: e.shortMessage || e.message }));
115
+ }
116
+ return;
117
+ }
118
+ // the dashboard uses the same frame code as the server
119
+ const file = url.pathname === "/frames.js" ? new URL("./frames.mjs", import.meta.url).pathname
120
+ : join(PUBLIC, url.pathname === "/" ? "index.html" : url.pathname.replace(/\.\./g, ""));
121
+ if (existsSync(file) && !file.endsWith("/")) {
122
+ res.writeHead(200, { "content-type": MIME[extname(file)] || "application/octet-stream" }).end(readFileSync(file));
123
+ } else res.writeHead(404).end("not found");
124
+ });
125
+
126
+ server.listen(CONFIG.port, CONFIG.host, () => log(`Vantyx Companion on http://${CONFIG.host}:${CONFIG.port} (chain ${CONFIG.chainId})`));
127
+
128
+ const loop = (fn, name) => setInterval(() => fn(log).catch((e) => log(`${name}: ${e.shortMessage || e.message}`)), CONFIG.pollMs);
129
+ loop(tick, "agents");
130
+ if (CONFIG.guardianKey) loop(scan, "guardian");