// The HTTP surface, kept free of sockets and keys so it can be tested with plain objects. // POST /rpc a scoped JSON-RPC endpoint a wallet can use as its Elysium connection // GET /v1/quote a premium quote // GET /v1/market the live inputs every quote is computed from // GET /v1/health what the relayer is configured to carry, and whether the contract is deployed import { Interface, keccak256 } from "ethers"; import { checkTx } from "./scope.mjs"; // Read-only calls used by /v1/proof. const VIEW = new Interface([ "function count() view returns (uint256)", "function getOptions(uint256 start,uint256 max) view returns (tuple(address writer,address holder,uint128 amount,uint128 strike,uint128 premium,uint64 expiry,uint8 state)[])", "function balanceOf(address) view returns (uint256)", ]); const STATES = ["none", "open", "sold", "exercised", "cancelled", "reclaimed"]; // 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 }); function limiter(max, windowMs, now) { const hits = new Map(); return (key) => { const t = now(); const list = (hits.get(key) ?? []).filter((x) => t - x < windowMs); if (list.length >= max) { hits.set(key, list); return false; } list.push(t); hits.set(key, list); if (hits.size > 5000) for (const [k, v] of hits) if (!v.some((x) => t - x < windowMs)) hits.delete(k); return true; }; } /** * @param {object} cfg chainId, options, tokens, dryRun, origins * @param {object} deps upstream(method, params) -> result | throws {code,message,data} * post(raw) -> hyperEvmTxHash (posts into the inbox) * quoter.quote(q) */ export function createApp(cfg, deps) { const now = deps.now ?? Date.now; const readLimit = limiter(cfg.readsPer10s ?? 120, 10_000, now); const sendLimit = limiter(cfg.sendsPerMinute ?? 10, 60_000, now); const log = deps.log ?? (() => {}); async function send(id, raw, ip) { if (typeof raw !== "string") return err(id, -32602, "expected one signed transaction"); if (!cfg.options) return err(id, -32000, "not-deployed: the options contract is not deployed on this chain yet, nothing was sent"); if (!sendLimit(ip)) return err(id, -32005, "too many transactions, wait a minute"); const c = checkTx(raw, cfg); if (!c.ok) { log({ event: "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 { const tx = { from: c.from, to: c.tx.to, data: c.tx.data, value: "0x" + c.tx.value.toString(16) }; await deps.upstream("eth_call", [tx, "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); } // The sender must be able to pay for it on Elysium. Otherwise the chain drops it after the // inbox, and the relayer's gas was spent for nothing: an empty account could drain it. try { const need = c.tx.gasLimit * (c.tx.maxFeePerGas ?? c.tx.gasPrice ?? 0n) + c.tx.value; const has = BigInt(await deps.upstream("eth_getBalance", [c.from, "latest"])); if (has < need) { log({ event: "refused", code: "funds", ip }); return err(id, -32000, "funds: the account holds too little HYPE on Elysium to pay for this transaction, nothing was sent"); } } catch { return err(id, -32603, "could not read the account's balance on Elysium, nothing was sent"); } if (cfg.dryRun) { log({ event: "dry-run", call: c.call, from: c.from, hash: c.hash }); return ok(id, c.hash); } 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: "posted", call: c.call, from: c.from, hash: c.hash, inboxTx: posted }); return ok(id, c.hash); } catch (e) { log({ event: "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, "kinetiq-options-relayer/0.1"); if (method === "eth_sendRawTransaction") return send(id, params[0], ip); if (!READS.has(method)) return err(id, -32601, `method ${method} is not carried by this relayer`); if (!readLimit(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); } } /** @returns {Promise<{status:number, headers:object, body:string}>} */ async function handle({ method, path, query = {}, body = "", ip = "?", origin }) { const allow = !cfg.origins?.length ? "*" : cfg.origins.includes(origin) ? origin : cfg.origins[0]; const headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": allow, "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", Vary: "Origin", }; const out = (status, obj) => ({ status, headers, body: JSON.stringify(obj) }); if (method === "OPTIONS") return { status: 204, headers, body: "" }; if (method === "GET" && path === "/v1/health") { return out(200, { ok: true, chainId: cfg.chainId, deployed: !!cfg.options, // the plain-HYPE market, when its contract is deployed: same code, wrapped HYPE as collateral optionsHype: cfg.optionsHype ?? null, whype: cfg.optionsHype ? (cfg.whype ?? null) : null, options: cfg.options ?? null, tokens: cfg.tokens, khype: cfg.tokens?.[0] ?? null, usdc: cfg.tokens?.[1] ?? null, usdcDecimals: cfg.usdcDecimals ?? 6, inbox: cfg.inbox ?? null, canSend: !!cfg.options && (!!cfg.dryRun || !!deps.post), dryRun: !!cfg.dryRun, }); } // What is on chain, read from Elysium at the moment of the request. Nothing here is the project's word: // each field names the call that produced it, so anyone can make the same call and compare. if (method === "GET" && path === "/v1/proof") { if (!readLimit(ip)) return out(429, { error: "too many requests" }); if (!cfg.options) return out(200, { deployed: false }); try { const view = async (to, fn, args = []) => VIEW.decodeFunctionResult(fn, await deps.upstream("eth_call", [{ to, data: VIEW.encodeFunctionData(fn, args) }, "latest"])); const [code, block, [count], [held]] = await Promise.all([ deps.upstream("eth_getCode", [cfg.options, "latest"]), deps.upstream("eth_blockNumber", []), view(cfg.options, "count"), view(cfg.tokens[0], "balanceOf", [cfg.options]), ]); const n = Number(count); const start = Math.max(0, n - 50); const [list] = n ? await view(cfg.options, "getOptions", [start, 50]) : [[]]; const options = [...list].map((o, k) => ({ id: start + k, state: STATES[Number(o.state)] ?? String(o.state), writer: o.writer, holder: o.holder, amount: o.amount.toString(), strike: o.strike.toString(), premium: o.premium.toString(), expiry: Number(o.expiry), })); const owed = [...list].filter((o) => Number(o.state) === 1 || Number(o.state) === 2).reduce((a, o) => a + o.amount, 0n); const explorer = cfg.explorer ? cfg.explorer + "/address/" + cfg.options : null; return out(200, { deployed: code !== "0x", chainId: cfg.chainId, chain: "Elysium. It is its own chain: an Elysium address has no code on HyperEVM, so ask an Elysium RPC.", readFrom: { thisRelayer: "POST /api/rpc on this host", publicRpc: cfg.publicRpc ?? null }, atBlock: Number(BigInt(block)), contract: { address: cfg.options, codeBytes: (code.length - 2) / 2, codeKeccak256: code === "0x" ? null : keccak256(code), howToCheck: 'eth_getCode ["' + cfg.options + '","latest"] on chain ' + cfg.chainId, sourceVerifiedOnExplorer: explorer ? explorer + "?tab=contract" : null, creation: cfg.creation ?? null, }, optionsWritten: { count: n, howToCheck: "eth_call count() and getOptions(start,max) on the contract", eventsOnExplorer: explorer ? explorer + "?tab=events" : null, listedFrom: start, list: options, }, covered: { collateralToken: cfg.tokens[0], heldByContract: held.toString(), claimableByOpenOptions: owed.toString(), oneForOne: held >= owed, howToCheck: "balanceOf(contract) on the collateral token, against the sum of amount over options in state open or sold", note: n > 50 ? "only the last 50 options are summed here" : undefined, }, units: "amount and premium in wei (18 decimals), strike in USDC units (6 decimals) per 1e18 of collateral, expiry in unix seconds", }); } catch (e) { return out(502, { error: "Elysium did not answer: " + String(e?.message ?? e) }); } } if (method === "GET" && path === "/v1/market") { if (!readLimit(ip)) return out(429, { error: "too many requests" }); try { const m = await deps.quoter.market(); return out(200, { hypeMid: m.hype, khypeUsd: m.khypeUsd, khypeRate: m.rate, khypeRateSource: m.rateSource, volatility: m.vol, volatilitySamples: m.samples, asOf: new Date(m.at).toISOString(), source: "Hyperliquid mids and 30-day hourly realised volatility of HYPE", }); } catch (e) { return out(502, { error: String(e?.message ?? e) }); } } if (method === "GET" && path === "/v1/quote") { if (!readLimit(ip)) return out(429, { error: "too many requests" }); try { return out(200, await deps.quoter.quote({ strike: query.strike, days: query.days, amount: query.amount ?? 1 })); } catch (e) { return out(e instanceof RangeError ? 400 : 502, { error: String(e?.message ?? e) }); } } if (method === "POST" && path === "/rpc") { let json; try { json = JSON.parse(body); } catch { return out(200, err(null, -32700, "parse error")); } if (Array.isArray(json)) { if (json.length === 0 || json.length > 20) return out(200, err(null, -32600, "batch of 1 to 20 requests")); return out(200, await Promise.all(json.map((r) => one(r, ip)))); } return out(200, await one(json, ip)); } return out(404, { error: "not found" }); } return { handle }; }