diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 7c4918fe..d2042979 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -53,7 +53,7 @@ jobs: run: yarn - name: Run coverage - run: forge coverage --match-path "test/{Swarm*,ServiceProvider,FleetIdentity,collections/*,tipping/*}*.t.sol" --ir-minimum --report lcov --report-file coverage.lcov + run: forge coverage --match-path "test/{Swarm*,ServiceProvider,FleetIdentity,collections/*,tipping/*,arcade/*}*.t.sol" --ir-minimum --report lcov --report-file coverage.lcov - name: Upload coverage report uses: actions/upload-artifact@v4 @@ -177,6 +177,39 @@ jobs: echo "Coverage check passed: $COVERAGE% >= $THRESHOLD%" + - name: Check line coverage threshold (arcade) + run: | + # Extract line coverage from lcov report for src/arcade/ contracts only + LINES_FOUND=$(awk ' + /^SF:.*src\/arcade\// { in_section = 1 } + /^end_of_record/ { in_section = 0 } + in_section && /^LF:/ { sum += substr($0, 4) } + END { print sum+0 } + ' coverage.lcov) + + LINES_HIT=$(awk ' + /^SF:.*src\/arcade\// { in_section = 1 } + /^end_of_record/ { in_section = 0 } + in_section && /^LH:/ { sum += substr($0, 4) } + END { print sum+0 } + ' coverage.lcov) + + if [ "$LINES_FOUND" -eq 0 ]; then + echo "Error: No lines found in coverage report for src/arcade/" + exit 1 + fi + + COVERAGE=$(awk "BEGIN {printf \"%.2f\", ($LINES_HIT / $LINES_FOUND) * 100}") + echo "Arcade line coverage: $COVERAGE% ($LINES_HIT / $LINES_FOUND lines)" + + THRESHOLD=95 + if awk "BEGIN {exit !($COVERAGE < $THRESHOLD)}"; then + echo "Error: Line coverage ($COVERAGE%) is below the required threshold ($THRESHOLD%)" + exit 1 + fi + + echo "Coverage check passed: $COVERAGE% >= $THRESHOLD%" + Specification-PDF: runs-on: ubuntu-latest if: github.event_name == 'pull_request' && github.base_ref == 'main' diff --git a/ops/verify_zksync_contracts.py b/ops/verify_zksync_contracts.py index ec07e1a7..22044813 100755 --- a/ops/verify_zksync_contracts.py +++ b/ops/verify_zksync_contracts.py @@ -92,6 +92,7 @@ "UserCollection1155": "src/collections/UserCollection1155.sol:UserCollection1155", "FundraiserFactory": "src/fundraising/FundraiserFactory.sol:FundraiserFactory", "Fundraiser": "src/fundraising/Fundraiser.sol:Fundraiser", + "ArcadeEscrow": "src/arcade/ArcadeEscrow.sol:ArcadeEscrow", } # Some zkSync forge broadcasts record deployments as calls to ContractDeployer @@ -126,6 +127,9 @@ "DeployFundraiserFactory.s.sol": [ "FundraiserFactory", ], + "DeployArcadeEscrow.s.sol": [ + "ArcadeEscrow", + ], } diff --git a/script/DeployArcadeEscrow.s.sol b/script/DeployArcadeEscrow.s.sol new file mode 100644 index 00000000..e79dd5a3 --- /dev/null +++ b/script/DeployArcadeEscrow.s.sol @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear + +pragma solidity ^0.8.26; + +import {Script, console} from "forge-std/Script.sol"; + +import {ArcadeEscrow} from "../src/arcade/ArcadeEscrow.sol"; + +/** + * @title DeployArcadeEscrow + * @notice Deployment script for the Arcade NODL escrow on ZkSync Era. + * @dev Design: agent-stack `docs/arcade-artifacts-backend-design.md`, section 9.3. + * + * The contract holds user funds and is not upgradeable: there is no proxy. To sponsor + * gas for `deposit`, whitelist the deployed address on the existing `WhitelistPaymaster` + * (`addWhitelistedContracts`); that is a separate admin transaction. + * + * Usage: + * forge script script/DeployArcadeEscrow.s.sol \ + * --rpc-url $L2_RPC --broadcast --zksync + * + * Environment Variables: + * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas. + * - N_TOKEN_ADDR: NODL token address. + * - N_ARCADE_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE. + * - N_ARCADE_ORACLE: arcade-forge settlement key, granted ORACLE_ROLE. + * - N_ARCADE_QUOTA: Total NODL (wei) that may be charged per period. + * - N_ARCADE_PERIOD: Optional quota period in seconds, defaults to 1 day. + * - N_ARCADE_MIN_DEPOSIT: Smallest deposit (wei) into an empty balance. + * - N_ARCADE_MAX_CHARGE: Largest single charge (wei). + * - N_ARCADE_WITHDRAW_DELAY: Optional, seconds, defaults to 1 hour. + */ +contract DeployArcadeEscrow is Script { + function run() external { + uint256 deployerPrivateKey = vm.envUint("DEPLOYER_PRIVATE_KEY"); + address nodl = vm.envAddress("N_TOKEN_ADDR"); + address admin = vm.envAddress("N_ARCADE_ADMIN"); + address oracle = vm.envAddress("N_ARCADE_ORACLE"); + uint256 quota = vm.envUint("N_ARCADE_QUOTA"); + uint256 period = vm.envOr("N_ARCADE_PERIOD", uint256(1 days)); + uint256 minDeposit = vm.envUint("N_ARCADE_MIN_DEPOSIT"); + uint256 maxCharge = vm.envUint("N_ARCADE_MAX_CHARGE"); + uint256 withdrawDelayRaw = vm.envOr("N_ARCADE_WITHDRAW_DELAY", uint256(1 hours)); + + // The constructor enforces the delay cap too; failing here saves a broadcast round-trip. + require(withdrawDelayRaw <= type(uint64).max, "N_ARCADE_WITHDRAW_DELAY out of range"); + require(maxCharge != 0, "N_ARCADE_MAX_CHARGE is zero"); + require(quota >= maxCharge, "N_ARCADE_QUOTA is below one max charge"); + uint64 withdrawDelay = uint64(withdrawDelayRaw); + + console.log("=== Deploying ArcadeEscrow on ZkSync ==="); + console.log("NODL:", nodl); + console.log("Admin:", admin); + console.log("Oracle:", oracle); + console.log("Quota / period:", quota, period); + console.log("Min deposit:", minDeposit); + console.log("Max charge:", maxCharge); + console.log("Withdraw delay:", withdrawDelay); + + vm.startBroadcast(deployerPrivateKey); + ArcadeEscrow escrow = new ArcadeEscrow(nodl, oracle, admin, quota, period, minDeposit, maxCharge, withdrawDelay); + vm.stopBroadcast(); + + console.log(""); + console.log("ArcadeEscrow:", address(escrow)); + } +} diff --git a/src/QuotaControl.sol b/src/QuotaControl.sol index 429efa49..f46cfdda 100644 --- a/src/QuotaControl.sol +++ b/src/QuotaControl.sol @@ -94,7 +94,7 @@ contract QuotaControl is AccessControl { * @dev Sets a new reward quota. Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. * @param newQuota The new maximum amount of rewards distributable in each period. */ - function setQuota(uint256 newQuota) external onlyRole(DEFAULT_ADMIN_ROLE) { + function setQuota(uint256 newQuota) external virtual onlyRole(DEFAULT_ADMIN_ROLE) { quota = newQuota; emit QuotaSet(newQuota); } @@ -106,7 +106,7 @@ contract QuotaControl is AccessControl { * Requirements: * - `newPeriod` must be greater than 0 and less than or equal to `MAX_PERIOD`. */ - function setPeriod(uint256 newPeriod) external onlyRole(DEFAULT_ADMIN_ROLE) { + function setPeriod(uint256 newPeriod) external virtual onlyRole(DEFAULT_ADMIN_ROLE) { _mustBeWithinPeriodRange(newPeriod); period = newPeriod; emit PeriodSet(newPeriod); diff --git a/src/arcade/ArcadeEscrow.sol b/src/arcade/ArcadeEscrow.sol new file mode 100644 index 00000000..edcf60ae --- /dev/null +++ b/src/arcade/ArcadeEscrow.sol @@ -0,0 +1,376 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {QuotaControl} from "../QuotaControl.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; + +/** + * @title ArcadeEscrow + * @notice Per-wallet NODL balance that pays for Arcade game builds. + * @dev Design: agent-stack `docs/arcade-artifacts-backend-design.md`, section 9.3. + * + * - A wallet tops up its balance with `deposit` (or anyone with `depositFor`). The balance is + * reused across builds, so funding happens rarely. + * - The oracle (arcade-forge) `charge`s a balance once per charged build. `ref` is a random + * nonce per build, never an artifact id, so the chain cannot link a charge to a game. + * - A wallet leaves with `requestWithdraw` → `withdraw` after `withdrawDelay`. The delay covers + * builds already running; arcade-forge never starts a build while a request is pending. + * + * Admin timelock: anything that widens what can be charged waits `ADMIN_DELAY`, which is longer + * than `MAX_WITHDRAW_DELAY`. That covers granting `ORACLE_ROLE`, raising `maxCharge` or the + * quota, and shortening the quota period. A user who disagrees with a scheduled change can + * `requestWithdraw` and be out before it applies. Changes that narrow it (revoking the oracle, + * lowering limits, pausing) apply immediately, so incident response is never delayed. + * + * Guarantees, which hold even with a compromised oracle key: + * - `withdrawFees` reaches `feesAccrued` only, never a user's balance, so + * `token.balanceOf(this) >= Σ balanceOf + feesAccrued` always holds. + * - `maxCharge` per call and `QuotaControl` per period bound a leaked oracle key, which can + * only move NODL into `feesAccrued`, which it cannot withdraw. + * - Pausing blocks `deposit` and `charge`, never a withdrawal. + * - `withdrawDelay` is capped by `MAX_WITHDRAW_DELAY`, so the admin cannot lock balances. + * - Not upgradeable. `token` must be a plain ERC-20 (no fee on transfer, no rebasing): NODL. + */ +contract ArcadeEscrow is QuotaControl, Pausable, ReentrancyGuard { + using SafeERC20 for IERC20; + + /// @dev Role identifier for the oracle. Accounts with this role can charge balances. + bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE"); + + /// @dev Upper bound on `withdrawDelay`, so a balance can never be locked for long. + uint64 public constant MAX_WITHDRAW_DELAY = 7 days; + + /// @dev Wait before a scheduled change applies. Longer than any withdrawal delay, so users can exit first. + uint64 public constant ADMIN_DELAY = MAX_WITHDRAW_DELAY + 1 days; + + /// @dev Admin changes that widen what can be charged, and so must wait `ADMIN_DELAY`. + enum Change { + GrantOracle, + MaxCharge, + Quota, + Period + } + + /// @dev A pending withdrawal. `amount == 0` means none is pending. + struct Withdrawal { + uint128 amount; + uint64 readyAt; + } + + /// @dev ERC20 token held in escrow (NODL). + IERC20 public immutable token; + + /// @dev Spendable balance per wallet. + mapping(address => uint256) public balanceOf; + + /// @dev At most one pending withdrawal per wallet. + mapping(address => Withdrawal) public withdrawals; + + /// @dev Per charged ref, `keccak256(account, amount)`, for idempotent settlement. + mapping(bytes32 => bytes32) public chargeOf; + + /// @dev Charged NODL the admin may withdraw. + uint256 public feesAccrued; + + /// @dev Smallest deposit that may fund an empty balance. + uint256 public minDeposit; + + /// @dev Largest amount a single `charge` may take. + uint256 public maxCharge; + + /// @dev Seconds between `requestWithdraw` and `withdraw`. + uint64 public withdrawDelay; + + /// @dev Per scheduled change, `keccak256(kind, value)`, the time it may be executed. + mapping(bytes32 => uint256) public scheduledChanges; + + event Deposited(address indexed account, address indexed from, uint256 amount, uint256 balance); + event WithdrawRequested(address indexed account, uint256 amount, uint64 readyAt); + event WithdrawCancelled(address indexed account); + event Withdrawn(address indexed account, uint256 amount); + event Charged(address indexed account, uint256 amount, bytes32 indexed ref); + event FeesWithdrawn(address indexed to, uint256 amount); + event MinDepositSet(uint256 minDeposit); + event MaxChargeSet(uint256 maxCharge); + event WithdrawDelaySet(uint64 withdrawDelay); + event ChangeScheduled(Change indexed kind, uint256 value, uint256 readyAt); + event ChangeCancelled(Change indexed kind, uint256 value); + event ChangeExecuted(Change indexed kind, uint256 value); + + error ZeroAddress(); + error ZeroAmount(); + error BelowMinDeposit(uint256 amount, uint256 minDeposit); + error InsufficientBalance(uint256 balance, uint256 needed); + error AmountTooLarge(uint256 amount); + error NoPendingWithdrawal(); + error WithdrawalNotReady(uint64 readyAt); + error AboveMaxCharge(uint256 amount, uint256 maxCharge); + error AlreadyCharged(bytes32 ref); + error ChargeConflict(bytes32 ref); + error InsufficientFees(uint256 feesAccrued, uint256 needed); + error WithdrawDelayTooLong(uint64 withdrawDelay); + error NeedsTimelock(); + error ChangeAlreadyScheduled(Change kind, uint256 value); + error ChangeNotScheduled(Change kind, uint256 value); + error ChangeNotReady(uint256 readyAt); + + /** + * @param _token The ERC20 token held in escrow (NODL). + * @param oracle The account granted `ORACLE_ROLE` (arcade-forge's settlement key). + * @param admin The account granted `DEFAULT_ADMIN_ROLE` (a multisig). + * @param initialQuota Total that may be charged per period, across all wallets. + * @param initialPeriod Quota period in seconds. + * @param _minDeposit Smallest deposit that may fund an empty balance. + * @param _maxCharge Largest amount a single `charge` may take. + * @param _withdrawDelay Seconds between `requestWithdraw` and `withdraw`, at most `MAX_WITHDRAW_DELAY`. + */ + constructor( + address _token, + address oracle, + address admin, + uint256 initialQuota, + uint256 initialPeriod, + uint256 _minDeposit, + uint256 _maxCharge, + uint64 _withdrawDelay + ) QuotaControl(initialQuota, initialPeriod, admin) { + if (_token == address(0) || oracle == address(0) || admin == address(0)) { + revert ZeroAddress(); + } + _mustBeValidWithdrawDelay(_withdrawDelay); + + token = IERC20(_token); + _grantRole(ORACLE_ROLE, oracle); + minDeposit = _minDeposit; + maxCharge = _maxCharge; + withdrawDelay = _withdrawDelay; + } + + // ── Users ───────────────────────────────────────────── + + /// @notice Tops up the caller's balance. Requires a prior `approve` of `amount`. + function deposit(uint256 amount) external whenNotPaused nonReentrant { + _deposit(msg.sender, amount); + } + + /// @notice Tops up `account`'s balance from the caller. Only `account` can withdraw it. + function depositFor(address account, uint256 amount) external whenNotPaused nonReentrant { + if (account == address(0)) revert ZeroAddress(); + _deposit(account, amount); + } + + /** + * @notice Starts a withdrawal of `amount`, payable after `withdrawDelay`. + * @dev Replaces any pending request and restarts its timer. + */ + function requestWithdraw(uint256 amount) external { + if (amount == 0) revert ZeroAmount(); + uint256 balance = balanceOf[msg.sender]; + if (amount > balance) revert InsufficientBalance(balance, amount); + if (amount > type(uint128).max) revert AmountTooLarge(amount); + + uint64 readyAt = uint64(block.timestamp) + withdrawDelay; + withdrawals[msg.sender] = Withdrawal({amount: uint128(amount), readyAt: readyAt}); + emit WithdrawRequested(msg.sender, amount, readyAt); + } + + /// @notice Cancels the caller's pending withdrawal, so builds can start again. + function cancelWithdraw() external { + if (withdrawals[msg.sender].amount == 0) revert NoPendingWithdrawal(); + delete withdrawals[msg.sender]; + emit WithdrawCancelled(msg.sender); + } + + /** + * @notice Pays out the caller's pending withdrawal once it is ready. + * @dev Pays `min(requested, balance)`: a charge that landed during the delay is deducted. + */ + function withdraw() external nonReentrant { + Withdrawal memory w = withdrawals[msg.sender]; + if (w.amount == 0) revert NoPendingWithdrawal(); + if (block.timestamp < w.readyAt) revert WithdrawalNotReady(w.readyAt); + + uint256 balance = balanceOf[msg.sender]; + uint256 amount = w.amount < balance ? w.amount : balance; + + delete withdrawals[msg.sender]; + balanceOf[msg.sender] = balance - amount; + emit Withdrawn(msg.sender, amount); + + if (amount != 0) token.safeTransfer(msg.sender, amount); + } + + // ── Oracle ──────────────────────────────────────────── + + /** + * @notice Charges `amount` from `account`'s balance into `feesAccrued`, once per `ref`. + * @dev A retry with the same `ref`, account and amount reverts with `AlreadyCharged`, which the + * settlement worker reads as "already settled". The same `ref` with a different account or + * amount reverts with `ChargeConflict`. Counted against the per-period quota. + */ + function charge(address account, uint256 amount, bytes32 ref) external whenNotPaused onlyRole(ORACLE_ROLE) { + if (amount == 0) revert ZeroAmount(); + bytes32 payload = keccak256(abi.encode(account, amount)); + bytes32 previous = chargeOf[ref]; + if (previous != 0) { + if (previous == payload) revert AlreadyCharged(ref); + revert ChargeConflict(ref); + } + if (amount > maxCharge) revert AboveMaxCharge(amount, maxCharge); + uint256 balance = balanceOf[account]; + if (amount > balance) revert InsufficientBalance(balance, amount); + + _checkedResetClaimed(); + _checkedUpdateClaimed(amount); + + chargeOf[ref] = payload; + balanceOf[account] = balance - amount; + feesAccrued += amount; + emit Charged(account, amount, ref); + } + + /// @notice Whether `ref` has been charged. + function charged(bytes32 ref) external view returns (bool) { + return chargeOf[ref] != 0; + } + + // ── Admin ───────────────────────────────────────────── + + /// @notice Withdraws up to `feesAccrued`. Users' balances are never reachable. + function withdrawFees(address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { + if (to == address(0)) revert ZeroAddress(); + if (amount > feesAccrued) revert InsufficientFees(feesAccrued, amount); + + feesAccrued -= amount; + emit FeesWithdrawn(to, amount); + token.safeTransfer(to, amount); + } + + function setMinDeposit(uint256 newMinDeposit) external onlyRole(DEFAULT_ADMIN_ROLE) { + minDeposit = newMinDeposit; + emit MinDepositSet(newMinDeposit); + } + + /// @dev Lowers `maxCharge` immediately. Raising it goes through `scheduleChange`. + function setMaxCharge(uint256 newMaxCharge) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (newMaxCharge > maxCharge) revert NeedsTimelock(); + _setMaxCharge(newMaxCharge); + } + + /// @dev Lowers the quota immediately. Raising it goes through `scheduleChange`. + function setQuota(uint256 newQuota) external override onlyRole(DEFAULT_ADMIN_ROLE) { + if (newQuota > quota) revert NeedsTimelock(); + _setQuota(newQuota); + } + + /// @dev Lengthens the period immediately. Shortening it goes through `scheduleChange`. + function setPeriod(uint256 newPeriod) external override onlyRole(DEFAULT_ADMIN_ROLE) { + if (newPeriod < period) revert NeedsTimelock(); + _setPeriod(newPeriod); + } + + /// @dev `ORACLE_ROLE` is granted through `scheduleChange` only. Revoking stays immediate. + function grantRole(bytes32 role, address account) public override { + if (role == ORACLE_ROLE) revert NeedsTimelock(); + super.grantRole(role, account); + } + + /** + * @notice Schedules a change that widens what can be charged, executable after `ADMIN_DELAY`. + * @param kind What to change. + * @param value The new value. For `GrantOracle`, the oracle address as a `uint256`. + */ + function scheduleChange(Change kind, uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (kind == Change.GrantOracle) { + if (value == 0) revert ZeroAddress(); + if (value > type(uint160).max) revert AmountTooLarge(value); + } + if (kind == Change.Period) _mustBeWithinPeriodRange(value); + + bytes32 id = _changeId(kind, value); + if (scheduledChanges[id] != 0) revert ChangeAlreadyScheduled(kind, value); + + uint256 readyAt = block.timestamp + ADMIN_DELAY; + scheduledChanges[id] = readyAt; + emit ChangeScheduled(kind, value, readyAt); + } + + function cancelChange(Change kind, uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { + bytes32 id = _changeId(kind, value); + if (scheduledChanges[id] == 0) revert ChangeNotScheduled(kind, value); + delete scheduledChanges[id]; + emit ChangeCancelled(kind, value); + } + + function executeChange(Change kind, uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { + bytes32 id = _changeId(kind, value); + uint256 readyAt = scheduledChanges[id]; + if (readyAt == 0) revert ChangeNotScheduled(kind, value); + if (block.timestamp < readyAt) revert ChangeNotReady(readyAt); + delete scheduledChanges[id]; + + if (kind == Change.GrantOracle) _grantRole(ORACLE_ROLE, address(uint160(value))); + else if (kind == Change.MaxCharge) _setMaxCharge(value); + else if (kind == Change.Quota) _setQuota(value); + else _setPeriod(value); + emit ChangeExecuted(kind, value); + } + + /// @dev Applies to new requests only: a pending request keeps its `readyAt`. + function setWithdrawDelay(uint64 newWithdrawDelay) external onlyRole(DEFAULT_ADMIN_ROLE) { + _mustBeValidWithdrawDelay(newWithdrawDelay); + withdrawDelay = newWithdrawDelay; + emit WithdrawDelaySet(newWithdrawDelay); + } + + /// @notice Blocks `deposit` and `charge`. Withdrawals stay open. + function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { + _pause(); + } + + function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { + _unpause(); + } + + // ── Internal ────────────────────────────────────────── + + function _deposit(address account, uint256 amount) internal { + if (amount == 0) revert ZeroAmount(); + uint256 balance = balanceOf[account]; + // The minimum applies to an empty balance only, so small top-ups are never blocked. + if (balance == 0 && amount < minDeposit) revert BelowMinDeposit(amount, minDeposit); + + uint256 newBalance = balance + amount; + balanceOf[account] = newBalance; + emit Deposited(account, msg.sender, amount, newBalance); + + token.safeTransferFrom(msg.sender, address(this), amount); + } + + function _setMaxCharge(uint256 newMaxCharge) internal { + maxCharge = newMaxCharge; + emit MaxChargeSet(newMaxCharge); + } + + function _setQuota(uint256 newQuota) internal { + quota = newQuota; + emit QuotaSet(newQuota); + } + + function _setPeriod(uint256 newPeriod) internal { + _mustBeWithinPeriodRange(newPeriod); + period = newPeriod; + emit PeriodSet(newPeriod); + } + + function _changeId(Change kind, uint256 value) internal pure returns (bytes32) { + return keccak256(abi.encode(kind, value)); + } + + function _mustBeValidWithdrawDelay(uint64 delay) internal pure { + if (delay > MAX_WITHDRAW_DELAY) revert WithdrawDelayTooLong(delay); + } +} diff --git a/test/arcade/ArcadeEscrow.t.sol b/test/arcade/ArcadeEscrow.t.sol new file mode 100644 index 00000000..04b87262 --- /dev/null +++ b/test/arcade/ArcadeEscrow.t.sol @@ -0,0 +1,651 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import "forge-std/Test.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {ArcadeEscrow} from "../../src/arcade/ArcadeEscrow.sol"; +import {QuotaControl} from "../../src/QuotaControl.sol"; +import {MockERC20} from "../__helpers__/MockERC20.sol"; +import {AccessControlUtils} from "../__helpers__/AccessControlUtils.sol"; + +contract ArcadeEscrowTest is Test { + using AccessControlUtils for Vm; + + address admin = makeAddr("admin"); + address oracle = makeAddr("oracle"); + address alice = makeAddr("alice"); + address bob = makeAddr("bob"); + + uint256 constant QUOTA = 1_000 ether; + uint256 constant PERIOD = 1 days; + uint256 constant MIN_DEPOSIT = 1 ether; + uint256 constant MAX_CHARGE = 100 ether; + uint64 constant DELAY = 1 hours; + + MockERC20 token; + ArcadeEscrow escrow; + + function setUp() public { + token = new MockERC20("Nodle", "NODL", 18); + escrow = new ArcadeEscrow(address(token), oracle, admin, QUOTA, PERIOD, MIN_DEPOSIT, MAX_CHARGE, DELAY); + _fund(alice, 10_000 ether); + _fund(bob, 10_000 ether); + } + + function _fund(address who, uint256 amount) internal { + token.mint(who, amount); + vm.prank(who); + token.approve(address(escrow), type(uint256).max); + } + + function _deposit(address who, uint256 amount) internal { + vm.prank(who); + escrow.deposit(amount); + } + + function _charge(address who, uint256 amount, bytes32 ref) internal { + vm.prank(oracle); + escrow.charge(who, amount, ref); + } + + // ── Constructor ─────────────────────────────────────── + + function test_constructorSetsState() public view { + assertEq(address(escrow.token()), address(token)); + assertTrue(escrow.hasRole(escrow.ORACLE_ROLE(), oracle)); + assertTrue(escrow.hasRole(escrow.DEFAULT_ADMIN_ROLE(), admin)); + assertEq(escrow.quota(), QUOTA); + assertEq(escrow.period(), PERIOD); + assertEq(escrow.minDeposit(), MIN_DEPOSIT); + assertEq(escrow.maxCharge(), MAX_CHARGE); + assertEq(escrow.withdrawDelay(), DELAY); + } + + function test_constructorRejectsZeroAddresses() public { + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + new ArcadeEscrow(address(0), oracle, admin, QUOTA, PERIOD, 0, 0, DELAY); + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + new ArcadeEscrow(address(token), address(0), admin, QUOTA, PERIOD, 0, 0, DELAY); + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + new ArcadeEscrow(address(token), oracle, address(0), QUOTA, PERIOD, 0, 0, DELAY); + } + + function test_constructorRejectsLongDelay() public { + uint64 tooLong = escrow.MAX_WITHDRAW_DELAY() + 1; + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.WithdrawDelayTooLong.selector, tooLong)); + new ArcadeEscrow(address(token), oracle, admin, QUOTA, PERIOD, 0, 0, tooLong); + } + + // ── Deposit ─────────────────────────────────────────── + + function test_depositCreditsCaller() public { + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.Deposited(alice, alice, 5 ether, 5 ether); + _deposit(alice, 5 ether); + + assertEq(escrow.balanceOf(alice), 5 ether); + assertEq(token.balanceOf(address(escrow)), 5 ether); + } + + function test_depositForCreditsAccountNotSender() public { + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.Deposited(alice, bob, 5 ether, 5 ether); + vm.prank(bob); + escrow.depositFor(alice, 5 ether); + + assertEq(escrow.balanceOf(alice), 5 ether); + assertEq(escrow.balanceOf(bob), 0); + } + + function test_depositForRejectsZeroAccount() public { + vm.prank(bob); + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + escrow.depositFor(address(0), 5 ether); + } + + function test_depositRejectsZero() public { + vm.prank(alice); + vm.expectRevert(ArcadeEscrow.ZeroAmount.selector); + escrow.deposit(0); + } + + function test_minDepositAppliesToEmptyBalanceOnly() public { + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.BelowMinDeposit.selector, 0.5 ether, MIN_DEPOSIT)); + escrow.deposit(0.5 ether); + + _deposit(alice, MIN_DEPOSIT); + _deposit(alice, 1); // a small top-up is fine once funded + assertEq(escrow.balanceOf(alice), MIN_DEPOSIT + 1); + } + + // ── Withdraw ────────────────────────────────────────── + + function test_withdrawAfterDelay() public { + _deposit(alice, 10 ether); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.WithdrawRequested(alice, 4 ether, uint64(block.timestamp) + DELAY); + vm.prank(alice); + escrow.requestWithdraw(4 ether); + + (uint128 amount, uint64 readyAt) = escrow.withdrawals(alice); + assertEq(amount, 4 ether); + assertEq(readyAt, block.timestamp + DELAY); + + vm.warp(readyAt - 1); + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.WithdrawalNotReady.selector, readyAt)); + escrow.withdraw(); + + vm.warp(readyAt); + uint256 before = token.balanceOf(alice); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.Withdrawn(alice, 4 ether); + vm.prank(alice); + escrow.withdraw(); + + assertEq(token.balanceOf(alice) - before, 4 ether); + assertEq(escrow.balanceOf(alice), 6 ether); + (amount,) = escrow.withdrawals(alice); + assertEq(amount, 0); + } + + function test_withdrawPaysWhatIsLeftAfterACharge() public { + _deposit(alice, 10 ether); + vm.prank(alice); + escrow.requestWithdraw(10 ether); + + // A build already running settles during the delay. + _charge(alice, 3 ether, keccak256("build")); + + vm.warp(block.timestamp + DELAY); + uint256 before = token.balanceOf(alice); + vm.prank(alice); + escrow.withdraw(); + + assertEq(token.balanceOf(alice) - before, 7 ether); + assertEq(escrow.balanceOf(alice), 0); + } + + function test_withdrawPaysNothingWhenBalanceWasCharged() public { + _deposit(alice, 10 ether); + vm.prank(alice); + escrow.requestWithdraw(10 ether); + _charge(alice, 10 ether, keccak256("build")); + + vm.warp(block.timestamp + DELAY); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.Withdrawn(alice, 0); + vm.prank(alice); + escrow.withdraw(); + + (uint128 amount,) = escrow.withdrawals(alice); + assertEq(amount, 0); + } + + function test_requestWithdrawValidates() public { + vm.startPrank(alice); + vm.expectRevert(ArcadeEscrow.ZeroAmount.selector); + escrow.requestWithdraw(0); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.InsufficientBalance.selector, 0, 1 ether)); + escrow.requestWithdraw(1 ether); + vm.stopPrank(); + } + + function test_requestWithdrawRejectsAmountAboveUint128() public { + uint256 huge = uint256(type(uint128).max) + 1; + _fund(alice, huge); + _deposit(alice, huge); + + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.AmountTooLarge.selector, huge)); + escrow.requestWithdraw(huge); + } + + function test_newRequestReplacesAndRestartsTimer() public { + _deposit(alice, 10 ether); + vm.prank(alice); + escrow.requestWithdraw(2 ether); + + vm.warp(block.timestamp + 30 minutes); + vm.prank(alice); + escrow.requestWithdraw(5 ether); + + (uint128 amount, uint64 readyAt) = escrow.withdrawals(alice); + assertEq(amount, 5 ether); + assertEq(readyAt, block.timestamp + DELAY); + } + + function test_cancelWithdraw() public { + _deposit(alice, 10 ether); + vm.prank(alice); + escrow.requestWithdraw(2 ether); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.WithdrawCancelled(alice); + vm.prank(alice); + escrow.cancelWithdraw(); + + (uint128 amount,) = escrow.withdrawals(alice); + assertEq(amount, 0); + + vm.warp(block.timestamp + DELAY); + vm.startPrank(alice); + vm.expectRevert(ArcadeEscrow.NoPendingWithdrawal.selector); + escrow.withdraw(); + vm.expectRevert(ArcadeEscrow.NoPendingWithdrawal.selector); + escrow.cancelWithdraw(); + vm.stopPrank(); + } + + function test_onlyAccountCanWithdrawItsBalance() public { + vm.prank(bob); + escrow.depositFor(alice, 10 ether); + + vm.prank(bob); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.InsufficientBalance.selector, 0, 10 ether)); + escrow.requestWithdraw(10 ether); + } + + function test_delayChangeDoesNotMovePendingRequest() public { + _deposit(alice, 10 ether); + vm.prank(alice); + escrow.requestWithdraw(1 ether); + (, uint64 readyAt) = escrow.withdrawals(alice); + + uint64 maxDelay = escrow.MAX_WITHDRAW_DELAY(); + vm.prank(admin); + escrow.setWithdrawDelay(maxDelay); + + vm.warp(readyAt); + vm.prank(alice); + escrow.withdraw(); + assertEq(escrow.balanceOf(alice), 9 ether); + } + + // ── Charge ──────────────────────────────────────────── + + function test_chargeMovesBalanceToFees() public { + _deposit(alice, 10 ether); + bytes32 ref = keccak256("nonce"); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.Charged(alice, 4 ether, ref); + _charge(alice, 4 ether, ref); + + assertEq(escrow.balanceOf(alice), 6 ether); + assertEq(escrow.feesAccrued(), 4 ether); + assertTrue(escrow.charged(ref)); + assertEq(escrow.claimed(), 4 ether); + assertEq(token.balanceOf(address(escrow)), 10 ether); + } + + function test_chargeIsIdempotentByRef() public { + _deposit(alice, 10 ether); + bytes32 ref = keccak256("nonce"); + _charge(alice, 1 ether, ref); + + vm.prank(oracle); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.AlreadyCharged.selector, ref)); + escrow.charge(alice, 1 ether, ref); + assertEq(escrow.balanceOf(alice), 9 ether); + } + + function test_chargeRefReusedWithDifferentPayloadConflicts() public { + _deposit(alice, 10 ether); + _deposit(bob, 10 ether); + bytes32 ref = keccak256("nonce"); + _charge(alice, 1 ether, ref); + + vm.startPrank(oracle); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.ChargeConflict.selector, ref)); + escrow.charge(bob, 1 ether, ref); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.ChargeConflict.selector, ref)); + escrow.charge(alice, 2 ether, ref); + vm.stopPrank(); + + assertEq(escrow.balanceOf(alice), 9 ether); + assertEq(escrow.balanceOf(bob), 10 ether); + } + + function test_chargeValidates() public { + _deposit(alice, 10 ether); + vm.startPrank(oracle); + vm.expectRevert(ArcadeEscrow.ZeroAmount.selector); + escrow.charge(alice, 0, "a"); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.AboveMaxCharge.selector, MAX_CHARGE + 1, MAX_CHARGE)); + escrow.charge(alice, MAX_CHARGE + 1, "b"); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.InsufficientBalance.selector, 10 ether, 11 ether)); + escrow.charge(alice, 11 ether, "c"); + vm.stopPrank(); + } + + function test_chargeIsCappedByQuota() public { + _deposit(alice, 5_000 ether); + for (uint256 i = 0; i < QUOTA / MAX_CHARGE; ++i) { + _charge(alice, MAX_CHARGE, bytes32(i + 1)); + } + + vm.prank(oracle); + vm.expectRevert(QuotaControl.QuotaExceeded.selector); + escrow.charge(alice, 1, "over"); + + vm.warp(block.timestamp + PERIOD); + _charge(alice, 1, "next period"); + assertEq(escrow.claimed(), 1); + } + + function test_onlyOracleCanCharge() public { + _deposit(alice, 10 ether); + vm.startPrank(admin); + vm.expectRevert_AccessControlUnauthorizedAccount(admin, escrow.ORACLE_ROLE()); + escrow.charge(alice, 1 ether, "x"); + vm.stopPrank(); + } + + // ── Fees ────────────────────────────────────────────── + + function test_adminWithdrawsFeesOnly() public { + _deposit(alice, 10 ether); + _charge(alice, 4 ether, "x"); + + vm.prank(admin); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.InsufficientFees.selector, 4 ether, 5 ether)); + escrow.withdrawFees(admin, 5 ether); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.FeesWithdrawn(bob, 4 ether); + vm.prank(admin); + escrow.withdrawFees(bob, 4 ether); + + assertEq(token.balanceOf(bob), 10_000 ether + 4 ether); + assertEq(escrow.feesAccrued(), 0); + assertEq(token.balanceOf(address(escrow)), escrow.balanceOf(alice)); + } + + function test_withdrawFeesRejectsZeroRecipient() public { + vm.prank(admin); + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + escrow.withdrawFees(address(0), 0); + } + + // ── Admin ───────────────────────────────────────────── + + function test_onlyAdminCanConfigure() public { + bytes32 adminRole = escrow.DEFAULT_ADMIN_ROLE(); + vm.startPrank(oracle); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.setMinDeposit(0); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.setMaxCharge(0); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.setWithdrawDelay(0); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.pause(); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.unpause(); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.withdrawFees(oracle, 0); + vm.stopPrank(); + + vm.startPrank(admin); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.MinDepositSet(2 ether); + escrow.setMinDeposit(2 ether); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.MaxChargeSet(50 ether); + escrow.setMaxCharge(50 ether); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.WithdrawDelaySet(2 hours); + escrow.setWithdrawDelay(2 hours); + vm.stopPrank(); + + assertEq(escrow.minDeposit(), 2 ether); + assertEq(escrow.maxCharge(), 50 ether); + assertEq(escrow.withdrawDelay(), 2 hours); + } + + function test_setWithdrawDelayIsCapped() public { + uint64 tooLong = escrow.MAX_WITHDRAW_DELAY() + 1; + vm.prank(admin); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.WithdrawDelayTooLong.selector, tooLong)); + escrow.setWithdrawDelay(tooLong); + } + + function test_pauseBlocksDepositAndChargeButNeverWithdraw() public { + _deposit(alice, 10 ether); + _charge(alice, 1 ether, "x"); + vm.prank(alice); + escrow.requestWithdraw(9 ether); + + vm.prank(admin); + escrow.pause(); + + vm.prank(alice); + vm.expectRevert(Pausable.EnforcedPause.selector); + escrow.deposit(1 ether); + vm.prank(bob); + vm.expectRevert(Pausable.EnforcedPause.selector); + escrow.depositFor(alice, 1 ether); + vm.prank(oracle); + vm.expectRevert(Pausable.EnforcedPause.selector); + escrow.charge(alice, 1 ether, "y"); + + vm.warp(block.timestamp + DELAY); + vm.prank(alice); + escrow.withdraw(); + assertEq(escrow.balanceOf(alice), 0); + + vm.prank(admin); + escrow.withdrawFees(admin, 1 ether); + + vm.prank(admin); + escrow.unpause(); + _deposit(alice, 1 ether); + } + + // ── Admin timelock ──────────────────────────────────── + + function _schedule(ArcadeEscrow.Change kind, uint256 value) internal { + vm.prank(admin); + escrow.scheduleChange(kind, value); + } + + function _execute(ArcadeEscrow.Change kind, uint256 value) internal { + vm.prank(admin); + escrow.executeChange(kind, value); + } + + function test_adminDelayOutlastsAnyWithdrawal() public view { + assertGt(escrow.ADMIN_DELAY(), escrow.MAX_WITHDRAW_DELAY()); + } + + function test_increasesNeedTimelock() public { + bytes32 oracleRole = escrow.ORACLE_ROLE(); + vm.startPrank(admin); + vm.expectRevert(ArcadeEscrow.NeedsTimelock.selector); + escrow.setMaxCharge(MAX_CHARGE + 1); + vm.expectRevert(ArcadeEscrow.NeedsTimelock.selector); + escrow.setQuota(QUOTA + 1); + vm.expectRevert(ArcadeEscrow.NeedsTimelock.selector); + escrow.setPeriod(PERIOD - 1); + vm.expectRevert(ArcadeEscrow.NeedsTimelock.selector); + escrow.grantRole(oracleRole, bob); + vm.stopPrank(); + } + + function test_decreasesAndRevokesApplyImmediately() public { + bytes32 oracleRole = escrow.ORACLE_ROLE(); + vm.startPrank(admin); + escrow.setMaxCharge(MAX_CHARGE - 1); + vm.expectEmit(address(escrow)); + emit QuotaControl.QuotaSet(QUOTA - 1); + escrow.setQuota(QUOTA - 1); + vm.expectEmit(address(escrow)); + emit QuotaControl.PeriodSet(PERIOD + 1); + escrow.setPeriod(PERIOD + 1); + escrow.revokeRole(oracleRole, oracle); + vm.stopPrank(); + + assertEq(escrow.maxCharge(), MAX_CHARGE - 1); + assertEq(escrow.quota(), QUOTA - 1); + assertEq(escrow.period(), PERIOD + 1); + assertFalse(escrow.hasRole(oracleRole, oracle)); + } + + function test_setPeriodStaysWithinRange() public { + uint256 tooLong = escrow.MAX_PERIOD() + 1; + vm.prank(admin); + vm.expectRevert(QuotaControl.TooLongPeriod.selector); + escrow.setPeriod(tooLong); + } + + function test_otherRolesGrantImmediately() public { + bytes32 adminRole = escrow.DEFAULT_ADMIN_ROLE(); + vm.prank(admin); + escrow.grantRole(adminRole, bob); + assertTrue(escrow.hasRole(adminRole, bob)); + } + + function test_scheduledChangesApplyAfterDelay() public { + uint256 readyAt = block.timestamp + escrow.ADMIN_DELAY(); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.ChangeScheduled(ArcadeEscrow.Change.MaxCharge, 2 * MAX_CHARGE, readyAt); + _schedule(ArcadeEscrow.Change.MaxCharge, 2 * MAX_CHARGE); + _schedule(ArcadeEscrow.Change.Quota, 2 * QUOTA); + _schedule(ArcadeEscrow.Change.Period, PERIOD / 2); + _schedule(ArcadeEscrow.Change.GrantOracle, uint160(bob)); + + vm.warp(readyAt - 1); + vm.prank(admin); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.ChangeNotReady.selector, readyAt)); + escrow.executeChange(ArcadeEscrow.Change.MaxCharge, 2 * MAX_CHARGE); + + vm.warp(readyAt); + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.ChangeExecuted(ArcadeEscrow.Change.MaxCharge, 2 * MAX_CHARGE); + _execute(ArcadeEscrow.Change.MaxCharge, 2 * MAX_CHARGE); + _execute(ArcadeEscrow.Change.Quota, 2 * QUOTA); + _execute(ArcadeEscrow.Change.Period, PERIOD / 2); + _execute(ArcadeEscrow.Change.GrantOracle, uint160(bob)); + + assertEq(escrow.maxCharge(), 2 * MAX_CHARGE); + assertEq(escrow.quota(), 2 * QUOTA); + assertEq(escrow.period(), PERIOD / 2); + assertTrue(escrow.hasRole(escrow.ORACLE_ROLE(), bob)); + + // Executed changes are consumed. + vm.prank(admin); + vm.expectRevert( + abi.encodeWithSelector(ArcadeEscrow.ChangeNotScheduled.selector, ArcadeEscrow.Change.Quota, 2 * QUOTA) + ); + escrow.executeChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + } + + function test_cancelChange() public { + _schedule(ArcadeEscrow.Change.Quota, 2 * QUOTA); + + vm.prank(admin); + vm.expectRevert( + abi.encodeWithSelector(ArcadeEscrow.ChangeAlreadyScheduled.selector, ArcadeEscrow.Change.Quota, 2 * QUOTA) + ); + escrow.scheduleChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + + vm.expectEmit(address(escrow)); + emit ArcadeEscrow.ChangeCancelled(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.prank(admin); + escrow.cancelChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + + vm.warp(block.timestamp + escrow.ADMIN_DELAY()); + vm.startPrank(admin); + vm.expectRevert( + abi.encodeWithSelector(ArcadeEscrow.ChangeNotScheduled.selector, ArcadeEscrow.Change.Quota, 2 * QUOTA) + ); + escrow.executeChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.expectRevert( + abi.encodeWithSelector(ArcadeEscrow.ChangeNotScheduled.selector, ArcadeEscrow.Change.Quota, 2 * QUOTA) + ); + escrow.cancelChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.stopPrank(); + } + + function test_scheduleChangeValidates() public { + vm.startPrank(admin); + vm.expectRevert(ArcadeEscrow.ZeroAddress.selector); + escrow.scheduleChange(ArcadeEscrow.Change.GrantOracle, 0); + uint256 notAnAddress = uint256(type(uint160).max) + 1; + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.AmountTooLarge.selector, notAnAddress)); + escrow.scheduleChange(ArcadeEscrow.Change.GrantOracle, notAnAddress); + vm.expectRevert(QuotaControl.ZeroPeriod.selector); + escrow.scheduleChange(ArcadeEscrow.Change.Period, 0); + vm.stopPrank(); + } + + function test_onlyAdminCanUseTimelock() public { + bytes32 adminRole = escrow.DEFAULT_ADMIN_ROLE(); + vm.startPrank(oracle); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.scheduleChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.cancelChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.executeChange(ArcadeEscrow.Change.Quota, 2 * QUOTA); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.setQuota(0); + vm.expectRevert_AccessControlUnauthorizedAccount(oracle, adminRole); + escrow.setPeriod(PERIOD); + vm.stopPrank(); + } + + /// @dev The point of the timelock: a user who reacts to a scheduled oracle grant at the slowest + /// allowed withdrawal delay still exits with their whole balance before the grant applies. + function test_userExitsBeforeScheduledOracleCanCharge() public { + uint64 maxDelay = escrow.MAX_WITHDRAW_DELAY(); + vm.prank(admin); + escrow.setWithdrawDelay(maxDelay); + _deposit(alice, 10 ether); + + address rogue = makeAddr("rogue"); + _schedule(ArcadeEscrow.Change.GrantOracle, uint160(rogue)); + + vm.prank(alice); + escrow.requestWithdraw(10 ether); + vm.warp(block.timestamp + maxDelay); + vm.prank(alice); + escrow.withdraw(); + assertEq(escrow.balanceOf(alice), 0); + + vm.warp(block.timestamp + escrow.ADMIN_DELAY() - maxDelay); + _execute(ArcadeEscrow.Change.GrantOracle, uint160(rogue)); + vm.prank(rogue); + vm.expectRevert(abi.encodeWithSelector(ArcadeEscrow.InsufficientBalance.selector, 0, 1 ether)); + escrow.charge(alice, 1 ether, "drain"); + } + + // ── Fuzz ────────────────────────────────────────────── + + function testFuzz_depositChargeWithdraw(uint256 deposited, uint256 chargedAmount, uint256 requested) public { + deposited = bound(deposited, MIN_DEPOSIT, 10_000 ether); + chargedAmount = bound(chargedAmount, 1, deposited < MAX_CHARGE ? deposited : MAX_CHARGE); + requested = bound(requested, 1, deposited); + + _deposit(alice, deposited); + vm.prank(alice); + escrow.requestWithdraw(requested); + _charge(alice, chargedAmount, "x"); + + vm.warp(block.timestamp + DELAY); + uint256 before = token.balanceOf(alice); + vm.prank(alice); + escrow.withdraw(); + + uint256 left = deposited - chargedAmount; + uint256 paid = requested < left ? requested : left; + assertEq(token.balanceOf(alice) - before, paid); + assertEq(escrow.balanceOf(alice), left - paid); + assertEq(escrow.feesAccrued(), chargedAmount); + assertEq(token.balanceOf(address(escrow)), escrow.balanceOf(alice) + escrow.feesAccrued()); + } +} diff --git a/test/arcade/ArcadeEscrowInvariants.t.sol b/test/arcade/ArcadeEscrowInvariants.t.sol new file mode 100644 index 00000000..55f78371 --- /dev/null +++ b/test/arcade/ArcadeEscrowInvariants.t.sol @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import "forge-std/Test.sol"; +import {ArcadeEscrow} from "../../src/arcade/ArcadeEscrow.sol"; +import {MockERC20} from "../__helpers__/MockERC20.sol"; + +/// @notice Drives the escrow through random sequences of every public action. +/// @dev Calls are wrapped in try/catch: a revert is a legitimate outcome (paused, not ready, +/// over quota), and what matters is that the invariants hold after whatever succeeded. +contract ArcadeEscrowHandler is Test { + ArcadeEscrow public escrow; + MockERC20 public token; + address public admin; + address public oracle; + address[] public actors; + + // ghosts + uint256 public totalCharged; + uint256 public totalFeesWithdrawn; + uint256 public refNonce; + bool public sawWithdrawBlockedByPause; + + constructor(ArcadeEscrow escrow_, MockERC20 token_, address admin_, address oracle_, address[] memory actors_) { + escrow = escrow_; + token = token_; + admin = admin_; + oracle = oracle_; + actors = actors_; + } + + function actorCount() external view returns (uint256) { + return actors.length; + } + + function _actor(uint256 seed) internal view returns (address) { + return actors[seed % actors.length]; + } + + function deposit(uint256 actorSeed, uint96 amount) external { + address a = _actor(actorSeed); + uint256 value = bound(uint256(amount), 1, 1_000 ether); + token.mint(a, value); + vm.startPrank(a); + token.approve(address(escrow), value); + try escrow.deposit(value) {} catch {} + vm.stopPrank(); + } + + function depositFor(uint256 fromSeed, uint256 toSeed, uint96 amount) external { + address from = _actor(fromSeed); + address to = _actor(toSeed); + uint256 value = bound(uint256(amount), 1, 1_000 ether); + token.mint(from, value); + vm.startPrank(from); + token.approve(address(escrow), value); + try escrow.depositFor(to, value) {} catch {} + vm.stopPrank(); + } + + function requestWithdraw(uint256 actorSeed, uint96 amount) external { + address a = _actor(actorSeed); + uint256 value = bound(uint256(amount), 1, 2_000 ether); + vm.prank(a); + try escrow.requestWithdraw(value) {} catch {} + } + + function cancelWithdraw(uint256 actorSeed) external { + vm.prank(_actor(actorSeed)); + try escrow.cancelWithdraw() {} catch {} + } + + function withdraw(uint256 actorSeed) external { + address a = _actor(actorSeed); + (uint128 pending, uint64 readyAt) = escrow.withdrawals(a); + vm.prank(a); + try escrow.withdraw() {} + catch { + if (pending != 0 && block.timestamp >= readyAt && escrow.paused()) sawWithdrawBlockedByPause = true; + } + } + + function charge(uint256 actorSeed, uint96 amount) external { + address a = _actor(actorSeed); + uint256 value = bound(uint256(amount), 1, 200 ether); + bytes32 ref = bytes32(++refNonce); + vm.prank(oracle); + try escrow.charge(a, value, ref) { + totalCharged += value; + } catch {} + } + + function withdrawFees(uint96 amount) external { + uint256 value = bound(uint256(amount), 0, escrow.feesAccrued()); + vm.prank(admin); + try escrow.withdrawFees(admin, value) { + totalFeesWithdrawn += value; + } catch {} + } + + function togglePause() external { + vm.startPrank(admin); + if (escrow.paused()) escrow.unpause(); + else escrow.pause(); + vm.stopPrank(); + } + + function warp(uint256 by) external { + vm.warp(block.timestamp + bound(by, 0, 2 days)); + } +} + +contract ArcadeEscrowInvariantTest is Test { + ArcadeEscrow escrow; + MockERC20 token; + ArcadeEscrowHandler handler; + + address admin = makeAddr("admin"); + address oracle = makeAddr("oracle"); + + function setUp() public { + token = new MockERC20("Nodle", "NODL", 18); + escrow = new ArcadeEscrow(address(token), oracle, admin, 2_000 ether, 1 days, 1 ether, 100 ether, 1 hours); + + address[] memory actors = new address[](4); + actors[0] = makeAddr("a0"); + actors[1] = makeAddr("a1"); + actors[2] = makeAddr("a2"); + actors[3] = makeAddr("a3"); + + handler = new ArcadeEscrowHandler(escrow, token, admin, oracle, actors); + targetContract(address(handler)); + } + + function _sumBalances() internal view returns (uint256 sum) { + for (uint256 i = 0; i < handler.actorCount(); ++i) { + sum += escrow.balanceOf(handler.actors(i)); + } + } + + /// @dev The admin can never reach users' balances: the escrow is always solvent. + function invariant_solvent() public view { + assertGe(token.balanceOf(address(escrow)), _sumBalances() + escrow.feesAccrued()); + } + + /// @dev With a plain ERC-20 and no stray transfers, solvency is exact. + function invariant_accountingIsExact() public view { + assertEq(token.balanceOf(address(escrow)), _sumBalances() + escrow.feesAccrued()); + } + + function invariant_feesTrackCharges() public view { + assertEq(escrow.feesAccrued(), handler.totalCharged() - handler.totalFeesWithdrawn()); + } + + function invariant_quotaNeverExceeded() public view { + assertLe(escrow.claimed(), escrow.quota()); + } + + function invariant_pauseNeverBlocksWithdraw() public view { + assertFalse(handler.sawWithdrawBlockedByPause()); + } +}