// The day's maths, in integers only. The keeper and the public verifier both run this file, // so anyone with a day's inputs file gets the same root. // // For each linked wallet, the day's share is the smallest of three numbers: // 1. its slice of the pot by fees: pot * fee / total fees of all counted wallets // 2. its supply cap: pot * balance / total supply // 3. its fees cap: the fees it paid, in HYPE, times capBps / 10000 // Whatever the shares do not add up to buys the coin back and burns it. import { encodeAbiParameters, keccak256, concat, toBytes, type Hex } from "viem"; export const INPUTS_VERSION = 1; export type WalletInput = { holder: string; // lowercase 0x, the Elysium wallet that holds the coin hyperliquid: string; // lowercase 0x, the linked Hyperliquid address balanceStartWei: string; // coin balance at the day's first snapshot ("0" on launch day, unused) balanceEndWei: string; // coin balance at the day's last block fills: number; // perps fills counted feeUsd6: string; // Hyperliquid perps fees paid in the day, in millionths of a dollar }; export type EpochInputs = { version: number; day: number; // UTC day number: unix seconds / 86400 windowStartMs: number; windowEndMs: number; // exclusive chainId: number; contract: string; token: string; startBlock: string; // last block before the day began endBlock: string; // last block of the day useStartBalance: boolean; // false on the coin's launch day: nobody could hold at its start potWei: string; supplyWei: string; // total supply at endBlock hypeUsd6: string; // HYPE in millionths of a dollar: the day's closing price on Hyperliquid hypeSource: string; capBps: number; // 10000 = up to 100% of fees paid feeRule: string; wallets: WalletInput[]; }; export type WalletResult = WalletInput & { balanceWei: string; // the balance counted byFeesWei: string; supplyCapWei: string; feesCapWei: string; amountWei: string; limit: "fees share" | "supply cap" | "fees cap" | "none"; }; export type EpochResult = { totalFeeUsd6: string; allocatedWei: string; toBurnWei: string; root: Hex; wallets: WalletResult[]; }; export const FEE_RULE = "Perps fills only (spot pairs are left out). Per fill: fee minus builderFee, in USDC or another dollar stablecoin. Maker rebates count as negative. The day's sum, never below zero."; const min = (a: bigint, b: bigint) => (a < b ? a : b); export const ZERO_ROOT = `0x${"0".repeat(64)}` as Hex; export const leafOf = (day: number, holder: string, amountWei: bigint): Hex => keccak256(keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "address" }, { type: "uint256" }], [BigInt(day), holder as Hex, amountWei]))); const pair = (a: Hex, b: Hex): Hex => (BigInt(a) < BigInt(b) ? keccak256(concat([a, b])) : keccak256(concat([b, a]))); /** Sorted-pair merkle tree. An odd node moves up unchanged. Returns the root and each leaf's proof. */ export const merkle = (leaves: Hex[]): { root: Hex; proofs: Hex[][] } => { if (!leaves.length) return { root: ZERO_ROOT, proofs: [] }; const proofs: Hex[][] = leaves.map(() => []); let layer = leaves.map((hash, i) => ({ hash, members: [i] })); while (layer.length > 1) { const next: typeof layer = []; for (let i = 0; i < layer.length; i += 2) { const a = layer[i]; const b = layer[i + 1]; if (!b) { next.push(a); continue; } for (const m of a.members) proofs[m].push(b.hash); for (const m of b.members) proofs[m].push(a.hash); next.push({ hash: pair(a.hash, b.hash), members: [...a.members, ...b.members] }); } layer = next; } return { root: layer[0].hash, proofs }; }; export const verifyProof = (leaf: Hex, proof: Hex[], root: Hex) => proof.reduce((n, p) => pair(n, p), leaf) === root; /** Work out every wallet's share of the day. Pure: the same inputs always give the same result. */ export const computeEpoch = (inp: EpochInputs): EpochResult => { const pot = BigInt(inp.potWei); const supply = BigInt(inp.supplyWei); const px = BigInt(inp.hypeUsd6); const cap = BigInt(inp.capBps); const rows = inp.wallets.map((w) => { const end = BigInt(w.balanceEndWei); const balance = inp.useStartBalance ? min(BigInt(w.balanceStartWei), end) : end; const fee = BigInt(w.feeUsd6) > 0n ? BigInt(w.feeUsd6) : 0n; return { w, balance, fee, counted: balance > 0n && fee > 0n }; }); const totalFee = rows.reduce((s, r) => (r.counted ? s + r.fee : s), 0n); let allocated = 0n; const wallets: WalletResult[] = rows.map(({ w, balance, fee, counted }) => { const byFees = counted && totalFee > 0n ? (pot * fee) / totalFee : 0n; const supplyCap = supply > 0n ? (pot * balance) / supply : 0n; const feesCap = px > 0n ? (fee * 10n ** 18n * cap) / (px * 10_000n) : 0n; const amount = counted ? min(byFees, min(supplyCap, feesCap)) : 0n; allocated += amount; const limit: WalletResult["limit"] = !counted || amount === 0n ? "none" : amount === feesCap ? "fees cap" : amount === supplyCap ? "supply cap" : "fees share"; return { ...w, balanceWei: balance.toString(), byFeesWei: byFees.toString(), supplyCapWei: supplyCap.toString(), feesCapWei: feesCap.toString(), amountWei: amount.toString(), limit }; }); if (allocated > pot) throw new Error("shares add up to more than the pot"); const paid = wallets.filter((w) => BigInt(w.amountWei) > 0n).sort((a, b) => (a.holder < b.holder ? -1 : 1)); const { root } = merkle(paid.map((w) => leafOf(inp.day, w.holder, BigInt(w.amountWei)))); return { totalFeeUsd6: totalFee.toString(), allocatedWei: allocated.toString(), toBurnWei: (pot - allocated).toString(), root, wallets }; }; /** Proofs for the wallets with a share, in the tree's order (holder address ascending). */ export const proofsOf = (day: number, result: EpochResult) => { const paid = result.wallets.filter((w) => BigInt(w.amountWei) > 0n).sort((a, b) => (a.holder < b.holder ? -1 : 1)); const { proofs } = merkle(paid.map((w) => leafOf(day, w.holder, BigInt(w.amountWei)))); return paid.map((w, i) => ({ holder: w.holder, hyperliquid: w.hyperliquid, amountWei: w.amountWei, feeUsd6: w.feeUsd6, proof: proofs[i] })); }; /** The published file: the inputs, then the result worked out from them. Its bytes are hashed on chain. */ export const inputsFile = (inp: EpochInputs, result: EpochResult) => JSON.stringify({ inputs: inp, result }, null, 1); export const hashFile = (file: string): Hex => keccak256(toBytes(file)); // ---- Hyperliquid fills to a day's fee ---- export type Fill = { coin: string; time: number; fee: string; feeToken?: string; builderFee?: string; tid?: number; oid?: number }; const STABLES = new Set(["USDC", "USDH", "USDT0", "USDE"]); /** A decimal string to millionths, exactly (no floats). */ export const toUsd6 = (v: string): bigint => { const neg = v.startsWith("-"); const [whole, frac = ""] = (neg ? v.slice(1) : v).split("."); const n = BigInt(whole || "0") * 1_000_000n + BigInt((frac + "000000").slice(0, 6) || "0"); return neg ? -n : n; }; export const isPerp = (coin: string) => !coin.startsWith("@") && !coin.includes("/"); /** The day's perps fees from a list of fills: fee minus builder fee, summed, never below zero. */ export const feeOfFills = (fills: Fill[]) => { let sum = 0n; let counted = 0; for (const f of fills) { if (!isPerp(f.coin) || !STABLES.has(f.feeToken ?? "USDC")) continue; sum += toUsd6(f.fee) - (f.builderFee ? toUsd6(f.builderFee) : 0n); counted += 1; } return { feeUsd6: sum > 0n ? sum : 0n, fills: counted }; };