// SPDX-License-Identifier: MIT pragma solidity 0.8.26; /// @dev Minimal ERC-20 surface this contract needs. interface IERC20 { function balanceOf(address account) external view returns (uint256); } /// @title IdleCredits /// @notice Prepaid credits for Idle, the GPU cloud on Elysium: an escrow, and a registry of hourly receipt roots. /// /// A user deposits one of two tokens fixed at deployment (USDC and EQNVDA). The deposit stays the /// user's until the operator charges it for GPU seconds already used. What is charged moves to /// `earned`, and only `earned` can leave to the operator. What is not charged can always be /// withdrawn by the user, after a delay fixed at deployment. /// /// WHAT THE OPERATOR CAN DO /// - `charge`: move any amount, up to what a user has here, from that user's balance to `earned`. /// The contract cannot know how many GPU seconds were really used: as with any prepaid service, /// a dishonest operator could charge more than what is owed. Every charge emits `Charged` with a /// receipt id that can never be used twice, and each hour's receipts are committed by `seal`: /// that is what makes an over-charge visible. It does not make it impossible. /// - `collect`: send what was earned, and nothing else, to an address of his choice. /// - `seal`: post one Merkle root per finished hour. A root is never rewritten. /// - `proposeOperator`: name a successor, who takes over by calling `acceptOperator`. /// /// WHAT THE OPERATOR CANNOT DO /// - take, move or freeze a balance in any way other than `charge`; /// - charge a withdrawal whose delay has passed (see the withdrawal rule below); /// - stop, delay or cancel a withdrawal; /// - charge the same receipt id twice, or change a sealed root; /// - pause or upgrade this contract, or change its tokens or its delay. There is no owner. /// /// THE WITHDRAWAL RULE /// `requestWithdrawal(token, amount)` starts a clock of `withdrawalDelay` seconds. /// - While the clock runs, the whole balance stays chargeable, the requested amount included. /// The contract cannot tell seconds used before the request from seconds used after it, so the /// delay is the operator's window to stop the user's machines and charge what they used. /// - Once the clock has run out, the requested amount (or what is left of the balance, if a charge /// took it below that) is out of the operator's reach: `charge` can no longer touch it, and /// `withdraw` sends it to the user. Nothing the operator does can prevent that. /// - A new request replaces the previous one and restarts the clock for the whole new amount. /// Otherwise a small old request could be enlarged at the last second to leave without paying. /// Off chain, the rental engine must stop counting a requested amount as credits from the moment /// it is requested: `available` gives that figure. /// /// RECEIPTS /// One leaf per receipt: /// leaf = keccak256(abi.encode(receiptId, user, token, amount, secondsBilled, gpuId)) /// with the types (bytes32, address, address, uint256, uint64, bytes32): six 32-byte words. /// The tree of an hour is built on the leaves sorted in ascending order. Each level pairs /// neighbours and hashes each pair with the smaller hash first: keccak256(min ++ max). /// A node left without a neighbour moves up unchanged. The root of a single leaf is that leaf. /// `scripts/merkle.mjs` builds exactly this tree. Which receipts go in which hour is the engine's /// convention (the hour of the `Charged` event): this contract cannot check it. contract IdleCredits { struct Withdrawal { uint256 amount; // as requested; what is really pending is capped at the balance uint64 unlockAt; // from this timestamp on, `withdraw` works and `charge` cannot reach it } /// @notice The delay between a withdrawal request and its payment can never exceed this. uint64 public constant MAX_WITHDRAWAL_DELAY = 24 hours; address public immutable usdc; address public immutable eqnvda; /// @notice Seconds between `requestWithdrawal` and `withdraw`. Fixed at deployment. uint64 public immutable withdrawalDelay; /// @notice The only privileged address. See the contract notice for what it can and cannot do. address public operator; /// @notice The address named by `proposeOperator`, until it accepts. address public pendingOperator; /// @notice What `user` holds here in `token`, not yet charged. A pending withdrawal is still part of it. mapping(address user => mapping(address token => uint256)) public balanceOf; /// @notice The sum of every user's balance in `token`. mapping(address token => uint256) public totalBalance; /// @notice What the operator has charged in `token` and not collected yet. mapping(address token => uint256) public earned; /// @notice When `receiptId` was charged (unix time); 0 if it never was. mapping(bytes32 receiptId => uint64) public chargedAt; /// @notice The Merkle root of the receipts of `hour` (unix time / 3600); 0 if that hour is not sealed. mapping(uint256 hour => bytes32) public rootOf; mapping(address user => mapping(address token => Withdrawal)) private _withdrawals; uint256 private _entered = 1; event Deposited(address indexed user, address indexed token, uint256 amount); event WithdrawalRequested(address indexed user, address indexed token, uint256 amount, uint64 unlockAt); event WithdrawalCancelled(address indexed user, address indexed token); event Withdrawn(address indexed user, address indexed token, uint256 amount); event Charged(bytes32 indexed receiptId, address indexed user, address indexed token, uint256 amount); event Collected(address indexed token, address indexed to, uint256 amount); event Sealed(uint256 indexed hour, bytes32 root); event OperatorProposed(address indexed operator, address indexed proposed); event OperatorChanged(address indexed previous, address indexed operator); error ZeroAddress(); error SameToken(); error DelayTooLong(); error NotOperator(); error NotPendingOperator(); error TokenNotAccepted(); error UnsupportedToken(); error ZeroAmount(); error InsufficientBalance(); error NothingPending(); error TooEarly(); error ZeroReceipt(); error ReceiptUsed(); error EmptyRoot(); error HourNotOver(); error AlreadySealed(); error NothingToCollect(); error Reentrancy(); error TransferFailed(); modifier nonReentrant() { if (_entered != 1) revert Reentrancy(); _entered = 2; _; _entered = 1; } modifier onlyOperator() { if (msg.sender != operator) revert NotOperator(); _; } modifier accepted(address token) { if (token != usdc && token != eqnvda) revert TokenNotAccepted(); _; } constructor(address usdc_, address eqnvda_, address operator_, uint64 withdrawalDelay_) { if (usdc_ == address(0) || eqnvda_ == address(0) || operator_ == address(0)) revert ZeroAddress(); if (usdc_ == eqnvda_) revert SameToken(); if (withdrawalDelay_ > MAX_WITHDRAWAL_DELAY) revert DelayTooLong(); usdc = usdc_; eqnvda = eqnvda_; withdrawalDelay = withdrawalDelay_; operator = operator_; emit OperatorChanged(address(0), operator_); } // ───────────────────────────── user ───────────────────────────── /// @notice Put `amount` of `token` here as prepaid credits. It needs an allowance first. function deposit(address token, uint256 amount) external nonReentrant accepted(token) { if (amount == 0) revert ZeroAmount(); // A token that takes a fee on transfer would leave the balances without their backing. uint256 before = IERC20(token).balanceOf(address(this)); _pull(token, msg.sender, address(this), amount); if (IERC20(token).balanceOf(address(this)) - before != amount) revert UnsupportedToken(); balanceOf[msg.sender][token] += amount; totalBalance[token] += amount; emit Deposited(msg.sender, token, amount); } /// @notice Ask to take `amount` of `token` back. It can be withdrawn `withdrawalDelay` seconds later. /// @dev Replaces any earlier request for this token and restarts the clock for the whole amount. function requestWithdrawal(address token, uint256 amount) external nonReentrant accepted(token) { if (amount == 0) revert ZeroAmount(); if (amount > balanceOf[msg.sender][token]) revert InsufficientBalance(); uint64 unlockAt = uint64(block.timestamp) + withdrawalDelay; _withdrawals[msg.sender][token] = Withdrawal({amount: amount, unlockAt: unlockAt}); emit WithdrawalRequested(msg.sender, token, amount, unlockAt); } /// @notice Drop a withdrawal request. The amount counts as credits again. function cancelWithdrawal(address token) external nonReentrant accepted(token) { if (_withdrawals[msg.sender][token].amount == 0) revert NothingPending(); delete _withdrawals[msg.sender][token]; emit WithdrawalCancelled(msg.sender, token); } /// @notice Receive a requested withdrawal once its delay has passed. /// @dev Sends the requested amount, or the whole balance if charges made during the delay took it below that. function withdraw(address token) external nonReentrant accepted(token) { Withdrawal memory w = _withdrawals[msg.sender][token]; if (w.amount == 0) revert NothingPending(); if (block.timestamp < w.unlockAt) revert TooEarly(); uint256 balance = balanceOf[msg.sender][token]; uint256 amount = w.amount < balance ? w.amount : balance; delete _withdrawals[msg.sender][token]; balanceOf[msg.sender][token] = balance - amount; totalBalance[token] -= amount; emit Withdrawn(msg.sender, token, amount); if (amount != 0) _push(token, msg.sender, amount); } // ───────────────────────────── operator ───────────────────────────── /// @notice Charge `user` `amount` of `token` for GPU seconds already used, under a receipt id used once. /// @dev At most `chargeable(user, token)`: the balance, less a withdrawal whose delay has passed. function charge(address user, address token, uint256 amount, bytes32 receiptId) external nonReentrant onlyOperator accepted(token) { if (amount == 0) revert ZeroAmount(); if (receiptId == bytes32(0)) revert ZeroReceipt(); if (chargedAt[receiptId] != 0) revert ReceiptUsed(); if (amount > _chargeable(user, token)) revert InsufficientBalance(); chargedAt[receiptId] = uint64(block.timestamp); balanceOf[user][token] -= amount; totalBalance[token] -= amount; earned[token] += amount; emit Charged(receiptId, user, token, amount); } /// @notice Send everything earned in `token` to `to`. Balances that were not charged cannot leave this way. function collect(address token, address to) external nonReentrant onlyOperator accepted(token) { if (to == address(0)) revert ZeroAddress(); uint256 amount = earned[token]; if (amount == 0) revert NothingToCollect(); earned[token] = 0; emit Collected(token, to, amount); _push(token, to, amount); } /// @notice Commit the receipts of a finished hour. One root per hour, never rewritten. /// @param hour Unix time divided by 3600. It must be over. /// @param root The Merkle root of that hour's receipt leaves (see the contract notice). function seal(uint256 hour, bytes32 root) external onlyOperator { if (root == bytes32(0)) revert EmptyRoot(); if (hour >= block.timestamp / 3600) revert HourNotOver(); if (rootOf[hour] != bytes32(0)) revert AlreadySealed(); rootOf[hour] = root; emit Sealed(hour, root); } /// @notice Name a successor. Nothing changes until that address calls `acceptOperator`. /// @dev Naming the zero address withdraws an earlier proposal. function proposeOperator(address proposed) external onlyOperator { pendingOperator = proposed; emit OperatorProposed(msg.sender, proposed); } /// @notice Take over as operator. Only the address named by `proposeOperator` can. function acceptOperator() external { if (msg.sender != pendingOperator) revert NotPendingOperator(); emit OperatorChanged(operator, msg.sender); operator = msg.sender; pendingOperator = address(0); } // ───────────────────────────── views ───────────────────────────── /// @notice Whether `token` is one of the two tokens this contract takes. function isAccepted(address token) external view returns (bool) { return token == usdc || token == eqnvda; } /// @notice The withdrawal `user` has requested in `token`: what `withdraw` would send, and from when. /// @return amount The requested amount, capped at the balance. 0 if nothing is pending. /// @return unlockAt The timestamp from which `withdraw` works. 0 if nothing is pending. function pendingWithdrawal(address user, address token) external view returns (uint256 amount, uint64 unlockAt) { Withdrawal storage w = _withdrawals[user][token]; if (w.amount == 0) return (0, 0); uint256 balance = balanceOf[user][token]; return (w.amount < balance ? w.amount : balance, w.unlockAt); } /// @notice What the operator could charge `user` in `token` right now. function chargeable(address user, address token) external view returns (uint256) { return _chargeable(user, token); } /// @notice What `user` can still spend on rentals in `token`: the balance less any requested withdrawal, /// whether its delay has passed or not. The rental engine must count this, not `balanceOf`. function available(address user, address token) external view returns (uint256) { uint256 balance = balanceOf[user][token]; uint256 requested = _withdrawals[user][token].amount; return requested < balance ? balance - requested : 0; } /// @notice The leaf of a receipt, as the off-chain engine must compute it. function leafOf(bytes32 receiptId, address user, address token, uint256 amount, uint64 secondsBilled, bytes32 gpuId) public pure returns (bytes32) { return keccak256(abi.encode(receiptId, user, token, amount, secondsBilled, gpuId)); } /// @notice Whether `proof` links `leaf` to the root sealed for `hour`. False for an hour that is not sealed. /// @dev A bare hash proves little: the inner nodes of a tree pass this check too. To check a receipt, /// compute the leaf from the receipt's fields, or call `verifyReceipt`, which does it. function verify(uint256 hour, bytes32 leaf, bytes32[] calldata proof) public view returns (bool) { bytes32 root = rootOf[hour]; if (root == bytes32(0)) return false; bytes32 node = leaf; for (uint256 i = 0; i < proof.length; ++i) { bytes32 other = proof[i]; node = node < other ? keccak256(abi.encode(node, other)) : keccak256(abi.encode(other, node)); } return node == root; } /// @notice Whether a receipt with exactly these fields is in the tree sealed for `hour`. function verifyReceipt( uint256 hour, bytes32 receiptId, address user, address token, uint256 amount, uint64 secondsBilled, bytes32 gpuId, bytes32[] calldata proof ) external view returns (bool) { return verify(hour, leafOf(receiptId, user, token, amount, secondsBilled, gpuId), proof); } // ───────────────────────────── internals ───────────────────────────── /// @dev The balance, less a requested withdrawal whose delay has passed. function _chargeable(address user, address token) private view returns (uint256) { uint256 balance = balanceOf[user][token]; Withdrawal storage w = _withdrawals[user][token]; if (w.amount == 0 || block.timestamp < w.unlockAt) return balance; return w.amount < balance ? balance - w.amount : 0; } function _push(address token, address to, uint256 value) private { _call(token, abi.encodeWithSelector(0xa9059cbb, to, value)); // transfer(address,uint256) } function _pull(address token, address from, address to, uint256 value) private { _call(token, abi.encodeWithSelector(0x23b872dd, from, to, value)); // transferFrom(address,address,uint256) } /// @dev Accepts tokens that return true and tokens that return nothing. function _call(address token, bytes memory data) private { if (token.code.length == 0) revert TransferFailed(); (bool ok, bytes memory ret) = token.call(data); if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert TransferFailed(); } }