import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { Wallet, Interface, parseEther, parseUnits, keccak256 } from "ethers"; import { checkTx, OPTIONS_ABI } from "../scope.mjs"; import { normCdf, callPrice, realisedVol, makeQuoter } from "../quote.mjs"; import { createApp } from "../app.mjs"; const OPTIONS = "0x00000000000000000000000000000000000000A1"; const KHYPE = "0x00000000000000000000000000000000000000B2"; const USDC = "0x00000000000000000000000000000000000000C3"; const OTHER = "0x00000000000000000000000000000000000000D4"; const cfg = { chainId: 99901, options: OPTIONS, tokens: [KHYPE, USDC] }; const wallet = Wallet.createRandom(); const opt = new Interface(OPTIONS_ABI); const erc20 = new Interface(["function approve(address,uint256)", "function transfer(address,uint256)"]); const sign = (o = {}) => wallet.signTransaction({ type: 2, chainId: 99901, nonce: 7, gasLimit: 300_000n, maxFeePerGas: 2_000_000_000n, maxPriorityFeePerGas: 0n, to: OPTIONS, value: 0n, data: "0x", ...o }); const writeData = opt.encodeFunctionData("write", [parseUnits("10", 18), parseUnits("70", 6), 2_000_000_000n, parseEther("0.3")]); describe("scope", () => { test("carries the six calls of the options contract", async () => { for (const [name, args, value] of [ ["write", [1n, 1n, 2_000_000_000n, 1n], 0n], ["cancel", [3n], 0n], ["reclaim", [3n], 0n], ["buy", [3n], parseEther("0.3")], ["transferOption", [3n, OTHER], 0n], ["exercise", [3n], 0n], ]) { const r = checkTx(await sign({ data: opt.encodeFunctionData(name, args), value }), cfg); assert.equal(r.ok, true, name); assert.equal(r.call, name); assert.equal(r.from, wallet.address); } }); test("the hash it returns is the hash of the signed bytes", async () => { const raw = await sign({ data: writeData }); assert.equal(checkTx(raw, cfg).hash, keccak256(raw)); }); test("carries approve on a listed token, for the options contract only", async () => { const good = await sign({ to: KHYPE, data: erc20.encodeFunctionData("approve", [OPTIONS, 5n]) }); assert.equal(checkTx(good, cfg).call, "approve"); const wrongSpender = await sign({ to: USDC, data: erc20.encodeFunctionData("approve", [OTHER, 5n]) }); assert.equal(checkTx(wrongSpender, cfg).code, "scope"); const transfer = await sign({ to: KHYPE, data: erc20.encodeFunctionData("transfer", [OTHER, 5n]) }); assert.equal(checkTx(transfer, cfg).code, "scope"); }); test("refuses everything else", async () => { const cases = { scope: [ await sign({ to: OTHER, data: writeData }), await sign({ to: OTHER, value: 1n }), await sign({ to: null, data: "0x6080" }), await sign({ data: "0xdeadbeef" }), await sign({ data: "0x" }), await sign({ data: writeData, value: 1n }), ], chain: [await sign({ chainId: 1, data: writeData })], gas: [await sign({ gasLimit: 5_000_000n, data: writeData })], fee: [await sign({ maxFeePerGas: parseUnits("900", "gwei"), data: writeData })], malformed: ["0x1234", "nonsense"], }; for (const [code, raws] of Object.entries(cases)) for (const raw of raws) assert.equal(checkTx(raw, cfg).code, code); }); test("refuses a transaction with no signature", () => { const unsigned = "0x02" + "e7" + "8301863d0780847735940083" + "0493e0"; assert.equal(checkTx(unsigned, cfg).ok, false); }); test("the plain-HYPE market: its contract, wrapping and unwrapping, and nothing more", async () => { const OPTIONS_HYPE = "0x00000000000000000000000000000000000000E5"; const WHYPE = "0x00000000000000000000000000000000000000F6"; const both = { ...cfg, optionsHype: OPTIONS_HYPE, whype: WHYPE }; const wrap = new Interface(["function deposit() payable", "function withdraw(uint256)", "function transfer(address,uint256)"]); assert.equal(checkTx(await sign({ to: OPTIONS_HYPE, data: writeData }), both).call, "write"); assert.equal(checkTx(await sign({ to: WHYPE, data: wrap.encodeFunctionData("deposit"), value: parseEther("1") }), both).call, "wrap"); assert.equal(checkTx(await sign({ to: WHYPE, data: wrap.encodeFunctionData("withdraw", [5n]) }), both).call, "unwrap"); assert.equal(checkTx(await sign({ to: WHYPE, data: erc20.encodeFunctionData("approve", [OPTIONS_HYPE, 5n]) }), both).call, "approve"); assert.equal(checkTx(await sign({ to: KHYPE, data: erc20.encodeFunctionData("approve", [OPTIONS_HYPE, 5n]) }), both).call, "approve"); for (const raw of [ await sign({ to: WHYPE, data: wrap.encodeFunctionData("deposit") }), // wraps nothing await sign({ to: WHYPE, data: wrap.encodeFunctionData("withdraw", [5n]), value: 1n }), await sign({ to: WHYPE, data: wrap.encodeFunctionData("transfer", [OTHER, 5n]) }), await sign({ to: WHYPE, value: parseEther("1") }), // a bare send is not carried await sign({ to: WHYPE, data: erc20.encodeFunctionData("approve", [OTHER, 5n]) }), ]) { assert.equal(checkTx(raw, both).code, "scope"); } // Until that contract is deployed, none of it is carried. assert.equal(checkTx(await sign({ to: OPTIONS_HYPE, data: writeData }), cfg).code, "scope"); assert.equal(checkTx(await sign({ to: WHYPE, data: wrap.encodeFunctionData("deposit"), value: parseEther("1") }), { ...cfg, whype: WHYPE }).code, "scope"); }); }); describe("quote", () => { test("the normal distribution and the call price behave", () => { assert.ok(Math.abs(normCdf(0) - 0.5) < 1e-6); assert.ok(Math.abs(normCdf(1.96) - 0.975) < 1e-3); assert.ok(Math.abs(callPrice(100, 100, 1, 0.2) - 7.9656) < 0.01); assert.ok(Math.abs(callPrice(100, 50, 0.01, 0.2) - 50) < 0.01); assert.ok(callPrice(60, 70, 7 / 365, 0.7) > 0 && callPrice(60, 70, 7 / 365, 0.7) < 1); assert.equal(callPrice(80, 70, 0, 0.7), 10); assert.ok(callPrice(60, 70, 30 / 365, 0.7) > callPrice(60, 70, 7 / 365, 0.7)); }); test("realised volatility", () => { assert.equal(realisedVol([5, 5, 5, 5], 365), 0); assert.ok(Number.isNaN(realisedVol([5], 365))); const up = realisedVol([100, 101, 100, 101, 100, 101], 365); assert.ok(up > 0.15 && up < 0.25); }); const fakeFetch = (calls) => async (_url, init) => { const body = JSON.parse(init.body); calls.push(body.type); const candles = Array.from({ length: 200 }, (_, i) => ({ c: String(60 + Math.sin(i / 3)) })); return { ok: true, json: async () => (body.type === "allMids" ? { HYPE: "62.5", BTC: "1" } : candles) }; }; test("quotes from the mid, the rate and the measured volatility, and caches the market", async () => { const calls = []; const q = makeQuoter({ fetch: fakeFetch(calls), rate: 1.03, now: () => 1_800_000_000_000 }); const a = await q.quote({ strike: 70, days: 7, amount: 100 }); assert.equal(a.hypeMid, 62.5); assert.ok(Math.abs(a.khypeUsd - 64.375) < 1e-9); assert.ok(a.volatility >= 0.2 && a.volatility <= 3); assert.ok(a.premiumUsd > 0); assert.ok(Math.abs(a.premiumHype - a.premiumUsd / 62.5) < 1e-12); assert.equal(a.strikeCostUsd, 7000); const b = await q.quote({ strike: 66, days: 7, amount: 100 }); assert.ok(b.premiumUsd > a.premiumUsd, "a lower strike costs more"); assert.equal(calls.length, 2, "the market was fetched once for both quotes"); }); test("refuses nonsense inputs", async () => { const q = makeQuoter({ fetch: fakeFetch([]) }); for (const bad of [{ strike: 0, days: 7 }, { strike: 70, days: 0 }, { strike: 70, days: 400 }, { strike: "x", days: 7 }, { strike: 70, days: 7, amount: -1 }]) { await assert.rejects(() => q.quote(bad), RangeError); } }); }); describe("relayer", () => { function setup(over = {}) { const seen = { upstream: [], posted: [] }; const deps = { upstream: async (method, params) => { seen.upstream.push(method); if (method === "eth_getTransactionCount") return "0x7"; if (method === "eth_call") { if (over.revert) throw { code: 3, message: "execution reverted: WrongPremium", data: "0x" }; return "0x"; } if (method === "eth_blockNumber") return "0x10"; if (method === "eth_getBalance") return over.balance ?? "0xde0b6b3a7640000"; // 1 HYPE return null; }, post: async (raw) => { if (over.postFails) throw new Error("hyperevm down"); seen.posted.push(raw); return "0xinbox"; }, quoter: { quote: async (q) => { if (!(q.strike > 0)) throw new RangeError("bad"); return { premiumHype: 0.3 }; } }, now: over.now, }; const app = createApp({ ...cfg, ...over.cfg }, deps); const rpc = async (payload, ip = "1.1.1.1") => JSON.parse((await app.handle({ method: "POST", path: "/rpc", body: JSON.stringify(payload), ip })).body); return { app, rpc, seen }; } const call = (method, params = [], id = 1) => ({ jsonrpc: "2.0", id, method, params }); test("answers the chain id itself and forwards listed reads", async () => { const { rpc, seen } = setup(); assert.equal((await rpc(call("eth_chainId"))).result, "0x1863d"); assert.equal((await rpc(call("net_version"))).result, "99901"); assert.equal((await rpc(call("eth_blockNumber"))).result, "0x10"); assert.deepEqual(seen.upstream, ["eth_blockNumber"]); }); test("refuses methods it does not carry", async () => { const { rpc, seen } = setup(); for (const m of ["eth_sendTransaction", "eth_sign", "personal_sign", "debug_traceTransaction", "eth_accounts"]) { assert.equal((await rpc(call(m))).error.code, -32601, m); } assert.equal(seen.upstream.length, 0); }); test("simulates, checks the nonce, then posts an in-scope transaction untouched", async () => { const { rpc, seen } = setup(); const raw = await sign({ data: writeData }); const r = await rpc(call("eth_sendRawTransaction", [raw])); assert.equal(r.result, keccak256(raw)); assert.deepEqual(seen.upstream, ["eth_call", "eth_getTransactionCount", "eth_getBalance"]); assert.deepEqual(seen.posted, [raw]); }); test("posts nothing when the sender cannot pay for it on Elysium", async () => { const { rpc, seen } = setup({ balance: "0x0" }); const r = await rpc(call("eth_sendRawTransaction", [await sign({ data: writeData })])); assert.match(r.error.message, /^funds:/); assert.equal(seen.posted.length, 0, "the relayer's gas is not spent on a transaction the chain would drop"); }); test("posts nothing when the transaction is out of scope", async () => { const { rpc, seen } = setup(); const r = await rpc(call("eth_sendRawTransaction", [await sign({ to: OTHER, value: 1n })])); assert.match(r.error.message, /^scope:/); assert.equal(seen.posted.length, 0); assert.equal(seen.upstream.length, 0, "it is refused before anything is run"); }); test("posts nothing when the transaction would revert or the nonce is out of turn", async () => { const a = setup({ revert: true }); const r1 = await a.rpc(call("eth_sendRawTransaction", [await sign({ data: writeData })])); assert.equal(r1.error.code, 3); assert.match(r1.error.message, /WrongPremium/); assert.equal(a.seen.posted.length, 0); const b = setup(); const r2 = await b.rpc(call("eth_sendRawTransaction", [await sign({ data: writeData, nonce: 9 })])); assert.match(r2.error.message, /^nonce:/); assert.equal(b.seen.posted.length, 0); }); test("a dry run checks everything and posts nothing", async () => { const { rpc, seen } = setup({ cfg: { dryRun: true } }); const raw = await sign({ data: writeData }); assert.equal((await rpc(call("eth_sendRawTransaction", [raw]))).result, keccak256(raw)); assert.equal(seen.posted.length, 0); }); test("reports a failed post without claiming the transaction was sent", async () => { const { rpc } = setup({ postFails: true }); const r = await rpc(call("eth_sendRawTransaction", [await sign({ data: writeData })])); assert.equal(r.error.code, -32603); assert.match(r.error.message, /nothing was sent/); }); test("limits sends per address and handles batches", async () => { const { rpc } = setup({ cfg: { sendsPerMinute: 2 }, now: () => 1000 }); const raw = await sign({ data: writeData }); const batch = await rpc([call("eth_chainId", [], 1), call("eth_sendRawTransaction", [raw], 2), call("eth_sendRawTransaction", [raw], 3), call("eth_sendRawTransaction", [raw], 4)]); assert.equal(batch.length, 4); assert.equal(batch[0].result, "0x1863d"); assert.ok(batch[1].result && batch[2].result); assert.equal(batch[3].error.code, -32005); assert.equal((await rpc(Array(21).fill(call("eth_chainId")))).error.code, -32600); assert.equal((await rpc(call("eth_sendRawTransaction", [raw]), "2.2.2.2")).result, keccak256(raw), "another address is not limited"); }); test("serves health, quotes and CORS, and nothing else", async () => { const { app } = setup({ cfg: { origins: ["https://example.test"] } }); const health = await app.handle({ method: "GET", path: "/v1/health" }); assert.equal(JSON.parse(health.body).chainId, 99901); assert.equal(health.headers["Access-Control-Allow-Origin"], "https://example.test"); const good = await app.handle({ method: "GET", path: "/v1/quote", query: { strike: "70", days: "7" } }); assert.equal(good.status, 200); const bad = await app.handle({ method: "GET", path: "/v1/quote", query: { strike: "0", days: "7" } }); assert.equal(bad.status, 400); assert.equal((await app.handle({ method: "GET", path: "/secret" })).status, 404); assert.equal((await app.handle({ method: "OPTIONS", path: "/rpc" })).status, 204); const parse = await app.handle({ method: "POST", path: "/rpc", body: "{" }); assert.equal(JSON.parse(parse.body).error.code, -32700); }); }); describe("before deployment, and the live market", () => { const market = (mids) => async (_url, init) => { const body = JSON.parse(init.body); if (body.type === "allMids") return { ok: true, json: async () => mids }; return { ok: true, json: async () => Array.from({ length: 200 }, (_, i) => ({ c: String(60 + Math.sin(i / 5) * 2) })) }; }; const raw = () => sign({ data: writeData }); const send = async (app, tx) => JSON.parse((await app.handle({ method: "POST", path: "/rpc", body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_sendRawTransaction", params: [tx] }), ip: "9.9.9.9" })).body); const upstream = async (method) => (method === "eth_getTransactionCount" ? "0x7" : method === "eth_getBalance" ? "0xde0b6b3a7640000" : "0x"); test("with no contract address it serves reads and quotes, and sends nothing", async () => { const posted = []; const app = createApp({ chainId: 99901, options: null, tokens: [KHYPE, USDC] }, { upstream, post: async (r) => posted.push(r), quoter: makeQuoter({ fetch: market({ HYPE: "62.5" }) }) }); const health = JSON.parse((await app.handle({ method: "GET", path: "/v1/health" })).body); assert.equal(health.deployed, false); assert.equal(health.options, null); assert.equal(health.canSend, false); assert.equal(health.khype, KHYPE); const r = await send(app, await raw()); assert.match(r.error.message, /^not-deployed/); assert.equal(posted.length, 0); assert.equal((await app.handle({ method: "GET", path: "/v1/quote", query: { strike: "70", days: "7" } })).status, 200); }); test("with a contract but no gas account it checks the transaction and sends nothing", async () => { const app = createApp(cfg, { upstream, post: null, quoter: makeQuoter({ fetch: market({ HYPE: "62.5" }) }) }); const health = JSON.parse((await app.handle({ method: "GET", path: "/v1/health" })).body); assert.equal(health.deployed, true); assert.equal(health.canSend, false); assert.match((await send(app, await raw())).error.message, /^no-gas-account/); }); test("the kHYPE rate comes from the two spot books when they agree with reality", async () => { const q = makeQuoter({ fetch: market({ HYPE: "62.5", "@107": "62.6", "@336": "64.4" }), rate: 1.0 }); const m = await q.market(); assert.ok(Math.abs(m.rate - 64.4 / 62.6) < 1e-12); assert.match(m.rateSource, /spot/); assert.ok(Math.abs(m.khypeUsd - 62.5 * (64.4 / 62.6)) < 1e-9); }); test("a wild or missing kHYPE price falls back to the configured rate", async () => { for (const mids of [{ HYPE: "62.5", "@107": "62.6", "@336": "140" }, { HYPE: "62.5", "@107": "62.6", "@336": "50" }, { HYPE: "62.5" }]) { const m = await makeQuoter({ fetch: market(mids), rate: 1.03 }).market(); assert.equal(m.rate, 1.03); assert.equal(m.rateSource, "configured"); } }); test("the market endpoint shows the inputs of every quote", async () => { const app = createApp(cfg, { upstream, post: null, quoter: makeQuoter({ fetch: market({ HYPE: "62.5", "@107": "62.5", "@336": "64.3" }) }) }); const r = await app.handle({ method: "GET", path: "/v1/market" }); const m = JSON.parse(r.body); assert.equal(r.status, 200); assert.equal(m.hypeMid, 62.5); assert.ok(m.khypeRate > 1 && m.volatility > 0 && m.volatilitySamples === 200); const quote = JSON.parse((await app.handle({ method: "GET", path: "/v1/quote", query: { strike: "70", days: "7" } })).body); assert.equal(quote.khypeUsd, m.khypeUsd); assert.equal(quote.volatility, m.volatility); }); }); describe("on-chain 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 ZERO = "0x0000000000000000000000000000000000000000"; // Two options on chain: one on offer (state 1) for 10, one cancelled (state 4) for 5. The contract holds 10. const list = [ [wallet.address, ZERO, parseUnits("10", 18), parseUnits("70", 6), parseEther("0.3"), 2_000_000_000n, 1], [wallet.address, ZERO, parseUnits("5", 18), parseUnits("72", 6), parseEther("0.1"), 2_000_000_000n, 4], ]; const chain = (held) => async (method, params) => { if (method === "eth_getCode") return "0x6080"; if (method === "eth_blockNumber") return "0x10"; if (method === "eth_call") { const fn = view.parseTransaction({ data: params[0].data }).name; if (fn === "count") return view.encodeFunctionResult("count", [2n]); if (fn === "getOptions") return view.encodeFunctionResult("getOptions", [list]); return view.encodeFunctionResult("balanceOf", [held]); } return null; }; test("reports the code, the options and the cover, each read from the chain", async () => { const app = createApp(cfg, { upstream: chain(parseUnits("10", 18)), post: null, quoter: {} }); const r = await app.handle({ method: "GET", path: "/v1/proof" }); const p = JSON.parse(r.body); assert.equal(r.status, 200); assert.equal(p.deployed, true); assert.equal(p.contract.codeBytes, 2); assert.equal(p.contract.codeKeccak256, keccak256("0x6080")); assert.equal(p.optionsWritten.count, 2); assert.deepEqual(p.optionsWritten.list.map((o) => o.state), ["open", "cancelled"]); assert.equal(p.covered.claimableByOpenOptions, parseUnits("10", 18).toString(), "the cancelled option claims nothing"); assert.equal(p.covered.oneForOne, true); }); test("says so when the contract holds less than its open options can claim", async () => { const app = createApp(cfg, { upstream: chain(parseUnits("9", 18)), post: null, quoter: {} }); const p = JSON.parse((await app.handle({ method: "GET", path: "/v1/proof" })).body); assert.equal(p.covered.oneForOne, false); }); test("before deployment it only says that nothing is deployed", async () => { const app = createApp({ ...cfg, options: null }, { upstream: chain(0n), post: null, quoter: {} }); assert.deepEqual(JSON.parse((await app.handle({ method: "GET", path: "/v1/proof" })).body), { deployed: false }); }); });