Перейти к содержимому
Проверенный контрактТочноеMIT

CryoChamber

Адрес0xae2ddc0ae9c498c82c01e34d48a7e84165322f26
Баланс

0,06336 ETH

 

Транзакций

197

 

Компилятор

solc 0.8.28

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.28+commit.7893614a
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
prague
Через IR
да
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 328 776
Транзакция создания
0xb5a5147cfe…5bada9daf9

src/CryoChamber.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {OwnableRoles} from "solady/auth/OwnableRoles.sol";
import {MerkleProofLib} from "solady/utils/MerkleProofLib.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {Pausable} from "solidity-kit/pause/Pausable.sol";

/// @notice The part of Genesis GVC the Chamber calls. GVC is a Solady ERC-721 whose transfers ask
///         Limit Break's validator V3; an operator's pull passes only once list 2 whitelists the
///         operator (runbook 1.3, P1-1).
interface IGenesisGVC {
    function transferFrom(address from, address to, uint256 tokenId) external;

    function ownerOf(uint256 tokenId) external view returns (address);
}

/**
 * @title CryoChamber
 * @notice Custody for Genesis GVC on Ethereum (spec §2). A GVC jailed here earns `creditsPerGvc`
 *         Moods mint credits, announced by `Jailed`, which the signer turns into trade-in vouchers
 *         on Robinhood Chain. There is no withdraw for a jailed or committed GVC, for anyone: a
 *         jailed GVC leaves only by exchange, on the same rules for the team as for anyone.
 *
 * Ways in, each credited once per GVC ever (P2-3):
 * - `deposit` / `depositWithProof`: the Chamber pulls the caller's GVCs, batch included;
 * - a `safeTransferFrom` straight to the Chamber: `onERC721Received` credits the sender, or the
 *   address the sender names in `data` so a contract wallet can credit its own EOA (COMP-3). Only
 *   the sender's own transfer may name one (`operator == from`).
 *
 * A plain `transferFrom` never calls the hook, so it credits nobody and jails nothing: such a GVC
 * belongs to the Chamber but is in no pool and no commitment, and only the owner can send it on
 * (`recoverOrphan`) — it is never silently credited or thrown into the pool.
 *
 * Caps count the sending address (`depositedBy`): `maxDeposits` GVCs in total, and per sender
 * `maxPerHolder` (0 means none) further capped, when `allowanceRoot` is set, by the sender's
 * snapshot allowance proven against that root. Naming another `creditTo` never moves a cap.
 *
 * Exchanges swap a GVC of the caller's for a jailed one and earn no credits:
 * - `exchangeSpecific` picks the jailed GVC. Once deposits are closed it works whether the owner
 *   has the exchange open or not, and a pause does not stop it, so the jail always has one exit a
 *   holder can buy without any switch. It cannot buy the slot a pending draw has drawn once that
 *   draw's entropy hash is public (`DrawnSlotReserved`);
 * - `exchangeRandom` commits the caller's GVC; the draw is seeded by the hash of a block mined
 *   after the commit (P2-1), and anyone (a keeper) settles it with `revealExchange` inside the
 *   256 blocks that hash stays readable. The drawn prize is bound to the slot it was drawn from:
 *   if that slot was rewritten since the commit (a same-window reveal or an exchange before the hash
 *   was public) or its GVC left the Chamber out of band, the draw is not settled against a
 *   substitute — `revealExchange` refuses it and `voidExchange` returns the committed GVC and the
 *   fee to the committer. After the window `expireExchange` returns the committed GVC and keeps the
 *   fee, which a nonzero fee floor makes a paid redraw.
 *
 * Fees never decide whether an exit settles. `exchangeRandom` escrows its fee (`escrowedFees`)
 * until the draw settles; a settled fee, random or specific, is accrued in `accruedFees` and paid
 * to `feeRecipient` by the permissionless `claimFees`. A voided draw's fee is pushed back to its
 * committer with bounded gas, and booked in `refundOwed` for `claimRefund` when the push fails.
 * Forced ETH (a selfdestruct or a pre-funded address) sits beside these ledgers; no function can
 * spend it.
 *
 * Both exchanges need `exchangesOpen`, which only the owner sets and which is false at deploy, so
 * swaps start when the team opens them (plan: after the mint), not on day one. `revealExchange`,
 * `expireExchange` and `voidExchange` never need it, so a commitment always settles.
 *
 * Switches: `openDeposits` takes the owner or a `SWITCH_ROLE` launch key; the one-way
 * `closeDeposits` retires the program and is the owner's alone, and only fires once deposits have
 * opened. `setExchangesOpen`, `pause` and `unpause` (the kit's `Pausable`), the fees, and the fee
 * recipient are the owner's alone. Pause stops every way in and new random exchanges; it never
 * blocks settling a commitment already made, and it never blocks `exchangeSpecific`.
 *
 * Ownership is two-step: `requestOwnershipHandover` then `completeOwnershipHandover`. The
 * single-step `transferOwnership` and `renounceOwnership` the base contract offers both revert, so
 * a typo or a renounce can never lock the jail. A handover leaves roles untouched: revoke
 * `SWITCH_ROLE` holders after one (docs/chamber.md).
 */
