Skip to content
Verified contractExactMIT

Vault

Address0xdaf6e42547acd2869a334d4250ea2d2da57f46a7
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,306,768
Creation transaction
0x8621220612…5855473857

src/Vault.sol

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

import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { ERC1967Utils } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { IKernel } from "./interfaces/IKernel.sol";
import { IVault } from "./interfaces/IVault.sol";
import { ICoin } from "./interfaces/ICoin.sol";
import { ICatalog } from "./interfaces/ICatalog.sol";
import {
    CheckpointStatus,
    CollectionPolicy,
    CoreConfiguration,
    CoreState,
    LevelPolicy,
    MiningAccounting,
    MiningConfiguration,
    MiningInitConfig,
    MiningState,
    Position,
    RoundPage,
    WeightActivation
} from "./types/Records.sol";

interface IDelayed {
    function getMinDelay() external view returns (uint256);
}

/// @dev Pure per-position accrual arithmetic (128-bit fixed point reward index).
library Accrual {
    uint256 internal constant PRECISION = 1 << 128;

    /// @dev Fold a pending weight in at the reward index observed when its round activated.
    function activate(Position memory p, uint256 activationIndex) internal pure {
        p.accruedScaled += (activationIndex - p.lastIndex) * p.activeWeight;
        p.activeWeight += p.pendingWeight;
        p.pendingWeight = 0;
        p.pendingRound = 0;
        p.lastIndex = activationIndex;
    }

    function accrue(Position memory p, uint256 rewardIndex) internal pure {
        p.accruedScaled += (rewardIndex - p.lastIndex) * p.activeWeight;
        p.lastIndex = rewardIndex;
    }

    function split(uint256 scaled) internal pure returns (uint256 whole, uint256 rest) {
        whole = scaled / PRECISION;
        rest = scaled % PRECISION;
    }
}

/// @dev Namespaced storage, errors, guards and tier-book helpers shared by the vault implementation.
abstract contract VaultState is IVault {
    error BindingCallFailed();
    error BootstrapAlreadyComplete();
    error BootstrapIncomplete();
    error ClonesAlreadyBound();
    error CollectionNotBound(uint8 collection);
    error CooldownActive(uint256 tokenId, uint64 nextMergeBlock);
    error CoreFutureRound();
    error CoreIdentityMismatch();
    error CoreInconsistent();
    error CoreNotFresh();
    error CorePaused();
    error CoreRegression();
    error CoreUnavailable();
    error CustodyShortfall();
    error InvalidBounds();
    error InvalidClaim();
    error InvalidCollection();
    error InvalidConfiguration();
    error InvalidGraphAdmin();
    error InvalidHistory();
    error InvalidImplementationCodeAddress();
    error InvalidMerge();
    error InvalidPosition();
    error InvalidProxyAdmin();
    error InvalidToken();
    error MintMismatch();
    error PendingActivation(uint256 tokenId, uint64 round);
    error ReentrantCall();
    error RoundNotSettled(uint64 round);
    error TokenSupplyMismatch();
    error Unauthorized();

    struct TierBook {
        address nft;
        uint16 maxSupply;
        uint8 maximumLevel;
        LevelPolicy[] levels;
    }

    struct Ledger {
        address core;
        bytes32 streamId;
        address governance;
        address token;
        uint64 minimumTimelockDelay;
        address bootstrapAuthority;
        bool bootstrapped;
        uint8 policyCount;
        uint256 reentrancy;

        uint256 minted;
        uint256 paid;
        uint256 totalWeight;
        uint256 rewardIndex;
        uint64 closedThroughBlock;
        uint64 lastActivationRound;
        uint64 processedThroughRound;
        uint64 closedCumulativeWork;
        uint96 closedCumulativeBlockUnits;
        uint32 closedWorkPerThousandBlocks;
        uint256 closedResidual;
        uint256 openResidualScaled;
        WeightActivation[] activations;
        uint256 activationCursor;
        mapping(uint64 round => uint256 rewardIndex) activationIndex;
        mapping(uint8 collection => TierBook book) books;
        mapping(uint8 collection => mapping(uint256 tokenId => Position position)) positions;
    }

    bytes32 private constant LEDGER_SLOT = keccak256("squeek.mining.storage.v6");

    uint8 internal constant TIER_LIMIT_VALUE = 10;
    uint8 internal constant GENESIS_BOOK = 0;
    uint8 internal constant CLONES_BOOK = 1;

    function _ledger() internal pure returns (Ledger storage l) {
        bytes32 slot = LEDGER_SLOT;

        assembly ("memory-safe") {
            l.slot := slot
        }
    }

    // ---- guards ----

    function _enter() internal {
        Ledger storage l = _ledger();
        if (l.reentrancy == 1) revert ReentrantCall();
        l.reentrancy = 1;
    }

    function _exit() internal {
        _ledger().reentrancy = 0;
    }

    function _requireSteward() internal view {
        if (msg.sender != _ledger().governance) revert Unauthorized();
    }

    function _requireAttached() internal view {
        if (!_ledger().bootstrapped) revert BootstrapIncomplete();
    }

    // ---- tier books ----

    function _book(Ledger storage l, uint8 collection) internal view returns (TierBook storage book) {
        book = l.books[collection];
        if (book.nft == address(0)) revert CollectionNotBound(collection);
    }

    function _bookOf(Ledger storage l, address nft) internal view returns (uint8) {
        for (uint8 collection; collection < l.policyCount; ++collection) {
            if (l.books[collection].nft == nft) return collection;
        }
        revert Unauthorized();
    }

    function _tier(Ledger storage l, uint8 collection, uint8 level) internal view returns (LevelPolicy storage) {
        TierBook storage book = _book(l, collection);
        if (level == 0 || level > book.maximumLevel) revert InvalidBounds();
        return book.levels[level - 1];
    }

    function _writeTiers(TierBook storage book, uint64[] calldata weights, uint64[] calldata cooldowns) internal {
        if (weights.length == 0 || weights.length > TIER_LIMIT_VALUE || cooldowns.length + 1 != weights.length) {
            revert InvalidConfiguration();
        }
        uint64 previous;
        for (uint256 index; index < weights.length; ++index) {
            if (weights[index] <= previous) revert InvalidConfiguration();
            previous = weights[index];
            book.levels.push(
                LevelPolicy({ weight: weights[index], cooldownBlocks: index + 1 < weights.length ? cooldowns[index] : 0 })
            );
        }
        book.maximumLevel = uint8(weights.length);
    }

    function _announceBook(uint8 collection, TierBook storage book) internal {
        uint256 count = book.levels.length;
        uint64[] memory weights = new uint64[](count);
        uint64[] memory cooldowns = new uint64[](count - 1);
        for (uint256 index; index < count; ++index) {
            weights[index] = book.levels[index].weight;
            if (index + 1 < count) cooldowns[index] = book.levels[index].cooldownBlocks;
        }
        emit CollectionPolicyUpdated(collection, book.nft, book.maximumLevel, weights, cooldowns);
    }

    // ---- kernel reads ----

    function _kernelProfile(address kernelAddress) internal view returns (CoreConfiguration memory) {
        try IKernel(kernelAddress).profile() returns (CoreConfiguration memory result) {
            return result;
        } catch {
            revert CoreUnavailable();
        }
    }

    function _kernelSnapshot(address kernelAddress) internal view returns (CoreState memory) {
        try IKernel(kernelAddress).snapshot() returns (CoreState memory result) {
            return result;
        } catch {
            revert CoreUnavailable();
        }
    }
}

