import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { GPUS, RENTALS_OPEN, card, findGpu, quote } from "../lib/rates.mjs"; import { makeMarket, abiText, units, ELYSIUM, EXTSLOAD, poolSlot, decodeSlot0, poolPriceMicro, gapBps } from "../lib/market.mjs"; import { createApp } from "../lib/app.mjs"; // What Elysium answered for the EQNVDA / USDC pool and for the token, at one block (see the file's note). const POOL = JSON.parse(readFileSync(new URL("./fixtures/elysium/eqnvda-pool.json", import.meta.url), "utf8")); const word = (n) => BigInt(n).toString(16).padStart(64, "0"); const str = (s) => "0x" + word(32) + word(s.length) + Buffer.from(s).toString("hex").padEnd(64, "0"); /** A stand-in for the two public sources. `o` breaks one of them. */ function world(o = {}) { const calls = { hl: 0, rpc: 0, slots: [] }; const fetch = async (url, init) => { const body = JSON.parse(init.body); const json = (v) => ({ ok: true, json: async () => v }); if (url.includes("hyperliquid")) { calls.hl++; if (o.hlDown) return { ok: false, status: 503, json: async () => ({}) }; return json(body.dex === "xyz" ? { "xyz:NVDA": o.nvda ?? "151.2" } : { HYPE: "64.8" }); } calls.rpc++; if (o.rpcDown) throw new Error("connection refused"); const ok = (result) => json({ jsonrpc: "2.0", id: 1, result }); if (body.method === "eth_chainId") return ok("0x" + (o.chainId ?? 99901).toString(16)); if (body.method === "eth_getBlockByNumber") return ok({ number: "0xc6100f", timestamp: "0x6b0b2000" }); if (body.method === "eth_call") { const { to, data } = body.params[0]; const sel = data.slice(0, 10); const who = String(to).toLowerCase(); // The PoolManager: one storage word per call. The pool's first word, and its liquidity three slots on. if (who === ELYSIUM.poolManager.toLowerCase() && sel === EXTSLOAD) { calls.slots.push("0x" + data.slice(10)); if (o.poolDown) return json({ jsonrpc: "2.0", id: 1, error: { message: "execution reverted" } }); if ("0x" + data.slice(10) === POOL.slot) return ok(o.slot0 ?? POOL.slot0); if (BigInt("0x" + data.slice(10)) === BigInt(POOL.slot) + 3n) return ok("0x" + word(POOL.liquidity)); return ok("0x" + word(0)); } if (who === ELYSIUM.eqnvda.toLowerCase()) { if (sel === "0x95d89b41") return ok(str(o.equitySymbol ?? POOL.symbol)); if (sel === "0x313ce567") return ok("0x" + word(POOL.decimals)); if (sel === "0x18160ddd") return ok("0x" + word(POOL.totalSupply)); } if (who === ELYSIUM.usdc.toLowerCase()) { if (sel === "0x95d89b41") return ok(str("USDC")); if (sel === "0x313ce567") return ok("0x" + word(6)); if (sel === "0x18160ddd") return ok("0x" + word(4331102715467n)); } } return json({ jsonrpc: "2.0", id: 1, error: { message: "unexpected " + body.method } }); }; return { fetch, calls }; } const market = (w, over = {}) => makeMarket({ fetch: w.fetch, rpc: "https://rpc.test", ...over }); const get = async (app, path, query = {}, ip = "1.1.1.1") => { const r = await app.handle({ method: "GET", path, query, ip }); return { status: r.status, body: JSON.parse(r.body) }; }; describe("rate card", () => { test("lists Nvidia GPUs with a rate, and claims none of them is available", () => { assert.equal(RENTALS_OPEN, false); assert.ok(GPUS.length >= 5); for (const g of GPUS) { assert.match(g.id, /^[a-z0-9-]+$/); assert.ok(g.vram > 0 && g.usdPerHour > 0); } assert.equal(new Set(GPUS.map((g) => g.id)).size, GPUS.length); for (const row of card(64.8)) assert.equal(row.available, 0); }); test("converts each rate to HYPE at the live mid, and gives no HYPE figure without one", () => { const h100 = card(50).find((g) => g.id === "h100"); assert.equal(h100.hypePerHour, +(h100.usdPerHour / 50).toFixed(6)); assert.equal(card(null)[0].hypePerHour, null); assert.equal(card(0)[0].hypePerHour, null); }); test("bills per second and rounds up to the last USDC decimal", () => { const gpu = findGpu("H100"); const one = quote(gpu, 1, 60); assert.equal(one.usd, Math.ceil((gpu.usdPerHour / 3600) * 1e6) / 1e6); assert.ok(one.usd * 3600 >= gpu.usdPerHour); assert.equal(quote(gpu, 3600, 60).usd, gpu.usdPerHour); assert.equal(quote(gpu, 3600, 60).hype, +(gpu.usdPerHour / 60).toFixed(6)); assert.equal(quote(gpu, 60, null).hype, null); }); test("refuses durations that are not whole seconds within a month, and unknown GPUs", () => { const gpu = findGpu("rtx-4090"); for (const s of [0, -5, 1.5, NaN, 30 * 86_400 + 1]) assert.throws(() => quote(gpu, s, 60), RangeError); assert.equal(findGpu("gtx-1080"), null); assert.throws(() => quote(null, 60, 60), RangeError); }); test("the site carries the same rate card as the API", () => { const page = readFileSync(new URL("../../_src/arbor.html", import.meta.url), "utf8"); const m = page.match(/const CARD=(\[[\s\S]*?\]);/); assert.ok(m, "the page has no CARD"); const onPage = Function("return " + m[1])(); assert.deepEqual(onPage, GPUS.map((g) => [g.id, g.name, g.vram, g.usdPerHour])); }); }); describe("market", () => { test("decodes what the chain answers", () => { assert.equal(abiText(str("USDC")), "USDC"); assert.equal(abiText("0x"), ""); assert.equal(units(4331102715467n, 6), "4331102.715467"); assert.equal(units(0n, 6), "0"); }); test("reads HYPE, Nvidia, the chain head and USDC", async () => { const m = await market(world())(); assert.equal(m.hypeMid, 64.8); assert.equal(m.nvda, 151.2); assert.equal(m.nvdaMarket, "xyz:NVDA"); assert.deepEqual(m.chain, { chainId: 99901, block: 0xc6100f, blockTime: new Date(0x6b0b2000 * 1000).toISOString() }); assert.deepEqual(m.usdc, { address: ELYSIUM.usdc, symbol: "USDC", decimals: 6, totalSupply: "4331102.715467" }); assert.deepEqual(m.errors, []); }); test("finds a Uniswap v4 pool's first word and reads its price, checked against what the chain answered", () => { // keccak256(abi.encode(poolId, uint256(6))): the slot the real PoolManager was asked for. assert.equal(poolSlot(POOL.poolId), POOL.slot); assert.equal(poolSlot(POOL.poolId.toUpperCase().replace("0X", "0x")), POOL.slot); assert.throws(() => poolSlot("0x1234"), /not a pool id/); const s0 = decodeSlot0(POOL.slot0); assert.deepEqual(s0, { sqrtPriceX96: BigInt(POOL.sqrtPriceX96), tick: POOL.tick, protocolFee: POOL.protocolFee, lpFee: POOL.lpFee }); // EQNVDA has 8 decimals and USDC 6: 151.368838 USDC per EQNVDA, next to an xyz:NVDA mid of 151.305 at that moment. assert.equal(poolPriceMicro(s0.sqrtPriceX96, POOL.decimals, POOL.usdcDecimals), BigInt(POOL.priceMicro)); assert.equal(POOL.priceMicro, 151_368_838); // The tick says the same price, to the tick's own coarseness (one tick is one basis point). const fromTick = 1.0001 ** s0.tick * 10 ** (POOL.decimals - POOL.usdcDecimals); assert.ok(Math.abs(fromTick - POOL.priceMicro / 1e6) / fromTick < 0.0001); }); test("decodes the packed word field by field, negative ticks included", () => { const pack = ({ sqrt, tick, protocolFee = 0, lpFee = 0 }) => "0x" + ((BigInt(lpFee) << 208n) | (BigInt(protocolFee) << 184n) | (BigInt(tick < 0 ? tick + 0x1000000 : tick) << 160n) | sqrt).toString(16).padStart(64, "0"); const one = 1n << 96n; // a price of exactly 1 raw unit per raw unit assert.deepEqual(decodeSlot0(pack({ sqrt: one, tick: 0 })), { sqrtPriceX96: one, tick: 0, protocolFee: 0, lpFee: 0 }); assert.deepEqual(decodeSlot0(pack({ sqrt: one, tick: -887272, protocolFee: 1000, lpFee: 3000 })), { sqrtPriceX96: one, tick: -887272, protocolFee: 1000, lpFee: 3000 }); assert.equal(decodeSlot0("0x" + "0".repeat(64)).sqrtPriceX96, 0n); assert.equal(poolPriceMicro(one, 6, 6), 1_000_000n); assert.equal(poolPriceMicro(one, 8, 6), 100_000_000n); // 100 raw token0 per whole-token ratio assert.equal(poolPriceMicro(one * 2n, 18, 18), 4_000_000n); assert.equal(poolPriceMicro(one, 6, 8), 10_000n); assert.equal(gapBps(151.368838, 151.305), 4); assert.equal(gapBps(100, 103), 291); assert.equal(gapBps(null, 103), null); assert.equal(gapBps(100, null), null); }); test("reads EQNVDA from the chain and its price from the pool, next to the Hyperliquid mark", async () => { const w = world({ nvda: POOL.xyzNvdaMid }); const m = await market(w)(); assert.deepEqual(m.equity, { symbol: "EQNVDA", token: ELYSIUM.eqnvda, decimals: 8, totalSupply: "192.14967691", poolManager: ELYSIUM.poolManager, poolId: ELYSIUM.eqnvdaPoolId, poolPriceUsd: 151.368838, poolLiquidity: "10321400", markUsd: 151.305, gapBps: 4, source: "PoolManager.extsload on Elysium (pool price), Hyperliquid xyz:NVDA (mark)", }); assert.deepEqual(m.errors, []); assert.deepEqual(w.calls.slots.sort(), [POOL.slot, "0x" + (BigInt(POOL.slot) + 3n).toString(16)].sort()); }); test("an unreadable pool, an uninitialised pool or a token of another name give no equity, and say why", async () => { const down = await market(world({ poolDown: true }))(); assert.equal(down.equity, null); assert.deepEqual(down.errors.map((e) => e.split(":")[0]), ["equity"]); assert.equal(down.usdc.symbol, "USDC", "the rest is still read"); const empty = await market(world({ slot0: "0x" + "0".repeat(64) }))(); assert.equal(empty.equity, null); assert.match(empty.errors.join(" "), /equity: the pool has no price/); const other = await market(world({ equitySymbol: "FAKE" }))(); assert.equal(other.equity, null); assert.match(other.errors.join(" "), /answers symbol "FAKE", not EQNVDA/); }); test("without the Hyperliquid mark the pool price is still shown, with no mark and no gap", async () => { const m = await market(world({ hlDown: true }))(); assert.equal(m.equity.poolPriceUsd, 151.368838); assert.equal(m.equity.markUsd, null); assert.equal(m.equity.gapBps, null); assert.deepEqual(m.errors.map((e) => e.split(":")[0]), ["hype", "nvda"]); }); test("keeps what one source says when the other is down, and names what failed", async () => { const a = await market(world({ hlDown: true }))(); assert.equal(a.hypeMid, null); assert.equal(a.nvda, null); assert.equal(a.chain.block, 0xc6100f); assert.deepEqual(a.errors.map((e) => e.split(":")[0]), ["hype", "nvda"]); const b = await market(world({ rpcDown: true }))(); assert.equal(b.hypeMid, 64.8); assert.equal(b.chain, null); assert.equal(b.usdc, null); assert.equal(b.equity, null); assert.deepEqual(b.errors.map((e) => e.split(":")[0]), ["chain", "usdc", "equity"]); }); test("refuses a node that answers for another chain, and a price of zero", async () => { assert.match((await market(world({ chainId: 1 }))()).errors.join(" "), /chain 1, expected 99901/); const m = await market(world({ nvda: "0" }))(); assert.equal(m.nvda, null); assert.equal(m.hypeMid, 64.8); }); test("caches a clean read, shares simultaneous reads, never caches a failed one", async () => { let t = 1_000_000; const w = world(); const read = market(w, { now: () => t, ttlMs: 20_000 }); await Promise.all([read(), read(), read()]); assert.equal(w.calls.hl, 2); // HYPE and Nvidia, once each t += 19_000; await read(); assert.equal(w.calls.hl, 2); t += 2_000; await read(); assert.equal(w.calls.hl, 4); const bad = world({ hlDown: true }); const again = market(bad, { now: () => t }); await again(); await again(); assert.equal(bad.calls.hl, 4); }); }); describe("api", () => { const make = (w = world(), cfg = {}) => createApp(cfg, { market: market(w) }); test("health says plainly that nothing can be rented", async () => { const { status, body } = await get(make(), "/v1/health"); assert.equal(status, 200); assert.equal(body.rentals, false); assert.equal(body.gpusListed, 0); assert.equal(body.chainId, 99901); assert.match(body.note, /not open/); }); test("the rate card comes with the live HYPE conversion and zero availability", async () => { const { body } = await get(make(), "/v1/gpus"); assert.equal(body.rentals, false); assert.equal(body.hypeMid, 64.8); assert.equal(body.gpus.length, GPUS.length); for (const g of body.gpus) { assert.equal(g.available, 0); assert.equal(g.hypePerHour, +(g.usdPerHour / 64.8).toFixed(6)); } }); test("the rate card still answers, without HYPE figures, when the price source is down", async () => { const { status, body } = await get(make(world({ hlDown: true })), "/v1/gpus"); assert.equal(status, 200); assert.equal(body.hypeMid, null); assert.equal(body.gpus[0].hypePerHour, null); assert.ok(body.gpus[0].usdPerHour > 0); }); test("quotes a duration, and says it is a target price", async () => { const { status, body } = await get(make(), "/v1/quote", { gpu: "h100", seconds: "1200" }); assert.equal(status, 200); assert.equal(body.usd, quote(findGpu("h100"), 1200, 64.8).usd); assert.equal(body.rentals, false); assert.match(body.note, /target price/i); assert.equal((await get(make(), "/v1/quote", { gpu: "nope", seconds: "60" })).status, 400); assert.equal((await get(make(), "/v1/quote", { gpu: "h100", seconds: "0" })).status, 400); assert.equal((await get(make(), "/v1/quote", { gpu: "h100" })).status, 400); }); test("serves the live facts without its internal clock", async () => { const { status, body } = await get(make(), "/v1/market"); assert.equal(status, 200); assert.equal(body.nvda, 151.2); assert.equal("at" in body, false); }); test("refuses every rental while no GPU is listed", async () => { const r = await make().handle({ method: "POST", path: "/v1/rent", ip: "1.1.1.1" }); assert.equal(r.status, 503); assert.equal(JSON.parse(r.body).error, "not-open"); }); test("answers nothing else, limits reads per address, and handles CORS", async () => { const app = make(world(), { readsPer10s: 3, origins: ["https://idle-elysium.vercel.app"] }); assert.equal((await get(app, "/v1/nope")).status, 404); assert.equal((await app.handle({ method: "DELETE", path: "/v1/gpus", ip: "9.9.9.9" })).status, 404); for (let i = 0; i < 3; i++) assert.equal((await get(app, "/v1/health", {}, "2.2.2.2")).status, 200); assert.equal((await get(app, "/v1/health", {}, "2.2.2.2")).status, 429); assert.equal((await get(app, "/v1/health", {}, "3.3.3.3")).status, 200); const pre = await app.handle({ method: "OPTIONS", path: "/v1/gpus", origin: "https://evil.example" }); assert.equal(pre.status, 204); assert.equal(pre.headers["Access-Control-Allow-Origin"], "https://idle-elysium.vercel.app"); }); });