contract CryoChamber is OwnableRoles, Pausable, ReentrancyGuard {
    /// @notice A random exchange between its commit and its settlement.
    /// @param account Who committed; receives the drawn GVC, or the committed GVC on expiry or void.
    /// @param entropyBlock The block whose hash seeds the draw; mined after the commit.
    /// @param poolSize `jailedCount()` at the commit; the draw's modulus, fixed so that later
    ///        deposits cannot steer a draw whose seed is already public.
    /// @param commitBlock The block of the commit; a slot written in that block or after it voids a
    ///        draw of it, so a searcher who orders after the commit inside the same block cannot
    ///        slip past.
    /// @param gvcId The GVC the account put in.
    /// @param fee The random-exchange fee this commitment paid, escrowed until it settles.
    struct PendingExchange {
        address account;
        uint64 entropyBlock;
        uint32 poolSize;
        uint64 commitBlock;
        uint256 gvcId;
        uint256 fee;
    }

    /// @notice Holders of this role may open deposits; grants are the owner's.
    uint256 public constant SWITCH_ROLE = _ROLE_0;

    /// @notice A random draw reads the hash of the block this many blocks after its commit.
    uint256 public constant ENTROPY_DELAY = 1;

    /// @notice `blockhash` reads only the latest 256 blocks: the window to reveal a draw.
    uint256 public constant REVEAL_WINDOW = 256;

    /// @notice The most either exchange may charge, so a fee typo cannot switch an exit off.
    uint256 public constant MAX_EXCHANGE_FEE = 1 ether;

    /// @notice The least either exchange may charge. A redraw and a bought prize both cost a fee;
    ///         a dust fee would make a lapsed draw (a free option on the whole pool) free.
    uint256 public constant MIN_EXCHANGE_FEE = 0.001 ether;

    /// @notice The most random exchanges pending at once, which bounds the loop in `exchangeSpecific`.
    uint256 public constant MAX_PENDING_EXCHANGES = 64;

    /// @notice The gas a void refund push gets; a refund that cannot be pushed is booked for `claimRefund`.
    uint256 internal constant REFUND_GAS = 50_000;

    /// @notice The most credits one jailed GVC may earn, so a credits typo stays bounded.
    uint8 public constant MAX_CREDITS_PER_GVC = 10;

    /// @notice Genesis GVC; the only ERC-721 the Chamber accepts.
    IGenesisGVC public immutable gvc;

    /// @notice The most GVCs the Chamber ever credits (spec: 500).
    uint256 public immutable maxDeposits;

    /// @notice Moods mint credits per jailed GVC (spec: 3, or 2).
    uint8 public immutable creditsPerGvc;

    /// @notice The most GVCs one holder may have credited; 0 means no flat cap.
    uint256 public immutable maxPerHolder;

    /// @notice Merkle root of snapshot allowances, leaf `allowanceLeaf(holder, allowance)`, the
    ///         solidity-kit MerkleAllowlist format; zero means no snapshot cap.
    bytes32 public immutable allowanceRoot;

    /// @notice The exact ETH `exchangeRandom` takes; escrowed until the draw settles.
    uint256 public randomExchangeFee;

    /// @notice The exact ETH `exchangeSpecific` takes.
    uint256 public specificExchangeFee;

    /// @notice Where `claimFees` pays the accrued exchange fees (the Toast Safe).
    address public feeRecipient;

    /// @notice True between `openDeposits` and `closeDeposits`.
    bool public depositsOpen;

    /// @notice True once `closeDeposits` ran; deposits never reopen.
    bool public depositsClosed;

    /// @notice True once the owner opens the exchange; false at deploy. Reopenable, owner-only.
    bool public exchangesOpen;

    /// @notice The random-exchange fees held for commitments not yet settled; every one is owed to
    ///         `accruedFees` on a settled draw and to its committer on a voided one.
    uint256 public escrowedFees;

    /// @notice The depositor each GVC was credited to. Permanent: it stays after the GVC leaves by
    ///         exchange, and a nonzero entry means the GVC can never be credited again (P2-3).
    mapping(uint256 gvcId => address depositor) public depositorOf;

    /// @notice Every GVC in the Chamber and available to exchanges, in slot order.
    uint256[] public jailed;

    /// @notice How many GVCs have been credited to each holder (the credit ledger).
    mapping(address holder => uint256 count) public creditedBy;

    /// @notice How many GVCs each address has put in itself (`deposit`, `depositWithProof`, or a
    ///         direct send it sent): the counter every cap checks, whoever the credit names.
    mapping(address sender => uint256 count) public depositedBy;

    /// @notice Settled exchange fees awaiting `claimFees`, owed to the current `feeRecipient`.
    uint256 public accruedFees;

    /// @notice Void refunds that could not be pushed to their committer, for `claimRefund`.
    mapping(address account => uint256 amount) public refundOwed;

    /// @notice The sum of `refundOwed`.
    uint256 public refundsOwed;

    /// @notice The commit id holding each GVC in escrow; zero when the GVC is not committed.
    mapping(uint256 gvcId => uint256 commitId) public pendingCommitOf;

    /// @dev `jailed` index + 1 of each jailed GVC; zero when the GVC is not jailed.
    mapping(uint256 gvcId => uint256 slot) private _slotOf;

    /// @dev The commit ids awaiting settlement, for the keeper's `pendingCommitIds`.
    uint256[] private _pendingIds;

    /// @dev 1-based index in `_pendingIds`; zero when the commit is settled.
    mapping(uint256 commitId => uint256 slot) private _pendingSlotOf;

    /// @dev The random exchanges awaiting settlement.
    mapping(uint256 commitId => PendingExchange) private _pending;

    /// @dev The last block that rewrote each `jailed` slot; a drawn slot whose stamp is at or past
    ///      its commitment's `commitBlock` is no longer the prize the commit was betting on, so that
    ///      draw cannot settle.
    mapping(uint256 slot => uint64 blockNo) private _slotWrittenAt;

    /// @notice The last commit id issued; ids start at 1.
    uint256 public commitCount;

    /// @notice A GVC entered the Chamber and earned `credits` for `depositor`. Frozen: topic0
    ///         0x490f95085331b576651257291856a32ee6a57d3edc827a0ec13a7be140d93e84.
    event Jailed(uint256 indexed gvcId, address indexed depositor, uint256 credits);

    /// @notice `account` committed `gvcId` to a random exchange seeded by `entropyBlock`'s hash.
    event ExchangeCommitted(
        uint256 indexed commitId, address indexed account, uint256 indexed gvcId, uint256 entropyBlock
    );

    /// @notice `account` gave `gaveId` and got the jailed `gotId`; `commitId` is 0 for a specific exchange.
    event Exchanged(address indexed account, uint256 indexed gaveId, uint256 indexed gotId, uint256 commitId);

    /// @notice A commitment's reveal window lapsed; `gvcId` went back to `account` and the fee was
    ///         accrued for the fee recipient.
    event ExchangeExpired(uint256 indexed commitId, address indexed account, uint256 indexed gvcId);

    /// @notice A commitment's drawn slot changed hands before settlement; `gvcId` went back to
    ///         `account` and so did the fee it paid.
    event ExchangeVoided(uint256 indexed commitId, address indexed account, uint256 indexed gvcId);

    /// @notice A GVC that reached the Chamber without the hook went to `to`; `recoverOrphan`.
    event OrphanRecovered(uint256 indexed gvcId, address indexed to);

    /// @notice A settled commitment's escrowed GVC was no longer in the Chamber (it left out of
    ///         band), so it could not be returned; the commitment cleared anyway.
    event EscrowedGvcMissing(uint256 indexed commitId, address indexed account, uint256 indexed gvcId);

    event DepositsOpened(address indexed by);
    event DepositsClosed(address indexed by);
    event ExchangesSet(bool open);
    event ExchangeFeesSet(uint256 randomExchangeFee, uint256 specificExchangeFee);
    event FeeRecipientSet(address indexed feeRecipient);
    event FeesClaimed(address indexed to, uint256 amount);
    event RefundOwed(address indexed account, uint256 amount);
    event RefundClaimed(address indexed account, address indexed to, uint256 amount);

    error ZeroAddress();
    error InvalidParameters();
    error NotGvc();
    error DepositsNotOpen();
    error DepositsAlreadyOpen();
    error DepositsClosedForever();
    error ExchangesClosed();
    error NoIds();
    error ChamberFull(uint256 room);
    error HolderLimitExceeded(address holder, uint256 limit);
    error AllowanceProofRequired();
    error AllowanceRootNotSet();
    error InvalidAllowanceProof();
    error AlreadyCredited(uint256 gvcId);
    error AlreadyJailed(uint256 gvcId);
    error NotJailed(uint256 gvcId);
    error NothingJailed();
    error WrongFee(uint256 expected, uint256 sent);
    error UnknownCommit(uint256 commitId);
    error EntropyNotReady(uint256 commitId, uint256 entropyBlock);
    error EntropyUnavailable(uint256 commitId);
    error CommitExpired(uint256 commitId);
    error CommitNotExpired(uint256 commitId, uint256 lastRevealBlock);
    error DrawnSlotMoved(uint256 commitId);
    error DrawNotMoved(uint256 commitId);
    error NotHeld(uint256 gvcId);
    error NotOrphaned(uint256 gvcId);
    error AlreadyCommitted(uint256 gvcId);
    error DrawnSlotReserved(uint256 commitId);
    error TooManyPending();
    error NothingToClaim();
    error UseOwnershipHandover();
    error RenounceNotAllowed();
    error NoValueAccepted();

    constructor(
        address gvc_,
        address owner_,
        address feeRecipient_,
        uint256 maxDeposits_,
        uint8 creditsPerGvc_,
        uint256 maxPerHolder_,
        bytes32 allowanceRoot_,
        uint256 randomExchangeFee_,
        uint256 specificExchangeFee_
    ) {
        if (gvc_ == address(0) || owner_ == address(0) || feeRecipient_ == address(0)) {
            revert ZeroAddress();
        }
        if (
            maxDeposits_ == 0 || maxDeposits_ > type(uint32).max || creditsPerGvc_ == 0
                || creditsPerGvc_ > MAX_CREDITS_PER_GVC || randomExchangeFee_ < MIN_EXCHANGE_FEE
                || specificExchangeFee_ < MIN_EXCHANGE_FEE || randomExchangeFee_ > MAX_EXCHANGE_FEE
                || specificExchangeFee_ > MAX_EXCHANGE_FEE || feeRecipient_ == address(this)
        ) revert InvalidParameters();

        gvc = IGenesisGVC(gvc_);
        maxDeposits = maxDeposits_;
        creditsPerGvc = creditsPerGvc_;
        maxPerHolder = maxPerHolder_;
        allowanceRoot = allowanceRoot_;
        randomExchangeFee = randomExchangeFee_;
        specificExchangeFee = specificExchangeFee_;
        feeRecipient = feeRecipient_;
        emit ExchangeFeesSet(randomExchangeFee_, specificExchangeFee_);
        emit FeeRecipientSet(feeRecipient_);
        _initializeOwner(owner_);
    }

    /*//////////////////////////////////////////////////////////////
                                DEPOSITS
    //////////////////////////////////////////////////////////////*/

    /// @notice Jail the caller's GVCs, which must have approved the Chamber, and credit the caller.
    ///         Without an `allowanceRoot`; with one, use `depositWithProof`.
    function deposit(uint256[] calldata ids) external nonReentrant whenNotPaused {
        _requireDepositsOpen();
        if (allowanceRoot != bytes32(0)) revert AllowanceProofRequired();
        _pullAndJail(ids, _flatLimit());
    }

    /// @notice `deposit` under a snapshot cap: `allowance` is the caller's leaf in `allowanceRoot`.
    function depositWithProof(uint256[] calldata ids, uint256 allowance, bytes32[] calldata proof)
        external
        nonReentrant
        whenNotPaused
    {
        _requireDepositsOpen();
        _pullAndJail(ids, _provenLimit(msg.sender, allowance, proof));
    }

    /// @notice Credits a GVC sent straight here with `safeTransferFrom` on the same rules as
    ///         `deposit`; a refusal reverts the transfer, so the GVC stays with the sender.
    ///         `data` is empty, or `abi.encode(address creditTo, uint256 allowance, bytes32[] proof)`:
    ///         `creditTo` (zero means the sender) receives the credit, so a contract wallet that
    ///         cannot exist on Robinhood Chain can credit its own EOA (COMP-3), and the allowance
    ///         and proof are the sender's leaf in `allowanceRoot`, required when there is one.
    ///         `creditTo` is honoured only when the sender itself initiates the transfer
    ///         (`operator == from`): a transfer an operator initiates for the holder (an approved
    ///         marketplace, a list 2 operator) credits the holder, whatever `data` names. The caps
    ///         count the sender (`depositedBy`), never the recipient it names.
    function onERC721Received(address operator, address from, uint256 id, bytes calldata data)
        external
        nonReentrant
        whenNotPaused
        returns (bytes4)
    {
        if (msg.sender != address(gvc)) revert NotGvc();
        if (from == address(0)) revert ZeroAddress();
        _requireDepositsOpen();
        address creditTo = from;
        uint256 limit;
        if (data.length == 0) {
            if (allowanceRoot != bytes32(0)) revert AllowanceProofRequired();
            limit = _flatLimit();
        } else {
            (address named, uint256 allowance, bytes32[] memory proof) = abi.decode(data, (address, uint256, bytes32[]));
            if (named != address(0) && operator == from) creditTo = named;
            limit = allowanceRoot == bytes32(0) ? _flatLimit() : _provenLimit(from, allowance, proof);
        }
        _admit(from, 1, limit);
        _requireJailable(id);
        _recordJail(from, creditTo, id);
        return this.onERC721Received.selector;
    }

    /*//////////////////////////////////////////////////////////////
                               EXCHANGES
    //////////////////////////////////////////////////////////////*/

    /// @notice Swap the caller's `myGvcId` for the jailed `wantId`, paying exactly `specificExchangeFee`
    ///         (accrued for the fee recipient). Needs `exchangesOpen`, unless deposits are closed:
    ///         from the cutoff on it always works, so the jail keeps one exit that no switch, pause
    ///         or fee recipient can hold. One for one, and it cannot touch a committed GVC, nor the
    ///         slot a pending commitment has drawn once its entropy hash is public
    ///         (`DrawnSlotReserved`): settle that commitment with `revealExchange` first, which
    ///         anyone may call.
    function exchangeSpecific(uint256 myGvcId, uint256 wantId) external payable nonReentrant {
        if (!exchangesOpen && !depositsClosed) revert ExchangesClosed();
        if (msg.value != specificExchangeFee) revert WrongFee(specificExchangeFee, msg.value);
        uint256 slot = _slotOf[wantId];
        if (slot == 0) revert NotJailed(wantId);
        if (_slotOf[myGvcId] != 0) revert AlreadyJailed(myGvcId);
        _requireNotDrawn(slot - 1);

        jailed[slot - 1] = myGvcId;
        _slotOf[myGvcId] = slot;
        delete _slotOf[wantId];
        // forge-lint: disable-next-line(unsafe-typecast)
        _slotWrittenAt[slot - 1] = uint64(block.number);
        accruedFees += msg.value;
        emit Exchanged(msg.sender, myGvcId, wantId, 0);

        gvc.transferFrom(msg.sender, address(this), myGvcId);
        gvc.transferFrom(address(this), msg.sender, wantId);
    }

    /// @notice Commit the caller's `myGvcId` to a random exchange, paying exactly `randomExchangeFee`,
    ///         which the Chamber escrows until the draw settles. The draw comes from the hash of block
    ///         `block.number + ENTROPY_DELAY`, which no one knows at the commit; anyone settles it
    ///         with `revealExchange` once that block is mined. Needs `exchangesOpen`.
    function exchangeRandom(uint256 myGvcId) external payable nonReentrant whenNotPaused returns (uint256 commitId) {
        if (!exchangesOpen) revert ExchangesClosed();
        if (msg.value != randomExchangeFee) revert WrongFee(randomExchangeFee, msg.value);
        if (_pendingIds.length >= MAX_PENDING_EXCHANGES) revert TooManyPending();
        uint256 poolSize = jailed.length;
        if (poolSize == 0) revert NothingJailed();
        if (_slotOf[myGvcId] != 0) revert AlreadyJailed(myGvcId);
        commitId = ++commitCount;
        uint256 entropyBlock = block.number + ENTROPY_DELAY;
        _pending[commitId] = PendingExchange({
            account: msg.sender,
            // forge-lint: disable-next-line(unsafe-typecast)
            entropyBlock: uint64(entropyBlock), // a block number; uint64 lasts past any chain's life
            // forge-lint: disable-next-line(unsafe-typecast)
            poolSize: uint32(poolSize), // at most maxDeposits, which the constructor bounds to uint32
            // forge-lint: disable-next-line(unsafe-typecast)
            commitBlock: uint64(block.number),
            gvcId: myGvcId,
            fee: msg.value
        });
        _trackPending(commitId);
        pendingCommitOf[myGvcId] = commitId;
        escrowedFees += msg.value;
        emit ExchangeCommitted(commitId, msg.sender, myGvcId, entropyBlock);

        gvc.transferFrom(msg.sender, address(this), myGvcId);
    }

    /// @notice Settle a random exchange: the committed GVC takes the drawn slot and the drawn GVC
    ///         goes to the committer, and the escrowed fee is accrued for the fee recipient. Anyone
    ///         may call it, from the block after the entropy block through `REVEAL_WINDOW` blocks
    ///         after it. Refuses a draw that cannot settle (its slot was rewritten since the commit, in
    ///         the commit's own block too, its GVC gone, or the committed GVC gone); `voidExchange`
    ///         settles that.
    function revealExchange(uint256 commitId) external nonReentrant returns (uint256 gotId) {
        PendingExchange memory p = _pending[commitId];
        if (p.account == address(0)) revert UnknownCommit(commitId);
        if (block.number <= p.entropyBlock) revert EntropyNotReady(commitId, p.entropyBlock);
        if (block.number > uint256(p.entropyBlock) + REVEAL_WINDOW) revert CommitExpired(commitId);
        bytes32 entropy = blockhash(p.entropyBlock);
        if (entropy == bytes32(0)) revert EntropyUnavailable(commitId);

        uint256 index = drawIndex(entropy, commitId, p.poolSize);
        if (_slotUnusable(index, p.commitBlock) || !_held(p.gvcId)) revert DrawnSlotMoved(commitId);

        gotId = jailed[index];
        jailed[index] = p.gvcId;
        _slotOf[p.gvcId] = index + 1;
        delete _slotOf[gotId];
        // forge-lint: disable-next-line(unsafe-typecast)
        _slotWrittenAt[index] = uint64(block.number);
        _clearPending(commitId, p);
        emit Exchanged(p.account, p.gvcId, gotId, commitId);

        gvc.transferFrom(address(this), p.account, gotId);
        _accrueFee(p.fee);
    }

    /// @notice Close a random exchange whose reveal window lapsed: the committed GVC goes back to
    ///         its committer, the fee stays with the fee recipient (a lapse is a paid redraw).
    ///         Anyone may call it.
    function expireExchange(uint256 commitId) external nonReentrant {
        PendingExchange memory p = _pending[commitId];
        if (p.account == address(0)) revert UnknownCommit(commitId);
        uint256 lastRevealBlock = uint256(p.entropyBlock) + REVEAL_WINDOW;
        if (block.number <= lastRevealBlock) revert CommitNotExpired(commitId, lastRevealBlock);

        _clearPending(commitId, p);
        emit ExchangeExpired(commitId, p.account, p.gvcId);

        _returnEscrowed(commitId, p);
        _accrueFee(p.fee);
    }

    /// @notice Void a random exchange that cannot settle: the drawn slot was rewritten at or after
    ///         the commit (a same-window reveal or exchange took it), or its GVC left the Chamber out
    ///         of band, or the committer's own GVC did. The committed GVC (if the Chamber still holds
    ///         it) and the fee go back to the committer (a refund that cannot be pushed is booked for
    ///         `claimRefund`). Anyone may call it, from the block after the entropy block while the
    ///         entropy hash is readable; after the window `expireExchange` covers it and keeps the fee.
    function voidExchange(uint256 commitId) external nonReentrant {
        PendingExchange memory p = _pending[commitId];
        if (p.account == address(0)) revert UnknownCommit(commitId);
        if (block.number <= p.entropyBlock) revert EntropyNotReady(commitId, p.entropyBlock);
        if (!_drawnSlotMoved(p, commitId)) revert DrawNotMoved(commitId);

        _clearPending(commitId, p);
        emit ExchangeVoided(commitId, p.account, p.gvcId);

        _returnEscrowed(commitId, p);
        _refund(p.account, p.fee);
    }

    /*//////////////////////////////////////////////////////////////
                                SWITCHES
    //////////////////////////////////////////////////////////////*/

    function openDeposits() external onlyOwnerOrRoles(SWITCH_ROLE) {
        if (depositsClosed) revert DepositsClosedForever();
        if (depositsOpen) revert DepositsAlreadyOpen();
        depositsOpen = true;
        emit DepositsOpened(msg.sender);
    }

    /// @notice One-way and the owner's alone: it retires the whole program, so the launch key
    ///         cannot do it. Only once deposits are open, so it can never fire before the mint.
    ///         Exchanges keep running.
    function closeDeposits() external onlyOwner {
        if (depositsClosed) revert DepositsClosedForever();
        if (!depositsOpen) revert DepositsNotOpen();
        depositsOpen = false;
        depositsClosed = true;
        emit DepositsClosed(msg.sender);
    }

    /*//////////////////////////////////////////////////////////////
                                 OWNER
    //////////////////////////////////////////////////////////////*/

    /// @notice Open or close the exchange. Owner-only and reopenable; closed at deploy, so swaps
    ///         start when the team opens them (plan: after the mint). Commitments already made settle,
    ///         and `exchangeSpecific` works regardless once deposits are closed.
    function setExchangesOpen(bool open) external onlyOwner {
        exchangesOpen = open;
        emit ExchangesSet(open);
    }

    /// @notice Set both exchange fees, inside `MIN_EXCHANGE_FEE` and `MAX_EXCHANGE_FEE`: a dust fee
    ///         would make a redraw free. A commitment already made keeps the fee it paid.
    function setExchangeFees(uint256 randomFee, uint256 specificFee) external onlyOwner {
        if (
            randomFee < MIN_EXCHANGE_FEE || specificFee < MIN_EXCHANGE_FEE || randomFee > MAX_EXCHANGE_FEE
                || specificFee > MAX_EXCHANGE_FEE
        ) {
            revert InvalidParameters();
        }
        randomExchangeFee = randomFee;
        specificExchangeFee = specificFee;
        emit ExchangeFeesSet(randomFee, specificFee);
    }

    function setFeeRecipient(address recipient) external onlyOwner {
        if (recipient == address(0)) revert ZeroAddress();
        if (recipient == address(this)) revert InvalidParameters();
        feeRecipient = recipient;
        emit FeeRecipientSet(recipient);
    }

    /// @notice Send on a GVC the Chamber owns that is neither jailed nor committed, which only a
    ///         plain `transferFrom` (no hook, no credit) can create, to an address the owner names.
    ///         Never touches a jailed or committed GVC, so it cannot be a withdraw.
    function recoverOrphan(uint256 gvcId, address to) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        if (_slotOf[gvcId] != 0 || pendingCommitOf[gvcId] != 0) revert NotOrphaned(gvcId);
        if (gvc.ownerOf(gvcId) != address(this)) revert NotHeld(gvcId);
        emit OrphanRecovered(gvcId, to);
        gvc.transferFrom(address(this), to, gvcId);
    }

    /*//////////////////////////////////////////////////////////////
                                PAYOUTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Pay every accrued fee to the current `feeRecipient`. Anyone may call it; the
    ///         recipient only receives, and a recipient that refuses ETH blocks this call and
    ///         nothing else (the owner points `setFeeRecipient` somewhere that takes it).
    function claimFees() external nonReentrant returns (uint256 amount) {
        amount = accruedFees;
        if (amount == 0) revert NothingToClaim();
        accruedFees = 0;
        address to = feeRecipient;
        emit FeesClaimed(to, amount);
        // forge-lint: disable-next-line(arbitrary-send-eth)
        SafeTransferLib.safeTransferETH(to, amount);
    }

    /// @notice Pull a voided draw's refund that `_refund` could not push to the caller, to `to`.
    function claimRefund(address to) external nonReentrant returns (uint256 amount) {
        if (to == address(0)) revert ZeroAddress();
        amount = refundOwed[msg.sender];
        if (amount == 0) revert NothingToClaim();
        delete refundOwed[msg.sender];
        refundsOwed -= amount;
        emit RefundClaimed(msg.sender, to, amount);
        SafeTransferLib.safeTransferETH(to, amount);
    }

    /// @dev Ownership is two-step only: `requestOwnershipHandover` then `completeOwnershipHandover`.
    function transferOwnership(address) public payable override {
        revert UseOwnershipHandover();
    }

    /// @dev Never: a renounce would freeze every switch, fees and the exchange for good.
    function renounceOwnership() public payable override {
        revert RenounceNotAllowed();
    }

    /// @dev The Chamber has no `receive`, no `fallback` and no sweep: only `exchangeRandom` and
    ///      `exchangeSpecific` take ETH, and what they take is booked. Solady's handover and role
    ///      entry points are `payable`, and `requestOwnershipHandover`, `cancelOwnershipHandover` and
    ///      `renounceRoles` are callable by anyone, so without these guards a wallet that attached
    ///      value to one would strand it. They stay `payable` (the signatures are inherited) and
    ///      refuse a non-zero value instead.
    function requestOwnershipHandover() public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.requestOwnershipHandover();
    }

    /// @dev See `requestOwnershipHandover`.
    function cancelOwnershipHandover() public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.cancelOwnershipHandover();
    }

    /// @dev See `requestOwnershipHandover`.
    function completeOwnershipHandover(address newOwner) public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.completeOwnershipHandover(newOwner);
    }

    /// @dev See `requestOwnershipHandover`.
    function grantRoles(address user, uint256 roles) public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.grantRoles(user, roles);
    }

    /// @dev See `requestOwnershipHandover`.
    function revokeRoles(address user, uint256 roles) public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.revokeRoles(user, roles);
    }

    /// @dev See `requestOwnershipHandover`.
    function renounceRoles(uint256 roles) public payable override {
        if (msg.value != 0) revert NoValueAccepted();
        super.renounceRoles(roles);
    }

    /*//////////////////////////////////////////////////////////////
                                 VIEWS
    //////////////////////////////////////////////////////////////*/

    function isJailed(uint256 gvcId) public view returns (bool) {
        return _slotOf[gvcId] != 0;
    }

    /// @notice Whether `gvcId` was ever credited; if so it is never credited again, so the signer's
    ///         trade-in nonce `gvcId` is spent at most once (P2-3).
    function everCredited(uint256 gvcId) external view returns (bool) {
        return depositorOf[gvcId] != address(0);
    }

    function jailedCount() external view returns (uint256) {
        return jailed.length;
    }

    function jailedIds() external view returns (uint256[] memory) {
        return jailed;
    }

    /// @notice Random exchanges committed and not yet settled.
    function pendingCount() external view returns (uint256) {
        return _pendingIds.length;
    }

    /// @notice The commit ids awaiting settlement, so a keeper scans these and not every id ever.
    function pendingCommitIds() external view returns (uint256[] memory) {
        return _pendingIds;
    }

    /// @notice A pending exchange's committer, entropy block, pool size and GVC.
    function pendingExchange(uint256 commitId)
        external
        view
        returns (address account, uint64 entropyBlock, uint32 poolSize, uint256 gvcId)
    {
        PendingExchange memory p = _pending[commitId];
        return (p.account, p.entropyBlock, p.poolSize, p.gvcId);
    }

    /// @notice Whether a commitment's drawn slot has changed hands at or after its commit, so
    ///         `revealExchange` refuses it and `voidExchange` settles it. False while the entropy
    ///         block is unmined or its hash is out of reach.
    function drawnSlotMoved(uint256 commitId) external view returns (bool) {
        PendingExchange memory p = _pending[commitId];
        if (p.account == address(0)) return false;
        return _drawnSlotMoved(p, commitId);
    }

    /// @notice The `jailed` index a random exchange draws from its entropy block's hash.
    function drawIndex(bytes32 entropy, uint256 commitId, uint256 poolSize) public pure returns (uint256) {
        return uint256(keccak256(abi.encode(entropy, commitId))) % poolSize;
    }

    /// @notice The snapshot leaf of `holder` with `allowance`: the solidity-kit MerkleAllowlist
    ///         format, so the kit's generate-merkle-root script builds `allowanceRoot`.
    function allowanceLeaf(address holder, uint256 allowance) public pure returns (bytes32) {
        return keccak256(bytes.concat(keccak256(abi.encode(holder, allowance))));
    }

    /*//////////////////////////////////////////////////////////////
                                INTERNAL
    //////////////////////////////////////////////////////////////*/

    /// @dev Takes custody before it books it: a `Jailed` the signer turns into a voucher only ever
    ///      follows a GVC that is already in the Chamber.
    function _pullAndJail(uint256[] calldata ids, uint256 limit) internal {
        _admit(msg.sender, ids.length, limit);
        for (uint256 i; i < ids.length; ++i) {
            uint256 id = ids[i];
            _requireJailable(id);
            gvc.transferFrom(msg.sender, address(this), id);
            _recordJail(msg.sender, msg.sender, id);
        }
    }

    function _requireDepositsOpen() internal view {
        if (!depositsOpen) revert DepositsNotOpen();
    }

    /// @dev Reverts unless `count` more GVCs may be put in by `sender` now. The cap counts the
    ///      sender (`depositedBy`), never a recipient the sender names, so a fresh recipient per
    ///      GVC cannot dodge it. The entry points check the pause and `_requireDepositsOpen`.
    function _admit(address sender, uint256 count, uint256 limit) internal view {
        if (count == 0) revert NoIds();
        uint256 room = maxDeposits - jailed.length;
        if (count > room) revert ChamberFull(room);
        if (depositedBy[sender] + count > limit) revert HolderLimitExceeded(sender, limit);
    }

    /// @dev A GVC is credited once ever, is not already in the pool, and is not held in escrow by a
    ///      commitment (a list 2 operator could otherwise self-transfer an escrowed GVC into the
    ///      hook and book it twice).
    function _requireJailable(uint256 id) internal view {
        if (depositorOf[id] != address(0)) revert AlreadyCredited(id);
        if (_slotOf[id] != 0) revert AlreadyJailed(id);
        if (pendingCommitOf[id] != 0) revert AlreadyCommitted(id);
    }

    /// @dev `sender` is who put the GVC in (the cap counter); `creditTo` receives the credit.
    function _recordJail(address sender, address creditTo, uint256 id) internal {
        jailed.push(id);
        _slotOf[id] = jailed.length;
        depositorOf[id] = creditTo;
        ++depositedBy[sender];
        ++creditedBy[creditTo];
        emit Jailed(id, creditTo, creditsPerGvc);
    }

    function _trackPending(uint256 commitId) internal {
        _pendingIds.push(commitId);
        _pendingSlotOf[commitId] = _pendingIds.length;
    }

    /// @dev Drop a settled commitment: its storage, its place in `_pendingIds`, its GVC's marker,
    ///      and its escrowed fee.
    function _clearPending(uint256 commitId, PendingExchange memory p) internal {
        delete _pending[commitId];
        delete pendingCommitOf[p.gvcId];
        escrowedFees -= p.fee;

        uint256 slot = _pendingSlotOf[commitId];
        uint256 last = _pendingIds.length;
        if (slot != last) {
            uint256 moved = _pendingIds[last - 1];
            _pendingIds[slot - 1] = moved;
            _pendingSlotOf[moved] = slot;
        }
        _pendingIds.pop();
        delete _pendingSlotOf[commitId];
    }

    /// @dev A draw cannot settle when its drawn slot cannot (`_slotUnusable`) or when the GVC the
    ///      committer escrowed is no longer in the Chamber (a list-2 operator moved it out of band): a
    ///      reveal would install a GVC the Chamber does not hold into the pool. Both void the draw.
    function _drawnSlotMoved(PendingExchange memory p, uint256 commitId) internal view returns (bool) {
        bytes32 entropy = blockhash(p.entropyBlock);
        if (entropy == bytes32(0)) return false;
        return _slotUnusable(drawIndex(entropy, commitId, p.poolSize), p.commitBlock) || !_held(p.gvcId);
    }

    /// @dev A drawn slot cannot settle a commitment when it was rewritten at or after the commit
    ///      (someone else's exchange or reveal took the prize the commit was betting on), or when
    ///      the GVC it names is no longer held by the Chamber (GVC's list 2 moved it out of band;
    ///      nothing here can hand it over). The committer is refunded either way.
    function _slotUnusable(uint256 index, uint64 commitBlock) internal view returns (bool) {
        if (_slotWrittenAt[index] >= commitBlock) return true;
        return !_held(jailed[index]);
    }

    /// @dev Whether the Chamber holds GVC `id` right now.
    function _held(uint256 id) internal view returns (bool) {
        try gvc.ownerOf(id) returns (address holder) {
            return holder == address(this);
        } catch {
            return false;
        }
    }

    /// @dev Send a settled commitment's escrowed GVC back, unless it already left the Chamber out of
    ///      band: a missing GVC may cost its owner the return, never the settlement, so a commitment
    ///      always clears and its pending slot and fee do not stay locked.
    function _returnEscrowed(uint256 commitId, PendingExchange memory p) internal {
        if (_held(p.gvcId)) {
            gvc.transferFrom(address(this), p.account, p.gvcId);
        } else {
            emit EscrowedGvcMissing(commitId, p.account, p.gvcId);
        }
    }

    /// @dev Reverts when `index` is the drawn slot of a commitment whose entropy hash is already
    ///      public and which has not settled, so a searcher cannot buy a prize it can see (C-03). A
    ///      commitment that is already void (its slot was rewritten, or a GVC it needs left the
    ///      Chamber) reserves nothing and is not counted. A live draw reserves exactly one slot, and
    ///      two live draws on the same slot reserve it once, so the reservation counts DISTINCT
    ///      drawn slots (a bit-field, one bit per slot) and yields only once they number the whole
    ///      jail (`distinct == jailed.length`), the one case in which every slot is reserved. While
    ///      `distinct < jailed.length` at least one jailed slot is unreserved, so the exit is never
    ///      fully reserved, and colliding draws never open the reservation with a slot still free.
    ///      The jail size counts every slot, including one whose GVC left the Chamber out of band
    ///      (nothing reserves that slot and nothing can buy it), so such a slot postpones the yield
    ///      (docs/chamber.md). The loop is bounded by `MAX_PENDING_EXCHANGES`, which also bounds the
    ///      bit-field: when the jail is larger than the pending draws the yield cannot happen, so
    ///      only a draw drawn on `index` is checked for liveness and the first live one reverts at
    ///      once; otherwise `jailed.length <= _pendingIds.length <= 64`, so every drawn slot is a
    ///      bit below 64.
    function _requireNotDrawn(uint256 index) internal view {
        uint256 count = _pendingIds.length;
        uint256 poolNow = jailed.length;
        bool canYield = poolNow <= count;
        uint256 reserved;
        uint256 distinct;
        uint256 reservedBy;
        for (uint256 i; i < count; ++i) {
            uint256 commitId = _pendingIds[i];
            PendingExchange storage p = _pending[commitId];
            uint256 entropyBlock = p.entropyBlock;
            if (block.number <= entropyBlock || block.number > entropyBlock + REVEAL_WINDOW) continue;
            bytes32 entropy = blockhash(entropyBlock);
            if (entropy == bytes32(0)) continue;
            uint256 drawn = drawIndex(entropy, commitId, p.poolSize);
            if (!canYield && drawn != index) continue;
            if (_slotUnusable(drawn, p.commitBlock) || !_held(p.gvcId)) continue;
            if (!canYield) revert DrawnSlotReserved(commitId);
            uint256 bit = 1 << drawn;
            if (reserved & bit == 0) {
                reserved |= bit;
                if (++distinct == poolNow) return;
            }
            if (reservedBy == 0 && drawn == index) reservedBy = commitId;
        }
        if (reservedBy != 0) revert DrawnSlotReserved(reservedBy);
    }

    /// @dev The per-sender limit without a snapshot root.
    function _flatLimit() internal view returns (uint256) {
        return maxPerHolder == 0 ? type(uint256).max : maxPerHolder;
    }

    /// @dev The per-sender limit under the snapshot root: the proven allowance, capped by `maxPerHolder`.
    function _provenLimit(address holder, uint256 allowance, bytes32[] memory proof) internal view returns (uint256) {
        if (allowanceRoot == bytes32(0)) revert AllowanceRootNotSet();
        if (!MerkleProofLib.verify(proof, allowanceRoot, allowanceLeaf(holder, allowance))) {
            revert InvalidAllowanceProof();
        }
        return maxPerHolder != 0 && maxPerHolder < allowance ? maxPerHolder : allowance;
    }

    /// @dev Books a settled fee for `feeRecipient`. Nothing is sent: no exit depends on what the
    ///      recipient's code does, and `claimFees` pays the bucket out on its own.
    function _accrueFee(uint256 fee) internal {
        accruedFees += fee;
    }

    /// @dev Returns a voided draw's fee to its committer with a bounded-gas push; a committer that
    ///      cannot take it (no `receive`, a reverting or gas-hungry one) has it booked in
    ///      `refundOwed` for `claimRefund`, so the void itself can never revert on the refund.
    function _refund(address account, uint256 fee) internal {
        // forge-lint: disable-next-line(arbitrary-send-eth)
        if (SafeTransferLib.trySafeTransferETH(account, fee, REFUND_GAS)) return;
        refundOwed[account] += fee;
        refundsOwed += fee;
        emit RefundOwed(account, fee);
    }
}

