// The live facts the site shows next to what it says. Each one is read from a public source // anyone can ask the same question: // the HYPE mid and the Nvidia price (the xyz:NVDA market) from Hyperliquid's public API; // the head of the chain and the USDC token (symbol, decimals, supply) from Elysium itself; // EQNVDA, EQX's tokenized Nvidia share (symbol, decimals, supply), and its price in USDC in the // Uniswap v4 pool on Elysium, read from the PoolManager's own storage. // Nothing here is configured by hand: a source that does not answer gives null and is named in `errors`. import { keccak256 } from "ethers"; export const ELYSIUM = { chainId: 99901, name: "Elysium", rpc: "https://rpc.montramarkets.xyz", explorer: "https://elysium.kinetiq.xyz", // symbol() answers "USDC", decimals() 6. usdc: "0xb47c4c8f73f009cc0c0d3f92b388d13e293f0b65", // Elysium settles to HyperEVM and takes its transactions through this inbox there (the relayer posts to it). hyperEvmRpc: "https://rpc.hyperliquid.xyz/evm", inbox: "0xce59f8B65ad41C9DAE4c07A0571a39824bD92cff", // Uniswap v4 on Elysium: one PoolManager holds every pool. poolManager: "0xE2e105d3F7209A9DA11f83cCf3E7398a753823F1", // EQX's tokenized NVIDIA share. symbol() answers "EQNVDA", decimals() 8. Neither is assumed: both are read. eqnvda: "0x5CeFf5C7316067b81B537a9aE011d6882f0A558A", // The EQNVDA / USDC pool, made by Pegisium (its hook is below). EQNVDA sorts before USDC, so it is // currency0 and the pool's price is USDC per EQNVDA. eqnvdaPoolId: "0x6fd22621b9baa37a4162a7893311f45f2ff5847f09565d7b1d1a8d12feb923db", eqnvdaPoolHook: "0xEb7316be9bf3733d34Ec50ee0a8867a0B021a0C8", }; // ---- Reading a Uniswap v4 pool's price without a contract call of its own ---- // The PoolManager keeps its pools in a mapping at storage slot 6 (v4-core, StateLibrary.POOLS_SLOT) and lets // anyone read a slot with extsload(bytes32). The first word of a pool's state packs, from the low bits up: // sqrtPriceX96 (160 bits), tick (24, signed), protocolFee (24), lpFee (24). Its liquidity is three slots further. export const EXTSLOAD = "0x1e2eaeaf"; // extsload(bytes32) const POOLS_SLOT = 6n; const hex64 = (n) => BigInt(n).toString(16).padStart(64, "0"); /** The storage slot of a pool's first word: keccak256(abi.encode(poolId, uint256(6))). */ export function poolSlot(poolId) { if (!/^0x[0-9a-fA-F]{64}$/.test(poolId ?? "")) throw new Error("not a pool id"); return keccak256(poolId.toLowerCase() + hex64(POOLS_SLOT)); } /** What the first word of a pool says. A pool that was never initialised has a price of zero. */ export function decodeSlot0(word) { const v = BigInt(word); const tick = Number((v >> 160n) & 0xffffffn); return { sqrtPriceX96: v & ((1n << 160n) - 1n), tick: tick >= 0x800000 ? tick - 0x1000000 : tick, protocolFee: Number((v >> 184n) & 0xffffffn), lpFee: Number((v >> 208n) & 0xffffffn), }; } /** * The price of one whole token0 in token1, in millionths of a token1, rounded down. * sqrtPriceX96 is sqrt(raw token1 per raw token0) times 2^96, so the price is its square over 2^192, * scaled by the decimals of the two tokens. */ export function poolPriceMicro(sqrtPriceX96, decimals0, decimals1) { const s = BigInt(sqrtPriceX96); return (s * s * 10n ** BigInt(decimals0) * 1_000_000n) / ((1n << 192n) * 10n ** BigInt(decimals1)); } /** How far the pool is from the mark, in basis points of the mark. Null when either is missing. */ export function gapBps(poolPriceUsd, markUsd) { return poolPriceUsd > 0 && markUsd > 0 ? Math.round((Math.abs(poolPriceUsd - markUsd) / markUsd) * 10_000) : null; } /** An ABI-encoded string (offset, length, bytes) as text. */ export function abiText(hex) { const h = String(hex ?? "").replace(/^0x/, ""); if (h.length < 128) return ""; const len = parseInt(h.slice(64, 128), 16); if (!(len >= 0) || len > 64) return ""; return Buffer.from(h.slice(128, 128 + 2 * len), "hex").toString("utf8"); } /** A token amount in base units as a decimal string, without trailing zeros. */ export function units(value, decimals) { const v = BigInt(value); const base = 10n ** BigInt(decimals); const frac = (v % base).toString().padStart(decimals, "0").replace(/0+$/, ""); return (v / base).toString() + (frac ? "." + frac : ""); } /** * @param {{fetch?:typeof fetch, url?:string, rpc?:string, chainId?:number, usdc?:string, * ttlMs?:number, now?:()=>number, nvdaDex?:string, nvdaCoin?:string, * poolManager?:string, eqnvda?:string, eqnvdaPoolId?:string}} o */ export function makeMarket(o = {}) { const f = o.fetch ?? fetch; const hl = o.url ?? "https://api.hyperliquid.xyz/info"; const node = o.rpc ?? ELYSIUM.rpc; const chainId = o.chainId ?? ELYSIUM.chainId; const usdcAddress = o.usdc ?? ELYSIUM.usdc; const poolManager = o.poolManager ?? ELYSIUM.poolManager; const equityToken = o.eqnvda ?? ELYSIUM.eqnvda; const equityPoolId = o.eqnvdaPoolId ?? ELYSIUM.eqnvdaPoolId; const nvdaDex = o.nvdaDex ?? "xyz"; const nvdaCoin = o.nvdaCoin ?? "xyz:NVDA"; const ttl = o.ttlMs ?? 20_000; const now = o.now ?? Date.now; let cache = null; let flight = null; const post = async (url, body) => { const r = await f(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); if (!r.ok) throw new Error("answered " + r.status); return r.json(); }; const rpc = async (method, params = []) => { const j = await post(node, { jsonrpc: "2.0", id: 1, method, params }); if (j.error) throw new Error(j.error.message ?? "rpc error"); return j.result; }; const call = (to, data) => rpc("eth_call", [{ to, data }, "latest"]); async function hype() { const mid = Number((await post(hl, { type: "allMids" })).HYPE); if (!(mid > 0)) throw new Error("no HYPE mid"); return mid; } async function nvda() { const mid = Number((await post(hl, { type: "allMids", dex: nvdaDex }))[nvdaCoin]); if (!(mid > 0)) throw new Error("no " + nvdaCoin + " price"); return mid; } async function chain() { const [id, head] = await Promise.all([rpc("eth_chainId"), rpc("eth_getBlockByNumber", ["latest", false])]); const got = parseInt(id, 16); if (got !== chainId) throw new Error(`the node answers chain ${got}, expected ${chainId}`); return { chainId: got, block: parseInt(head.number, 16), blockTime: new Date(parseInt(head.timestamp, 16) * 1000).toISOString() }; } async function usdc() { const [symbol, decimals, supply] = await Promise.all([call(usdcAddress, "0x95d89b41"), call(usdcAddress, "0x313ce567"), call(usdcAddress, "0x18160ddd")]); const d = parseInt(decimals, 16); if (!(d >= 0 && d <= 36)) throw new Error("decimals() gave no number"); return { address: usdcAddress, symbol: abiText(symbol), decimals: d, totalSupply: units(BigInt(supply), d) }; } /** EQNVDA as the chain describes it, and what the pool says one is worth in USDC. */ async function equity() { const slot = poolSlot(equityPoolId); const [symbol, decimals, supply, usdcDecimals, word, liquidity] = await Promise.all([ call(equityToken, "0x95d89b41"), call(equityToken, "0x313ce567"), call(equityToken, "0x18160ddd"), call(usdcAddress, "0x313ce567"), call(poolManager, EXTSLOAD + slot.slice(2)), call(poolManager, EXTSLOAD + hex64(BigInt(slot) + 3n)), ]); const name = abiText(symbol); if (name !== "EQNVDA") throw new Error(`the token answers symbol "${name}", not EQNVDA`); const d = parseInt(decimals, 16); const d1 = parseInt(usdcDecimals, 16); if (!(d >= 0 && d <= 36) || !(d1 >= 0 && d1 <= 36)) throw new Error("decimals() gave no number"); const { sqrtPriceX96 } = decodeSlot0(word); if (sqrtPriceX96 === 0n) throw new Error("the pool has no price (not initialised, or not at this id)"); const micro = poolPriceMicro(sqrtPriceX96, d, d1); if (micro <= 0n || micro > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("the pool price is out of range"); return { symbol: name, token: equityToken, decimals: d, totalSupply: units(BigInt(supply), d), poolManager, poolId: equityPoolId, poolPriceUsd: Number(micro) / 1e6, poolLiquidity: BigInt(liquidity).toString() }; } async function read() { const at = now(); const names = ["hype", "nvda", "chain", "usdc", "equity"]; const got = await Promise.allSettled([hype(), nvda(), chain(), usdc(), equity()]); const val = (i) => (got[i].status === "fulfilled" ? got[i].value : null); const errors = got.flatMap((g, i) => (g.status === "rejected" ? [`${names[i]}: ${g.reason?.message ?? g.reason}`] : [])); return { hypeMid: val(0), nvda: val(1), nvdaMarket: nvdaCoin, chain: val(2), usdc: val(3), // The pool's price next to the mark it is compared with. `markUsd` and `gapBps` are null when Hyperliquid // did not answer; the whole object is null when the token or the pool could not be read. equity: val(4) && { ...val(4), markUsd: val(1), gapBps: gapBps(val(4).poolPriceUsd, val(1)), source: `PoolManager.extsload on Elysium (pool price), Hyperliquid ${nvdaCoin} (mark)` }, asOf: new Date(at).toISOString(), sources: { prices: hl, chain: node }, errors, at, }; } /** Cached for a few seconds; simultaneous callers share one read. A read with errors is not cached. */ return async function market() { if (cache && now() - cache.at < ttl) return cache; flight ??= read().finally(() => { flight = null; }); const m = await flight; if (m.errors.length === 0) cache = m; return m; }; }