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/src/server.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // It never holds the vault's keys: it relays what the offline vault signed, runs agents inside their allowances,
3
3
  // and runs the guardian.
4
4
  import { createServer } from "node:http";
5
+ import { createHash, timingSafeEqual } from "node:crypto";
5
6
  import { readFileSync, writeFileSync, existsSync } from "node:fs";
6
7
  import { join, extname } from "node:path";
7
8
  import { CONFIG } from "./config.mjs";
@@ -10,13 +11,15 @@ import { frames, Joiner } from "./frames.mjs";
10
11
  import { listAgents, createAgent, updateAgent, tick, agentFetch } from "./agents.mjs";
11
12
  import { watch, guardianState, noteRelayed, scan } from "./guardian.mjs";
12
13
  import { privateKeyToAccount } from "viem/accounts";
14
+ import { verifyGenesis, sealSync } from "./pq.mjs";
13
15
 
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 });
16
+ import { keysOf, remember, register, verifyBundle } from "./vaultkeys.mjs";
17
17
  const PUBLIC = new URL("../public/", import.meta.url).pathname;
18
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
19
  const isAddr = (s) => /^0x[0-9a-fA-F]{40}$/.test(s || "");
20
+ const ip = (req) => String(req.headers["x-real-ip"] || req.socket.remoteAddress || "?");
21
+ const holderHits = new Map();
22
+ const holderLimit = (who) => { const now = Date.now(), a = (holderHits.get(who) || []).filter((t) => now - t < 600_000); if (a.length >= 8) throw new Error("too many tries; wait ten minutes"); a.push(now); holderHits.set(who, a); };
20
23
  const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
21
24
 
