Skip to content
Verified contractPartialMIT

GridMining

Address0x25a149077d6dff602bbd7660190597cc47fd6f0e
Balance

0 ETH

 

Transactions

14

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,406,006
Creation transaction
0x71fc83cbc6…247847bc61

src/GridMining.sol

// SPDX-License-Identifier: MIT
//
//   Gridstake (GRID)
//   Website: https://gridstake.vip
//   X:       https://x.com/gridstake
//
pragma solidity 0.8.26;

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

interface IGridToken is IERC20 {
    function mint(address to, uint256 amount) external;
    function maxSupply() external view returns (uint256);
}

interface IRandomnessOracle {
    function randomnessFor(uint256 closeTime, bytes calldata signature)
        external
        view
        returns (bytes32 randomness, uint64 round);
}

/// @title GridMining
/// @notice The canonical game. Each epoch miners deploy ETH across a 5x5 grid.
///         A verifiable drand beacon picks one winning block. Wallets on that
///         block split the ETH pot pro rata and earn GRID emissions.
///
///         Accounting is O(1) per settlement: nothing ever loops over players.
///         Stakes are tracked in units of 1e12 wei packed four-per-slot.
contract GridMining is Ownable2Step, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ------------------------------------------------------------ constants

    uint256 public constant BLOCKS = 25;
    uint256 public constant SOLO_BLOCKS = 10;
    /// @notice Stake granularity. All deployments are multiples of this.
    uint256 public constant UNIT = 1e12;
    uint256 public constant BPS = 10_000;
    /// @notice Taken from every deployed wei.
    uint256 public constant ADMIN_FEE_BPS = 100;
    /// @notice Share of losing-block stake (after admin fee) sent to the Treasury.
    uint256 public constant TREASURY_BPS = 1_000;
    /// @notice Paid to a wallet's referrer, as a share of that wallet's deployed volume.
    ///         Funded out of the Treasury cut (falling back to the admin fee).
    uint256 public constant REFERRAL_BPS = 45;
    /// @notice Fee on claiming mined GRID, shared among the other wallets still holding unclaimed GRID.
    uint256 public constant REALIZE_FEE_BPS = 1_000;
    /// @notice Extra emission into the jackpot, as a share of the block reward.
    uint256 public constant POT_BPS = 2_000;
    /// @notice Emission steps: reward falls by 1/8 of base for every 1/8 of the cap minted.
    uint256 public constant EMISSION_STEPS = 8;

    uint256 private constant LANE = type(uint64).max;
    uint256 private constant ACC = 1e27;

    // ----------------------------------------------------------- immutables

    IGridToken public immutable token;
    IRandomnessOracle public immutable oracle;
    address public immutable treasury;
    /// @notice Epoch length in seconds.
    uint256 public immutable epochDuration;
    /// @notice GRID minted to the winning block per epoch at step 0.
    uint256 public immutable baseReward;
    /// @notice The jackpot pays out with probability 1/potOdds per winning epoch.
    uint256 public immutable potOdds;
    /// @notice Minimum stake per block, in units.
    uint64 public immutable minUnits;

    // --------------------------------------------------------------- config

    address public feeCollector;
    /// @notice Only this address (the liquidity hook) can start the game, so
    ///         trading and mining open in the same transaction.
    address public launcher;
    /// @notice Gas reimbursed (at basefee * 1.25) to whoever settles an epoch.
    uint32 public settleGas = 420_000;
    /// @notice Gas reimbursed to whoever executes an Auto deployment.
    uint32 public autoGas = 200_000;

    // ---------------------------------------------------------------- state

    /// @notice Timestamp of the start of epoch 0. Zero until launched.
    uint256 public genesis;

    struct Epoch {
        uint96 totalUnits;
        uint96 referredUnits;
        uint32 soloMask;
        uint8 winningBlock;
        bool settled;
        bool soloWin;
        bool potHit;
        uint128 winnersPool; // wei shared pro rata by the winning block
        uint128 sharedReward; // GRID shared pro rata by the winning block
        uint128 soloReward; // GRID for the single solo winner
        uint64 winnerUnits; // total units on the winning block
        uint64 soloPoint; // winning offset inside the winning block's stake
    }

    struct Position {
        uint32 mask;
        uint64 units; // per selected block
        bool checkpointed;
    }

    struct Auto {
        uint32 mask; // fixed selection (ignored when randomCount > 0)
        uint8 randomCount; // >0: pick this many pseudo-random blocks each epoch
        uint64 units; // per block
        uint32 epochsLeft;
        uint96 balance; // prepaid wei
        uint24 maxFeeGwei; // cap on the per-epoch executor fee
    }

    mapping(uint256 epoch => Epoch) public epochs;
    mapping(uint256 epoch => uint256[7]) private _blockUnits;
    mapping(uint256 epoch => mapping(address => Position)) public positions;
    mapping(uint256 epoch => mapping(address => mapping(uint256 => uint256))) private _soloStarts;
    mapping(address => uint256) private _lastEpochPlusOne;

    mapping(address => Auto) public autos;
    mapping(address => address) public referrerOf;
    mapping(address => uint256) public referralEarned;

    /// @notice ETH owed to an account (winnings, referral rewards, fees, bounties).
    mapping(address => uint256) public pendingEth;

    /// @notice Jackpot balance.
    uint256 public gridPot;
    uint256 public totalUnrealized;
    uint256 public accFeePerShare;
    mapping(address => uint256) private _unrealized;
    mapping(address => uint256) private _feeDebt;
    mapping(address => uint256) private _realized;

    // --------------------------------------------------------------- events

    event Launched(uint256 genesis);
    event Deployed(uint256 indexed epoch, address indexed user, uint32 mask, uint64 unitsPerBlock, bool auto_);
    event Settled(
        uint256 indexed epoch,
        uint64 drandRound,
        uint8 winningBlock,
        uint256 totalWei,
        uint256 winnersPool,
        uint256 treasuryCut,
        uint256 blockReward,
        bool soloWin,
        bool potHit,
        uint256 potPaid
    );
    event Checkpointed(uint256 indexed epoch, address indexed user, uint256 ethWon, uint256 gridWon, bool soloWinner);
    event GridClaimed(address indexed user, uint256 unrealizedClaimed, uint256 fee, uint256 paid);
    event EthWithdrawn(address indexed account, uint256 amount);
    event ReferrerSet(address indexed user, address indexed referrer);
    event ReferralPaid(address indexed referrer, address indexed user, uint256 amount);
    event AutoSet(address indexed user, uint32 mask, uint8 randomCount, uint64 units, uint32 epochs, uint256 balance);
    event AutoCancelled(address indexed user, uint256 refunded);

    // --------------------------------------------------------------- errors

    error NotLauncher();
    error AlreadyLaunched();
    error NotLaunched();
    error InvalidMask();
    error InvalidAmount();
    error BelowMinimum();
    error AlreadyDeployed();
    error LaneOverflow();
    error EpochNotClosed();
    error AlreadySettled();
    error EmptyEpoch();
    error InvalidReferrer();
    error InsufficientBalance();
    error NothingToWithdraw();
    error TransferFailed();
    error OutOfBounds();

    constructor(
        IGridToken token_,
        IRandomnessOracle oracle_,
        address treasury_,
        address feeCollector_,
        uint256 epochDuration_,
        uint256 baseReward_,
        uint256 potOdds_,
        uint256 minStakePerBlock_
    ) Ownable(msg.sender) {
        require(address(token_) != address(0) && address(oracle_) != address(0), "zero");
        require(treasury_ != address(0) && feeCollector_ != address(0), "zero");
        require(epochDuration_ >= 60 && potOdds_ > 0, "params");
        require(minStakePerBlock_ >= UNIT && minStakePerBlock_ % UNIT == 0, "min");
        token = token_;
        oracle = oracle_;
        treasury = treasury_;
        feeCollector = feeCollector_;
        epochDuration = epochDuration_;
        baseReward = baseReward_;
        potOdds = potOdds_;
        minUnits = uint64(minStakePerBlock_ / UNIT);
    }

    // ---------------------------------------------------------------- admin

    function setLauncher(address launcher_) external onlyOwner {
        if (genesis != 0) revert AlreadyLaunched();
        launcher = launcher_;
    }

    function setFeeCollector(address feeCollector_) external onlyOwner {
        require(feeCollector_ != address(0), "zero");
        feeCollector = feeCollector_;
    }

    function setGasAllowances(uint32 settleGas_, uint32 autoGas_) external onlyOwner {
        if (settleGas_ > 1_000_000 || autoGas_ > 500_000) revert OutOfBounds();
        settleGas = settleGas_;
        autoGas = autoGas_;
    }

    /// @notice Opens mining. Called by the liquidity hook inside its launch transaction.
    function start() external {
        if (msg.sender != launcher) revert NotLauncher();
        if (genesis != 0) revert AlreadyLaunched();
        genesis = block.timestamp;
        emit Launched(block.timestamp);
    }

    // ---------------------------------------------------------------- views

    function currentEpoch() public view returns (uint256) {
        if (genesis == 0) revert NotLaunched();
        return (block.timestamp - genesis) / epochDuration;
    }

    function epochStart(uint256 epoch) public view returns (uint256) {
        return genesis + epoch * epochDuration;
    }

    function epochClose(uint256 epoch) public view returns (uint256) {
        return genesis + (epoch + 1) * epochDuration;
    }

    /// @notice Which blocks are "solo" in an epoch. Deterministic and public in advance.
    function soloMaskOf(uint256 epoch) public view returns (uint32 mask) {
        mask = epochs[epoch].soloMask;
        if (mask == 0) mask = _computeSoloMask(epoch);
    }

    /// @notice Total units staked on each of the 25 blocks.
    function blockUnits(uint256 epoch) public view returns (uint64[25] memory out) {
        uint256[7] storage lanes = _blockUnits[epoch];
        for (uint256 b; b < BLOCKS; ++b) {
            out[b] = uint64((lanes[b >> 2] >> ((b & 3) * 64)) & LANE);
        }
    }

    /// @notice GRID reward for the next winning block, before the jackpot add-on.
    function currentReward() public view returns (uint256) {
        uint256 cap = token.maxSupply();
        uint256 supply = token.totalSupply();
        if (supply >= cap) return 0;
        uint256 step = (supply * EMISSION_STEPS) / cap;
        return (baseReward * (EMISSION_STEPS - step)) / EMISSION_STEPS;
    }

    /// @notice What `user` would receive by checkpointing `epoch`.
    function pendingFor(uint256 epoch, address user)
        public
        view
        returns (uint256 ethWon, uint256 gridWon, bool soloWinner)
    {
        Position memory pos = positions[epoch][user];
        Epoch storage ep = epochs[epoch];
        if (pos.units == 0 || pos.checkpointed || !ep.settled) return (0, 0, false);
        return _winnings(epoch, user, pos, ep);
    }

    /// @return unrealized Mined GRID, subject to the realizing fee when claimed.
    /// @return realized GRID earned from other miners' realizing fees, claimable fee-free.
    function gridBalances(address user) public view returns (uint256 unrealized, uint256 realized) {
        unrealized = _unrealized[user];
        uint256 acc = (unrealized * accFeePerShare) / ACC;
        uint256 debt = _feeDebt[user];
        realized = _realized[user] + (acc > debt ? acc - debt : 0);
    }

    // --------------------------------------------------------------- mining

    /// @notice Deploy msg.value split equally across the blocks set in `mask`
    ///         (bit i = block i) for the current epoch. One deployment per
    ///         wallet per epoch.
    /// @param referrer Optional; bound permanently on first use.
    function deploy(uint32 mask, address referrer) external payable {
        uint256 count = _popcount(mask);
        if (count == 0) revert InvalidMask();
        uint256 perBlock = msg.value / count;
        if (perBlock * count != msg.value || perBlock % UNIT != 0) revert InvalidAmount();
        if (referrer != address(0) && referrerOf[msg.sender] == address(0)) _setReferrer(msg.sender, referrer);
        _deploy(msg.sender, currentEpoch(), mask, uint64(perBlock / UNIT), false);
    }

    function setReferrer(address referrer) external {
        if (referrerOf[msg.sender] != address(0)) revert InvalidReferrer();
        _setReferrer(msg.sender, referrer);
    }

    function _setReferrer(address user, address referrer) private {
        if (referrer == address(0) || referrer == user) revert InvalidReferrer();
        referrerOf[user] = referrer;
        emit ReferrerSet(user, referrer);
    }

    function _deploy(address user, uint256 epoch, uint32 mask, uint64 units, bool auto_) private {
        if (mask == 0 || mask >= (1 << BLOCKS)) revert InvalidMask();
        if (units < minUnits) revert BelowMinimum();
        Position storage pos = positions[epoch][user];
        if (pos.units != 0) revert AlreadyDeployed();

        // Roll the wallet's previous epoch into its balances if it is ready.
        uint256 last = _lastEpochPlusOne[user];
        if (last != 0 && last - 1 != epoch) _checkpoint(last - 1, user);
        _lastEpochPlusOne[user] = epoch + 1;

        Epoch storage ep = epochs[epoch];
        uint32 solo = ep.soloMask;
        if (solo == 0) {
            solo = _computeSoloMask(epoch);
            ep.soloMask = solo;
        }

        uint256 count;
        {
            uint256[7] storage lanes = _blockUnits[epoch];
            mapping(uint256 => uint256) storage starts = _soloStarts[epoch][user];
            uint256 soloRank;
            uint256 startWord;
            for (uint256 w; w < 7; ++w) {
                uint256 nib = (mask >> (w * 4)) & 0xF;
                if (nib == 0) continue;
                uint256 word = lanes[w];
                for (uint256 i; i < 4; ++i) {
                    if (nib & (1 << i) == 0) continue;
                    uint256 shift = i * 64;
                    uint256 cur = (word >> shift) & LANE;
                    uint256 next = cur + units;
                    if (next > LANE) revert LaneOverflow();
                    word = (word & ~(LANE << shift)) | (next << shift);
                    if ((solo >> (w * 4 + i)) & 1 == 1) {
                        // Remember where this wallet's stake begins inside the block,
                        // so a solo winner can be identified in O(1).
                        startWord |= cur << ((soloRank & 3) * 64);
                        ++soloRank;
                        if (soloRank & 3 == 0) {
                            starts[(soloRank >> 2) - 1] = startWord;
                            startWord = 0;
                        }
                    }
                    ++count;
                }
                lanes[w] = word;
            }
            if (soloRank & 3 != 0) starts[soloRank >> 2] = startWord;
        }

        uint256 totalUnits = uint256(units) * count;
        ep.totalUnits += uint96(totalUnits);
        pos.mask = mask;
        pos.units = units;

        address referrer = referrerOf[user];
        if (referrer != address(0)) {
            ep.referredUnits += uint96(totalUnits);
            uint256 reward = (totalUnits * UNIT * REFERRAL_BPS) / BPS;
            pendingEth[referrer] += reward;
            referralEarned[referrer] += reward;
            emit ReferralPaid(referrer, user, reward);
        }

        emit Deployed(epoch, user, mask, units, auto_);
    }

    // ----------------------------------------------------------- settlement

    /// @notice Settle a closed epoch with its drand beacon. Permissionless: the
    ///         beacon round is fixed by the epoch's close time and the signature
    ///         is verified on-chain, so the caller has no influence on the result.
    ///         The caller is reimbursed for gas from the epoch's Treasury cut.
    function settle(uint256 epoch, bytes calldata signature) external nonReentrant {
        if (genesis == 0) revert NotLaunched();
        if (block.timestamp < epochClose(epoch)) revert EpochNotClosed();
        Epoch storage ep = epochs[epoch];
        if (ep.settled) revert AlreadySettled();
        uint256 total = ep.totalUnits;
        if (total == 0) revert EmptyEpoch();

        (bytes32 rand, uint64 round) = oracle.randomnessFor(epochClose(epoch), signature);

        uint8 winning = uint8(uint256(keccak256(abi.encode(rand, uint256(0)))) % BLOCKS);
        uint256 winnerUnits = (_blockUnits[epoch][winning >> 2] >> ((winning & 3) * 64)) & LANE;

        uint256 totalWei = total * UNIT;
        uint256 adminFee = (totalWei * ADMIN_FEE_BPS) / BPS;
        uint256 treasuryCut;
        uint256 winnersPool;
        if (winnerUnits == 0) {
            // Nobody picked the winning block: the round is vaulted to the Treasury.
            treasuryCut = totalWei - adminFee;
        } else {
            uint256 losingWei = (total - winnerUnits) * UNIT;
            treasuryCut = (losingWei * (BPS - ADMIN_FEE_BPS) * TREASURY_BPS) / (BPS * BPS);
            winnersPool = totalWei - adminFee - treasuryCut;
        }

        // Referral rewards were credited at deploy time; fund them now.
        {
            uint256 owed = (uint256(ep.referredUnits) * UNIT * REFERRAL_BPS) / BPS;
            if (owed <= treasuryCut) {
                treasuryCut -= owed;
            } else {
                adminFee -= owed - treasuryCut; // REFERRAL_BPS < ADMIN_FEE_BPS, cannot underflow
                treasuryCut = 0;
            }
        }

        // Gas reimbursement for the settler.
        {
            uint256 bounty = (uint256(settleGas) * block.basefee * 5) / 4;
            if (bounty > treasuryCut) bounty = treasuryCut;
            if (bounty != 0) {
                treasuryCut -= bounty;
                pendingEth[msg.sender] += bounty;
            }
        }

        ep.settled = true;
        ep.winningBlock = winning;
        ep.winnersPool = uint128(winnersPool);
        ep.winnerUnits = uint64(winnerUnits);

        uint256 blockReward;
        uint256 potPaid;
        bool soloWin;
        bool potHit;
        if (winnerUnits != 0) {
            uint256 potAdd;
            (blockReward, potAdd) = _emission();
            if (blockReward + potAdd != 0) token.mint(address(this), blockReward + potAdd);
            uint256 pot = gridPot + potAdd;

            soloWin = (ep.soloMask >> winning) & 1 == 1;
            uint256 shared;
            if (soloWin) {
                ep.soloWin = true;
                ep.soloReward = uint128(blockReward);
                ep.soloPoint = uint64(uint256(keccak256(abi.encode(rand, uint256(1)))) % winnerUnits);
            } else {
                shared = blockReward;
            }
            if (pot != 0 && uint256(keccak256(abi.encode(rand, uint256(2)))) % potOdds == 0) {
                potHit = true;
                potPaid = pot;
                shared += pot;
                pot = 0;
                ep.potHit = true;
            }
            gridPot = pot;
            ep.sharedReward = uint128(shared);
        }

        pendingEth[feeCollector] += adminFee;
        pendingEth[treasury] += treasuryCut;

        emit Settled(
            epoch, round, winning, totalWei, winnersPool, treasuryCut, blockReward, soloWin, potHit, potPaid
        );
    }

    function _emission() private view returns (uint256 blockReward, uint256 potAdd) {
        uint256 cap = token.maxSupply();
        uint256 supply = token.totalSupply();
        if (supply >= cap) return (0, 0);
        uint256 room = cap - supply;
        uint256 step = (supply * EMISSION_STEPS) / cap;
        blockReward = (baseReward * (EMISSION_STEPS - step)) / EMISSION_STEPS;
        if (blockReward > room) blockReward = room;
        potAdd = (blockReward * POT_BPS) / BPS;
        if (potAdd > room - blockReward) potAdd = room - blockReward;
    }

    // ---------------------------------------------------------- checkpoints

    /// @notice Move a wallet's winnings for settled epochs into its claimable
    ///         balances. Anyone may call this for anyone; epochs that are not
    ///         ready or were already processed are skipped.
    function checkpoint(address user, uint256[] calldata epochList) external nonReentrant {
        for (uint256 i; i < epochList.length; ++i) {
            _checkpoint(epochList[i], user);
        }
    }

    function _checkpoint(uint256 epoch, address user) private {
        Position storage posRef = positions[epoch][user];
        Position memory pos = posRef;
        if (pos.units == 0 || pos.checkpointed) return;
        Epoch storage ep = epochs[epoch];
        if (!ep.settled) return;
        posRef.checkpointed = true;

        (uint256 ethWon, uint256 gridWon, bool soloWinner) = _winnings(epoch, user, pos, ep);
        if (ethWon != 0) pendingEth[user] += ethWon;
        if (gridWon != 0) _addUnrealized(user, gridWon);
        emit Checkpointed(epoch, user, ethWon, gridWon, soloWinner);
    }

    function _winnings(uint256 epoch, address user, Position memory pos, Epoch storage ep)
        private
        view
        returns (uint256 ethWon, uint256 gridWon, bool soloWinner)
    {
        uint256 winning = ep.winningBlock;
        if ((pos.mask >> winning) & 1 == 0) return (0, 0, false);
        uint256 winnerUnits = ep.winnerUnits;
        ethWon = (uint256(ep.winnersPool) * pos.units) / winnerUnits;
        gridWon = (uint256(ep.sharedReward) * pos.units) / winnerUnits;
        if (ep.soloWin) {
            uint256 rank = _popcount(pos.mask & ep.soloMask & uint32((1 << winning) - 1));
            uint256 begin = (_soloStarts[epoch][user][rank >> 2] >> ((rank & 3) * 64)) & LANE;
            uint256 point = ep.soloPoint;
            if (point >= begin && point < begin + pos.units) {
                soloWinner = true;
                gridWon += ep.soloReward;
            }
        }
    }

    // --------------------------------------------------------------- claims

    /// @notice Send an account the ETH it is owed. Callable by anyone.
    function withdrawEth(address account) external nonReentrant {
        uint256 amount = pendingEth[account];
        if (amount == 0) revert NothingToWithdraw();
        pendingEth[account] = 0;
        (bool ok,) = account.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit EthWithdrawn(account, amount);
    }

    /// @notice Claim `amount` of mined (unrealized) GRID, paying the realizing
    ///         fee, plus all fee-free realized GRID. Pass 0 to claim only the
    ///         realized balance.
    function claimGrid(uint256 amount) external nonReentrant {
        address user = msg.sender;
        _harvest(user);
        uint256 balance = _unrealized[user];
        if (amount > balance) revert InsufficientBalance();

        uint256 fee;
        if (amount != 0) {
            balance -= amount;
            _unrealized[user] = balance;
            uint256 remaining = totalUnrealized - amount;
            totalUnrealized = remaining;
            fee = (amount * REALIZE_FEE_BPS) / BPS;
            // The fee is shared by every OTHER wallet still holding unclaimed GRID.
            uint256 others = remaining - balance;
            if (others != 0) {
                accFeePerShare += (fee * ACC) / others;
            } else {
                gridPot += fee; // nobody else to share it with: feed the jackpot
            }
            // Re-base the claimer so it does not collect a share of its own fee.
            _feeDebt[user] = _debtOf(balance);
        }

        uint256 paid = amount - fee + _realized[user];
        if (paid == 0) revert NothingToWithdraw();
        _realized[user] = 0;
        IERC20(address(token)).safeTransfer(user, paid);
        emit GridClaimed(user, amount, fee, paid);
    }

    /// @dev Fee debts are rounded UP and accruals DOWN, so the sum of all credited
    ///      fees can never exceed the fees actually collected.
    function _debtOf(uint256 balance) private view returns (uint256) {
        return (balance * accFeePerShare + ACC - 1) / ACC;
    }

    function _harvest(address user) private {
        uint256 balance = _unrealized[user];
        uint256 acc = (balance * accFeePerShare) / ACC;
        uint256 debt = _feeDebt[user];
        if (acc > debt) _realized[user] += acc - debt;
        _feeDebt[user] = _debtOf(balance);
    }

    function _addUnrealized(address user, uint256 amount) private {
        _harvest(user);
        uint256 balance = _unrealized[user] + amount;
        _unrealized[user] = balance;
        totalUnrealized += amount;
        _feeDebt[user] = _debtOf(balance);
    }

    // ----------------------------------------------------------------- auto

    /// @notice Prepay repeat deployments. Replaces any existing configuration;
    ///         msg.value is added to the prepaid balance. Anyone (normally a
    ///         keeper) can then call `executeAuto` once per epoch and is paid
    ///         a gas-based fee, capped by `maxFeeGwei`, from the balance.
    /// @param mask Fixed block selection; ignored if randomCount > 0.
    /// @param randomCount If > 0, deploy to this many pseudo-random blocks each epoch.
    function setAuto(uint32 mask, uint8 randomCount, uint256 perBlock, uint32 epochCount, uint24 maxFeeGwei)
        external
        payable
    {
        if (randomCount > BLOCKS) revert InvalidMask();
        if (randomCount == 0 && (mask == 0 || mask >= (1 << BLOCKS))) revert InvalidMask();
        if (perBlock % UNIT != 0 || perBlock / UNIT < minUnits || perBlock / UNIT > LANE) revert InvalidAmount();
        Auto storage a = autos[msg.sender];
        uint256 balance = uint256(a.balance) + msg.value;
        if (balance > type(uint96).max) revert InvalidAmount();
        a.mask = mask;
        a.randomCount = randomCount;
        a.units = uint64(perBlock / UNIT);
        a.epochsLeft = epochCount;
        a.balance = uint96(balance);
        a.maxFeeGwei = maxFeeGwei;
        emit AutoSet(msg.sender, mask, randomCount, a.units, epochCount, balance);
    }

    /// @notice Stop Auto and move the unused prepaid balance to `pendingEth`.
    function cancelAuto() external {
        Auto storage a = autos[msg.sender];
        uint256 refund = a.balance;
        delete autos[msg.sender];
        if (refund != 0) pendingEth[msg.sender] += refund;
        emit AutoCancelled(msg.sender, refund);
    }

    /// @notice Deploy the current epoch for each listed Auto wallet. Wallets that
    ///         are inactive, underfunded or already deployed are skipped.
    function executeAuto(address[] calldata users) external nonReentrant {
        uint256 epoch = currentEpoch();
        uint256 gasFee = (uint256(autoGas) * block.basefee * 5) / 4;
        uint256 earned;
        for (uint256 i; i < users.length; ++i) {
            address user = users[i];
            Auto memory a = autos[user];
            if (a.epochsLeft == 0 || positions[epoch][user].units != 0) continue;
            uint32 mask = a.randomCount == 0 ? a.mask : _randomMask(user, epoch, a.randomCount);
            uint256 cost = uint256(a.units) * UNIT * _popcount(mask);
            uint256 fee = gasFee;
            uint256 cap = uint256(a.maxFeeGwei) * 1 gwei;
            if (fee > cap) fee = cap;
            if (a.balance < cost + fee) continue;
            Auto storage s = autos[user];
            s.balance = uint96(a.balance - cost - fee);
            s.epochsLeft = a.epochsLeft - 1;
            earned += fee;
            _deploy(user, epoch, mask, a.units, true);
        }
        if (earned != 0) pendingEth[msg.sender] += earned;
    }

    // ------------------------------------------------------------- internal

    function _computeSoloMask(uint256 epoch) private view returns (uint32 mask) {
        bytes32 seed = keccak256(abi.encode(address(this), "solo", epoch));
        return _pick(seed, SOLO_BLOCKS);
    }

    function _randomMask(address user, uint256 epoch, uint256 count) private pure returns (uint32) {
        return _pick(keccak256(abi.encode(user, "auto", epoch)), count);
    }

    /// @dev Partial Fisher-Yates: choose `count` distinct blocks from 25.
    function _pick(bytes32 seed, uint256 count) private pure returns (uint32 mask) {
        uint8[25] memory idx;
        for (uint256 i; i < BLOCKS; ++i) {
            idx[i] = uint8(i);
        }
        uint256 r = uint256(seed);
        for (uint256 i; i < count; ++i) {
            uint256 j = i + (r % (BLOCKS - i));
            r = uint256(keccak256(abi.encode(r)));
            (idx[i], idx[j]) = (idx[j], idx[i]);
            mask |= uint32(1) << idx[i];
        }
    }

    function _popcount(uint32 x) private pure returns (uint256 c) {
        while (x != 0) {
            x &= x - 1;
            ++c;
        }
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "bls/=lib/bls-solidity/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.