// Transaction auditor and x402 payments. // // Auditor: before a vault-key batch is signed, every call is decoded and simulated with eth_call from the vault's own // address against the latest block, then fixed rules look for the things that drain vaults (a near-total outflow, a // brand-new recipient, unlimited approvals, a replaced daily key, a raised limit, an agent that may pay anyone). // The report lists every input it used (block, from, to, value, data), so anyone can re-run the same eth_calls and get // the same answer; its SHA-256 identifies it. An optional language-model summary is added on top, never instead. // // x402: paid endpoints answer 402 with a USDG price on Robinhood Chain. The caller pays with any USDG transfer to the // published address (a Hashfort agent pays through its vault's agentSpend, inside the limits the vault key set) and // retries with X-PAYMENT: base64 {"x402Version":1,"scheme":"exact-onchain","network":"eip155:4663","payload":{"txHash":"0x…"}}. // The server reads that transaction's receipt: success, a USDG Transfer to the address for at least the price, recent, // and never used before. Each transaction pays for one call. import fs from "node:fs"; import path from "node:path"; import { createHash, randomBytes } from "node:crypto"; import { ethers } from "ethers"; import { dataDir } from "./burn.mjs"; let ctx = { provider: () => null, implementations: () => [], tokenAddress: () => null, plans: () => null }; // set by server.mjs export function configure(c) { ctx = { ...ctx, ...c }; } // ---------------------------------------------------------------- auditor const VAULT = new ethers.Interface([ "function setDailyLimit(address token, uint256 limit)", "function setOwner(address newOwner)", "function rotate(bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight)", "function setGuardians(address[] guardians, uint8 threshold, uint32 delay)", "function cancelRecovery()", "function setAgent(address agent, uint64 expiry, bool anyTarget)", "function setAgentLimit(address agent, address token, uint256 limit)", "function setAgentTarget(address agent, address target, bool allowed)", "function revokeAgent(address agent)", "function setSentinel(address who, bool allowed)", "function freeze()", "function unfreeze()", "function owner() view returns (address)", "function dailyLimit(address) view returns (uint256)", "function frozen() view returns (bool)", "function guardians() view returns (address[])", "function agentLimit(address,address) view returns (uint256)", "function setPrimaryKey((address dataA, address dataB, bytes32 pkHash) key)", "function setRecoveryKey(bytes32 recoveryKey)", "function setKeyRecoveryDelay(uint32 delay)", ]); const ERC20 = new ethers.Interface([ "function transfer(address to, uint256 amount) returns (bool)", "function approve(address spender, uint256 amount) returns (bool)", "function transferFrom(address from, address to, uint256 amount) returns (bool)", "function increaseAllowance(address spender, uint256 added) returns (bool)", "function balanceOf(address) view returns (uint256)", "function symbol() view returns (string)", "function decimals() view returns (uint8)", ]); const NATIVE = { 56: "BNB", 137: "POL" }; const cloneCode = (impl) => ("0x363d3d373d3d3d363d73" + impl.slice(2) + "5af43d82803e903d91602b57fd5bf3").toLowerCase(); const fmt = (v, d) => { const s = ethers.formatUnits(v, d); return s.includes(".") ? s.replace(/(\.\d{0,6})\d*$/, "$1").replace(/\.?0+$/, "") : s; }; const canon = (o) => JSON.stringify(o, (k, v) => (typeof v === "bigint" ? v.toString() : v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((x) => [x, v[x]])) : v)); const sha = (s) => "0x" + createHash("sha256").update(s).digest("hex"); async function tokenInfo(p, addr, vault) { const t = new ethers.Contract(addr, ERC20, p); const [symbol, decimals, bal] = await Promise.all([t.symbol().catch(() => "token"), t.decimals().catch(() => 18n), t.balanceOf(vault).catch(() => null)]); return { symbol: String(symbol).slice(0, 16), decimals: Number(decimals), balance: bal }; } function revertText(e) { const data = e?.data || e?.info?.error?.data || e?.error?.data; if (typeof data === "string" && data.length >= 10) { for (const i of [VAULT, new ethers.Interface(["error OverLimit()", "error NotSelf()", "error BadConfig()", "error IsFrozen()", "error NotAgent()", "error TargetNotAllowed()", "error AgentExpired()"])]) { try { const p = i.parseError(data); if (p) return p.name; } catch {} } try { return ethers.AbiCoder.defaultAbiCoder().decode(["string"], "0x" + data.slice(10))[0]; } catch {} return data.slice(0, 10); } return (e?.shortMessage || e?.message || "reverted").slice(0, 120); } export async function audit({ chainId, vault, calls }) { chainId = Number(chainId); const p = ctx.provider(chainId); if (!p) throw Object.assign(new Error("Unsupported chain."), { status: 400 }); if (!ethers.isAddress(vault)) throw Object.assign(new Error("Bad vault address."), { status: 400 }); vault = ethers.getAddress(vault); if (!Array.isArray(calls) || !calls.length || calls.length > 8) throw Object.assign(new Error("Send 1 to 8 calls."), { status: 400 }); calls = calls.map((c) => ({ target: ethers.getAddress(c.target), value: BigInt(c.value || 0), data: /^0x([0-9a-fA-F]{2})*$/.test(c.data || "0x") ? String(c.data || "0x") : "0x" })); const block = await p.getBlock("latest"), tag = block.number; const code = (await p.getCode(vault, tag)).toLowerCase(); const isVault = ctx.implementations(chainId).some((i) => cloneCode(i) === code); const v = new ethers.Contract(vault, VAULT, p); const [ethBal, owner, frozen, guardians] = await Promise.all([p.getBalance(vault, tag), v.owner().catch(() => null), v.frozen().catch(() => null), v.guardians().catch(() => [])]); const sym = NATIVE[chainId] || "ETH", warnings = [], out = []; const warn = (level, code, text, call) => warnings.push({ level, code, text, ...(call !== undefined ? { call } : {}) }); if (!isVault) warn("high", "NOT_A_VAULT", "This address is not a Hashfort vault on this chain."); const outflow = new Map(); // asset -> total leaving the vault in this batch for (const [i, c] of calls.entries()) { const row = { i, target: c.target, value: c.value.toString(), data: c.data, kind: "call", summary: "" }; const addOut = (asset, amount, symbol, decimals, balance) => { const o = outflow.get(asset) || { asset, amount: 0n, symbol, decimals, balance }; o.amount += amount; outflow.set(asset, o); row.outflow = { asset, amount: amount.toString(), symbol, decimals }; }; if (c.value > 0n) addOut(ethers.ZeroAddress, c.value, sym, 18, ethBal); if (c.target === vault) { let f; try { f = VAULT.parseTransaction({ data: c.data }); } catch {} row.kind = "settings"; if (!f) { row.summary = "Unknown call to the vault itself"; warn("high", "UNKNOWN_SELF_CALL", "A call to the vault that this checker cannot read.", i); } else { const a = f.args; switch (f.name) { case "setDailyLimit": { const old = await v.dailyLimit(a[0]).catch(() => 0n); const t = a[0] === ethers.ZeroAddress ? { symbol: sym, decimals: 18, balance: ethBal } : await tokenInfo(p, a[0], vault); row.summary = `Daily-key limit for ${t.symbol}: ${fmt(old, t.decimals)} -> ${fmt(a[1], t.decimals)} per day`; if (a[1] > old * 2n && a[1] > 0n) warn("medium", "LIMIT_RAISE", `The daily key will be able to spend ${fmt(a[1], t.decimals)} ${t.symbol} a day, more than double today's limit. If the daily key leaks, that is what can go per day.`, i); if (t.balance != null && t.balance > 0n && a[1] * 2n >= t.balance) warn("medium", "LIMIT_NEAR_BALANCE", `The new limit is at least half of the vault's ${t.symbol} balance.`, i); break; } case "setOwner": row.summary = `Replace the daily key with ${a[0]}`; warn("high", "OWNER_CHANGE", `The daily key becomes ${a[0]}. That wallet can spend up to the daily limits.`, i); break; case "rotate": row.summary = `Rotate the vault key to root ${a[0].slice(0, 12)}…`; warn("medium", "KEY_ROTATION", "The current vault key stops working. Make sure the new Recovery Kit is saved and opens.", i); break; case "setGuardians": row.summary = `Guardians: ${a[1]} of ${a[0].length}, ${Math.round(Number(a[2]) / 3600)} h wait`; if (Number(a[1]) === 1 && a[0].length > 0) warn("medium", "SINGLE_GUARDIAN", "One guardian alone can start replacing your keys. The vault key can still cancel during the wait.", i); break; case "cancelRecovery": row.summary = "Cancel every pending guardian recovery"; break; case "setAgent": { const days = (Number(a[1]) - block.timestamp) / 86400; row.summary = `Agent ${a[0].slice(0, 10)}… active for ${days.toFixed(1)} days, ${a[2] ? "may pay anyone" : "allowed addresses only"}`; if (a[2]) warn("medium", "AGENT_ANY_TARGET", "This agent may pay any address (still within its daily limits).", i); if (days > 90) warn("info", "AGENT_LONG_EXPIRY", "The agent key stays valid for more than 90 days.", i); break; } case "setAgentLimit": { const t = a[1] === ethers.ZeroAddress ? { symbol: sym, decimals: 18, balance: ethBal } : await tokenInfo(p, a[1], vault); row.summary = `Agent ${a[0].slice(0, 10)}… may spend ${fmt(a[2], t.decimals)} ${t.symbol} a day`; if (t.balance != null && t.balance > 0n && a[2] * 4n >= t.balance) warn("medium", "AGENT_LIMIT_HIGH", `The agent's daily limit is at least a quarter of the vault's ${t.symbol} balance.`, i); break; } case "setAgentTarget": row.summary = `Agent ${a[0].slice(0, 10)}… ${a[2] ? "may pay" : "may no longer pay"} ${a[1]}`; break; case "revokeAgent": row.summary = `Revoke agent ${a[0]}`; break; case "setSentinel": row.summary = `${a[1] ? "Add" : "Remove"} sentinel ${a[0]} (it can only freeze and revoke agents)`; break; case "freeze": row.summary = "Freeze daily-key and agent spending"; break; case "setPrimaryKey": row.summary = `Replace the ML-DSA-65 primary key (new key hash ${a[0].pkHash.slice(0, 12)}…)`; warn("medium", "KEY_ROTATION", "The current primary key stops working. Make sure the new Primary Kit is saved and opens.", i); break; case "setRecoveryKey": row.summary = `Replace the SLH-DSA recovery key with ${a[0].slice(0, 14)}…`; warn("medium", "RECOVERY_KEY_CHANGE", "Whoever holds the new recovery key can start replacing your primary key (with a delay you can cancel).", i); break; case "setKeyRecoveryDelay": row.summary = `Recovery-key delay: ${Math.round(Number(a[0]) / 3600)} h`; break; case "unfreeze": row.summary = "Unfreeze daily-key and agent spending"; if (frozen) warn("info", "UNFREEZE", "Make sure whatever triggered the freeze is understood first.", i); break; default: row.summary = f.name; } } } else if (c.data === "0x") { row.kind = "transfer"; row.summary = `Send ${fmt(c.value, 18)} ${sym} to ${c.target}`; } else { let f; try { f = ERC20.parseTransaction({ data: c.data }); } catch {} if (f && (f.name === "transfer" || f.name === "transferFrom")) { const t = await tokenInfo(p, c.target, vault), to = f.name === "transfer" ? f.args[0] : f.args[1], amount = f.name === "transfer" ? f.args[1] : f.args[2]; row.kind = "token-transfer"; row.summary = `Send ${fmt(amount, t.decimals)} ${t.symbol} to ${to}`; row.recipient = to; if (f.name === "transfer") addOut(c.target, amount, t.symbol, t.decimals, t.balance); } else if (f && (f.name === "approve" || f.name === "increaseAllowance")) { const t = await tokenInfo(p, c.target, vault), [spender, amount] = f.args; row.kind = "approval"; row.summary = `Allow ${spender} to take ${amount >= 2n ** 128n ? "unlimited" : fmt(amount, t.decimals)} ${t.symbol}`; if (amount >= 2n ** 128n) warn("high", "UNLIMITED_APPROVAL", `Unlimited ${t.symbol} approval to ${spender}: that contract could take every ${t.symbol} the vault holds, now or later.`, i); if ((await p.getCode(spender, tag)) === "0x") warn("high", "APPROVAL_TO_WALLET", `The approval goes to a plain wallet (${spender}), not a contract. Phishing approvals look like this.`, i); } else { row.kind = "contract-call"; row.summary = `Call ${c.data.slice(0, 10)} on ${c.target}`; warn("medium", "UNKNOWN_CALL", `A contract call this checker cannot decode (${c.data.slice(0, 10)} on ${c.target}). Only sign it if you know exactly what it does.`, i); } } const recipient = row.kind === "transfer" ? c.target : row.recipient; if (recipient && recipient !== vault) { const [n, b, rc] = await Promise.all([p.getTransactionCount(recipient, tag), p.getBalance(recipient, tag), p.getCode(recipient, tag)]); if (rc === "0x" && n === 0 && b === 0n) warn("medium", "FRESH_RECIPIENT", `${recipient} has never been used on this chain. Check every character: poisoned look-alike addresses are a common way to lose funds.`, i); if (owner && recipient.toLowerCase() === owner.toLowerCase()) row.note = "to this vault's daily key"; } // simulate this call exactly as the vault would make it try { const gas = await p.estimateGas({ from: vault, to: c.target, value: c.value, data: c.data, blockTag: tag }); row.sim = { ok: true, gas: gas.toString() }; } catch (e) { row.sim = { ok: false, revert: revertText(e) }; warn("high", "REVERTS", `Call ${i + 1} fails in simulation (${row.sim.revert}), so the whole batch would revert and the one-time key would be spent for nothing.`, i); } out.push(row); } for (const o of outflow.values()) { if (o.balance == null || o.balance === 0n) continue; const pct = Number((o.amount * 10000n) / o.balance) / 100; o.share = pct; if (pct >= 95) warn("high", "NEAR_TOTAL_OUTFLOW", `This batch moves ${pct.toFixed(1)}% of the vault's ${o.symbol}.`); else if (pct >= 50) warn("medium", "LARGE_OUTFLOW", `This batch moves ${pct.toFixed(1)}% of the vault's ${o.symbol}.`); } if (calls.length > 1) warn("info", "SEQUENTIAL", "Calls were simulated one at a time against the same block; a call that depends on an earlier one in this batch can show a false failure."); const level = warnings.some((w) => w.level === "high") ? "stop" : warnings.some((w) => w.level === "medium") ? "review" : "ok"; const report = { version: 1, chainId, vault, block: block.number, blockHash: block.hash, blockTime: block.timestamp, simulatedFrom: vault, vaultState: { isHashfortVault: isVault, owner, frozen, guardians: guardians.length, nativeBalance: ethBal.toString() }, calls: out, outflows: [...outflow.values()].map((o) => ({ asset: o.asset, symbol: o.symbol, amount: o.amount.toString(), decimals: o.decimals, share: o.share ?? null })), warnings, verdict: level, method: "eth_estimateGas from the vault for each call at the block above, then fixed rules (services.mjs on /code/)", }; report.hash = sha(canon(report)); return report; } // ---------------------------------------------------------------- x402 const USDG = { 4663: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" }; if (process.env.HF_LOCAL_USDG) USDG[31337] = process.env.HF_LOCAL_USDG; export const usdgOf = (chainId) => USDG[chainId] || null; const X = () => path.join(dataDir(), "x402.json"); const xr = () => { let c; try { c = JSON.parse(fs.readFileSync(X(), "utf8")); } catch { c = { payTo: null, chainId: 4663, prices: { exposure: 50000, audit: 20000 }, used: {} }; } c.holderThreshold ??= "1000000"; return c; }; const xw = (v) => { const p = X(), tmp = p + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(v, null, 1), { mode: 0o600 }); fs.renameSync(tmp, p); }; export const SERVICES = { exposure: { path: "/x402/exposure", description: "Quantum-exposure report for up to 20 addresses on every supported chain plus Bitcoin" }, audit: { path: "/x402/audit", description: "Simulated audit of a vault batch, with a plain-language summary when the AI is on" }, }; export function x402Config({ payTo, prices, chainId, holderThreshold } = {}) { const c = xr(); if (holderThreshold !== undefined) { const n = String(holderThreshold).replace(/[,_\s]/g, ""); if (!/^\d+(\.\d+)?$/.test(n)) throw new Error("Holder threshold must be a number of tokens."); c.holderThreshold = n; } if (payTo !== undefined) { if (payTo && !ethers.isAddress(payTo)) throw new Error("Not an address."); c.payTo = payTo ? ethers.getAddress(payTo) : null; } if (chainId !== undefined && USDG[Number(chainId)]) c.chainId = Number(chainId); for (const k of Object.keys(SERVICES)) if (prices?.[k] !== undefined) c.prices[k] = Math.max(0, Math.min(100_000_000, Math.floor(+prices[k] || 0))); xw(c); return x402Status(); } export function x402Status() { const c = xr(); return { live: !!c.payTo, payTo: c.payTo, network: `eip155:${c.chainId}`, chainId: c.chainId, asset: USDG[c.chainId], symbol: "USDG", decimals: 6, services: Object.entries(SERVICES).map(([k, s]) => ({ id: k, ...s, price: String(c.prices[k] ?? 0), priceUsd: (Number(c.prices[k] ?? 0) / 1e6).toFixed(2) })), paidCalls: Object.keys(c.used || {}).length, holders: { token: ctx.tokenAddress() || null, threshold: c.holderThreshold, benefit: `Wallets or vaults holding at least ${Number(c.holderThreshold).toLocaleString("en-US")} HASHFORT use these services free: no x402 payment.` } }; } // ---------------------------------------------------------------- token utility: holders use the services free // The balance is read from the HASHFORT token contract on Robinhood Chain at the moment of the request. const holderCache = new Map(); export async function holderStatus(address) { const c = xr(), token = ctx.tokenAddress(); if (!token || !ethers.isAddress(address)) return { holder: false, balance: "0", threshold: c.holderThreshold, token }; address = ethers.getAddress(address); const hit = holderCache.get(address); if (hit && Date.now() - hit.at < 60_000 && hit.threshold === c.holderThreshold) return hit.v; const t = new ethers.Contract(token, ["function balanceOf(address) view returns (uint256)", "function decimals() view returns (uint8)"], ctx.provider(c.chainId)); const [bal, dec] = await Promise.all([t.balanceOf(address), t.decimals().catch(() => 18n)]); const v = { address, token, balance: ethers.formatUnits(bal, dec), threshold: c.holderThreshold, holder: bal >= ethers.parseUnits(c.holderThreshold, dec) }; holderCache.set(address, { at: Date.now(), threshold: c.holderThreshold, v }); if (holderCache.size > 5000) holderCache.clear(); return v; } export const holderMessage = (address, issued) => `Hashfort holder access\nAddress: ${address}\nIssued: ${issued}\nThis signature only proves you hold HASHFORT. It cannot move funds.`; const INTERNAL = randomBytes(24).toString("hex"); // for this server's own agents, never sent out export const internalHolderHeader = (address) => `${INTERNAL}:${ethers.getAddress(address)}`; export function offer(service, resource) { const c = xr(), s = SERVICES[service]; return { x402Version: 1, error: "X-PAYMENT header is required", accepts: [{ scheme: "exact-onchain", network: `eip155:${c.chainId}`, asset: USDG[c.chainId], payTo: c.payTo, maxAmountRequired: String(c.prices[service]), resource, description: s.description, mimeType: "application/json", maxTimeoutSeconds: 3600, extra: { name: "Global Dollar", symbol: "USDG", decimals: 6, holderAccess: `Free for wallets holding at least ${Number(c.holderThreshold).toLocaleString("en-US")} HASHFORT: send X-HOLDER: base64 of {address, issued, sig}, where sig is a personal_sign of the holder message (GET /api/holder/message?address=).`, howToPay: "Transfer at least maxAmountRequired of the asset to payTo on this network (any wallet, or a Hashfort agent via agentSpend), then repeat the request with X-PAYMENT: base64 of {x402Version:1, scheme:'exact-onchain', network, payload:{txHash}}. One transaction pays for one call." } }] }; } const TRANSFER = ethers.id("Transfer(address,address,uint256)"); const pending = new Set(); /** Returns null after writing a 402, or { txHash, from, amount } once the payment checks out. */ export async function gate(req, res, service, resource) { const c = xr(); if (!c.payTo) { res.writeHead(503, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "Paid services are not switched on yet." })); return null; } // holders skip payment: this server's agents (internal header), or anyone with a signed holder proof const ih = String(req.headers["x-hashfort-internal-holder"] || ""); if (ih.startsWith(INTERNAL + ":")) { const who = ih.slice(INTERNAL.length + 1); if ((await tierOf([who])).tier >= 1) { res.setHeader("x-holder-access", who); return { holder: true, from: who, txHash: null }; } } const hp = req.headers["x-holder"]; if (hp) { let a; try { a = JSON.parse(Buffer.from(String(hp), "base64").toString("utf8")); } catch {} if (a?.address && a?.sig && Math.abs(Date.now() / 1000 - Number(a.issued)) < 3600) { let who = null; try { who = ethers.verifyMessage(holderMessage(ethers.getAddress(a.address), a.issued), a.sig); } catch {} if (who && who.toLowerCase() === String(a.address).toLowerCase()) { const st = await holderStatus(who), t = await tierOf([who]); if (t.tier >= 1) { res.setHeader("x-holder-access", who); return { holder: true, from: who, txHash: null }; } throw Object.assign(new Error(`This wallet holds ${st.balance} HASHFORT and has no Pro plan; free access needs ${st.threshold} HASHFORT or a Pro plan.`), { status: 402 }); } } throw Object.assign(new Error("Bad X-HOLDER proof: sign the holder message with the wallet, within the last hour."), { status: 400 }); } const h = req.headers["x-payment"]; if (!h) { res.writeHead(402, { "content-type": "application/json", "cache-control": "no-store" }); res.end(JSON.stringify(offer(service, resource))); return null; } const fail = (code, msg) => { throw Object.assign(new Error(msg), { status: code }); }; let pl; try { pl = JSON.parse(Buffer.from(String(h), "base64").toString("utf8")); } catch { fail(400, "X-PAYMENT must be base64 JSON."); } const txHash = String(pl?.payload?.txHash || "").toLowerCase(); if (pl?.scheme !== "exact-onchain" || pl?.network !== `eip155:${c.chainId}` || !/^0x[0-9a-f]{64}$/.test(txHash)) fail(400, "Unsupported payment: use scheme exact-onchain on " + `eip155:${c.chainId}` + " with payload.txHash."); if (c.used[txHash] || pending.has(txHash)) fail(402, "That payment transaction was already used for a call."); pending.add(txHash); try { const p = ctx.provider(c.chainId); const rc = await p.getTransactionReceipt(txHash); if (!rc) fail(402, "Payment transaction not found yet. Wait for it to be mined and retry."); if (rc.status !== 1) fail(402, "The payment transaction failed."); const blk = await p.getBlock(rc.blockNumber); if (Math.floor(Date.now() / 1000) - blk.timestamp > 3600) fail(402, "That payment is older than an hour."); const price = BigInt(c.prices[service]), asset = USDG[c.chainId].toLowerCase(), to = ethers.zeroPadValue(c.payTo, 32).toLowerCase(); const log = rc.logs.find((l) => l.address.toLowerCase() === asset && l.topics[0] === TRANSFER && l.topics[2]?.toLowerCase() === to && BigInt(l.data) >= price); if (!log) fail(402, `No USDG transfer of at least ${Number(price) / 1e6} to ${c.payTo} in that transaction.`); const paid = { txHash, from: ethers.getAddress("0x" + log.topics[1].slice(26)), amount: BigInt(log.data).toString(), service, at: new Date().toISOString() }; const now = xr(); now.used[txHash] = paid; const keys = Object.keys(now.used); if (keys.length > 50000) for (const k of keys.slice(0, 10000)) delete now.used[k]; xw(now); res.setHeader("x-payment-response", Buffer.from(JSON.stringify({ success: true, txHash, network: `eip155:${c.chainId}`, payer: paid.from })).toString("base64")); return paid; } finally { pending.delete(txHash); } } // ---------------------------------------------------------------- plans: Free / Pro / Team // Tier of a vault = the best of: a plan bought in HashfortPlans for the vault or its daily key, and HASHFORT holder // status (holders get Pro). Read from the chain, cached for a minute. export const TIERS = ["Free", "Pro", "Team"]; export const LIMITS = { agents: [1, 5, 20], pushDevices: [0, 3, 10] }; const tierCache = new Map(); export async function tierOf(addresses) { const list = [...new Set(addresses.filter((a) => a && ethers.isAddress(a)).map((a) => ethers.getAddress(a)))]; const key = list.join(","), hit = tierCache.get(key); if (hit && Date.now() - hit.at < 60_000) return hit.v; let best = { tier: 0, name: "Free", source: null, until: 0, account: null }; const pl = ctx.plans(); for (const a of list) { if (pl) { try { const c = new ethers.Contract(pl.address, ["function planOf(address) view returns (uint8, uint64)"], ctx.provider(pl.chainId)); const [plan, until] = await c.planOf(a); const viaHolding = BigInt(until) === 2n ** 64n - 1n; // planOf: Pro while the account holds the HASHFORT threshold if (Number(plan) > best.tier) best = { tier: Number(plan), name: TIERS[Number(plan)], source: viaHolding ? "holder" : "plan", until: viaHolding ? 0 : Number(until), account: a }; } catch {} } if (best.tier < 1) { const h = await holderStatus(a).catch(() => null); if (h?.holder) best = { tier: 1, name: "Pro", source: "holder", until: 0, account: a, balance: h.balance }; } } tierCache.set(key, { at: Date.now(), v: best }); if (tierCache.size > 5000) tierCache.clear(); return best; } export function plansInfo() { const pl = ctx.plans(), x = x402Status(); const hold = pl?.holderThreshold ? (BigInt(pl.holderThreshold) / 10n ** 18n).toString() : x.holders.threshold; return { holderOnChain: !!pl?.holderThreshold, contract: pl?.address || null, chainId: pl?.chainId || 4663, token: pl?.token || USDG[4663], symbol: "USDG", treasury: pl?.treasury || null, prices: { pro: pl?.proPrice || "9000000", team: pl?.teamPrice || "49000000" }, periodDays: 30, holderThreshold: hold, tiers: [ { id: 0, name: "Free", price: "0", features: ["Post-quantum vaults (v3 and Standard)", "Exposure scanner and the rule-based transaction check", "1 agent per vault", "Sentinel alerts in the app", "Paid services at x402 prices"] }, { id: 1, name: "Pro", price: pl?.proPrice || "9000000", orHold: hold, features: ["Everything in Free", "5 agents per vault", "AI summaries in the transaction check and AI tasks for agents", "Paid services free (exposure reports, audits)", "Sentinel push alerts on up to 3 devices"] }, { id: 2, name: "Team", price: pl?.teamPrice || "49000000", features: ["Everything in Pro", "20 agents per vault", "Team dashboard: every vault your wallet owns, at a glance", "Sentinel push alerts on up to 10 devices"] }, ] }; } // ---------------------------------------------------------------- proofs anyone can re-run // 1. A real v3 withdrawal: decode its calldata, recompute the digest it signed, and call the live ML-DSA-65 verifier // with the exact signature from the transaction (true), then with one byte flipped (false). // 2. A fresh key, no funds: sign in software and call the live verifiers, using eth_call state overrides to place a // new key's data contracts at throwaway addresses for the duration of the call (nothing is written to the chain). const V3 = new ethers.Interface([ "function execute((address target,uint256 value,bytes data)[] calls, uint64 deadline, bytes sig)", "function primary() view returns (address dataA, address dataB, bytes32 pkHash)", "function policyVersion() view returns (uint32)", "function mldsa() view returns (address)", "function slhdsa() view returns (address)", "event Executed(uint64 indexed nonce, bytes32 digest)", ]); const VERIFY_ML = new ethers.Interface(["function verify(bytes m, bytes ctx, bytes sig, address dataA, address dataB) view returns (bool)"]); const VERIFY_SLH = new ethers.Interface(["function verify(bytes m, bytes ctx, bytes sig, bytes32 pk) view returns (bool)"]); const OP_CTX = ethers.toUtf8Bytes("HASHFORT_V3_OP"); async function rawCall(p, to, data, overrides) { const params = [{ to, data, gas: "0x2faf080" }, "latest"]; if (overrides) params.push(overrides); return p.send("eth_call", params); } export async function proofTx(hash) { if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) throw Object.assign(new Error("Give a transaction hash (0x + 64 hex)."), { status: 400 }); const p = ctx.provider(4663); const [tx, rc] = await Promise.all([p.getTransaction(hash), p.getTransactionReceipt(hash)]); if (!tx || !rc) throw Object.assign(new Error("Transaction not found on Robinhood Chain."), { status: 404 }); let call; try { call = V3.parseTransaction({ data: tx.data }); } catch {} if (!call || call.name !== "execute") throw Object.assign(new Error("That transaction is not a v3 vault execute()."), { status: 400 }); const vault = ethers.getAddress(tx.to), v = new ethers.Contract(vault, V3, p); const ev = rc.logs.filter((l) => l.address.toLowerCase() === vault.toLowerCase()).map((l) => { try { return V3.parseLog(l); } catch { return null; } }).find((e) => e?.name === "Executed"); const [primary, verifier, pol] = await Promise.all([v.primary(), v.mldsa(), v.policyVersion()]); const calls = call.args.calls.map((c) => [c.target, c.value, c.data]), deadline = call.args.deadline, sig = ethers.getBytes(call.args.sig); const nonce = ev ? ev.args.nonce : null, digest = ev ? ev.args.digest : null; let recomputed = null, policyVersionAtSigning = null; for (let pv = Number(pol); pv >= 0 && nonce !== null; pv--) { // the policy version at signing is at most today's const d = ethers.keccak256(ethers.AbiCoder.defaultAbiCoder().encode(["bytes32", "uint256", "address", "uint32", "uint64", "uint64", "bytes32"], [ethers.id("HASHFORT_V3_OP"), 4663, vault, pv, nonce, deadline, ethers.keccak256(ethers.AbiCoder.defaultAbiCoder().encode(["(address,uint256,bytes)[]"], [calls]))])); if (d === digest) { recomputed = d; policyVersionAtSigning = pv; break; } } const data = VERIFY_ML.encodeFunctionData("verify", [digest, OP_CTX, sig, primary.dataA, primary.dataB]); const ok = VERIFY_ML.decodeFunctionResult("verify", await rawCall(p, verifier, data))[0]; const bad = sig.slice(); bad[1000] ^= 1; const tampered = VERIFY_ML.decodeFunctionResult("verify", await rawCall(p, verifier, VERIFY_ML.encodeFunctionData("verify", [digest, OP_CTX, bad, primary.dataA, primary.dataB])))[0]; return { transaction: hash, status: rc.status === 1 ? "success" : "failed", block: rc.blockNumber, gasUsed: rc.gasUsed.toString(), vault, decoded: { function: "execute(calls, deadline, sig)", calls: calls.map(([t, val, d]) => ({ target: t, value: val.toString(), data: d })), deadline: deadline.toString(), signatureBytes: sig.length, signatureSha256: ethers.sha256(sig) }, executedEvent: { nonce: nonce?.toString() ?? null, digest }, digestCheck: { recomputedFromCalldata: recomputed, matchesEvent: recomputed !== null, policyVersionAtSigning, formula: "keccak256(abi.encode(keccak256('HASHFORT_V3_OP'), chainid, vault, policyVersion, nonce, deadline, keccak256(abi.encode(calls))))" }, primaryKey: { dataA: primary.dataA, dataB: primary.dataB, pkHash: primary.pkHash }, verifier, context: "HASHFORT_V3_OP", results: { signatureFromThisTransaction: ok, sameSignatureWithOneByteFlipped: tampered }, reproduce: { method: "eth_call", to: verifier, data, block: "latest", note: "MLDSA65Verifier is stateless and the key data contracts are immutable, so this call gives the same answer at any block." }, }; } let pq = null; async function libs() { if (!pq) { const [ml, slh, sdk] = await Promise.all([import("@noble/post-quantum/ml-dsa.js"), import("@noble/post-quantum/slh-dsa.js"), import("./sdk/mldsa65.mjs")]); pq = { ml: ml.ml_dsa65, slh: slh.slh_dsa_sha2_128s, pre: sdk.precompute }; } return pq; } export async function proofDemo({ verifierMl, verifierSlh }) { const { ml, slh, pre } = await libs(), p = ctx.provider(4663); const msg = ethers.randomBytes(32), k = ml.keygen(ethers.randomBytes(32)), { A, B } = pre(k.publicKey); const sig = ml.sign(msg, k.secretKey, { context: OP_CTX }); const a1 = ethers.hexlify(ethers.randomBytes(20)), a2 = ethers.hexlify(ethers.randomBytes(20)); const over = { [a1]: { code: "0x00" + Buffer.from(A).toString("hex") }, [a2]: { code: "0x00" + Buffer.from(B).toString("hex") } }; const mlOk = VERIFY_ML.decodeFunctionResult("verify", await rawCall(p, verifierMl, VERIFY_ML.encodeFunctionData("verify", [msg, OP_CTX, sig, a1, a2]), over))[0]; const bad = sig.slice(); bad[2000] ^= 1; const mlBad = VERIFY_ML.decodeFunctionResult("verify", await rawCall(p, verifierMl, VERIFY_ML.encodeFunctionData("verify", [msg, OP_CTX, bad, a1, a2]), over))[0]; const rctx = ethers.toUtf8Bytes("HASHFORT_V3_RECOVERY"), sk = slh.keygen(ethers.randomBytes(48)), ssig = slh.sign(msg, sk.secretKey, { context: rctx }); const slhOk = VERIFY_SLH.decodeFunctionResult("verify", await rawCall(p, verifierSlh, VERIFY_SLH.encodeFunctionData("verify", [msg, rctx, ssig, ethers.hexlify(sk.publicKey)])))[0]; const sbad = ssig.slice(); sbad[3000] ^= 1; const slhBad = VERIFY_SLH.decodeFunctionResult("verify", await rawCall(p, verifierSlh, VERIFY_SLH.encodeFunctionData("verify", [msg, rctx, sbad, ethers.hexlify(sk.publicKey)])))[0]; return { at: new Date().toISOString(), chain: "Robinhood Chain (4663)", message: ethers.hexlify(msg), mldsa65: { verifier: verifierMl, publicKeyHash: ethers.keccak256(k.publicKey), signatureBytes: sig.length, valid: mlOk, oneByteFlipped: mlBad, how: "A brand-new ML-DSA-65 key signs a random message. The live verifier checks it via eth_call; the key's precomputed data is supplied with eth_call state overrides at throwaway addresses, so nothing is written on chain." }, slhdsa128s: { verifier: verifierSlh, publicKey: ethers.hexlify(sk.publicKey), signatureBytes: ssig.length, valid: slhOk, oneByteFlipped: slhBad }, }; }