contract Vault is Initializable, VaultState {
    using SafeCast for uint256;
    using SafeERC20 for IERC20;
    using Accrual for Position;

    uint16 private constant REDEEM_LIMIT_VALUE = 32;
    uint16 private constant ROLL_LIMIT_VALUE = 32;
    uint256 private constant BLOCK_YIELD_VALUE = 5_600 ether;
    uint256 private constant CEILING_VALUE = 2_100_000_000 ether;
    uint96 private constant UNITS_PER_BLOCK = 1_000_000_000;
    uint64 private constant REVISION = 6;
    bytes32 private constant SCHEMA_HASH = 0xace564e9c052f30122779a32fdf3333ebce7cc708eae9c01cb7875b4f6ad37a6;

    address private immutable _LOGIC = address(this);

    constructor() {
        _disableInitializers();
    }

    // ------------------------------------------------------------------------------------------------
    // lifecycle
    // ------------------------------------------------------------------------------------------------

    function boot(MiningInitConfig calldata config) external initializer {
        if (address(this) == _LOGIC || ERC1967Utils.getImplementation() != _LOGIC) {
            revert InvalidImplementationCodeAddress();
        }
        if (ERC1967Utils.getAdmin() != address(0)) revert InvalidProxyAdmin();
        if (config.core == address(0) || config.core.code.length == 0 || config.streamId == bytes32(0)) {
            revert InvalidConfiguration();
        }
        if (_kernelProfile(config.core).streamId != config.streamId) revert CoreIdentityMismatch();
        CoreState memory kernelState = _kernelSnapshot(config.core);
        if (kernelState.settledThroughRound != 0 || kernelState.cumulativeBlockUnits != 0) revert CoreNotFresh();
        _screenSteward(config);

        Ledger storage l = _ledger();
        l.core = config.core;
        l.streamId = config.streamId;
        l.governance = config.governance;
        l.minimumTimelockDelay = config.minimumTimelockDelay;
        l.bootstrapAuthority = msg.sender;
        _writeTiers(l.books[GENESIS_BOOK], config.levelWeights, config.cooldownBlocks);
        l.policyCount = 1;

        emit MiningInitialized(config.core, config.streamId, config.governance);
    }

    function attach(address token_, address genesisNft) external {
        Ledger storage l = _ledger();
        if (msg.sender != l.bootstrapAuthority) revert Unauthorized();
        if (l.bootstrapped) revert BootstrapAlreadyComplete();
        _screenCoin(token_);
        if (genesisNft == address(0) || genesisNft.code.length == 0 || genesisNft == token_) revert InvalidCollection();
        ICatalog nft = ICatalog(genesisNft);
        if (nft.vault() != address(this) || nft.kernel() != l.core || nft.totalSupply() != 0) {
            revert InvalidCollection();
        }
        TierBook storage book = l.books[GENESIS_BOOK];
        book.nft = genesisNft;
        book.maxSupply = nft.CAPACITY();
        l.token = token_;
        l.bootstrapped = true;
        l.bootstrapAuthority = address(0);

        emit MiningBootstrapped(token_, genesisNft);
        _announceBook(GENESIS_BOOK, book);
    }

    function enroll(uint256 tokenId) external {
        _requireAttached();
        Ledger storage l = _ledger();
        uint8 collection = _bookOf(l, msg.sender);
        TierBook storage book = l.books[collection];
        if (ICatalog(book.nft).ownerOf(tokenId) == address(0)) revert MintMismatch();
        Position storage stored = l.positions[collection][tokenId];
        if (stored.level != 0) revert InvalidPosition();

        LevelPolicy storage first = book.levels[0];
        uint64 weight = first.weight;
        uint64 firstRound = _roundNow(l) + 1;
        uint64 nextMergeBlock = l.closedThroughBlock + first.cooldownBlocks;
        _schedule(l, firstRound, weight);

        stored.level = 1;
        stored.pendingWeight = weight;
        stored.pendingRound = uint40(firstRound);
        stored.nextMergeBlock = uint48(nextMergeBlock);
        stored.lastIndex = l.rewardIndex;

        emit PositionRegistered(collection, tokenId, firstRound, weight, nextMergeBlock);
    }

    function fuse(uint8 collection, uint256 survivorId, uint256 donorId) external {
        _enter();
        _requireAttached();
        Ledger storage l = _ledger();
        TierBook storage book = _book(l, collection);
        if (survivorId == donorId) revert InvalidMerge();
        ICatalog nft = ICatalog(book.nft);
        if (nft.ownerOf(survivorId) != msg.sender || nft.ownerOf(donorId) != msg.sender) revert InvalidMerge();

        Position memory survivor = _settled(l, l.positions[collection][survivorId]);
        Position memory donor = _settled(l, l.positions[collection][donorId]);
        _screenFuse(l, book, survivor, donor, survivorId, donorId);

        uint8 newLevel = survivor.level + 1;
        LevelPolicy storage target = book.levels[newLevel - 1];
        uint64 effectiveRound = _roundNow(l) + 1;
        uint64 combined = survivor.activeWeight + donor.activeWeight;
        uint64 pending = target.weight > combined ? target.weight - combined : 0;
        uint64 nextMergeBlock = l.closedThroughBlock + target.cooldownBlocks;

        survivor.activeWeight = combined;
        survivor.accruedScaled += donor.accruedScaled;
        survivor.level = newLevel;
        survivor.nextMergeBlock = uint48(nextMergeBlock);
        if (pending != 0) {
            survivor.pendingWeight = pending;
            survivor.pendingRound = uint40(effectiveRound);
            _schedule(l, effectiveRound, pending);
        }
        l.positions[collection][survivorId] = survivor;
        delete l.positions[collection][donorId];
        nft.scrap(donorId);

        emit PositionsMerged(
            collection,
            survivorId,
            donorId,
            newLevel,
            effectiveRound,
            nextMergeBlock,
            combined,
            pending,
            survivor.accruedScaled
        );
        _exit();
    }

    function redeem(uint8 collection, uint256[] calldata tokenIds) external returns (uint256 paid) {
        _enter();
        _requireAttached();
        Ledger storage l = _ledger();
        TierBook storage book = _book(l, collection);
        if (tokenIds.length == 0 || tokenIds.length > REDEEM_LIMIT_VALUE) revert InvalidClaim();
        ICatalog nft = ICatalog(book.nft);
        uint256 remainderScaled;
        for (uint256 index; index < tokenIds.length; ++index) {
            uint256 tokenId = tokenIds[index];
            if (nft.ownerOf(tokenId) != msg.sender) revert InvalidClaim();
            Position storage stored = l.positions[collection][tokenId];
            if (stored.level == 0) revert InvalidPosition();
            Position memory current = _settled(l, stored);
            (uint256 amount, uint256 remainder) = Accrual.split(current.accruedScaled);
            current.accruedScaled = remainder;
            l.positions[collection][tokenId] = current;
            paid += amount;
            remainderScaled += remainder;
        }
        l.paid += paid;
        l.openResidualScaled += remainderScaled;
        IERC20 token = IERC20(l.token);
        if (token.balanceOf(address(this)) < paid) revert CustodyShortfall();
        if (paid != 0) token.safeTransfer(msg.sender, paid);
        emit RewardsClaimed(msg.sender, collection, paid, remainderScaled, tokenIds);
        _exit();
    }

    function roll() external {
        _enter();
        _requireAttached();
        Ledger storage l = _ledger();
        CoreState memory kernelState = _kernelSnapshot(l.core);
        if (kernelState.paused) revert CorePaused();
        uint64 processed = l.processedThroughRound;
        if (kernelState.settledThroughRound < processed) revert CoreRegression();
        if (kernelState.settledThroughRound == processed) revert RoundNotSettled(processed + 1);
        uint64 target = kernelState.settledThroughRound;

        if (!_drain(l, target) && target > l.processedThroughRound) _close(l, target);
        _exit();
    }

    function enlist(address clonesNft, uint64[] calldata levelWeights, uint64[] calldata levelCooldowns) external {
        _requireSteward();
        _requireAttached();
        Ledger storage l = _ledger();
        if (l.policyCount > CLONES_BOOK) revert ClonesAlreadyBound();
        if (clonesNft == address(0) || clonesNft.code.length == 0 || clonesNft == l.books[GENESIS_BOOK].nft) {
            revert InvalidCollection();
        }
        uint256 maxSupply = _probeCatalog(l, clonesNft);
        if (maxSupply == 0 || maxSupply > type(uint16).max) revert InvalidCollection();

        TierBook storage book = l.books[CLONES_BOOK];
        book.nft = clonesNft;
        book.maxSupply = uint16(maxSupply);
        _writeTiers(book, levelWeights, levelCooldowns);
        l.policyCount = CLONES_BOOK + 1;
        _announceBook(CLONES_BOOK, book);
    }

    function growTiers(uint64[] calldata levelWeights, uint64[] calldata levelCooldowns) external {
        _requireSteward();
        Ledger storage l = _ledger();
        TierBook storage book = l.books[CLONES_BOOK];
        if (book.nft == address(0)) revert CollectionNotBound(CLONES_BOOK);
        if (levelWeights.length == 0 || levelWeights.length != levelCooldowns.length) revert InvalidConfiguration();
        if (book.levels.length + levelWeights.length > TIER_LIMIT_VALUE) revert InvalidConfiguration();
        uint64 previousWeight = book.levels[book.levels.length - 1].weight;
        for (uint256 index; index < levelWeights.length; ++index) {
            if (levelWeights[index] <= previousWeight) revert InvalidConfiguration();
            book.levels[book.levels.length - 1].cooldownBlocks = levelCooldowns[index];
            book.levels.push(LevelPolicy({ weight: levelWeights[index], cooldownBlocks: 0 }));
            previousWeight = levelWeights[index];
        }
        book.maximumLevel = uint8(book.levels.length);
        _announceBook(CLONES_BOOK, book);
    }

    // ------------------------------------------------------------------------------------------------
    // limits
    // ------------------------------------------------------------------------------------------------

    function TIER_LIMIT() external pure returns (uint8) {
        return TIER_LIMIT_VALUE;
    }

    function REDEEM_LIMIT() external pure returns (uint16) {
        return REDEEM_LIMIT_VALUE;
    }

    function ROLL_LIMIT() external pure returns (uint16) {
        return ROLL_LIMIT_VALUE;
    }

    function BLOCK_YIELD() external pure returns (uint256) {
        return BLOCK_YIELD_VALUE;
    }

    function PRECISION() external pure returns (uint256) {
        return Accrual.PRECISION;
    }

    function CEILING() external pure returns (uint256) {
        return CEILING_VALUE;
    }

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

    function kernel() external view returns (address) {
        return _ledger().core;
    }

    function bootstrapper() external view returns (address) {
        return _ledger().bootstrapAuthority;
    }

    function profile() external view returns (MiningConfiguration memory result) {
        Ledger storage l = _ledger();
        CoreConfiguration memory kernelProfile = _kernelProfile(l.core);
        TierBook storage genesis = l.books[GENESIS_BOOK];
        result = MiningConfiguration({
            core: l.core,
            streamId: l.streamId,
            governance: l.governance,
            token: l.token,
            genesisCollection: genesis.nft,
            genesisTimestamp: kernelProfile.genesisTimestamp,
            genesisMaxSupply: genesis.maxSupply,
            maxWorkPerRound: kernelProfile.maxWorkPerRound,
            minimumTimelockDelay: l.minimumTimelockDelay,
            supplyCap: uint128(CEILING_VALUE),
            genesisMaximumLevel: genesis.maximumLevel,
            initialWorkPerThousandBlocks: kernelProfile.initialWorkPerThousandBlocks
        });
    }

    function snapshot() external view returns (MiningState memory result) {
        Ledger storage l = _ledger();
        result = MiningState({
            minted: l.minted,
            paid: l.paid,
            totalWeight: l.totalWeight,
            rewardIndex: l.rewardIndex,
            closedThroughBlock: l.closedThroughBlock,
            lastActivationRound: l.lastActivationRound,
            weightActivationCursor: l.activationCursor,
            weightActivationCount: l.activations.length,
            bootstrapped: l.bootstrapped,
            processedThroughRound: l.processedThroughRound,
            closedCumulativeWork: l.closedCumulativeWork,
            closedCumulativeBlockUnits: l.closedCumulativeBlockUnits,
            closedWorkPerThousandBlocks: l.closedWorkPerThousandBlocks
        });
    }

    function books() external view returns (MiningAccounting memory result) {
        Ledger storage l = _ledger();
        result = MiningAccounting({
            closedResidual: l.closedResidual,
            openResidual: l.openResidualScaled / Accrual.PRECISION,
            miningBalance: l.token == address(0) ? 0 : IERC20(l.token).balanceOf(address(this)),
            trackedCustody: l.minted - l.paid
        });
    }

    function rollStatus() external view returns (CheckpointStatus memory result) {
        Ledger storage l = _ledger();
        CoreState memory kernelState = _kernelSnapshot(l.core);
        uint64 nextRound = l.processedThroughRound + 1;
        result = CheckpointStatus({
            corePaused: kernelState.paused,
            nextRound: nextRound,
            roundSettled: kernelState.settledThroughRound >= nextRound
        });
    }

    function tiers(uint8 collection) external view returns (CollectionPolicy memory policy) {
        TierBook storage book = _book(_ledger(), collection);
        policy = CollectionPolicy({
            nft: book.nft,
            maxSupply: book.maxSupply,
            maximumLevel: book.maximumLevel,
            levels: book.levels
        });
    }

    function holding(uint8 collection, uint256 tokenId) external view returns (Position memory) {
        Ledger storage l = _ledger();
        Position storage stored = l.positions[collection][tokenId];
        if (stored.level == 0) revert InvalidPosition();
        return _settled(l, stored);
    }

    function redeemable(uint8 collection, uint256[] calldata tokenIds) external view returns (uint256 amount) {
        Ledger storage l = _ledger();
        uint256 scaled;
        for (uint256 index; index < tokenIds.length; ++index) {
            Position storage stored = l.positions[collection][tokenIds[index]];
            if (stored.level == 0) revert InvalidPosition();
            scaled += _settled(l, stored).accruedScaled;
        }
        amount = scaled / Accrual.PRECISION;
    }

    function queued(uint256 index) external view returns (WeightActivation memory) {
        Ledger storage l = _ledger();
        if (index >= l.activations.length) revert InvalidBounds();
        return l.activations[index];
    }

    function weightOf(uint8 collection, uint8 level) external view returns (uint64) {
        return _tier(_ledger(), collection, level).weight;
    }

    function cooldownOf(uint8 collection, uint8 level) external view returns (uint64) {
        return _tier(_ledger(), collection, level).cooldownBlocks;
    }

    function frozen() external view returns (bool) {
        return _kernelSnapshot(_ledger().core).paused;
    }

    function custodian() external view returns (address) {
        return ERC1967Utils.getAdmin();
    }

    function logic() external view returns (address) {
        return _LOGIC;
    }

    function revision() external pure returns (uint64) {
        return REVISION;
    }

    function schemaHash() external pure returns (bytes32) {
        return SCHEMA_HASH;
    }

    // ------------------------------------------------------------------------------------------------
    // internals
    // ------------------------------------------------------------------------------------------------

    function _screenSteward(MiningInitConfig calldata config) private view {
        if (
            config.governance == address(0) || config.governance.code.length == 0 || config.minimumTimelockDelay == 0
                || config.governance == config.core
        ) revert InvalidGraphAdmin();
        (bool ok, bytes memory ret) = config.governance.staticcall(abi.encodeCall(IDelayed.getMinDelay, ()));
        if (!ok || ret.length < 32 || abi.decode(ret, (uint256)) < config.minimumTimelockDelay) {
            revert InvalidGraphAdmin();
        }
    }

    function _screenCoin(address token_) private view {
        if (token_ == address(0) || token_.code.length == 0) revert InvalidToken();
        ICoin token = ICoin(token_);
        if (token.vault() != address(this) || token.cap() != CEILING_VALUE) revert InvalidToken();
        if (token.totalSupply() != token.SEED_ALLOCATION()) revert TokenSupplyMismatch();
    }

    function _screenFuse(
        Ledger storage l,
        TierBook storage book,
        Position memory survivor,
        Position memory donor,
        uint256 survivorId,
        uint256 donorId
    ) private view {
        if (survivor.level == 0 || donor.level == 0) revert InvalidPosition();
        if (survivor.level != donor.level || survivor.level >= book.maximumLevel) revert InvalidMerge();
        if (survivor.pendingWeight != 0) revert PendingActivation(survivorId, survivor.pendingRound);
        if (donor.pendingWeight != 0) revert PendingActivation(donorId, donor.pendingRound);
        if (survivor.nextMergeBlock > l.closedThroughBlock) revert CooldownActive(survivorId, survivor.nextMergeBlock);
        if (donor.nextMergeBlock > l.closedThroughBlock) revert CooldownActive(donorId, donor.nextMergeBlock);
    }

    /// @dev Static probe of a candidate clones catalog; returns its capacity.
    function _probeCatalog(Ledger storage l, address clonesNft) private view returns (uint256 maxSupply) {
        (bool ok, bytes memory ret) = clonesNft.staticcall(abi.encodeCall(ICatalog.vault, ()));
        if (!ok || ret.length < 32 || abi.decode(ret, (address)) != address(this)) revert BindingCallFailed();
        (ok, ret) = clonesNft.staticcall(abi.encodeCall(ICatalog.kernel, ()));
        if (!ok || ret.length < 32 || abi.decode(ret, (address)) != l.core) revert BindingCallFailed();
        (ok, ret) = clonesNft.staticcall(abi.encodeCall(ICatalog.CAPACITY, ()));
        if (!ok || ret.length < 32) revert BindingCallFailed();
        maxSupply = abi.decode(ret, (uint256));
    }

    /// @dev Activate queued weight up to `target`, at most ROLL_LIMIT entries per call.
    ///      Returns true when the call stopped early because the limit was hit.
    function _drain(Ledger storage l, uint64 target) private returns (bool halted) {
        uint256 handled;
        while (l.activationCursor < l.activations.length && handled < ROLL_LIMIT_VALUE) {
            WeightActivation storage activation = l.activations[l.activationCursor];
            uint64 round = activation.round;
            if (round == 0 || round - 1 > target) break;
            if (round - 1 < l.processedThroughRound) revert InvalidHistory();
            if (round - 1 > l.processedThroughRound) _close(l, round - 1);
            l.totalWeight += activation.addedWeight;
            l.activationIndex[round] = l.rewardIndex;
            l.lastActivationRound = round;
            ++l.activationCursor;
            ++handled;
            emit WeightActivated(round, l.totalWeight, l.rewardIndex);
        }
        if (handled == ROLL_LIMIT_VALUE && l.activationCursor < l.activations.length) {
            WeightActivation storage next = l.activations[l.activationCursor];
            if (next.round - 1 <= target) {
                if (next.round - 1 > l.processedThroughRound) _close(l, next.round - 1);
                return true;
            }
        }
    }

    /// @dev Close the ledger through `throughRound`: mint the completed blocks and move the reward index.
    function _close(Ledger storage l, uint64 throughRound) private {
        uint64 afterRound = l.processedThroughRound;
        RoundPage memory page;
        try IKernel(l.core).window(throughRound, throughRound, 0) returns (RoundPage memory result) {
            page = result;
        } catch {
            revert CoreUnavailable();
        }
        if (page.certifiedThroughRound < throughRound) revert CoreFutureRound();
        if (
            page.start.cumulativeBlockUnits < l.closedCumulativeBlockUnits
                || page.start.cumulativeWork < l.closedCumulativeWork
        ) revert CoreInconsistent();

        uint64 endBlock = uint64(page.start.cumulativeBlockUnits / UNITS_PER_BLOCK);
        uint64 completed = endBlock - l.closedThroughBlock;
        uint256 amount;
        if (completed != 0 && l.totalWeight != 0) amount = _issue(l, throughRound, completed);

        l.closedThroughBlock = endBlock;
        l.processedThroughRound = throughRound;
        l.closedCumulativeWork = page.start.cumulativeWork;
        l.closedCumulativeBlockUnits = page.start.cumulativeBlockUnits;
        l.closedWorkPerThousandBlocks = page.start.workPerThousandBlocks;

        emit Checkpointed(
            afterRound,
            throughRound,
            completed,
            page.start.cumulativeWork,
            page.start.cumulativeBlockUnits,
            amount,
            l.minted,
            l.lastActivationRound,
            l.totalWeight,
            l.rewardIndex
        );
    }

    /// @dev Mint the yield for `completed` blocks (capped by the coin's headroom) and spread it over the weight.
    function _issue(Ledger storage l, uint64 throughRound, uint64 completed) private returns (uint256 amount) {
        amount = uint256(completed) * BLOCK_YIELD_VALUE;
        uint256 remaining = ICoin(l.token).headroom();
        if (amount > remaining) amount = remaining;
        if (amount == 0) return 0;
        l.minted += amount;
        ICoin(l.token).award(throughRound, amount);
        uint256 indexDelta = amount * Accrual.PRECISION / l.totalWeight;
        l.rewardIndex += indexDelta;
        l.closedResidual += amount - indexDelta * l.totalWeight / Accrual.PRECISION;
    }

    function _settled(Ledger storage l, Position storage stored) private view returns (Position memory p) {
        p = stored;
        if (p.pendingWeight != 0 && p.pendingRound <= l.lastActivationRound) {
            p.activate(l.activationIndex[p.pendingRound]);
        }
        p.accrue(l.rewardIndex);
    }

    function _schedule(Ledger storage l, uint64 round, uint64 weight) private {
        uint256 length = l.activations.length;
        if (length != 0 && length > l.activationCursor) {
            WeightActivation storage last = l.activations[length - 1];
            if (last.round == round) {
                last.addedWeight += weight;
                return;
            }
            if (last.round > round) revert InvalidHistory();
        }
        l.activations.push(WeightActivation({ round: round, addedWeight: weight }));
    }

    function _roundNow(Ledger storage l) private view returns (uint64) {
        CoreConfiguration memory kernelProfile = _kernelProfile(l.core);
        return uint64((block.timestamp - kernelProfile.genesisTimestamp) / kernelProfile.roundDuration + 1);
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

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

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/interfaces/ICatalog.sol

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

import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";

interface ICatalog is IERC721 {
    event AllowlistMinted(address indexed account, uint256 indexed firstTokenId, uint8 quantity);
    event AllowlistRootUpdated(bytes32 indexed previousRoot, bytes32 indexed newRoot);
    event AllowlistStartUpdated(uint64 previousStart, uint64 newStart);
    event AllowlistWindowReset(
        bytes32 indexed previousRoot,
        bytes32 indexed newRoot,
        uint64 previousStart,
        uint64 previousEnd,
        uint64 newStart,
        uint64 newEnd
    );
    event MintConfigurationFinalized(bytes32 indexed root, uint64 start, uint64 end);
    event ProtocolReserveMinted(uint256 indexed firstTokenId, uint16 quantity, uint16 reserveMinted);
    event PublicMinted(address indexed account, uint256 indexed firstTokenId, uint8 quantity, uint256 paid);
    event PublicRemainderMinted(uint256 indexed firstTokenId, uint16 quantity, uint16 remaining);
    event PublicSaleClosed(uint16 publicMintedBefore, uint16 remainderAssigned, address indexed recipient);
    event ProceedsSwept(address indexed caller, address indexed recipient, uint256 amount);
    event MetadataUpdate(uint256 _tokenId);
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
    event Paused(address account);
    event Unpaused(address account);

    // ---- limits ----
    function CAPACITY() external pure returns (uint16);
    function OPEN_ALLOCATION() external pure returns (uint16);
    function HELD_ALLOCATION() external pure returns (uint16);
    function OPEN_PRICE() external pure returns (uint256);
    function GATE_PRICE() external pure returns (uint256);
    function GATE_DURATION() external pure returns (uint64);
    function ORDER_LIMIT() external pure returns (uint8);
    function DRAW_LIMIT() external pure returns (uint16);
    function ACCOUNT_LIMIT() external pure returns (uint8);

    // ---- views ----
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function tokenURI(uint256 tokenId) external view returns (string memory);
    function contractURI() external view returns (string memory);
    function totalSupply() external view returns (uint256);
    function issued() external view returns (uint256);
    function scrapped() external view returns (uint16);
    function vault() external view returns (address);
    function kernel() external view returns (address);
    function steward() external view returns (address);
    function warden() external view returns (address);
    function payee() external view returns (address);
    function painter() external view returns (address);
    function plate() external view returns (address);
    function plateCodehash() external view returns (bytes32);
    function plateHash() external view returns (bytes32);
    function kitHash() external view returns (bytes32);
    function entropy() external view returns (bytes32);
    function royaltyRate() external view returns (uint96);
    function frozen() external view returns (bool);
    function stage() external view returns (uint8);
    function burned() external view returns (bool);
    function gateRoot() external view returns (bytes32);
    function gateStart() external view returns (uint64);
    function gateEnd() external view returns (uint64);
    function openIssued() external view returns (uint16);
    function heldIssued() external view returns (uint16);
    function openStarted() external view returns (bool);
    function openClosed() external view returns (bool);
    function leftoverAssigned() external view returns (uint16);
    function leftoverIssued() external view returns (uint16);
    function nextOpenId() external view returns (uint256);
    function nextHeldId() external view returns (uint256);
    function accountIssued(address account) external view returns (uint8 quantity);

    // ---- sale ----
    function obtain(uint8 quantity) external payable;
    function obtainWithProof(uint8 quantity, bytes32[] calldata proof) external payable;
    function drawReserve(uint16 quantity) external;
    function conclude(uint16 quantity) external;
    function drawRemainder(uint16 quantity) external;

    // ---- lifecycle ----
    function scrap(uint256 tokenId) external;
    function freeze() external;
    function thaw() external;
    function flush() external;
    function setGateRoot(bytes32 newRoot) external;
    function setGateStart(uint64 newStart) external;
    function burnnn() external;
    function resetGate(uint64 newStart, bytes32 newRoot) external;
    function announce() external;
}

src/interfaces/ICoin.sol

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

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";

interface ICoin is IERC20, IERC20Permit {
    event CheckpointMinted(uint64 indexed throughRound, uint256 amount, uint256 totalMinted);

    function vault() external view returns (address);
    function cap() external view returns (uint256);
    function SEED_ALLOCATION() external view returns (uint256);
    function headroom() external view returns (uint256);
    function decimals() external view returns (uint8);
    function award(uint64 throughRound, uint256 amount) external returns (uint256);
}

src/interfaces/IKernel.sol

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

import {
    BlockInfo,
    CoreConfiguration,
    CoreLaunchConfig,
    CoreState,
    Round,
    RoundPage
} from "../types/Records.sol";

interface IKernel {
    event CoreInitialized(
        bytes32 indexed streamId,
        address indexed guardian,
        address indexed reporter,
        uint64 genesisTimestamp,
        uint32 initialWorkPerThousandBlocks,
        uint64 maxWorkPerRound
    );
    event RoundRecorded(
        uint64 indexed roundId,
        uint64 work,
        uint64 cumulativeWork,
        uint96 cumulativeBlockUnits,
        uint32 workPerThousandBlocks,
        bytes32 dataHash
    );
    event BatchSettled(
        bytes32 indexed digest,
        address indexed reporter,
        uint64 indexed settledThroughRound,
        uint256 nonce,
        uint64 previousSettledThroughRound,
        uint16 activeRoundCount,
        uint64 cumulativeWork,
        uint96 cumulativeBlockUnits
    );
    event ReporterUpdated(address indexed previousReporter, address indexed newReporter);
    event Paused(address account);
    event Unpaused(address account);
    event EIP712DomainChanged();

    // ---- views ----
    function profile() external view returns (CoreConfiguration memory result);
    function snapshot() external view returns (CoreState memory result);
    function lookup(uint64 squeekBlock) external view returns (BlockInfo memory result);
    function window(uint64 afterRound, uint64 throughRound, uint256 maxRecords)
        external
        view
        returns (RoundPage memory result);
    function everSigner(address candidate) external view returns (bool);
    function frozen() external view returns (bool);
    function custodian() external view returns (address);
    function logic() external view returns (address);
    function revision() external pure returns (uint64);
    function schemaHash() external pure returns (bytes32);
    function hashBatch(
        uint64 previousSettledThroughRound,
        uint64 settledThroughRound,
        Round[] calldata rounds,
        uint256 nonce,
        uint256 deadline
    ) external view returns (bytes32);
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );

    // ---- lifecycle ----
    function boot(CoreLaunchConfig calldata config) external;
    function advance(
        Round[] calldata rounds,
        uint64 settledThroughRound,
        uint256 expectedNonce,
        uint256 deadline,
        bytes calldata signature
    ) external;
    function freeze() external;
    function thaw() external;
    function rotateSigner(address newReporter) external;
}

src/interfaces/IVault.sol

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

import {
    CheckpointStatus,
    CollectionPolicy,
    MiningAccounting,
    MiningConfiguration,
    MiningInitConfig,
    MiningState,
    Position,
    WeightActivation
} from "../types/Records.sol";

interface IVault {
    event MiningInitialized(address indexed core, bytes32 indexed streamId, address governance);
    event MiningBootstrapped(address indexed token, address indexed collection);
    event CollectionPolicyUpdated(
        uint8 indexed collection,
        address nft,
        uint8 maximumLevel,
        uint64[] levelWeights,
        uint64[] cooldownBlocks
    );
    event PositionRegistered(
        uint8 indexed collection,
        uint256 indexed tokenId,
        uint64 firstRound,
        uint128 weight,
        uint64 nextMergeBlock
    );
    event PositionsMerged(
        uint8 indexed collection,
        uint256 indexed survivor,
        uint256 indexed donor,
        uint8 level,
        uint64 effectiveRound,
        uint64 nextMergeBlock,
        uint128 activeWeight,
        uint128 pendingWeight,
        uint256 accruedScaled
    );
    event WeightActivated(uint64 indexed round, uint256 totalWeight, uint256 rewardIndex);
    event Checkpointed(
        uint64 indexed afterRound,
        uint64 indexed throughRound,
        uint64 completedBlocks,
        uint64 cumulativeWork,
        uint96 cumulativeBlockUnits,
        uint256 amount,
        uint256 minted,
        uint64 lastActivationRound,
        uint256 totalWeight,
        uint256 rewardIndex
    );
    event RewardsClaimed(
        address indexed owner,
        uint8 indexed collection,
        uint256 amount,
        uint256 remainderScaled,
        uint256[] tokenIds
    );

    // ---- lifecycle ----
    function boot(MiningInitConfig calldata config) external;
    function attach(address token_, address genesisNft) external;
    function enroll(uint256 tokenId) external;
    function roll() external;
    function redeem(uint8 collection, uint256[] calldata tokenIds) external returns (uint256 paid);
    function fuse(uint8 collection, uint256 survivorId, uint256 donorId) external;
    function enlist(address clonesNft, uint64[] calldata levelWeights, uint64[] calldata levelCooldowns) external;
    function growTiers(uint64[] calldata levelWeights, uint64[] calldata levelCooldowns) external;

    // ---- limits ----
    function TIER_LIMIT() external pure returns (uint8);
    function REDEEM_LIMIT() external pure returns (uint16);
    function ROLL_LIMIT() external pure returns (uint16);
    function BLOCK_YIELD() external pure returns (uint256);
    function PRECISION() external pure returns (uint256);
    function CEILING() external pure returns (uint256);

    // ---- views ----
    function kernel() external view returns (address);
    function bootstrapper() external view returns (address);
    function profile() external view returns (MiningConfiguration memory result);
    function snapshot() external view returns (MiningState memory result);
    function books() external view returns (MiningAccounting memory result);
    function rollStatus() external view returns (CheckpointStatus memory result);
    function tiers(uint8 collection) external view returns (CollectionPolicy memory policy);
    function holding(uint8 collection, uint256 tokenId) external view returns (Position memory);
    function redeemable(uint8 collection, uint256[] calldata tokenIds) external view returns (uint256 amount);
    function queued(uint256 index) external view returns (WeightActivation memory);
    function weightOf(uint8 collection, uint8 level) external view returns (uint64);
    function cooldownOf(uint8 collection, uint8 level) external view returns (uint64);
    function frozen() external view returns (bool);
    function custodian() external view returns (address);
    function logic() external view returns (address);
    function revision() external pure returns (uint64);
    function schemaHash() external pure returns (bytes32);
}

src/types/Records.sol

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

struct Round {
    uint64 roundId;
    uint64 work;
    bytes32 dataHash;
}

struct CoreLaunchConfig {
    bytes32 streamId;
    address guardian;
    address reporter;
    uint64 genesisTimestamp;
    uint32 initialWorkPerThousandBlocks;
    uint64 maxWorkPerRound;
}

struct CoreConfiguration {
    bytes32 streamId;
    uint64 genesisTimestamp;
    uint64 roundDuration;
    uint64 maxWorkPerRound;
    uint16 maxRoundsPerBatch;
    address guardian;
    address reporter;
    uint32 initialWorkPerThousandBlocks;
    uint64 targetBlocksPerActiveRound;
    uint64 difficultySmoothingRounds;
    uint96 blockUnitsPerBlock;
}

struct CoreState {
    uint64 settledThroughRound;
    uint64 cumulativeWork;
    uint96 cumulativeBlockUnits;
    uint64 blockHeight;
    uint96 blockProgress;
    uint32 workPerThousandBlocks;
    uint256 authorizationNonce;
    bool paused;
}

struct BlockInfo {
    uint64 roundId;
    uint64 workThreshold;
}

struct RoundCursor {
    uint64 cumulativeWork;
    uint96 cumulativeBlockUnits;
    uint32 workPerThousandBlocks;
}

struct RoundRecord {
    uint64 roundId;
    uint64 cumulativeWork;
    uint96 cumulativeBlockUnits;
    uint32 workPerThousandBlocks;
    bytes32 dataHash;
}

struct RoundPage {
    uint64 certifiedThroughRound;
    RoundCursor start;
    RoundCursor end;
    RoundRecord[] rounds;
}

struct MiningInitConfig {
    address core;
    bytes32 streamId;
    address governance;
    uint64 minimumTimelockDelay;
    uint64[] levelWeights;
    uint64[] cooldownBlocks;
}

struct MiningConfiguration {
    address core;
    bytes32 streamId;
    address governance;
    address token;
    address genesisCollection;
    uint64 genesisTimestamp;
    uint16 genesisMaxSupply;
    uint64 maxWorkPerRound;
    uint64 minimumTimelockDelay;
    uint128 supplyCap;
    uint8 genesisMaximumLevel;
    uint32 initialWorkPerThousandBlocks;
}

struct MiningState {
    uint256 minted;
    uint256 paid;
    uint256 totalWeight;
    uint256 rewardIndex;
    uint64 closedThroughBlock;
    uint64 lastActivationRound;
    uint256 weightActivationCursor;
    uint256 weightActivationCount;
    bool bootstrapped;
    uint64 processedThroughRound;
    uint64 closedCumulativeWork;
    uint96 closedCumulativeBlockUnits;
    uint32 closedWorkPerThousandBlocks;
}

struct MiningAccounting {
    uint256 closedResidual;
    uint256 openResidual;
    uint256 miningBalance;
    uint256 trackedCustody;
}

struct Position {
    uint64 activeWeight;
    uint64 pendingWeight;
    uint40 pendingRound;
    uint48 nextMergeBlock;
    uint8 level;
    uint256 lastIndex;
    uint256 accruedScaled;
}

struct LevelPolicy {
    uint64 weight;
    uint64 cooldownBlocks;
}

struct CollectionPolicy {
    address nft;
    uint16 maxSupply;
    uint8 maximumLevel;
    LevelPolicy[] levels;
}

struct WeightActivation {
    uint64 round;
    uint192 addedWeight;
}

struct CheckpointStatus {
    bool corePaused;
    uint64 nextRound;
    bool roundSettled;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "v3-core/=lib/v3-core/contracts/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.