// The credits contract as the API reads it, and what the relayer agrees to carry to it. // The chain here is a stand-in that answers eth_call the way IdleCredits and two ERC-20 tokens do, // from a small state held in memory. The contract itself is tested in onchain/ (81 tests, on Hardhat). import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { Interface, Wallet, getAddress } from "ethers"; import { CREDITS_ABI, ELYSIUM_CREDITS, readCredits, readCreditsAccount } from "../lib/contract.mjs"; import { checkTx, createRelayer, carries } from "../lib/relayer.mjs"; import { world } from "./world.mjs"; const USDC = "0xb47c4c8f73f009cc0c0d3f92b388d13e293f0b65"; const EQNVDA = "0x5ceff5c7316067b81b537a9ae011d6882f0a558a"; const CREDITS = ELYSIUM_CREDITS.address.toLowerCase(); const OPERATOR = "0x" + "0b".repeat(20); const ALICE = "0x" + "a1".repeat(20); const TREASURY = "0x" + "7e".repeat(20); const credits = new Interface(CREDITS_ABI); const erc20 = new Interface([ "function balanceOf(address account) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function approve(address spender, uint256 value) returns (bool)", "function transfer(address to, uint256 value) returns (bool)", ]); const cfg = { address: CREDITS, tokens: [{ symbol: "USDC", address: USDC, decimals: 6 }, { symbol: "EQNVDA", address: EQNVDA, decimals: 8 }] }; /** A chain that answers for the contract and its two tokens. `state` can be changed between calls. */ function fakeChain(state = {}) { const s = { code: "0x6080", usdc: USDC, eqnvda: EQNVDA, operator: OPERATOR, delay: 3600n, total: { [USDC]: 25_000_000n, [EQNVDA]: 0n }, earned: { [USDC]: 1_500_000n, [EQNVDA]: 0n }, tokenBalance: { [USDC]: 26_500_000n, [EQNVDA]: 0n }, wallet: { [USDC]: 40_000_000n, [EQNVDA]: 150_000_000n }, allowance: { [USDC]: 10_000_000n, [EQNVDA]: 0n }, inContract: { [USDC]: 25_000_000n, [EQNVDA]: 0n }, requested: { [USDC]: 5_000_000n, [EQNVDA]: 0n }, unlockAt: 1_800_000_000n, calls: 0, ...state, }; const rpc = async (method, [call] = []) => { if (method === "eth_getCode") return s.code; if (method !== "eth_call") throw { code: -32000, message: "unexpected " + method }; s.calls++; const to = call.to.toLowerCase(); if (to === CREDITS) { const p = credits.parseTransaction({ data: call.data }); const token = p.args.token?.toLowerCase() ?? p.args[p.args.length - 1]?.toLowerCase?.(); const out = { usdc: () => [s.usdc], eqnvda: () => [s.eqnvda], operator: () => [s.operator], pendingOperator: () => ["0x" + "0".repeat(40)], withdrawalDelay: () => [s.delay], totalBalance: () => [s.total[token]], earned: () => [s.earned[token]], balanceOf: () => [s.inContract[token]], available: () => [s.inContract[token] - s.requested[token]], chargeable: () => [s.inContract[token]], pendingWithdrawal: () => (s.requested[token] > 0n ? [s.requested[token], s.unlockAt] : [0n, 0n]), }[p.name](); return credits.encodeFunctionResult(p.name, out); } const p = erc20.parseTransaction({ data: call.data }); if (p.name === "balanceOf") return erc20.encodeFunctionResult("balanceOf", [p.args.account.toLowerCase() === CREDITS ? s.tokenBalance[to] : s.wallet[to]]); if (p.name === "allowance") return erc20.encodeFunctionResult("allowance", [s.allowance[to]]); throw { code: 3, message: "execution reverted" }; }; return { rpc, state: s }; } describe("reading the credits contract", () => { test("what it holds, who can charge it, and how long a withdrawal waits", async () => { const k = await readCredits(fakeChain().rpc, cfg); assert.equal(k.deployed, true); assert.equal(k.address, getAddress(CREDITS)); assert.equal(k.matches, true); assert.equal(k.operator, getAddress(OPERATOR)); assert.equal(k.pendingOperator, null); assert.equal(k.withdrawalDelaySeconds, 3600); const [usdc, eq] = k.tokens; assert.deepEqual(usdc.heldForUsers, { units: "25000000", amount: "25.0" }); assert.deepEqual(usdc.earnedByOperator, { units: "1500000", amount: "1.5" }); assert.deepEqual(usdc.tokenBalance, { units: "26500000", amount: "26.5" }); assert.equal(usdc.covered, true); assert.deepEqual([eq.symbol, eq.decimals, eq.heldForUsers.amount], ["EQNVDA", 8, "0.0"]); }); test("no code at the address is said, not guessed around", async () => { assert.deepEqual(await readCredits(fakeChain({ code: "0x" }).rpc, cfg), { deployed: false, address: getAddress(CREDITS) }); }); test("a contract built on other tokens, or holding less than it owes, is flagged", async () => { const other = await readCredits(fakeChain({ usdc: "0x" + "33".repeat(20) }).rpc, cfg); assert.equal(other.matches, false); const short = await readCredits(fakeChain({ tokenBalance: { [USDC]: 1n, [EQNVDA]: 0n } }).rpc, cfg); assert.equal(short.tokens[0].covered, false); }); test("one address: wallet, allowance, balance, what is available, and the pending withdrawal", async () => { const a = await readCreditsAccount(fakeChain().rpc, cfg, ALICE); assert.equal(a.address, getAddress(ALICE)); const [usdc, eq] = a.tokens; assert.equal(usdc.inWallet.amount, "40.0"); assert.equal(usdc.allowance.amount, "10.0"); assert.equal(usdc.inContract.amount, "25.0"); assert.equal(usdc.available.amount, "20.0"); assert.equal(usdc.chargeable.amount, "25.0"); assert.deepEqual(usdc.pendingWithdrawal, { units: "5000000", amount: "5.0", unlockAt: "2027-01-15T08:00:00.000Z", unlockAtUnix: 1_800_000_000 }); assert.equal(eq.inWallet.amount, "1.5"); assert.equal(eq.pendingWithdrawal, null); }); }); describe("the contract routes", () => { const withContract = (state, over = {}) => { const chain = fakeChain(state); return { w: world({ cfg: { credits: CREDITS, ...(over.cfg ?? {}) }, deps: { chain: chain.rpc, ...(over.deps ?? {}) } }), chain }; }; test("a deployment without a contract says so, and carries nothing to one", async () => { const w = world(); assert.deepEqual((await w.call("GET", "/v1/contract")).body.deployed, false); assert.equal((await w.call("GET", "/v1/contract/account", { query: { address: ALICE } })).status, 503); const h = (await w.call("GET", "/v1/health")).body; assert.equal(h.contract, null); assert.equal(h.relayer.carries.some((x) => /credits/.test(x)), false); }); test("GET /v1/contract answers what the chain says, with where to check it", async () => { const { w } = withContract(); const r = await w.call("GET", "/v1/contract"); assert.equal(r.status, 200); const k = r.body; assert.deepEqual([k.name, k.deployed, k.address, k.operator, k.withdrawalDelaySeconds, k.audited, k.wiredToRentals], ["IdleCredits", true, getAddress(CREDITS), getAddress(OPERATOR), 3600, false, false]); assert.equal(k.explorer, "https://elysium.kinetiq.xyz/address/" + getAddress(CREDITS)); assert.equal(k.deployment.block, ELYSIUM_CREDITS.block); assert.equal(k.tokens[0].heldForUsers.amount, "25.0"); assert.match(k.note, /cannot be spent on a rental today/); assert.equal(k.relayer.canSend, false); assert.deepEqual(k.relayer.carries, ["USDC.approve(credits, amount)", "EQNVDA.approve(credits, amount)", "credits.deposit(token, amount)", "credits.requestWithdrawal(token, amount)", "credits.cancelWithdrawal(token)", "credits.withdraw(token)"]); const h = (await w.call("GET", "/v1/health")).body; assert.deepEqual(h.contract, { name: "IdleCredits", address: getAddress(CREDITS), path: "/v1/contract", wiredToRentals: false }); }); test("the contract is read at most once every ten seconds", async () => { const { w, chain } = withContract(); await w.call("GET", "/v1/contract"); const after = chain.state.calls; await w.call("GET", "/v1/contract"); assert.equal(chain.state.calls, after); w.advance(11); await w.call("GET", "/v1/contract"); assert.ok(chain.state.calls > after); }); test("GET /v1/contract/account answers for one address, and refuses what is not an address", async () => { const { w } = withContract(); const r = await w.call("GET", "/v1/contract/account", { query: { address: ALICE } }); assert.equal(r.status, 200); assert.equal(r.body.tokens[0].available.amount, "20.0"); assert.equal(r.body.withdrawalDelaySeconds, 3600); assert.equal((await w.call("GET", "/v1/contract/account", { query: { address: "alice" } })).status, 400); assert.equal((await w.call("GET", "/v1/contract/account")).status, 400); }); test("a chain that does not answer is an error, never an empty contract", async () => { const w = world({ cfg: { credits: CREDITS }, deps: { chain: async () => { throw { code: -32000, message: "down" }; } } }); assert.equal((await w.call("GET", "/v1/contract")).status, 502); assert.equal((await w.call("GET", "/v1/contract/account", { query: { address: ALICE } })).status, 502); }); }); describe("what the relayer carries to the credits contract", () => { const wallet = Wallet.createRandom(); const rcfg = { chainId: 99901, usdc: USDC, eqnvda: EQNVDA, treasury: null, credits: CREDITS }; const sign = (to, data, over = {}) => wallet.signTransaction({ chainId: 99901, type: 2, to, data, value: 0n, nonce: 0, gasLimit: 150_000n, maxFeePerGas: 2_000_000_000n, maxPriorityFeePerGas: 1_000_000_000n, ...over }); const call = (fn, args) => credits.encodeFunctionData(fn, args); test("an approval for the contract, a deposit, a withdrawal request, its cancellation and the withdrawal", async () => { const approve = checkTx(await sign(USDC, erc20.encodeFunctionData("approve", [CREDITS, 5_000_000n])), rcfg); assert.deepEqual([approve.ok, approve.call, approve.token, approve.amount], [true, "approve", "USDC", 5_000_000n]); const deposit = checkTx(await sign(CREDITS, call("deposit", [USDC, 5_000_000n])), rcfg); assert.deepEqual([deposit.ok, deposit.call, deposit.token, deposit.amount], [true, "deposit", "USDC", 5_000_000n]); const request = checkTx(await sign(CREDITS, call("requestWithdrawal", [EQNVDA, 150_000_000n])), rcfg); assert.deepEqual([request.ok, request.call, request.token], [true, "requestWithdrawal", "EQNVDA"]); assert.deepEqual([checkTx(await sign(CREDITS, call("cancelWithdrawal", [USDC])), rcfg).call, checkTx(await sign(CREDITS, call("withdraw", [USDC])), rcfg).call], ["cancelWithdrawal", "withdraw"]); assert.equal(carries(rcfg).length, 8); }); test("anything else on the contract or its tokens is refused", async () => { const operatorOnly = new Interface(["function charge(address user, address token, uint256 amount, bytes32 receiptId)", "function collect(address token, address to)", "function seal(uint256 hour, bytes32 root)", "function proposeOperator(address proposed)"]); for (const data of [ operatorOnly.encodeFunctionData("charge", [ALICE, USDC, 1n, "0x" + "11".repeat(32)]), operatorOnly.encodeFunctionData("collect", [USDC, ALICE]), operatorOnly.encodeFunctionData("seal", [1n, "0x" + "22".repeat(32)]), operatorOnly.encodeFunctionData("proposeOperator", [ALICE]), "0x", call("deposit", [USDC, 5_000_000n]) + "00", ]) { const c = checkTx(await sign(CREDITS, data), rcfg); assert.deepEqual([c.ok, c.code], [false, "scope"], data.slice(0, 10)); } assert.match(checkTx(await sign(CREDITS, call("deposit", ["0x" + "33".repeat(20), 5n])), rcfg).reason, /only takes USDC and EQNVDA/); assert.match(checkTx(await sign(CREDITS, call("deposit", [USDC, 0n])), rcfg).reason, /zero/); assert.match(checkTx(await sign(CREDITS, call("deposit", [USDC, 5n]), { value: 1n }), rcfg).reason, /no HYPE/); assert.match(checkTx(await sign(USDC, erc20.encodeFunctionData("approve", [ALICE, 5n])), rcfg).reason, /credits contract as spender/); assert.equal(checkTx(await sign(CREDITS, call("deposit", [USDC, 5n]), { gasLimit: 400_000n }), rcfg).code, "gas"); // Without a treasury a plain transfer is still not carried, and it says why. assert.equal(checkTx(await sign(USDC, erc20.encodeFunctionData("transfer", [TREASURY, 5n])), rcfg).code, "not-open"); // Without a contract configured, none of this exists. const plain = { ...rcfg, treasury: TREASURY, credits: null }; assert.equal(checkTx(await sign(CREDITS, call("deposit", [USDC, 5n])), plain).code, "scope"); assert.equal(checkTx(await sign(USDC, erc20.encodeFunctionData("approve", [CREDITS, 5n])), plain).code, "scope"); }); test("a deposit is posted to the inbox once it has run cleanly, and not without a gas account", async () => { const posted = []; let balance = 10n ** 18n; const upstream = async (method) => (method === "eth_call" ? "0x" : method === "eth_getTransactionCount" ? "0x0" : method === "eth_getBalance" ? "0x" + balance.toString(16) : null); const relayer = createRelayer(rcfg, { upstream, post: async (raw) => (posted.push(raw), "0x" + "aa".repeat(32)), allowRead: () => true, allowSend: () => true }); assert.equal(relayer.canSend(), true); const raw = await sign(CREDITS, call("deposit", [USDC, 5_000_000n])); const r = await relayer.rpc({ id: 1, method: "eth_sendRawTransaction", params: [raw] }, "ip"); assert.equal(r.result, checkTx(raw, rcfg).hash); assert.deepEqual(posted, [raw]); // A sender who cannot pay for the transaction on Elysium is not carried: an approval from an empty // wallet would otherwise be a free way to spend the relayer's gas. balance = 150_000n * 2_000_000_000n - 1n; const approval = await sign(USDC, erc20.encodeFunctionData("approve", [CREDITS, 5n])); assert.match((await relayer.rpc({ id: 3, method: "eth_sendRawTransaction", params: [approval] }, "ip")).error.message, /^no-gas: /); assert.equal(posted.length, 1); balance += 1n; assert.equal((await relayer.rpc({ id: 4, method: "eth_sendRawTransaction", params: [approval] }, "ip")).result, checkTx(approval, rcfg).hash); assert.equal(posted.length, 2); const noGas = createRelayer(rcfg, { upstream, post: null, allowRead: () => true, allowSend: () => true }); assert.equal(noGas.canSend(), false); assert.match((await noGas.rpc({ id: 2, method: "eth_sendRawTransaction", params: [raw] }, "ip")).error.message, /^no-gas-account/); }); }); describe("the contract through the MCP server", () => { const call = async (w, args) => { const r = await w.app.handle({ method: "POST", path: "/mcp", ip: "7.7.7.7", headers: { "mcp-protocol-version": "2025-11-25" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "credits_contract", arguments: args } }) }); return JSON.parse(r.body).result; }; test("credits_contract reads the contract, or one address in it, with no account", async () => { const w = world({ cfg: { credits: CREDITS }, deps: { chain: fakeChain().rpc } }); const k = await call(w, {}); assert.equal(k.isError ?? false, false); assert.deepEqual([k.structuredContent.address, k.structuredContent.withdrawalDelaySeconds, k.structuredContent.wiredToRentals], [getAddress(CREDITS), 3600, false]); const a = await call(w, { address: ALICE }); assert.equal(a.structuredContent.tokens[0].available.amount, "20.0"); assert.equal((await w.call("GET", "/v1/health")).body.mcp.openTools.includes("credits_contract"), true); }); });