Skip to content
Verified contractPartialMIT

NormiesArenaSkins

Address0x3f298b7b7d5300aab34a22470b8d1d54b8b30a05
Balance

0 ETH

 

Transactions

42

 

Compiler

solc 0.8.33

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.33+commit.64118f21
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
prague
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,421,432
Creation transaction
0x80e9817735…8386a784a8

src/NormiesArenaSkins.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

import { ArenaAccess } from "./arena/ArenaAccess.sol";

/**
 * @title NormiesArenaSkins
 * @author Normies by Serc (https://x.com/serc1n)
 * @author Smart Contract by Yigit Duman (https://x.com/yigitduman)
 * @notice Sells custom skins for Normies in the Arena. Anyone may buy a skin for any Normie that exists. The price
 *         moves from a wallet straight to the treasury, never from a Normie's Arena balance: from the caller's
 *         wallet, or from a wallet that gave the caller a pixel allowance on the ledger. The purchase is recorded
 *         in the storage against the Normie, so it stays with the Normie when it changes hands. The storage emits
 *         SkinPurchased; the skin itself is made and served off chain from that event.
 *
 *         Needs a mover role on the pixel ledger (which also lets it spend allowances) and to be an authorized
 *         writer of the storage.
 */
contract NormiesArenaSkins is ArenaAccess {
    /// @notice The price changed before the purchase landed.
    error PriceChanged(uint256 expected, uint256 current);

    /// @notice Highest settable price, in pixels.
    uint256 public constant MAX_PRICE = 10_000;

    /// @notice Price of one skin, in pixels.
    uint256 public price = 5;
    /// @notice Receiver of skin payments. Set at deployment and changed with setTreasury.
    address public treasury;

    /// @notice The skin price was set to `price`.
    event PriceSet(uint256 price);
    /// @notice The treasury was set to `treasury`.
    event TreasurySet(address indexed treasury);

    /// @param store_    The NormiesArenaStorage to use.
    /// @param admin     The owner.
    /// @param treasury_ The first receiver of skin payments.
    constructor(address store_, address admin, address treasury_) ArenaAccess(store_, admin) {
        require(treasury_ != address(0), InvalidInput());
        treasury = treasury_;
    }

    /**
     * @notice Buy a skin for Normie `id`. Anyone, while running. Reverts with InvalidInput for a Normie that is
     *         burned or out of range, and with PriceChanged when `expectedPrice` is not the current price.
     * @param expectedPrice The price the caller agreed to.
     * @param payer         The wallet that pays: the caller, or a wallet that gave the caller an allowance of at
     *                      least the price on the pixel ledger, which the purchase spends. The ledger requires the
     *                      payer's pixels to be past their cooldown.
     */
    function purchase(uint256 id, uint256 expectedPrice, address payer) external nonReentrant whenRunning {
        uint256 current = price;
        require(expectedPrice == current, PriceChanged(expectedPrice, current));
        require(id < store.ID_BOUND() && !store.isBurned(id) && payer != address(0), InvalidInput());
        if (payer != msg.sender) pixels.useAllowance(payer, msg.sender, current);
        pixels.moveBalance(payer, treasury, current);
        store.recordPurchase(id, msg.sender, current);
    }

    /// @notice Set the skin price, from 1 to MAX_PRICE pixels. Owner only. Purchases quoting another price revert.
    function setPrice(uint256 value) external onlyOwner {
        require(value > 0 && value <= MAX_PRICE, InvalidInput());
        price = value;
        emit PriceSet(value);
    }

    /// @notice Set the receiver of later skin payments. Owner only. Pixels already paid stay with the old treasury.
    function setTreasury(address _treasury) external onlyOwner {
        require(_treasury != address(0), InvalidInput());
        treasury = _treasury;
        emit TreasurySet(_treasury);
    }
}

node_modules/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();
        _;
    }
}

node_modules/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;
}

node_modules/solady/src/utils/Lifebuoy.sol

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

