const { expect } = require("chai"); const { ethers } = require("hardhat"); const { time, loadFixture } = require("@nomicfoundation/hardhat-network-helpers"); const { execFileSync } = require("node:child_process"); const { mkdtempSync, writeFileSync, rmSync } = require("node:fs"); const { tmpdir } = require("node:os"); const path = require("node:path"); const USDC = (n) => ethers.parseUnits(String(n), 6); const EQNVDA = (n) => ethers.parseUnits(String(n), 8); const HOUR = 3600n; const DELAY = 3600n; const RID = (text) => ethers.id(text); // a receipt id, as scripts/merkle.mjs makes them const selector = (signature) => ethers.id(signature).slice(0, 10); let M; // scripts/merkle.mjs, the off-chain side describe("IdleCredits", function () { before(async function () { M = await import("../scripts/merkle.mjs"); }); async function deploy() { const [deployer, operator, alice, bob, carol, treasury] = await ethers.getSigners(); const Token = await ethers.getContractFactory("MockERC20"); const usdc = await Token.deploy("USD Coin", "USDC", 6); const eqnvda = await Token.deploy("EQX NVIDIA", "EQNVDA", 8); const Credits = await ethers.getContractFactory("IdleCredits"); const credits = await Credits.deploy(usdc.target, eqnvda.target, operator.address, DELAY); for (const user of [alice, bob, carol]) { await usdc.mint(user.address, USDC(10_000)); await eqnvda.mint(user.address, EQNVDA(100)); await usdc.connect(user).approve(credits.target, ethers.MaxUint256); await eqnvda.connect(user).approve(credits.target, ethers.MaxUint256); } return { credits, Credits, usdc, eqnvda, deployer, operator, alice, bob, carol, treasury }; } // Alice holds 100 USDC and 2 EQNVDA of credits. async function funded() { const f = await loadFixture(deploy); await f.credits.connect(f.alice).deposit(f.usdc.target, USDC(100)); await f.credits.connect(f.alice).deposit(f.eqnvda.target, EQNVDA(2)); return f; } // What the contract holds must be exactly what users hold in it plus what the operator earned. async function expectBacked(f) { for (const token of [f.usdc, f.eqnvda]) { const held = await token.balanceOf(f.credits.target); expect(held).to.equal((await f.credits.totalBalance(token.target)) + (await f.credits.earned(token.target))); } } describe("deployment", function () { it("stores its parameters", async function () { const { credits, usdc, eqnvda, operator } = await loadFixture(deploy); expect(await credits.usdc()).to.equal(usdc.target); expect(await credits.eqnvda()).to.equal(eqnvda.target); expect(await credits.operator()).to.equal(operator.address); expect(await credits.pendingOperator()).to.equal(ethers.ZeroAddress); expect(await credits.withdrawalDelay()).to.equal(DELAY); expect(await credits.MAX_WITHDRAWAL_DELAY()).to.equal(24n * HOUR); expect(await credits.isAccepted(usdc.target)).to.equal(true); expect(await credits.isAccepted(eqnvda.target)).to.equal(true); expect(await credits.isAccepted(operator.address)).to.equal(false); }); it("announces its first operator", async function () { const { credits, operator } = await loadFixture(deploy); await expect(credits.deploymentTransaction()).to.emit(credits, "OperatorChanged").withArgs(ethers.ZeroAddress, operator.address); }); it("has no owner, no pause, no upgrade and no way to move tokens other than the documented ones", async function () { const { credits } = await loadFixture(deploy); for (const name of ["owner", "pause", "unpause", "upgradeTo", "upgradeToAndCall", "sweep", "rescue", "setOperator", "transferOwnership", "setWithdrawalDelay"]) { expect(credits.interface.getFunction(name), name).to.equal(null); } // Every function that changes state, and nothing else. const writers = credits.interface.fragments .filter((x) => x.type === "function" && x.stateMutability !== "view" && x.stateMutability !== "pure") .map((x) => x.name) .sort(); expect(writers).to.deep.equal(["acceptOperator", "cancelWithdrawal", "charge", "collect", "deposit", "proposeOperator", "requestWithdrawal", "seal", "withdraw"]); }); it("refuses zero addresses, twice the same token and a delay above 24 hours", async function () { const { Credits, usdc, eqnvda, operator } = await loadFixture(deploy); const zero = ethers.ZeroAddress; await expect(Credits.deploy(zero, eqnvda.target, operator.address, DELAY)).to.be.revertedWithCustomError(Credits, "ZeroAddress"); await expect(Credits.deploy(usdc.target, zero, operator.address, DELAY)).to.be.revertedWithCustomError(Credits, "ZeroAddress"); await expect(Credits.deploy(usdc.target, eqnvda.target, zero, DELAY)).to.be.revertedWithCustomError(Credits, "ZeroAddress"); await expect(Credits.deploy(usdc.target, usdc.target, operator.address, DELAY)).to.be.revertedWithCustomError(Credits, "SameToken"); await expect(Credits.deploy(usdc.target, eqnvda.target, operator.address, 24n * HOUR + 1n)).to.be.revertedWithCustomError(Credits, "DelayTooLong"); }); it("accepts a delay of exactly 24 hours, and of zero", async function () { const { Credits, usdc, eqnvda, operator } = await loadFixture(deploy); const day = await Credits.deploy(usdc.target, eqnvda.target, operator.address, 24n * HOUR); expect(await day.withdrawalDelay()).to.equal(24n * HOUR); const none = await Credits.deploy(usdc.target, eqnvda.target, operator.address, 0); expect(await none.withdrawalDelay()).to.equal(0); }); }); describe("deposit", function () { it("pulls USDC (6 decimals) and credits the sender", async function () { const f = await loadFixture(deploy); const { credits, usdc, alice } = f; const tx = credits.connect(alice).deposit(usdc.target, USDC(25.5)); await expect(tx).to.emit(credits, "Deposited").withArgs(alice.address, usdc.target, 25_500_000n); await expect(tx).to.changeTokenBalances(usdc, [alice, credits], [-USDC(25.5), USDC(25.5)]); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(25_500_000n); expect(await credits.totalBalance(usdc.target)).to.equal(25_500_000n); expect(await credits.available(alice.address, usdc.target)).to.equal(25_500_000n); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(25_500_000n); await expectBacked(f); }); it("pulls EQNVDA (8 decimals) and keeps the two tokens apart", async function () { const f = await loadFixture(deploy); const { credits, usdc, eqnvda, alice, bob } = f; await credits.connect(alice).deposit(usdc.target, USDC(40)); const tx = credits.connect(alice).deposit(eqnvda.target, EQNVDA(1.5)); await expect(tx).to.emit(credits, "Deposited").withArgs(alice.address, eqnvda.target, 150_000_000n); await expect(tx).to.changeTokenBalances(eqnvda, [alice, credits], [-EQNVDA(1.5), EQNVDA(1.5)]); await credits.connect(bob).deposit(eqnvda.target, 1n); // the smallest unit of an 8-decimal token expect(await credits.balanceOf(alice.address, eqnvda.target)).to.equal(150_000_000n); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(40_000_000n); expect(await credits.balanceOf(bob.address, eqnvda.target)).to.equal(1n); expect(await credits.balanceOf(bob.address, usdc.target)).to.equal(0); expect(await credits.totalBalance(eqnvda.target)).to.equal(150_000_001n); expect(await credits.totalBalance(usdc.target)).to.equal(40_000_000n); await expectBacked(f); }); it("adds up several deposits", async function () { const { credits, usdc, alice } = await loadFixture(deploy); await credits.connect(alice).deposit(usdc.target, USDC(1)); await credits.connect(alice).deposit(usdc.target, USDC(2)); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(3)); }); it("refuses zero, and any token other than the two", async function () { const { credits, usdc, alice, bob } = await loadFixture(deploy); const other = await (await ethers.getContractFactory("MockERC20")).deploy("Other", "OTHER", 18); await other.mint(alice.address, 1000); await other.connect(alice).approve(credits.target, ethers.MaxUint256); await expect(credits.connect(alice).deposit(usdc.target, 0)).to.be.revertedWithCustomError(credits, "ZeroAmount"); await expect(credits.connect(alice).deposit(other.target, 1000)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); await expect(credits.connect(alice).deposit(ethers.ZeroAddress, 1)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); await expect(credits.connect(alice).deposit(bob.address, 1)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); }); it("fails cleanly without an allowance or without the tokens", async function () { const { credits, usdc, deployer, alice } = await loadFixture(deploy); await usdc.mint(deployer.address, USDC(5)); await expect(credits.connect(deployer).deposit(usdc.target, USDC(5))).to.be.revertedWithCustomError(credits, "TransferFailed"); await expect(credits.connect(alice).deposit(usdc.target, USDC(10_001))).to.be.revertedWithCustomError(credits, "TransferFailed"); expect(await credits.totalBalance(usdc.target)).to.equal(0); }); it("refuses native HYPE sent to it", async function () { const { credits, alice } = await loadFixture(deploy); await expect(alice.sendTransaction({ to: credits.target, value: 1n })).to.be.reverted; }); }); describe("unusual tokens", function () { it("refuses a token that takes a fee on transfer", async function () { const { Credits, eqnvda, operator, alice } = await loadFixture(deploy); const fee = await (await ethers.getContractFactory("FeeToken")).deploy(); const credits = await Credits.deploy(fee.target, eqnvda.target, operator.address, DELAY); await fee.mint(alice.address, 10_000); await fee.connect(alice).approve(credits.target, ethers.MaxUint256); await expect(credits.connect(alice).deposit(fee.target, 10_000)).to.be.revertedWithCustomError(credits, "UnsupportedToken"); expect(await credits.balanceOf(alice.address, fee.target)).to.equal(0); expect(await fee.balanceOf(credits.target)).to.equal(0); expect(await fee.balanceOf(alice.address)).to.equal(10_000); }); it("works with a token that returns nothing, all the way round", async function () { const { Credits, eqnvda, operator, alice, treasury } = await loadFixture(deploy); const quiet = await (await ethers.getContractFactory("NoReturnToken")).deploy(); const credits = await Credits.deploy(quiet.target, eqnvda.target, operator.address, DELAY); await quiet.mint(alice.address, 1000); await quiet.connect(alice).approve(credits.target, 1000); await credits.connect(alice).deposit(quiet.target, 1000); expect(await credits.balanceOf(alice.address, quiet.target)).to.equal(1000); await credits.connect(operator).charge(alice.address, quiet.target, 300, RID("quiet-1")); await credits.connect(operator).collect(quiet.target, treasury.address); expect(await quiet.balanceOf(treasury.address)).to.equal(300); await credits.connect(alice).requestWithdrawal(quiet.target, 700); await time.increase(DELAY); await credits.connect(alice).withdraw(quiet.target); expect(await quiet.balanceOf(alice.address)).to.equal(700); expect(await quiet.balanceOf(credits.target)).to.equal(0); }); it("treats a token that answers false as a failed transfer, in and out", async function () { const { Credits, eqnvda, operator, alice, treasury } = await loadFixture(deploy); const liar = await (await ethers.getContractFactory("FalseToken")).deploy(); const credits = await Credits.deploy(liar.target, eqnvda.target, operator.address, DELAY); await liar.mint(alice.address, 1000); await liar.setRefusing(true); await expect(credits.connect(alice).deposit(liar.target, 500)).to.be.revertedWithCustomError(credits, "TransferFailed"); await liar.setRefusing(false); await credits.connect(alice).deposit(liar.target, 500); await credits.connect(operator).charge(alice.address, liar.target, 100, RID("liar-1")); await credits.connect(alice).requestWithdrawal(liar.target, 400); await time.increase(DELAY); await liar.setRefusing(true); await expect(credits.connect(alice).withdraw(liar.target)).to.be.revertedWithCustomError(credits, "TransferFailed"); await expect(credits.connect(operator).collect(liar.target, treasury.address)).to.be.revertedWithCustomError(credits, "TransferFailed"); // Nothing was lost by the failed attempts. expect(await credits.balanceOf(alice.address, liar.target)).to.equal(400); expect(await credits.earned(liar.target)).to.equal(100); await liar.setRefusing(false); await credits.connect(alice).withdraw(liar.target); await credits.connect(operator).collect(liar.target, treasury.address); expect(await liar.balanceOf(alice.address)).to.equal(900); expect(await liar.balanceOf(treasury.address)).to.equal(100); }); it("fails cleanly when a token address has no code", async function () { const { Credits, eqnvda, operator, alice, carol } = await loadFixture(deploy); const credits = await Credits.deploy(carol.address, eqnvda.target, operator.address, DELAY); await expect(credits.connect(alice).deposit(carol.address, 1)).to.be.reverted; expect(await credits.balanceOf(alice.address, carol.address)).to.equal(0); }); }); describe("withdrawal", function () { it("starts a clock on request and pays when it has run out", async function () { const f = await funded(); const { credits, usdc, alice } = f; const at = BigInt(await time.latest()) + 10n; await time.setNextBlockTimestamp(at); await expect(credits.connect(alice).requestWithdrawal(usdc.target, USDC(60))) .to.emit(credits, "WithdrawalRequested") .withArgs(alice.address, usdc.target, USDC(60), at + DELAY); expect(await credits.pendingWithdrawal(alice.address, usdc.target)).to.deep.equal([USDC(60), at + DELAY]); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100)); // still hers, still here expect(await credits.available(alice.address, usdc.target)).to.equal(USDC(40)); // what she can still rent with await time.setNextBlockTimestamp(at + DELAY); const tx = credits.connect(alice).withdraw(usdc.target); await expect(tx).to.emit(credits, "Withdrawn").withArgs(alice.address, usdc.target, USDC(60)); await expect(tx).to.changeTokenBalances(usdc, [credits, alice], [-USDC(60), USDC(60)]); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(40)); expect(await credits.totalBalance(usdc.target)).to.equal(USDC(40)); expect(await credits.pendingWithdrawal(alice.address, usdc.target)).to.deep.equal([0n, 0n]); expect(await credits.available(alice.address, usdc.target)).to.equal(USDC(40)); await expectBacked(f); }); it("refuses to pay one second early", async function () { const { credits, usdc, alice } = await funded(); const at = BigInt(await time.latest()) + 10n; await time.setNextBlockTimestamp(at); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(60)); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "TooEarly"); await time.setNextBlockTimestamp(at + DELAY - 1n); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "TooEarly"); await time.setNextBlockTimestamp(at + DELAY); await credits.connect(alice).withdraw(usdc.target); expect(await usdc.balanceOf(alice.address)).to.equal(USDC(10_000 - 40)); }); it("keeps working long after the delay", async function () { const { credits, eqnvda, alice } = await funded(); await credits.connect(alice).requestWithdrawal(eqnvda.target, EQNVDA(2)); await time.increase(400n * 24n * HOUR); await expect(credits.connect(alice).withdraw(eqnvda.target)).to.changeTokenBalances(eqnvda, [credits, alice], [-EQNVDA(2), EQNVDA(2)]); }); it("refuses zero, more than the balance, another token, and a withdrawal nobody requested", async function () { const { credits, usdc, eqnvda, alice, bob, operator } = await funded(); await expect(credits.connect(alice).requestWithdrawal(usdc.target, 0)).to.be.revertedWithCustomError(credits, "ZeroAmount"); await expect(credits.connect(alice).requestWithdrawal(usdc.target, USDC(100) + 1n)).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(bob).requestWithdrawal(usdc.target, 1)).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(alice).requestWithdrawal(operator.address, 1)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); await expect(credits.connect(alice).withdraw(operator.address)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); await expect(credits.connect(alice).cancelWithdrawal(operator.address)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await expect(credits.connect(alice).cancelWithdrawal(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); // A request in one token is no request in the other. await credits.connect(alice).requestWithdrawal(usdc.target, USDC(1)); await time.increase(DELAY); await expect(credits.connect(alice).withdraw(eqnvda.target)).to.be.revertedWithCustomError(credits, "NothingPending"); }); it("pays once: a second withdraw finds nothing", async function () { const { credits, usdc, alice } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.increase(DELAY); await credits.connect(alice).withdraw(usdc.target); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); expect(await usdc.balanceOf(alice.address)).to.equal(USDC(10_000)); }); it("pays only the one who asked", async function () { const { credits, usdc, alice, bob, operator } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.increase(DELAY); await expect(credits.connect(bob).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await expect(credits.connect(operator).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100)); }); it("can be cancelled, and the amount counts as credits again", async function () { const { credits, usdc, alice, operator } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.increase(DELAY); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(0); await expect(credits.connect(alice).cancelWithdrawal(usdc.target)).to.emit(credits, "WithdrawalCancelled").withArgs(alice.address, usdc.target); expect(await credits.pendingWithdrawal(alice.address, usdc.target)).to.deep.equal([0n, 0n]); expect(await credits.available(alice.address, usdc.target)).to.equal(USDC(100)); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(100)); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await credits.connect(operator).charge(alice.address, usdc.target, USDC(100), RID("after-cancel")); }); it("pays at once when the contract was deployed without a delay", async function () { const { Credits, usdc, eqnvda, operator, alice } = await loadFixture(deploy); const instant = await Credits.deploy(usdc.target, eqnvda.target, operator.address, 0); await usdc.connect(alice).approve(instant.target, ethers.MaxUint256); await instant.connect(alice).deposit(usdc.target, USDC(10)); await instant.connect(alice).requestWithdrawal(usdc.target, USDC(10)); await expect(instant.connect(operator).charge(alice.address, usdc.target, 1, RID("late"))).to.be.revertedWithCustomError(instant, "InsufficientBalance"); await expect(instant.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [instant, alice], [-USDC(10), USDC(10)]); }); }); describe("the withdrawal rule, under adversarial timing", function () { it("request, then charge during the delay: the user cannot dodge what was used", async function () { const f = await funded(); const { credits, usdc, alice, operator } = f; // Alice has used 30 USDC of GPU time, then asks for everything back before it is charged. await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(100)); expect(await credits.available(alice.address, usdc.target)).to.equal(0); await credits.connect(operator).charge(alice.address, usdc.target, USDC(30), RID("used-before-request")); expect(await credits.pendingWithdrawal(alice.address, usdc.target).then((p) => p[0])).to.equal(USDC(70)); // capped at what is left await time.increase(DELAY); const tx = credits.connect(alice).withdraw(usdc.target); await expect(tx).to.emit(credits, "Withdrawn").withArgs(alice.address, usdc.target, USDC(70)); await expect(tx).to.changeTokenBalances(usdc, [credits, alice], [-USDC(70), USDC(70)]); expect(await credits.earned(usdc.target)).to.equal(USDC(30)); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(0); await expectBacked(f); }); it("the last second of the delay is still chargeable, the next one is not", async function () { const { credits, usdc, alice, operator } = await funded(); const at = BigInt(await time.latest()) + 10n; await time.setNextBlockTimestamp(at); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.setNextBlockTimestamp(at + DELAY - 1n); await credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("last-second")); await time.setNextBlockTimestamp(at + DELAY); await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, RID("one-second-late"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(0); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(99)]); }); it("once the delay has passed the operator cannot touch the requested amount, even if the user waits", async function () { const f = await funded(); const { credits, usdc, alice, operator } = f; await credits.connect(alice).requestWithdrawal(usdc.target, USDC(60)); await time.increase(DELAY + 5n * 24n * HOUR); // she does not withdraw for days expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(40)); await expect(credits.connect(operator).charge(alice.address, usdc.target, USDC(40) + 1n, RID("too-much"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(operator).charge(alice.address, usdc.target, USDC(100), RID("everything"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); // The part she did not ask back is still chargeable, to the last unit. await credits.connect(operator).charge(alice.address, usdc.target, USDC(40), RID("the-rest")); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(0); await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, RID("one-more"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [credits, alice], [-USDC(60), USDC(60)]); await expectBacked(f); }); it("the operator cannot block an exit, whatever he does", async function () { const f = await funded(); const { credits, usdc, eqnvda, alice, bob, operator, treasury } = f; await credits.connect(operator).charge(alice.address, usdc.target, USDC(10), RID("honest")); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(90)); await credits.connect(alice).requestWithdrawal(eqnvda.target, EQNVDA(2)); await time.increase(DELAY); // Everything the operator has: charging, collecting, sealing, handing over. None of it has a hold on her exit. await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, RID("grab-1"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(operator).charge(alice.address, eqnvda.target, 1, RID("grab-2"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await credits.connect(operator).collect(usdc.target, treasury.address); await expect(credits.connect(operator).collect(usdc.target, treasury.address)).to.be.revertedWithCustomError(credits, "NothingToCollect"); await expect(credits.connect(operator).collect(eqnvda.target, treasury.address)).to.be.revertedWithCustomError(credits, "NothingToCollect"); await expect(credits.connect(operator).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await expect(credits.connect(operator).cancelWithdrawal(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await credits.connect(operator).seal(BigInt(await time.latest()) / HOUR - 1n, RID("some-root")); await credits.connect(operator).proposeOperator(bob.address); await credits.connect(bob).acceptOperator(); await expect(credits.connect(bob).charge(alice.address, usdc.target, 1, RID("grab-3"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(90)]); await expect(credits.connect(alice).withdraw(eqnvda.target)).to.changeTokenBalances(eqnvda, [alice], [EQNVDA(2)]); expect(await usdc.balanceOf(treasury.address)).to.equal(USDC(10)); expect(await usdc.balanceOf(credits.target)).to.equal(0); expect(await eqnvda.balanceOf(credits.target)).to.equal(0); }); it("charge, then request: only what is left can be asked back", async function () { const { credits, usdc, alice, operator } = await funded(); await credits.connect(operator).charge(alice.address, usdc.target, USDC(30), RID("first")); await expect(credits.connect(alice).requestWithdrawal(usdc.target, USDC(100))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(alice).requestWithdrawal(usdc.target, USDC(70) + 1n)).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(70)); await time.increase(DELAY); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(70)]); }); it("charged to zero during the delay: the withdrawal goes through and sends nothing", async function () { const f = await funded(); const { credits, usdc, alice, operator } = f; await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await credits.connect(operator).charge(alice.address, usdc.target, USDC(100), RID("all-used")); expect(await credits.pendingWithdrawal(alice.address, usdc.target).then((p) => p[0])).to.equal(0); await time.increase(DELAY); const tx = credits.connect(alice).withdraw(usdc.target); await expect(tx).to.emit(credits, "Withdrawn").withArgs(alice.address, usdc.target, 0); await expect(tx).to.changeTokenBalances(usdc, [credits, alice], [0, 0]); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "NothingPending"); await expectBacked(f); }); it("double request: a small old request cannot be enlarged to leave at once", async function () { const { credits, usdc, alice, operator } = await funded(); // The dodge: request one unit, let it mature, rent on the rest, then enlarge the request and withdraw at once. await credits.connect(alice).requestWithdrawal(usdc.target, 1); await time.increase(DELAY); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(100) - 1n); const at = BigInt(await time.latest()) + 10n; await time.setNextBlockTimestamp(at); await expect(credits.connect(alice).requestWithdrawal(usdc.target, USDC(100))) .to.emit(credits, "WithdrawalRequested") .withArgs(alice.address, usdc.target, USDC(100), at + DELAY); // The clock restarted for the whole amount: nothing leaves now, and all of it is chargeable again. await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "TooEarly"); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(100)); await credits.connect(operator).charge(alice.address, usdc.target, USDC(55), RID("used-meanwhile")); await time.setNextBlockTimestamp(at + DELAY); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(45)]); }); it("double request: the second one replaces the first, it does not add to it", async function () { const { credits, usdc, alice } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(80)); await time.increase(DELAY / 2n); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(20)); const [amount, unlockAt] = await credits.pendingWithdrawal(alice.address, usdc.target); expect(amount).to.equal(USDC(20)); expect(unlockAt).to.equal(BigInt(await time.latest()) + DELAY); await time.increase(DELAY / 2n); await expect(credits.connect(alice).withdraw(usdc.target)).to.be.revertedWithCustomError(credits, "TooEarly"); // the first clock is gone await time.increase(DELAY / 2n); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(20)]); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(80)); }); it("a deposit made after a request is ordinary credit: chargeable, and not part of the withdrawal", async function () { const { credits, usdc, alice, operator } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.increase(DELAY); await credits.connect(alice).deposit(usdc.target, USDC(50)); expect(await credits.available(alice.address, usdc.target)).to.equal(USDC(50)); expect(await credits.chargeable(alice.address, usdc.target)).to.equal(USDC(50)); await expect(credits.connect(operator).charge(alice.address, usdc.target, USDC(50) + 1n, RID("over"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await credits.connect(operator).charge(alice.address, usdc.target, USDC(50), RID("new-rental")); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(100)]); }); it("a request in one token does not shield or expose the other", async function () { const { credits, usdc, eqnvda, alice, operator } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await time.increase(DELAY); expect(await credits.chargeable(alice.address, eqnvda.target)).to.equal(EQNVDA(2)); await credits.connect(operator).charge(alice.address, eqnvda.target, EQNVDA(0.5), RID("eq-1")); expect(await credits.balanceOf(alice.address, eqnvda.target)).to.equal(EQNVDA(1.5)); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100)); }); }); describe("charge", function () { it("moves the amount from the user to earned, under a receipt id", async function () { const f = await funded(); const { credits, usdc, eqnvda, alice, operator } = f; const at = BigInt(await time.latest()) + 10n; await time.setNextBlockTimestamp(at); const tx = credits.connect(operator).charge(alice.address, usdc.target, USDC(12.345678), RID("e0001")); await expect(tx).to.emit(credits, "Charged").withArgs(RID("e0001"), alice.address, usdc.target, 12_345_678n); await expect(tx).to.changeTokenBalances(usdc, [credits, alice, operator], [0, 0, 0]); // nothing leaves the contract expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100) - 12_345_678n); expect(await credits.earned(usdc.target)).to.equal(12_345_678n); expect(await credits.totalBalance(usdc.target)).to.equal(USDC(100) - 12_345_678n); expect(await credits.chargedAt(RID("e0001"))).to.equal(at); expect(await credits.chargedAt(RID("e0002"))).to.equal(0); await expect(credits.connect(operator).charge(alice.address, eqnvda.target, 1n, RID("e0002"))) .to.emit(credits, "Charged") .withArgs(RID("e0002"), alice.address, eqnvda.target, 1n); expect(await credits.earned(eqnvda.target)).to.equal(1n); expect(await credits.balanceOf(alice.address, eqnvda.target)).to.equal(EQNVDA(2) - 1n); await expectBacked(f); }); it("is for the operator only", async function () { const { credits, usdc, alice, bob, deployer } = await funded(); for (const who of [alice, bob, deployer]) { await expect(credits.connect(who).charge(alice.address, usdc.target, 1, RID("x"))).to.be.revertedWithCustomError(credits, "NotOperator"); } expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100)); }); it("takes at most the user's balance", async function () { const { credits, usdc, eqnvda, alice, bob, operator } = await funded(); await expect(credits.connect(operator).charge(alice.address, usdc.target, USDC(100) + 1n, RID("a"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(operator).charge(alice.address, eqnvda.target, EQNVDA(2) + 1n, RID("a"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await expect(credits.connect(operator).charge(bob.address, usdc.target, 1, RID("a"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await credits.connect(operator).charge(alice.address, usdc.target, USDC(100), RID("a")); // exactly the balance expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(0); await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, RID("b"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); }); it("cannot charge one user from another's balance", async function () { const { credits, usdc, alice, bob, operator } = await funded(); await credits.connect(bob).deposit(usdc.target, USDC(5)); await expect(credits.connect(operator).charge(bob.address, usdc.target, USDC(6), RID("a"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); await credits.connect(operator).charge(bob.address, usdc.target, USDC(5), RID("a")); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(100)); }); it("refuses zero, a zero receipt id and any other token", async function () { const { credits, usdc, alice, operator } = await funded(); await expect(credits.connect(operator).charge(alice.address, usdc.target, 0, RID("a"))).to.be.revertedWithCustomError(credits, "ZeroAmount"); await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, ethers.ZeroHash)).to.be.revertedWithCustomError(credits, "ZeroReceipt"); await expect(credits.connect(operator).charge(alice.address, operator.address, 1, RID("a"))).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); }); it("uses a receipt id once, whatever the user, the token or the amount", async function () { const { credits, usdc, eqnvda, alice, bob, operator } = await funded(); await credits.connect(bob).deposit(usdc.target, USDC(5)); await credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("e0001")); const again = (user, token, amount) => credits.connect(operator).charge(user.address, token.target, amount, RID("e0001")); await expect(again(alice, usdc, USDC(1))).to.be.revertedWithCustomError(credits, "ReceiptUsed"); // exact replay await expect(again(alice, usdc, 1)).to.be.revertedWithCustomError(credits, "ReceiptUsed"); // another amount await expect(again(alice, eqnvda, 1)).to.be.revertedWithCustomError(credits, "ReceiptUsed"); // another token await expect(again(bob, usdc, 1)).to.be.revertedWithCustomError(credits, "ReceiptUsed"); // another user await time.increase(30n * 24n * HOUR); await expect(again(alice, usdc, USDC(1))).to.be.revertedWithCustomError(credits, "ReceiptUsed"); // much later expect(await credits.earned(usdc.target)).to.equal(USDC(1)); // A failed charge does not use up its id. await expect(credits.connect(operator).charge(alice.address, usdc.target, USDC(1000), RID("e0002"))).to.be.revertedWithCustomError(credits, "InsufficientBalance"); expect(await credits.chargedAt(RID("e0002"))).to.equal(0); await credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("e0002")); }); it("a new operator cannot reuse the ids of the old one", async function () { const { credits, usdc, alice, bob, operator } = await funded(); await credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("e0001")); await credits.connect(operator).proposeOperator(bob.address); await credits.connect(bob).acceptOperator(); await expect(credits.connect(bob).charge(alice.address, usdc.target, USDC(1), RID("e0001"))).to.be.revertedWithCustomError(credits, "ReceiptUsed"); }); }); describe("collect", function () { it("sends what was earned, and only that", async function () { const f = await funded(); const { credits, usdc, eqnvda, alice, bob, operator, treasury } = f; await credits.connect(bob).deposit(usdc.target, USDC(50)); await credits.connect(operator).charge(alice.address, usdc.target, USDC(7), RID("a")); await credits.connect(operator).charge(bob.address, usdc.target, USDC(3), RID("b")); const tx = credits.connect(operator).collect(usdc.target, treasury.address); await expect(tx).to.emit(credits, "Collected").withArgs(usdc.target, treasury.address, USDC(10)); await expect(tx).to.changeTokenBalances(usdc, [credits, treasury, operator], [-USDC(10), USDC(10), 0]); expect(await credits.earned(usdc.target)).to.equal(0); // What users still hold is all there. expect(await usdc.balanceOf(credits.target)).to.equal(USDC(140)); expect(await credits.totalBalance(usdc.target)).to.equal(USDC(140)); expect(await credits.balanceOf(alice.address, usdc.target)).to.equal(USDC(93)); expect(await credits.balanceOf(bob.address, usdc.target)).to.equal(USDC(47)); expect(await eqnvda.balanceOf(credits.target)).to.equal(EQNVDA(2)); await expectBacked(f); }); it("collects each token on its own", async function () { const { credits, usdc, eqnvda, alice, operator, treasury } = await funded(); await credits.connect(operator).charge(alice.address, usdc.target, USDC(7), RID("a")); await credits.connect(operator).charge(alice.address, eqnvda.target, EQNVDA(0.25), RID("b")); await expect(credits.connect(operator).collect(eqnvda.target, treasury.address)).to.changeTokenBalances(eqnvda, [credits, treasury], [-EQNVDA(0.25), EQNVDA(0.25)]); expect(await credits.earned(usdc.target)).to.equal(USDC(7)); expect(await usdc.balanceOf(treasury.address)).to.equal(0); }); it("has nothing to send when nothing was charged, or twice in a row", async function () { const { credits, usdc, alice, operator, treasury } = await funded(); await expect(credits.connect(operator).collect(usdc.target, treasury.address)).to.be.revertedWithCustomError(credits, "NothingToCollect"); await credits.connect(operator).charge(alice.address, usdc.target, USDC(7), RID("a")); await credits.connect(operator).collect(usdc.target, treasury.address); await expect(credits.connect(operator).collect(usdc.target, treasury.address)).to.be.revertedWithCustomError(credits, "NothingToCollect"); expect(await usdc.balanceOf(treasury.address)).to.equal(USDC(7)); }); it("is for the operator only, to a real address, in one of the two tokens", async function () { const { credits, usdc, alice, bob, operator } = await funded(); await credits.connect(operator).charge(alice.address, usdc.target, USDC(7), RID("a")); await expect(credits.connect(alice).collect(usdc.target, alice.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(bob).collect(usdc.target, bob.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(operator).collect(usdc.target, ethers.ZeroAddress)).to.be.revertedWithCustomError(credits, "ZeroAddress"); await expect(credits.connect(operator).collect(bob.address, bob.address)).to.be.revertedWithCustomError(credits, "TokenNotAccepted"); }); it("leaves tokens sent to the contract by mistake where they are", async function () { const { credits, usdc, alice, carol, operator, treasury } = await funded(); await usdc.connect(carol).transfer(credits.target, USDC(500)); // a plain transfer, not a deposit expect(await credits.balanceOf(carol.address, usdc.target)).to.equal(0); await credits.connect(operator).charge(alice.address, usdc.target, USDC(7), RID("a")); await expect(credits.connect(operator).collect(usdc.target, treasury.address)).to.changeTokenBalances(usdc, [treasury], [USDC(7)]); expect(await usdc.balanceOf(credits.target)).to.equal(USDC(593)); // 93 of Alice's, and 500 nobody can take }); }); describe("seal", function () { it("records one root for a finished hour", async function () { const { credits, operator } = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR - 1n; expect(await credits.rootOf(hour)).to.equal(ethers.ZeroHash); await expect(credits.connect(operator).seal(hour, RID("root-1"))).to.emit(credits, "Sealed").withArgs(hour, RID("root-1")); expect(await credits.rootOf(hour)).to.equal(RID("root-1")); }); it("never rewrites a root", async function () { const { credits, operator } = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR - 1n; await credits.connect(operator).seal(hour, RID("root-1")); await expect(credits.connect(operator).seal(hour, RID("root-2"))).to.be.revertedWithCustomError(credits, "AlreadySealed"); await expect(credits.connect(operator).seal(hour, RID("root-1"))).to.be.revertedWithCustomError(credits, "AlreadySealed"); await time.increase(100n * HOUR); await expect(credits.connect(operator).seal(hour, RID("root-2"))).to.be.revertedWithCustomError(credits, "AlreadySealed"); expect(await credits.rootOf(hour)).to.equal(RID("root-1")); }); it("only seals hours that are over", async function () { const { credits, operator } = await loadFixture(deploy); const now = BigInt(await time.latest()); const hour = now / HOUR + 2n; // an hour well ahead, so the test controls every second around its end await expect(credits.connect(operator).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "HourNotOver"); await expect(credits.connect(operator).seal(now / HOUR, RID("r"))).to.be.revertedWithCustomError(credits, "HourNotOver"); // the running hour await expect(credits.connect(operator).seal(ethers.MaxUint256, RID("r"))).to.be.revertedWithCustomError(credits, "HourNotOver"); await time.setNextBlockTimestamp(hour * HOUR); // its first second await expect(credits.connect(operator).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "HourNotOver"); await time.setNextBlockTimestamp((hour + 1n) * HOUR - 1n); // its last second await expect(credits.connect(operator).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "HourNotOver"); await time.setNextBlockTimestamp((hour + 1n) * HOUR); // the first second of the next hour await credits.connect(operator).seal(hour, RID("r")); expect(await credits.rootOf(hour)).to.equal(RID("r")); }); it("can seal old hours late, in any order", async function () { const { credits, operator } = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR; await credits.connect(operator).seal(hour - 1n, RID("r1")); await credits.connect(operator).seal(hour - 50n, RID("r50")); await credits.connect(operator).seal(hour - 2n, RID("r2")); expect(await credits.rootOf(hour - 50n)).to.equal(RID("r50")); expect(await credits.rootOf(hour - 3n)).to.equal(ethers.ZeroHash); }); it("refuses an empty root, and anyone but the operator", async function () { const { credits, operator, alice, deployer } = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR - 1n; await expect(credits.connect(operator).seal(hour, ethers.ZeroHash)).to.be.revertedWithCustomError(credits, "EmptyRoot"); await expect(credits.connect(alice).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(deployer).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "NotOperator"); }); }); describe("receipts and Merkle proofs", function () { const GPUS = ["h100", "rtx-4090", "b200", "l40s"]; function receipts(f, n, tag = "e") { return Array.from({ length: n }, (_, i) => ({ receiptId: M.receiptId(tag + String(i).padStart(4, "0")), user: [f.alice, f.bob, f.carol][i % 3].address, token: i % 2 === 0 ? f.usdc.target : f.eqnvda.target, amount: BigInt(1_000 + 7_919 * i), secondsBilled: 60 + 61 * i, gpuId: M.gpuId(GPUS[i % GPUS.length]), })); } const fields = (r) => [r.receiptId, r.user, r.token, r.amount, r.secondsBilled, r.gpuId]; it("computes the same leaf on chain and off chain", async function () { const f = await loadFixture(deploy); for (const r of receipts(f, 5)) { expect(await f.credits.leafOf(...fields(r))).to.equal(M.leafOf(r)); } // The definition, spelled out: six 32-byte words. const r = receipts(f, 1)[0]; const encoded = ethers.AbiCoder.defaultAbiCoder().encode(["bytes32", "address", "address", "uint256", "uint256", "bytes32"], fields(r)); expect(ethers.dataLength(encoded)).to.equal(192); expect(M.leafOf(r)).to.equal(ethers.keccak256(encoded)); expect(M.gpuId("h100")).to.equal("0x6831303000000000000000000000000000000000000000000000000000000000"); expect(M.receiptId("e0042")).to.equal(ethers.keccak256(ethers.toUtf8Bytes("e0042"))); }); for (const n of [1, 2, 3, 9]) { it(`proves every receipt of a tree of ${n} ${n === 1 ? "leaf" : "leaves"}`, async function () { const f = await loadFixture(deploy); const { credits, operator } = f; const hour = BigInt(await time.latest()) / HOUR - 1n; const list = receipts(f, n); const tree = M.buildTree(list); expect(tree.receipts.length).to.equal(n); if (n === 1) { expect(tree.root).to.equal(M.leafOf(list[0])); expect(tree.proofOf(list[0].receiptId)).to.deep.equal([]); } await credits.connect(operator).seal(hour, tree.root); for (const r of list) { const proof = tree.proofOf(r.receiptId); const leaf = tree.leafOfId(r.receiptId); expect(proof.length).to.be.at.most(Math.ceil(Math.log2(n)) || 0); expect(M.verify(tree.root, leaf, proof)).to.equal(true); expect(await credits.verify(hour, leaf, proof)).to.equal(true); expect(await credits.verifyReceipt(hour, ...fields(r), proof)).to.equal(true); } }); } it("gives the same root whatever the order of the receipts", async function () { const f = await loadFixture(deploy); const list = receipts(f, 9); const shuffled = [list[4], list[8], list[0], list[2], list[7], list[1], list[6], list[3], list[5]]; expect(M.buildTree(shuffled).root).to.equal(M.buildTree(list).root); expect(M.buildTree([...list].reverse()).root).to.equal(M.buildTree(list).root); }); it("rejects wrong proofs", async function () { const f = await loadFixture(deploy); const { credits, operator } = f; const hour = BigInt(await time.latest()) / HOUR - 1n; const list = receipts(f, 9); const tree = M.buildTree(list); await credits.connect(operator).seal(hour, tree.root); const a = list[0]; const b = list[5]; const proofA = tree.proofOf(a.receiptId); const leafA = tree.leafOfId(a.receiptId); expect(await credits.verify(hour, leafA, proofA)).to.equal(true); expect(await credits.verify(hour, leafA, tree.proofOf(b.receiptId))).to.equal(false); // someone else's proof expect(await credits.verify(hour, tree.leafOfId(b.receiptId), proofA)).to.equal(false); // someone else's leaf expect(await credits.verify(hour, leafA, proofA.slice(0, -1))).to.equal(false); // one step short expect(await credits.verify(hour, leafA, proofA.slice(1))).to.equal(false); // first step missing expect(await credits.verify(hour, leafA, [...proofA, RID("extra")])).to.equal(false); // one step too many expect(await credits.verify(hour, leafA, [])).to.equal(false); expect(await credits.verify(hour, leafA, [...proofA].reverse())).to.equal(proofA.length < 2); // steps out of order const flipped = [...proofA]; flipped[0] = ethers.toBeHex(BigInt(flipped[0]) ^ 1n, 32); expect(await credits.verify(hour, leafA, flipped)).to.equal(false); // one bit changed expect(await credits.verify(hour, RID("not-a-receipt"), proofA)).to.equal(false); expect(await credits.verify(hour, ethers.ZeroHash, [])).to.equal(false); // The right proof, for another hour. expect(await credits.verify(hour - 1n, leafA, proofA)).to.equal(false); // not sealed await credits.connect(operator).seal(hour - 1n, M.buildTree(receipts(f, 3, "other")).root); expect(await credits.verify(hour - 1n, leafA, proofA)).to.equal(false); // sealed with other receipts }); it("rejects a receipt with any field changed", async function () { const f = await loadFixture(deploy); const { credits, operator } = f; const hour = BigInt(await time.latest()) / HOUR - 1n; const list = receipts(f, 9); const tree = M.buildTree(list); await credits.connect(operator).seal(hour, tree.root); const r = list[4]; const proof = tree.proofOf(r.receiptId); expect(await credits.verifyReceipt(hour, ...fields(r), proof)).to.equal(true); const changed = [ { ...r, receiptId: M.receiptId("e9999") }, { ...r, user: f.treasury.address }, { ...r, token: r.token === f.usdc.target ? f.eqnvda.target : f.usdc.target }, { ...r, amount: r.amount + 1n }, { ...r, amount: r.amount - 1n }, { ...r, secondsBilled: r.secondsBilled + 1 }, { ...r, gpuId: M.gpuId("h200") }, ]; for (const c of changed) { expect(await credits.verifyReceipt(hour, ...fields(c), proof)).to.equal(false); expect(M.verify(tree.root, M.leafOf(c), proof)).to.equal(false); } }); it("an unsealed hour proves nothing, not even an empty proof of an empty leaf", async function () { const f = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR - 1n; const r = receipts(f, 1)[0]; expect(await f.credits.verify(hour, M.leafOf(r), [])).to.equal(false); expect(await f.credits.verify(hour, ethers.ZeroHash, [])).to.equal(false); expect(await f.credits.verifyReceipt(hour, ...fields(r), [])).to.equal(false); }); it("verify() also accepts the inner nodes of a tree, which is why receipts are checked with verifyReceipt()", async function () { const f = await loadFixture(deploy); const { credits, operator } = f; const hour = BigInt(await time.latest()) / HOUR - 1n; const tree = M.treeOfLeaves(receipts(f, 4).map((r) => M.leafOf(r))); await credits.connect(operator).seal(hour, tree.root); const [left, right] = tree.layers[1]; expect(await credits.verify(hour, left, [right])).to.equal(true); // a node, not a receipt expect(await credits.verify(hour, tree.root, [])).to.equal(true); // the root itself // No receipt hashes to an inner node: a leaf is the hash of 192 bytes, a node the hash of 64. }); it("ties the tree to the charges: every Charged event of an hour has its leaf", async function () { const f = await funded(); const { credits, usdc, eqnvda, alice, bob, operator } = f; await credits.connect(bob).deposit(usdc.target, USDC(20)); const hour = BigInt(await time.latest()) / HOUR + 1n; await time.setNextBlockTimestamp(hour * HOUR + 5n); const list = [ { receiptId: M.receiptId("e0001"), user: alice.address, token: usdc.target, amount: USDC(1.5), secondsBilled: 2007, gpuId: M.gpuId("h100") }, { receiptId: M.receiptId("e0002"), user: bob.address, token: usdc.target, amount: USDC(0.25), secondsBilled: 1525, gpuId: M.gpuId("rtx-4090") }, { receiptId: M.receiptId("e0003"), user: alice.address, token: eqnvda.target, amount: EQNVDA(0.01), secondsBilled: 990, gpuId: M.gpuId("b200") }, ]; for (const r of list) await credits.connect(operator).charge(r.user, r.token, r.amount, r.receiptId); const tree = M.buildTree(list); await expect(credits.connect(operator).seal(hour, tree.root)).to.be.revertedWithCustomError(credits, "HourNotOver"); await time.setNextBlockTimestamp((hour + 1n) * HOUR); await credits.connect(operator).seal(hour, tree.root); // What anyone can do afterwards: read the events of that hour, and ask for the proof of each. const events = await credits.queryFilter(credits.filters.Charged()); expect(events.length).to.equal(3); for (const e of events) { const block = await e.getBlock(); expect(BigInt(block.timestamp) / HOUR).to.equal(hour); const r = list.find((x) => x.receiptId === e.args.receiptId); expect([e.args.user, e.args.token, e.args.amount]).to.deep.equal([r.user, r.token, r.amount]); expect(await credits.verifyReceipt(hour, e.args.receiptId, e.args.user, e.args.token, e.args.amount, r.secondsBilled, r.gpuId, tree.proofOf(r.receiptId))).to.equal(true); expect(M.hourOf(await credits.chargedAt(e.args.receiptId))).to.equal(Number(hour)); } }); }); describe("scripts/merkle.mjs", function () { const base = () => ({ receiptId: M.receiptId("e0001"), user: "0x00000000000000000000000000000000000000a1", token: "0x00000000000000000000000000000000000000b2", amount: 1_500_000n, secondsBilled: 2007, gpuId: M.gpuId("h100"), }); it("refuses an empty hour, a receipt id used twice and malformed receipts", function () { expect(() => M.buildTree([])).to.throw(/at least one receipt/); expect(() => M.buildTree(null)).to.throw(/at least one receipt/); expect(() => M.treeOfLeaves([])).to.throw(/at least one leaf/); expect(() => M.buildTree([base(), { ...base(), amount: 2n }])).to.throw(/receiptId appears twice/); expect(() => M.treeOfLeaves([M.leafOf(base()), M.leafOf(base())])).to.throw(/same leaf appears twice/); expect(() => M.leafOf({ ...base(), receiptId: "e0001" })).to.throw(/receiptId/); expect(() => M.leafOf({ ...base(), gpuId: "h100" })).to.throw(/gpuId/); expect(() => M.leafOf({ ...base(), user: "0x1234" })).to.throw(); expect(() => M.leafOf({ ...base(), amount: -1 })).to.throw(/amount/); expect(() => M.leafOf({ ...base(), amount: 1.5 })).to.throw(/amount/); expect(() => M.leafOf({ ...base(), amount: 2 ** 60 })).to.throw(/amount/); expect(() => M.leafOf({ ...base(), secondsBilled: 2n ** 64n })).to.throw(/secondsBilled/); expect(() => M.leafOf(null)).to.throw(); expect(() => M.receiptId("")).to.throw(); expect(() => M.gpuId("")).to.throw(); expect(() => M.gpuId("x".repeat(32))).to.throw(); }); it("accepts amounts as numbers, text or BigInt, and addresses in any case", function () { const leaf = M.leafOf(base()); expect(M.leafOf({ ...base(), amount: 1_500_000 })).to.equal(leaf); expect(M.leafOf({ ...base(), amount: "1500000", secondsBilled: "2007" })).to.equal(leaf); expect(M.leafOf({ ...base(), user: base().user.toUpperCase().replace("0X", "0x") })).to.equal(leaf); expect(M.leafOf({ ...base(), receiptId: base().receiptId.toUpperCase().replace("0X", "0x") })).to.equal(leaf); }); it("pairs with the smaller hash first, and moves a lone node up unchanged", function () { const [a, b, c] = ["0x" + "11".repeat(32), "0x" + "22".repeat(32), "0x" + "33".repeat(32)]; expect(M.hashPair(a, b)).to.equal(ethers.keccak256(ethers.concat([a, b]))); expect(M.hashPair(b, a)).to.equal(M.hashPair(a, b)); const tree = M.treeOfLeaves([c, a, b]); expect(tree.leaves).to.deep.equal([a, b, c]); expect(tree.layers[1]).to.deep.equal([M.hashPair(a, b), c]); expect(tree.root).to.equal(M.hashPair(M.hashPair(a, b), c)); expect(tree.proofOfLeaf(c)).to.deep.equal([M.hashPair(a, b)]); expect(tree.proofOfLeaf(a)).to.deep.equal([b, c]); expect(() => tree.proofOfLeaf("0x" + "44".repeat(32))).to.throw(/not in the tree/); expect(M.rootFromProof(a, [b, c])).to.equal(tree.root); }); it("counts hours as the contract does", function () { expect(M.hourOf(0)).to.equal(0); expect(M.hourOf(3599)).to.equal(0); expect(M.hourOf(3600)).to.equal(1); expect(M.hourOf(1_795_996_800)).to.equal(498_888); expect(M.hourOf(1_795_996_800n)).to.equal(498_888); }); it("runs from the command line, and its output verifies on chain", async function () { const f = await loadFixture(deploy); const hour = BigInt(await time.latest()) / HOUR - 1n; const dir = mkdtempSync(path.join(tmpdir(), "idle-merkle-")); try { const file = path.join(dir, "receipts.json"); const input = { hour: Number(hour), receipts: [ { id: "e0001", user: f.alice.address, token: f.usdc.target, amount: "1500000", secondsBilled: 2007, gpu: "h100" }, { id: "e0002", user: f.bob.address, token: f.eqnvda.target, amount: "1000000", secondsBilled: 990, gpu: "b200" }, { id: "e0003", user: f.carol.address, token: f.usdc.target, amount: "250000", secondsBilled: 1525, gpu: "rtx-4090" }, ], }; writeFileSync(file, JSON.stringify(input)); const out = JSON.parse(execFileSync(process.execPath, [path.join(__dirname, "..", "scripts", "merkle.mjs"), file], { encoding: "utf8" })); expect(out.hour).to.equal(Number(hour)); expect(out.receipts.length).to.equal(3); await f.credits.connect(f.operator).seal(hour, out.root); for (const r of out.receipts) { expect(await f.credits.verifyReceipt(hour, r.receiptId, r.user, r.token, r.amount, r.secondsBilled, r.gpuId, r.proof)).to.equal(true); expect(await f.credits.verify(hour, r.leaf, r.proof)).to.equal(true); } expect(out.receipts[0].receiptId).to.equal(M.receiptId("e0001")); expect(out.receipts[1].gpuId).to.equal(M.gpuId("b200")); } finally { rmSync(dir, { recursive: true, force: true }); } }); }); describe("operator rotation", function () { it("hands over in two steps", async function () { const { credits, usdc, alice, bob, operator, treasury } = await funded(); await expect(credits.connect(operator).proposeOperator(bob.address)).to.emit(credits, "OperatorProposed").withArgs(operator.address, bob.address); expect(await credits.pendingOperator()).to.equal(bob.address); // Nothing has changed yet. expect(await credits.operator()).to.equal(operator.address); await expect(credits.connect(bob).charge(alice.address, usdc.target, 1, RID("a"))).to.be.revertedWithCustomError(credits, "NotOperator"); await credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("a")); await expect(credits.connect(bob).acceptOperator()).to.emit(credits, "OperatorChanged").withArgs(operator.address, bob.address); expect(await credits.operator()).to.equal(bob.address); expect(await credits.pendingOperator()).to.equal(ethers.ZeroAddress); // The old operator has lost every power, the new one has them all. const hour = BigInt(await time.latest()) / HOUR - 1n; await expect(credits.connect(operator).charge(alice.address, usdc.target, 1, RID("b"))).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(operator).collect(usdc.target, operator.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(operator).seal(hour, RID("r"))).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(operator).proposeOperator(operator.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await credits.connect(bob).charge(alice.address, usdc.target, USDC(2), RID("b")); await credits.connect(bob).seal(hour, RID("r")); await expect(credits.connect(bob).collect(usdc.target, treasury.address)).to.changeTokenBalances(usdc, [treasury], [USDC(3)]); // earned under both }); it("only the operator proposes, only the proposed address accepts", async function () { const { credits, alice, bob, carol, operator, deployer } = await loadFixture(deploy); await expect(credits.connect(alice).proposeOperator(alice.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(deployer).proposeOperator(deployer.address)).to.be.revertedWithCustomError(credits, "NotOperator"); await expect(credits.connect(alice).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); // nobody is proposed await credits.connect(operator).proposeOperator(bob.address); await expect(credits.connect(carol).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); await expect(credits.connect(operator).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); expect(await credits.operator()).to.equal(operator.address); }); it("a proposal can be replaced or withdrawn before it is accepted", async function () { const { credits, bob, carol, operator } = await loadFixture(deploy); await credits.connect(operator).proposeOperator(bob.address); await credits.connect(operator).proposeOperator(carol.address); await expect(credits.connect(bob).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); await expect(credits.connect(operator).proposeOperator(ethers.ZeroAddress)).to.emit(credits, "OperatorProposed").withArgs(operator.address, ethers.ZeroAddress); await expect(credits.connect(carol).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); expect(await credits.operator()).to.equal(operator.address); await credits.connect(operator).proposeOperator(carol.address); await credits.connect(carol).acceptOperator(); expect(await credits.operator()).to.equal(carol.address); }); it("an accepted proposal cannot be accepted again, and the operator can never become the zero address", async function () { const { credits, bob, operator } = await loadFixture(deploy); await credits.connect(operator).proposeOperator(bob.address); await credits.connect(bob).acceptOperator(); await expect(credits.connect(bob).acceptOperator()).to.be.revertedWithCustomError(credits, "NotPendingOperator"); // The zero address cannot call acceptOperator, so proposing it can only withdraw a proposal. await credits.connect(bob).proposeOperator(ethers.ZeroAddress); expect(await credits.operator()).to.equal(bob.address); }); it("changes nothing for users: balances and pending withdrawals survive a handover", async function () { const { credits, usdc, alice, bob, operator } = await funded(); await credits.connect(alice).requestWithdrawal(usdc.target, USDC(100)); await credits.connect(operator).proposeOperator(bob.address); await credits.connect(bob).acceptOperator(); await time.increase(DELAY); await expect(credits.connect(alice).withdraw(usdc.target)).to.changeTokenBalances(usdc, [alice], [USDC(100)]); }); }); describe("reentrancy through a hostile token", function () { // The first token is hostile and is also the operator, so that it can try every function from inside a transfer. async function hostile() { const [, , alice, bob] = await ethers.getSigners(); const token = await (await ethers.getContractFactory("ReentrantToken")).deploy(); const other = await (await ethers.getContractFactory("MockERC20")).deploy("EQX NVIDIA", "EQNVDA", 8); const Credits = await ethers.getContractFactory("IdleCredits"); const credits = await Credits.deploy(token.target, other.target, token.target, DELAY); const call = (name, args) => credits.interface.encodeFunctionData(name, args); const asToken = (name, args) => token.exec(credits.target, call(name, args)); await token.mint(alice.address, 1000); await token.mint(token.target, 1000); await token.connect(alice).approve(credits.target, ethers.MaxUint256); await token.exec(token.target, token.interface.encodeFunctionData("approve", [credits.target, ethers.MaxUint256])); // Alice: 500 here, 200 of them asked back. The token itself: 300 here, 100 asked back. 100 earned. await credits.connect(alice).deposit(token.target, 600); await asToken("deposit", [token.target, 300]); await asToken("charge", [alice.address, token.target, 100, RID("setup")]); await credits.connect(alice).requestWithdrawal(token.target, 200); await asToken("requestWithdrawal", [token.target, 100]); await time.increase(DELAY); // Each of these would succeed if the token made it in a transaction of its own. const attacks = { deposit: call("deposit", [token.target, 10]), requestWithdrawal: call("requestWithdrawal", [token.target, 10]), cancelWithdrawal: call("cancelWithdrawal", [token.target]), withdraw: call("withdraw", [token.target]), charge: call("charge", [alice.address, token.target, 1, RID("attack")]), collect: call("collect", [token.target, token.target]), }; return { credits, token, alice, bob, attacks, asToken, call }; } async function expectUnchanged(f) { expect(await f.credits.balanceOf(f.token.target, f.token.target)).to.equal(300); expect(await f.credits.pendingWithdrawal(f.token.target, f.token.target).then((p) => p[0])).to.equal(100); expect(await f.credits.chargedAt(RID("attack"))).to.equal(0); } it("each call the token will try is a valid call on its own", async function () { for (const name of ["deposit", "requestWithdrawal", "cancelWithdrawal", "withdraw", "charge", "collect"]) { const f = await loadFixture(hostile); await f.token.exec(f.credits.target, f.attacks[name]); } }); for (const name of ["deposit", "requestWithdrawal", "cancelWithdrawal", "withdraw", "charge", "collect"]) { it(`blocks ${name}() from inside a deposit, a withdrawal and a collection`, async function () { const outer = { deposit: (f) => f.credits.connect(f.alice).deposit(f.token.target, 50), withdraw: (f) => f.credits.connect(f.alice).withdraw(f.token.target), collect: (f) => f.asToken("collect", [f.token.target, f.bob.address]), }; for (const [during, run] of Object.entries(outer)) { const f = await loadFixture(hostile); await f.token.arm(f.credits.target, f.attacks[name]); await run(f); // the honest call goes through expect(await f.token.attempted(), `${name} during ${during}: attempted`).to.equal(true); expect(await f.token.succeeded(), `${name} during ${during}: succeeded`).to.equal(false); expect(await f.token.lastError(), `${name} during ${during}: reason`).to.equal(selector("Reentrancy()")); await expectUnchanged(f); // And the honest call had exactly its usual effect. if (during === "deposit") expect(await f.credits.balanceOf(f.alice.address, f.token.target)).to.equal(550); if (during === "withdraw") expect(await f.token.balanceOf(f.alice.address)).to.equal(600); if (during === "collect") expect(await f.token.balanceOf(f.bob.address)).to.equal(100); expect(await f.token.balanceOf(f.credits.target)).to.equal((await f.credits.totalBalance(f.token.target)) + (await f.credits.earned(f.token.target))); } }); } it("is usable again after a blocked attempt", async function () { const f = await loadFixture(hostile); await f.token.arm(f.credits.target, f.attacks.withdraw); await f.credits.connect(f.alice).deposit(f.token.target, 50); await f.credits.connect(f.alice).deposit(f.token.target, 50); await f.token.exec(f.credits.target, f.attacks.withdraw); expect(await f.credits.balanceOf(f.alice.address, f.token.target)).to.equal(600); expect(await f.credits.balanceOf(f.token.target, f.token.target)).to.equal(200); }); }); describe("the books always balance", function () { it("holds through 300 pseudo-random steps checked against a model", async function () { this.timeout(120_000); const f = await loadFixture(deploy); const { credits, operator, treasury } = f; const users = [f.alice, f.bob, f.carol]; const tokens = [f.usdc, f.eqnvda]; // A small deterministic generator, so a failure can be replayed. let seed = 0x1d1e5eed; const rnd = (n) => { seed = (seed + 0x6d2b79f5) >>> 0; // mulberry32 let x = Math.imul(seed ^ (seed >>> 15), seed | 1); x ^= x + Math.imul(x ^ (x >>> 7), x | 61); return ((x ^ (x >>> 14)) >>> 0) % n; }; // The model: what the rules in the contract's notice say should happen. const key = (u, t) => u.address + t.target; const bal = new Map(); const pend = new Map(); const earned = new Map(tokens.map((t) => [t.target, 0n])); const collected = new Map(tokens.map((t) => [t.target, 0n])); for (const u of users) for (const t of tokens) bal.set(key(u, t), 0n); const min = (a, b) => (a < b ? a : b); let receipts = 0; const counts = { deposit: 0, request: 0, cancel: 0, withdraw: 0, early: 0, charge: 0, overcharge: 0, collect: 0 }; for (let step = 0; step < 300; step++) { const u = users[rnd(3)]; const t = tokens[rnd(2)]; const k = key(u, t); const now = BigInt(await time.latest()) + 1n; // the timestamp of the next block const p = pend.get(k); const matured = p && now >= p.unlockAt; const reserved = matured ? min(p.amount, bal.get(k)) : 0n; const chargeable = bal.get(k) - reserved; switch (rnd(8)) { case 0: case 1: { const amount = BigInt(1 + rnd(5_000_000)); await credits.connect(u).deposit(t.target, amount); bal.set(k, bal.get(k) + amount); counts.deposit++; break; } case 2: { if (bal.get(k) === 0n) break; const amount = BigInt(1 + rnd(Number(min(bal.get(k), 4_000_000_000n)))); await credits.connect(u).requestWithdrawal(t.target, amount); pend.set(k, { amount, unlockAt: now + DELAY }); counts.request++; break; } case 3: { if (!p) { await expect(credits.connect(u).withdraw(t.target)).to.be.revertedWithCustomError(credits, "NothingPending"); } else if (!matured) { await expect(credits.connect(u).withdraw(t.target)).to.be.revertedWithCustomError(credits, "TooEarly"); counts.early++; } else { const amount = min(p.amount, bal.get(k)); await expect(credits.connect(u).withdraw(t.target)).to.changeTokenBalances(t, [u, credits], [amount, -amount]); bal.set(k, bal.get(k) - amount); pend.delete(k); counts.withdraw++; } break; } case 4: case 5: { const id = RID("model-" + receipts++); if (rnd(4) === 0) { // The operator reaches for more than he may. await expect(credits.connect(operator).charge(u.address, t.target, chargeable + 1n, id)).to.be.revertedWithCustomError(credits, "InsufficientBalance"); counts.overcharge++; } else if (chargeable > 0n) { const amount = BigInt(1 + rnd(Number(min(chargeable, 4_000_000_000n)))); await credits.connect(operator).charge(u.address, t.target, amount, id); bal.set(k, bal.get(k) - amount); earned.set(t.target, earned.get(t.target) + amount); counts.charge++; } break; } case 6: { if (rnd(3) === 0 && p) { await credits.connect(u).cancelWithdrawal(t.target); pend.delete(k); counts.cancel++; } else if (earned.get(t.target) > 0n && rnd(2) === 0) { await credits.connect(operator).collect(t.target, treasury.address); collected.set(t.target, collected.get(t.target) + earned.get(t.target)); earned.set(t.target, 0n); counts.collect++; } break; } default: await time.increase(BigInt(1 + rnd(2400))); } // After every step, the chain and the model agree, and the contract holds exactly what it owes. const at = BigInt(await time.latest()); for (const token of tokens) { let sum = 0n; for (const user of users) { const kk = key(user, token); const b = bal.get(kk); const pp = pend.get(kk); sum += b; expect(await credits.balanceOf(user.address, token.target)).to.equal(b); const [amount, unlockAt] = await credits.pendingWithdrawal(user.address, token.target); expect(amount).to.equal(pp ? min(pp.amount, b) : 0n); expect(unlockAt).to.equal(pp ? pp.unlockAt : 0n); expect(await credits.available(user.address, token.target)).to.equal(pp ? b - min(pp.amount, b) : b); expect(await credits.chargeable(user.address, token.target)).to.equal(pp && at >= pp.unlockAt ? b - min(pp.amount, b) : b); } expect(await credits.totalBalance(token.target)).to.equal(sum); expect(await credits.earned(token.target)).to.equal(earned.get(token.target)); expect(await token.balanceOf(credits.target)).to.equal(sum + earned.get(token.target)); expect(await token.balanceOf(treasury.address)).to.equal(collected.get(token.target)); } } // The run must really have exercised every path. for (const [name, n] of Object.entries(counts)) expect(n, name).to.be.greaterThan(0); }); }); describe("gas", function () { it("reports what each call costs", async function () { const f = await funded(); const { credits, Credits, usdc, eqnvda, alice, bob, operator, treasury } = f; const used = async (tx) => (await (await tx).wait()).gasUsed; const rows = []; rows.push(["deploy", (await credits.deploymentTransaction().wait()).gasUsed]); rows.push(["deposit (first)", await used(credits.connect(bob).deposit(usdc.target, USDC(10)))]); rows.push(["deposit (again)", await used(credits.connect(bob).deposit(usdc.target, USDC(10)))]); rows.push(["charge", await used(credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("g1")))]); rows.push(["charge (again)", await used(credits.connect(operator).charge(alice.address, usdc.target, USDC(1), RID("g2")))]); rows.push(["requestWithdrawal", await used(credits.connect(alice).requestWithdrawal(usdc.target, USDC(50)))]); await time.increase(DELAY); rows.push(["withdraw", await used(credits.connect(alice).withdraw(usdc.target))]); rows.push(["collect", await used(credits.connect(operator).collect(usdc.target, treasury.address))]); rows.push(["seal", await used(credits.connect(operator).seal(BigInt(await time.latest()) / HOUR - 1n, RID("root")))]); console.log(rows.map(([name, gas]) => ` ${name.padEnd(20)} ${gas.toString().padStart(9)} gas`).join("\n")); const size = ethers.dataLength(await ethers.provider.getCode(credits.target)); console.log(` ${"deployed code".padEnd(20)} ${String(size).padStart(9)} bytes (limit 24576)`); expect(size).to.be.lessThan(24_576); expect(Credits.bytecode.length).to.be.greaterThan(0); expect(await eqnvda.balanceOf(credits.target)).to.equal(EQNVDA(2)); }); }); });