// Credits are bought on Elysium: the wallet sends USDC, or EQNVDA (EQX's tokenized Nvidia share), to the // treasury, then gives the transaction hash. This file reads that transaction from the chain and says what // it holds, and prices EQNVDA. It credits nothing itself: the engine does, and it refuses a hash it has // already credited. // // A top-up counts when the receipt shows a successful Transfer of one of the two tokens from the signed-in // wallet to the treasury, buried under at least `minConfirmations` blocks, and exactly one such transfer: // a transaction that holds two is refused rather than guessed at. // USDC has 6 decimals, so one base unit is one micro-dollar: it is credited as it is. // EQNVDA is credited at the lower of two prices, less a haircut, rounded down to the micro-dollar: // the Uniswap v4 pool on Elysium and Hyperliquid's xyz:NVDA mark. Taking the lower one means that pushing // the pool's price up buys nothing. It is priced when it is claimed, not when it was sent. // Native HYPE top-ups are not read. // // What this trusts: the RPC node (a node that lies about a receipt could mint credits), and for EQNVDA the // two price sources. export const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; const no = (error, message, extra = {}) => ({ ok: false, error, message, ...extra }); const topicAddress = (t) => "0x" + String(t ?? "").slice(-40).toLowerCase(); /** * @param {{rpc:(method:string, params:any[])=>Promise, txHash:string, from:string, treasury:string, usdc:string, * equity?:string|null, chainId:number, minConfirmations?:number, minBlock?:number}} o * addresses in lower case. `equity` is the EQNVDA token; without it only USDC is taken. * @returns {Promise<{ok:true, token:"USDC"|"EQNVDA", tokenAddress:string, amount:bigint, block:number, confirmations:number} * | {ok:false, error:string, message:string}>} `amount` is in the token's base units */ export async function readTopup({ rpc, txHash, from, treasury, usdc, equity = null, chainId, minConfirmations = 2, minBlock = 0 }) { if (typeof txHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(txHash)) return no("invalid", "txHash must be a transaction hash."); const hash = txHash.toLowerCase(); const accepted = equity ? "USDC and EQNVDA" : "USDC"; let id, receipt, head; try { [id, receipt, head] = await Promise.all([rpc("eth_chainId", []), rpc("eth_getTransactionReceipt", [hash]), rpc("eth_blockNumber", [])]); } catch (e) { return no("chain-unreachable", "Elysium did not answer. Nothing was credited; try again.", { detail: String(e?.message ?? e) }); } if (parseInt(id, 16) !== chainId) return no("chain-unreachable", `The node answers for chain ${parseInt(id, 16)}, not ${chainId}. Nothing was credited.`); if (!receipt || !receipt.blockNumber) return no("tx-not-found", "No such transaction on Elysium yet. If you just sent it, wait a few seconds."); if (String(receipt.transactionHash ?? hash).toLowerCase() !== hash) return no("chain-unreachable", "The node answered for another transaction. Nothing was credited."); if (receipt.status !== "0x1") return no("tx-reverted", "This transaction failed on chain. Nothing was sent, nothing is credited."); const transfers = (receipt.logs ?? []).filter((l) => l.topics?.length === 3 && l.topics[0] === TRANSFER_TOPIC); const tokenOf = (l) => { const a = String(l.address).toLowerCase(); return a === usdc ? "USDC" : equity && a === equity ? "EQNVDA" : null; }; const sender = (l) => topicAddress(l.topics[1]) === from; const toTreasury = (l) => topicAddress(l.topics[2]) === treasury; const good = transfers.filter((l) => tokenOf(l) && sender(l) && toTreasury(l)); if (good.length === 0) { if (transfers.some((l) => !tokenOf(l) && sender(l) && toTreasury(l))) return no("wrong-token", `This transaction sent another token. Only ${accepted} on Elysium buy credits.`); if (transfers.some((l) => tokenOf(l) && toTreasury(l))) return no("wrong-sender", "This transfer was sent by another wallet. A top-up is credited to the wallet that sent it: sign in with that one."); if (transfers.some((l) => tokenOf(l) && sender(l))) return no("wrong-recipient", "This transfer did not go to the Idle treasury."); return no("no-transfer", `This transaction holds no ${accepted} transfer to the Idle treasury.`); } if (good.length > 1) return no("ambiguous-transfer", "This transaction holds more than one transfer to the Idle treasury. A top-up is one transfer in one transaction; nothing was credited.", { transfers: good.length }); const [log] = good; const amount = BigInt(log.data && log.data !== "0x" ? log.data : "0x0"); if (amount <= 0n || amount > BigInt(Number.MAX_SAFE_INTEGER)) return no("no-transfer", "This transfer carries no usable amount."); const block = parseInt(receipt.blockNumber, 16); if (block < minBlock) return no("too-old", "This transaction is older than this deployment takes."); const confirmations = parseInt(head, 16) - block + 1; if (!(confirmations >= minConfirmations)) return no("unconfirmed", `Seen on chain with ${Math.max(0, confirmations)} of ${minConfirmations} confirmations. Try again in a few seconds.`, { confirmations: Math.max(0, confirmations), needed: minConfirmations }); return { ok: true, token: tokenOf(log), tokenAddress: String(log.address).toLowerCase(), amount, block, confirmations }; } /** * What an amount of EQNVDA is worth in credits. * price = min(pool, mark), each taken to the micro-dollar * credits = floor(amount × price × (10000 - haircutBps) / 10000), in micro-dollars * Refused with `price-unavailable` when either price is missing, and with `price-unstable` when the two differ * by more than `maxGapBps` of the mark: then one of them is wrong, and nobody should be credited on a guess. * @param {{amount:bigint, decimals:number, poolPriceUsd:number|null, markUsd:number|null, haircutBps:number, maxGapBps:number}} o * `amount` in base units * @returns {{ok:true, micro:number, priceUsd:number, poolPriceUsd:number, markUsd:number, haircutBps:number, gapBps:number} * | {ok:false, error:string, message:string}} */ export function priceEquity({ amount, decimals, poolPriceUsd, markUsd, haircutBps, maxGapBps }) { if (!(poolPriceUsd > 0) || !(markUsd > 0) || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) { return no("price-unavailable", "EQNVDA cannot be priced right now: " + (!(poolPriceUsd > 0) ? "the pool on Elysium could not be read" : !(markUsd > 0) ? "Hyperliquid's xyz:NVDA mark could not be read" : "the token could not be read") + ". Nothing was credited; try again.", { poolPriceUsd: poolPriceUsd ?? null, markUsd: markUsd ?? null }); } const pool = BigInt(Math.round(poolPriceUsd * 1e6)); const mark = BigInt(Math.round(markUsd * 1e6)); const diff = pool > mark ? pool - mark : mark - pool; const gapBps = Number((diff * 10_000n) / mark); if (diff * 10_000n > BigInt(maxGapBps) * mark) { return no("price-unstable", `The pool (${poolPriceUsd} USD) and the mark (${markUsd} USD) differ by more than ${maxGapBps / 100} %. Nothing was credited; try again when they agree.`, { poolPriceUsd, markUsd, gapBps, maxGapBps }); } const price = pool < mark ? pool : mark; const micro = (BigInt(amount) * price * BigInt(10_000 - haircutBps)) / (10n ** BigInt(decimals) * 10_000n); if (micro > BigInt(Number.MAX_SAFE_INTEGER)) return no("invalid", "Amount too large."); return { ok: true, micro: Number(micro), priceUsd: Number(price) / 1e6, poolPriceUsd, markUsd, haircutBps, gapBps }; } /** A decimal string ("1.5") as base units, or null when it is not a positive amount the token can carry. */ export function parseAmount(text, decimals) { if (typeof text !== "string" || text.length > 40 || !/^\d+(\.\d+)?$/.test(text)) return null; const [whole, frac = ""] = text.split("."); if (frac.length > decimals) return null; const v = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(frac.padEnd(decimals, "0") || "0"); return v > 0n && v <= BigInt(Number.MAX_SAFE_INTEGER) ? v : null; } /** Base units as a decimal string, without trailing zeros. */ export function formatAmount(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 : ""); }