/// @notice Class that allows for rescue of ETH, ERC20, ERC721 tokens.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Lifebuoy.sol)
///
/// @dev This contract is created to mitigate the following disasters:
/// - Careless user sends tokens to the wrong chain or wrong contract.
/// - Careless dev deploys a contract without a withdraw function in attempt to rescue
///   careless user's tokens, due to deployment nonce mismatch caused by
///   script misfire / misconfiguration.
/// - Careless dev forgets to add a withdraw function to a NFT sale contract.
///
/// Note: if you are deploying via a untrusted `tx.origin`,
/// you MUST override `_lifebuoyDefaultDeployer` to return a trusted address.
///
/// For best safety:
/// - For non-escrow contracts, inherit Lifebuoy as much as possible,
///   and leave it unlocked.
/// - For escrow contracts, lock access as tight as possible,
///   as soon as possible. Or simply don't inherit Lifebuoy.
/// Escrow: Your contract is designed to hold ETH, ERC20s, ERC721s
/// (e.g. liquidity pools).
///
/// All rescue and rescue authorization functions require either:
/// - Caller is the deployer
///   AND the contract is not a proxy
///   AND `rescueLocked() & _LIFEBUOY_DEPLOYER_ACCESS_LOCK == 0`.
/// - Caller is `owner()`
///   AND `rescueLocked() & _LIFEBUOY_OWNER_ACCESS_LOCK == 0`.
///
/// The choice of using bit flags to represent locked statuses is for
/// efficiency, flexibility, convenience.
///
/// This contract is optimized with a priority on minimal bytecode size,
/// as the methods are not intended to be called often.
contract Lifebuoy {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to rescue or lock the rescue function.
    error RescueUnauthorizedOrLocked();

    /// @dev The rescue operation has failed due to a failed transfer.
    error RescueTransferFailed();

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

    // These flags are kept internal to avoid bloating up the function dispatch.
    // You can just copy paste this into your own code.

    /// @dev Flag to denote that the deployer's access is locked. (1)
    uint256 internal constant _LIFEBUOY_DEPLOYER_ACCESS_LOCK = 1 << 0;

    /// @dev Flag to denote that the `owner()`'s access is locked. (2)
    uint256 internal constant _LIFEBUOY_OWNER_ACCESS_LOCK = 1 << 1;

    /// @dev Flag to denote that the `lockRescue` function is locked. (4)
    uint256 internal constant _LIFEBUOY_LOCK_RESCUE_LOCK = 1 << 2;

    /// @dev Flag to denote that the `rescueETH` function is locked. (8)
    uint256 internal constant _LIFEBUOY_RESCUE_ETH_LOCK = 1 << 3;

    /// @dev Flag to denote that the `rescueERC20` function is locked. (16)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC20_LOCK = 1 << 4;

    /// @dev Flag to denote that the `rescueERC721` function is locked. (32)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC721_LOCK = 1 << 5;

    /// @dev Flag to denote that the `rescueERC1155` function is locked. (64)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC1155_LOCK = 1 << 6;

    /// @dev Flag to denote that the `rescueERC6909` function is locked. (128)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC6909_LOCK = 1 << 7;

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

    /// @dev For checking that the caller is the deployer and
    /// that the context is not a delegatecall
    /// (so that the implementation deployer cannot drain proxies).
    bytes32 internal immutable _lifebuoyDeployerHash;

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

    /// @dev The rescue locked flags slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_RESCUE_LOCKED_FLAGS_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 _RESCUE_LOCKED_FLAGS_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffb8e2915b;

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

    constructor() payable {
        bytes32 hash;
        uint256 deployer = uint160(_lifebuoyDefaultDeployer());
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, address())
            mstore(0x20, deployer)
            hash := keccak256(0x00, 0x40)
        }
        _lifebuoyDeployerHash = hash;
    }

    /// @dev Returns `tx.origin` by default. Override to return another address if needed.
    ///
    /// Note: If you are deploying via a untrusted `tx.origin` (e.g. ERC4337 bundler)
    /// you MUST override this function to return a trusted address.
    function _lifebuoyDefaultDeployer() internal view virtual returns (address) {
        // I know about EIP7645, and I will stop it if it gets traction.
        // Worse case, I will add an `ecrecover` method. But not today.
        return tx.origin;
    }

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

    /// @dev Sends `amount` (in wei) ETH from the current contract to `to`.
    /// Reverts upon failure.
    function rescueETH(address to, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ETH_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0x7ec62e76) // `RescueTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC20(address token, address to, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC20_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // `RescueTransferFailed()` and `transfer(address,uint256)`.
            mstore(0x00, shl(96, 0x7ec62e76a9059cbb))
            if iszero(call(gas(), token, callvalue(), 0x10, 0x44, codesize(), 0x00)) {
                revert(0x0c, 0x04)
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends `id` of ERC721 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC721(address token, address to, uint256 id)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC721_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, id) // Store the `id` argument.
            mstore(0x40, shr(96, shl(96, to))) // Store the `to` argument.
            mstore(0x20, address()) // Store the `from` argument.
            // `RescueTransferFailed()` and `transferFrom(address,address,uint256)`.
            mstore(0x00, 0x7ec62e7623b872dd)
            if iszero(call(gas(), token, callvalue(), 0x1c, 0x64, codesize(), 0x00)) {
                revert(0x18, 0x04)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of `id` of ERC1155 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC1155(
        address token,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) public payable virtual onlyRescuer(_LIFEBUOY_RESCUE_ERC1155_LOCK) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            // `RescueTransferFailed()` and `safeTransferFrom(address,address,uint256,uint256,bytes)`.
            mstore(m, 0x7ec62e76f242432a)
            mstore(add(0x20, m), address()) // Store the `from` argument.
            mstore(add(0x40, m), shr(96, shl(96, to))) // Store the `to` argument.
            mstore(add(0x60, m), id) // Store the `id` argument.
            mstore(add(0x80, m), amount) // Store the `amount` argument.
            mstore(add(0xa0, m), 0xa0) // Store the offset to `data`.
            mstore(add(0xc0, m), data.length)
            calldatacopy(add(m, 0xe0), data.offset, data.length)
            // forgefmt: disable-next-item
            if iszero(
                call(gas(), token, callvalue(), add(m, 0x1c), add(0xc4, data.length), codesize(), 0x00)
            ) { revert(add(m, 0x18), 0x04) }
        }
    }

    /// @dev Sends `amount` of `id` of ERC6909 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC6909(address token, address to, uint256 id, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC6909_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, id) // Store the `id` argument.
            mstore(0x54, amount) // Store the `amount` argument.
            // `RescueTransferFailed()` and `transfer(address,uint256,uint256)`.
            mstore(0x00, shl(96, 0x7ec62e76095bcdb6))
            if iszero(call(gas(), token, callvalue(), 0x10, 0x64, codesize(), 0x00)) {
                revert(0x0c, 0x04)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              RESCUE AUTHORIZATION OPERATIONS               */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the flags denoting whether access to rescue functions
    /// (including `lockRescue`) is locked.
    function rescueLocked() public view virtual returns (uint256 locks) {
        /// @solidity memory-safe-assembly
        assembly {
            locks := sload(_RESCUE_LOCKED_FLAGS_SLOT)
        }
    }

    /// @dev Locks (i.e. permanently removes) access to rescue functions (including `lockRescue`).
    function lockRescue(uint256 locksToSet)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_LOCK_RESCUE_LOCK)
    {
        _lockRescue(locksToSet);
    }

    /// @dev Internal function to set the lock flags without going through access control.
    function _lockRescue(uint256 locksToSet) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let s := _RESCUE_LOCKED_FLAGS_SLOT
            sstore(s, or(sload(s), locksToSet))
        }
    }

    /// @dev Requires that the rescue function being guarded is:
    /// 1. Not locked, AND
    /// 2. Called by either:
    ///   (a) The `owner()`, OR
    ///   (b) The deployer (if not via a delegate call and deployer is an EOA).
    function _checkRescuer(uint256 modeLock) internal view virtual {
        uint256 locks = rescueLocked();
        bytes32 h = _lifebuoyDeployerHash;
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                // If the `modeLock` flag is true, set all bits in `locks` to true.
                locks := or(sub(0, iszero(iszero(and(modeLock, locks)))), locks)
                // Caller is the deployer
                // AND the contract is not a proxy
                // AND `locks & _LIFEBUOY_DEPLOYER_ACCESS_LOCK` is false.
                mstore(0x20, caller())
                mstore(and(locks, _LIFEBUOY_DEPLOYER_ACCESS_LOCK), address())
                if eq(keccak256(0x00, 0x40), h) { break }
                // If the caller is `owner()`
                // AND `locks & _LIFEBUOY_OWNER_ACCESS_LOCK` is false.
                mstore(0x08, 0x8da5cb5b0a0362e0) // `owner()` and `RescueUnauthorizedOrLocked()`.
                if and( // The arguments of `and` are evaluated from right to left.
                    lt(
                        and(locks, _LIFEBUOY_OWNER_ACCESS_LOCK),
                        and(gt(returndatasize(), 0x1f), eq(mload(0x00), caller()))
                    ),
                    staticcall(gas(), address(), 0x20, 0x04, 0x00, 0x20)
                ) { break }
                revert(0x24, 0x04)
            }
        }
    }

    /// @dev Modifier that calls `_checkRescuer()` at the start of the function.
    modifier onlyRescuer(uint256 modeLock) virtual {
        _checkRescuer(modeLock);
        _;
    }
}

