// The scoped relayer, adapted from idle/relayer/. Elysium takes its transactions through an inbox on HyperEVM, // and the public RPC does not carry a user's transaction there. A wallet can use POST /rpc as its Elysium // connection: reads are forwarded, and exactly one kind of transaction is carried, on two tokens: // // USDC.transfer(TREASURY_ADDRESS, amount) no HYPE attached, call data exactly that call // EQNVDA.transfer(TREASURY_ADDRESS, amount) the same, on EQX's tokenized Nvidia share // // which is how credits are bought. When the credits contract (IdleCredits) is configured, it also carries // what a wallet needs to use that contract, and nothing more: // // USDC.approve(credits, amount), EQNVDA.approve(credits, amount) // credits.deposit(token, amount), credits.requestWithdrawal(token, amount), // credits.cancelWithdrawal(token), credits.withdraw(token) token being USDC or EQNVDA // // Everything else is refused before anything is run or posted. Nothing is posted unless a gas account // (RELAYER_KEY) is configured. import { Interface, Transaction, getAddress } from "ethers"; const erc20 = new Interface(["function transfer(address to, uint256 value) returns (bool)"]); const erc20Approve = new Interface(["function approve(address spender, uint256 value) returns (bool)"]); const creditsAbi = new Interface([ "function deposit(address token, uint256 amount)", "function requestWithdrawal(address token, uint256 amount)", "function cancelWithdrawal(address token)", "function withdraw(address token)", ]); // Decodes call data against an interface, and only accepts it if encoding it again gives the same bytes: // nothing appended, nothing loosely encoded. function exact(iface, tx) { try { const parsed = iface.parseTransaction({ data: tx.data, value: tx.value }); return parsed && iface.encodeFunctionData(parsed.fragment, parsed.args) === tx.data.toLowerCase() ? parsed : null; } catch { return null; } } const refuse = (code, reason) => ({ ok: false, code, reason }); const same = (a, b) => !!a && !!b && getAddress(a) === getAddress(b); /** * @param {string} raw the signed transaction, 0x-prefixed * @param {{chainId:number, usdc:string, eqnvda?:string|null, treasury:string|null, credits?:string|null, maxGas?:bigint, maxFeePerGas?:bigint}} cfg * @returns {{ok:true, tx:Transaction, from:string, hash:string, call:string, token:"USDC"|"EQNVDA", amount:bigint} | {ok:false, code:string, reason:string}} */ export function checkTx(raw, cfg) { let tx; try { tx = Transaction.from(raw); } catch { return refuse("malformed", "not a valid signed transaction"); } if (!tx.isSigned() || !tx.from) return refuse("unsigned", "the transaction carries no valid signature"); if (tx.chainId !== BigInt(cfg.chainId)) return refuse("chain", `signed for chain ${tx.chainId}, expected ${cfg.chainId}`); if (tx.type !== 0 && tx.type !== 2) return refuse("type", "only legacy and EIP-1559 transactions are carried"); if (!tx.to) return refuse("scope", "contract creation is not carried"); if (tx.gasLimit > (cfg.maxGas ?? (cfg.credits ? 300_000n : 200_000n))) return refuse("gas", "gas limit above what a token transfer ever needs"); if ((tx.maxFeePerGas ?? tx.gasPrice ?? 0n) > (cfg.maxFeePerGas ?? 500_000_000_000n)) return refuse("fee", "fee cap unreasonably high"); const symbolOf = (a) => (same(a, cfg.usdc) ? "USDC" : cfg.eqnvda && same(a, cfg.eqnvda) ? "EQNVDA" : null); // A call to the credits contract: one of its four user functions, on one of its two tokens. if (cfg.credits && same(tx.to, cfg.credits)) { if (tx.value !== 0n) return refuse("scope", "the credits contract takes no HYPE"); const call = exact(creditsAbi, tx); if (!call) return refuse("scope", "only deposit, requestWithdrawal, cancelWithdrawal and withdraw are carried on the credits contract"); const sym = symbolOf(call.args.token); if (!sym) return refuse("scope", "the credits contract only takes " + carried(cfg).join(" and ")); const amount = call.args.amount ?? 0n; if (call.fragment.inputs.length === 2 && amount <= 0n) return refuse("scope", "an amount of zero is not carried"); return { ok: true, tx, from: tx.from, hash: tx.hash, call: call.name, token: sym, amount }; } const token = symbolOf(tx.to); if (!token) return refuse("scope", `this relayer only carries ${carried(cfg).join(" and ")} transfers to the Idle treasury`); if (tx.value !== 0n) return refuse("scope", "a top-up carries no HYPE"); // An allowance for the credits contract, so that deposit() can pull the tokens. No other spender. if (cfg.credits) { const approval = exact(erc20Approve, tx); if (approval) { if (!same(approval.args.spender, cfg.credits)) return refuse("scope", "an approval must name the Idle credits contract as spender"); return { ok: true, tx, from: tx.from, hash: tx.hash, call: "approve", token, amount: approval.args.value }; } } if (!cfg.treasury) return refuse("not-open", "no treasury is configured, nothing was sent"); let parsed = null; try { parsed = erc20.parseTransaction({ data: tx.data, value: tx.value }); } catch { parsed = null; } // The call data must be exactly one transfer: nothing appended, nothing loosely encoded. if (!parsed || erc20.encodeFunctionData(parsed.fragment, parsed.args) !== tx.data.toLowerCase()) return refuse("scope", "only transfer(treasury, amount) is carried on " + token); if (!same(parsed.args.to, cfg.treasury)) return refuse("scope", "the transfer must name the Idle treasury as recipient"); if (parsed.args.value <= 0n) return refuse("scope", "a transfer of zero is not carried"); return { ok: true, tx, from: tx.from, hash: tx.hash, call: "transfer", token, amount: parsed.args.value }; } /** The tokens this configuration carries, by symbol. */ export const carried = (cfg) => (cfg.eqnvda ? ["USDC", "EQNVDA"] : ["USDC"]); /** Every call this configuration carries, as text for /v1/health. */ export const carries = (cfg) => [ ...carried(cfg).map((t) => t + ".transfer(treasury, amount)"), ...(cfg.credits ? [...carried(cfg).map((t) => t + ".approve(credits, amount)"), "credits.deposit(token, amount)", "credits.requestWithdrawal(token, amount)", "credits.cancelWithdrawal(token)", "credits.withdraw(token)"] : []), ]; // Reads a wallet or the site needs. Anything else is refused. const READS = new Set([ "eth_blockNumber", "eth_getBalance", "eth_call", "eth_estimateGas", "eth_gasPrice", "eth_maxPriorityFeePerGas", "eth_feeHistory", "eth_getTransactionCount", "eth_getTransactionReceipt", "eth_getTransactionByHash", "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getCode", "eth_getLogs", ]); const err = (id, code, message, data) => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message, ...(data ? { data } : {}) } }); const ok = (id, result) => ({ jsonrpc: "2.0", id: id ?? null, result }); /** * @param {{chainId:number, usdc:string, eqnvda?:string|null, treasury:string|null, credits?:string|null}} cfg * @param {{upstream:(method:string, params:any[])=>Promise, post?:((raw:string)=>Promise)|null, * allowRead:(ip:string)=>boolean, allowSend:(ip:string)=>boolean, log?:(e:object)=>void}} deps * upstream a JSON-RPC call to Elysium; throws {code, message, data} * post posts a signed transaction into the inbox on HyperEVM; absent when no gas account is configured */ export function createRelayer(cfg, deps) { const log = deps.log ?? (() => {}); const canSend = () => (!!cfg.treasury || !!cfg.credits) && !!deps.post; async function send(id, raw, ip) { if (typeof raw !== "string") return err(id, -32602, "expected one signed transaction"); if (!cfg.treasury && !cfg.credits) return err(id, -32000, "not-open: no treasury is configured, nothing was sent"); if (!deps.allowSend(ip)) return err(id, -32005, "too many transactions, wait a minute"); const c = checkTx(raw, cfg); if (!c.ok) { log({ event: "relay-refused", code: c.code, ip }); return err(id, -32000, `${c.code}: ${c.reason}`); } // Run it once on Elysium first, so a revert is told now instead of vanishing in the inbox. try { await deps.upstream("eth_call", [{ from: c.from, to: c.tx.to, data: c.tx.data, value: "0x0" }, "latest"]); const nonce = BigInt(await deps.upstream("eth_getTransactionCount", [c.from, "pending"])); if (BigInt(c.tx.nonce) !== nonce) return err(id, -32000, `nonce: signed ${c.tx.nonce}, the account is at ${nonce}`); } catch (e) { return err(id, 3, "would revert: " + (e?.message ?? "execution reverted"), e?.data); } // An approval runs cleanly from any address, even an empty one, so it would be a free way to spend this // relayer's gas. A call to the contract or an approval is only carried for a sender who can pay for it on // Elysium: without that the transaction would be dropped there anyway. if (c.call !== "transfer") { try { const need = c.tx.gasLimit * (c.tx.maxFeePerGas ?? c.tx.gasPrice ?? 0n); if (BigInt(await deps.upstream("eth_getBalance", [c.from, "latest"])) < need) return err(id, -32000, "no-gas: the sender holds too little HYPE on Elysium to pay for this transaction, nothing was sent"); } catch { return err(id, -32603, "could not read the sender's balance on Elysium, nothing was sent"); } } if (!deps.post) return err(id, -32000, "no-gas-account: this relayer has no HyperEVM gas account configured, nothing was sent"); try { const posted = await deps.post(raw); log({ event: "relay-posted", from: c.from, hash: c.hash, token: c.token, amount: c.amount.toString(), inboxTx: posted }); return ok(id, c.hash); } catch (e) { log({ event: "relay-post-failed", hash: c.hash, error: String(e?.message ?? e) }); return err(id, -32603, "could not post to the inbox, nothing was sent"); } } async function one(req, ip) { if (!req || typeof req !== "object" || typeof req.method !== "string") return err(req?.id, -32600, "invalid request"); const { id, method, params = [] } = req; if (method === "eth_chainId") return ok(id, "0x" + cfg.chainId.toString(16)); if (method === "net_version") return ok(id, String(cfg.chainId)); if (method === "web3_clientVersion") return ok(id, "idle-gpu-relayer/0.3"); if (method === "eth_sendRawTransaction") return send(id, Array.isArray(params) ? params[0] : undefined, ip); if (!READS.has(method)) return err(id, -32601, `method ${method} is not carried by this relayer`); if (!deps.allowRead(ip)) return err(id, -32005, "too many requests"); try { return ok(id, await deps.upstream(method, params)); } catch (e) { return err(id, e?.code ?? -32603, e?.message ?? "upstream error", e?.data); } } /** One JSON-RPC request or a batch of up to 20, already parsed. Always answers a JSON-RPC body. */ async function rpc(json, ip) { if (Array.isArray(json)) { if (json.length === 0 || json.length > 20) return err(null, -32600, "batch of 1 to 20 requests"); return Promise.all(json.map((r) => one(r, ip))); } return one(json, ip); } return { rpc, canSend, carries: carries(cfg) }; }