lib/solidity-kit/lib/solady/src/auth/Ownable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

lib/solidity-kit/lib/solady/src/auth/OwnableRoles.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

/// @notice Simple single owner and multiroles authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/OwnableRoles.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract OwnableRoles is Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The `user`'s roles is updated to `roles`.
    /// Each bit of `roles` represents whether the role is set.
    event RolesUpdated(address indexed user, uint256 indexed roles);

    /// @dev `keccak256(bytes("RolesUpdated(address,uint256)"))`.
    uint256 private constant _ROLES_UPDATED_EVENT_SIGNATURE =
        0x715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe26;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The role slot of `user` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _ROLE_SLOT_SEED))
    ///     let roleSlot := keccak256(0x00, 0x20)
    /// ```
    /// This automatically ignores the upper bits of the `user` in case
    /// they are not clean, as well as keep the `keccak256` under 32-bytes.
    ///
    /// Note: This is equivalent to `uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))`.
    uint256 private constant _ROLE_SLOT_SEED = 0x8b78c6d8;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Overwrite the roles directly without authorization guard.
    function _setRoles(address user, uint256 roles) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            // Store the new value.
            sstore(keccak256(0x0c, 0x20), roles)
            // Emit the {RolesUpdated} event.
            log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), roles)
        }
    }

    /// @dev Updates the roles directly without authorization guard.
    /// If `on` is true, each set bit of `roles` will be turned on,
    /// otherwise, each set bit of `roles` will be turned off.
    function _updateRoles(address user, uint256 roles, bool on) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            let roleSlot := keccak256(0x0c, 0x20)
            // Load the current value.
            let current := sload(roleSlot)
            // Compute the updated roles if `on` is true.
            let updated := or(current, roles)
            // Compute the updated roles if `on` is false.
            // Use `and` to compute the intersection of `current` and `roles`,
            // `xor` it with `current` to flip the bits in the intersection.
            if iszero(on) { updated := xor(current, and(current, roles)) }
            // Then, store the new value.
            sstore(roleSlot, updated)
            // Emit the {RolesUpdated} event.
            log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), updated)
        }
    }

    /// @dev Grants the roles directly without authorization guard.
    /// Each bit of `roles` represents the role to turn on.
    function _grantRoles(address user, uint256 roles) internal virtual {
        _updateRoles(user, roles, true);
    }

    /// @dev Removes the roles directly without authorization guard.
    /// Each bit of `roles` represents the role to turn off.
    function _removeRoles(address user, uint256 roles) internal virtual {
        _updateRoles(user, roles, false);
    }

    /// @dev Throws if the sender does not have any of the `roles`.
    function _checkRoles(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, caller())
            // Load the stored value, and if the `and` intersection
            // of the value and `roles` is zero, revert.
            if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Throws if the sender is not the owner,
    /// and does not have any of the `roles`.
    /// Checks for ownership first, then lazily checks for roles.
    function _checkOwnerOrRoles(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner.
            // Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
            if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
                // Compute the role slot.
                mstore(0x0c, _ROLE_SLOT_SEED)
                mstore(0x00, caller())
                // Load the stored value, and if the `and` intersection
                // of the value and `roles` is zero, revert.
                if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Throws if the sender does not have any of the `roles`,
    /// and is not the owner.
    /// Checks for roles first, then lazily checks for ownership.
    function _checkRolesOrOwner(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, caller())
            // Load the stored value, and if the `and` intersection
            // of the value and `roles` is zero, revert.
            if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                // If the caller is not the stored owner.
                // Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
                if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Convenience function to return a `roles` bitmap from an array of `ordinals`.
    /// This is meant for frontends like Etherscan, and is therefore not fully optimized.
    /// Not recommended to be called on-chain.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _rolesFromOrdinals(uint8[] memory ordinals) internal pure returns (uint256 roles) {
        /// @solidity memory-safe-assembly
        assembly {
            for { let i := shl(5, mload(ordinals)) } i { i := sub(i, 0x20) } {
                // We don't need to mask the values of `ordinals`, as Solidity
                // cleans dirty upper bits when storing variables into memory.
                roles := or(shl(mload(add(ordinals, i)), 1), roles)
            }
        }
    }

    /// @dev Convenience function to return an array of `ordinals` from the `roles` bitmap.
    /// This is meant for frontends like Etherscan, and is therefore not fully optimized.
    /// Not recommended to be called on-chain.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ordinalsFromRoles(uint256 roles) internal pure returns (uint8[] memory ordinals) {
        /// @solidity memory-safe-assembly
        assembly {
            // Grab the pointer to the free memory.
            ordinals := mload(0x40)
            let ptr := add(ordinals, 0x20)
            let o := 0
            // The absence of lookup tables, De Bruijn, etc., here is intentional for
            // smaller bytecode, as this function is not meant to be called on-chain.
            for { let t := roles } 1 {} {
                mstore(ptr, o)
                // `shr` 5 is equivalent to multiplying by 0x20.
                // Push back into the ordinals array if the bit is set.
                ptr := add(ptr, shl(5, and(t, 1)))
                o := add(o, 1)
                t := shr(o, roles)
                if iszero(t) { break }
            }
            // Store the length of `ordinals`.
            mstore(ordinals, shr(5, sub(ptr, add(ordinals, 0x20))))
            // Allocate the memory.
            mstore(0x40, ptr)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to grant `user` `roles`.
    /// If the `user` already has a role, then it will be an no-op for the role.
    function grantRoles(address user, uint256 roles) public payable virtual onlyOwner {
        _grantRoles(user, roles);
    }

    /// @dev Allows the owner to remove `user` `roles`.
    /// If the `user` does not have a role, then it will be an no-op for the role.
    function revokeRoles(address user, uint256 roles) public payable virtual onlyOwner {
        _removeRoles(user, roles);
    }

    /// @dev Allow the caller to remove their own roles.
    /// If the caller does not have a role, then it will be an no-op for the role.
    function renounceRoles(uint256 roles) public payable virtual {
        _removeRoles(msg.sender, roles);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the roles of `user`.
    function rolesOf(address user) public view virtual returns (uint256 roles) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            // Load the stored value.
            roles := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns whether `user` has any of `roles`.
    function hasAnyRole(address user, uint256 roles) public view virtual returns (bool) {
        return rolesOf(user) & roles != 0;
    }

    /// @dev Returns whether `user` has all of `roles`.
    function hasAllRoles(address user, uint256 roles) public view virtual returns (bool) {
        return rolesOf(user) & roles == roles;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by an account with `roles`.
    modifier onlyRoles(uint256 roles) virtual {
        _checkRoles(roles);
        _;
    }

    /// @dev Marks a function as only callable by the owner or by an account
    /// with `roles`. Checks for ownership first, then lazily checks for roles.
    modifier onlyOwnerOrRoles(uint256 roles) virtual {
        _checkOwnerOrRoles(roles);
        _;
    }

    /// @dev Marks a function as only callable by an account with `roles`
    /// or the owner. Checks for roles first, then lazily checks for ownership.
    modifier onlyRolesOrOwner(uint256 roles) virtual {
        _checkRolesOrOwner(roles);
        _;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ROLE CONSTANTS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // IYKYK

    uint256 internal constant _ROLE_0 = 1 << 0;
    uint256 internal constant _ROLE_1 = 1 << 1;
    uint256 internal constant _ROLE_2 = 1 << 2;
    uint256 internal constant _ROLE_3 = 1 << 3;
    uint256 internal constant _ROLE_4 = 1 << 4;
    uint256 internal constant _ROLE_5 = 1 << 5;
    uint256 internal constant _ROLE_6 = 1 << 6;
    uint256 internal constant _ROLE_7 = 1 << 7;
    uint256 internal constant _ROLE_8 = 1 << 8;
    uint256 internal constant _ROLE_9 = 1 << 9;
    uint256 internal constant _ROLE_10 = 1 << 10;
    uint256 internal constant _ROLE_11 = 1 << 11;
    uint256 internal constant _ROLE_12 = 1 << 12;
    uint256 internal constant _ROLE_13 = 1 << 13;
    uint256 internal constant _ROLE_14 = 1 << 14;
    uint256 internal constant _ROLE_15 = 1 << 15;
    uint256 internal constant _ROLE_16 = 1 << 16;
    uint256 internal constant _ROLE_17 = 1 << 17;
    uint256 internal constant _ROLE_18 = 1 << 18;
    uint256 internal constant _ROLE_19 = 1 << 19;
    uint256 internal constant _ROLE_20 = 1 << 20;
    uint256 internal constant _ROLE_21 = 1 << 21;
    uint256 internal constant _ROLE_22 = 1 << 22;
    uint256 internal constant _ROLE_23 = 1 << 23;
    uint256 internal constant _ROLE_24 = 1 << 24;
    uint256 internal constant _ROLE_25 = 1 << 25;
    uint256 internal constant _ROLE_26 = 1 << 26;
    uint256 internal constant _ROLE_27 = 1 << 27;
    uint256 internal constant _ROLE_28 = 1 << 28;
    uint256 internal constant _ROLE_29 = 1 << 29;
    uint256 internal constant _ROLE_30 = 1 << 30;
    uint256 internal constant _ROLE_31 = 1 << 31;
    uint256 internal constant _ROLE_32 = 1 << 32;
    uint256 internal constant _ROLE_33 = 1 << 33;
    uint256 internal constant _ROLE_34 = 1 << 34;
    uint256 internal constant _ROLE_35 = 1 << 35;
    uint256 internal constant _ROLE_36 = 1 << 36;
    uint256 internal constant _ROLE_37 = 1 << 37;
    uint256 internal constant _ROLE_38 = 1 << 38;
    uint256 internal constant _ROLE_39 = 1 << 39;
    uint256 internal constant _ROLE_40 = 1 << 40;
    uint256 internal constant _ROLE_41 = 1 << 41;
    uint256 internal constant _ROLE_42 = 1 << 42;
    uint256 internal constant _ROLE_43 = 1 << 43;
    uint256 internal constant _ROLE_44 = 1 << 44;
    uint256 internal constant _ROLE_45 = 1 << 45;
    uint256 internal constant _ROLE_46 = 1 << 46;
    uint256 internal constant _ROLE_47 = 1 << 47;
    uint256 internal constant _ROLE_48 = 1 << 48;
    uint256 internal constant _ROLE_49 = 1 << 49;
    uint256 internal constant _ROLE_50 = 1 << 50;
    uint256 internal constant _ROLE_51 = 1 << 51;
    uint256 internal constant _ROLE_52 = 1 << 52;
    uint256 internal constant _ROLE_53 = 1 << 53;
    uint256 internal constant _ROLE_54 = 1 << 54;
    uint256 internal constant _ROLE_55 = 1 << 55;
    uint256 internal constant _ROLE_56 = 1 << 56;
    uint256 internal constant _ROLE_57 = 1 << 57;
    uint256 internal constant _ROLE_58 = 1 << 58;
    uint256 internal constant _ROLE_59 = 1 << 59;
    uint256 internal constant _ROLE_60 = 1 << 60;
    uint256 internal constant _ROLE_61 = 1 << 61;
    uint256 internal constant _ROLE_62 = 1 << 62;
    uint256 internal constant _ROLE_63 = 1 << 63;
    uint256 internal constant _ROLE_64 = 1 << 64;
    uint256 internal constant _ROLE_65 = 1 << 65;
    uint256 internal constant _ROLE_66 = 1 << 66;
    uint256 internal constant _ROLE_67 = 1 << 67;
    uint256 internal constant _ROLE_68 = 1 << 68;
    uint256 internal constant _ROLE_69 = 1 << 69;
    uint256 internal constant _ROLE_70 = 1 << 70;
    uint256 internal constant _ROLE_71 = 1 << 71;
    uint256 internal constant _ROLE_72 = 1 << 72;
    uint256 internal constant _ROLE_73 = 1 << 73;
    uint256 internal constant _ROLE_74 = 1 << 74;
    uint256 internal constant _ROLE_75 = 1 << 75;
    uint256 internal constant _ROLE_76 = 1 << 76;
    uint256 internal constant _ROLE_77 = 1 << 77;
    uint256 internal constant _ROLE_78 = 1 << 78;
    uint256 internal constant _ROLE_79 = 1 << 79;
    uint256 internal constant _ROLE_80 = 1 << 80;
    uint256 internal constant _ROLE_81 = 1 << 81;
    uint256 internal constant _ROLE_82 = 1 << 82;
    uint256 internal constant _ROLE_83 = 1 << 83;
    uint256 internal constant _ROLE_84 = 1 << 84;
    uint256 internal constant _ROLE_85 = 1 << 85;
    uint256 internal constant _ROLE_86 = 1 << 86;
    uint256 internal constant _ROLE_87 = 1 << 87;
    uint256 internal constant _ROLE_88 = 1 << 88;
    uint256 internal constant _ROLE_89 = 1 << 89;
    uint256 internal constant _ROLE_90 = 1 << 90;
    uint256 internal constant _ROLE_91 = 1 << 91;
    uint256 internal constant _ROLE_92 = 1 << 92;
    uint256 internal constant _ROLE_93 = 1 << 93;
    uint256 internal constant _ROLE_94 = 1 << 94;
    uint256 internal constant _ROLE_95 = 1 << 95;
    uint256 internal constant _ROLE_96 = 1 << 96;
    uint256 internal constant _ROLE_97 = 1 << 97;
    uint256 internal constant _ROLE_98 = 1 << 98;
    uint256 internal constant _ROLE_99 = 1 << 99;
    uint256 internal constant _ROLE_100 = 1 << 100;
    uint256 internal constant _ROLE_101 = 1 << 101;
    uint256 internal constant _ROLE_102 = 1 << 102;
    uint256 internal constant _ROLE_103 = 1 << 103;
    uint256 internal constant _ROLE_104 = 1 << 104;
    uint256 internal constant _ROLE_105 = 1 << 105;
    uint256 internal constant _ROLE_106 = 1 << 106;
    uint256 internal constant _ROLE_107 = 1 << 107;
    uint256 internal constant _ROLE_108 = 1 << 108;
    uint256 internal constant _ROLE_109 = 1 << 109;
    uint256 internal constant _ROLE_110 = 1 << 110;
    uint256 internal constant _ROLE_111 = 1 << 111;
    uint256 internal constant _ROLE_112 = 1 << 112;
    uint256 internal constant _ROLE_113 = 1 << 113;
    uint256 internal constant _ROLE_114 = 1 << 114;
    uint256 internal constant _ROLE_115 = 1 << 115;
    uint256 internal constant _ROLE_116 = 1 << 116;
    uint256 internal constant _ROLE_117 = 1 << 117;
    uint256 internal constant _ROLE_118 = 1 << 118;
    uint256 internal constant _ROLE_119 = 1 << 119;
    uint256 internal constant _ROLE_120 = 1 << 120;
    uint256 internal constant _ROLE_121 = 1 << 121;
    uint256 internal constant _ROLE_122 = 1 << 122;
    uint256 internal constant _ROLE_123 = 1 << 123;
    uint256 internal constant _ROLE_124 = 1 << 124;
    uint256 internal constant _ROLE_125 = 1 << 125;
    uint256 internal constant _ROLE_126 = 1 << 126;
    uint256 internal constant _ROLE_127 = 1 << 127;
    uint256 internal constant _ROLE_128 = 1 << 128;
    uint256 internal constant _ROLE_129 = 1 << 129;
    uint256 internal constant _ROLE_130 = 1 << 130;
    uint256 internal constant _ROLE_131 = 1 << 131;
    uint256 internal constant _ROLE_132 = 1 << 132;
    uint256 internal constant _ROLE_133 = 1 << 133;
    uint256 internal constant _ROLE_134 = 1 << 134;
    uint256 internal constant _ROLE_135 = 1 << 135;
    uint256 internal constant _ROLE_136 = 1 << 136;
    uint256 internal constant _ROLE_137 = 1 << 137;
    uint256 internal constant _ROLE_138 = 1 << 138;
    uint256 internal constant _ROLE_139 = 1 << 139;
    uint256 internal constant _ROLE_140 = 1 << 140;
    uint256 internal constant _ROLE_141 = 1 << 141;
    uint256 internal constant _ROLE_142 = 1 << 142;
    uint256 internal constant _ROLE_143 = 1 << 143;
    uint256 internal constant _ROLE_144 = 1 << 144;
    uint256 internal constant _ROLE_145 = 1 << 145;
    uint256 internal constant _ROLE_146 = 1 << 146;
    uint256 internal constant _ROLE_147 = 1 << 147;
    uint256 internal constant _ROLE_148 = 1 << 148;
    uint256 internal constant _ROLE_149 = 1 << 149;
    uint256 internal constant _ROLE_150 = 1 << 150;
    uint256 internal constant _ROLE_151 = 1 << 151;
    uint256 internal constant _ROLE_152 = 1 << 152;
    uint256 internal constant _ROLE_153 = 1 << 153;
    uint256 internal constant _ROLE_154 = 1 << 154;
    uint256 internal constant _ROLE_155 = 1 << 155;
    uint256 internal constant _ROLE_156 = 1 << 156;
    uint256 internal constant _ROLE_157 = 1 << 157;
    uint256 internal constant _ROLE_158 = 1 << 158;
    uint256 internal constant _ROLE_159 = 1 << 159;
    uint256 internal constant _ROLE_160 = 1 << 160;
    uint256 internal constant _ROLE_161 = 1 << 161;
    uint256 internal constant _ROLE_162 = 1 << 162;
    uint256 internal constant _ROLE_163 = 1 << 163;
    uint256 internal constant _ROLE_164 = 1 << 164;
    uint256 internal constant _ROLE_165 = 1 << 165;
    uint256 internal constant _ROLE_166 = 1 << 166;
    uint256 internal constant _ROLE_167 = 1 << 167;
    uint256 internal constant _ROLE_168 = 1 << 168;
    uint256 internal constant _ROLE_169 = 1 << 169;
    uint256 internal constant _ROLE_170 = 1 << 170;
    uint256 internal constant _ROLE_171 = 1 << 171;
    uint256 internal constant _ROLE_172 = 1 << 172;
    uint256 internal constant _ROLE_173 = 1 << 173;
    uint256 internal constant _ROLE_174 = 1 << 174;
    uint256 internal constant _ROLE_175 = 1 << 175;
    uint256 internal constant _ROLE_176 = 1 << 176;
    uint256 internal constant _ROLE_177 = 1 << 177;
    uint256 internal constant _ROLE_178 = 1 << 178;
    uint256 internal constant _ROLE_179 = 1 << 179;
    uint256 internal constant _ROLE_180 = 1 << 180;
    uint256 internal constant _ROLE_181 = 1 << 181;
    uint256 internal constant _ROLE_182 = 1 << 182;
    uint256 internal constant _ROLE_183 = 1 << 183;
    uint256 internal constant _ROLE_184 = 1 << 184;
    uint256 internal constant _ROLE_185 = 1 << 185;
    uint256 internal constant _ROLE_186 = 1 << 186;
    uint256 internal constant _ROLE_187 = 1 << 187;
    uint256 internal constant _ROLE_188 = 1 << 188;
    uint256 internal constant _ROLE_189 = 1 << 189;
    uint256 internal constant _ROLE_190 = 1 << 190;
    uint256 internal constant _ROLE_191 = 1 << 191;
    uint256 internal constant _ROLE_192 = 1 << 192;
    uint256 internal constant _ROLE_193 = 1 << 193;
    uint256 internal constant _ROLE_194 = 1 << 194;
    uint256 internal constant _ROLE_195 = 1 << 195;
    uint256 internal constant _ROLE_196 = 1 << 196;
    uint256 internal constant _ROLE_197 = 1 << 197;
    uint256 internal constant _ROLE_198 = 1 << 198;
    uint256 internal constant _ROLE_199 = 1 << 199;
    uint256 internal constant _ROLE_200 = 1 << 200;
    uint256 internal constant _ROLE_201 = 1 << 201;
    uint256 internal constant _ROLE_202 = 1 << 202;
    uint256 internal constant _ROLE_203 = 1 << 203;
    uint256 internal constant _ROLE_204 = 1 << 204;
    uint256 internal constant _ROLE_205 = 1 << 205;
    uint256 internal constant _ROLE_206 = 1 << 206;
    uint256 internal constant _ROLE_207 = 1 << 207;
    uint256 internal constant _ROLE_208 = 1 << 208;
    uint256 internal constant _ROLE_209 = 1 << 209;
    uint256 internal constant _ROLE_210 = 1 << 210;
    uint256 internal constant _ROLE_211 = 1 << 211;
    uint256 internal constant _ROLE_212 = 1 << 212;
    uint256 internal constant _ROLE_213 = 1 << 213;
    uint256 internal constant _ROLE_214 = 1 << 214;
    uint256 internal constant _ROLE_215 = 1 << 215;
    uint256 internal constant _ROLE_216 = 1 << 216;
    uint256 internal constant _ROLE_217 = 1 << 217;
    uint256 internal constant _ROLE_218 = 1 << 218;
    uint256 internal constant _ROLE_219 = 1 << 219;
    uint256 internal constant _ROLE_220 = 1 << 220;
    uint256 internal constant _ROLE_221 = 1 << 221;
    uint256 internal constant _ROLE_222 = 1 << 222;
    uint256 internal constant _ROLE_223 = 1 << 223;
    uint256 internal constant _ROLE_224 = 1 << 224;
    uint256 internal constant _ROLE_225 = 1 << 225;
    uint256 internal constant _ROLE_226 = 1 << 226;
    uint256 internal constant _ROLE_227 = 1 << 227;
    uint256 internal constant _ROLE_228 = 1 << 228;
    uint256 internal constant _ROLE_229 = 1 << 229;
    uint256 internal constant _ROLE_230 = 1 << 230;
    uint256 internal constant _ROLE_231 = 1 << 231;
    uint256 internal constant _ROLE_232 = 1 << 232;
    uint256 internal constant _ROLE_233 = 1 << 233;
    uint256 internal constant _ROLE_234 = 1 << 234;
    uint256 internal constant _ROLE_235 = 1 << 235;
    uint256 internal constant _ROLE_236 = 1 << 236;
    uint256 internal constant _ROLE_237 = 1 << 237;
    uint256 internal constant _ROLE_238 = 1 << 238;
    uint256 internal constant _ROLE_239 = 1 << 239;
    uint256 internal constant _ROLE_240 = 1 << 240;
    uint256 internal constant _ROLE_241 = 1 << 241;
    uint256 internal constant _ROLE_242 = 1 << 242;
    uint256 internal constant _ROLE_243 = 1 << 243;
    uint256 internal constant _ROLE_244 = 1 << 244;
    uint256 internal constant _ROLE_245 = 1 << 245;
    uint256 internal constant _ROLE_246 = 1 << 246;
    uint256 internal constant _ROLE_247 = 1 << 247;
    uint256 internal constant _ROLE_248 = 1 << 248;
    uint256 internal constant _ROLE_249 = 1 << 249;
    uint256 internal constant _ROLE_250 = 1 << 250;
    uint256 internal constant _ROLE_251 = 1 << 251;
    uint256 internal constant _ROLE_252 = 1 << 252;
    uint256 internal constant _ROLE_253 = 1 << 253;
    uint256 internal constant _ROLE_254 = 1 << 254;
    uint256 internal constant _ROLE_255 = 1 << 255;
}

lib/solidity-kit/lib/solady/src/utils/MerkleProofLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
library MerkleProofLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*            MERKLE PROOF VERIFICATION OPERATIONS            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf)
        internal
        pure
        returns (bool isValid)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if mload(proof) {
                // Initialize `offset` to the offset of `proof` elements in memory.
                let offset := add(proof, 0x20)
                // Left shift by 5 is equivalent to multiplying by 0x20.
                let end := add(offset, shl(5, mload(proof)))
                // Iterate over proof elements to compute root hash.
                for {} 1 {} {
                    // Slot of `leaf` in scratch space.
                    // If the condition is true: 0x20, otherwise: 0x00.
                    let scratch := shl(5, gt(leaf, mload(offset)))
                    // Store elements to hash contiguously in scratch space.
                    // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                    mstore(scratch, leaf)
                    mstore(xor(scratch, 0x20), mload(offset))
                    // Reuse `leaf` to store the hash to reduce stack operations.
                    leaf := keccak256(0x00, 0x40)
                    offset := add(offset, 0x20)
                    if iszero(lt(offset, end)) { break }
                }
            }
            isValid := eq(leaf, root)
        }
    }

    /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf)
        internal
        pure
        returns (bool isValid)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if proof.length {
                // Left shift by 5 is equivalent to multiplying by 0x20.
                let end := add(proof.offset, shl(5, proof.length))
                // Initialize `offset` to the offset of `proof` in the calldata.
                let offset := proof.offset
                // Iterate over proof elements to compute root hash.
                for {} 1 {} {
                    // Slot of `leaf` in scratch space.
                    // If the condition is true: 0x20, otherwise: 0x00.
                    let scratch := shl(5, gt(leaf, calldataload(offset)))
                    // Store elements to hash contiguously in scratch space.
                    // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                    mstore(scratch, leaf)
                    mstore(xor(scratch, 0x20), calldataload(offset))
                    // Reuse `leaf` to store the hash to reduce stack operations.
                    leaf := keccak256(0x00, 0x40)
                    offset := add(offset, 0x20)
                    if iszero(lt(offset, end)) { break }
                }
            }
            isValid := eq(leaf, root)
        }
    }

    /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
    /// given `proof` and `flags`.
    ///
    /// Note:
    /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
    ///   will always return false.
    /// - The sum of the lengths of `proof` and `leaves` must never overflow.
    /// - Any non-zero word in the `flags` array is treated as true.
    /// - The memory offset of `proof` must be non-zero
    ///   (i.e. `proof` is not pointing to the scratch space).
    function verifyMultiProof(
        bytes32[] memory proof,
        bytes32 root,
        bytes32[] memory leaves,
        bool[] memory flags
    ) internal pure returns (bool isValid) {
        // Rebuilds the root by consuming and producing values on a queue.
        // The queue starts with the `leaves` array, and goes into a `hashes` array.
        // After the process, the last element on the queue is verified
        // to be equal to the `root`.
        //
        // The `flags` array denotes whether the sibling
        // should be popped from the queue (`flag == true`), or
        // should be popped from the `proof` (`flag == false`).
        /// @solidity memory-safe-assembly
        assembly {
            // Cache the lengths of the arrays.
            let leavesLength := mload(leaves)
            let proofLength := mload(proof)
            let flagsLength := mload(flags)

            // Advance the pointers of the arrays to point to the data.
            leaves := add(0x20, leaves)
            proof := add(0x20, proof)
            flags := add(0x20, flags)

            // If the number of flags is correct.
            for {} eq(add(leavesLength, proofLength), add(flagsLength, 1)) {} {
                // For the case where `proof.length + leaves.length == 1`.
                if iszero(flagsLength) {
                    // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
                    isValid := eq(mload(xor(leaves, mul(xor(proof, leaves), proofLength))), root)
                    break
                }

                // The required final proof offset if `flagsLength` is not zero, otherwise zero.
                let proofEnd := add(proof, shl(5, proofLength))
                // We can use the free memory space for the queue.
                // We don't need to allocate, since the queue is temporary.
                let hashesFront := mload(0x40)
                // Copy the leaves into the hashes.
                // Sometimes, a little memory expansion costs less than branching.
                // Should cost less, even with a high free memory offset of 0x7d00.
                leavesLength := shl(5, leavesLength)
                for { let i := 0 } iszero(eq(i, leavesLength)) { i := add(i, 0x20) } {
                    mstore(add(hashesFront, i), mload(add(leaves, i)))
                }
                // Compute the back of the hashes.
                let hashesBack := add(hashesFront, leavesLength)
                // This is the end of the memory for the queue.
                // We recycle `flagsLength` to save on stack variables (sometimes save gas).
                flagsLength := add(hashesBack, shl(5, flagsLength))

                for {} 1 {} {
                    // Pop from `hashes`.
                    let a := mload(hashesFront)
                    // Pop from `hashes`.
                    let b := mload(add(hashesFront, 0x20))
                    hashesFront := add(hashesFront, 0x40)

                    // If the flag is false, load the next proof,
                    // else, pops from the queue.
                    if iszero(mload(flags)) {
                        // Loads the next proof.
                        b := mload(proof)
                        proof := add(proof, 0x20)
                        // Unpop from `hashes`.
                        hashesFront := sub(hashesFront, 0x20)
                    }

                    // Advance to the next flag.
                    flags := add(flags, 0x20)

                    // Slot of `a` in scratch space.
                    // If the condition is true: 0x20, otherwise: 0x00.
                    let scratch := shl(5, gt(a, b))
                    // Hash the scratch space and push the result onto the queue.
                    mstore(scratch, a)
                    mstore(xor(scratch, 0x20), b)
                    mstore(hashesBack, keccak256(0x00, 0x40))
                    hashesBack := add(hashesBack, 0x20)
                    if iszero(lt(hashesBack, flagsLength)) { break }
                }
                isValid :=
                    and(
                        // Checks if the last value in the queue is same as the root.
                        eq(mload(sub(hashesBack, 0x20)), root),
                        // And whether all the proofs are used, if required.
                        eq(proofEnd, proof)
                    )
                break
            }
        }
    }

    /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
    /// given `proof` and `flags`.
    ///
    /// Note:
    /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
    ///   will always return false.
    /// - Any non-zero word in the `flags` array is treated as true.
    /// - The calldata offset of `proof` must be non-zero
    ///   (i.e. `proof` is from a regular Solidity function with a 4-byte selector).
    function verifyMultiProofCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32[] calldata leaves,
        bool[] calldata flags
    ) internal pure returns (bool isValid) {
        // Rebuilds the root by consuming and producing values on a queue.
        // The queue starts with the `leaves` array, and goes into a `hashes` array.
        // After the process, the last element on the queue is verified
        // to be equal to the `root`.
        //
        // The `flags` array denotes whether the sibling
        // should be popped from the queue (`flag == true`), or
        // should be popped from the `proof` (`flag == false`).
        /// @solidity memory-safe-assembly
        assembly {
            // If the number of flags is correct.
            for {} eq(add(leaves.length, proof.length), add(flags.length, 1)) {} {
                // For the case where `proof.length + leaves.length == 1`.
                if iszero(flags.length) {
                    // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
                    // forgefmt: disable-next-item
                    isValid := eq(
                        calldataload(
                            xor(leaves.offset, mul(xor(proof.offset, leaves.offset), proof.length))
                        ),
                        root
                    )
                    break
                }

                // The required final proof offset if `flagsLength` is not zero, otherwise zero.
                let proofEnd := add(proof.offset, shl(5, proof.length))
                // We can use the free memory space for the queue.
                // We don't need to allocate, since the queue is temporary.
                let hashesFront := mload(0x40)
                // Copy the leaves into the hashes.
                // Sometimes, a little memory expansion costs less than branching.
                // Should cost less, even with a high free memory offset of 0x7d00.
                calldatacopy(hashesFront, leaves.offset, shl(5, leaves.length))
                // Compute the back of the hashes.
                let hashesBack := add(hashesFront, shl(5, leaves.length))
                // This is the end of the memory for the queue.
                // We recycle `flagsLength` to save on stack variables (sometimes save gas).
                flags.length := add(hashesBack, shl(5, flags.length))

                // We don't need to make a copy of `proof.offset` or `flags.offset`,
                // as they are pass-by-value (this trick may not always save gas).

                for {} 1 {} {
                    // Pop from `hashes`.
                    let a := mload(hashesFront)
                    // Pop from `hashes`.
                    let b := mload(add(hashesFront, 0x20))
                    hashesFront := add(hashesFront, 0x40)

                    // If the flag is false, load the next proof,
                    // else, pops from the queue.
                    if iszero(calldataload(flags.offset)) {
                        // Loads the next proof.
                        b := calldataload(proof.offset)
                        proof.offset := add(proof.offset, 0x20)
                        // Unpop from `hashes`.
                        hashesFront := sub(hashesFront, 0x20)
                    }

                    // Advance to the next flag offset.
                    flags.offset := add(flags.offset, 0x20)

                    // Slot of `a` in scratch space.
                    // If the condition is true: 0x20, otherwise: 0x00.
                    let scratch := shl(5, gt(a, b))
                    // Hash the scratch space and push the result onto the queue.
                    mstore(scratch, a)
                    mstore(xor(scratch, 0x20), b)
                    mstore(hashesBack, keccak256(0x00, 0x40))
                    hashesBack := add(hashesBack, 0x20)
                    if iszero(lt(hashesBack, flags.length)) { break }
                }
                isValid :=
                    and(
                        // Checks if the last value in the queue is same as the root.
                        eq(mload(sub(hashesBack, 0x20)), root),
                        // And whether all the proofs are used, if required.
                        eq(proofEnd, proof.offset)
                    )
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   EMPTY CALLDATA HELPERS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns an empty calldata bytes32 array.
    function emptyProof() internal pure returns (bytes32[] calldata proof) {
        /// @solidity memory-safe-assembly
        assembly {
            proof.length := 0
        }
    }

    /// @dev Returns an empty calldata bytes32 array.
    function emptyLeaves() internal pure returns (bytes32[] calldata leaves) {
        /// @solidity memory-safe-assembly
        assembly {
            leaves.length := 0
        }
    }

    /// @dev Returns an empty calldata bool array.
    function emptyFlags() internal pure returns (bool[] calldata flags) {
        /// @solidity memory-safe-assembly
        assembly {
            flags.length := 0
        }
    }
}

lib/solidity-kit/lib/solady/src/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
        }
        _;
    }
}