node_modules/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)
            }
        }
        _;
    }
}

src/NormiesAccess.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

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

/**
 * @title NormiesAccess
 * @author Smart Contract by Yigit Duman (https://x.com/yigitduman)
 * @notice Who may do what on the Pixel Market contracts. No single key can do everything:
 *
 *           owner     ADMIN, held by a Safe multisig. Role grants, mover roles, overlay writers, fee recipients,
 *                     withdrawals, pointers to other contracts, ownership. Two-step handover
 *                     (requestOwnershipHandover / completeOwnershipHandover) for later moves.
 *           GUARDIAN  operations, with no delay: pause and unpause, the allowance kill switch, cancelling an epoch
 *                     before its claims open. It can never grant anything or withdraw value, though a long canvas
 *                     pause lowers pending burn rolls.
 *           CONFIG    operating parameters: prices, burn tiers, fees (capped), the listing floor, the claim window
 *                     (with a floor). Burn tiers are read at reveal, so lowering them also lowers burns already
 *                     committed.
 *           POSTER    revenue pool only: postEpoch. A posted epoch opens for claims POST_DELAY later, so a guardian
 *                     can cancel a bad root before it pays anything.
 */
abstract contract NormiesAccess is OwnableRoles {
    uint256 internal constant GUARDIAN_ROLE = _ROLE_0;
    uint256 internal constant CONFIG_ROLE = _ROLE_1;
    uint256 internal constant POSTER_ROLE = _ROLE_2;
}

src/NormiesArenaStorage.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

import { NormiesAccess } from "./NormiesAccess.sol";
import { IDelegateRegistry } from "./interfaces/IDelegateRegistry.sol";
import { IDelegateRegistryV1 } from "./interfaces/IDelegateRegistryV1.sol";
import { ReentrancyGuard } from "solady/utils/ReentrancyGuard.sol";
import { Lifebuoy } from "solady/utils/Lifebuoy.sol";

/// @notice The pixel ledger functions the Arena uses (NormiesCanvasStorageV2).
interface IArenaPixels {
    /// @notice Move `amount` wallet pixels from `from` to `to`. Callable by holders of a mover role.
    function moveBalance(address from, address to, uint256 amount) external;
    /// @notice Spend `amount` of the allowance `owner` gave `spender`. Callable by holders of a mover role.
    function useAllowance(address owner, address spender, uint256 amount) external;
    /// @notice Wallet pixel balance of `account`.
    function balanceOf(address account) external view returns (uint256);
}

/// @notice The Normies collection.
interface IArenaCollection {
    /// @notice Holder of Normie `id`. Reverts for an id that does not exist.
    function ownerOf(uint256 id) external view returns (address);
}

/// @notice The ERC-8004 identity adapter.
interface IArenaAdapter {
    /// @notice What agent `agentId` is bound to: a token standard (0 for ERC-721), a contract and a token id.
    function bindingOf(uint256 agentId) external view returns (uint8 standard, address boundAddress, uint256 tokenId);
}

/**
 * @title NormiesArenaStorage
 * @author Normies by Serc (https://x.com/serc1n)
 * @author Smart Contract by Yigit Duman (https://x.com/yigitduman)
 * @notice State and custody for the Normies Arena: every Arena pixel, and the records of balances, the line, agent
 *         links, rounds and skin purchases. Authorized writers (the Arena logic contracts) change the records
 *         through the setters below, each one state change with its event. The game rules live in the logic.
 *
 *         Custody: every Arena pixel sits in this contract's wallet balance on the pixel ledger, either in a
 *         Normie's balance (totalAllocated) or in a round's unpaid pool (totalPooled). Balances are keyed by Normie
 *         id, so they follow the NFT. Every setter that brings pixels in checks that the ledger balance covers both
 *         totals.
 *
 *         Pixels leave only from this contract's own address: withdraw (a Normie's holder or a delegate, always
 *         paid to the holder), rescue (owner, a burned Normie's whole balance), sweep (owner, surplus only) and the
 *         writer setter releaseSponsorship. Needs a mover role on the pixel ledger.
 *
 *         Line: a first-in, first-out line of tickets. A Normie has one current ticket; any other ticket for it is
 *         stale and is skipped when taken from the head. Sixteen tickets share a storage slot, each holding a Normie
 *         id in 16 bits, so issuing a ticket mostly writes to a slot already in use.
 *
 *         Holders: a Normie's holder is collection.ownerOf(id). Its delegates are the accounts the holder delegated
 *         to on delegate.xyz (v2 or v1), at wallet, contract or token level. A Normie is burned when ownerOf
 *         reverts for an id below ID_BOUND, or returns DEAD (0x000000000000000000000000000000000000dEaD).
 *
 *         ETH or tokens sent to it by mistake can be recovered with solady's Lifebuoy: by the owner, and by the
 *         deployer until it locks its own access with lockRescue(1). The pixel ledger has no ERC-20 transfer, so
 *         Lifebuoy cannot move the pixels this contract holds; they leave only as described above.
 */
