Verified contractPartialMIT
NormiesArenaMigrator
Address0x16f8620b88cdee0eecf783735f00b7aeacd540fd
- Balance
0 ETH
- Transactions
10
- 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
- 0x77888f83e7…d3a5de9571
10 files
- src/arena/NormiesArenaMigrator.solmain9.91 KB
- node_modules/solady/src/auth/Ownable.sol12.55 KB
- node_modules/solady/src/auth/OwnableRoles.sol25.85 KB
- node_modules/solady/src/utils/Lifebuoy.sol14.5 KB
- node_modules/solady/src/utils/ReentrancyGuard.sol2.33 KB
- node_modules/solady/src/utils/SafeCastLib.sol23.8 KB
- src/NormiesAccess.sol1.57 KB
- src/NormiesArenaStorage.sol43.38 KB
- src/interfaces/IDelegateRegistry.sol771 B
- src/interfaces/IDelegateRegistryV1.sol706 B
src/arena/NormiesArenaMigrator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.33;
import { NormiesAccess } from "../NormiesAccess.sol";
import { NormiesArenaStorage, IArenaPixels } from "../NormiesArenaStorage.sol";
/// @notice The Arena v2 storage functions the migration reads and writes.
interface ILegacyArenaStorage {
struct Round {
uint256 sponsorship;
uint256 fees;
bytes32 resultHash;
bool closed;
bool settled;
bool cancelled;
bool started;
bool finished;
uint64 ticketCutoff;
uint256 unpaid;
}
function pixels() external view returns (address);
function collection() external view returns (address);
function currentRound() external view returns (uint256);
function totalAllocated() external view returns (uint256);
function totalPooled() external view returns (uint256);
function balanceOf(uint256 id) external view returns (uint256);
function roundOf(uint256 round) external view returns (Round memory);
function head() external view returns (uint64);
function tail() external view returns (uint64);
function tickets(uint64 ticket) external view returns (uint256);
function agentBound(uint256 id) external view returns (bool);
function agentOf(uint256 id) external view returns (uint256);
function purchased(uint256 id) external view returns (uint256);
function purchaseCount() external view returns (uint256);
function isBurned(uint256 id) external view returns (bool);
function setStarted(uint256 round) external;
function setFinished(uint256 round) external;
function chargeEntry(uint256 round, uint256 id, uint256 amount) external;
function moveSponsorship(uint256 from, uint256 to, uint256 amount) external;
function releaseSponsorship(uint256 round, address to, uint256 amount) external;
}
/**
* @title NormiesArenaMigrator
* @author Smart Contract by Yigit Duman (https://x.com/yigitduman)
* @notice One-off move of the Arena v2 storage (line based, no round played) into the v3 storage. It must be an
* authorized writer of both, and the v2 logic contracts must be revoked as writers first so nothing changes
* underneath it. Every value it moves is read from the v2 storage; callers pass only which ids and how
* many tickets to process.
*
* 1. moveFunds: pays every v2 pool and balance into the v3 storage and books them there under the same
* rounds and Normie ids. Balances arrive unregistered; registerTickets registers the Normies in line.
* v2 can release only sponsorship, so balances go through round 1: charged as its entry fees, moved to
* round 2's sponsorship and released from there. v2 is left with round 1 started and finished, every
* balance and pool at zero.
* 2. registerTickets: walks the v2 line from ticket 1 and registers each Normie that holds a ticket (once,
* whether it is still waiting or not), copying its agent link. Burned Normies are skipped.
* 3. copyPurchases: copies skin purchase counts.
* 4. finish: checks everything moved and locks the contract.
*
* Owner or OPERATOR_ROLE.
*/
contract NormiesArenaMigrator is NormiesAccess {
/// @notice Role that may run the migration (_ROLE_3, value 8).
uint256 public constant OPERATOR_ROLE = _ROLE_3;
/// @notice A malformed argument.
error InvalidInput();
/// @notice The call is not allowed in the current state.
error InvalidState();
/// @notice A check of the moved values failed.
error Mismatch();
/// @notice The v2 storage.
ILegacyArenaStorage public immutable legacy;
/// @notice The v3 storage.
NormiesArenaStorage public immutable store;
/// @notice The pixel ledger both use.
IArenaPixels public immutable pixels;
/// @notice Whether moveFunds ran.
bool public fundsMoved;
/// @notice Next v2 ticket registerTickets reads; zero before the first call.
uint256 public nextTicket;
/// @notice Whether finish ran. Every step reverts afterwards.
bool public finished;
/// @notice moveFunds moved `balances` pixels of Normie balances and `pools` pixels of round pools.
event FundsMoved(uint256 balances, uint256 pools);
/// @notice registerTickets read tickets up to `lastTicket` and registered `registered` Normies.
event TicketsRegistered(uint256 lastTicket, uint256 registered);
/// @notice The migration was finished.
event Finished();
/// @param legacy_ The v2 storage.
/// @param store_ The v3 storage.
/// @param admin The owner.
constructor(address legacy_, address store_, address admin) {
require(legacy_ != address(0) && store_ != address(0) && admin != address(0), InvalidInput());
legacy = ILegacyArenaStorage(legacy_);
store = NormiesArenaStorage(store_);
pixels = NormiesArenaStorage(store_).pixels();
require(
ILegacyArenaStorage(legacy_).pixels() == address(pixels)
&& ILegacyArenaStorage(legacy_).collection() == address(NormiesArenaStorage(store_).collection()),
InvalidInput()
);
_initializeOwner(admin);
}
/// @dev Reverts once finished.
modifier open() {
require(!finished, InvalidState());
_;
}
/**
* @notice Move every v2 balance and pool into the v3 storage. Runs once. `ids` must be strictly increasing and
* hold every Normie with a v2 balance (their sum must equal v2 totalAllocated); `lastRound` must cover
* every v2 round with a pool (their sum must equal v2 totalPooled). v2 must not have started a round.
*/
function moveFunds(uint256[] calldata ids, uint256 lastRound) external onlyOwnerOrRoles(OPERATOR_ROLE) open {
require(!fundsMoved && legacy.currentRound() == 0 && lastRound > 0, InvalidState());
uint256[] memory balances = new uint256[](ids.length);
uint256 totalBalances;
for (uint256 i; i < ids.length; ++i) {
require(i == 0 || ids[i] > ids[i - 1], InvalidInput());
balances[i] = legacy.balanceOf(ids[i]);
totalBalances += balances[i];
}
require(totalBalances == legacy.totalAllocated(), Mismatch());
uint256[] memory pools = new uint256[](lastRound + 1);
uint256 totalPools;
for (uint256 r = 1; r <= lastRound; ++r) {
ILegacyArenaStorage.Round memory g = legacy.roundOf(r);
require(!g.started && g.unpaid == g.sponsorship, Mismatch());
pools[r] = g.unpaid;
totalPools += g.unpaid;
}
require(totalPools == legacy.totalPooled(), Mismatch());
uint256 before = pixels.balanceOf(address(store));
for (uint256 r = 1; r <= lastRound; ++r) {
if (pools[r] != 0) legacy.releaseSponsorship(r, address(store), pools[r]);
}
if (totalBalances != 0) {
legacy.setStarted(1);
for (uint256 i; i < ids.length; ++i) {
if (balances[i] != 0) legacy.chargeEntry(1, ids[i], balances[i]);
}
legacy.moveSponsorship(1, 2, totalBalances);
legacy.releaseSponsorship(2, address(store), totalBalances);
legacy.setFinished(1);
}
require(legacy.totalAllocated() == 0 && legacy.totalPooled() == 0, Mismatch());
require(pixels.balanceOf(address(store)) == before + totalBalances + totalPools, Mismatch());
for (uint256 r = 1; r <= lastRound; ++r) {
if (pools[r] != 0) store.addSponsorship(r, address(legacy), pools[r]);
}
for (uint256 i; i < ids.length; ++i) {
if (balances[i] == 0) continue;
store.deposit(ids[i], address(legacy), balances[i], false);
_copyLink(ids[i]);
}
fundsMoved = true;
emit FundsMoved(totalBalances, totalPools);
}
/// @notice Register the Normies behind the next `count` v2 tickets, from ticket 1 to tail, each once. The v2
/// line must never have been taken from (head 1).
function registerTickets(uint256 count) external onlyOwnerOrRoles(OPERATOR_ROLE) open {
require(count > 0, InvalidInput());
uint256 t = nextTicket;
if (t == 0) {
require(legacy.head() == 1, InvalidState());
t = 1;
}
uint256 tail = legacy.tail();
uint256 end = t + count;
if (end > tail + 1) end = tail + 1;
uint256 registered;
for (; t < end; ++t) {
uint256 id = legacy.tickets(uint64(t));
if (store.isRegistered(id) || store.isBurned(id)) continue;
store.register(id);
_copyLink(id);
++registered;
}
nextTicket = t;
emit TicketsRegistered(t - 1, registered);
}
/// @notice Copy the v2 skin purchase counts of `ids`.
function copyPurchases(uint256[] calldata ids) external onlyOwnerOrRoles(OPERATOR_ROLE) open {
for (uint256 i; i < ids.length; ++i) {
store.importPurchases(ids[i], legacy.purchased(ids[i]));
}
}
/// @notice Check that every pool, balance, ticket and purchase moved, then lock the contract.
function finish() external onlyOwnerOrRoles(OPERATOR_ROLE) open {
require(fundsMoved && nextTicket > legacy.tail(), InvalidState());
require(
store.purchaseCount() == legacy.purchaseCount() && legacy.totalAllocated() == 0
&& legacy.totalPooled() == 0,
Mismatch()
);
finished = true;
emit Finished();
}
/// @dev Copies Normie `id`'s v2 agent link, if it has one and v3 has none.
function _copyLink(uint256 id) private {
if (legacy.agentBound(id) && !store.agentBound(id)) store.linkAgent(id, legacy.agentOf(id));
}
}
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)
}
}
_;
}
}
node_modules/solady/src/utils/SafeCastLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to cast to the target type due to overflow.
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a uint8. Reverts on overflow.
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
/// @dev Casts `x` to a uint16. Reverts on overflow.
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
/// @dev Casts `x` to a uint24. Reverts on overflow.
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
/// @dev Casts `x` to a uint32. Reverts on overflow.
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
/// @dev Casts `x` to a uint40. Reverts on overflow.
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
/// @dev Casts `x` to a uint48. Reverts on overflow.
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
/// @dev Casts `x` to a uint56. Reverts on overflow.
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
/// @dev Casts `x` to a uint64. Reverts on overflow.
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
/// @dev Casts `x` to a uint72. Reverts on overflow.
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
/// @dev Casts `x` to a uint80. Reverts on overflow.
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
/// @dev Casts `x` to a uint88. Reverts on overflow.
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
/// @dev Casts `x` to a uint96. Reverts on overflow.
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
/// @dev Casts `x` to a uint104. Reverts on overflow.
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
/// @dev Casts `x` to a uint112. Reverts on overflow.
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
/// @dev Casts `x` to a uint120. Reverts on overflow.
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
/// @dev Casts `x` to a uint128. Reverts on overflow.
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
/// @dev Casts `x` to a uint136. Reverts on overflow.
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
/// @dev Casts `x` to a uint144. Reverts on overflow.
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
/// @dev Casts `x` to a uint152. Reverts on overflow.
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
/// @dev Casts `x` to a uint160. Reverts on overflow.
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
/// @dev Casts `x` to a uint168. Reverts on overflow.
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
/// @dev Casts `x` to a uint176. Reverts on overflow.
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
/// @dev Casts `x` to a uint184. Reverts on overflow.
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
/// @dev Casts `x` to a uint192. Reverts on overflow.
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
/// @dev Casts `x` to a uint200. Reverts on overflow.
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
/// @dev Casts `x` to a uint208. Reverts on overflow.
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
/// @dev Casts `x` to a uint216. Reverts on overflow.
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
/// @dev Casts `x` to a uint224. Reverts on overflow.
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
/// @dev Casts `x` to a uint232. Reverts on overflow.
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
/// @dev Casts `x` to a uint240. Reverts on overflow.
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
/// @dev Casts `x` to a uint248. Reverts on overflow.
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(int256 x) internal pure returns (int8) {
unchecked {
if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(int256 x) internal pure returns (int16) {
unchecked {
if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(int256 x) internal pure returns (int24) {
unchecked {
if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(int256 x) internal pure returns (int32) {
unchecked {
if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(int256 x) internal pure returns (int40) {
unchecked {
if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(int256 x) internal pure returns (int48) {
unchecked {
if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(int256 x) internal pure returns (int56) {
unchecked {
if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(int256 x) internal pure returns (int64) {
unchecked {
if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(int256 x) internal pure returns (int72) {
unchecked {
if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(int256 x) internal pure returns (int80) {
unchecked {
if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(int256 x) internal pure returns (int88) {
unchecked {
if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(int256 x) internal pure returns (int96) {
unchecked {
if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(int256 x) internal pure returns (int104) {
unchecked {
if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(int256 x) internal pure returns (int112) {
unchecked {
if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(int256 x) internal pure returns (int120) {
unchecked {
if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(int256 x) internal pure returns (int128) {
unchecked {
if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(int256 x) internal pure returns (int136) {
unchecked {
if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(int256 x) internal pure returns (int144) {
unchecked {
if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(int256 x) internal pure returns (int152) {
unchecked {
if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(int256 x) internal pure returns (int160) {
unchecked {
if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(int256 x) internal pure returns (int168) {
unchecked {
if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(int256 x) internal pure returns (int176) {
unchecked {
if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(int256 x) internal pure returns (int184) {
unchecked {
if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(int256 x) internal pure returns (int192) {
unchecked {
if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(int256 x) internal pure returns (int200) {
unchecked {
if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(int256 x) internal pure returns (int208) {
unchecked {
if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(int256 x) internal pure returns (int216) {
unchecked {
if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(int256 x) internal pure returns (int224) {
unchecked {
if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(int256 x) internal pure returns (int232) {
unchecked {
if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(int256 x) internal pure returns (int240) {
unchecked {
if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(int256 x) internal pure returns (int248) {
unchecked {
if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
_revertOverflow();
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(uint256 x) internal pure returns (int8) {
if (x >= 1 << 7) _revertOverflow();
return int8(int256(x));
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(uint256 x) internal pure returns (int16) {
if (x >= 1 << 15) _revertOverflow();
return int16(int256(x));
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(uint256 x) internal pure returns (int24) {
if (x >= 1 << 23) _revertOverflow();
return int24(int256(x));
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(uint256 x) internal pure returns (int32) {
if (x >= 1 << 31) _revertOverflow();
return int32(int256(x));
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(uint256 x) internal pure returns (int40) {
if (x >= 1 << 39) _revertOverflow();
return int40(int256(x));
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(uint256 x) internal pure returns (int48) {
if (x >= 1 << 47) _revertOverflow();
return int48(int256(x));
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(uint256 x) internal pure returns (int56) {
if (x >= 1 << 55) _revertOverflow();
return int56(int256(x));
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(uint256 x) internal pure returns (int64) {
if (x >= 1 << 63) _revertOverflow();
return int64(int256(x));
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(uint256 x) internal pure returns (int72) {
if (x >= 1 << 71) _revertOverflow();
return int72(int256(x));
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(uint256 x) internal pure returns (int80) {
if (x >= 1 << 79) _revertOverflow();
return int80(int256(x));
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(uint256 x) internal pure returns (int88) {
if (x >= 1 << 87) _revertOverflow();
return int88(int256(x));
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(uint256 x) internal pure returns (int96) {
if (x >= 1 << 95) _revertOverflow();
return int96(int256(x));
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(uint256 x) internal pure returns (int104) {
if (x >= 1 << 103) _revertOverflow();
return int104(int256(x));
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(uint256 x) internal pure returns (int112) {
if (x >= 1 << 111) _revertOverflow();
return int112(int256(x));
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(uint256 x) internal pure returns (int120) {
if (x >= 1 << 119) _revertOverflow();
return int120(int256(x));
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(uint256 x) internal pure returns (int136) {
if (x >= 1 << 135) _revertOverflow();
return int136(int256(x));
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(uint256 x) internal pure returns (int144) {
if (x >= 1 << 143) _revertOverflow();
return int144(int256(x));
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(uint256 x) internal pure returns (int152) {
if (x >= 1 << 151) _revertOverflow();
return int152(int256(x));
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(uint256 x) internal pure returns (int160) {
if (x >= 1 << 159) _revertOverflow();
return int160(int256(x));
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(uint256 x) internal pure returns (int168) {
if (x >= 1 << 167) _revertOverflow();
return int168(int256(x));
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(uint256 x) internal pure returns (int176) {
if (x >= 1 << 175) _revertOverflow();
return int176(int256(x));
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(uint256 x) internal pure returns (int184) {
if (x >= 1 << 183) _revertOverflow();
return int184(int256(x));
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(uint256 x) internal pure returns (int192) {
if (x >= 1 << 191) _revertOverflow();
return int192(int256(x));
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(uint256 x) internal pure returns (int200) {
if (x >= 1 << 199) _revertOverflow();
return int200(int256(x));
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(uint256 x) internal pure returns (int208) {
if (x >= 1 << 207) _revertOverflow();
return int208(int256(x));
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(uint256 x) internal pure returns (int216) {
if (x >= 1 << 215) _revertOverflow();
return int216(int256(x));
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(uint256 x) internal pure returns (int224) {
if (x >= 1 << 223) _revertOverflow();
return int224(int256(x));
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(uint256 x) internal pure returns (int232) {
if (x >= 1 << 231) _revertOverflow();
return int232(int256(x));
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(uint256 x) internal pure returns (int240) {
if (x >= 1 << 239) _revertOverflow();
return int240(int256(x));
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(uint256 x) internal pure returns (int248) {
if (x >= 1 << 247) _revertOverflow();
return int248(int256(x));
}
/// @dev Casts `x` to a int256. Reverts on overflow.
function toInt256(uint256 x) internal pure returns (int256) {
if (int256(x) >= 0) return int256(x);
_revertOverflow();
}
/// @dev Casts `x` to a uint256. Reverts on overflow.
function toUint256(int256 x) internal pure returns (uint256) {
if (x >= 0) return uint256(x);
_revertOverflow();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
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";
import { SafeCastLib } from "solady/utils/SafeCastLib.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, each Normie's balance, registrations, agent
* links, rounds and skin purchases. Authorized writers (the Arena logic contracts) change the records through
* the setters below. The game rules live in the logic contracts.
*
* Lazy charging. There is no line and no admission. A paid round is played by every active Normie (registered,
* not short) whose balance covers its price when it starts, and charging them writes nothing per Normie. The
* storage keeps the running total C of the prices of all started rounds (cumulativeAt) and, for each Normie, a
* level L = balance + C at its last change. A registered Normie is active while L >= C: its balance is L - C.
* Starting a paid round at price p raises C by p. Active Normies with L < C + p cannot cover it: they sit out
* ("short") and keep their leftover L - C, and the round's players are the active Normies left. To count the
* Normies that drop out, active Normies are counted per level in 16-bit lanes, sixteen to a slot; only lanes at
* or above C are live, since C never decreases and every live level is at or above it. A short Normie plays
* again after any top-up or credit. A free round charges nothing and is played by every registered Normie,
* short or not.
*
* A Normie that joins or tops up while a round is open is written at the current C, which already includes
* that round's price, so it neither pays for nor plays that round.
*
* Normie states: unregistered (may hold a balance credited to it, frozen), active, short (frozen leftover),
* cleared (burned and taken out by clear; frozen balance, which only rescue moves). Only the queue registers
* a Normie, for its holder or a delegate; nothing registers one on anyone's behalf.
*
* Custody: every Arena pixel sits in this contract's wallet balance on the pixel ledger, either in a
* Normie's balance (totalAllocated, always the exact sum of balanceOf) or in a round's unpaid pool
* (totalPooled). Pixels leave only from this contract's own address: withdraw (a Normie's holder or a
* delegate, paid to the holder), rescue (owner, a burned Normie's balance), sweep (owner, surplus only) and
* the writer setter releaseSponsorship.
*
* 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.
*/
contract NormiesArenaStorage is NormiesAccess, ReentrancyGuard, Lifebuoy {
using SafeCastLib for uint256;
/// @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 price, 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 record. One slot.
struct Normie {
/// @dev Active: balance + C at the last change. Any other state: the balance itself.
uint64 level;
/// @dev currentRound at the last change.
uint32 checkpoint;
/// @dev Registered by its holder (join or deposit) and not cleared.
bool registered;
/// @dev Burned and taken out by clear. Final.
bool cleared;
/// @dev Registered but sat out a paid round it could not cover; `level` is its leftover balance.
bool short_;
/// @dev Whether it played round `checkpoint`.
bool inRound;
/// @dev Linked to an agent (agentOf).
bool linked;
}
/// @notice A round's record.
struct Round {
/// @dev Sponsored pixels, including any rolled in from the previous round.
uint128 sponsorship;
/// @dev Entry pixels charged when the round started: players * price.
uint128 fees;
/// @dev Pixels of the pool not yet credited, rolled forward or released.
uint128 unpaid;
/// @dev Pixels credited from the pool so far.
uint128 paid;
/// @dev C after the round started.
uint64 cumulative;
/// @dev Players when it started.
uint32 players;
/// @dev Entry price; zero for a free round.
uint16 price;
bool free;
bool started;
bool ended;
bool cancelled;
}
/// @notice The global counters. One slot.
struct Globals {
/// @dev C: the sum of the prices of every started round.
uint64 cumulative;
/// @dev The latest round started. Zero before round 1.
uint32 currentRound;
/// @dev Registered Normies (not cleared).
uint32 registeredCount;
/// @dev Active Normies: registered, not short, level >= C.
uint32 activeCount;
/// @dev Whether round currentRound is free.
bool currentFree;
}
/// @notice Normie states reported in Leveled.
uint8 public constant STATE_UNREGISTERED = 0;
uint8 public constant STATE_ACTIVE = 1;
uint8 public constant STATE_SHORT = 2;
uint8 public constant STATE_CLEARED = 3;
/// @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 Highest entry price of a round. Bounds the lanes startRound reads.
uint256 public constant MAX_PRICE = 10_000;
/// @notice Most entries in one withdrawBatch or clearBatch. Measured on the real ledger after 520 rounds (half the
/// entries lazily short, fresh holders): withdrawBatch 10.3M gas. A short Normie's leftover search grows by
/// one storage read each time the number of rounds doubles.
uint256 public constant MAX_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 Sum of all Normie balances.
uint128 public totalAllocated;
/// @notice Sum of every round's unpaid pool.
uint128 public totalPooled;
/// @dev The global counters.
Globals internal _g;
/// @dev Each Normie's record.
mapping(uint256 => Normie) internal _normies;
/// @dev Active Normies per level: level l is the 16-bit lane l % 16 of slot l / 16.
mapping(uint256 => uint256) internal _lanes;
/// @dev Each round's record.
mapping(uint256 => Round) internal _rounds;
/// @notice The agent each Normie is linked to.
mapping(uint256 => uint256) public agentOf;
/// @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 Normie `id` was registered during round `round` (it plays from the next round started).
event Registered(uint256 indexed id, uint256 round);
/// @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 `amount` pixels of `round`'s pool were added to Normie `id`'s balance, as a refund or a prize.
event Credited(uint256 indexed round, uint256 indexed id, uint256 amount, bool refund);
/// @notice Burned Normie `id` was taken out of the game with `balance` pixels left.
event Cleared(uint256 indexed id, uint256 balance);
/// @notice The balance of burned Normie `id`, `amount` pixels, was sent to `to`.
event Rescued(uint256 indexed id, address indexed to, uint256 amount);
/// @notice Normie `id`'s record after a change: its balance, its level and its state (STATE_*). An active
/// Normie's balance falls by each later paid round's price while level >= C; readers derive charges and
/// drop-outs from RoundStarted.
event Leveled(uint256 indexed id, uint256 balance, uint256 level, uint8 state);
/// @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 pool were paid out to `to`.
event SponsorshipReleased(uint256 indexed round, address indexed to, uint256 amount);
/// @notice Normie `id` was linked to agent `agentId`.
event AgentLinked(uint256 indexed id, uint256 indexed agentId);
/// @notice `round` started at `price` (zero when free) with `players` players, charging `fees` pixels in total.
/// C is now `cumulative`. `at` is the block time, recorded for readers only.
event RoundStarted(
uint256 indexed round, uint256 price, bool free, uint256 players, uint256 fees, uint256 cumulative, uint256 at
);
/// @notice `round` ended: `paid` pixels were credited from its pool and `rolled` moved to the next round.
event RoundEnded(uint256 indexed round, uint256 paid, uint256 rolled, uint256 at);
/// @notice `round` was cancelled: `paid` pixels had been credited and `rolled` moved to the next round.
event RoundCancelled(uint256 indexed round, uint256 paid, uint256 rolled, uint256 at);
/// @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);
/// @notice Normie `id`'s skin purchase count was imported as `count`.
event PurchasesImported(uint256 indexed id, uint256 count);
/// @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
/// unstarted pools. 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.
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`, clearing it first if needed. 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(to != address(0), InvalidInput());
require(isBurned(id), NotBurned());
Globals memory g = _g;
Normie memory n = _sync(id, g);
if (!n.cleared) _clear(id, n, g);
uint256 amount = n.level;
require(amount > 0, InvalidInput());
n.level = 0;
totalAllocated -= uint128(amount);
_save(id, n, g);
_g = g;
pixels.moveBalance(address(this), to, amount);
emit Rescued(id, to, amount);
}
// ──────────────────────────────────────────────
// Permissionless
// ──────────────────────────────────────────────
/// @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. A Normie that withdraws
/// below the next price sits out until a top-up or a credit.
function withdraw(uint256 id, uint256 amount) external nonReentrant {
_withdraw(id, amount, _g);
}
/// @notice withdraw for several Normies, up to MAX_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_BATCH, InvalidInput());
Globals memory g = _g;
for (uint256 i; i < ids.length; ++i) {
_withdraw(ids[i], amounts[i], g);
}
}
/// @notice Take burned Normie `id` out of the game: it stops counting as a player, and its balance stays here
/// for rescue. Anyone, at any time. Reverts with NotBurned while it exists and with InvalidState when it
/// was already cleared.
function clear(uint256 id) external {
Globals memory g = _g;
_clearOne(id, g);
_g = g;
}
/// @notice clear for several Normies, up to MAX_BATCH. Reverts entirely if one entry fails.
function clearBatch(uint256[] calldata ids) external {
require(ids.length > 0 && ids.length <= MAX_BATCH, InvalidInput());
Globals memory g = _g;
for (uint256 i; i < ids.length; ++i) {
_clearOne(ids[i], g);
}
_g = g;
}
// ──────────────────────────────────────────────
// Views
// ──────────────────────────────────────────────
/// @notice The holder of Normie `id` when `account` is that holder or one of its delegates. Reverts with
/// Burned for a burned Normie, with 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: ownerOf reverts or returns DEAD. False for ids at or above ID_BOUND.
function isBurned(uint256 id) public view returns (bool) {
return id < ID_BOUND && _holder(id) == address(0);
}
/// @notice Ledger pixels here beyond every balance and unpaid pool.
function surplus() public view returns (uint256) {
uint256 balance = pixels.balanceOf(address(this));
uint256 required = uint256(totalAllocated) + totalPooled;
return balance > required ? balance - required : 0;
}
/// @notice Normie `id`'s balance now.
function balanceOf(uint256 id) external view returns (uint256) {
Globals memory g = _g;
Normie memory n = _sync(id, g);
return _balance(n, g);
}
/// @notice Normie `id`'s state now (STATE_*).
function stateOf(uint256 id) external view returns (uint8) {
return _state(_sync(id, _g));
}
/// @notice Normie `id`'s record as stored. Its level may predate later rounds; use balanceOf and stateOf.
function normieOf(uint256 id) external view returns (Normie memory) {
return _normies[id];
}
/// @notice Whether Normie `id` is registered (and not cleared).
function isRegistered(uint256 id) external view returns (bool) {
return _normies[id].registered;
}
/// @notice Whether Normie `id` is linked to an agent.
function agentBound(uint256 id) external view returns (bool) {
return _normies[id].linked;
}
/// @notice Whether Normie `id` played round currentRound (or is playing it). False before round 1.
function isPlayer(uint256 id) external view returns (bool) {
Globals memory g = _g;
Normie memory n = _normies[id];
if (g.currentRound == 0) return false;
if (n.checkpoint == g.currentRound) return n.inRound;
return n.registered && (g.currentFree || (!n.short_ && n.level >= g.cumulative));
}
/// @notice How many Normies would play a paid round started now at `price`.
function countCovering(uint256 price) external view returns (uint256) {
require(price <= MAX_PRICE, InvalidInput());
Globals memory g = _g;
return g.activeCount - _countRange(g.cumulative, uint256(g.cumulative) + price);
}
/// @notice C: the sum of the prices of every started round.
function cumulative() external view returns (uint256) {
return _g.cumulative;
}
/// @notice C after `round` started; zero for round 0. Only meaningful for started rounds.
function cumulativeAt(uint256 round) public view returns (uint256) {
return round == 0 ? 0 : _rounds[round].cumulative;
}
/// @notice The latest round started. Zero before round 1.
function currentRound() external view returns (uint256) {
return _g.currentRound;
}
/// @notice Whether round currentRound is free.
function currentFree() external view returns (bool) {
return _g.currentFree;
}
/// @notice Registered Normies (not cleared): the players of a free round started now.
function registeredCount() external view returns (uint256) {
return _g.registeredCount;
}
/// @notice Active Normies: registered, not short, with a balance at least as high as the last paid price left.
function activeCount() external view returns (uint256) {
return _g.activeCount;
}
/// @notice `round`'s record.
function roundOf(uint256 round) external view returns (Round memory) {
return _rounds[round];
}
/// @notice `round`'s pool: its sponsorship plus its entry fees.
function poolOf(uint256 round) external view returns (uint256) {
return uint256(_rounds[round].sponsorship) + _rounds[round].fees;
}
/// @notice Whether `round` has started and is neither ended nor cancelled.
function isOpen(uint256 round) public view returns (bool) {
Round storage r = _rounds[round];
return r.started && !r.ended && !r.cancelled;
}
// ──────────────────────────────────────────────
// Writers: Normies
// ──────────────────────────────────────────────
/// @notice Register Normie `id`: it plays every free round and, while active with a balance that covers the
/// price, every paid round, from the next round started. A balance credited to it while unregistered
/// comes with it. Writers only (the queue checks holder and agent link). Reverts with InvalidState
/// when it is already registered or cleared.
function register(uint256 id) external onlyWriter {
require(id < ID_BOUND, InvalidInput());
Globals memory g = _g;
Normie memory n = _sync(id, g);
require(!n.registered && !n.cleared, InvalidState());
_register(id, n, g, 0);
_save(id, n, g);
_g = g;
}
/// @notice Add `amount` pixels from `from` to Normie `id`'s balance. Writers only. With `register_`, an
/// unregistered Normie is registered too; without it, it keeps the pixels unregistered (migration). A
/// short Normie plays again from the next round. The pixels must already be in this contract's ledger
/// balance, or the backing check reverts with BackingShortfall. Reverts with InvalidState for a cleared
/// Normie.
function deposit(uint256 id, address from, uint256 amount, bool register_) external onlyWriter {
require(id < ID_BOUND && amount > 0, InvalidInput());
Globals memory g = _g;
Normie memory n = _sync(id, g);
require(!n.cleared, InvalidState());
if (!n.registered && register_) _register(id, n, g, amount);
else _add(n, g, amount);
totalAllocated += amount.toUint128();
_checkBacking();
emit Deposited(id, from, amount);
_save(id, n, g);
_g = g;
}
/// @notice Link Normie `id` to agent `agentId`. Writers only.
function linkAgent(uint256 id, uint256 agentId) external onlyWriter {
require(id < ID_BOUND, InvalidInput());
agentOf[id] = agentId;
_normies[id].linked = true;
emit AgentLinked(id, agentId);
}
// ──────────────────────────────────────────────
// Writers: pools
// ──────────────────────────────────────────────
/// @notice Add `amount` pixels from `from` to `round`'s pool. Writers only, for a round above zero that is
/// neither ended 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 = _rounds[round];
require(round > 0 && !r.ended && !r.cancelled, InvalidState());
require(amount > 0, InvalidInput());
uint128 a = amount.toUint128();
r.sponsorship += a;
r.unpaid += a;
totalPooled += a;
_checkBacking();
emit Sponsored(round, from, amount);
}
/// @notice Pay `amount` pixels of the pool of `round`, which has not started, to `to`. Writers only.
function releaseSponsorship(uint256 round, address to, uint256 amount) external onlyWriter nonReentrant {
Round storage r = _rounds[round];
require(!r.started, InvalidState());
require(to != address(0) && amount > 0 && amount <= r.unpaid, InvalidInput());
uint128 a = uint128(amount);
r.sponsorship -= a;
r.unpaid -= a;
totalPooled -= a;
pixels.moveBalance(address(this), to, amount);
emit SponsorshipReleased(round, to, amount);
}
// ──────────────────────────────────────────────
// Writers: rounds
// ──────────────────────────────────────────────
/**
* @notice Start `round` at `price`, or free. Writers only. `round` must be currentRound + 1, and the current
* round ended or cancelled. A paid round (price 1 to MAX_PRICE) is played by every active Normie whose
* balance covers the price, each charged the price; the others sit out. A free round (price 0) is
* played by every registered Normie and charges nothing.
*/
function startRound(uint256 round, uint256 price, bool free) external onlyWriter {
Globals memory g = _g;
uint256 previous = g.currentRound;
require(round == previous + 1, InvalidState());
if (previous != 0) require(_rounds[previous].ended || _rounds[previous].cancelled, InvalidState());
require(free ? price == 0 : price > 0 && price <= MAX_PRICE, InvalidInput());
Round storage r = _rounds[round];
uint256 players;
uint256 fees;
if (free) {
players = g.registeredCount;
} else {
uint256 next = uint256(g.cumulative) + price;
players = g.activeCount - _countRange(g.cumulative, next);
fees = players * price;
g.cumulative = next.toUint64();
g.activeCount = uint32(players);
totalAllocated -= uint128(fees);
totalPooled += uint128(fees);
r.fees = uint128(fees);
r.unpaid += uint128(fees);
}
g.currentRound = uint32(round);
g.currentFree = free;
r.cumulative = g.cumulative;
r.players = uint32(players);
r.price = uint16(price);
r.free = free;
r.started = true;
_g = g;
emit RoundStarted(round, price, free, players, fees, g.cumulative, block.timestamp);
}
/**
* @notice Credit from the pool of `round`, which must be open: first the round's price to each of `refundees`,
* then `amounts[i]` to each of `winners[i]`. Writers only. Reverts with InvalidState when the total
* exceeds the unpaid pool. Zero credits are skipped. A credit to a short Normie lets it play again; a
* credit to an unregistered Normie stays with it until its holder registers it.
*/
function payout(
uint256 round,
uint256[] calldata refundees,
uint256[] calldata winners,
uint256[] calldata amounts
) external onlyWriter {
require(winners.length == amounts.length, InvalidInput());
Round storage r = _rounds[round];
Globals memory g = _g;
require(round == g.currentRound && isOpen(round), InvalidState());
uint256 price = r.price;
uint256 total;
if (price != 0) {
for (uint256 i; i < refundees.length; ++i) {
_credit(round, refundees[i], price, true, g);
}
total = refundees.length * price;
}
for (uint256 i; i < winners.length; ++i) {
uint256 amount = amounts[i];
if (amount == 0) continue;
_credit(round, winners[i], amount, false, g);
total += amount;
}
require(total <= r.unpaid, InvalidState());
uint128 t = uint128(total);
r.unpaid -= t;
r.paid += t;
totalPooled -= t;
totalAllocated += t;
_g = g;
}
/// @notice End `round`, which must be open, and roll its unpaid pool into round + 1. Writers only.
function endRound(uint256 round) external onlyWriter {
require(round == _g.currentRound && isOpen(round), InvalidState());
_rounds[round].ended = true;
uint256 rolled = _roll(round);
emit RoundEnded(round, _rounds[round].paid, rolled, block.timestamp);
}
/// @notice Cancel `round`, which must be open, and roll its unpaid pool into round + 1. Credits already made
/// stay; nothing is refunded and C stays as it is. Writers only.
function cancelRound(uint256 round) external onlyWriter {
require(round == _g.currentRound && isOpen(round), InvalidState());
_rounds[round].cancelled = true;
uint256 rolled = _roll(round);
emit RoundCancelled(round, _rounds[round].paid, rolled, block.timestamp);
}
// ──────────────────────────────────────────────
// Writers: skins
// ──────────────────────────────────────────────
/// @notice Record a skin purchase for Normie `id`. Writers only.
function recordPurchase(uint256 id, address buyer, uint256 price) external onlyWriter {
++purchased[id];
emit SkinPurchased(++purchaseCount, id, buyer, price);
}
/// @notice Set Normie `id`'s skin purchase count to `count` (migration). Writers only, before round 1.
function importPurchases(uint256 id, uint256 count) external onlyWriter {
require(_g.currentRound == 0, InvalidState());
require(id < ID_BOUND, InvalidInput());
purchaseCount = purchaseCount - purchased[id] + count;
purchased[id] = count;
emit PurchasesImported(id, count);
}
// ──────────────────────────────────────────────
// Internal: Normies
// ──────────────────────────────────────────────
/**
* @dev Normie `id`'s record brought up to round currentRound, in memory: records whether it played that round,
* turns a Normie that dropped out of a paid round since its last change into a short one with its leftover
* balance, and moves its checkpoint to currentRound. After this an active Normie has level >= C, and
* every other state holds its balance in level.
*/
function _sync(uint256 id, Globals memory g) internal view returns (Normie memory n) {
n = _normies[id];
uint256 checkpoint = n.checkpoint;
if (checkpoint == g.currentRound) return n;
// Nothing changed this Normie since before round currentRound started, so its level then is its level now.
bool coveredNow = !n.short_ && n.level >= g.cumulative;
n.inRound = n.registered && (g.currentFree || coveredNow);
if (n.registered && !n.short_ && !coveredNow) {
n.level = uint64(n.level - _cumulativeBefore(n.level, checkpoint, g.currentRound));
n.short_ = true;
}
n.checkpoint = g.currentRound;
}
/// @dev C just before the round the Normie at `level` dropped out of: the highest cumulativeAt(r) <= level for
/// r in [low, high). cumulativeAt(low) <= level holds since the Normie was active at round `low`, and
/// cumulativeAt(high) > level since it is not active now.
function _cumulativeBefore(uint256 level, uint256 low, uint256 high) internal view returns (uint256) {
// Invariant: cumulativeAt(low) <= level < cumulativeAt(high).
while (high - low > 1) {
uint256 mid = (low + high) >> 1;
if (_rounds[mid].cumulative <= level) low = mid;
else high = mid;
}
return cumulativeAt(low);
}
/// @dev The balance of a record returned by _sync.
function _balance(Normie memory n, Globals memory g) internal pure returns (uint256) {
return n.registered && !n.short_ ? n.level - g.cumulative : n.level;
}
/// @dev The state of a record returned by _sync.
function _state(Normie memory n) internal pure returns (uint8) {
if (n.cleared) return STATE_CLEARED;
if (!n.registered) return STATE_UNREGISTERED;
return n.short_ ? STATE_SHORT : STATE_ACTIVE;
}
/// @dev Registers an unregistered record and makes it active with its frozen balance plus `amount`.
function _register(uint256 id, Normie memory n, Globals memory g, uint256 amount) internal {
n.registered = true;
++g.registeredCount;
_activate(n, g, uint256(n.level) + amount);
emit Registered(id, g.currentRound);
}
/// @dev Adds `amount` to a synced record's balance. A short Normie becomes active again.
function _add(Normie memory n, Globals memory g, uint256 amount) internal {
if (!n.registered) {
n.level = (uint256(n.level) + amount).toUint64();
} else if (n.short_) {
_activate(n, g, uint256(n.level) + amount);
} else {
_move(n, uint256(n.level) + amount);
}
}
/// @dev Makes a registered record active with `balance`.
function _activate(Normie memory n, Globals memory g, uint256 balance) internal {
n.short_ = false;
n.level = (balance + g.cumulative).toUint64();
_laneAdd(n.level);
++g.activeCount;
}
/// @dev Moves an active record to `level`.
function _move(Normie memory n, uint256 level) internal {
_laneSub(n.level);
n.level = level.toUint64();
_laneAdd(n.level);
}
/// @dev Pays `amount` of Normie `id`'s balance to its holder. Never changes the global counters, so callers
/// need not write `g` back.
function _withdraw(uint256 id, uint256 amount, Globals memory g) internal {
address holder = holderFor(id, msg.sender);
Normie memory n = _sync(id, g);
require(amount > 0 && amount <= _balance(n, g), InvalidInput());
if (n.registered && !n.short_) _move(n, n.level - amount);
else n.level -= uint64(amount);
totalAllocated -= uint128(amount);
_save(id, n, g);
pixels.moveBalance(address(this), holder, amount);
emit Withdrawn(id, holder, amount);
}
/// @dev Credits `amount` of `round`'s pool to Normie `id`. The pool totals are the caller's.
function _credit(uint256 round, uint256 id, uint256 amount, bool refund, Globals memory g) internal {
require(id < ID_BOUND, InvalidInput());
Normie memory n = _sync(id, g);
if (n.cleared) n.level = (uint256(n.level) + amount).toUint64();
else _add(n, g, amount);
emit Credited(round, id, amount, refund);
_save(id, n, g);
}
/// @dev Clears burned Normie `id`.
function _clearOne(uint256 id, Globals memory g) internal {
require(isBurned(id), NotBurned());
Normie memory n = _sync(id, g);
require(!n.cleared, InvalidState());
_clear(id, n, g);
_save(id, n, g);
}
/// @dev Takes a synced record out of the game, freezing its balance in level.
function _clear(uint256 id, Normie memory n, Globals memory g) internal {
if (n.registered) {
if (!n.short_) {
_laneSub(n.level);
--g.activeCount;
n.level -= g.cumulative;
}
--g.registeredCount;
}
n.registered = false;
n.short_ = false;
n.cleared = true;
emit Cleared(id, n.level);
}
/// @dev Writes a record and reports it.
function _save(uint256 id, Normie memory n, Globals memory g) internal {
_normies[id] = n;
emit Leveled(id, _balance(n, g), n.level, _state(n));
}
// ──────────────────────────────────────────────
// Internal: lanes, pools
// ──────────────────────────────────────────────
/// @dev One more active Normie at `level`. Live lanes never exceed ID_BOUND, so a lane cannot overflow.
function _laneAdd(uint256 level) internal {
unchecked {
_lanes[level >> 4] += uint256(1) << ((level & 15) << 4);
}
}
/// @dev One fewer active Normie at `level`, which holds at least one.
function _laneSub(uint256 level) internal {
unchecked {
_lanes[level >> 4] -= uint256(1) << ((level & 15) << 4);
}
}
/// @dev Active Normies with a level in [from, to), for from >= C (only lanes at or above C are live).
function _countRange(uint256 from, uint256 to) internal view returns (uint256 total) {
if (to <= from) return 0;
unchecked {
uint256 last = to - 1;
uint256 firstSlot = from >> 4;
uint256 lastSlot = last >> 4;
for (uint256 s = firstSlot; s <= lastSlot; ++s) {
uint256 w = _lanes[s];
if (w == 0) continue;
if (s == firstSlot) w &= type(uint256).max << ((from & 15) << 4);
if (s == lastSlot) {
uint256 top = ((last & 15) + 1) << 4;
if (top < 256) w &= (uint256(1) << top) - 1;
}
total += _sumLanes(w);
}
}
}
/// @dev Sum of the sixteen 16-bit lanes of `w`.
function _sumLanes(uint256 w) internal pure returns (uint256) {
unchecked {
w = (w & 0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff)
+ ((w >> 16) & 0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff);
w = (w & 0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff)
+ ((w >> 32) & 0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff);
w = (w & 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff)
+ ((w >> 64) & 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff);
return (w & type(uint128).max) + (w >> 128);
}
}
/// @dev Moves `round`'s unpaid pool to round + 1 as sponsorship.
function _roll(uint256 round) internal returns (uint256 rolled) {
Round storage r = _rounds[round];
rolled = r.unpaid;
if (rolled == 0) return 0;
r.unpaid = 0;
Round storage next = _rounds[round + 1];
next.sponsorship += uint128(rolled);
next.unpaid += uint128(rolled);
emit SponsorshipMoved(round, round + 1, rolled);
}
/// @dev The holder of `id`, or zero when it is burned.
function _holder(uint256 id) internal view returns (address) {
try collection.ownerOf(id) returns (address holder) {
return holder == DEAD ? address(0) : holder;
} catch {
return address(0);
}
}
/// @dev Reverts with BackingShortfall unless the ledger balance covers every balance and unpaid pool.
function _checkBacking() internal view {
uint256 balance = pixels.balanceOf(address(this));
uint256 required = uint256(totalAllocated) + totalPooled;
require(balance >= required, BackingShortfall(balance, required));
}
}
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.