import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { formatAmount, parseAmount, priceEquity, readTopup, TRANSFER_TOPIC } from "../lib/credits.mjs"; import { createFakeChain } from "../lib/chain-fake.mjs"; import * as E from "../lib/engine.mjs"; import { memoryStore, transact } from "../lib/store.mjs"; import { A, B, T0, addr } from "./helpers.mjs"; const USDC = "0xb47c4c8f73f009cc0c0d3f92b388d13e293f0b65"; const EQNVDA = "0x5ceff5c7316067b81b537a9ae011d6882f0a558a"; const OTHER_TOKEN = addr(0x70c3); const TREASURY = addr(0x7ea5); const world = () => createFakeChain({ usdc: USDC, env: {} }); const read = (chain, txHash, over = {}) => readTopup({ rpc: chain.rpc, txHash, from: A, treasury: TREASURY, usdc: USDC, equity: EQNVDA, chainId: 99901, ...over }); const pad = (a) => "0x" + a.slice(2).padStart(64, "0"); const log = (token, from, to, amount) => ({ address: token, topics: [TRANSFER_TOPIC, pad(from), pad(to)], data: pad("0x" + BigInt(amount).toString(16)) }); describe("reading a top-up from the chain", () => { test("a confirmed USDC transfer from the wallet to the treasury is worth its amount, one base unit per micro-dollar", async () => { const chain = world(); const tx = chain.transfer({ from: A, to: TREASURY, amount: 25_500_000n }); chain.mine(1); assert.deepEqual(await read(chain, tx), { ok: true, token: "USDC", tokenAddress: USDC, amount: 25_500_000n, block: 1001, confirmations: 2 }); assert.equal((await read(chain, tx.toUpperCase().replace("0X", "0x"))).ok, true, "the hash is taken in any case"); }); test("too few confirmations: not yet, and it says how many", async () => { const chain = world(); const tx = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n }); const early = await read(chain, tx); assert.equal(early.error, "unconfirmed"); assert.equal(early.confirmations, 1); assert.equal(early.needed, 2); chain.mine(1); assert.equal((await read(chain, tx)).ok, true); assert.equal((await read(chain, tx, { minConfirmations: 5 })).error, "unconfirmed"); }); test("the wrong sender, the wrong token and the wrong recipient are each refused by name", async () => { const chain = world(); const bySomeoneElse = chain.transfer({ from: B, to: TREASURY, amount: 1_000_000n }); const otherToken = chain.transfer({ token: OTHER_TOKEN, from: A, to: TREASURY, amount: 1_000_000n }); const elsewhere = chain.transfer({ from: A, to: B, amount: 1_000_000n }); chain.mine(5); assert.equal((await read(chain, bySomeoneElse)).error, "wrong-sender"); assert.equal((await read(chain, otherToken)).error, "wrong-token"); assert.equal((await read(chain, elsewhere)).error, "wrong-recipient"); // The same transaction is fine for the wallet that did send it. assert.equal((await read(chain, bySomeoneElse, { from: B })).ok, true); }); test("a reverted transaction, an unknown one and a malformed hash credit nothing", async () => { const chain = world(); const reverted = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n, status: 0 }); chain.mine(5); assert.equal((await read(chain, reverted)).error, "tx-reverted"); assert.equal((await read(chain, "0x" + "ab".repeat(32))).error, "tx-not-found"); for (const bad of ["0x12", "", null, undefined, "ab".repeat(32), 7]) assert.equal((await read(chain, bad)).error, "invalid"); }); test("only real Transfer logs count: an Approval, an NFT transfer or a zero amount are not a top-up", async () => { const chain = world(); const pad = (a) => "0x" + a.slice(2).padStart(64, "0"); const approval = { address: USDC, topics: ["0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925", pad(A), pad(TREASURY)], data: pad("0x" + (5_000_000).toString(16)) }; const nft = { address: USDC, topics: [TRANSFER_TOPIC, pad(A), pad(TREASURY), pad("0x01")], data: "0x" }; const decoy = chain.transfer({ from: A, to: B, amount: 1n, extraLogs: [approval, nft] }); const zero = chain.transfer({ from: A, to: TREASURY, amount: 0n }); chain.mine(5); assert.equal((await read(chain, decoy)).error, "wrong-recipient"); assert.equal((await read(chain, zero)).error, "no-transfer"); }); test("an EQNVDA transfer to the treasury is recognised from the receipt, in its own base units", async () => { const chain = world(); const tx = chain.transfer({ token: EQNVDA, from: A, to: TREASURY, amount: 150_000_000n }); // 1.5 EQNVDA, 8 decimals chain.mine(1); assert.deepEqual(await read(chain, tx), { ok: true, token: "EQNVDA", tokenAddress: EQNVDA, amount: 150_000_000n, block: 1001, confirmations: 2 }); // The same refusals hold for it: another sender, another recipient, too few confirmations. assert.equal((await read(chain, tx, { from: B })).error, "wrong-sender"); const elsewhere = chain.transfer({ token: EQNVDA, from: A, to: B, amount: 1n }); assert.equal((await read(chain, elsewhere)).error, "wrong-recipient"); const fresh = chain.transfer({ token: EQNVDA, from: A, to: TREASURY, amount: 1n }); assert.equal((await read(chain, fresh)).error, "unconfirmed"); // A reader that was not given the token does not take it. assert.equal((await read(chain, tx, { equity: null })).error, "wrong-token"); }); test("exactly one transfer to the treasury: two of them, of the same token or of both, are refused rather than guessed at", async () => { const chain = world(); const twoUsdc = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n, extraLogs: [log(USDC, A, TREASURY, 250_000)] }); const both = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n, extraLogs: [log(EQNVDA, A, TREASURY, 50_000_000)] }); const twoEquity = chain.transfer({ token: EQNVDA, from: A, to: TREASURY, amount: 1n, extraLogs: [log(EQNVDA, A, TREASURY, 2)] }); chain.mine(3); for (const tx of [twoUsdc, both, twoEquity]) { const r = await read(chain, tx); assert.equal(r.error, "ambiguous-transfer"); assert.equal(r.transfers, 2); } // Other movements in the same transaction do not count: only transfers of the two tokens, from the wallet, to the treasury. const noise = chain.transfer({ from: A, to: TREASURY, amount: 7_000_000n, extraLogs: [log(USDC, B, TREASURY, 9), log(EQNVDA, A, B, 9), log(OTHER_TOKEN, A, TREASURY, 9)] }); chain.mine(1); assert.deepEqual([(await read(chain, noise)).token, (await read(chain, noise)).amount], ["USDC", 7_000_000n]); }); test("a node that is down, or that answers for another chain, credits nothing", async () => { const chain = world(); const tx = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n }); chain.mine(1); chain.down = true; assert.equal((await read(chain, tx)).error, "chain-unreachable"); chain.down = false; assert.equal((await read(chain, tx, { chainId: 1 })).error, "chain-unreachable"); const liar = async (method, params) => (method === "eth_getTransactionReceipt" ? { ...(await chain.rpc(method, params)), transactionHash: "0x" + "cd".repeat(32) } : chain.rpc(method, params)); assert.equal((await read(chain, tx, { rpc: liar })).error, "chain-unreachable"); }); test("a transaction older than the deployment takes is refused", async () => { const chain = world(); const tx = chain.transfer({ from: A, to: TREASURY, amount: 1_000_000n }); chain.mine(1); assert.equal((await read(chain, tx, { minBlock: 1002 })).error, "too-old"); assert.equal((await read(chain, tx, { minBlock: 1001 })).ok, true); }); test("the fake chain refuses to exist on a deployment", () => { assert.throws(() => createFakeChain({ usdc: USDC, env: { VERCEL: "1" } }), /does not start on a deployment/); assert.throws(() => createFakeChain({ usdc: USDC, env: { NODE_ENV: "production" } }), /does not start on a deployment/); }); }); describe("pricing EQNVDA", () => { const base = { amount: 150_000_000n, decimals: 8, poolPriceUsd: 151.368838, markUsd: 151.305, haircutBps: 100, maxGapBps: 300 }; test("the lower of the pool and the mark, less the haircut, rounded down to the micro-dollar", () => { // 1.5 EQNVDA at min(151.368838, 151.305) = 151.305, less 1 %: 224.688 (and 0.000925 that is dropped, not rounded up). assert.deepEqual(priceEquity(base), { ok: true, micro: 224_687_925, priceUsd: 151.305, poolPriceUsd: 151.368838, markUsd: 151.305, haircutBps: 100, gapBps: 4 }); // The pool below the mark: the pool is the price. const low = priceEquity({ ...base, poolPriceUsd: 150 }); assert.deepEqual([low.priceUsd, low.micro], [150, 222_750_000]); // A pool pushed above the mark buys nothing more: the mark caps it. assert.equal(priceEquity({ ...base, poolPriceUsd: 155 }).micro, priceEquity({ ...base, poolPriceUsd: 151.305 }).micro); assert.equal(priceEquity({ ...base, haircutBps: 0 }).micro, 226_957_500); assert.equal(priceEquity({ ...base, haircutBps: 2500 }).micro, 170_218_125); }); test("rounds down, never up: the smallest amounts are worth what they are worth, or nothing", () => { // One base unit (1e-8 EQNVDA) at 151.305 less 1 % is 1.4979 micro-dollars: 1. assert.equal(priceEquity({ ...base, amount: 1n }).micro, 1); // At a price under 1.01 USD one base unit is under a micro-dollar: 0, and the claim route refuses it. assert.equal(priceEquity({ ...base, amount: 1n, poolPriceUsd: 0.99, markUsd: 1 }).micro, 0); // 0.33333333 EQNVDA: 33333333 x 151305000 x 9900 / (1e8 x 10000) = 49930649.50 micro-dollars: the half is dropped. assert.equal(priceEquity({ ...base, amount: 33_333_333n }).micro, 49_930_649); assert.equal((33_333_333n * 151_305_000n * 9_900n) / 10n ** 12n, 49_930_649n); for (const amount of [1n, 7n, 12_345_678n, 99_999_999n, 150_000_001n]) { const p = priceEquity({ ...base, amount }); const exact = (Number(amount) / 1e8) * 151.305 * 0.99 * 1e6; assert.ok(p.micro <= exact + 1e-6 && p.micro > exact - 1, String(amount)); } }); test("refused as price-unavailable when either price is missing", () => { for (const over of [{ poolPriceUsd: null }, { markUsd: null }, { poolPriceUsd: 0 }, { markUsd: NaN }, { poolPriceUsd: undefined, markUsd: undefined }, { decimals: undefined }]) { const r = priceEquity({ ...base, ...over }); assert.equal(r.ok, false); assert.equal(r.error, "price-unavailable", JSON.stringify(over)); } assert.match(priceEquity({ ...base, poolPriceUsd: null }).message, /pool on Elysium/); assert.match(priceEquity({ ...base, markUsd: null }).message, /xyz:NVDA/); }); test("refused as price-unstable when the pool and the mark differ by more than the limit, on either side", () => { // 3 % of a mark of 100 is 3: exactly at the limit passes, a micro-dollar past it does not. const at = { ...base, markUsd: 100, maxGapBps: 300 }; assert.equal(priceEquity({ ...at, poolPriceUsd: 103 }).ok, true); assert.equal(priceEquity({ ...at, poolPriceUsd: 97 }).ok, true); for (const poolPriceUsd of [103.000001, 96.999999, 50, 500]) { const r = priceEquity({ ...at, poolPriceUsd }); assert.equal(r.error, "price-unstable", String(poolPriceUsd)); assert.equal(r.maxGapBps, 300); } assert.equal(priceEquity({ ...at, poolPriceUsd: 110 }).gapBps, 1000); assert.equal(priceEquity({ ...at, poolPriceUsd: 110, maxGapBps: 1000 }).ok, true); }); test("amounts are read from and written as decimal strings, exactly", () => { assert.equal(parseAmount("1.5", 8), 150_000_000n); assert.equal(parseAmount("0.00000001", 8), 1n); assert.equal(parseAmount("25", 6), 25_000_000n); for (const bad of ["", "0", "0.0", "-1", "1e3", "1,5", ".5", "1.", "0.000000001", " 1", "abc", null, 1.5, "9".repeat(41)]) assert.equal(parseAmount(bad, 8), null, String(bad)); assert.equal(parseAmount("1.1234567", 6), null, "more decimals than the token has"); assert.equal(formatAmount(150_000_000n, 8), "1.5"); assert.equal(formatAmount(1n, 8), "0.00000001"); assert.equal(formatAmount(25_000_000n, 6), "25"); assert.equal(formatAmount(parseAmount("123.45678901", 8), 8), "123.45678901"); }); }); describe("crediting", () => { test("a replay is refused, even when two claims of the same transaction arrive at the same instant", async () => { const chain = world(); const tx = chain.transfer({ from: A, to: TREASURY, amount: 3_000_000n }); chain.mine(1); const top = await read(chain, tx); const store = memoryStore(); const claim = () => transact(store, (state) => E.claim(state, { address: A, txHash: tx, micro: Number(top.amount), block: top.block, now: T0 })); const results = await Promise.all([claim(), claim(), claim()]); assert.deepEqual(results.map((r) => r.ok).sort(), [false, false, true]); assert.ok(results.filter((r) => !r.ok).every((r) => r.error === "already-claimed")); assert.ok(store.conflicts >= 2); assert.equal(store.peek().accounts[A].credits, 3_000_000); assert.equal((await claim()).error, "already-claimed"); }); });