contract NormiesArenaStorage is NormiesAccess, ReentrancyGuard, Lifebuoy {
    /// @notice The caller is not an authorized writer.
    error NotAuthorized();
    /// @notice A malformed argument: a zero address or amount, an out-of-range id, or a bad batch.
    error InvalidInput();
    /// @notice The call is not allowed in the current state.
    error InvalidState();
    /// @notice The caller is neither the Normie's holder nor one of its delegates.
    error Forbidden();
    /// @notice The Normie is burned.
    error Burned();
    /// @notice The Normie is not burned.
    error NotBurned();
    /// @notice The ledger balance `balance` does not cover the `required` allocated and pooled pixels.
    error BackingShortfall(uint256 balance, uint256 required);

    /// @notice A Normie's place in the line.
    struct Enrollment {
        /// @dev The Normie's current ticket.
        uint64 ticket;
        /// @dev Whether the Normie is waiting in the line.
        bool active;
        /// @dev Whether it left the line only because its balance was below a round's price.
        bool needsFunds;
    }

    /// @notice A round's record.
    struct Round {
        /// @dev Sponsored pixels added to the round, including any moved in from a cancelled round.
        uint256 sponsorship;
        /// @dev Entry pixels charged to the round's players.
        uint256 fees;
        /// @dev The latest results hash posted for the round.
        bytes32 resultHash;
        /// @dev Admissions are closed.
        bool closed;
        bool settled;
        bool cancelled;
        bool started;
        bool finished;
        /// @dev The newest ticket when the round started. Higher tickets cannot be admitted to it.
        uint64 ticketCutoff;
        /// @dev Pixels of the pool not yet credited, moved or released.
        uint256 unpaid;
    }

    /// @notice A round's rules, recorded when it starts.
    struct Rules {
        /// @dev Most Normies admitted.
        uint32 capacity;
        /// @dev Share of players who win, in basis points.
        uint16 winnerBps;
        /// @dev Pixels charged per admission. Zero in a free round.
        uint64 price;
        /// @dev Whether the round is free.
        bool free;
        /// @dev Whether the rules have been recorded.
        bool fixed_;
    }

    /// @notice Normie ids are below this bound.
    uint256 public constant ID_BOUND = 10_000;
    /// @notice A Normie held by this address counts as burned.
    address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
    /// @notice Most entries in one withdrawBatch.
    uint256 public constant MAX_WITHDRAW_BATCH = 100;

    /// @notice The pixel ledger holding this contract's pixels.
    IArenaPixels public immutable pixels;
    /// @notice The Normies collection.
    IArenaCollection public immutable collection;
    /// @notice delegate.xyz v2 registry.
    IDelegateRegistry public immutable delegateRegistry;
    /// @notice delegate.xyz v1 registry.
    IDelegateRegistryV1 public immutable delegateRegistryV1;
    /// @notice The ERC-8004 identity adapter that agent links are checked against. Set by the owner.
    IArenaAdapter public adapter;

    /// @notice Logic contracts allowed to call the writer setters.
    mapping(address => bool) public authorizedWriters;

    /// @notice Each Normie's balance.
    mapping(uint256 => uint256) public balanceOf;
    /// @notice Sum of all Normie balances.
    uint256 public totalAllocated;
    /// @notice Sum of every round's unpaid pool.
    uint256 public totalPooled;

    /// @notice Each Normie's place in the line.
    mapping(uint256 => Enrollment) public enrollment;
    /// @dev The line: ticket t's Normie id sits in bits [16 * (t % 16), 16 * (t % 16) + 16) of slot t / 16. A
    ///      taken ticket is left in place; tickets(t) reads only the tickets from head to tail.
    mapping(uint256 => uint256) private _line;
    /// @notice The oldest ticket not yet taken.
    uint64 public head = 1;
    /// @notice The newest ticket issued. Tickets are numbered from 1 in the order issued.
    uint64 public tail;

    /// @notice The agent each Normie is linked to.
    mapping(uint256 => uint256) public agentOf;
    /// @notice Whether a Normie has been linked to an agent.
    mapping(uint256 => bool) public agentBound;

    /// @notice The latest round started. Zero before round 1.
    uint256 public currentRound;

    /// @notice Each round's record, field by field (roundOf returns it as a struct).
    mapping(uint256 => Round) public games;
    /// @dev Each round's rules.
    mapping(uint256 => Rules) internal _rules;
    /// @dev Normies admitted to each round, in admission order.
    mapping(uint256 => uint256[]) internal _players;
    /// @notice Whether a Normie was admitted to a round.
    mapping(uint256 => mapping(uint256 => bool)) public played;

    /// @notice Skin purchases per Normie.
    mapping(uint256 => uint256) public purchased;
    /// @notice Skin purchases in total.
    uint256 public purchaseCount;

    /// @notice `writer` was authorized (`allowed`) or revoked.
    event AuthorizedWriterSet(address indexed writer, bool allowed);
    /// @notice The identity adapter was set to `adapter`.
    event AdapterSet(address indexed adapter);
    /// @notice `amount` surplus pixels were sent to `to`.
    event Swept(address indexed to, uint256 amount);
    /// @notice `amount` pixels from `from` were added to Normie `id`'s balance.
    event Deposited(uint256 indexed id, address indexed from, uint256 amount);
    /// @notice `amount` pixels of Normie `id`'s balance were paid to its holder `to`.
    event Withdrawn(uint256 indexed id, address indexed to, uint256 amount);
    /// @notice The whole balance of burned Normie `id`, `amount` pixels, was sent to `to`.
    event Rescued(uint256 indexed id, address indexed to, uint256 amount);
    /// @notice `amount` pixels of Normie `id`'s balance went into `round`'s pool as its entry price.
    event Charged(uint256 indexed round, uint256 indexed id, uint256 amount);
    /// @notice `amount` pixels of `round`'s pool were added to Normie `id`'s balance, as a prize or a refund.
    event Credited(uint256 indexed round, uint256 indexed id, uint256 amount);
    /// @notice `from` added `amount` pixels of sponsorship to `round`.
    event Sponsored(uint256 indexed round, address indexed from, uint256 amount);
    /// @notice `amount` unpaid pixels moved from round `from` to round `to` as sponsorship.
    event SponsorshipMoved(uint256 indexed from, uint256 indexed to, uint256 amount);
    /// @notice `amount` pixels of `round`'s sponsorship were paid out to `to`.
    event SponsorshipReleased(uint256 indexed round, address indexed to, uint256 amount);
    /// @notice Normie `id` took ticket `ticket` at the back of the line.
    event Enrolled(uint256 indexed id, uint64 ticket);
    /// @notice Normie `id` left the line; `needsFunds` is set when it left only for lack of funds.
    event EnrollmentPaused(uint256 indexed id, bool needsFunds);
    /// @notice Normie `id` was linked to agent `agentId`.
    event AgentLinked(uint256 indexed id, uint256 indexed agentId);
    /// @notice `round`'s rules were recorded.
    event RulesFixed(uint256 indexed round, uint256 capacity, uint256 price, uint256 winnerBps, bool free);
    /// @notice `round` started. Tickets up to `ticketCutoff` can be admitted to it. `at` is the block time, recorded
    ///         for readers only.
    event RoundStarted(uint256 indexed round, uint64 ticketCutoff, uint256 at);
    /// @notice Normie `id` was admitted to `round`.
    event Admitted(uint256 indexed round, uint256 indexed id);
    /// @notice Admissions to `round` closed with `participants` admitted.
    event AdmissionsClosed(uint256 indexed round, uint256 participants);
    /// @notice `round` finished with `players` admitted. `at` is the block time, recorded for readers only.
    event RoundFinished(uint256 indexed round, uint256 players, uint256 at);
    /// @notice `resultHash` was posted as `round`'s results.
    event ResultsPosted(uint256 indexed round, bytes32 indexed resultHash);
    /// @notice `round` was settled for results `resultHash`; its `pool` pixels went to the winners' balances.
    event Settled(uint256 indexed round, bytes32 indexed resultHash, uint256 pool);
    /// @notice `round` was cancelled: `refunded` entry pixels went back to the players' balances and its
    ///         sponsorship moved to round `carriedTo`.
    event Cancelled(uint256 indexed round, uint256 refunded, uint256 carriedTo);
    /// @notice Skin purchase `purchaseId` (numbered from 1) for Normie `id`, bought by `buyer` for `price` pixels.
    event SkinPurchased(uint256 indexed purchaseId, uint256 indexed id, address indexed buyer, uint256 price);

    /// @param pixels_     The pixel ledger.
    /// @param collection_ The Normies collection.
    /// @param adapter_    The ERC-8004 identity adapter.
    /// @param registry_   The delegate.xyz v2 registry.
    /// @param registryV1_ The delegate.xyz v1 registry.
    /// @param admin       The owner.
    constructor(
        address pixels_,
        address collection_,
        address adapter_,
        address registry_,
        address registryV1_,
        address admin
    ) {
        require(
            pixels_ != address(0) && collection_ != address(0) && adapter_ != address(0) && registry_ != address(0)
                && registryV1_ != address(0) && admin != address(0),
            InvalidInput()
        );
        pixels = IArenaPixels(pixels_);
        collection = IArenaCollection(collection_);
        adapter = IArenaAdapter(adapter_);
        delegateRegistry = IDelegateRegistry(registry_);
        delegateRegistryV1 = IDelegateRegistryV1(registryV1_);
        _initializeOwner(admin);
    }

    /// @dev Reverts with NotAuthorized unless the caller is an authorized writer.
    modifier onlyWriter() {
        require(authorizedWriters[msg.sender], NotAuthorized());
        _;
    }

    // ──────────────────────────────────────────────
    //  Owner
    // ──────────────────────────────────────────────

    /// @notice Authorize or revoke a writer. Owner only. A writer can change every record and pool here and pay out
    ///         sponsorship. The owner is not a writer unless it authorizes itself.
    function setAuthorizedWriter(address writer, bool allowed) external onlyOwner {
        require(writer != address(0), InvalidInput());
        authorizedWriters[writer] = allowed;
        emit AuthorizedWriterSet(writer, allowed);
    }

    /// @notice Set the identity adapter. Owner only. Existing agent links stay recorded.
    function setAdapter(address value) external onlyOwner {
        require(value != address(0), InvalidInput());
        adapter = IArenaAdapter(value);
        emit AdapterSet(value);
    }

    /// @notice Send `amount` surplus pixels to `to`, such as pixels sent here by mistake. Owner only. `amount` must
    ///         not exceed surplus(), so a sweep cannot reach a balance or a pool.
    function sweep(address to, uint256 amount) external onlyOwner nonReentrant {
        require(to != address(0) && amount > 0 && amount <= surplus(), InvalidInput());
        pixels.moveBalance(address(this), to, amount);
        emit Swept(to, amount);
    }

    /// @notice Send the whole balance of burned Normie `id` to `to`. Owner only. Reverts with NotBurned while the
    ///         Normie exists and with InvalidInput when its balance is zero. The only way a burned Normie's balance
    ///         leaves.
    function rescue(uint256 id, address to) external onlyOwner nonReentrant {
        require(isBurned(id), NotBurned());
        uint256 amount = balanceOf[id];
        require(to != address(0) && amount > 0, InvalidInput());
        balanceOf[id] = 0;
        totalAllocated -= amount;
        pixels.moveBalance(address(this), to, amount);
        emit Rescued(id, to, amount);
    }

    // ──────────────────────────────────────────────
    //  Withdrawals
    // ──────────────────────────────────────────────

    /// @notice Pay `amount` pixels of Normie `id`'s balance to the Normie's holder. The holder or one of its
    ///         delegates may call it, at any time; it has no pause and needs no logic contract. Reverts with Burned
    ///         for a burned Normie and with InvalidInput for zero or more than the balance. The ledger's cooldown
    ///         applies to the pixels arriving in the holder's wallet.
    function withdraw(uint256 id, uint256 amount) external nonReentrant {
        _withdraw(id, amount);
    }

    /// @notice withdraw for several Normies, up to MAX_WITHDRAW_BATCH. Reverts entirely if one entry fails.
    function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts) external nonReentrant {
        require(ids.length == amounts.length && ids.length > 0 && ids.length <= MAX_WITHDRAW_BATCH, InvalidInput());
        for (uint256 i; i < ids.length; ++i) {
            _withdraw(ids[i], amounts[i]);
        }
    }

    /// @dev Debits Normie `id` and pays its holder.
    function _withdraw(uint256 id, uint256 amount) private {
        address holder = holderFor(id, msg.sender);
        require(amount > 0 && balanceOf[id] >= amount, InvalidInput());
        balanceOf[id] -= amount;
        totalAllocated -= amount;
        pixels.moveBalance(address(this), holder, amount);
        emit Withdrawn(id, holder, amount);
    }

    // ──────────────────────────────────────────────
    //  Views
    // ──────────────────────────────────────────────

    /**
     * @notice The holder of Normie `id`, if `account` is the holder or one of its delegates.
     * @dev Reverts with InvalidInput for an id at or above ID_BOUND, Burned for a burned Normie, and Forbidden for
     *      any other account. The delegate.xyz registries are read only for an account that is not the holder.
     */
    function holderFor(uint256 id, address account) public view returns (address holder) {
        require(id < ID_BOUND, InvalidInput());
        holder = _holder(id);
        require(holder != address(0), Burned());
        require(
            account == holder || delegateRegistry.checkDelegateForERC721(account, holder, address(collection), id, "")
                || delegateRegistryV1.checkDelegateForToken(account, holder, address(collection), id),
            Forbidden()
        );
    }

    /// @notice Whether Normie `id` is burned: an id below ID_BOUND for which collection.ownerOf reverts or returns
    ///         DEAD.
    function isBurned(uint256 id) public view returns (bool) {
        return id < ID_BOUND && _holder(id) == address(0);
    }

    /// @dev collection.ownerOf(id), or zero when it reverts or returns DEAD.
    function _holder(uint256 id) private view returns (address) {
        try collection.ownerOf(id) returns (address holder) {
            return holder == DEAD ? address(0) : holder;
        } catch {
            return address(0);
        }
    }

    /// @notice Pixels held beyond totalAllocated and totalPooled. Zero when there are none.
    function surplus() public view returns (uint256) {
        uint256 balance = pixels.balanceOf(address(this));
        uint256 required = totalAllocated + totalPooled;
        return balance > required ? balance - required : 0;
    }

    /// @notice `round`'s record.
    function roundOf(uint256 round) external view returns (Round memory) {
        return games[round];
    }

    /// @notice `round`'s recorded rules. All zero, with `fixed_` false, before the round starts.
    function rulesOf(uint256 round) external view returns (Rules memory) {
        return _rules[round];
    }

    /// @notice Normies admitted to `round`, in admission order.
    function players(uint256 round) external view returns (uint256[] memory) {
        return _players[round];
    }

    /// @notice Number of Normies admitted to `round`.
    function playerCount(uint256 round) external view returns (uint256) {
        return _players[round].length;
    }

    /// @notice `round`'s pool: its sponsorship plus its entry fees.
    function poolOf(uint256 round) external view returns (uint256) {
        return games[round].sponsorship + games[round].fees;
    }

    /// @notice Whether `round` has started and is neither finished nor cancelled.
    function isOpen(uint256 round) public view returns (bool) {
        Round storage r = games[round];
        return r.started && !r.finished && !r.cancelled;
    }

    /// @notice The Normie `ticket` is for while it is in the line (from head to tail). Zero for a ticket already
    ///         taken or not yet issued, which is also Normie #0's id: check head and tail to tell them apart.
    function tickets(uint64 ticket) public view returns (uint256) {
        if (ticket < head || ticket > tail) return 0;
        return _ticketAt(ticket);
    }

    /// @dev The id stored for `ticket`.
    function _ticketAt(uint64 ticket) private view returns (uint256) {
        return (_line[ticket >> 4] >> ((ticket & 15) << 4)) & 0xffff;
    }

    /// @notice Whether the line has no ticket `round` can admit: the line is empty or its head is past the round's
    ///         ticket cutoff. True for a round that has not started.
    function lineExhausted(uint256 round) public view returns (bool) {
        return head > tail || head > games[round].ticketCutoff;
    }

    // ──────────────────────────────────────────────
    //  Writers: balances and pools
    // ──────────────────────────────────────────────

    /// @notice Add `amount` pixels from `from` to Normie `id`'s balance. Writers only. The pixels must already be in
    ///         this contract's ledger balance, or the backing check reverts with BackingShortfall.
    function addBalance(uint256 id, address from, uint256 amount) external onlyWriter {
        require(id < ID_BOUND && amount > 0, InvalidInput());
        balanceOf[id] += amount;
        totalAllocated += amount;
        _checkBacking();
        emit Deposited(id, from, amount);
    }

    /// @notice Move `amount` pixels from Normie `id`'s balance into `round`'s pool as entry fees. Writers only, for
    ///         a started round that is neither settled nor cancelled. Reverts with InvalidState when the balance is
    ///         short.
    function chargeEntry(uint256 round, uint256 id, uint256 amount) external onlyWriter {
        Round storage r = games[round];
        require(r.started && !r.settled && !r.cancelled && balanceOf[id] >= amount, InvalidState());
        balanceOf[id] -= amount;
        totalAllocated -= amount;
        totalPooled += amount;
        r.fees += amount;
        r.unpaid += amount;
        emit Charged(round, id, amount);
    }

    /// @notice Move pixels from `round`'s unpaid pool into Normie balances, `amounts[i]` to `ids[i]`. Writers only,
    ///         for a round that is neither settled nor cancelled. Reverts with InvalidState when the amounts add up to
    ///         more than the unpaid pool.
    function creditFromPool(uint256 round, uint256[] calldata ids, uint256[] calldata amounts) external onlyWriter {
        Round storage r = games[round];
        require(!r.settled && !r.cancelled, InvalidState());
        require(ids.length == amounts.length, InvalidInput());
        uint256 total;
        for (uint256 i; i < ids.length; ++i) {
            uint256 id = ids[i];
            require(id < ID_BOUND, InvalidInput());
            balanceOf[id] += amounts[i];
            total += amounts[i];
            emit Credited(round, id, amounts[i]);
        }
        require(total <= r.unpaid, InvalidState());
        r.unpaid -= total;
        totalPooled -= total;
        totalAllocated += total;
    }

    /// @notice Add `amount` pixels of sponsorship from `from` to `round`. Writers only, for a round above zero that
    ///         is neither settled nor cancelled. The pixels must already be in this contract's ledger balance.
    function addSponsorship(uint256 round, address from, uint256 amount) external onlyWriter {
        Round storage r = games[round];
        require(round > 0 && !r.settled && !r.cancelled, InvalidState());
        require(amount > 0, InvalidInput());
        r.sponsorship += amount;
        r.unpaid += amount;
        totalPooled += amount;
        _checkBacking();
        emit Sponsored(round, from, amount);
    }

    /// @notice Move `amount` unpaid pixels of round `from` to round `to` as sponsorship. Writers only. Neither round
    ///         may be settled or cancelled, and `to` must not have started.
    function moveSponsorship(uint256 from, uint256 to, uint256 amount) external onlyWriter {
        Round storage a = games[from];
        Round storage b = games[to];
        require(
            to > 0 && from != to && !a.settled && !a.cancelled && !b.started && !b.settled && !b.cancelled
                && amount <= a.unpaid,
            InvalidState()
        );
        a.unpaid -= amount;
        b.sponsorship += amount;
        b.unpaid += amount;
        emit SponsorshipMoved(from, to, amount);
    }

    /// @notice Pay `amount` of `round`'s sponsorship to `to`. Writers only, for a round that is neither settled nor
    ///         cancelled, up to both its sponsorship and its unpaid pool.
    function releaseSponsorship(uint256 round, address to, uint256 amount) external onlyWriter nonReentrant {
        Round storage r = games[round];
        require(!r.settled && !r.cancelled, InvalidState());
        require(to != address(0) && amount > 0 && amount <= r.sponsorship && amount <= r.unpaid, InvalidInput());
        r.sponsorship -= amount;
        r.unpaid -= amount;
        totalPooled -= amount;
        pixels.moveBalance(address(this), to, amount);
        emit SponsorshipReleased(round, to, amount);
    }

    // ──────────────────────────────────────────────
    //  Writers: rounds
    // ──────────────────────────────────────────────

    /// @notice Record `round`'s rules and mark them fixed. Writers only, before the round starts.
    function setRules(uint256 round, Rules calldata r) external onlyWriter {
        require(!games[round].started, InvalidState());
        _rules[round] =
            Rules({ capacity: r.capacity, winnerBps: r.winnerBps, price: r.price, free: r.free, fixed_: true });
        emit RulesFixed(round, r.capacity, r.price, r.winnerBps, r.free);
    }

    /// @notice Mark `round` started, make it currentRound and set its ticket cutoff to the newest ticket. Writers
    ///         only, once per round.
    function setStarted(uint256 round) external onlyWriter {
        Round storage r = games[round];
        require(round > 0 && !r.started, InvalidState());
        r.started = true;
        r.ticketCutoff = tail;
        currentRound = round;
        emit RoundStarted(round, tail, block.timestamp);
    }

    /// @notice Record Normie `id` as a player of `round`. Writers only, for a started round, once per Normie.
    function addPlayer(uint256 round, uint256 id) external onlyWriter {
        require(games[round].started && !played[round][id], InvalidState());
        played[round][id] = true;
        _players[round].push(id);
        emit Admitted(round, id);
    }

    /// @notice Close admissions to `round`. Writers only, once, for a started round.
    function setClosed(uint256 round) external onlyWriter {
        Round storage r = games[round];
        require(r.started && !r.closed, InvalidState());
        r.closed = true;
        emit AdmissionsClosed(round, _players[round].length);
    }

    /// @notice Mark `round` finished. Writers only, once, for a started round that is not cancelled.
    function setFinished(uint256 round) external onlyWriter {
        Round storage r = games[round];
        require(r.started && !r.finished && !r.cancelled, InvalidState());
        r.finished = true;
        emit RoundFinished(round, _players[round].length, block.timestamp);
    }

    /// @notice Record `resultHash` as `round`'s results, replacing any earlier hash. Writers only.
    function setResultHash(uint256 round, bytes32 resultHash) external onlyWriter {
        games[round].resultHash = resultHash;
        emit ResultsPosted(round, resultHash);
    }

    /// @notice Mark `round` settled. Writers only, once, for a started round whose whole pool has been credited
    ///         (unpaid is zero).
    function setSettled(uint256 round) external onlyWriter {
        Round storage r = games[round];
        require(r.started && !r.settled && !r.cancelled && r.unpaid == 0, InvalidState());
        r.settled = true;
        emit Settled(round, r.resultHash, r.sponsorship + r.fees);
    }

    /// @notice Mark `round` cancelled and closed, its sponsorship having moved to round `carriedTo`. Writers only,
    ///         once, for a started round whose whole pool has been refunded or moved (unpaid is zero).
    function setCancelled(uint256 round, uint256 carriedTo) external onlyWriter {
        Round storage r = games[round];
        require(r.started && !r.settled && !r.cancelled && r.unpaid == 0, InvalidState());
        r.cancelled = true;
        r.closed = true;
        emit Cancelled(round, r.fees, carriedTo);
    }

    // ──────────────────────────────────────────────
    //  Writers: line, links, skins
    // ──────────────────────────────────────────────

    /// @notice Give Normie `id` a new ticket at the back of the line and mark it active, clearing needsFunds. Its
    ///         earlier ticket, if any, stays in the line and is skipped when taken. Writers only.
    function pushTicket(uint256 id) external onlyWriter {
        require(id < ID_BOUND, InvalidInput());
        uint64 ticket = ++tail;
        uint256 shift = uint256(ticket & 15) << 4;
        uint256 key = ticket >> 4;
        // Ticket numbers only grow, so this ticket's 16 bits have never been written.
        _line[key] |= id << shift;
        enrollment[id] = Enrollment({ ticket: ticket, active: true, needsFunds: false });
        emit Enrolled(id, ticket);
    }

    /**
     * @notice Take the ticket at the head of the line, if `round` can admit it. Writers only.
     * @return found  False when the line is empty or its head was issued after `round` started; nothing is taken.
     * @return ticket The ticket taken.
     * @return id     The Normie the ticket is for.
     */
    function popTicket(uint256 round) external onlyWriter returns (bool found, uint64 ticket, uint256 id) {
        if (lineExhausted(round)) return (false, 0, 0);
        ticket = head++;
        id = _ticketAt(ticket);
        found = true;
    }

    /// @notice Take Normie `id` out of the line, recording whether it left only for lack of funds. Its ticket stays
    ///         in the line and is skipped when taken. Writers only.
    function deactivate(uint256 id, bool needsFunds_) external onlyWriter {
        Enrollment storage e = enrollment[id];
        e.active = false;
        e.needsFunds = needsFunds_;
        emit EnrollmentPaused(id, needsFunds_);
    }

    /// @notice Link Normie `id` to agent `agentId`, replacing any earlier link. Writers only.
    function linkAgent(uint256 id, uint256 agentId) external onlyWriter {
        require(id < ID_BOUND, InvalidInput());
        agentOf[id] = agentId;
        agentBound[id] = true;
        emit AgentLinked(id, agentId);
    }

    /// @notice Count a skin purchase of `price` pixels for Normie `id` by `buyer`. Writers only.
    function recordPurchase(uint256 id, address buyer, uint256 price) external onlyWriter {
        ++purchased[id];
        emit SkinPurchased(++purchaseCount, id, buyer, price);
    }

    // ──────────────────────────────────────────────
    //  Internal
    // ──────────────────────────────────────────────

    /// @dev Reverts with BackingShortfall unless the ledger balance covers totalAllocated plus totalPooled.
    function _checkBacking() private view {
        uint256 balance = pixels.balanceOf(address(this));
        uint256 required = totalAllocated + totalPooled;
        require(balance >= required, BackingShortfall(balance, required));
    }
}

