// Hashfort vault app. Everything secret stays in this tab: the seed is generated here, encrypted here with the user's
// passphrase, and only ever decrypted here to sign. The page reads the chain through the site's read-only RPC proxy
// and sends every transaction through the user's own wallet.
import * as ethers from "/app/vendor/ethers.min.js";
import * as HS from "/app/hashsig.mjs";
import * as PQ from "/app/vendor/pq.js";
const $ = (s) => document.querySelector(s);
const enc = new TextEncoder();
const HEIGHT = 10, TREE0 = 0, KDF_ROUNDS = 600_000;
const store = {
get() { try { return JSON.parse(localStorage.getItem("hashfort.vaults") || "{}"); } catch { return {}; } },
put(addr, rec) { const all = store.get(); all[addr.toLowerCase()] = { ...(all[addr.toLowerCase()] || {}), ...rec }; try { localStorage.setItem("hashfort.vaults", JSON.stringify(all)); } catch {} },
one(addr) { return store.get()[addr.toLowerCase()] || null; },
};
let cfg, abi, read, wallet, signer, account;
const NATIVE = { 56: { name: "BNB", symbol: "BNB", decimals: 18 }, 137: { name: "POL", symbol: "POL", decimals: 18 } };
const SYM = () => (NATIVE[cfg?.chainId] || { symbol: "ETH" }).symbol;
let draft = null; // v2: { seed, tree, kit }; v3: { mode: "v3", seed, rseed, ml, slh, A, B, pkHash, recKey, kit, rkit }
let mode = "v2"; // which vault the create panel makes: "v2" (hash one-time keys) or "v3" (ML-DSA-65 + SLH-DSA)
let ver = 2; // version of the open vault (1/2 = hash key, 3 = ML-DSA-65)
let current = null; // address of the open vault
const trees = new Map(); // root -> tree, kept in memory only for this tab
// ---------------------------------------------------------------- log
function log(msg, { hash, err } = {}) {
const ol = $("#log"); ol.querySelector(".empty")?.remove();
const li = document.createElement("li");
const t = document.createElement("time"); t.textContent = new Date().toLocaleTimeString();
const m = document.createElement("span"); m.className = "msg" + (err ? " err" : ""); m.textContent = msg;
li.append(t, m);
if (hash) { const a = document.createElement("a"); a.href = `${cfg.explorer}/tx/${hash}`; a.target = "_blank"; a.rel = "noopener"; a.textContent = hash.slice(0, 10) + "…"; li.append(a); }
ol.prepend(li);
}
const fail = (e) => log(niceError(e), { err: true });
const WHY = { OverLimit: "over the daily limit", NotOwner: "the connected wallet is not the daily key", BadSignature: "the vault-key signature did not check out",
BadIndex: "that one-time key was already used", Expired: "the signature expired", NotSelf: "only the vault key can change settings", TransferFailed: "the transfer failed", CallFailed: "the call failed",
IsFrozen: "the vault is frozen; only the vault key can unfreeze it", NotAgent: "that address is not an active agent", NotSentinel: "only the daily key, the vault key or a Sentinel can do that" };
function revertName(e) { // find revert data anywhere in a wallet/RPC error and decode it with the vault ABI
const seen = new Set(), stack = [e];
while (stack.length) {
const x = stack.pop(); if (!x || typeof x !== "object" || seen.has(x)) continue; seen.add(x);
if (x.revert?.name) return x.revert.name;
for (const v of Object.values(x)) {
if (typeof v === "string" && /^0x[0-9a-f]{8}/i.test(v)) { try { const p = new ethers.Interface(abi.vault).parseError(v); if (p) return p.name; } catch {} }
else if (v && typeof v === "object") stack.push(v);
}
}
return null;
}
function niceError(e) {
const m = e?.shortMessage || e?.info?.error?.message || e?.message || String(e);
if (e?.userFacing) return m;
if (/user rejected|denied|ACTION_REJECTED/i.test(m)) return "You cancelled it in the wallet.";
const n = revertName(e) || Object.keys(WHY).find((k) => m.includes(k));
if (n) return `The vault refused it: ${WHY[n] || n} (${n}).`;
if (/insufficient funds|exceeds balance|INSUFFICIENT_FUNDS/i.test(m)) return `Your wallet does not have enough ${SYM()} on ${cfg?.chainName || "this network"} to pay for this and its gas. Add a little ${SYM()} to ${account ? account.slice(0, 8) + "…" : "your wallet"} and try again.`;
if (/invalid address|bad address checksum|UNCONFIGURED_NAME|ENS name|could not resolve/i.test(m)) return "That address is not valid. Paste a full 0x… address (42 characters) and check every character.";
if (/invalid (BigNumberish|decimal)|NUMERIC_FAULT|too many decimals|underflow/i.test(m)) return "That amount is not a valid number. Use digits and a dot, like 0.01.";
if (/network changed|chainId|wrong chain|unsupported chain/i.test(m)) return `Your wallet is on a different network. Switch it to ${cfg?.chainName || "Robinhood Chain"} and try again.`;
if (/nonce|replacement (fee|transaction)|already known/i.test(m)) return "Your wallet still has an earlier transaction pending. Wait for it to confirm (or speed it up in the wallet), then try again.";
if (/timeout|timed out|ETIMEDOUT|failed to fetch|NetworkError/i.test(m)) return "The network did not answer in time. Check your connection and try again; nothing was signed twice.";
if (/execution reverted|CALL_EXCEPTION|missing revert data/i.test(m)) return "The contract refused this transaction (no reason given). Check the amounts and that the vault has enough funds.";
return m;
}
/** An error whose message is already meant for the user. */
const oops = (msg) => Object.assign(new Error(msg), { userFacing: true });
function inlineMsg(btn, text, kind) {
const box = btn.closest(".act, .st, .frozen, .wideact, .agent, .panel") || btn.parentElement;
let m = box.querySelector(":scope > .fmsg");
if (!m) { m = document.createElement("p"); m.className = "fmsg"; m.setAttribute("role", kind === "err" ? "alert" : "status"); box.append(m); }
m.className = "fmsg " + kind; m.textContent = text; m.hidden = !text;
if (text && kind === "err") { const r = m.getBoundingClientRect(); if (r.bottom > innerHeight || r.top < 0) m.scrollIntoView({ behavior: "smooth", block: "center" }); }
}
let toastT;
function toast(text, kind) {
let t = document.querySelector("#toast");
if (!t) { t = document.createElement("div"); t.id = "toast"; t.setAttribute("aria-live", "polite"); document.body.append(t); }
t.className = kind; t.textContent = text; t.hidden = false;
clearTimeout(toastT); toastT = setTimeout(() => (t.hidden = true), kind === "err" ? 9000 : 5000);
}
async function busy(btn, label, fn) {
const old = btn.textContent; btn.disabled = true; btn.textContent = label;
inlineMsg(btn, "", "ok");
const before = document.querySelectorAll("#log li .msg").length;
try {
const r = await fn();
const msgs = document.querySelectorAll("#log li .msg");
if (msgs.length > before) { const last = msgs[0].textContent; inlineMsg(btn, last, "ok"); toast(last, "ok"); }
return r;
} catch (e) { const m = niceError(e); fail(e); inlineMsg(btn, m, "err"); toast(m, "err"); }
finally { btn.disabled = false; if (btn.textContent === label) btn.textContent = old; }
}
// ---------------------------------------------------------------- setup
async function init() {
abi = await (await fetch("/app/abi.json")).json();
const deps = await (await fetch("/api/deployments", { cache: "no-store" })).json().catch(() => []);
const sel = $("#chainSel");
if (deps.length) sel.innerHTML = deps.map((d) => ``).join("");
const params = new URLSearchParams(location.search);
let want = Number(params.get("chain")) || (() => { try { return Number(localStorage.getItem("hashfort.chain")); } catch { return 0; } })() || 4663;
cfg = deps.find((d) => d.chainId === want) || deps[0] || null;
if (!cfg?.factory && !cfg?.v3?.factory) {
cfg = { chainId: 4663, explorer: "https://explorer.mainnet.chain.robinhood.com", chainName: "Robinhood Chain" };
note("The vault factory is not deployed yet. You can make and save a vault key now; creating the vault opens once the factory is live.");
}
sel.value = String(cfg.chainId);
if (cfg.v3?.factory) {
$("#vtype").hidden = false;
const pick = (v) => { mode = cfg.factory ? v : "v3"; document.querySelectorAll(".vt").forEach((l) => l.classList.toggle("on", l.querySelector("input").value === mode)); setModeText(); draft = null; $("#keyOut").hidden = true; $("#rehearse").hidden = true; ["#s1", "#s2", "#s3"].forEach((x) => $(x).classList.remove("done")); refreshButtons(); };
document.querySelectorAll('input[name="vtype"]').forEach((r) => (r.onchange = () => pick(r.value)));
pick("v3");
}
sel.onchange = () => { try { localStorage.setItem("hashfort.chain", sel.value); } catch {} const u = new URL(location.href); u.searchParams.set("chain", sel.value); u.searchParams.delete("vault"); location.href = u; };
read = new ethers.JsonRpcProvider(`${location.origin}/api/rpc?chain=${cfg.chainId}`, cfg.chainId, { staticNetwork: true, batchMaxCount: 1 });
const q = params.get("vault");
const mine = Object.entries(store.get()).filter(([, r]) => (r.chainId || 4663) === cfg.chainId).map(([a]) => a);
const last = q || mine[0];
if (last && ethers.isAddress(last)) { $("#vaultAddr").value = ethers.getAddress(last); openVault(last).catch(fail); }
if (window.ethereum?.selectedAddress) connect().catch(() => {});
migView().catch(() => {});
}
function note(t) { const n = $("#notice"); n.textContent = t; n.hidden = false; }
function setModeText() {
const v3 = mode === "v3";
$("#s1h").textContent = v3 ? "Make the keys" : "Make the vault key";
$("#s1p").textContent = v3 ? "Two post-quantum keys from your browser's randomness: an ML-DSA-65 primary key (FIPS 204) and an SLH-DSA-SHA2-128s recovery key (FIPS 205). Only public data goes on chain."
: "A random seed from your browser becomes a tree of 1,024 one-time hash keys. Only its root goes on chain.";
$("#genKey").textContent = v3 ? "Generate keys" : "Generate vault key";
$("#kRootL").textContent = v3 ? "Primary key hash" : "Root";
$("#kSeedL").textContent = v3 ? "Recovery key" : "Public seed";
$("#s2h").textContent = v3 ? "Save both kits" : "Save the Recovery Kit";
$("#s2p").textContent = v3 ? "Two files, each encrypted with your passphrase (PBKDF2, 600,000 rounds, AES-256-GCM): the Primary Kit you sign with, and the Recovery Kit to keep offline (a USB stick, a printout). Lose both and nobody, including you, can sign for the vault."
: "The seed, encrypted with your passphrase (PBKDF2, 600,000 rounds, AES-256-GCM). Without the kit and the passphrase nobody, including you, can use the vault key.";
$("#saveKit").textContent = v3 ? "Download both kits" : "Download Recovery Kit";
$("#kitFileL").textContent = v3 ? "Primary Kit file (hashfort-primary-kit-….json)" : "Recovery Kit file";
}
// ---------------------------------------------------------------- wallet
async function connect() {
if (!window.ethereum) throw new Error("No wallet found in this browser. Install a wallet such as MetaMask or Rabby.");
await window.ethereum.request({ method: "eth_requestAccounts" });
await ensureChain();
wallet = new ethers.BrowserProvider(window.ethereum);
signer = await wallet.getSigner();
account = await signer.getAddress();
$("#connect").textContent = account.slice(0, 6) + "…" + account.slice(-4);
$("#connect").disabled = false;
$("#net").className = "netpill ok";
refreshButtons(); planView().catch(() => {}); migView().catch(() => {});
window.ethereum.on?.("accountsChanged", () => location.reload());
window.ethereum.on?.("chainChanged", () => location.reload());
}
async function ensureChain() {
const hexId = "0x" + cfg.chainId.toString(16);
const now = await window.ethereum.request({ method: "eth_chainId" });
if (now === hexId) return;
try { await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: hexId }] }); }
catch (e) {
if (e.code !== 4902 && e?.data?.originalError?.code !== 4902) throw e;
await window.ethereum.request({ method: "wallet_addEthereumChain", params: [{
chainId: hexId, chainName: cfg.chainName || "Robinhood Chain", nativeCurrency: NATIVE[cfg.chainId] || { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: cfg.rpcUrls || ["https://rpc.mainnet.chain.robinhood.com"], blockExplorerUrls: [cfg.explorer] }] });
}
}
function needWallet() { if (!signer) throw oops("Connect your wallet first (button at the top right)."); }
/** Before a large transaction: will the connected wallet be able to pay the gas? */
async function canPay(gas, what) {
const fee = await read.getFeeData(), price = fee.maxFeePerGas ?? fee.gasPrice ?? 0n, need = BigInt(gas) * price, have = await read.getBalance(account);
if (have < need) throw oops(`${what} needs about ${(+ethers.formatEther(need)).toFixed(6)} ${SYM()} of gas; your wallet ${account.slice(0, 8)}… has ${(+ethers.formatEther(have)).toFixed(6)} ${SYM()} on ${cfg.chainName}. Add a little ${SYM()} and try again.`);
}
// ---------------------------------------------------------------- key making
function buildTree(seed, treeNo, height) {
return new Promise((ok, no) => {
const w = new Worker("/app/keyworker.js", { type: "module" });
w.onmessage = (e) => { w.terminate(); ok(e.data); };
w.onerror = (e) => { w.terminate(); no(new Error(e.message || "key worker failed")); };
w.postMessage({ seed, treeNo, height });
});
}
async function kdf(pass, salt) {
const base = await crypto.subtle.importKey("raw", enc.encode(pass), "PBKDF2", false, ["deriveKey"]);
return crypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: KDF_ROUNDS, hash: "SHA-256" }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
}
async function sealBytes(secret, pass, aad, extra) { // v3 kits: the same encryption, bound to a public identifier
const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(aad) }, await kdf(pass, salt), secret);
return { format: "hashfort-recovery-kit", version: 3, chainId: cfg.chainId, ...extra,
kdf: { name: "PBKDF2-SHA256", iterations: KDF_ROUNDS, salt: HS.hex(salt) }, cipher: { name: "AES-256-GCM", iv: HS.hex(iv), aad: extra.kind === "recovery-slhdsa128s" ? "recoveryKey" : "pkHash" },
ciphertext: HS.hex(new Uint8Array(ct)), created: new Date().toISOString() };
}
const kitAad = (kit) => kit.root || (kit.kind === "recovery-slhdsa128s" ? kit.recoveryKey : kit.pkHash);
function download(obj, name) {
const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" })); a.download = name; a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
}
function mlFromSeed(seed) { const k = PQ.ml_dsa65.keygen(seed); return { ...k, pkHash: ethers.keccak256(k.publicKey) }; }
async function sealKit(seed, pass, tree) {
const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));
const root = HS.hex(tree.root);
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(root) }, await kdf(pass, salt), seed);
return { format: "hashfort-recovery-kit", version: 1, chainId: cfg.chainId, root, pubSeed: HS.hex(tree.pubSeed), treeNo: tree.treeNo, height: tree.height,
kdf: { name: "PBKDF2-SHA256", iterations: KDF_ROUNDS, salt: HS.hex(salt) }, cipher: { name: "AES-256-GCM", iv: HS.hex(iv), aad: "root" },
ciphertext: HS.hex(new Uint8Array(ct)), created: new Date().toISOString() };
}
async function openKit(kit, pass) {
if (kit?.format !== "hashfort-recovery-kit") throw new Error("This is not a Hashfort Recovery Kit.");
try {
const key = await kdf(pass, HS.unhex(kit.kdf.salt));
return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: HS.unhex(kit.cipher.iv), additionalData: enc.encode(kitAad(kit)) }, key, HS.unhex(kit.ciphertext)));
} catch { throw new Error("Wrong passphrase, or the kit file was changed."); }
}
$("#genKey").onclick = (e) => mode === "v3" ? busy(e.target, "Making keys…", genV3) : busy(e.target, "Building 1,024 keys…", async () => {
const seed = crypto.getRandomValues(new Uint8Array(32));
const { tree, ms } = await buildTree(seed, TREE0, HEIGHT);
draft = { seed, tree, kit: null, rehearsed: false };
$("#kRoot").textContent = HS.hex(tree.root); $("#kSeed").textContent = HS.hex(tree.pubSeed); $("#kMs").textContent = (ms / 1000).toFixed(1) + " s, in this tab";
$("#keyOut").hidden = false; $("#s1").classList.add("done");
log("Vault key made in this browser. Root " + HS.hex(tree.root).slice(0, 12) + "…");
refreshButtons();
});
async function genV3() {
const t0 = performance.now();
const seed = crypto.getRandomValues(new Uint8Array(32)), rseed = crypto.getRandomValues(new Uint8Array(48));
const ml = mlFromSeed(seed), slh = PQ.slh_dsa_sha2_128s.keygen(rseed);
const { A, B } = PQ.precompute(ml.publicKey);
draft = { mode: "v3", seed, rseed, ml, A, B, pkHash: ml.pkHash, recKey: HS.hex(slh.publicKey), kit: null, rkit: null, rehearsed: false };
$("#kRoot").textContent = draft.pkHash; $("#kSeed").textContent = draft.recKey; $("#kMs").textContent = ((performance.now() - t0) / 1000).toFixed(2) + " s, in this tab";
$("#keyOut").hidden = false; $("#s1").classList.add("done");
log("ML-DSA-65 primary key and SLH-DSA-SHA2-128s recovery key made in this browser.");
refreshButtons();
}
for (const id of ["#pass1", "#pass2"]) $(id).oninput = refreshButtons;
$("#saveKit").onclick = (e) => draft?.mode === "v3" ? busy(e.target, "Encrypting…", async () => {
const pass = $("#pass1").value;
draft.kit = await sealBytes(draft.seed, pass, draft.pkHash, { kind: "primary-mldsa65", pkHash: draft.pkHash });
draft.rkit = await sealBytes(draft.rseed, pass, draft.recKey, { kind: "recovery-slhdsa128s", recoveryKey: draft.recKey });
download(draft.kit, `hashfort-primary-kit-${draft.pkHash.slice(2, 10)}.json`);
setTimeout(() => download(draft.rkit, `hashfort-RECOVERY-kit-${draft.recKey.slice(2, 10)}.json`), 600);
$("#rehearse").hidden = false;
log("Primary Kit and Recovery Kit saved. Keep the Recovery Kit offline. Open the Primary Kit below to prove it works.");
}) : busy(e.target, "Encrypting…", async () => {
draft.kit = await sealKit(draft.seed, $("#pass1").value, draft.tree);
const blob = new Blob([JSON.stringify(draft.kit, null, 2)], { type: "application/json" });
const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `hashfort-recovery-kit-${draft.kit.root.slice(2, 10)}.json`; a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
$("#rehearse").hidden = false;
log("Recovery Kit saved. Open it once below to prove it works.");
});
$("#checkKit").onclick = (e) => busy(e.target, "Checking…", async () => {
const f = $("#kitFile").files[0]; if (!f) throw new Error("Choose the Recovery Kit file you saved.");
const kit = JSON.parse(await f.text());
if (draft?.mode === "v3") {
if (kit.kind !== "primary-mldsa65") throw new Error("Choose the Primary Kit (hashfort-primary-kit-….json) for this rehearsal.");
const seed = await openKit(kit, $("#pass3").value);
if (kit.pkHash !== draft.pkHash || mlFromSeed(seed).pkHash !== draft.pkHash) throw new Error("That kit belongs to a different key.");
draft.rehearsed = true; $("#kitOk").hidden = false; $("#s2").classList.add("done");
log("Rehearsal passed: the Primary Kit and passphrase open this key.");
refreshButtons(); predict().catch(fail); return;
}
const seed = await openKit(kit, $("#pass3").value);
if (kit.root !== HS.hex(draft.tree.root) || HS.hex(seed) !== HS.hex(draft.seed)) throw new Error("That kit belongs to a different key.");
draft.rehearsed = true; $("#kitOk").hidden = false; $("#s2").classList.add("done");
log("Rehearsal passed: the kit and passphrase open this vault key.");
refreshButtons(); predict().catch(fail);
});
$("#limit").oninput = () => predict().catch(() => {});
$("#pqOnly").onchange = () => {
const on = $("#pqOnly").checked;
$("#limitBox").hidden = on;
$("#limit").value = on ? "0" : ($("#limit").value === "0" ? "0.01" : $("#limit").value);
predict().catch(() => {});
};
const limitWei = () => ($("#pqOnly")?.checked ? 0n : ethers.parseEther(($("#limit").value || "0").trim()));
const createArgs = () => [account, HS.hex(draft.tree.root), HS.hex(draft.tree.pubSeed), HEIGHT, limitWei(), ethers.ZeroHash];
const v3Args = () => [account, draft.pkHash, draft.recKey, limitWei(), ethers.ZeroHash];
async function predict() {
if (!draft?.rehearsed || !account) return;
if (draft.mode === "v3") { $("#pred").textContent = await new ethers.Contract(cfg.v3.factory, abi.factory3, read).predict(...v3Args()); $("#predOut").hidden = false; return; }
if (!cfg.factory) return;
const f = new ethers.Contract(cfg.factory, abi.factory, read);
$("#pred").textContent = await f.predict(...createArgs()); $("#predOut").hidden = false;
}
$("#deploy").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needWallet();
if (draft.mode === "v3") {
const addr = await new ethers.Contract(cfg.v3.factory, abi.factory3, read).predict(...v3Args());
await canPay(6_600_000, "Creating a post-quantum vault");
store.put(addr, { kit: draft.kit, chainId: cfg.chainId, v3: true }); // saved before sending; the Recovery Kit is never stored here
const tx = await new ethers.Contract(cfg.v3.factory, abi.factory3, signer).createWithKey(account, draft.A, draft.B, draft.pkHash, draft.recKey, limitWei(), ethers.ZeroHash);
log("Creating the post-quantum vault (key data and vault in one transaction)…", { hash: tx.hash });
await tx.wait();
$("#s3").classList.add("done");
log("Vault created at " + addr, { hash: tx.hash });
$("#vaultAddr").value = addr; await openVault(addr);
$("#use").scrollIntoView({ behavior: "smooth" });
return;
}
const f = new ethers.Contract(cfg.factory, abi.factory, signer);
const addr = await new ethers.Contract(cfg.factory, abi.factory, read).predict(...createArgs());
store.put(addr, { kit: draft.kit, nextLeaf: 0, chainId: cfg.chainId }); // kit.chainId was set when the kit was sealed // saved before sending, so a closed tab loses nothing
trees.set(draft.kit.root, draft.tree);
const tx = await f.create(...createArgs());
log("Creating the vault…", { hash: tx.hash });
await tx.wait();
$("#s3").classList.add("done");
log("Vault created at " + addr, { hash: tx.hash });
$("#vaultAddr").value = addr; await openVault(addr);
$("#use").scrollIntoView({ behavior: "smooth" });
});
// ---------------------------------------------------------------- using a vault
// Assets per chain: the native coin plus wrapped BTC (addresses read from each token contract before listing).
const BTC = {
1: [["WBTC", "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", 8], ["cbBTC", "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf", 8]],
8453: [["cbBTC", "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf", 8]],
42161: [["WBTC", "0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f", 8]],
10: [["WBTC", "0x68f180fcCe6836688e9084f035309E29Bf0A2095", 8]],
137: [["WBTC", "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6", 8]],
56: [["BTCB", "0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c", 18]],
};
const ERC20 = ["function balanceOf(address) view returns (uint256)", "function transfer(address,uint256) returns (bool)", "function symbol() view returns (string)", "function decimals() view returns (uint8)"];
const assets = () => [{ sym: SYM(), addr: ethers.ZeroAddress, dec: 18 }, ...(BTC[cfg.chainId] || []).map(([sym, addr, dec]) => ({ sym, addr, dec }))];
const asset = () => assets().find((x) => x.addr === $("#asset").value) || assets()[0];
const fmtU = (v, dec) => { const s = ethers.formatUnits(v, dec); return s.includes(".") ? s.replace(/(\.\d{0,8})\d*$/, "$1").replace(/\.?0+$/, "") || "0" : s; };
const fmt = (wei) => fmtU(wei, 18);
function amt(id) {
const raw = $(id).value.trim().replace(",", ".");
if (!raw) throw oops("Enter an amount.");
let v; try { v = ethers.parseUnits(raw, asset().dec); } catch { throw oops(`"${raw}" is not a valid amount. Use digits and a dot, like 0.01${asset().dec < 18 ? ` (at most ${asset().dec} decimals)` : ""}.`); }
if (v <= 0n) throw oops("The amount must be more than 0.");
return v;
}
function addrIn(id, what = "the address to send to") {
const raw = $(id).value.trim();
if (!raw) throw oops(`Enter ${what} (0x…, 42 characters).`);
if (!ethers.isAddress(raw)) throw oops(`"${raw.slice(0, 14)}${raw.length > 14 ? "…" : ""}" is not a valid address. Paste the full 0x… address (42 characters) and check every character.`);
return ethers.getAddress(raw);
}
async function vaultBalance(A) { return A.addr === ethers.ZeroAddress ? read.getBalance(current) : new ethers.Contract(A.addr, ERC20, read).balanceOf(current); }
function needVault() { if (!current) throw oops("Open a vault first (paste its address above and press Open)."); }
function fillAssets() {
const sel = $("#asset"), keep = sel.value;
sel.innerHTML = assets().map((x) => ``).join("");
if (assets().some((x) => x.addr === keep)) sel.value = keep;
document.querySelectorAll(".unit").forEach((e) => (e.textContent = asset().sym));
}
const vabi = () => (ver === 3 ? abi.vault3 : abi.vault);
const vaultR = (a) => new ethers.Contract(a, vabi(), read);
const cloneOf = (impl) => ("0x363d3d373d3d3d363d73" + impl.slice(2) + "5af43d82803e903d91602b57fd5bf3").toLowerCase();
async function openVault(addr) {
addr = ethers.getAddress(addr.trim());
const code = (await read.getCode(addr)).toLowerCase();
if (code === "0x") throw new Error("No vault contract at " + addr + " on this chain.");
ver = cfg.v3?.implementation && code === cloneOf(cfg.v3.implementation) ? 3 : 2;
fillAssets();
const v = vaultR(addr), A = asset();
const balOf = A.addr === ethers.ZeroAddress ? read.getBalance(addr) : new ethers.Contract(A.addr, ERC20, read).balanceOf(addr);
let root, height, next;
if (ver === 3) { const k = await v.primary(); root = k.pkHash; next = await v.nonce(); height = 0; }
else [root, height, next] = await Promise.all([v.root(), v.height(), v.nextIndex()]);
const [bal, owner, pol, lim, spent] = await Promise.all([balOf, v.owner(), v.policyVersion(), v.dailyLimit(A.addr), v.spentToday(A.addr)]);
current = addr;
$("#vIdx").previousElementSibling.textContent = ver === 3 ? "Primary-key signatures" : "One-time keys used";
$("#vRoot").previousElementSibling.textContent = ver === 3 ? "Primary key (ML-DSA-65)" : "Vault key root";
$("#withdraw").closest(".act").querySelector("p").textContent = ver === 3 ? "Any amount. Signed here with your ML-DSA-65 primary key (FIPS 204); the contract verifies it." : "Any amount. Signed here with a one-time hash key; the contract checks it.";
$("#vBal").textContent = fmtU(bal, A.dec) + " " + A.sym;
$("#vSpent").textContent = `${fmtU(spent, A.dec)} / ${fmtU(lim, A.dec)} ${A.sym}`;
$("#vIdx").textContent = ver === 3 ? `${next} (no limit)` : `${next} / ${2 ** Number(height)}`;
$("#vPol").textContent = "v" + pol;
$("#vAddr").textContent = addr; $("#vOwner").textContent = owner; $("#vRoot").textContent = root;
$("#vLink").href = `${cfg.explorer}/address/${addr}`;
$("#vaultView").hidden = false;
const rec = store.one(addr);
if (!rec?.kit || kitAad(rec.kit).toLowerCase() !== root.toLowerCase()) kitPicker(true);
else kitPicker(false);
const keep = new URLSearchParams(location.search).get("recover");
history.replaceState(null, "", `?chain=${cfg.chainId}&vault=${addr}` + (keep ? `&recover=${keep}` : ""));
relayStatus(); guardiansView().catch(fail); v2View().catch(fail); recovery3View().catch(fail); planView().catch(() => {}); if (!migBusy()) migView().catch(() => {});
}
function kitPicker(show) {
let box = $("#kitPick");
if (!show) { box?.remove(); return; }
if (box) return;
box = document.createElement("label"); box.className = "fl"; box.id = "kitPick";
box.innerHTML = (ver === 3 ? "Primary Kit" : "Recovery Kit") + ' for this vault not stored in this browser';
$("#withdraw").before(box);
}
$("#loadForm").onsubmit = (e) => { e.preventDefault(); const b = $("#loadForm button"); busy(b, "Opening…", async () => { addrIn("#vaultAddr", "the vault address"); await openVault($("#vaultAddr").value); }); };
$("#asset").onchange = () => { document.querySelectorAll(".unit").forEach((e) => (e.textContent = asset().sym)); if (current) openVault(current).catch(fail); };
$("#deposit").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needVault(); needWallet(); const A = asset(), value = amt("#depAmt");
const have = A.addr === ethers.ZeroAddress ? await read.getBalance(account) : await new ethers.Contract(A.addr, ERC20, read).balanceOf(account);
if (have < value) throw oops(`Your wallet has only ${fmtU(have, A.dec)} ${A.sym} on ${cfg.chainName}.`);
const tx = A.addr === ethers.ZeroAddress ? await signer.sendTransaction({ to: current, value }) : await new ethers.Contract(A.addr, ERC20, signer).transfer(current, value);
log(`Depositing ${fmtU(value, A.dec)} ${A.sym}…`, { hash: tx.hash });
await tx.wait(); log(`Deposited ${fmtU(value, A.dec)} ${A.sym}.`, { hash: tx.hash }); await openVault(current);
});
$("#spend").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needVault(); needWallet();
const v = vaultR(current); if ((await v.owner()).toLowerCase() !== account.toLowerCase()) throw oops(`The connected wallet (${account.slice(0, 8)}…) is not this vault's daily key. Switch to ${(await v.owner()).slice(0, 8)}… in your wallet.`);
const A = asset(), to = addrIn("#spTo"), value = amt("#spAmt");
if (ver === 3 || isV2) { if (await v.frozen()) throw oops("The vault is frozen, so the daily key cannot spend. Unfreeze it with the vault key first."); }
const [lim, used, bal] = await Promise.all([v.dailyLimit(A.addr), v.spentToday(A.addr), vaultBalance(A)]);
if (lim === 0n) throw oops(`This vault is post-quantum only: the daily key is off for ${A.sym}, so every spend needs the post-quantum key. Use "Withdraw with the vault key", or turn the daily key on under "Change the daily limit".`);
if (used + value > lim) throw oops(`Over the daily limit: the daily key can spend ${fmtU(lim > used ? lim - used : 0n, A.dec)} more ${A.sym} today (limit ${fmtU(lim, A.dec)}). Use "Withdraw with the vault key" for more.`);
if (bal < value) throw oops(`The vault holds only ${fmtU(bal, A.dec)} ${A.sym}.`);
const tx = await new ethers.Contract(current, abi.vault, signer).spend(A.addr, to, value);
log(`Daily key: sending ${fmtU(value, A.dec)} ${A.sym}…`, { hash: tx.hash }); await tx.wait();
log(`Daily key sent ${fmtU(value, A.dec)} ${A.sym} to ${to.slice(0, 8)}…`, { hash: tx.hash }); await openVault(current);
});
// Signs a batch of calls with the next one-time key and submits it from the connected wallet.
let relayOn = false;
async function relayStatus() {
try { const r = await (await fetch(`/api/relay/status?chain=${cfg.chainId}`)).json(); relayOn = !!(r.enabled && r.funded); } catch { relayOn = false; }
$("#gaslessBox").hidden = !relayOn || ver === 3;
}
async function vaultExecute(calls, pass, what) {
if (!pass) throw new Error("Enter the passphrase of this vault's Recovery Kit.");
await auditGate(calls); // simulated and checked before anything is signed
if (ver === 3) return executeV3(calls, pass, what);
const useRelay = relayOn && $("#gasless").checked;
if (!useRelay) needWallet();
const v = vaultR(current);
let rec = store.one(current) || {};
if (!rec.kit) {
const f = $("#kitPick input")?.files?.[0]; if (!f) throw new Error("Choose this vault's Recovery Kit file.");
rec = { kit: JSON.parse(await f.text()), nextLeaf: 0 };
}
const [root, height, onNext, policyVersion] = await Promise.all([v.root(), v.height(), v.nextIndex(), v.policyVersion()]);
if (rec.kit.root.toLowerCase() !== root.toLowerCase()) throw new Error("This kit is not the vault's current key (it may have been rotated).");
let tree = trees.get(rec.kit.root);
if (!tree) {
log("Unlocking the kit and rebuilding the key tree (a few seconds)…");
const seed = await openKit(rec.kit, pass);
tree = (await buildTree(seed, rec.kit.treeNo, rec.kit.height)).tree;
if (HS.hex(tree.root).toLowerCase() !== root.toLowerCase()) throw new Error("The rebuilt key does not match the vault.");
trees.set(rec.kit.root, tree);
} else await openKit(rec.kit, pass); // the passphrase is still required for every signature
const leaf = Math.max(Number(onNext), rec.nextLeaf || 0);
if (leaf >= 2 ** Number(height)) throw new Error("All 1,024 one-time keys are used. Rotate to a new key.");
const deadline = Number((await read.getBlock("latest")).timestamp) + 1800; // 30 minutes of chain time
const tuples = calls.map((c) => [c.target, c.value, c.data]);
const digest = HS.opDigest(ethers.AbiCoder.defaultAbiCoder(), { chainId: cfg.chainId, vault: current, policyVersion: Number(policyVersion), leaf, deadline, calls });
if (HS.hex(digest) !== (await v.opDigest(tuples, leaf, deadline))) throw new Error("Digest mismatch with the contract; nothing was signed.");
const { sig, path } = HS.sign(tree, leaf, digest);
store.put(current, { kit: rec.kit, nextLeaf: leaf + 1 }); // this one-time key is spent from now on, sent or not
let hash;
if (useRelay) {
const res = await fetch("/api/relay", { method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ chainId: cfg.chainId, vault: current, calls: calls.map((c) => ({ target: c.target, value: c.value.toString(), data: c.data })), leaf, deadline, sig, path }) });
const j = await res.json(); if (!res.ok) throw new Error(j.error || "The relayer refused it.");
hash = j.hash; log(`${what} (one-time key #${leaf}), sent by the relayer…`, { hash });
} else {
const tx = await new ethers.Contract(current, abi.vault, signer).execute(tuples, leaf, deadline, sig, path);
hash = tx.hash; log(`${what} (one-time key #${leaf})…`, { hash });
}
const r = await read.waitForTransaction(hash, 1, 180_000);
if (!r || r.status !== 1) throw new Error("The transaction did not go through. Check it on the explorer.");
log(`${what}: done, ${r.gasUsed.toLocaleString()} gas${useRelay ? ", paid by the relayer" : ""}.`, { hash });
await openVault(current);
}
// v3: sign with the ML-DSA-65 primary key and submit from the connected wallet.
async function primaryKey(pass) {
let rec = store.one(current) || {};
if (!rec.kit) { const f = $("#kitPick input")?.files?.[0]; if (!f) throw new Error("Choose this vault's Primary Kit file."); rec = { kit: JSON.parse(await f.text()) }; }
if (rec.kit.kind !== "primary-mldsa65") throw new Error("That is not a Primary Kit (hashfort-primary-kit-….json).");
const k = mlFromSeed(await openKit(rec.kit, pass));
const onChain = (await vaultR(current).primary()).pkHash;
if (k.pkHash.toLowerCase() !== onChain.toLowerCase()) throw new Error("This kit is not the vault's current primary key (it may have been replaced).");
store.put(current, { kit: rec.kit, chainId: cfg.chainId, v3: true });
return k;
}
async function executeV3(calls, pass, what) {
needWallet();
const k = await primaryKey(pass), v = vaultR(current);
await canPay(5_600_000 + 400_000 * calls.length, "An ML-DSA-65 signed operation");
const deadline = Number((await read.getBlock("latest")).timestamp) + 1800;
const tuples = calls.map((c) => [c.target, c.value, c.data]);
const digest = await v.opDigest(tuples, deadline);
const sig = PQ.ml_dsa65.sign(ethers.getBytes(digest), k.secretKey, { context: enc.encode("HASHFORT_V3_OP") });
const tx = await new ethers.Contract(current, abi.vault3, signer).execute(tuples, deadline, sig);
log(`${what} (ML-DSA-65 signature #${await v.nonce()})…`, { hash: tx.hash });
const r = await read.waitForTransaction(tx.hash, 1, 180_000);
if (!r || r.status !== 1) throw new Error("The transaction did not go through. Check it on the explorer.");
log(`${what}: done, ${r.gasUsed.toLocaleString()} gas.`, { hash: tx.hash });
await openVault(current);
}
$("#withdraw").onclick = (e) => busy(e.target, "Signing…", async () => {
needVault();
const A = asset(), to = addrIn("#wdTo"), value = amt("#wdAmt");
if (!$("#wdPass").value) throw oops("Enter the passphrase of this vault's " + (ver === 3 ? "Primary Kit." : "Recovery Kit."));
const bal = await vaultBalance(A);
if (bal < value) throw oops(`The vault holds only ${fmtU(bal, A.dec)} ${A.sym}, less than ${fmtU(value, A.dec)}.`);
const call = A.addr === ethers.ZeroAddress ? { target: to, value, data: "0x" } : { target: A.addr, value: 0n, data: new ethers.Interface(ERC20).encodeFunctionData("transfer", [to, value]) };
await vaultExecute([call], $("#wdPass").value, `Vault key: withdrawing ${fmtU(value, A.dec)} ${A.sym}`);
});
$("#setLimit").onclick = (e) => busy(e.target, "Signing…", async () => {
needVault(); const A = asset(), value = amt("#newLimit");
const data = new ethers.Interface(abi.vault).encodeFunctionData("setDailyLimit", [A.addr, value]);
await vaultExecute([{ target: current, value: 0n, data }], $("#limPass").value, `Vault key: ${A.sym} daily limit to ${fmtU(value, A.dec)}`);
});
// ---------------------------------------------------------------- guardians and recovery
const b64 = (o) => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const unb64 = (t) => JSON.parse(atob(t.replace(/-/g, "+").replace(/_/g, "/")));
let request = null; // { owner, root, seed, height } from ?recover=
async function guardiansView() {
const v = vaultR(current);
const [gs, thr, delay] = await Promise.all([v.guardians(), v.threshold(), v.recoveryDelay()]);
$("#guardians").hidden = false;
$("#gList").textContent = gs.length ? gs.join("\n") : "none set";
$("#gThr").textContent = gs.length ? `${thr} of ${gs.length}` : "—";
$("#gDelay").textContent = gs.length ? `${Math.round(Number(delay) / 3600)} hours` : "—";
const q = new URLSearchParams(location.search).get("recover");
if (!q) { $("#reqBox").hidden = true; return; }
try { request = unb64(q); } catch { request = null; }
if (!request) return;
const id = ver === 3 ? await v.recoveryId(request.owner, [request.dataA, request.dataB, request.pkHash], request.recoveryKey)
: await v.recoveryId(request.owner, request.root, request.seed, request.height);
const [mask, ready] = await Promise.all([v.approvals(id), v.readyAt(id)]);
const n = mask.toString(2).split("").filter((x) => x === "1").length, now = Number((await read.getBlock("latest")).timestamp); // chain time, not the browser clock
$("#reqBox").hidden = false;
$("#reqInfo").textContent = ver === 3 ? `New primary key ${request.pkHash.slice(0, 12)}…, new recovery key ${request.recoveryKey.slice(0, 12)}…, new daily key ${request.owner.slice(0, 10)}…`
: `New vault key ${request.root.slice(0, 12)}…, new daily key ${request.owner.slice(0, 10)}…`;
$("#reqApp").textContent = `${n} of ${thr}`;
$("#reqReady").textContent = Number(ready) === 0 ? "needs more approvals" : Number(ready) <= now ? "ready now" : `in ${Math.ceil((Number(ready) - now) / 3600)} h (${new Date(Number(ready) * 1000).toLocaleString()})`;
$("#reqExec").disabled = !(Number(ready) > 0 && Number(ready) <= now);
}
$("#gSet").onclick = (e) => busy(e.target, "Signing…", async () => {
const addrs = $("#gAddrs").value.split(/[\s,]+/).filter(Boolean).map((a) => ethers.getAddress(a));
const need = Number($("#gNeed").value), hours = Number($("#gHours").value);
if (addrs.length < 1 || addrs.length > 8 || !(need >= 1 && need <= addrs.length)) throw new Error("Enter 1 to 8 guardians and an approval count no larger than that.");
if (!(hours >= 24)) throw new Error("The waiting time must be at least 24 hours.");
const data = new ethers.Interface(abi.vault).encodeFunctionData("setGuardians", [addrs, need, hours * 3600]);
await vaultExecute([{ target: current, value: 0n, data }], $("#gPass").value, `Vault key: ${need} of ${addrs.length} guardians, ${hours} h wait`);
});
$("#cGo").onclick = (e) => busy(e.target, "Signing…", async () => {
const data = new ethers.Interface(abi.vault).encodeFunctionData("cancelRecovery", []);
await vaultExecute([{ target: current, value: 0n, data }], $("#cPass").value, "Vault key: cancel pending recoveries");
});
$("#rStart").onclick = (e) => busy(e.target, "Building the new key…", async () => {
const pass = $("#rPass").value; if (pass.length < 12) throw new Error("Use a passphrase of at least 12 characters.");
const owner = account || (await vaultR(current).owner());
if (ver === 3) {
needWallet();
const nk = await newPrimary(pass);
const rseed = crypto.getRandomValues(new Uint8Array(48)), recKey = HS.hex(PQ.slh_dsa_sha2_128s.keygen(rseed).publicKey);
const rkit = await sealBytes(rseed, pass, recKey, { kind: "recovery-slhdsa128s", recoveryKey: recKey });
setTimeout(() => download(rkit, `hashfort-RECOVERY-kit-${recKey.slice(2, 10)}.json`), 600);
const req = { v: 3, owner, dataA: nk.dataA, dataB: nk.dataB, pkHash: nk.pkHash, recoveryKey: recKey };
store.put(current, { pendingKit: nk.kit, chainId: cfg.chainId });
const link = `${location.origin}/app/?chain=${cfg.chainId}&vault=${current}&recover=${b64(req)}`;
$("#rLink").textContent = link; $("#rLinkBox").hidden = false;
history.replaceState(null, "", link.slice(location.origin.length));
log("New primary and recovery keys made, their kits saved and the key data stored on chain. Send the link to your guardians.");
return guardiansView();
}
const seed = crypto.getRandomValues(new Uint8Array(32));
const { tree } = await buildTree(seed, TREE0, HEIGHT);
const kit = await sealKit(seed, pass, tree);
const blob = new Blob([JSON.stringify(kit, null, 2)], { type: "application/json" });
const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `hashfort-recovery-kit-${kit.root.slice(2, 10)}.json`; a.click();
store.put(current, { pendingKit: kit, chainId: cfg.chainId });
const req = { owner, root: kit.root, seed: kit.pubSeed, height: HEIGHT };
const link = `${location.origin}/app/?chain=${cfg.chainId}&vault=${current}&recover=${b64(req)}`;
$("#rLink").textContent = link; $("#rLinkBox").hidden = false;
history.replaceState(null, "", link.slice(location.origin.length));
log("New vault key made and its Recovery Kit saved. Send the link to your guardians.");
await guardiansView();
});
$("#reqApprove").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needWallet(); if (!request) throw new Error("No recovery request in this link.");
const gs = (await vaultR(current).guardians()).map((x) => x.toLowerCase());
if (!gs.includes(account.toLowerCase())) throw new Error("The connected wallet is not a guardian of this vault.");
const tx = ver === 3 ? await new ethers.Contract(current, abi.vault3, signer).approveRecovery(request.owner, [request.dataA, request.dataB, request.pkHash], request.recoveryKey)
: await new ethers.Contract(current, abi.vault, signer).approveRecovery(request.owner, request.root, request.seed, request.height);
log("Guardian approval sent…", { hash: tx.hash }); await tx.wait(); log("Guardian approval recorded.", { hash: tx.hash }); await guardiansView();
});
$("#reqExec").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needWallet(); if (!request) throw new Error("No recovery request in this link.");
const tx = ver === 3 ? await new ethers.Contract(current, abi.vault3, signer).executeRecovery(request.owner, [request.dataA, request.dataB, request.pkHash], request.recoveryKey)
: await new ethers.Contract(current, abi.vault, signer).executeRecovery(request.owner, request.root, request.seed, request.height);
log("Executing recovery…", { hash: tx.hash }); await tx.wait();
const rec = store.one(current);
if (rec?.pendingKit && kitAad(rec.pendingKit).toLowerCase() === (request.root || request.pkHash).toLowerCase()) store.put(current, { kit: rec.pendingKit, nextLeaf: 0, pendingKit: null });
log("Recovered: the vault now answers to the new key.", { hash: tx.hash });
const u = new URL(location.href); u.searchParams.delete("recover"); history.replaceState(null, "", u.pathname + u.search);
await openVault(current);
});
// ---------------------------------------------------------------- buttons
function refreshButtons() {
const p1 = $("#pass1").value, p2 = $("#pass2").value;
const hint = (id, text) => { let h = $(id); if (!h) return; h.textContent = text; h.hidden = !text; };
hint("#passHint", !draft ? "Make the key in step 01 first." : !p1 ? "" : p1.length < 12 ? `At least 12 characters (${p1.length} so far).` : p2 && p1 !== p2 ? "The two passphrases do not match." : "");
hint("#deployHint", !draft ? "Make the key in step 01 first." : !draft.rehearsed ? "Open the kit you saved in step 02 first (rehearsal)." : !signer ? "Connect your wallet (top right); it becomes the daily key." : "");
$("#saveKit").disabled = !draft || p1.length < 12 || p1 !== p2;
$("#deploy").disabled = !draft?.rehearsed || !(draft?.mode === "v3" ? cfg?.v3?.factory : cfg?.factory) || !signer;
if (draft?.rehearsed && signer) predict().catch(() => {});
}
$("#connect").onclick = (e) => busy(e.target, "Connecting…", connect);
init().catch(fail);
// ---------------------------------------------------------------- auditor (before every vault-key signature)
function auditGate(calls) {
const d = $("#audit"), title = $("#adTitle");
title.className = ""; title.textContent = "Checking this transaction…";
$("#adCalls").innerHTML = ""; $("#adWarn").innerHTML = ""; $("#adAi").hidden = true; $("#adMeta").textContent = ""; $("#adYes").disabled = true;
d.showModal();
return new Promise((ok, no) => {
$("#adNo").onclick = () => { d.close(); no(new Error("Cancelled before signing.")); };
d.oncancel = (e) => { e.preventDefault(); $("#adNo").onclick(); };
$("#adYes").onclick = () => { d.close(); ok(); };
fetch("/api/audit", { method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ chainId: cfg.chainId, vault: current, explain: true, calls: calls.map((c) => ({ target: c.target, value: c.value.toString(), data: c.data })) }) })
.then(async (r) => { const j = await r.json(); if (!r.ok) throw new Error(j.error || "audit failed"); return j; })
.then((rep) => {
title.className = rep.verdict;
title.textContent = { ok: "Simulated: nothing unusual found", review: "Simulated: read the notes before signing", stop: "Simulated: this looks dangerous" }[rep.verdict];
for (const c of rep.calls) {
const li = document.createElement("li"); li.className = c.sim.ok ? "" : "bad";
const a = document.createElement("span"); a.textContent = c.summary + (c.note ? ` (${c.note})` : "");
const b = document.createElement("span"); b.textContent = c.sim.ok ? `ok · ${Number(c.sim.gas).toLocaleString()} gas` : "fails: " + c.sim.revert;
li.append(a, b); $("#adCalls").append(li);
}
for (const w of rep.warnings) { const li = document.createElement("li"); li.className = w.level; li.textContent = w.text; $("#adWarn").append(li); }
if (rep.explanation || rep.explainNote) { $("#adAi").textContent = rep.explanation || rep.explainNote; $("#adAi").hidden = false; }
$("#adMeta").textContent = `Block ${rep.block} · simulated from the vault · report ${rep.hash}`;
$("#adYes").textContent = rep.verdict === "stop" ? "Sign anyway" : "Sign";
$("#adYes").disabled = false;
})
.catch((e) => { title.className = "review"; title.textContent = "The check could not run: " + e.message; $("#adYes").textContent = "Sign without the check"; $("#adYes").disabled = false; });
});
}
// ---------------------------------------------------------------- v2: frozen state, agents, Sentinel
const clone = (impl) => ("0x363d3d373d3d3d363d73" + impl.slice(2) + "5af43d82803e903d91602b57fd5bf3").toLowerCase();
let isV2 = false, pub = null;
const VI = () => new ethers.Interface(abi.vault);
const selfCall = (fn, args) => ({ target: current, value: 0n, data: VI().encodeFunctionData(fn, args) });
const usdgFmt = (x) => (Number(x) / 1e6).toLocaleString(undefined, { maximumFractionDigits: 2 });
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }
async function v2View() {
const code = (await read.getCode(current)).toLowerCase();
isV2 = ver === 3 || (cfg.version === 2 && !!cfg.implementation && code === clone(cfg.implementation));
$("#agentsPanel").hidden = $("#sentinelPanel").hidden = !isV2;
if (!isV2) { $("#frozenBox").hidden = true; return; }
const v = vaultR(current);
$("#frozenBox").hidden = !(await v.frozen());
pub = await (await fetch(`/api/sentinel/public?chain=${cfg.chainId}`)).json().catch(() => null);
$("#snAddr").textContent = pub?.address || "not set up on this site yet";
const on = pub?.address ? await v.sentinel(pub.address) : false;
$("#snOn").textContent = on ? "added (can freeze and revoke agents only)" : "not added";
$("#snEnable").hidden = on; $("#snDisable").hidden = !on; $("#snEnable").disabled = !pub?.address;
const x = pub?.x402;
$("#x402Note").textContent = x?.live
? `What agents can buy: ${x.services.map((s) => `${s.id === "exposure" ? "exposure report" : "transaction audit"} for ${s.priceUsd} USDG`).join(", ")}, paid on chain to ${x.payTo}.`
: "Paid services are not switched on for this site yet, so agents have nothing to buy.";
if (session()) { loadAgents().catch(fail); loadSentinel().catch(fail); }
}
$("#unfreeze").onclick = (e) => busy(e.target, "Signing…", () => vaultExecute([selfCall("unfreeze", [])], $("#ufPass").value, "Vault key: unfreeze"));
// owner session: a signature from the daily key, valid 12 h, for this vault only
const SKEY = () => `hashfort.session.${cfg.chainId}.${current?.toLowerCase()}`;
function session() { try { const s = JSON.parse(sessionStorage.getItem(SKEY()) || "null"); return s && Date.now() / 1000 - s.issued < 11.5 * 3600 ? s.header : null; } catch { return null; } }
async function signIn() {
needWallet();
if ((await vaultR(current).owner()).toLowerCase() !== account.toLowerCase()) throw new Error("Connect this vault's daily key (the wallet that owns it) to sign in.");
const m = await (await fetch(`/api/agents/session?chain=${cfg.chainId}&vault=${current}`)).json();
const sig = await signer.signMessage(m.message);
const header = btoa(JSON.stringify({ vault: current, chainId: cfg.chainId, issued: m.issued, sig }));
try { sessionStorage.setItem(SKEY(), JSON.stringify({ issued: m.issued, header })); } catch {}
log("Signed in as the vault owner for 12 hours (this cannot move funds).");
await Promise.all([loadAgents(), loadSentinel()]);
}
$("#signIn").onclick = (e) => busy(e.target, "Sign in your wallet…", signIn);
async function api(path, body) {
const h = session(); if (!h) throw new Error("Sign in with the daily key first.");
const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json", "x-hf-auth": h }, body: JSON.stringify({ chainId: cfg.chainId, vault: current, ...body }) });
const j = await r.json().catch(() => ({}));
if (r.status === 401) { try { sessionStorage.removeItem(SKEY()); } catch {} }
if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
return j;
}
// agents
async function loadAgents() {
const d = await api("/api/agents/list", {});
$("#agentsBody").hidden = false; $("#signIn").hidden = true;
const box = $("#agentList"); box.innerHTML = "";
if (!d.agents.length) { box.append(el("p", "hint", "No agents yet.")); return; }
for (const a of d.agents) box.append(agentCard(a, d));
}
function txLink(hash, text) { const a = el("a", "", text); a.href = `${cfg.explorer}/tx/${hash}`; a.target = "_blank"; a.rel = "noopener"; return a; }
function agentCard(a, d) {
const c = a.chain || {}, card = el("div", "agent");
const top = el("div", "top"), h = el("h3", "", a.name);
h.append(el("span", "pill " + (c.active && !c.frozen ? "on" : "off"), c.frozen ? "vault frozen" : c.active ? "active" : c.enabled ? "expired" : "not active"));
top.append(h, el("code", "", a.address));
const grid = el("div", "grid");
for (const [k, v] of [["USDG today", `${usdgFmt(c.usdgSpentToday || 0)} / ${usdgFmt(c.usdgLimit || 0)}`], ["Expires", c.expiry ? new Date(c.expiry * 1000).toLocaleDateString() : "—"],
["Gas left", c.gasWei ? (+ethers.formatEther(c.gasWei)).toFixed(5) + " ETH" : "—"], ["May pay", c.anyTarget ? "anyone" : "allowed addresses"]]) { const x = el("div"); x.append(el("span", "", k), el("b", "", v)); grid.append(x); }
const cols = el("div", "cols");
const pro = (d.tier?.tier || 0) >= 1, aiOk = d.ai && pro;
const t = el("div", "act"); t.append(el("h3", "", "Give it a task"), el("p", "", !d.ai ? "The AI is not switched on for this site yet; the exposure report next to this works without it."
: !pro ? "AI tasks are a Pro feature: buy Pro in the Plan panel, or hold HASHFORT. The exposure report next to this works on every plan." : "Plain words. It can read the vault, get an exposure report, and remember things."));
const ta = el("textarea"); ta.placeholder = "Check whether my other wallets 0x… and bc1q… are quantum-exposed, and remember which ones are."; ta.disabled = !aiOk;
const tb = el("button", "b dark", "Run task"); tb.type = "button"; tb.disabled = !aiOk;
tb.onclick = () => busy(tb, "Working…", async () => { await api("/api/agents/run", { agent: a.address, task: ta.value }); log(`${a.name}: task done.`); await loadAgents(); });
t.append(ta, tb);
const x = el("div", "act"); x.append(el("h3", "", "Exposure report"), el("p", "", "Paid over x402 from this agent's allowance, on chain. Up to 20 EVM or Bitcoin addresses."));
const xa = el("textarea", "mono"); xa.placeholder = "one address per line";
const xb = el("button", "b dark", "Buy report"); xb.type = "button";
xb.onclick = () => busy(xb, "Paying and scanning…", async () => {
const r = await api("/api/agents/run", { agent: a.address, kind: "exposure", addresses: xa.value.split(/[\s,]+/).filter(Boolean) });
const pay = r.trail.find((s) => s.tx), hold = r.trail.find((s) => s.step === "holder");
log(`${a.name} ${hold ? "used holder access (free, " + hold.balance + ")" : "paid " + (pay?.amount || "")} and got the report: ${r.answer.summary.exposed} exposed, ${r.answer.summary.hidden} not exposed.`, { hash: pay?.tx });
await loadAgents();
});
x.append(xa, xb);
const m = el("div", "act"); m.append(el("h3", "", "MEMORY.md"), el("p", "", "What the agent reads before every task. Yours to edit."));
const ma = el("textarea", "mono"); ma.value = a.memory; ma.rows = 8;
const mb = el("button", "b dark", "Save memory"); mb.type = "button";
mb.onclick = () => busy(mb, "Saving…", async () => { await api("/api/agents/memory", { agent: a.address, memory: ma.value }); log(`${a.name}: MEMORY.md saved.`); });
m.append(ma, mb);
cols.append(t, x, m);
const row = el("div", "row");
const rv = el("button", "b", "Revoke now (daily key)"); rv.type = "button"; rv.disabled = !c.enabled;
rv.onclick = () => busy(rv, "Confirm in your wallet…", async () => { needWallet(); const tx = await new ethers.Contract(current, abi.vault, signer).revokeAgent(a.address); log(`Revoking ${a.name}…`, { hash: tx.hash }); await tx.wait(); log(`${a.name} revoked.`, { hash: tx.hash }); await loadAgents(); });
const fg = el("button", "b", "Delete its key from the server"); fg.type = "button";
fg.onclick = () => busy(fg, "Deleting…", async () => { if (c.enabled) throw new Error("Revoke it on chain first."); await api("/api/agents/forget", { agent: a.address }); log(`${a.name}: key destroyed on the server.`); await loadAgents(); });
row.append(rv, fg);
card.append(top, grid, cols, row);
if (a.runs?.length) {
const runs = el("ol", "runs");
for (const r of a.runs) {
const li = el("li"); li.append(el("div", "q", `${new Date(r.started).toLocaleString()} · ${r.task}`));
if (r.error) li.append(el("div", "e", r.error));
else li.append(el("div", "a", typeof r.answer === "string" ? r.answer : `${r.answer.summary.addresses} address(es): ${r.answer.summary.exposed} exposed, ${r.answer.summary.hidden} not exposed. ` +
r.answer.results.map((x) => `${x.address.slice(0, 10)}… ${x.results.filter((y) => y.status === "exposed").map((y) => y.network).join(", ") || "not exposed"}`).join("; ")));
for (const s of r.trail.filter((s) => s.tx)) li.append(document.createElement("br"), txLink(s.tx, `paid ${s.amount}: ${s.tx.slice(0, 12)}…`));
for (const s of r.trail.filter((s) => s.step === "holder")) li.append(document.createElement("br"), el("span", "q", `free: HASHFORT holder (${s.balance})`));
runs.append(li);
}
card.append(runs);
}
return card;
}
$("#naGo").onclick = (e) => busy(e.target, "Creating…", async () => {
const pass = $("#naPass").value; if (!pass) throw new Error("Enter the passphrase of this vault's Recovery Kit.");
const limit = ethers.parseUnits(($("#naLimit").value || "0").trim(), 6), days = Number($("#naDays").value), gas = ethers.parseEther(($("#naGas").value || "0").trim());
if (!(days >= 1 && days <= 365)) throw new Error("Valid for 1 to 365 days.");
const made = await api("/api/agents/create", { name: $("#naName").value });
log(`Agent key ${made.address.slice(0, 10)}… made on the server. Now the vault key adds it.`);
const expiry = Number((await read.getBlock("latest")).timestamp) + days * 86400;
const calls = [selfCall("setAgent", [made.address, expiry, false]), selfCall("setAgentLimit", [made.address, made.usdg, limit])];
if (made.payTo) calls.push(selfCall("setAgentTarget", [made.address, made.payTo, true]));
if (gas > 0n) calls.push({ target: made.address, value: gas, data: "0x" });
try { await vaultExecute(calls, pass, `Vault key: add agent ${$("#naName").value} (${ethers.formatUnits(limit, 6)} USDG a day, ${days} days)`); }
finally { await loadAgents().catch(() => {}); }
});
// Sentinel
async function loadSentinel() {
const s = await api("/api/sentinel/get", {});
$("#rRecovery").checked = s.rules.freezeOnRecovery; $("#rPct").value = s.rules.freezeOnSpendPct; $("#rAgent").checked = s.rules.alertAgentSpend;
$("#snOn").textContent = s.enabledOnChain ? (s.watching ? "added and watching" : "added, watcher off") : "not added";
$("#snPush").textContent = s.pushDevices ? `${s.pushDevices} device(s)` : "none";
const ol = $("#alerts"); ol.innerHTML = "";
if (!s.alerts.length) ol.append(el("li", "empty", "No alerts yet."));
for (const a of s.alerts) {
const li = el("li", a.level); li.append(el("time", "", new Date(a.at).toLocaleString()));
const m = el("span", "msg"); m.append(el("b", "", a.title + ". "), document.createTextNode(a.body)); li.append(m);
if (a.tx) li.append(txLink(a.tx, a.tx.slice(0, 10) + "…"));
ol.append(li);
}
vapidKey = s.vapidPublicKey;
}
let vapidKey = null;
$("#snEnable").onclick = (e) => busy(e.target, "Signing…", async () => {
if (!pub?.address) throw new Error("The Sentinel is not set up on this site yet.");
if (!session()) await signIn();
await vaultExecute([selfCall("setSentinel", [pub.address, true])], $("#snPass").value, "Vault key: add the Sentinel");
await api("/api/sentinel/set", { on: true }); log("Sentinel on: it now watches this vault."); await v2View();
});
$("#snDisable").onclick = (e) => busy(e.target, "Signing…", async () => {
await vaultExecute([selfCall("setSentinel", [pub.address, false])], $("#snPass").value, "Vault key: remove the Sentinel");
if (session()) await api("/api/sentinel/set", { on: false }); log("Sentinel removed from this vault."); await v2View();
});
$("#rSave").onclick = (e) => busy(e.target, "Saving…", async () => {
await api("/api/sentinel/set", { rules: { freezeOnRecovery: $("#rRecovery").checked, freezeOnSpendPct: Number($("#rPct").value), alertAgentSpend: $("#rAgent").checked } });
log("Sentinel rules saved."); await loadSentinel();
});
$("#snPushGo").onclick = (e) => busy(e.target, "Asking…", async () => {
if (!("serviceWorker" in navigator) || !("PushManager" in window)) throw new Error("This browser does not support push notifications.");
if (!session()) await signIn();
if (!vapidKey) await loadSentinel();
if ((await Notification.requestPermission()) !== "granted") throw new Error("Notifications were not allowed.");
const reg = await navigator.serviceWorker.register("/app/sw.js", { scope: "/app/" });
await navigator.serviceWorker.ready;
const b = vapidKey.replace(/-/g, "+").replace(/_/g, "/"), key = Uint8Array.from(atob(b + "=".repeat((4 - (b.length % 4)) % 4)), (ch) => ch.charCodeAt(0));
const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
await api("/api/sentinel/subscribe", { subscription: sub.toJSON() });
log("Alerts will arrive on this device."); await loadSentinel();
});
// keep alerts and the frozen banner current while the page is open
setInterval(() => {
if (!isV2 || !current || document.hidden) return;
vaultR(current).frozen().then((f) => { $("#frozenBox").hidden = !f; }).catch(() => {});
if (session()) loadSentinel().catch(() => {});
}, 15_000);
// proof of use, read from Robinhood Chain by the server: vaults made and vault-key signatures the contracts verified
fetch("/api/live").then((r) => r.json()).then((d) => {
if (!d?.vaults) return;
const ex = "https://explorer.mainnet.chain.robinhood.com", b = $("#liveProof");
b.append(`On Robinhood Chain now: ${d.vaults} vault${d.vaults === 1 ? "" : "s"} created by the factories, ${d.vaultKeyOperations} post-quantum signature${d.vaultKeyOperations === 1 ? "" : "s"} verified by the contracts (ML-DSA-65 for v3 vaults, hash-based for standard ones).`);
if (d.latest) {
b.append(` Latest (${d.latest.version === 3 ? "v3, ML-DSA-65" : "standard"}): vault `);
for (const [txt, href] of [[d.latest.vault.slice(0, 10) + "…", `${ex}/address/${d.latest.vault}`], [" "], ["created", `${ex}/tx/${d.latest.createdTx}`], [", "], ["vault-key withdrawal", `${ex}/tx/${d.latest.executeTx}`], ["."]]) {
if (!href) { b.append(txt); continue; }
const a = document.createElement("a"); a.href = href; a.target = "_blank"; a.rel = "noopener"; a.textContent = txt; b.append(a);
}
}
b.hidden = false;
}).catch(() => {});
// ---------------------------------------------------------------- v3: new primary keys and the SLH-DSA recovery key
async function storeData(bytes) {
const f = new ethers.Contract(cfg.v3.factory, abi.factory3, read), at = await f.dataAddress(bytes);
if ((await read.getCode(at)) !== "0x") return at;
await canPay(bytes.length > 10000 ? 5_200_000 : 1_200_000, "Storing the new key's data");
const tx = await new ethers.Contract(cfg.v3.factory, abi.factory3, signer).storeData(bytes);
log(`Storing key data on chain (${bytes.length.toLocaleString()} bytes)…`, { hash: tx.hash });
await tx.wait();
return at;
}
/** A fresh ML-DSA-65 primary key: its kit downloads, its verification data goes on chain. */
async function newPrimary(pass) {
const seed = crypto.getRandomValues(new Uint8Array(32)), k = mlFromSeed(seed), { A, B } = PQ.precompute(k.publicKey);
const kit = await sealBytes(seed, pass, k.pkHash, { kind: "primary-mldsa65", pkHash: k.pkHash });
download(kit, `hashfort-primary-kit-${k.pkHash.slice(2, 10)}.json`);
const dataA = await storeData(A), dataB = await storeData(B);
return { kit, pkHash: k.pkHash, dataA, dataB };
}
async function recovery3View() {
$("#recovery3").hidden = ver !== 3;
if (ver !== 3) return;
const v = vaultR(current);
const [rk, delay, ready, pend] = await Promise.all([v.recoveryKey(), v.keyRecoveryDelay(), v.pendingKeyReadyAt(), v.pendingKey()]);
$("#r3Key").textContent = rk === ethers.ZeroHash ? "none set" : rk;
$("#r3Delay").textContent = `${Math.round(Number(delay) / 3600)} hours`;
const now = Number((await read.getBlock("latest")).timestamp);
$("#r3Pending").textContent = Number(ready) === 0 ? "none" : `primary key ${pend.pkHash.slice(0, 14)}…, ${Number(ready) <= now ? "ready now" : "ready " + new Date(Number(ready) * 1000).toLocaleString()}`;
$("#r3Finish").disabled = !(Number(ready) > 0 && Number(ready) <= now);
}
$("#r3Start").onclick = (e) => busy(e.target, "Working…", async () => {
needWallet();
const pass = $("#r3New").value; if (pass.length < 12) throw new Error("Use a passphrase of at least 12 characters for the new primary key.");
const f = $("#r3Kit").files[0]; if (!f) throw new Error("Choose your Recovery Kit file (hashfort-RECOVERY-kit-….json).");
const rkit = JSON.parse(await f.text());
if (rkit.kind !== "recovery-slhdsa128s") throw new Error("That is not a Recovery Kit.");
const v = vaultR(current);
if (rkit.recoveryKey.toLowerCase() !== (await v.recoveryKey()).toLowerCase()) throw new Error("That Recovery Kit is not this vault's recovery key.");
const slh = PQ.slh_dsa_sha2_128s.keygen(await openKit(rkit, $("#r3Pass").value)); // checks the passphrase before anything goes on chain
const nk = await newPrimary(pass);
const key = [nk.dataA, nk.dataB, nk.pkHash], deadline = Number((await read.getBlock("latest")).timestamp) + 3600;
const digest = await v.recoveryDigest(key, deadline);
log("Signing with the SLH-DSA recovery key (about a second)…");
await new Promise((r) => setTimeout(r, 30));
const sig = PQ.slh_dsa_sha2_128s.sign(ethers.getBytes(digest), slh.secretKey, { context: enc.encode("HASHFORT_V3_RECOVERY") });
const tx = await new ethers.Contract(current, abi.vault3, signer).startKeyRecovery(key, deadline, sig);
log("Recovery-key request sent…", { hash: tx.hash }); await tx.wait();
store.put(current, { pendingKit: nk.kit, chainId: cfg.chainId });
log("Replacement started. It can be finished after the delay; your old primary key can cancel it until then.", { hash: tx.hash });
await recovery3View();
});
$("#r3Finish").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needWallet();
const tx = await new ethers.Contract(current, abi.vault3, signer).finishKeyRecovery();
log("Finishing the key replacement…", { hash: tx.hash }); await tx.wait();
const rec = store.one(current), k = await vaultR(current).primary();
if (rec?.pendingKit && rec.pendingKit.pkHash.toLowerCase() === k.pkHash.toLowerCase()) store.put(current, { kit: rec.pendingKit, pendingKit: null });
log("Done: the vault now answers to the new primary key.", { hash: tx.hash });
await openVault(current);
});
$("#r3Cancel").onclick = (e) => busy(e.target, "Signing…", () => vaultExecute([selfCall("cancelRecovery", [])], $("#r3CPass").value, "Primary key: cancel pending recoveries"));
// ---------------------------------------------------------------- plans (HashfortPlans, USDG) and the team dashboard
let plansCfg = null;
const usd = (v) => (Number(v) / 1e6).toLocaleString("en-US", { maximumFractionDigits: 2 });
async function loadPlans() {
plansCfg = await (await fetch("/api/plans")).json().catch(() => null);
if (!plansCfg) return;
const box = $("#planCards"); box.innerHTML = "";
for (const t of plansCfg.tiers) {
const c = el("div", "pc"); c.dataset.tier = t.id;
c.append(el("h3", "", t.name));
const pr = el("p", "pr", t.id === 0 ? "0" : usd(t.price)); pr.append(el("small", "", t.id === 0 ? " free" : " USDG / 30 days")); c.append(pr);
if (t.orHold) c.append(el("p", "or", `or hold ${Number(t.orHold).toLocaleString("en-US")} HASHFORT, no payment`));
const ul = el("ul"); for (const f of t.features) ul.append(el("li", "", f)); c.append(ul);
box.append(c);
}
// arriving from a pricing card (?plan=1 or 2): pick that plan, bring the panel into view and mark the card
const want = Number(new URL(location.href).searchParams.get("plan"));
if (want === 1 || want === 2) {
$("#pbPlan").value = String(want);
box.querySelector(`.pc[data-tier="${want}"]`)?.classList.add("want");
requestAnimationFrame(() => $("#planPanel").scrollIntoView({ behavior: "smooth", block: "start" }));
}
if (!plansCfg.contract) { $("#pbGo").disabled = true; $("#planBuyP").textContent = "The HashfortPlans contract is not deployed yet. Holders of HASHFORT already get Pro."; }
await planView();
}
async function planView() {
if (!plansCfg) return;
const who = [account, current, current ? await vaultR(current).owner().catch(() => null) : null].filter(Boolean);
if (!who.length) return;
const t = await (await fetch(`/api/plan?address=${who.join(",")}`)).json().catch(() => null);
if (!t) return;
document.querySelectorAll(".pc").forEach((c) => c.classList.toggle("on", Number(c.dataset.tier) === t.tier));
const how = t.source === "holder" ? `by holding ${Number(t.balance).toLocaleString("en-US", { maximumFractionDigits: 0 })} HASHFORT` : t.source === "plan" ? `until ${new Date(t.until * 1000).toLocaleDateString()}` : "";
$("#planNow").innerHTML = ""; $("#planNow").append("Your plan: ", el("b", "", t.name), how ? ` (${how})` : "", ".");
if (t.tier === 2 && current && session()) teamView().catch(() => {});
}
async function teamView() {
const d = await api("/api/team/vaults", {});
$("#teamBox").hidden = false;
const ol = $("#teamList"); ol.innerHTML = "";
if (!d.vaults.length) ol.append(el("li", "empty", "No vaults found for this wallet yet."));
for (const v of d.vaults) {
const li = el("li"); const m = el("span", "msg", `${v.vault.slice(0, 10)}… · v${v.version} · ${(+v.eth).toFixed(5)} ETH · ${v.operations} post-quantum operations${v.frozen ? " · FROZEN" : ""}`);
const a = el("a", "", "open"); a.href = `/app/?chain=${cfg.chainId}&vault=${v.vault}`; li.append(m, a); ol.append(li);
}
}
$("#pbGo").onclick = (e) => busy(e.target, "Confirm in your wallet…", async () => {
needWallet();
if (!plansCfg?.contract) throw oops("The plans contract is not live yet.");
const plan = Number($("#pbPlan").value), months = Number($("#pbMonths").value);
if (!(months >= 1 && months <= 24) || !Number.isInteger(months)) throw oops("Months must be a whole number from 1 to 24.");
const forRaw = $("#pbFor").value.trim(), forWho = forRaw ? addrIn("#pbFor", "the account to pay for") : account;
const price = BigInt(plan === 1 ? plansCfg.prices.pro : plansCfg.prices.team) * BigInt(months);
const tok = new ethers.Contract(plansCfg.token, ["function balanceOf(address) view returns (uint256)", "function allowance(address,address) view returns (uint256)", "function approve(address,uint256) returns (bool)"], signer);
const have = await tok.balanceOf(account);
if (have < price) throw oops(`This costs ${usd(price)} USDG; your wallet has ${usd(have)} USDG on ${cfg.chainName}.`);
if ((await tok.allowance(account, plansCfg.contract)) < price) {
const a = await tok.approve(plansCfg.contract, price); log(`Allowing the plans contract to take ${usd(price)} USDG…`, { hash: a.hash }); await a.wait();
}
const tx = await new ethers.Contract(plansCfg.contract, ["function buy(address,uint8,uint32) returns (uint64)"], signer).buy(forWho, plan, months);
log(`Paying for ${plan === 1 ? "Pro" : "Team"}, ${months} × 30 days…`, { hash: tx.hash }); await tx.wait();
log(`${plan === 1 ? "Pro" : "Team"} active for ${forWho.slice(0, 8)}… (${usd(price)} USDG paid to the treasury).`, { hash: tx.hash });
await planView();
});
loadPlans().catch(() => {});
setInterval(() => planView().catch(() => {}), 30_000);
// ---------------------------------------------------------------- migrate: move funds from an exposed wallet into the vault
// Lists what the connected wallet holds on this chain (native coin, BTC wrappers, USDG, HASHFORT and the most traded
// Robinhood Chain tokens from the exposure leaderboard) and moves it into the open vault, one wallet transaction each.
const migrateFrom = (() => { const m = new URLSearchParams(location.search).get("migrate"); return m && ethers.isAddress(m) ? ethers.getAddress(m) : null; })();
let migTokens = null;
async function migCandidates() {
if (!migTokens) {
const list = (BTC[cfg.chainId] || []).map(([sym, addr, dec]) => ({ sym, addr, dec }));
if (cfg.chainId === 4663) {
list.push({ sym: "USDG", addr: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", dec: 6 });
const [t, x] = await Promise.all([fetch("/api/token").then((r) => r.json()).catch(() => ({})), fetch("/api/exposure").then((r) => r.json()).catch(() => ({}))]);
if (t.address) list.push({ sym: t.symbol || "HASHFORT", addr: t.address, dec: 18 });
for (const k of x.tokens || []) if (!list.some((l) => l.addr.toLowerCase() === k.address.toLowerCase())) list.push({ sym: k.symbol, addr: k.address, dec: k.decimals ?? 18 });
}
migTokens = list;
}
return migTokens;
}
async function nativeMovable() { // leave enough for this transfer's gas (and the L1 data fee on rollups)
const [bal, fee] = await Promise.all([read.getBalance(account), read.getFeeData()]);
const price = fee.maxFeePerGas ?? fee.gasPrice ?? 0n, reserve = price * 21_000n * 3n + (cfg.chainId === 1 || cfg.chainId === 56 || cfg.chainId === 137 ? 0n : ethers.parseEther("0.00002"));
return { bal, move: bal > reserve ? bal - reserve : 0n, reserve };
}
async function migView() {
const box = $("#migList"), now = $("#migNow"), go = $("#migAll"); box.innerHTML = ""; go.disabled = true; $("#migFine").textContent = "";
if (!current) { box.append(el("li", "info", migrateFrom ? `Create or open a vault first (above). Then connect ${migrateFrom.slice(0, 8)}… and its funds can move here.` : "Open a vault first; this panel then moves funds into it.")); return; }
if (!account) { box.append(el("li", "info", migrateFrom ? `Connect ${migrateFrom.slice(0, 8)}… (the wallet you scanned) to see what it holds.` : "Connect the wallet you want to empty.")); return; }
if (account.toLowerCase() === current.toLowerCase()) return;
const sent = await read.getTransactionCount(account);
now.innerHTML = ""; now.append(`${account.slice(0, 8)}…${account.slice(-4)} on ${cfg.chainName}`, el("span", "expo " + (sent > 0 ? "bad" : "ok"), sent > 0 ? `key exposed · ${sent} tx sent` : "key not public yet"));
if (migrateFrom && migrateFrom.toLowerCase() !== account.toLowerCase()) box.append(el("li", "info", `You scanned ${migrateFrom.slice(0, 8)}…, but ${account.slice(0, 8)}… is connected. Switch accounts in your wallet to move that one.`));
const rows = [];
const nat = await nativeMovable();
if (nat.move > 0n) rows.push({ sym: SYM(), addr: ethers.ZeroAddress, dec: 18, bal: nat.move, note: `keeps ${fmt(nat.reserve)} ${SYM()} for gas` });
const toks = await migCandidates();
const bals = await Promise.all(toks.map((t) => new ethers.Contract(t.addr, ERC20, read).balanceOf(account).catch(() => 0n)));
toks.forEach((t, i) => { if (bals[i] > 0n) rows.push({ ...t, bal: bals[i] }); });
if (!rows.length) { box.append(el("li", "empty", `Nothing to move: this wallet holds no ${SYM()} above the gas reserve and none of the ${toks.length} tokens checked on ${cfg.chainName}.`)); return; }
for (const r of rows) {
const li = el("li"); li.append(el("span", "", r.sym), el("span", "amt", fmtU(r.bal, r.dec) + (r.note ? ` (${r.note})` : "")));
const b = el("button", "b dark", "Move"); b.type = "button"; b.onclick = () => busy(b, "Confirm in your wallet…", () => migMove(r, li)); li.append(b); box.append(li); r.li = li;
}
go.disabled = false;
go.onclick = () => busy(go, "Moving…", async () => { migRunning = true; try { for (const r of rows) if (!r.li.classList.contains("done")) await migMove(r, r.li); } finally { migRunning = false; } });
$("#migFine").textContent = `${rows.length} asset${rows.length === 1 ? "" : "s"} · one wallet confirmation each · to vault ${current.slice(0, 8)}…`;
}
async function migMove(r, li) {
needWallet(); needVault();
if (r.addr === ethers.ZeroAddress) {
const nat = await nativeMovable(); if (nat.move === 0n) throw oops(`Only the gas reserve is left in ${SYM()}.`);
const tx = await signer.sendTransaction({ to: current, value: nat.move }); log(`Moving ${fmt(nat.move)} ${SYM()} into the vault…`, { hash: tx.hash }); await tx.wait();
log(`Moved ${fmt(nat.move)} ${SYM()} into the vault.`, { hash: tx.hash });
} else {
const c = new ethers.Contract(r.addr, ERC20, signer), bal = await c.balanceOf(account);
if (bal === 0n) throw oops(`No ${r.sym} left in this wallet.`);
await canPay(80_000, `Moving ${r.sym}`);
const tx = await c.transfer(current, bal); log(`Moving ${fmtU(bal, r.dec)} ${r.sym} into the vault…`, { hash: tx.hash }); await tx.wait();
log(`Moved ${fmtU(bal, r.dec)} ${r.sym} into the vault.`, { hash: tx.hash });
}
li.classList.add("done"); li.querySelector("button").disabled = true; li.querySelector("button").textContent = "Moved";
openVault(current).catch(() => {});
}
let migRunning = false;
const migBusy = () => migRunning;
if (migrateFrom) requestAnimationFrame(() => $("#migPanel").scrollIntoView({ behavior: "smooth", block: "start" }));