22
25
  function bundleFrom(body) {
@@ -31,7 +34,28 @@ function bundleFrom(body) {
31
34
  throw new Error("send { bundle } or { frames: [...] }");
32
35
  }
33
36
 
37
+ // studio: owner only, by the key in <data>/studio/secrets.json (or STUDIO_KEY); 10 wrong keys lock an address out for 10 minutes
38
+ const keyDigest = (x) => createHash("sha256").update(String(x)).digest(), studioMisses = new Map();
39
+ async function studioGate(req) {
40
+ const S = await import("./studio.mjs"), who = ip(req), now = Date.now(), m = (studioMisses.get(who) || []).filter((t) => now - t < 600_000);
41
+ if (m.length >= 10) throw Object.assign(new Error("Too many wrong keys. Wait 10 minutes."), { status: 429 });
42
+ if (!timingSafeEqual(keyDigest(req.headers["x-studio-key"] || ""), keyDigest(S.STUDIO_KEY))) {
43
+ studioMisses.set(who, [...m, now]); if (studioMisses.size > 5000) studioMisses.clear();
44
+ throw Object.assign(new Error("Wrong studio key."), { status: 401 });
45
+ }
46
+ return S;
47
+ }
48
+
34
49
  const routes = [
50
+ // public: the token the site shows in its top bar (CA, ticker, buy link, burns)
51
+ ["GET", /^\/api\/token$/, async () => (await import("./studio.mjs")).publicView()],
52
+ ["GET", /^\/api\/studio\/status$/, async (_, __, req) => (await studioGate(req)).status()],
53
+ ["POST", /^\/api\/studio\/token$/, async (_, b, req) => (await studioGate(req)).saveToken(b)],
54
+ ["POST", /^\/api\/studio\/wallet$/, async (_, b, req) => (await studioGate(req)).saveKey(b.privateKey || "")],
55
+ ["DELETE", /^\/api\/studio\/wallet$/, async (_, __, req) => (await studioGate(req)).removeKey()],
56
+ ["POST", /^\/api\/studio\/buyback$/, async (_, b, req) => (await studioGate(req)).buyback(b.usd)],
57
+ ["POST", /^\/api\/studio\/supply$/, async (_, b, req) => (await studioGate(req)).burnSupply(b.usd)],
58
+ ["POST", /^\/api\/studio\/burn-held$/, async (_, __, req) => (await studioGate(req)).burnHeld()],
35
59
  ["GET", /^\/api\/config$/, async () => ({
36
60
  chainId: CONFIG.chainId, rpc: CONFIG.rpc, usdg: CONFIG.usdg,
37
61
  relayer: CONFIG.relayerKey ? privateKeyToAccount(CONFIG.relayerKey).address : null,
@@ -42,23 +66,32 @@ const routes = [
42
66
  // what the offline vault scans to catch up: its counters as animated-QR frames
43
67
  ["GET", /^\/api\/vault\/(0x[0-9a-fA-F]{40})\/sync$/, async (m) => {
44
68
  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 })) };
69
+ const view = { vault: s.vault, nonce: s.nonce, chain_used: s.chain_used, next_leaf: s.next_leaf, mode: s.mode, epoch: s.epoch };
70
+ // encrypted to the vault's ML-KEM-768 key when this companion knows it (always, for vaults it deployed)
71
+ const kem = keysOf(m[1])?.kem;
72
+ const payload = kem ? sealSync(view, kem) : { type: "sync", ...view };
73
+ return { view, encrypted: !!kem, frames: frames(JSON.stringify(payload)) };
47
74
  }],
48
75
  ["POST", /^\/api\/deploy$/, async (_, b) => {
49
76
  const g = b.genesis || (b.frames && bundleFrom({ frames: b.frames }));
50
77
  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(); }
78
+ // the guardian and the cold address come from the signed genesis, never from this request
79
+ const fixed = verifyGenesis(g, CONFIG.chainId);
80
+ const r = await deployVault(g, fixed);
81
+ remember(r.vault, g);
53
82
  log(`deployed vault ${r.vault}`);
54
- return r;
83
+ return { ...r, ...fixed };
84
+ }],
85
+ // a companion that did not deploy the vault learns its keys by scanning the deploy QR once
86
+ ["POST", /^\/api\/identity\/(0x[0-9a-fA-F]{40})$/, async (m, b) => {
87
+ const g = b.genesis || (b.frames && bundleFrom({ frames: b.frames }));
88
+ await register(m[1], g);
89
+ return { ok: true, vault: m[1] };
55
90
  }],
56
91
  ["POST", /^\/api\/submit$/, async (_, b) => {
57
92
  const bundle = bundleFrom(b);
58
93
  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);
94
+ const identity = await verifyBundle(bundle);
62
95
  noteRelayed(bundle.vault, bundle.action_hash);
63
96
  const r = await submit(bundle, log);
64
97
  log(`relayed nonce ${bundle.nonce} (${bundle.description}): ${r.ok ? "done" : "proof spent, action failed"}`);
@@ -75,7 +108,23 @@ const routes = [
75
108
  return { status: r.status, body: (await r.text()).slice(0, 2000) };
76
109
  }],
77
110
  ["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)],
111
+ ["POST", /^\/api\/guardian\/(0x[0-9a-fA-F]{40})$/, async (m, b) => { await (await import("./hosted.mjs")).requirePro(m[1]); return watch(m[1], b); }],
112
+ // holder access to the private GitHub repo: sign with a holding wallet, get invited
113
+ ["GET", /^\/api\/holders\/status$/, async () => (await import("./holders.mjs")).status()],
114
+ ["POST", /^\/api\/holders\/claim$/, async (_, b, req) => { holderLimit(ip(req)); return (await import("./holders.mjs")).claim(b); }],
115
+ // support chat: visitors talk to the assistant, then to the team; the team answers from /support/admin/
116
+ ["POST", /^\/api\/support\/start$/, async (_, b, req) => (await import("./support.mjs")).start(ip(req))],
117
+ ["POST", /^\/api\/support\/send$/, async (_, b, req) => (await import("./support.mjs")).send(ip(req), b)],
118
+ ["POST", /^\/api\/support\/human$/, async (_, b, req) => (await import("./support.mjs")).human(ip(req), b)],
119
+ ["POST", /^\/api\/support\/poll$/, async (_, b) => (await import("./support.mjs")).poll(b)],
120
+ ["GET", /^\/api\/support\/admin\/list$/, async (_, __, req) => { const s = await import("./support.mjs"); s.checkAdmin(req.headers.authorization); return s.adminList(); }],
121
+ ["GET", /^\/api\/support\/admin\/c\/([0-9a-f]{12})$/, async (m, __, req) => { const s = await import("./support.mjs"); s.checkAdmin(req.headers.authorization); return s.adminGet(m[1]); }],
122
+ ["POST", /^\/api\/support\/admin\/c\/([0-9a-f]{12})\/reply$/, async (m, b, req) => { const s = await import("./support.mjs"); s.checkAdmin(req.headers.authorization); return s.adminReply(m[1], b.text); }],
123
+ ["POST", /^\/api\/support\/admin\/c\/([0-9a-f]{12})\/close$/, async (m, b, req) => { const s = await import("./support.mjs"); s.checkAdmin(req.headers.authorization); return s.adminClose(m[1]); }],
124
+ // hosted Guardian (paid plan): status is public, rules need a signature from the wallet that paid
125
+ ["GET", /^\/api\/hosted\/(0x[0-9a-fA-F]{40})$/, async (m) => (await import("./hosted.mjs")).status(m[1])],
126
+ ["POST", /^\/api\/hosted\/rules$/, async (_, b) => (await import("./hosted.mjs")).setRules(b)],
127
+ ["GET", /^\/api\/hosted$/, async () => { const h = await import("./hosted.mjs"); return { guardian: h.hostedGuardian(), plans: h.PLANS }; }],
79
128
  // a paid API for trying x402 agents: costs 0.25 USDG per call, paid to DEMO_PAYEE (or the relayer)
80
129
  ["GET", /^\/demo\/premium$/, async (_, __, req) => {
81
130
  const payTo = process.env.VANTYX_DEMO_PAYEE || (CONFIG.relayerKey && privateKeyToAccount(CONFIG.relayerKey).address);
@@ -95,7 +144,15 @@ const server = createServer(async (req, res) => {
95
144
  const url = new URL(req.url, "http://x");
96
145
  // the API only answers this machine's own pages
97
146
  const origin = req.headers.origin;
98
- if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) { res.writeHead(403).end(); return; }
147
+ const allowed = process.env.VANTYX_ALLOWED_ORIGIN;
148
+ if (origin && origin !== allowed && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) { res.writeHead(403).end(); return; }
149
+ // hosted mode serves only the hosted Guardian API: no relaying, agents or deployments for strangers
150
+ if (process.env.VANTYX_HOSTED && !url.pathname.startsWith("/api/hosted") && !url.pathname.startsWith("/api/support") && !url.pathname.startsWith("/api/holders") && !url.pathname.startsWith("/api/studio/") && url.pathname !== "/api/token" && url.pathname !== "/studio") { res.writeHead(404).end("not found"); return; }
151
+ // the owner's studio page: never indexed, never framed
152
+ if (url.pathname === "/studio" && req.method === "GET") {
153
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", "x-robots-tag": "noindex", "x-frame-options": "DENY", "referrer-policy": "no-referrer" }).end(readFileSync(join(PUBLIC, "studio.html")));
154
+ return;
155
+ }
99
156
  for (const [method, re, fn] of routes) {
100
157
  const m = url.pathname.match(re);
101
158
  if (!m || req.method !== method) continue;
@@ -103,6 +160,8 @@ const server = createServer(async (req, res) => {
103
160
  if (method !== "GET") {
104
161
  const chunks = [];
105
162
  for await (const c of req) chunks.push(c);
163
+ // a strict-mode bundle (one-time signature + Merkle path + ML-DSA) is 18-31 KB; 256 KB leaves room and still caps abuse
164
+ if (chunks.reduce((n, c) => n + c.length, 0) > 262144) { res.writeHead(413, { "content-type": "application/json" }).end(JSON.stringify({ error: "request too large" })); return; }
106
165
  try { body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : {}; } catch { body = {}; }
107
166
  }
108
167
  try {
@@ -111,7 +170,7 @@ const server = createServer(async (req, res) => {
111
170
  if (out?.$status) delete out.$status;
112
171
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(out ?? null, (_, v) => (typeof v === "bigint" ? v.toString() : v)));
113
172
  } catch (e) {
114
- res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: e.shortMessage || e.message }));
173
+ res.writeHead(e.status || 400, { "content-type": "application/json" }).end(JSON.stringify({ error: e.shortMessage || e.message }));
115
174
  }
116
175
  return;
117
176
  }
@@ -128,3 +187,5 @@ server.listen(CONFIG.port, CONFIG.host, () => log(`Vantyx Companion on http://${
128
187
  const loop = (fn, name) => setInterval(() => fn(log).catch((e) => log(`${name}: ${e.shortMessage || e.message}`)), CONFIG.pollMs);
129
188
  loop(tick, "agents");
130
189
  if (CONFIG.guardianKey) loop(scan, "guardian");
190
+ // the hosted server starts the holder re-check loop at boot (it only runs once the token and GitHub token are set)
191
+ if (process.env.VANTYX_HOSTED) import("./holders.mjs").catch((e) => log("holders:", e.message));
package/src/studio.mjs ADDED
@@ -0,0 +1,303 @@
1
+ // Vantyx studio: the token settings (the CA shown in the site's top bar, also used by the holders gate and Guardian Pro) and the
2
+ // manual buyback-and-burn, run by the owner from /studio. Nothing here runs on its own.
3
+ // One wallet key lives here, the buyback wallet's, encrypted at rest (AES-256-GCM under a scrypt key from BURN_SECRET).
4
+ // A buyback spends the dollars the owner names (paid in ETH at the live price) on the token (on the Pons curve before graduation, on Uniswap v4 after) and sends
5
+ // exactly what it bought to the dead address. A supply burn sends tokens the wallet already holds, sized in dollars. Every step is written to history.json before the next wait, so a restart
6
+ // mid-burn leaves the hashes on record instead of losing them.
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import crypto from "node:crypto";
10
+ import { ethers } from "ethers";
11
+
12
+ import { CONFIG } from "./config.mjs";
13
+ const DIR = path.join(CONFIG.dataDir, "studio");
14
+ fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
15
+ const read = (f, d) => { try { return JSON.parse(fs.readFileSync(path.join(DIR, f), "utf8")); } catch { return d; } };
16
+ const write = (f, v) => { const p = path.join(DIR, f), tmp = `${p}.${process.pid}.tmp`; if (v === null) return fs.rmSync(p, { force: true }); fs.writeFileSync(tmp, JSON.stringify(v, null, 1), { mode: 0o600 }); fs.renameSync(tmp, p); };
17
+
18
+ // ---------- secrets: from .env when set, otherwise generated once on this machine and kept in <data>/studio/secrets.json (0600) ----------
19
+ const SECRETS = (() => {
20
+ const s = read("secrets.json", {});
21
+ if (!s.studioKey || !s.burnSecret) { s.studioKey ||= crypto.randomBytes(24).toString("hex"); s.burnSecret ||= crypto.randomBytes(32).toString("hex"); write("secrets.json", s); }
22
+ return { studioKey: (process.env.STUDIO_KEY || s.studioKey).trim(), burnSecret: (process.env.BURN_SECRET || s.burnSecret).trim() };
23
+ })();
24
+ export const STUDIO_KEY = SECRETS.studioKey;
25
+ const SECRET = SECRETS.burnSecret;
26
+
27
+ const RPC = (process.env.VANTYX_TOKEN_RPC || process.env.RPC_URL || "https://rpc.mainnet.chain.robinhood.com").split(",")[0].trim();
28
+ const provider = new ethers.JsonRpcProvider(RPC, 4663, { staticNetwork: true, cacheTimeout: -1 });
29
+ export const EXPLORER = "https://explorer.mainnet.chain.robinhood.com";
30
+ // Pons v2 and Uniswap v4 on Robinhood Chain (the same addresses the EOLA engine burns with)
31
+ const FACTORY = "0x7eD598BcEf8bd9Edd8C97A195C6d13f40801EC7e", HOOK = "0xE5e702641Ea86F4ae6cC3cDaeD2B886f976Be044";
32
+ const ROUTER = "0x8876789976dEcBfCbBbe364623C63652db8C0904", POOL_MANAGER = "0x8366a39CC670B4001A1121B8F6A443A643e40951";
33
+ export const DEAD = "0x000000000000000000000000000000000000dEaD";
34
+ const POOL_CREATED = 2, BPS = 10_000n, SLIPPAGE_BPS = 500n, GAS_ROOM = ethers.parseEther("0.0008");
35
+ const MAX_USD = Number(process.env.BURN_MAX_USD || 100), DAY_USD = Number(process.env.BURN_DAY_USD || 300);
36
+ const FACTORY_ABI = [
37
+ "function getLaunchedToken(address token) view returns (tuple(address token, address curve, address deployer, address creatorFeeRecipient, address pairToken, uint256 graduationThreshold, uint24 poolFee, int24 tickSpacing, uint16 creatorTaxBps, bool buybackEnabled, uint8 phase, uint256 sweptQuote, uint256 sweptTokens, uint256 sweptAt, bool exists))",
38
+ "function getLaunchFeePolicy(address token) view returns (tuple(address protocolFeeRecipient, uint16 protocolFeeShareBps, uint16 buybackBurnBps, uint16 hookFeeBps, uint16 maxInternalPriceImpactBps))",
39
+ ];
40
+ const CURVE_ABI = [
41
+ "function buy(uint256 quoteIn, uint256 minTokensOut, address recipient) payable returns (uint256)",
42
+ "function getReserves() view returns (uint256 quoteReserve, uint256 tokenReserve)", "function sellableTokens() view returns (uint256)",
43
+ "function feeBps() view returns (uint256)", "function creatorTaxBps() view returns (uint256)", "function currentSnipeTaxBps(address recipient) view returns (uint256)",
44
+ ];
45
+ const ERC20 = ["function balanceOf(address) view returns (uint256)", "function transfer(address to, uint256 amount) returns (bool)", "function symbol() view returns (string)"];
46
+
47
+ /** Retries a chain read: the shared public RPC answers bursts with 429. */
48
+ async function again(fn, tries = 6) {
49
+ for (let i = 1; ; i++) { try { return await fn(); } catch (e) { if (["CALL_EXCEPTION", "INSUFFICIENT_FUNDS"].includes(e.code)) throw e; if (i >= tries) throw new Error(`The Robinhood Chain RPC is busy (${e.shortMessage || e.message}). Try again in a minute.`); await new Promise((r) => setTimeout(r, 3000 * i)); } }
50
+ }
51
+ /** Sends without losing the transaction to a 429: gas, fees and nonce are filled with retries, the transaction is signed once,
52
+ * and the same signed bytes are rebroadcast (same hash), so a retry can never send it twice. */
53
+ async function send(w, req) {
54
+ const pop = await again(async () => w.populateTransaction({ ...req, nonce: await provider.getTransactionCount(w.address, "pending") }));
55
+ const signed = await w.signTransaction(pop), hash = ethers.keccak256(signed);
56
+ for (let i = 1; ; i++) {
57
+ try { await provider.broadcastTransaction(signed); return hash; } catch (e) {
58
+ if (/already known/i.test(e.message) || await provider.getTransaction(hash).catch(() => null)) return hash; // the first try landed, only its answer was lost
59
+ if (e.code === "INSUFFICIENT_FUNDS" || /nonce too low/i.test(e.message)) throw e;
60
+ if (i >= 6) throw new Error(`The Robinhood Chain RPC is busy (${e.shortMessage || e.message}). Nothing was sent. Try again in a minute.`);
61
+ await new Promise((ok) => setTimeout(ok, 3000 * i));
62
+ }
63
+ }
64
+ }
65
+ /** Waits for a receipt by polling, so one 429 never loses track of a sent transaction. */
66
+ async function receipt(hash) {
67
+ for (let i = 0; i < 90; i++) { const r = await provider.getTransactionReceipt(hash).catch(() => null); if (r) return r; await new Promise((ok) => setTimeout(ok, 2000)); }
68
+ return null;
69
+ }
70
+
71
+ let logs = read("log.json", []);
72
+ function log(level, text) { logs = [{ t: new Date().toISOString(), level, text }, ...logs].slice(0, 120); write("log.json", logs); console.log(`[burn] ${level} ${text}`); }
73
+ const history = () => read("history.json", []);
74
+ // every entry carries the CA it burned, so a new token never shows an earlier token's burns
75
+ function record(id, patch) { const h = history(), i = h.findIndex((x) => x.id === id); if (i < 0) h.unshift({ id, t: new Date().toISOString(), ca: tokenConfig().ca, ...patch }); else Object.assign(h[i], patch); write("history.json", h.slice(0, 500)); }
76
+ const sameCa = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase();
77
+ const doneFor = (ca) => history().filter((h) => h.status === "done" && +h.burned > 0 && sameCa(h.ca, ca));
78
+ const totals = () => read("totals.json", { boughtEth: "0", burned: "0", runs: 0 });
79
+ /** kind: "buyback" (bought with ETH), "supply" (tokens the wallet already held) or "held" (the recovery button) */
80
+ function addTotals(spentWei, burnedWei, kind = "buyback", usd = 0) {
81
+ const t = totals(); t.boughtEth = (BigInt(t.boughtEth || "0") + spentWei).toString(); t.burned = (BigInt(t.burned || "0") + burnedWei).toString(); t.runs = (t.runs || 0) + 1;
82
+ if (kind === "buyback") { t.boughtBurned = (BigInt(t.boughtBurned || "0") + burnedWei).toString(); t.buybacks = (t.buybacks || 0) + 1; t.boughtUsd = +((t.boughtUsd || 0) + usd).toFixed(2); }
83
+ else { t.supplyBurned = (BigInt(t.supplyBurned || "0") + burnedWei).toString(); t.supplyBurns = (t.supplyBurns || 0) + 1; }
84
+ write("totals.json", t);
85
+ }
86
+
87
+ // ---------- prices: ETH in dollars from Coinbase (CoinGecko as backup), the token from its curve or pool ----------
88
+ let ethUsdCache = { at: 0, v: 0 };
89
+ async function ethUsd() {
90
+ if (Date.now() - ethUsdCache.at < 60_000 && ethUsdCache.v) return ethUsdCache.v;
91
+ for (const [url, pick] of [["https://api.coinbase.com/v2/prices/ETH-USD/spot", (j) => +j.data.amount], ["https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd", (j) => +j.ethereum.usd]]) {
92
+ try { const v = pick(await (await fetch(url, { signal: AbortSignal.timeout(6000) })).json()); if (v > 0) { ethUsdCache = { at: Date.now(), v }; return v; } } catch {}
93
+ }
94
+ if (ethUsdCache.v) return ethUsdCache.v;
95
+ throw new Error("Could not read the ETH price. Try again in a minute.");
96
+ }
97
+ /** ETH per whole token: the curve's reserves before graduation, the v4 pool's price after. */
98
+ async function tokenPriceEth(token, l) {
99
+ if (l.phase === POOL_CREATED) {
100
+ const m = new ethers.Contract(POOL_MANAGER, ["function extsload(bytes32 slot) view returns (bytes32)"], provider);
101
+ const state = BigInt(ethers.keccak256(coder.encode(["bytes32", "uint256"], [poolId(token, l.pool), 6n])));
102
+ const P = BigInt(await m.extsload(ethers.toBeHex(state, 32))) & ((1n << 160n) - 1n); if (!P) throw new Error("The pool has no price yet.");
103
+ const tokPerEth = (Number(P) / 2 ** 96) ** 2; return 1 / tokPerEth;
104
+ }
105
+ const [qr, tr] = await new ethers.Contract(l.curve, CURVE_ABI, provider).getReserves();
106
+ return Number(ethers.formatEther(qr)) / Number(ethers.formatUnits(tr, 18));
107
+ }
108
+ const usdIn = (v) => { const n = Number(String(v ?? "").trim().replace(/^\$/, "").replace(",", ".")); if (!(n > 0)) throw new Error("Enter an amount in dollars, for example 10."); return n; };
109
+ const usdToday = () => history().filter((h) => h.kind === "buyback" && h.status !== "failed" && Date.now() - Date.parse(h.t) < 864e5).reduce((a, h) => a + (+h.usd || 0), 0);
110
+
111
+ // ---------- token settings ----------
112
+ const DEFAULTS = { ca: "", symbol: "VANTYX" };
113
+ export const tokenConfig = () => ({ ...DEFAULTS, ...read("token.json", {}) });
114
+ export async function saveToken({ ca, symbol }) {
115
+ const out = { ...tokenConfig() };
116
+ if (ca !== undefined) {
117
+ const c = String(ca).trim();
118
+ if (c === "") out.ca = "";
119
+ else { if (!ethers.isAddress(c)) throw new Error("That is not a contract address."); out.ca = ethers.getAddress(c); }
120
+ }
121
+ if (symbol !== undefined) { const s = String(symbol).trim().replace(/^\$/, "").toUpperCase(); if (!/^[A-Z0-9]{1,12}$/.test(s)) throw new Error("Ticker: 1 to 12 letters or digits."); out.symbol = s; }
122
+ let warn = null;
123
+ if (out.ca) { const l = await again(() => launchOf(out.ca)).catch(() => null); if (!l) warn = "Saved, but the Pons factory has no launch for this address. Check the CA."; }
124
+ write("token.json", out); log("info", `Token set: ${out.ca || "(none)"} $${out.symbol}`); cache = null;
125
+ return { config: out, warn };
126
+ }
127
+
128
+ // ---------- the key ----------
129
+ const kdf = (salt) => crypto.scryptSync(SECRET, salt, 32);
130
+ export function saveKey(pk) {
131
+ let w; try { w = new ethers.Wallet(String(pk).trim()); } catch { throw new Error("That is not a valid private key."); }
132
+ const salt = crypto.randomBytes(16), iv = crypto.randomBytes(12), c = crypto.createCipheriv("aes-256-gcm", kdf(salt), iv);
133
+ const data = Buffer.concat([c.update(w.privateKey, "utf8"), c.final()]);
134
+ write("wallet.enc", { address: w.address, salt: salt.toString("hex"), iv: iv.toString("hex"), tag: c.getAuthTag().toString("hex"), data: data.toString("hex") });
135
+ log("info", `Buyback wallet set: ${w.address}`); return { address: w.address };
136
+ }
137
+ function wallet() {
138
+ const f = read("wallet.enc", null); if (!f) return null;
139
+ const d = crypto.createDecipheriv("aes-256-gcm", kdf(Buffer.from(f.salt, "hex")), Buffer.from(f.iv, "hex")); d.setAuthTag(Buffer.from(f.tag, "hex"));
140
+ return new ethers.Wallet(Buffer.concat([d.update(Buffer.from(f.data, "hex")), d.final()]).toString("utf8"), provider);
141
+ }
142
+ const walletAddress = () => read("wallet.enc", null)?.address || null;
143
+ export function removeKey() { if (busy) throw new Error("Wait for the buyback to finish."); write("wallet.enc", null); log("info", "Buyback wallet removed"); return { ok: true }; }
144
+
145
+ // ---------- Pons and Uniswap v4 ----------
146
+ const coder = ethers.AbiCoder.defaultAbiCoder();
147
+ const poolId = (token, k) => ethers.keccak256(coder.encode(["address", "address", "uint24", "int24", "address"], [ethers.ZeroAddress, token, k.fee, k.tickSpacing, k.hooks]));
148
+ async function launchOf(token) {
149
+ const l = await new ethers.Contract(FACTORY, FACTORY_ABI, provider).getLaunchedToken(token);
150
+ if (!l?.exists) return null;
151
+ return { curve: l.curve, pairToken: l.pairToken, phase: Number(l.phase), creatorTaxBps: BigInt(l.creatorTaxBps), pool: { fee: Number(l.poolFee), tickSpacing: Number(l.tickSpacing), hooks: HOOK } };
152
+ }
153
+ const minOut = (expected, feeBps = 0n) => (expected * (BPS - feeBps) * (BPS - SLIPPAGE_BPS)) / (BPS * BPS);
154
+ async function quoteCurve(curveAddr, quoteIn, recipient) {
155
+ const c = new ethers.Contract(curveAddr, CURVE_ABI, provider);
156
+ const [[qr, tr], sellable, fee, tax, snipe0] = await Promise.all([c.getReserves(), c.sellableTokens(), c.feeBps(), c.creatorTaxBps(), c.currentSnipeTaxBps(recipient)]);
157
+ const snipe = snipe0 > BPS - fee - tax - 100n ? BPS - fee - tax - 100n : snipe0;
158
+ const net = quoteIn - (quoteIn * fee) / BPS - (quoteIn * tax) / BPS - (snipe > 0n ? (quoteIn * snipe) / BPS : 0n);
159
+ const out = (net * tr) / (qr + net);
160
+ return out <= sellable ? out : sellable;
161
+ }
162
+ async function quoteV4(token, key, amountIn) {
163
+ const m = new ethers.Contract(POOL_MANAGER, ["function extsload(bytes32 slot) view returns (bytes32)"], provider);
164
+ const state = BigInt(ethers.keccak256(coder.encode(["bytes32", "uint256"], [poolId(token, key), 6n])));
165
+ const [slot0, liq] = await Promise.all([m.extsload(ethers.toBeHex(state, 32)), m.extsload(ethers.toBeHex(state + 3n, 32))]);
166
+ const P = BigInt(slot0) & ((1n << 160n) - 1n), L = BigInt(liq) & ((1n << 128n) - 1n), Q96 = 1n << 96n;
167
+ if (!P || !L) throw new Error("The Uniswap v4 pool has no price or liquidity yet.");
168
+ return (L * (P - (L * Q96 * P) / (L * Q96 + amountIn * P))) / Q96;
169
+ }
170
+ function v4BuyData(token, amountIn, key, min) {
171
+ const swap = coder.encode(["tuple(tuple(address,address,uint24,int24,address),bool,uint128,uint128,bytes)"], [[[ethers.ZeroAddress, token, key.fee, key.tickSpacing, key.hooks], true, amountIn, min, "0x"]]);
172
+ const input = coder.encode(["bytes", "bytes[]"], ["0x060c0f", [swap, coder.encode(["address", "uint256"], [ethers.ZeroAddress, amountIn]), coder.encode(["address", "uint256"], [token, min])]]);
173
+ return new ethers.Interface(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]).encodeFunctionData("execute", ["0x10", [input], Math.floor(Date.now() / 1000) + 300]);
174
+ }
175
+
176
+ // ---------- the two actions ----------
177
+ let busy = false, quietUntil = 0;
178
+ /** True while the studio is open or a buyback runs: the engine skips its cycles so the RPC rate limit is left for the burn. */
179
+ export const quiet = () => busy || Date.now() < quietUntil;
180
+ async function ready() {
181
+ const cfg = tokenConfig(), w = wallet();
182
+ if (!ethers.isAddress(cfg.ca)) throw new Error("Save the contract address first.");
183
+ if (!w) throw new Error("Add the buyback wallet key first.");
184
+ return { cfg, w, token: ethers.getAddress(cfg.ca) };
185
+ }
186
+ const guard = async (fn) => {
187
+ if (busy) throw new Error("Another buyback is still running.");
188
+ busy = true; quietUntil = Date.now() + 120_000;
189
+ try { return await fn(); } catch (e) { const m = e.shortMessage || e.message; log("error", m); throw new Error(m); } finally { busy = false; }
190
+ };
191
+ async function burnAmount(w, token, amount, cfg, id) {
192
+ log("info", `Burning ${ethers.formatUnits(amount, 18)} $${cfg.symbol}`);
193
+ const hash = await send(w, { to: token, data: new ethers.Interface(ERC20).encodeFunctionData("transfer", [DEAD, amount]) });
194
+ record(id, { status: "burning", burnTx: hash, burned: ethers.formatUnits(amount, 18) }); // on disk before the wait
195
+ const rc = await receipt(hash); if (!rc) throw new Error(`Burn sent (${hash}) but no receipt yet. Check the explorer before trying again.`);
196
+ if (rc.status !== 1) { record(id, { status: "failed" }); throw new Error(`Burn ${hash} failed.`); }
197
+ return hash;
198
+ }
199
+
200
+ /** Spends `usd` dollars (paid in ETH at the live price) from the buyback wallet on the token, then burns exactly what that buy returned. */
201
+ export const buyback = (usdRaw) => guard(async () => {
202
+ const { cfg, w, token } = await ready(), usd = usdIn(usdRaw);
203
+ if (usd > MAX_USD) throw new Error(`At most $${MAX_USD} per buyback (BURN_MAX_USD).`);
204
+ const today = usdToday(); if (today + usd > DAY_USD) throw new Error(`Daily limit is $${DAY_USD} (BURN_DAY_USD); $${today.toFixed(2)} already used in the last 24 hours.`);
205
+ const price = await ethUsd(), spend = ethers.parseEther((usd / price).toFixed(18));
206
+ const bal = await again(() => provider.getBalance(w.address)), most = bal > GAS_ROOM ? bal - GAS_ROOM : 0n;
207
+ if (spend > most) throw new Error(`$${usd} is ${ethers.formatEther(spend).slice(0, 10)} ETH, but the wallet can spend ${ethers.formatEther(most).slice(0, 10)} ETH (about $${(Number(ethers.formatEther(most)) * price).toFixed(2)}). Add ETH or enter less.`);
208
+ const l = await again(() => launchOf(token));
209
+ if (!l) throw new Error("The Pons factory has no launch for this CA.");
210
+ if (l.pairToken !== ethers.ZeroAddress) throw new Error("Only native ETH Pons launches are supported.");
211
+ if (l.phase !== 0 && l.phase !== POOL_CREATED) throw new Error(`The launch is moving from the curve to its pool (phase ${l.phase}). Try again in a minute.`);
212
+ const erc = new ethers.Contract(token, ERC20, w), before = await again(() => erc.balanceOf(w.address));
213
+ const id = crypto.randomBytes(5).toString("hex");
214
+ let hash;
215
+ if (l.phase === POOL_CREATED) {
216
+ const fee = BigInt((await again(() => new ethers.Contract(FACTORY, FACTORY_ABI, provider).getLaunchFeePolicy(token))).hookFeeBps) + l.creatorTaxBps;
217
+ const min = minOut(await again(() => quoteV4(token, l.pool, spend)), fee), req = { to: ROUTER, value: spend, data: v4BuyData(token, spend, l.pool, min) };
218
+ const gas = await again(() => w.estimateGas(req), 3); // a swap that would revert stops here and costs nothing
219
+ log("info", `Buying $${cfg.symbol} on Uniswap v4 with ${ethers.formatEther(spend)} ETH`);
220
+ hash = await send(w, { ...req, gasLimit: (gas * 13n) / 10n });
221
+ } else {
222
+ const min = minOut(await again(() => quoteCurve(l.curve, spend, w.address)));
223
+ log("info", `Buying $${cfg.symbol} on the Pons curve with ${ethers.formatEther(spend)} ETH`);
224
+ hash = await send(w, { to: l.curve, value: spend, data: new ethers.Interface(CURVE_ABI).encodeFunctionData("buy", [spend, min, w.address]) });
225
+ }
226
+ record(id, { kind: "buyback", status: "buying", usd, spentEth: ethers.formatEther(spend), buyTx: hash });
227
+ const rc = await receipt(hash); if (!rc) throw new Error(`Buy sent (${hash}) but no receipt yet. If it went through, use "Burn what the wallet holds".`);
228
+ if (rc.status !== 1) { record(id, { status: "failed" }); throw new Error(`Buy ${hash} failed.`); }
229
+ const bought = (await again(() => erc.balanceOf(w.address))) - before;
230
+ if (bought <= 0n) { record(id, { status: "failed" }); throw new Error(`The buy went through (${hash}) but no $${cfg.symbol} arrived. Nothing burned.`); }
231
+ const burnTx = await burnAmount(w, token, bought, cfg, id);
232
+ addTotals(spend, bought, "buyback", usd); record(id, { status: "done" }); cache = null;
233
+ log("ok", `Bought and burned ${ethers.formatUnits(bought, 18)} $${cfg.symbol} for $${usd} (${ethers.formatEther(spend)} ETH)`);
234
+ return { ok: true, usd, burned: ethers.formatUnits(bought, 18), buyTx: hash, burnTx };
235
+ });
236
+
237
+ /** Burns tokens the wallet already holds (send the supply to the buyback wallet first), sized in dollars at the live price.
238
+ * usd "max" burns everything the wallet holds. */
239
+ export const burnSupply = (usdRaw) => guard(async () => {
240
+ const { cfg, w, token } = await ready(), l = await again(() => launchOf(token));
241
+ if (!l) throw new Error("The Pons factory has no launch for this CA.");
242
+ const bal = await again(() => new ethers.Contract(token, ERC20, provider).balanceOf(w.address));
243
+ if (bal === 0n) throw new Error(`The burn wallet holds no $${cfg.symbol}. Send the supply you want to burn to ${w.address} first.`);
244
+ const px = (await again(() => tokenPriceEth(token, l))) * (await ethUsd());
245
+ let amount, usd;
246
+ if (String(usdRaw).trim().toLowerCase() === "max") { amount = bal; usd = Number(ethers.formatUnits(bal, 18)) * px; }
247
+ else {
248
+ usd = usdIn(usdRaw); amount = ethers.parseUnits((usd / px).toFixed(6), 18);
249
+ if (amount > bal) throw new Error(`$${usd} is ${Math.round(usd / px).toLocaleString("en-US")} $${cfg.symbol}, but the wallet holds ${Math.round(Number(ethers.formatUnits(bal, 18))).toLocaleString("en-US")} (about $${(Number(ethers.formatUnits(bal, 18)) * px).toFixed(2)}). Enter less or send more tokens to the burn wallet.`);
250
+ }
251
+ const id = crypto.randomBytes(5).toString("hex"); record(id, { kind: "supply", status: "burning", usd: +usd.toFixed(2), priceUsd: px });
252
+ const burnTx = await burnAmount(w, token, amount, cfg, id);
253
+ addTotals(0n, amount, "supply"); record(id, { status: "done" }); cache = null;
254
+ log("ok", `Burned ${ethers.formatUnits(amount, 18)} $${cfg.symbol} from supply (about $${usd.toFixed(2)})`);
255
+ return { ok: true, usd: +usd.toFixed(2), burned: ethers.formatUnits(amount, 18), burnTx };
256
+ });
257
+
258
+ /** Burns everything the wallet holds, for example after a buy that stopped before its burn. */
259
+ export const burnHeld = () => guard(async () => {
260
+ const { cfg, w, token } = await ready(), bal = await again(() => new ethers.Contract(token, ERC20, provider).balanceOf(w.address));
261
+ if (bal === 0n) throw new Error(`The wallet holds no $${cfg.symbol}.`);
262
+ const id = crypto.randomBytes(5).toString("hex"); record(id, { kind: "held", status: "burning", held: true });
263
+ const burnTx = await burnAmount(w, token, bal, cfg, id);
264
+ addTotals(0n, bal, "held"); record(id, { status: "done" }); cache = null;
265
+ log("ok", `Burned ${ethers.formatUnits(bal, 18)} $${cfg.symbol} the wallet held`);
266
+ return { ok: true, burned: ethers.formatUnits(bal, 18), burnTx };
267
+ });
268
+
269
+ // ---------- views ----------
270
+ // totals are read from history for the current CA only; buybacks made before the dollar panel (no kind, no usd) still count as buybacks
271
+ const publicTotals = () => {
272
+ const done = doneFor(tokenConfig().ca), buys = done.filter((h) => h.kind !== "supply"), sup = done.filter((h) => h.kind === "supply");
273
+ const sum = (xs, k) => xs.reduce((a, h) => a + Number(h[k] || 0), 0);
274
+ return { boughtEth: String(+sum(buys, "spentEth").toFixed(18)), boughtUsd: +sum(buys, "usd").toFixed(2), burned: String(sum(done, "burned")), runs: done.length,
275
+ bought: String(sum(buys, "burned")), buybacks: buys.length, supply: String(sum(sup, "burned")), supplyBurns: sup.length };
276
+ };
277
+ let cache = null, lastDead = null;
278
+ /** What the site shows: the CA once it is set, the dead-address balance and the finished burns. */
279
+ export async function publicView() {
280
+ if (cache && Date.now() - cache.at < 60_000) return cache.v;
281
+ const cfg = tokenConfig(); let v = { live: false, symbol: cfg.symbol };
282
+ if (cfg.ca) {
283
+ // a busy RPC keeps the last balance read for this CA instead of showing nothing
284
+ let dead = null; try { dead = ethers.formatUnits(await again(() => new ethers.Contract(cfg.ca, ERC20, provider).balanceOf(DEAD), 3), 18); lastDead = { ca: cfg.ca, dead }; } catch { if (lastDead?.ca === cfg.ca) dead = lastDead.dead; }
285
+ v = { live: true, ca: cfg.ca, symbol: cfg.symbol, buy: `https://ponsfamily.com/launchpad/${cfg.ca}`, explorer: EXPLORER, deadBalance: dead, totals: publicTotals(),
286
+ burns: doneFor(cfg.ca).slice(0, 10).map(({ t, kind, burned, usd, spentEth, buyTx, burnTx }) => ({ t, kind: kind || "buyback", burned, usd: usd ?? null, spentEth: spentEth || null, buyTx: buyTx || null, burnTx })) };
287
+ }
288
+ cache = { at: Date.now(), v }; return v;
289
+ }
290
+ export async function status() {
291
+ quietUntil = Math.max(quietUntil, Date.now() + 90_000);
292
+ const cfg = tokenConfig(), addr = walletAddress(), out = { config: cfg, wallet: addr, busy, maxUsd: MAX_USD, dayUsd: DAY_USD, todayUsd: +usdToday().toFixed(2), totals: publicTotals(), logs: logs.slice(0, 40), history: history().slice(0, 30), explorer: EXPLORER };
293
+ try {
294
+ out.ethUsd = await ethUsd().catch(() => null);
295
+ if (addr) { const b = await again(() => provider.getBalance(addr)); out.walletEth = ethers.formatEther(b); out.spendableEth = ethers.formatEther(b > GAS_ROOM ? b - GAS_ROOM : 0n); if (out.ethUsd) out.spendableUsd = +(Number(out.spendableEth) * out.ethUsd).toFixed(2); }
296
+ if (ethers.isAddress(cfg.ca)) {
297
+ const l = await again(() => launchOf(cfg.ca)); out.phase = l ? l.phase : null; out.onPons = !!l;
298
+ if (l && out.ethUsd) out.tokenPriceUsd = (await again(() => tokenPriceEth(cfg.ca, l))) * out.ethUsd;
299
+ if (addr) { out.tokenBal = ethers.formatUnits(await again(() => new ethers.Contract(cfg.ca, ERC20, provider).balanceOf(addr)), 18); if (out.tokenPriceUsd) out.tokenBalUsd = +(Number(out.tokenBal) * out.tokenPriceUsd).toFixed(2); }
300
+ }
301
+ } catch (e) { out.error = e.shortMessage || e.message; }
302
+ return out;
303
+ }