src/arena/ArenaAccess.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

import { NormiesAccess } from "../NormiesAccess.sol";
import { NormiesArenaStorage, IArenaPixels, IArenaAdapter } from "../NormiesArenaStorage.sol";
import { ReentrancyGuard } from "solady/utils/ReentrancyGuard.sol";
import { Lifebuoy } from "solady/utils/Lifebuoy.sol";

/**
 * @title ArenaAccess
 * @author Normies by Serc (https://x.com/serc1n)
 * @author Smart Contract by Yigit Duman (https://x.com/yigitduman)
 * @notice Base for the Arena logic contracts (NormiesArena, NormiesArenaQueue, NormiesArenaSkins): the storage they
 *         write to, the pixel ledger, a pause switch, and agent linking.
 *
 *         Each logic contract is tied to one NormiesArenaStorage for its lifetime and writes to it only while the
 *         storage owner lists it as an authorized writer. Every logic contract starts paused; the owner or
 *         GUARDIAN_ROLE pauses and unpauses it.
 *
 *         Holds no tokens. ETH or tokens sent to it by mistake can be recovered with solady's Lifebuoy: by the
 *         owner, and by the deployer until it locks its own access with lockRescue(1).
 */
abstract contract ArenaAccess is NormiesAccess, ReentrancyGuard, Lifebuoy {
    /// @notice A malformed argument (a zero address or amount, an out-of-range id or value, an empty or oversized
    ///         batch), or an agent binding that does not point at the Normie.
    error InvalidInput();
    /// @notice The contract is paused.
    error Paused();
    /// @notice The call is not allowed in the current state.
    error InvalidState();

    /// @notice The Arena storage this contract reads and writes.
    NormiesArenaStorage public immutable store;
    /// @notice The pixel ledger, read from the storage at deployment.
    IArenaPixels public immutable pixels;
    /// @notice Whether functions guarded by whenRunning revert. All other functions work while paused. Starts paused.
    bool public paused = true;

    /// @notice The pause switch was set to `paused`.
    event PauseChanged(bool paused);

    /// @param store_ The NormiesArenaStorage to use.
    /// @param admin  The owner.
    constructor(address store_, address admin) {
        require(store_ != address(0) && admin != address(0), InvalidInput());
        store = NormiesArenaStorage(store_);
        pixels = NormiesArenaStorage(store_).pixels();
        _initializeOwner(admin);
    }

    /// @dev Reverts with Paused while the contract is paused.
    modifier whenRunning() {
        require(!paused, Paused());
        _;
    }

    /// @notice Pause or unpause the functions guarded by whenRunning. Owner or GUARDIAN_ROLE. Each Arena logic
    ///         contract has its own switch and its own roles. Withdrawals are on the storage and have no pause.
    function setPaused(bool value) external onlyOwnerOrRoles(GUARDIAN_ROLE) {
        paused = value;
        emit PauseChanged(value);
    }

    /// @notice Link Normie `id` to agent `agentId`, replacing any earlier link. The Normie's holder or one of its
    ///         delegates only (see NormiesArenaStorage.holderFor, which reverts with Forbidden for anyone else and
    ///         Burned for a burned Normie). The adapter's binding for `agentId` must be the ERC-721 binding to this
    ///         Normie, or it reverts with InvalidInput.
    function bindAgent(uint256 id, uint256 agentId) external {
        store.holderFor(id, msg.sender);
        _bindAgent(id, agentId);
    }

    /// @dev Links the Normie to the agent after checking the adapter binding. The caller check is the caller's.
    function _bindAgent(uint256 id, uint256 agentId) internal {
        require(_bindingMatches(id, agentId), InvalidInput());
        store.linkAgent(id, agentId);
    }

    /// @dev Whether the Normie is linked to an agent whose adapter binding still points at it.
    function _awake(uint256 id) internal view returns (bool) {
        return store.agentBound(id) && _bindingMatches(id, store.agentOf(id));
    }

    /// @dev Whether the adapter's binding for `agentId` is the ERC-721 binding (standard 0) to Normie `id`.
    function _bindingMatches(uint256 id, uint256 agentId) private view returns (bool) {
        (uint8 standard, address boundAddress, uint256 tokenId) = store.adapter().bindingOf(agentId);
        return id < store.ID_BOUND() && standard == 0 && boundAddress == address(store.collection()) && tokenId == id;
    }
}