lib/solidity-kit/lib/solady/src/utils/SafeTransferLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` does not implement `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented :=
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

lib/solidity-kit/src/pause/Pausable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

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

/**
 * @title Pausable
 * @notice Minimal gas-efficient emergency pause mechanism.
 *         Uses uint256 slot to avoid unnecessary conversions and booleans.
 */
abstract contract Pausable is Ownable {
    uint256 private _paused;

    event Paused(address indexed account);
    event Unpaused(address indexed account);

    error ContractPaused();
    error ContractNotPaused();

    modifier whenNotPaused() {
        if (_paused == 1) revert ContractPaused();
        _;
    }

    modifier whenPaused() {
        if (_paused == 0) revert ContractNotPaused();
        _;
    }

    function paused() public view virtual returns (bool) {
        return _paused == 1;
    }

    function pause() external onlyOwner whenNotPaused {
        _pause();
    }

    function unpause() external onlyOwner whenPaused {
        _unpause();
    }

    function _pause() internal virtual whenNotPaused {
        _paused = 1;
        emit Paused(msg.sender);
    }

    function _unpause() internal virtual whenPaused {
        _paused = 0;
        emit Unpaused(msg.sender);
    }
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "solidity-kit/=lib/solidity-kit/src/",
    "solady/=lib/solidity-kit/lib/solady/src/",
    "forge-std/=lib/solidity-kit/lib/forge-std/src/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.