// Gasless relayer for vault-key operations. The owner stores the relayer wallet's key in /studio (encrypted at rest, // same secret as the buyback wallet). The relayer pays gas only; it cannot change what it submits, because the vault // contract verifies the hash-based signature over the exact calls. Before sending anything it checks that the target is // a Hashfort vault (an EIP-1167 clone of the chain's official implementation) and simulates the call, so a request that // would revert costs nothing. Limits: per IP, per vault and per chain per day, plus a gas-price ceiling. import fs from "node:fs"; import path from "node:path"; import { ethers } from "ethers"; import { seal, unseal, dataDir } from "./burn.mjs"; const FILE = () => path.join(dataDir(), "relayer.json"); const read = () => { try { return JSON.parse(fs.readFileSync(FILE(), "utf8")); } catch { return { enabled: false, perDayPerChain: 25, perVaultPerDay: 5, wallet: null }; } }; const write = (v) => { const p = FILE(), tmp = p + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(v, null, 1), { mode: 0o600 }); fs.renameSync(tmp, p); }; const VAULT_ABI = ["function execute((address target,uint256 value,bytes data)[] calls, uint32 leafIndex, uint64 deadline, bytes32[67] sig, bytes32[] path) returns (bytes[])"]; const MAX_GWEI = { 1: 20, 56: 5, 137: 300 }; // chains not listed: 2 gwei let chains = {}; // chainId -> { rpc, implementations, explorer, name } export function configure(list) { chains = Object.fromEntries(list.map((c) => [c.chainId, c])); } const counts = new Map(); // key -> [timestamps] function bump(key, limit, windowMs) { const now = Date.now(), xs = (counts.get(key) || []).filter((t) => now - t < windowMs); if (xs.length >= limit) return false; xs.push(now); counts.set(key, xs); if (counts.size > 20000) counts.clear(); return true; } function wallet(chainId) { const c = read(); if (!c.wallet) return null; return new ethers.Wallet(unseal(c.wallet.sealed), new ethers.JsonRpcProvider(chains[chainId].rpc, chainId, { staticNetwork: true })); } const cloneCode = (impl) => ("0x363d3d373d3d3d363d73" + impl.slice(2) + "5af43d82803e903d91602b57fd5bf3").toLowerCase(); export function saveKey(pk) { let w; try { w = new ethers.Wallet(String(pk).trim()); } catch { throw new Error("That is not a valid private key."); } const c = read(); c.wallet = { address: w.address, sealed: seal(w.privateKey) }; write(c); return { address: w.address }; } export function removeKey() { const c = read(); c.wallet = null; c.enabled = false; write(c); return { ok: true }; } export function settings({ enabled, perDayPerChain, perVaultPerDay }) { const c = read(); if (enabled !== undefined) { if (enabled && !c.wallet) throw new Error("Save the relayer wallet key first."); c.enabled = !!enabled; } if (perDayPerChain !== undefined) c.perDayPerChain = Math.max(0, Math.min(500, Math.floor(+perDayPerChain || 0))); if (perVaultPerDay !== undefined) c.perVaultPerDay = Math.max(0, Math.min(50, Math.floor(+perVaultPerDay || 0))); write(c); return publicStatus(); } /** For the app: is gasless available on this chain right now. */ export async function publicStatus(chainId) { const c = read(), out = { enabled: !!c.enabled && !!c.wallet, address: c.wallet?.address || null }; if (chainId && chains[chainId] && out.enabled) { try { const b = await new ethers.JsonRpcProvider(chains[chainId].rpc, chainId, { staticNetwork: true }).getBalance(out.address); out.funded = b > ethers.parseEther("0.0002"); } catch { out.funded = false; } } return out; } /** For the studio: balances on every chain. */ export async function ownerStatus() { const c = read(), out = { enabled: !!c.enabled, perDayPerChain: c.perDayPerChain, perVaultPerDay: c.perVaultPerDay, address: c.wallet?.address || null, chains: [] }; if (out.address) out.chains = await Promise.all(Object.values(chains).map(async (ch) => { try { const b = await new ethers.JsonRpcProvider(ch.rpc, ch.chainId, { staticNetwork: true }).getBalance(out.address); return { chainId: ch.chainId, name: ch.name, balance: ethers.formatEther(b) }; } catch { return { chainId: ch.chainId, name: ch.name, balance: null }; } })); return out; } export async function relay(body, ip) { const c = read(); if (!c.enabled || !c.wallet) throw Object.assign(new Error("The relayer is off. Submit from your own wallet."), { status: 503 }); const chainId = Number(body.chainId), ch = chains[chainId]; if (!ch) throw Object.assign(new Error("Unsupported chain."), { status: 400 }); if (!ethers.isAddress(body.vault)) throw Object.assign(new Error("Bad vault address."), { status: 400 }); const vault = ethers.getAddress(body.vault); const calls = (body.calls || []).map((x) => [ethers.getAddress(x.target), BigInt(x.value), String(x.data)]); if (!calls.length || calls.length > 8 || !Array.isArray(body.sig) || body.sig.length !== 67 || !Array.isArray(body.path) || body.path.length > 16) throw Object.assign(new Error("Malformed request."), { status: 400 }); if (!bump("ip:" + ip, 10, 3600_000)) throw Object.assign(new Error("Too many relays from this address. Try again in an hour or use your own wallet."), { status: 429 }); const w = wallet(chainId), p = w.provider; // only Hashfort vaults: a minimal proxy of this chain's official implementation const code = (await p.getCode(vault)).toLowerCase(); if (!ch.implementations.some((i) => cloneCode(i) === code)) throw Object.assign(new Error("That address is not a Hashfort vault on this chain."), { status: 400 }); const fee = await p.getFeeData(), price = fee.maxFeePerGas ?? fee.gasPrice; if (price > ethers.parseUnits(String(MAX_GWEI[chainId] ?? 2), "gwei")) throw Object.assign(new Error("Gas is too expensive on this chain right now for the free relayer. Use your own wallet."), { status: 503 }); const v = new ethers.Contract(vault, VAULT_ABI, w), args = [calls, Number(body.leaf), BigInt(body.deadline), body.sig, body.path]; let gas; try { gas = await v.execute.estimateGas(...args); } // a call that would revert stops here and costs nothing catch (e) { throw Object.assign(new Error("The vault would refuse this: " + (e.shortMessage || e.message).slice(0, 160)), { status: 400 }); } if (gas > 600_000n) throw Object.assign(new Error("Too much gas for the free relayer. Use your own wallet."), { status: 400 }); if (!bump(`vault:${chainId}:${vault}`, c.perVaultPerDay, 86400_000)) throw Object.assign(new Error("This vault used its free relays for today."), { status: 429 }); if (!bump(`chain:${chainId}`, c.perDayPerChain, 86400_000)) throw Object.assign(new Error("The relayer's daily budget on this chain is used up. Use your own wallet."), { status: 429 }); const tx = await v.execute(...args, { gasLimit: (gas * 13n) / 10n }); return { hash: tx.hash, from: w.address }; }