src/interfaces/IDelegateRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

/// @notice Minimal interface for delegate.xyz v2 registry
/// @dev Full registry at 0x00000000000000447e69651d841bD8D104Bed493
interface IDelegateRegistry {
    function checkDelegateForAll(address to, address from, bytes32 rights) external view returns (bool);
    function checkDelegateForContract(
        address to,
        address from,
        address contract_,
        bytes32 rights
    ) external view returns (bool);

    /// @notice True for a token, contract or wallet level delegation from `from` to `to`.
    function checkDelegateForERC721(
        address to,
        address from,
        address contract_,
        uint256 tokenId,
        bytes32 rights
    ) external view returns (bool);
}

src/interfaces/IDelegateRegistryV1.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;

/// @notice Minimal interface for delegate.xyz v1 registry
/// @dev Full registry at 0x00000000000076A84feF008CDAbe6409d2FE638B
interface IDelegateRegistryV1 {
    function checkDelegateForAll(address delegate, address vault) external view returns (bool);
    function checkDelegateForContract(address delegate, address vault, address contract_) external view returns (bool);

    /// @notice True for a token, contract or wallet level delegation from `vault` to `delegate`.
    function checkDelegateForToken(
        address delegate,
        address vault,
        address contract_,
        uint256 tokenId
    ) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "forge-std/=node_modules/forge-std/",
    "@manifoldxyz/creator-core-solidity/=node_modules/@manifoldxyz/creator-core-solidity/",
    "solady/=node_modules/solady/src/",
    "@ensdomains/=node_modules/@ensdomains/",
    "@limitbreak/=node_modules/@limitbreak/",
    "erc721a/=node_modules/erc721a/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.