Skip to content
Verified contractPartialBUSL-1.1

EthOsTokenRedeemer

Address0xdc1956b33ea8649bd5aa03be8d8fec2c9b3d5bbf
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,254,400
Creation transaction
0x16cf410fd8…98563022ec
Libraries
contracts/tokens/EthOsTokenRedeemer.sol:ExitQueue0x7233…5cab97

39 files

contracts/tokens/EthOsTokenRedeemer.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IEthOsTokenRedeemer} from "../interfaces/IEthOsTokenRedeemer.sol";
import {OsTokenRedeemer} from "./OsTokenRedeemer.sol";

/**
 * @title EthOsTokenRedeemer
 * @author StakeWise
 * @notice This contract is used to redeem OsTokens for the underlying asset.
 */
contract EthOsTokenRedeemer is IEthOsTokenRedeemer, ReentrancyGuard, OsTokenRedeemer {
    /**
     * @dev Constructor
     * @param vaultsRegistry_ The address of the VaultsRegistry contract
     * @param osToken_ The address of the OsToken contract
     * @param osTokenVaultController_ The address of the OsTokenVaultController contract
     * @param owner_ The address of the owner
     * @param exitQueueUpdateDelay_ The delay in seconds for exit queue updates
     * @param maxRedemptionFeePercent_ The maximum redemption fee in basis points
     */
    constructor(
        address vaultsRegistry_,
        address osToken_,
        address osTokenVaultController_,
        address owner_,
        uint256 exitQueueUpdateDelay_,
        uint256 maxRedemptionFeePercent_
    )
        ReentrancyGuard()
        OsTokenRedeemer(
            vaultsRegistry_, osToken_, osTokenVaultController_, owner_, exitQueueUpdateDelay_, maxRedemptionFeePercent_
        )
    {}

    /// @inheritdoc IEthOsTokenRedeemer
    function swapAssetsToOsTokenShares(address receiver) external payable override returns (uint256 osTokenShares) {
        return _swapAssetsToOsTokenShares(receiver, msg.value);
    }

    /// @inheritdoc OsTokenRedeemer
    function _getAssets(address account) internal view override returns (uint256) {
        return account.balance;
    }

    /// @inheritdoc OsTokenRedeemer
    function _transferAssets(address receiver, uint256 assets) internal override nonReentrant {
        return Address.sendValue(payable(receiver), assets);
    }

    /**
     * @dev Function for receiving redeemed assets.
     */
    receive() external payable {}
}

contracts/base/Multicall.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IMulticall.sol";

/**
 * @title Multicall
 * @author StakeWise
 * @notice Enables calling multiple methods in a single call to the contract
 */
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(bytes[] calldata data) external override returns (bytes[] memory results) {
        uint256 dataLength = data.length;
        results = new bytes[](dataLength);
        for (uint256 i = 0; i < dataLength; i++) {
            bytes memory result = Address.functionDelegateCall(address(this), data[i]);
            results[i] = result;
        }
    }
}

contracts/interfaces/IEthOsTokenRedeemer.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

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

/**
 * @title IEthOsTokenRedeemer
 * @author StakeWise
 * @notice Interface for EthOsTokenRedeemer contract
 */
interface IEthOsTokenRedeemer is IOsTokenRedeemer {
    /**
     * @notice Swap assets to OsToken shares. Must send ETH together with the call.
     * @param receiver The address to receive the OsToken shares
     * @return osTokenShares The amount of OsToken shares received
     */
    function swapAssetsToOsTokenShares(address receiver) external payable returns (uint256 osTokenShares);
}

contracts/interfaces/IKeeperOracles.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";

/**
 * @title IKeeperOracles
 * @author StakeWise
 * @notice Defines the interface for the KeeperOracles contract
 */
interface IKeeperOracles is IERC5267 {
    /**
     * @notice Event emitted on the oracle addition
     * @param oracle The address of the added oracle
     */
    event OracleAdded(address indexed oracle);

    /**
     * @notice Event emitted on the oracle removal
     * @param oracle The address of the removed oracle
     */
    event OracleRemoved(address indexed oracle);

    /**
     * @notice Event emitted on oracles config update
     * @param configIpfsHash The IPFS hash of the new config
     */
    event ConfigUpdated(string configIpfsHash);

    /**
     * @notice Function for verifying whether oracle is registered or not
     * @param oracle The address of the oracle to check
     * @return `true` for the registered oracle, `false` otherwise
     */
    function isOracle(address oracle) external view returns (bool);

    /**
     * @notice Total Oracles
     * @return The total number of oracles registered
     */
    function totalOracles() external view returns (uint256);

    /**
     * @notice Function for adding oracle to the set
     * @param oracle The address of the oracle to add
     */
    function addOracle(address oracle) external;

    /**
     * @notice Function for removing oracle from the set
     * @param oracle The address of the oracle to remove
     */
    function removeOracle(address oracle) external;

    /**
     * @notice Function for updating the config IPFS hash
     * @param configIpfsHash The new config IPFS hash
     */
    function updateConfig(string calldata configIpfsHash) external;
}

contracts/interfaces/IKeeperRewards.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

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

/**
 * @title IKeeperRewards
 * @author StakeWise
 * @notice Defines the interface for the Keeper contract rewards
 */
interface IKeeperRewards is IKeeperOracles {
    /**
     * @notice Event emitted on rewards update
     * @param caller The address of the function caller
     * @param rewardsRoot The new rewards merkle tree root
     * @param avgRewardPerSecond The new average reward per second
     * @param updateTimestamp The update timestamp used for rewards calculation
     * @param nonce The nonce used for verifying signatures
     * @param rewardsIpfsHash The new rewards IPFS hash
     */
    event RewardsUpdated(
        address indexed caller,
        bytes32 indexed rewardsRoot,
        uint256 avgRewardPerSecond,
        uint64 updateTimestamp,
        uint64 nonce,
        string rewardsIpfsHash
    );

    /**
     * @notice Event emitted on Vault harvest
     * @param vault The address of the Vault
     * @param rewardsRoot The rewards merkle tree root
     * @param totalAssetsDelta The Vault total assets delta since last sync. Can be negative in case of penalty/slashing.
     * @param unlockedMevDelta The Vault execution reward that can be withdrawn from shared MEV escrow. Only used by shared MEV Vaults.
     */
    event Harvested(
        address indexed vault, bytes32 indexed rewardsRoot, int256 totalAssetsDelta, uint256 unlockedMevDelta
    );

    /**
     * @notice Event emitted on rewards min oracles number update
     * @param oracles The new minimum number of oracles required to update rewards
     */
    event RewardsMinOraclesUpdated(uint256 oracles);

    /**
     * @notice A struct containing the last synced Vault's cumulative reward
     * @param assets The Vault cumulative reward earned since the start. Can be negative in case of penalty/slashing.
     * @param nonce The nonce of the last sync
     */
    struct Reward {
        int192 assets;
        uint64 nonce;
    }

    /**
     * @notice A struct containing the last unlocked Vault's cumulative execution reward that can be withdrawn from shared MEV escrow. Only used by shared MEV Vaults.
     * @param assets The shared MEV Vault's cumulative execution reward that can be withdrawn
     * @param nonce The nonce of the last sync
     */
    struct UnlockedMevReward {
        uint192 assets;
        uint64 nonce;
    }

    /**
     * @notice A struct containing parameters for rewards update
     * @param rewardsRoot The new rewards merkle root
     * @param avgRewardPerSecond The new average reward per second
     * @param updateTimestamp The update timestamp used for rewards calculation
     * @param rewardsIpfsHash The new IPFS hash with all the Vaults' rewards for the new root
     * @param signatures The concatenation of the Oracles' signatures
     */
    struct RewardsUpdateParams {
        bytes32 rewardsRoot;
        uint256 avgRewardPerSecond;
        uint64 updateTimestamp;
        string rewardsIpfsHash;
        bytes signatures;
    }

    /**
     * @notice A struct containing parameters for harvesting rewards. Can only be called by Vault.
     * @param rewardsRoot The rewards merkle root
     * @param reward The Vault cumulative reward earned since the start. Can be negative in case of penalty/slashing.
     * @param unlockedMevReward The Vault cumulative execution reward that can be withdrawn from shared MEV escrow. Only used by shared MEV Vaults.
     * @param proof The proof to verify that Vault's reward is correct
     */
    struct HarvestParams {
        bytes32 rewardsRoot;
        int160 reward;
        uint160 unlockedMevReward;
        bytes32[] proof;
    }

    /**
     * @notice Previous Rewards Root
     * @return The previous merkle tree root of the rewards accumulated by the Vaults
     */
    function prevRewardsRoot() external view returns (bytes32);

    /**
     * @notice Rewards Root
     * @return The latest merkle tree root of the rewards accumulated by the Vaults
     */
    function rewardsRoot() external view returns (bytes32);

    /**
     * @notice Rewards Nonce
     * @return The nonce used for updating rewards merkle tree root
     */
    function rewardsNonce() external view returns (uint64);

    /**
     * @notice The last rewards update
     * @return The timestamp of the last rewards update
     */
    function lastRewardsTimestamp() external view returns (uint64);

    /**
     * @notice The minimum number of oracles required to update rewards
     * @return The minimum number of oracles
     */
    function rewardsMinOracles() external view returns (uint256);

    /**
     * @notice The rewards delay
     * @return The delay in seconds between rewards updates
     */
    function rewardsDelay() external view returns (uint256);

    /**
     * @notice Get last synced Vault cumulative reward
     * @param vault The address of the Vault
     * @return assets The last synced reward assets
     * @return nonce The last synced reward nonce
     */
    function rewards(address vault) external view returns (int192 assets, uint64 nonce);

    /**
     * @notice Get last unlocked shared MEV Vault cumulative reward
     * @param vault The address of the Vault
     * @return assets The last synced reward assets
     * @return nonce The last synced reward nonce
     */
    function unlockedMevRewards(address vault) external view returns (uint192 assets, uint64 nonce);

    /**
     * @notice Checks whether Vault must be harvested
     * @param vault The address of the Vault
     * @return `true` if the Vault requires harvesting, `false` otherwise
     */
    function isHarvestRequired(address vault) external view returns (bool);

    /**
     * @notice Checks whether the Vault can be harvested
     * @param vault The address of the Vault
     * @return `true` if Vault can be harvested, `false` otherwise
     */
    function canHarvest(address vault) external view returns (bool);

    /**
     * @notice Checks whether rewards can be updated
     * @return `true` if rewards can be updated, `false` otherwise
     */
    function canUpdateRewards() external view returns (bool);

    /**
     * @notice Checks whether the Vault has registered validators
     * @param vault The address of the Vault
     * @return `true` if Vault is collateralized, `false` otherwise
     */
    function isCollateralized(address vault) external view returns (bool);

    /**
     * @notice Update rewards data
     * @param params The struct containing rewards update parameters
     */
    function updateRewards(RewardsUpdateParams calldata params) external;

    /**
     * @notice Harvest rewards. Can be called only by Vault.
     * @param params The struct containing rewards harvesting parameters
     * @return totalAssetsDelta The total reward/penalty accumulated by the Vault since the last sync
     * @return unlockedMevDelta The Vault execution reward that can be withdrawn from shared MEV escrow. Only used by shared MEV Vaults.
     * @return harvested `true` when the rewards were harvested, `false` otherwise
     */
    function harvest(HarvestParams calldata params)
        external
        returns (int256 totalAssetsDelta, uint256 unlockedMevDelta, bool harvested);

    /**
     * @notice Set min number of oracles for confirming rewards update. Can only be called by the owner.
     * @param _rewardsMinOracles The new min number of oracles for confirming rewards update
     */
    function setRewardsMinOracles(uint256 _rewardsMinOracles) external;
}

contracts/interfaces/IMulticall.sol

// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.22;

/**
 * @title Multicall
 * @author Uniswap
 * @notice Adopted from https://github.com/Uniswap/v3-periphery/blob/1d69caf0d6c8cfeae9acd1f34ead30018d6e6400/contracts/base/Multicall.sol
 * @notice Enables calling multiple methods in a single call to the contract
 */
interface IMulticall {
    /**
     * @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
     * @param data The encoded function data for each of the calls to make to this contract
     * @return results The results from each of the calls passed in via data
     */
    function multicall(bytes[] calldata data) external returns (bytes[] memory results);
}

contracts/interfaces/IOsTokenRedeemer.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {IKeeperRewards} from "./IKeeperRewards.sol";
import {IMulticall} from "./IMulticall.sol";

/**
 * @title IOsTokenRedeemer
 * @author StakeWise
 * @notice Interface for OsTokenRedeemer contract
 */
interface IOsTokenRedeemer is IMulticall {
    /**
     * @notice Struct to store the redeemable positions Merkle root and IPFS hash
     * @param merkleRoot The Merkle root of the redeemable positions
     * @param ipfsHash The IPFS hash of the redeemable positions
     */
    struct RedeemablePositions {
        bytes32 merkleRoot;
        string ipfsHash;
    }

    /**
     * @notice Struct to store the redeemed OsToken position details
     * @param vault The address of the Vault
     * @param owner The address of the position owner
     * @param leafShares The amount of OsToken shares used to calculate the merkle leaf
     * @param sharesToRedeem The amount of OsToken shares to redeem
     */
    struct OsTokenPosition {
        address vault;
        address owner;
        uint256 leafShares;
        uint256 sharesToRedeem;
    }

    /**
     * @notice Event emitted when the positions manager is updated
     * @param positionsManager The address of the new positions manager
     */
    event PositionsManagerUpdated(address indexed positionsManager);

    /**
     * @notice Event emitted when new redeemable positions are proposed
     * @param merkleRoot The Merkle root of the redeemable positions
     * @param ipfsHash The IPFS hash of the redeemable positions
     */
    event RedeemablePositionsUpdated(bytes32 indexed merkleRoot, string ipfsHash);

    /**
     * @notice Event emitted on shares added to the exit queue
     * @param owner The address that owns the shares
     * @param receiver The address that will receive withdrawn assets
     * @param positionTicket The exit queue ticket that was assigned to the position
     * @param shares The number of shares that queued for the exit, net of the redemption fee
     * @param fee The redemption fee charged in OsToken shares
     */
    event ExitQueueEntered(
        address indexed owner, address indexed receiver, uint256 positionTicket, uint256 shares, uint256 fee
    );

    /**
     * @notice Event emitted on claim of the exited assets
     * @param receiver The address that has received withdrawn assets
     * @param prevPositionTicket The exit queue ticket received after the `enterExitQueue` call
     * @param newPositionTicket The new exit queue ticket in case not all the shares were withdrawn. Otherwise 0.
     * @param withdrawnAssets The total number of assets withdrawn
     */
    event ExitedAssetsClaimed(
        address indexed receiver, uint256 prevPositionTicket, uint256 newPositionTicket, uint256 withdrawnAssets
    );

    /**
     * @notice Event emitted on shares swapped for assets
     * @param sender The address that initiated the swap
     * @param receiver The address that will receive the shares
     * @param shares The number of shares received
     * @param assets The number of assets spent
     */
    event OsTokenSharesSwapped(address indexed sender, address indexed receiver, uint256 shares, uint256 assets);

    /**
     * @notice Event emitted on checkpoint creation
     * @param shares The number of burned shares
     * @param assets The amount of exited assets
     */
    event CheckpointCreated(uint256 shares, uint256 assets);

    /**
     * @notice Event emitted when OsToken positions are redeemed
     * @param shares The number of shares redeemed
     * @param assets The number of assets redeemed
     */
    event OsTokenPositionsRedeemed(uint256 shares, uint256 assets);

    /**
     * @notice Event emitted when the redemption fee is updated
     * @param redemptionFeePercent The new redemption fee in basis points
     */
    event FeeUpdated(uint256 redemptionFeePercent);

    /**
     * @notice Event emitted when the accumulated fees are claimed
     * @param receiver The address that received the fees
     * @param shares The number of claimed OsToken shares
     */
    event FeesClaimed(address indexed receiver, uint256 shares);

    /**
     * @notice The maximum redemption fee in basis points
     * @return The maximum redemption fee
     */
    function maxRedemptionFeePercent() external view returns (uint256);

    /**
     * @notice The redemption fee in basis points charged in OsToken shares on entering the exit queue
     * @return The redemption fee
     */
    function redemptionFeePercent() external view returns (uint256);

    /**
     * @notice The number of accumulated OsToken shares fees that can be claimed by the owner
     * @return The accumulated fees in OsToken shares
     */
    function accumulatedFees() external view returns (uint256);

    /**
     * @notice The delay in seconds for the exit queue updates
     * @return The delay in seconds
     */
    function exitQueueUpdateDelay() external view returns (uint256);

    /**
     * @notice The number of queued OsToken shares
     * @return The number of queued shares
     */
    function queuedShares() external view returns (uint128);

    /**
     * @notice The number of unclaimed assets in the exit queue
     * @return The number of unclaimed assets
     */
    function unclaimedAssets() external view returns (uint128);

    /**
     * @notice The number of redeemed OsToken shares
     * @return The number of redeemed shares
     */
    function redeemedShares() external view returns (uint128);

    /**
     * @notice The number of redeemed assets
     * @return The number of redeemed assets
     */
    function redeemedAssets() external view returns (uint128);

    /**
     * @notice The number of swapped OsToken shares
     * @return The number of swapped shares
     */
    function swappedShares() external view returns (uint128);

    /**
     * @notice The number of swapped assets
     * @return The number of swapped assets
     */
    function swappedAssets() external view returns (uint128);

    /**
     * @notice Maps a Merkle tree leaf to processed shares
     * @param leaf The leaf of the Merkle tree
     * @return processedShares The number of processed shares corresponding to the leaf
     */
    function leafToProcessedShares(bytes32 leaf) external view returns (uint256 processedShares);

    /**
     * @notice Maps a exit request hash to the number of exiting shares
     * @param exitRequestHash The hash of the exit request
     * @return shares The number of shares that are exiting for the given exit request hash
     */
    function exitRequests(bytes32 exitRequestHash) external view returns (uint256 shares);

    /**
     * @notice The timestamp when the exit queue was last updated
     * @return The timestamp of the last exit queue update
     */
    function exitQueueTimestamp() external view returns (uint256);

    /**
     * @notice The address authorized to redeem OsToken positions
     * @return The address of the positions manager
     */
    function positionsManager() external view returns (address);

    /**
     * @notice The current nonce for the redemptions
     * @return The current nonce value
     */
    function nonce() external view returns (uint256);

    /**
     * @notice Get the current exit queue data
     * @return queuedShares The total number of shares currently queued for exit
     * @return unclaimedAssets The total number of assets that have not been claimed yet
     * @return totalTickets The total number of tickets (shares) processed in the exit queue
     */
    function getExitQueueData()
        external
        view
        returns (uint256 queuedShares, uint256 unclaimedAssets, uint256 totalTickets);

    /**
     * @notice Gets the cumulative tickets in the exit queue
     * @return The cumulative tickets in the exit queue
     */
    function getExitQueueCumulativeTickets() external view returns (uint256);

    /**
     * @notice Calculates the missing assets in the exit queue for a target cumulative tickets.
     * @param targetCumulativeTickets The target cumulative tickets in the exit queue
     * @return missingAssets The number of missing assets in the exit queue
     */
    function getExitQueueMissingAssets(uint256 targetCumulativeTickets) external view returns (uint256 missingAssets);

    /**
     * @notice Checks if the exit queue can be processed
     * @return True if the exit queue can be processed, false otherwise
     */
    function canProcessExitQueue() external view returns (bool);

    /**
     * @notice The current redeemable positions Merkle root and IPFS hash
     * @return merkleRoot The Merkle root of the redeemable positions
     * @return ipfsHash The IPFS hash of the redeemable positions
     */
    function redeemablePositions() external view returns (bytes32 merkleRoot, string memory ipfsHash);

    /**
     * @notice Gets the index of the exit queue for a given position ticket.
     * @param positionTicket The position ticket to search for
     * @return The index of the exit queue or -1 if not found
     */
    function getExitQueueIndex(uint256 positionTicket) external view returns (int256);

    /**
     * @notice Calculates the exited assets for a given position ticket and exit queue index.
     * @param receiver The address of the receiver
     * @param positionTicket The position ticket to calculate exited assets for
     * @param exitQueueIndex The index of the exit queue to calculate exited assets for
     * @return leftTickets The number of tickets left in the exit queue
     * @return exitedTickets The number of tickets that have exited
     * @return exitedAssets The number of assets that have exited
     */
    function calculateExitedAssets(address receiver, uint256 positionTicket, uint256 exitQueueIndex)
        external
        view
        returns (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets);

    /**
     * @notice Update the address of the positions manager. Can only be called by the owner.
     * @param positionsManager_ The address of the new positions manager
     */
    function setPositionsManager(address positionsManager_) external;

    /**
     * @notice Update the redemption fee. Can only be called by the owner.
     * @param redemptionFeePercent_ The new redemption fee in basis points
     */
    function setRedemptionFeePercent(uint256 redemptionFeePercent_) external;

    /**
     * @notice Claim the accumulated OsToken shares fees. Can only be called by the owner.
     * @param receiver The address that will receive the OsToken shares
     */
    function claimFees(address receiver) external;

    /**
     * @notice Set new redeemable positions. Can only be called by the owner.
     * @param newPositions The new redeemable positions
     */
    function setRedeemablePositions(RedeemablePositions calldata newPositions) external;

    /**
     * @notice Permit OsToken shares to be used for redemption.
     * @param shares The number of shares to permit
     * @param deadline The deadline for the permit
     * @param v The recovery byte of the signature
     * @param r The output of the ECDSA signature
     * @param s The output of the ECDSA signature
     */
    function permitOsToken(uint256 shares, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;

    /**
     * @notice Enters the exit queue with a given number of shares and receiver address.
     *         The redemption fee is deducted from the shares and accumulated in OsToken shares.
     * @param shares The number of shares to enter the exit queue with, including the redemption fee
     * @param receiver The address that will receive the assets after exit
     * @return positionTicket The position ticket for the entered exit queue
     */
    function enterExitQueue(uint256 shares, address receiver) external returns (uint256 positionTicket);

    /**
     * @notice Claims exited assets for a given position ticket and exit queue index.
     * @param positionTicket The position ticket to claim exited assets for
     * @param exitQueueIndex The index of the exit queue to claim exited assets for
     */
    function claimExitedAssets(uint256 positionTicket, uint256 exitQueueIndex) external;

    /**
     * @notice Redeem OsToken shares from a specific sub-vault. Can only be called by the meta vault.
     * @param subVault The address of the sub-vault
     * @param osTokenShares The number of OsToken shares to redeem
     * @return The amount of redeemed assets
     */
    function redeemSubVaultOsToken(address subVault, uint256 osTokenShares) external returns (uint256);

    /**
     * @notice Redeem assets from the sub-vaults to the meta vault. Can only be called by the positions manager.
     * @param metaVault The address of the meta vault
     * @param assetsToRedeem The number of assets to redeem
     * @return totalRedeemedAssets The total number of redeemed assets
     */
    function redeemSubVaultsAssets(address metaVault, uint256 assetsToRedeem)
        external
        returns (uint256 totalRedeemedAssets);

    /**
     * @notice Redeem OsToken shares from the vault positions.
     * @param positions The array of OsToken positions to redeem
     * @param proof The Merkle proof for the positions root
     * @param proofFlags The flags for the Merkle proof
     */
    function redeemOsTokenPositions(
        OsTokenPosition[] memory positions,
        bytes32[] calldata proof,
        bool[] calldata proofFlags
    ) external;

    /**
     * @notice Updates the vault state. To be used in multicall to update state and redeem positions.
     * @param vault The address of the vault to update
     * @param harvestParams The harvest parameters for the vault state update
     */
    function updateVaultState(address vault, IKeeperRewards.HarvestParams calldata harvestParams) external;

    /**
     * @notice Process the exit queue and checkpoint swapped or redeemed shares. Can only be called once per `exitQueueUpdateDelay`.
     */
    function processExitQueue() external;
}

contracts/interfaces/IOsTokenVaultController.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

/**
 * @title IOsTokenVaultController
 * @author StakeWise
 * @notice Defines the interface for the OsTokenVaultController contract
 */
interface IOsTokenVaultController {
    /**
     * @notice Event emitted on minting shares
     * @param vault The address of the Vault
     * @param receiver The address that received the shares
     * @param assets The number of assets collateralized
     * @param shares The number of tokens the owner received
     */
    event Mint(address indexed vault, address indexed receiver, uint256 assets, uint256 shares);

    /**
     * @notice Event emitted on burning shares
     * @param vault The address of the Vault
     * @param owner The address that owns the shares
     * @param assets The total number of assets withdrawn
     * @param shares The total number of shares burned
     */
    event Burn(address indexed vault, address indexed owner, uint256 assets, uint256 shares);

    /**
     * @notice Event emitted on state update
     * @param profitAccrued The profit accrued since the last update
     * @param treasuryShares The number of shares minted for the treasury
     * @param treasuryAssets The number of assets minted for the treasury
     */
    event StateUpdated(uint256 profitAccrued, uint256 treasuryShares, uint256 treasuryAssets);

    /**
     * @notice Event emitted on capacity update
     * @param capacity The amount after which the OsToken stops accepting deposits
     */
    event CapacityUpdated(uint256 capacity);

    /**
     * @notice Event emitted on treasury address update
     * @param treasury The new treasury address
     */
    event TreasuryUpdated(address indexed treasury);

    /**
     * @notice Event emitted on fee percent update
     * @param feePercent The new fee percent
     */
    event FeePercentUpdated(uint16 feePercent);

    /**
     * @notice Event emitted on average reward per second update
     * @param avgRewardPerSecond The new average reward per second
     */
    event AvgRewardPerSecondUpdated(uint256 avgRewardPerSecond);

    /**
     * @notice Event emitted on keeper address update
     * @param keeper The new keeper address
     */
    event KeeperUpdated(address keeper);

    /**
     * @notice The OsToken capacity
     * @return The amount after which the OsToken stops accepting deposits
     */
    function capacity() external view returns (uint256);

    /**
     * @notice The DAO treasury address that receives OsToken fees
     * @return The address of the treasury
     */
    function treasury() external view returns (address);

    /**
     * @notice The fee percent (multiplied by 100)
     * @return The fee percent applied by the OsToken on the rewards
     */
    function feePercent() external view returns (uint64);

    /**
     * @notice The address that can update avgRewardPerSecond
     * @return The address of the keeper contract
     */
    function keeper() external view returns (address);

    /**
     * @notice The average reward per second used to mint OsToken rewards
     * @return The average reward per second earned by the Vaults
     */
    function avgRewardPerSecond() external view returns (uint256);

    /**
     * @notice The fee per share used for calculating the fee for every position
     * @return The cumulative fee per share
     */
    function cumulativeFeePerShare() external view returns (uint256);

    /**
     * @notice The total number of shares controlled by the OsToken
     * @return The total number of shares
     */
    function totalShares() external view returns (uint256);

    /**
     * @notice Total assets controlled by the OsToken
     * @return The total amount of the underlying asset that is "managed" by OsToken
     */
    function totalAssets() external view returns (uint256);

    /**
     * @notice Converts assets to shares
     * @param assets The amount of assets to convert to shares
     * @return shares The amount of OsToken shares obtained when exchanging with the amount of assets provided
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @notice Converts shares to assets
     * @param shares The amount of shares to convert to assets
     * @return assets The amount of assets obtained when exchanging with the amount of OsToken shares provided
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @notice Updates rewards and treasury fee checkpoint for the OsToken
     */
    function updateState() external;

    /**
     * @notice Mint OsToken shares. Can only be called by the registered vault.
     * @param receiver The address that will receive the shares
     * @param shares The amount of shares to mint
     * @return assets The amount of assets minted
     */
    function mintShares(address receiver, uint256 shares) external returns (uint256 assets);

    /**
     * @notice Burn shares for withdrawn assets. Can only be called by the registered vault.
     * @param owner The address that owns the shares
     * @param shares The amount of shares to burn
     * @return assets The amount of assets withdrawn
     */
    function burnShares(address owner, uint256 shares) external returns (uint256 assets);

    /**
     * @notice Update treasury address. Can only be called by the owner.
     * @param _treasury The new treasury address
     */
    function setTreasury(address _treasury) external;

    /**
     * @notice Update capacity. Can only be called by the owner.
     * @param _capacity The amount after which the OsToken stops accepting deposits
     */
    function setCapacity(uint256 _capacity) external;

    /**
     * @notice Update fee percent. Can only be called by the owner. Cannot be larger than 10 000 (100%).
     * @param _feePercent The new fee percent
     */
    function setFeePercent(uint16 _feePercent) external;

    /**
     * @notice Update keeper address. Can only be called by the owner.
     * @param _keeper The new keeper address
     */
    function setKeeper(address _keeper) external;

    /**
     * @notice Updates average reward per second. Can only be called by the keeper.
     * @param _avgRewardPerSecond The new average reward per second
     */
    function setAvgRewardPerSecond(uint256 _avgRewardPerSecond) external;
}

contracts/interfaces/ISubVaultsCurator.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

/**
 * @title ISubVaultsCurator
 * @author StakeWise
 * @notice Defines the interface for the SubVaultsCurator contract
 */
interface ISubVaultsCurator {
    /**
     * @notice Struct for storing deposit data
     * @param vault The address of the vault
     * @param assets The amount of assets to deposit
     */
    struct Deposit {
        address vault;
        uint256 assets;
    }

    /**
     * @notice Struct for storing exit request data
     * @param vault The address of the vault
     * @param assets The amount of assets to exit
     */
    struct ExitRequest {
        address vault;
        uint256 assets;
    }

    /**
     * @notice Function to get the deposits to the sub-vaults
     * @param assetsToDeposit The amount of assets to deposit
     * @param subVaults The addresses of the sub-vaults
     * @param ejectingVault The address of the sub-vault that is currently ejecting. Should be zero if none.
     * @return deposits An array of Deposit structs containing the vault addresses and the amounts to deposit
     */
    function getDeposits(uint256 assetsToDeposit, address[] calldata subVaults, address ejectingVault)
        external
        view
        returns (Deposit[] memory deposits);

    /**
     * @notice Function to get the exit requests to the sub-vaults
     * @param assetsToExit The amount of assets to exit
     * @param subVaults The addresses of the sub-vaults
     * @param balances The balances of the sub-vaults
     * @param ejectingVault The address of the sub-vault that is currently ejecting. Should be zero if none.
     * @return exitRequests An array of ExitRequest structs containing the vault addresses and the amounts to exit
     */
    function getExitRequests(
        uint256 assetsToExit,
        address[] calldata subVaults,
        uint256[] memory balances,
        address ejectingVault
    ) external pure returns (ExitRequest[] memory exitRequests);
}

contracts/interfaces/ISubVaultsRegistry.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {IMulticall} from "./IMulticall.sol";
import {ISubVaultsCurator} from "./ISubVaultsCurator.sol";

/**
 * @title ISubVaultsRegistry
 * @author StakeWise
 * @notice Defines the interface for the SubVaultsRegistry contract
 */
interface ISubVaultsRegistry is IMulticall {
    /**
     * @notice Struct for sub vault exit request
     * @param exitQueueIndex The index of the exit queue
     * @param vault The address of the sub vault
     * @param timestamp The timestamp of the exit request
     */
    struct SubVaultExitRequest {
        uint256 exitQueueIndex;
        address vault;
        uint64 timestamp;
    }

    /**
     * @notice Struct for sub vault state
     * @param stakedShares The number of shares staked in the sub vault
     * @param queuedShares The number of shares queued for exit in the sub vault
     */
    struct SubVaultState {
        uint128 stakedShares;
        uint128 queuedShares;
    }

    /**
     * @notice Emitted when the sub vaults are harvested
     * @param totalAssetsDelta The change in total assets after the harvest
     */
    event SubVaultsHarvested(int256 totalAssetsDelta);

    /**
     * @notice Emitted when the sub-vaults curator is updated
     * @param curator The address of the new sub-vaults curator
     */
    event SubVaultsCuratorUpdated(address indexed curator);

    /**
     * @notice Emitted when the rewards nonce is updated
     * @param rewardsNonce The new rewards nonce
     */
    event RewardsNonceUpdated(uint256 rewardsNonce);

    /**
     * @notice Emitted when a new sub-vault is added
     * @param vault The address of the sub-vault
     */
    event SubVaultAdded(address indexed vault);

    /**
     * @notice Emitted when a new meta sub-vault is proposed
     * @param vault The address of the meta sub-vault
     */
    event MetaSubVaultProposed(address indexed vault);

    /**
     * @notice Emitted when a meta sub-vault is rejected
     * @param vault The address of the meta sub-vault
     */
    event MetaSubVaultRejected(address indexed vault);

    /**
     * @notice Emitted when a sub-vault is ejecting
     * @param vault The address of the sub-vault
     */
    event SubVaultEjecting(address indexed vault);

    /**
     * @notice Emitted when a sub-vault is ejected
     * @param vault The address of the sub-vault
     */
    event SubVaultEjected(address indexed vault);

    /**
     * @notice Event emitted when assets are redeemed from sub-vaults
     * @param assetsRedeemed The amount of assets redeemed to the meta vault
     */
    event SubVaultsAssetsRedeemed(uint256 assetsRedeemed);

    /**
     * @notice Event emitted when state is migrated from meta vault
     * @param metaVault The address of the meta vault
     */
    event Migrated(address indexed metaVault);

    /**
     * @notice The address of the meta vault
     * @return The address of the meta vault
     */
    function metaVault() external view returns (address);

    /**
     * @notice The address of the sub-vaults curator
     * @return The address of the sub-vaults curator
     */
    function subVaultsCurator() external view returns (address);

    /**
     * @notice Pending meta sub-vault waiting for approval
     * @return The address of the pending meta sub-vault
     */
    function pendingMetaSubVault() external view returns (address);

    /**
     * @notice Function to get the rewards nonce of the sub-vaults
     * @return The rewards nonce
     */
    function subVaultsRewardsNonce() external view returns (uint128);

    /**
     * @notice The address of the sub-vault being ejected
     * @return The address of the ejecting sub-vault
     */
    function ejectingSubVault() external view returns (address);

    /**
     * @notice The number of shares of the ejecting sub-vault
     * @return The number of shares
     */
    function ejectingSubVaultShares() external view returns (uint256);

    /**
     * @notice Returns the state of a sub-vault
     * @param vault The address of the sub-vault
     * @return The state of the sub-vault
     */
    function subVaultsStates(address vault) external view returns (SubVaultState memory);

    /**
     * @notice Returns the exits queue for a sub-vault
     * @param vault The address of the sub-vault
     * @return The array of packed exit data (positionTicket: uint160, shares: uint96)
     */
    function subVaultsExits(address vault) external view returns (bytes32[] memory);

    /**
     * @notice Returns the list of sub-vaults
     * @return The array of sub-vault addresses
     */
    function getSubVaults() external view returns (address[] memory);

    /**
     * @notice Checks if the given address is a sub-vault
     * @param vault The address to check
     * @return True if the address is a sub-vault, false otherwise
     */
    function isSubVault(address vault) external view returns (bool);

    /**
     * @notice Initializes the SubVaultsRegistry
     * @param metaVault The address of the meta vault
     * @param curator The address of initial sub-vaults curator
     */
    function initialize(address metaVault, address curator) external;

    /**
     * @notice Function to update the sub-vaults curator. Can only be called by the meta vault admin.
     * @param curator The address of the new sub-vaults curator
     */
    function setSubVaultsCurator(address curator) external;

    /**
     * @notice Function to add a new sub-vault. Can only be called by the meta vault admin.
     * @param vault The address of the sub-vault to add
     */
    function addSubVault(address vault) external;

    /**
     * @notice Function to accept a meta sub-vault. Can only be called by the VaultsRegistry owner.
     * @param metaSubVault The address of the meta sub-vault to accept
     */
    function acceptMetaSubVault(address metaSubVault) external;

    /**
     * @notice Function to reject a meta sub-vault. Can only be called by the VaultsRegistry owner or meta vault admin.
     * @param metaSubVault The address of the meta sub-vault to reject
     */
    function rejectMetaSubVault(address metaSubVault) external;

    /**
     * @notice Function to eject a sub-vault. Can only be called by the meta vault admin.
     * All the sub-vault shares will be added to the exit queue.
     * @param vault The address of the sub-vault to eject
     */
    function ejectSubVault(address vault) external;

    /**
     * @notice Checks whether the state can be updated
     * @return True if the state can be updated, false otherwise
     */
    function canUpdateState() external view returns (bool);

    /**
     * @notice Checks whether the meta vault is collateralized
     * @return True if the meta vault is collateralized, false otherwise
     */
    function isCollateralized() external view returns (bool);

    /**
     * @notice The total assets deposited to sub-vaults
     */
    function subVaultsTotalAssets() external view returns (uint128);

    /**
     * @notice Checks whether the state update is required
     * @return True if the state update is required, false otherwise
     */
    function isStateUpdateRequired() external view returns (bool);

    /**
     * @notice Deposit available assets to the sub vaults
     */
    function depositToSubVaults() external;

    /**
     * @notice Claims exited assets from sub vaults
     * @param exitRequests The array of exit requests to claim
     */
    function claimSubVaultsExitedAssets(SubVaultExitRequest[] calldata exitRequests) external;

    /**
     * @notice Harvests sub-vaults assets. Can only be called by the meta vault.
     * @return totalAssetsDelta The change in total assets after the harvest
     * @return harvested Whether the sub-vaults were harvested
     */
    function harvestSubVaultsAssets() external returns (int256 totalAssetsDelta, bool harvested);

    /**
     * @notice Enters the exit queue for sub-vaults. Can only be called by the meta vault.
     */
    function enterSubVaultsExitQueue() external;

    /**
     * @notice Calculates the required sub-vaults exit requests to fulfill the assets to redeem
     * @param assetsToRedeem The amount of assets to redeem
     * @return redeemRequests The array of sub-vaults exit requests
     */
    function calculateSubVaultsRedemptions(uint256 assetsToRedeem)
        external
        view
        returns (ISubVaultsCurator.ExitRequest[] memory redeemRequests);

    /**
     * @notice Redeems assets from sub-vaults to the meta vault. Can only be called by the redeemer.
     * @param assetsToRedeem The amount of assets to redeem to the meta vault
     * @return totalRedeemedAssets The total amount of assets redeemed from sub-vaults
     */
    function redeemSubVaultsAssets(uint256 assetsToRedeem) external returns (uint256 totalRedeemedAssets);
}

contracts/interfaces/IVaultAdmin.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

/**
 * @title IVaultState
 * @author StakeWise
 * @notice Defines the interface for the VaultAdmin contract
 */
interface IVaultAdmin {
    /**
     * @notice Event emitted on metadata ipfs hash update
     * @param caller The address of the function caller
     * @param metadataIpfsHash The new metadata IPFS hash
     */
    event MetadataUpdated(address indexed caller, string metadataIpfsHash);

    /**
     * @notice Event emitted on admin update
     * @param caller The address of the function caller
     * @param newAdmin The new admin address
     */
    event AdminUpdated(address indexed caller, address indexed newAdmin);

    /**
     * @notice The Vault admin
     * @return The address of the Vault admin
     */
    function admin() external view returns (address);

    /**
     * @notice Function for updating the metadata IPFS hash. Can only be called by Vault admin.
     * @param metadataIpfsHash The new metadata IPFS hash
     */
    function setMetadata(string calldata metadataIpfsHash) external;

    /**
     * @notice Function for updating the admin address. Can only be called by Vault current admin.
     * @param newAdmin The new admin address
     */
    function setAdmin(address newAdmin) external;
}

contracts/interfaces/IVaultEnterExit.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

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

/**
 * @title IVaultEnterExit
 * @author StakeWise
 * @notice Defines the interface for the VaultEnterExit contract
 */
interface IVaultEnterExit is IVaultState {
    /**
     * @notice Event emitted on deposit
     * @param caller The address that called the deposit function
     * @param receiver The address that received the shares
     * @param assets The number of assets deposited by the caller
     * @param shares The number of shares received
     * @param referrer The address of the referrer
     */
    event Deposited(address indexed caller, address indexed receiver, uint256 assets, uint256 shares, address referrer);

    /**
     * @notice Event emitted on redeem
     * @param owner The address that owns the shares
     * @param receiver The address that received withdrawn assets
     * @param assets The total number of withdrawn assets
     * @param shares The total number of withdrawn shares
     */
    event Redeemed(address indexed owner, address indexed receiver, uint256 assets, uint256 shares);

    /**
     * @notice Event emitted on shares added to the exit queue
     * @param owner The address that owns the shares
     * @param receiver The address that will receive withdrawn assets
     * @param positionTicket The exit queue ticket that was assigned to the position
     * @param shares The number of shares that queued for the exit
     */
    event ExitQueueEntered(address indexed owner, address indexed receiver, uint256 positionTicket, uint256 shares);

    /**
     * @notice Event emitted on shares added to the V2 exit queue (deprecated)
     * @param owner The address that owns the shares
     * @param receiver The address that will receive withdrawn assets
     * @param positionTicket The exit queue ticket that was assigned to the position
     * @param shares The number of shares that queued for the exit
     * @param assets The number of assets that queued for the exit
     */
    event V2ExitQueueEntered(
        address indexed owner, address indexed receiver, uint256 positionTicket, uint256 shares, uint256 assets
    );

    /**
     * @notice Event emitted on claim of the exited assets
     * @param receiver The address that has received withdrawn assets
     * @param prevPositionTicket The exit queue ticket received after the `enterExitQueue` call
     * @param newPositionTicket The new exit queue ticket in case not all the shares were withdrawn. Otherwise 0.
     * @param withdrawnAssets The total number of assets withdrawn
     */
    event ExitedAssetsClaimed(
        address indexed receiver, uint256 prevPositionTicket, uint256 newPositionTicket, uint256 withdrawnAssets
    );

    /**
     * @notice Locks shares to the exit queue. The shares continue earning rewards until they will be burned by the Vault.
     * @dev For ERC-20 vault variants, balanceOf(vault) does not reflect queued exit shares despite the emitted Transfer event.
     * @param shares The number of shares to lock
     * @param receiver The address that will receive assets upon withdrawal
     * @return positionTicket The position ticket of the exit queue. Returns uint256 max if no ticket created.
     */
    function enterExitQueue(uint256 shares, address receiver) external returns (uint256 positionTicket);

    /**
     * @notice Get the exit queue index to claim exited assets from
     * @param positionTicket The exit queue position ticket to get the index for
     * @return The exit queue index that should be used to claim exited assets.
     *         Returns -1 in case such index does not exist.
     */
    function getExitQueueIndex(uint256 positionTicket) external view returns (int256);

    /**
     * @notice Calculates the number of shares and assets that can be claimed from the exit queue.
     * @param receiver The address that will receive assets upon withdrawal
     * @param positionTicket The exit queue ticket received after the `enterExitQueue` call
     * @param timestamp The timestamp when the shares entered the exit queue
     * @param exitQueueIndex The exit queue index at which the shares were burned. It can be looked up by calling `getExitQueueIndex`.
     * @return leftTickets The number of tickets left in the queue
     * @return exitedTickets The number of tickets that have already exited
     * @return exitedAssets The number of assets that can be claimed
     */
    function calculateExitedAssets(address receiver, uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex)
        external
        view
        returns (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets);

    /**
     * @notice Claims assets that were withdrawn by the Vault. It can be called only after the `enterExitQueue` call by the `receiver`.
     * @param positionTicket The exit queue ticket received after the `enterExitQueue` call
     * @param timestamp The timestamp when the assets entered the exit queue
     * @param exitQueueIndex The exit queue index at which the shares were burned.
     *        It can be looked up by calling `getExitQueueIndex`.
     */
    function claimExitedAssets(uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex) external;

    /**
     * @notice Rescue any assets that are not backing shares when the vault is not collateralized.
     * @dev Can be called only by the admin when the vault is not collateralized.
     */
    function rescueAssets() external;
}

contracts/interfaces/IVaultFee.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

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

/**
 * @title IVaultFee
 * @author StakeWise
 * @notice Defines the interface for the VaultFee contract
 */
interface IVaultFee is IVaultAdmin {
    /**
     * @notice Event emitted on fee recipient update
     * @param caller The address of the function caller
     * @param feeRecipient The address of the new fee recipient
     */
    event FeeRecipientUpdated(address indexed caller, address indexed feeRecipient);

    /**
     * @notice Event emitted on fee percent update
     * @param caller The address of the function caller
     * @param feePercent The new fee percent
     */
    event FeePercentUpdated(address indexed caller, uint16 feePercent);

    /**
     * @notice The Vault's fee recipient
     * @return The address of the Vault's fee recipient
     */
    function feeRecipient() external view returns (address);

    /**
     * @notice The Vault's fee percent in BPS
     * @return The fee percent applied by the Vault on the rewards
     */
    function feePercent() external view returns (uint16);

    /**
     * @notice Function for updating the fee recipient address. Can only be called by the admin.
     * @param _feeRecipient The address of the new fee recipient
     */
    function setFeeRecipient(address _feeRecipient) external;

    /**
     * @notice Function for updating the fee percent. Can only be called by the admin.
     * @param _feePercent The new fee percent
     */
    function setFeePercent(uint16 _feePercent) external;
}

contracts/interfaces/IVaultOsToken.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {IVaultState} from "./IVaultState.sol";
import {IVaultEnterExit} from "./IVaultEnterExit.sol";

/**
 * @title IVaultOsToken
 * @author StakeWise
 * @notice Defines the interface for the VaultOsToken contract
 */
interface IVaultOsToken is IVaultState, IVaultEnterExit {
    /**
     * @notice Event emitted on minting osToken
     * @param caller The address of the function caller
     * @param receiver The address of the osToken receiver
     * @param assets The amount of minted assets
     * @param shares The amount of minted shares
     * @param referrer The address of the referrer
     */
    event OsTokenMinted(address indexed caller, address receiver, uint256 assets, uint256 shares, address referrer);

    /**
     * @notice Event emitted on burning OsToken
     * @param caller The address of the function caller
     * @param assets The amount of burned assets
     * @param shares The amount of burned shares
     */
    event OsTokenBurned(address indexed caller, uint256 assets, uint256 shares);

    /**
     * @notice Event emitted on osToken position liquidation
     * @param caller The address of the function caller
     * @param user The address of the user liquidated
     * @param receiver The address of the receiver of the liquidated assets
     * @param osTokenShares The amount of osToken shares to liquidate
     * @param shares The amount of vault shares burned
     * @param receivedAssets The amount of assets received
     */
    event OsTokenLiquidated(
        address indexed caller,
        address indexed user,
        address receiver,
        uint256 osTokenShares,
        uint256 shares,
        uint256 receivedAssets
    );

    /**
     * @notice Event emitted on osToken position redemption
     * @param caller The address of the function caller
     * @param user The address of the position owner to redeem from
     * @param receiver The address of the receiver of the redeemed assets
     * @param osTokenShares The amount of osToken shares to redeem
     * @param shares The amount of vault shares burned
     * @param assets The amount of assets received
     */
    event OsTokenRedeemed(
        address indexed caller,
        address indexed user,
        address receiver,
        uint256 osTokenShares,
        uint256 shares,
        uint256 assets
    );

    /**
     * @notice Struct of osToken position
     * @param shares The total number of minted osToken shares. Will increase based on the treasury fee.
     * @param cumulativeFeePerShare The cumulative fee per share
     */
    struct OsTokenPosition {
        uint128 shares;
        uint128 cumulativeFeePerShare;
    }

    /**
     * @notice Get total amount of minted osToken shares
     * @param user The address of the user
     * @return shares The number of minted osToken shares
     */
    function osTokenPositions(address user) external view returns (uint128 shares);

    /**
     * @notice Mints OsToken shares
     * @param receiver The address that will receive the minted OsToken shares
     * @param osTokenShares The number of OsToken shares to mint to the receiver. To mint the maximum amount of shares, use 2^256 - 1.
     * @param referrer The address of the referrer
     * @return assets The number of assets minted to the receiver
     */
    function mintOsToken(address receiver, uint256 osTokenShares, address referrer) external returns (uint256 assets);

    /**
     * @notice Burns osToken shares
     * @param osTokenShares The number of shares to burn
     * @return assets The number of assets burned
     */
    function burnOsToken(uint128 osTokenShares) external returns (uint256 assets);

    /**
     * @notice Liquidates a user position and returns the number of received assets.
     *         Can only be called when health factor is below 1 by the liquidator.
     * @param osTokenShares The number of shares to cover
     * @param owner The address of the position owner to liquidate
     * @param receiver The address of the receiver of the liquidated assets
     */
    function liquidateOsToken(uint256 osTokenShares, address owner, address receiver) external;

    /**
     * @notice Redeems osToken shares for assets. Can only be called when health factor is above redeemFromHealthFactor by the redeemer.
     * @param osTokenShares The number of osToken shares to redeem
     * @param owner The address of the position owner to redeem from
     * @param receiver The address of the receiver of the redeemed assets
     */
    function redeemOsToken(uint256 osTokenShares, address owner, address receiver) external;

    /**
     * @notice Transfers minted osToken shares to the OsTokenVaultEscrow contract, enters the exit queue for staked assets
     * @param osTokenShares The number of osToken shares to transfer
     * @return positionTicket The exit position ticket
     */
    function transferOsTokenPositionToEscrow(uint256 osTokenShares) external returns (uint256 positionTicket);
}

contracts/interfaces/IVaultState.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {IKeeperRewards} from "./IKeeperRewards.sol";
import {IVaultFee} from "./IVaultFee.sol";

/**
 * @title IVaultState
 * @author StakeWise
 * @notice Defines the interface for the VaultState contract
 */
interface IVaultState is IVaultFee {
    /**
     * @notice Event emitted on checkpoint creation
     * @param shares The number of burned shares
     * @param assets The amount of exited assets
     */
    event CheckpointCreated(uint256 shares, uint256 assets);

    /**
     * @notice Event emitted on minting fee recipient shares
     * @param receiver The address of the fee recipient
     * @param shares The number of minted shares
     * @param assets The amount of minted assets
     */
    event FeeSharesMinted(address receiver, uint256 shares, uint256 assets);

    /**
     * @notice Event emitted when exiting assets are penalized (deprecated)
     * @param penalty The total penalty amount
     */
    event ExitingAssetsPenalized(uint256 penalty);

    /**
     * @notice Event emitted when the assets are donated to the Vault
     * @param sender The address of the sender
     * @param assets The amount of donated assets
     */
    event AssetsDonated(address sender, uint256 assets);

    /**
     * @notice Event emitted when the shares are donated to the Vault
     * @param sender The address of the sender
     * @param shares The number of donated shares
     */
    event SharesDonated(address sender, uint256 shares);

    /**
     * @notice Total assets in the Vault
     * @return The total amount of the underlying asset that is "managed" by Vault
     */
    function totalAssets() external view returns (uint256);

    /**
     * @notice Function for retrieving total shares
     * @return The amount of shares in existence
     */
    function totalShares() external view returns (uint256);

    /**
     * @notice The Vault's capacity
     * @return The amount after which the Vault stops accepting deposits
     */
    function capacity() external view returns (uint256);

    /**
     * @notice Total assets available in the Vault. They can be staked or withdrawn.
     * @return The total amount of withdrawable assets
     */
    function withdrawableAssets() external view returns (uint256);

    /**
     * @notice Get exit queue data
     * @return queuedShares The number of shares in the exit queue
     * @return unclaimedAssets The amount of unclaimed assets in the exit queue
     * @return totalExitingTickets The total number of exiting tickets
     * @return totalExitingAssets The total amount of exiting assets
     * @return totalTickets The total number of tickets in the exit queue
     */
    function getExitQueueData()
        external
        view
        returns (
            uint128 queuedShares,
            uint128 unclaimedAssets,
            uint128 totalExitingTickets,
            uint128 totalExitingAssets,
            uint256 totalTickets
        );

    /**
     * @notice Returns the number of shares held by an account
     * @param account The account for which to look up the number of shares it has, i.e. its balance
     * @return The number of shares held by the account
     */
    function getShares(address account) external view returns (uint256);

    /**
     * @notice Converts assets to shares
     * @param assets The amount of assets to convert to shares
     * @return shares The amount of shares that the Vault would exchange for the amount of assets provided
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @notice Converts shares to assets
     * @param shares The amount of shares to convert to assets
     * @return assets The amount of assets that the Vault would exchange for the amount of shares provided
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @notice Donates shares to the Vault by burning them from the caller,
     *         increasing the value per share for remaining holders
     * @param shares The number of shares to donate
     */
    function donateShares(uint256 shares) external;

    /**
     * @notice Check whether state update is required
     * @return `true` if state update is required, `false` otherwise
     */
    function isStateUpdateRequired() external view returns (bool);

    /**
     * @notice Updates the total amount of assets in the Vault and its exit queue
     * @param harvestParams The parameters for harvesting Keeper rewards
     */
    function updateState(IKeeperRewards.HarvestParams calldata harvestParams) external;
}

contracts/interfaces/IVaultSubVaults.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

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

/**
 * @title IVaultSubVaults
 * @author StakeWise
 * @notice Defines the interface for the VaultSubVaults contract
 */
interface IVaultSubVaults is IVaultState {
    /**
     * @notice Emitted when the rewards nonce is updated
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param rewardsNonce The new rewards nonce
     */
    event RewardsNonceUpdated(uint256 rewardsNonce);

    /**
     * @notice Emitted when the sub vaults are harvested
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param totalAssetsDelta The change in total assets after the harvest
     */
    event SubVaultsHarvested(int256 totalAssetsDelta);

    /**
     * @notice Emitted when the new sub-vault is added
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param caller The address of the caller
     * @param vault The address of the sub-vault
     */
    event SubVaultAdded(address indexed caller, address indexed vault);

    /**
     * @notice Emitted when the sub-vault is ejecting
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param caller The address of the caller
     * @param vault The address of the sub-vault
     */
    event SubVaultEjecting(address indexed caller, address indexed vault);

    /**
     * @notice Emitted when the sub-vault is ejected
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param caller The address of the caller
     * @param vault The address of the sub-vault
     */
    event SubVaultEjected(address indexed caller, address indexed vault);

    /**
     * @notice Emitted when the sub-vaults curator is updated
     * @dev Deprecated: moved to SubVaultsRegistry
     * @param caller The address of the caller
     * @param curator The address of the new sub-vaults curator
     */
    event SubVaultsCuratorUpdated(address indexed caller, address indexed curator);

    /**
     * @notice Returns the address of the SubVaultsRegistry contract
     * @return The address of the SubVaultsRegistry
     */
    function subVaultsRegistry() external view returns (address);

    /**
     * @notice Function to deposit assets to a sub vault. Can only be called by SubVaultsRegistry contract.
     * @param vault The address of the sub-vault
     * @param assets The amount of assets to deposit
     * @return shares The amount of vault shares received
     */
    function depositToSubVault(address vault, uint256 assets) external returns (uint256 shares);

    /**
     * @notice Function to enter sub-vault exit queue. Can only be called by SubVaultsRegistry contract.
     * @param vault The address of the sub-vault
     * @param shares The amount of shares to exit
     * @return positionTicket The position ticket in the exit queue
     */
    function enterSubVaultExitQueue(address vault, uint256 shares) external returns (uint256 positionTicket);

    /**
     * @notice Function to claim exited assets from a sub-vault. Can only be called by SubVaultsRegistry contract.
     * @param vault The address of the sub-vault
     * @param positionTicket The position ticket in the exit queue
     * @param timestamp The timestamp of the exit request
     * @param exitQueueIndex The index of the exit queue
     */
    function claimSubVaultExitedAssets(address vault, uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex)
        external;

    /**
     * @notice Function to mint osToken for a sub-vault. Can only be called by SubVaultsRegistry contract.
     * @param vault The address of the sub-vault
     * @param receiver The address that will receive the minted osToken shares
     * @param osTokenShares The amount of osToken shares to mint
     */
    function mintSubVaultOsToken(address vault, address receiver, uint256 osTokenShares) external;

    /**
     * @notice Function to redeem osToken from a sub-vault. Can only be called by SubVaultsRegistry contract.
     * @param vault The address of the sub-vault
     * @param redeemer The address of the OsToken redeemer
     * @param osTokenShares The amount of osToken shares to redeem
     * @return assets The amount of assets redeemed
     */
    function redeemSubVaultOsToken(address vault, address redeemer, uint256 osTokenShares)
        external
        returns (uint256 assets);
}

contracts/interfaces/IVaultsRegistry.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

/**
 * @title IVaultsRegistry
 * @author StakeWise
 * @notice Defines the interface for the VaultsRegistry
 */
interface IVaultsRegistry {
    /**
     * @notice Event emitted on a Vault addition
     * @param caller The address that has added the Vault
     * @param vault The address of the added Vault
     */
    event VaultAdded(address indexed caller, address indexed vault);

    /**
     * @notice Event emitted on adding Vault implementation contract
     * @param impl The address of the new implementation contract
     */
    event VaultImplAdded(address indexed impl);

    /**
     * @notice Event emitted on removing Vault implementation contract
     * @param impl The address of the removed implementation contract
     */
    event VaultImplRemoved(address indexed impl);

    /**
     * @notice Event emitted on whitelisting the factory
     * @param factory The address of the whitelisted factory
     */
    event FactoryAdded(address indexed factory);

    /**
     * @notice Event emitted on removing the factory from the whitelist
     * @param factory The address of the factory removed from the whitelist
     */
    event FactoryRemoved(address indexed factory);

    /**
     * @notice Registered Vaults
     * @param vault The address of the vault to check whether it is registered
     * @return `true` for the registered Vault, `false` otherwise
     */
    function vaults(address vault) external view returns (bool);

    /**
     * @notice Registered Vault implementations
     * @param impl The address of the vault implementation
     * @return `true` for the registered implementation, `false` otherwise
     */
    function vaultImpls(address impl) external view returns (bool);

    /**
     * @notice Registered Factories
     * @param factory The address of the factory to check whether it is whitelisted
     * @return `true` for the whitelisted Factory, `false` otherwise
     */
    function factories(address factory) external view returns (bool);

    /**
     * @notice Function for adding Vault to the registry. Can only be called by the whitelisted Factory.
     * @param vault The address of the Vault to add
     */
    function addVault(address vault) external;

    /**
     * @notice Function for adding Vault implementation contract
     * @param newImpl The address of the new implementation contract
     */
    function addVaultImpl(address newImpl) external;

    /**
     * @notice Function for removing Vault implementation contract
     * @param impl The address of the removed implementation contract
     */
    function removeVaultImpl(address impl) external;

    /**
     * @notice Function for adding the factory to the whitelist
     * @param factory The address of the factory to add to the whitelist
     */
    function addFactory(address factory) external;

    /**
     * @notice Function for removing the factory from the whitelist
     * @param factory The address of the factory to remove from the whitelist
     */
    function removeFactory(address factory) external;

    /**
     * @notice Function for initializing the registry. Can only be called once during the deployment.
     * @param _owner The address of the owner of the contract
     */
    function initialize(address _owner) external;
}

contracts/libraries/Errors.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

/**
 * @title Errors
 * @author StakeWise
 * @notice Contains all the custom errors
 */
library Errors {
    error AccessDenied();
    error InvalidShares();
    error InvalidAssets();
    error ZeroAddress();
    error CapacityExceeded();
    error InvalidCapacity();
    error InvalidSecurityDeposit();
    error InvalidFeeRecipient();
    error InvalidFeePercent();
    error NotHarvested();
    error NotCollateralized();
    error Collateralized();
    error InvalidProof();
    error LowLtv();
    error InvalidPosition();
    error InvalidHealthFactor();
    error InvalidReceivedAssets();
    error InvalidTokenMeta();
    error UpgradeFailed();
    error InvalidValidators();
    error DeadlineExpired();
    error PermitInvalidSigner();
    error InvalidValidatorsRegistryRoot();
    error InvalidVault();
    error AlreadyAdded();
    error AlreadyRemoved();
    error InvalidOracles();
    error NotEnoughSignatures();
    error InvalidOracle();
    error TooEarlyUpdate();
    error InvalidAvgRewardPerSecond();
    error InvalidRewardsRoot();
    error HarvestFailed();
    error LiquidationDisabled();
    error InvalidLiqThresholdPercent();
    error InvalidLiqBonusPercent();
    error InvalidLtvPercent();
    error InvalidCheckpointIndex();
    error InvalidCheckpointValue();
    error MaxOraclesExceeded();
    error ExitRequestNotProcessed();
    error ValueNotChanged();
    error FlashLoanFailed();
    error CannotTopUpV1Validators();
    error InvalidSignatures();
    error EmptySubVaults();
    error EjectingVaultNotFound();
    error EjectingVault();
    error RepeatedEjectingVault();
    error UnclaimedAssets();
    error InvalidCurator();
    error RewardsNonceIsHigher();
    error InvalidRedeemablePositions();
    error InvalidDelay();
    error InvalidTicket();
    error LowBalance();
    error InvalidMinBalancePercent();
}

contracts/libraries/ExitQueue.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Errors} from "./Errors.sol";

/**
 * @title ExitQueue
 * @author StakeWise
 * @notice ExitQueue represent checkpoints of burned shares and exited assets
 */
library ExitQueue {
    /**
     * @notice A struct containing checkpoint data
     * @param totalTickets The cumulative number of tickets (shares) exited
     * @param exitedAssets The number of assets that exited in this checkpoint
     */
    struct Checkpoint {
        uint160 totalTickets;
        uint96 exitedAssets;
    }

    /**
     * @notice A struct containing the history of checkpoints data
     * @param checkpoints An array of checkpoints
     */
    struct History {
        Checkpoint[] checkpoints;
    }

    /**
     * @notice Get the latest checkpoint total tickets
     * @param self An array containing checkpoints
     * @return The current total tickets or zero if there are no checkpoints
     */
    function getLatestTotalTickets(History storage self) internal view returns (uint256) {
        uint256 pos = self.checkpoints.length;
        unchecked {
            // cannot underflow as subtraction happens in case pos > 0
            return pos == 0 ? 0 : _unsafeAccess(self.checkpoints, pos - 1).totalTickets;
        }
    }

    /**
     * @notice Get checkpoint index for the burned shares
     * @param self An array containing checkpoints
     * @param positionTicket The position ticket to search the closest checkpoint for
     * @return The checkpoint index or the length of checkpoints array in case there is no such
     */
    function getCheckpointIndex(History storage self, uint256 positionTicket) external view returns (uint256) {
        uint256 high = self.checkpoints.length;
        uint256 low;
        while (low < high) {
            uint256 mid = Math.average(low, high);
            if (_unsafeAccess(self.checkpoints, mid).totalTickets > positionTicket) {
                high = mid;
            } else {
                unchecked {
                    // cannot underflow as mid < high
                    low = mid + 1;
                }
            }
        }
        return high;
    }

    /**
     * @notice Calculates burned shares and exited assets
     * @param self An array containing checkpoints
     * @param checkpointIdx The index of the checkpoint to start calculating from
     * @param positionTicket The position ticket to start calculating exited assets from
     * @param positionShares The number of shares to calculate assets for
     * @return burnedShares The number of shares burned
     * @return exitedAssets The number of assets exited
     */
    function calculateExitedAssets(
        History storage self,
        uint256 checkpointIdx,
        uint256 positionTicket,
        uint256 positionShares
    ) external view returns (uint256 burnedShares, uint256 exitedAssets) {
        uint256 length = self.checkpoints.length;
        // there are no exited assets for such checkpoint index or no shares to burn
        if (checkpointIdx >= length || positionShares == 0) return (0, 0);

        // previous total tickets for calculating how much shares were burned for the period
        uint256 prevTotalTickets;
        unchecked {
            // cannot underflow as subtraction happens in case checkpointIdx > 0
            prevTotalTickets = checkpointIdx == 0 ? 0 : _unsafeAccess(self.checkpoints, checkpointIdx - 1).totalTickets;
        }

        // current total tickets for calculating assets per burned share
        // can be used with _unsafeAccess as checkpointIdx < length
        Checkpoint memory checkpoint = _unsafeAccess(self.checkpoints, checkpointIdx);
        uint256 currTotalTickets = checkpoint.totalTickets;
        uint256 checkpointAssets = checkpoint.exitedAssets;
        // check whether position ticket is in [prevTotalTickets, currTotalTickets) range
        if (positionTicket < prevTotalTickets || currTotalTickets <= positionTicket) {
            revert Errors.InvalidCheckpointIndex();
        }

        if (currTotalTickets > 1 && checkpointAssets == 0 && checkpointIdx + 1 < length) {
            // only single checkpoint created during V2 -> V3 migration can pass this if
            checkpoint = _unsafeAccess(self.checkpoints, checkpointIdx + 1);
            uint256 totalShares = checkpoint.totalTickets - currTotalTickets;
            if (positionShares > totalShares) {
                revert Errors.InvalidShares();
            }
            return (positionShares, Math.mulDiv(positionShares, checkpoint.exitedAssets, totalShares));
        }

        // calculate amount of available shares that will be updated while iterating over checkpoints
        uint256 availableShares;
        unchecked {
            // cannot underflow as positionTicket < currTotalTickets
            availableShares = currTotalTickets - positionTicket;
        }

        // accumulate assets until the number of required shares is collected
        while (true) {
            unchecked {
                // cannot underflow as prevTotalTickets <= positionTicket
                uint256 checkpointShares = currTotalTickets - prevTotalTickets;
                // cannot underflow as positionShares > burnedShares while in the loop
                uint256 sharesDelta = Math.min(availableShares, positionShares - burnedShares);

                // cannot overflow as it is capped with underlying asset total supply
                burnedShares += sharesDelta;
                exitedAssets += Math.mulDiv(sharesDelta, checkpointAssets, checkpointShares);

                // cannot overflow as checkpoints are created max once per day
                checkpointIdx++;
            }

            // stop when required shares collected or reached end of checkpoints list
            if (positionShares <= burnedShares || checkpointIdx >= length) {
                return (burnedShares, exitedAssets);
            }

            // take next checkpoint
            prevTotalTickets = currTotalTickets;
            // can use _unsafeAccess as checkpointIdx < length is checked above
            checkpoint = _unsafeAccess(self.checkpoints, checkpointIdx);
            currTotalTickets = checkpoint.totalTickets;
            checkpointAssets = checkpoint.exitedAssets;

            unchecked {
                // cannot underflow as every next checkpoint total tickets is larger than previous
                availableShares = currTotalTickets - prevTotalTickets;
            }
        }
    }

    /**
     * @notice Pushes a new checkpoint onto a History
     * @param self An array containing checkpoints
     * @param shares The number of shares to add to the latest checkpoint
     * @param assets The number of assets that were exited for this checkpoint
     */
    function push(History storage self, uint256 shares, uint256 assets) internal {
        if (shares == 0) revert Errors.InvalidCheckpointValue();
        Checkpoint memory checkpoint = Checkpoint({
            totalTickets: SafeCast.toUint160(getLatestTotalTickets(self) + shares),
            exitedAssets: SafeCast.toUint96(assets)
        });
        self.checkpoints.push(checkpoint);
    }

    function _unsafeAccess(Checkpoint[] storage self, uint256 pos) private pure returns (Checkpoint storage result) {
        assembly {
            mstore(0, self.slot)
            result.slot := add(keccak256(0, 0x20), pos)
        }
    }
}

contracts/tokens/OsTokenRedeemer.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.22;

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IKeeperRewards} from "../interfaces/IKeeperRewards.sol";
import {IOsTokenRedeemer} from "../interfaces/IOsTokenRedeemer.sol";
import {IOsTokenVaultController} from "../interfaces/IOsTokenVaultController.sol";
import {IVaultOsToken} from "../interfaces/IVaultOsToken.sol";
import {IVaultState} from "../interfaces/IVaultState.sol";
import {IVaultSubVaults} from "../interfaces/IVaultSubVaults.sol";
import {ISubVaultsRegistry} from "../interfaces/ISubVaultsRegistry.sol";
import {IVaultsRegistry} from "../interfaces/IVaultsRegistry.sol";
import {Multicall} from "../base/Multicall.sol";
import {Errors} from "../libraries/Errors.sol";
import {ExitQueue} from "../libraries/ExitQueue.sol";

/**
 * @title OsTokenRedeemer
 * @author StakeWise
 * @notice This contract is used to redeem OsTokens for the underlying asset.
 */
abstract contract OsTokenRedeemer is Ownable2Step, Multicall, IOsTokenRedeemer {
    uint256 private constant _maxPercent = 10_000; // @dev 100.00 %

    IVaultsRegistry private immutable _vaultsRegistry;
    IERC20 private immutable _osToken;
    IOsTokenVaultController private immutable _osTokenVaultController;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public immutable override exitQueueUpdateDelay;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public immutable override maxRedemptionFeePercent;

    /// @inheritdoc IOsTokenRedeemer
    address public override positionsManager;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public override nonce;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override queuedShares;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override unclaimedAssets;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override redeemedShares;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override redeemedAssets;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override swappedShares;

    /// @inheritdoc IOsTokenRedeemer
    uint128 public override swappedAssets;

    /// @inheritdoc IOsTokenRedeemer
    mapping(bytes32 leaf => uint256 processedShares) public override leafToProcessedShares;

    /// @inheritdoc IOsTokenRedeemer
    mapping(bytes32 exitRequestHash => uint256 shares) public override exitRequests;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public override exitQueueTimestamp;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public override redemptionFeePercent;

    /// @inheritdoc IOsTokenRedeemer
    uint256 public override accumulatedFees;

    RedeemablePositions private _redeemablePositions;
    ExitQueue.History private _exitQueue;

    /**
     * @dev Constructor
     * @param vaultsRegistry_ The address of the VaultsRegistry contract
     * @param osToken_ The address of the OsToken contract
     * @param osTokenVaultController_ The address of the OsTokenVaultController contract
     * @param owner_ The address of the owner
     * @param exitQueueUpdateDelay_ The delay in seconds for exit queue updates
     * @param maxRedemptionFeePercent_ The maximum redemption fee in basis points
     */
    constructor(
        address vaultsRegistry_,
        address osToken_,
        address osTokenVaultController_,
        address owner_,
        uint256 exitQueueUpdateDelay_,
        uint256 maxRedemptionFeePercent_
    ) Ownable(owner_) {
        if (exitQueueUpdateDelay_ > type(uint64).max) {
            revert Errors.InvalidDelay();
        }
        if (maxRedemptionFeePercent_ > _maxPercent) {
            revert Errors.InvalidFeePercent();
        }
        _vaultsRegistry = IVaultsRegistry(vaultsRegistry_);
        _osToken = IERC20(osToken_);
        _osTokenVaultController = IOsTokenVaultController(osTokenVaultController_);
        exitQueueUpdateDelay = exitQueueUpdateDelay_;
        maxRedemptionFeePercent = maxRedemptionFeePercent_;
    }

    /// @inheritdoc IOsTokenRedeemer
    function getExitQueueData() public view override returns (uint256, uint256, uint256) {
        return (
            queuedShares,
            unclaimedAssets + redeemedAssets + swappedAssets,
            ExitQueue.getLatestTotalTickets(_exitQueue) + redeemedShares + swappedShares
        );
    }

    /// @inheritdoc IOsTokenRedeemer
    function getExitQueueCumulativeTickets() external view override returns (uint256) {
        (uint256 _queuedShares,, uint256 totalTickets) = getExitQueueData();
        return totalTickets + _queuedShares;
    }

    /// @inheritdoc IOsTokenRedeemer
    function redeemablePositions() external view override returns (bytes32 merkleRoot, string memory ipfsHash) {
        merkleRoot = _redeemablePositions.merkleRoot;
        ipfsHash = _redeemablePositions.ipfsHash;
    }

    /// @inheritdoc IOsTokenRedeemer
    function getExitQueueIndex(uint256 positionTicket) external view override returns (int256) {
        uint256 checkpointIdx = ExitQueue.getCheckpointIndex(_exitQueue, positionTicket);
        return checkpointIdx < _exitQueue.checkpoints.length ? int256(checkpointIdx) : -1;
    }

    /// @inheritdoc IOsTokenRedeemer
    function canProcessExitQueue() external view override returns (bool) {
        if (exitQueueTimestamp + exitQueueUpdateDelay > block.timestamp) {
            return false;
        }
        uint256 processedShares = swappedShares + redeemedShares;
        uint256 processedAssets = swappedAssets + redeemedAssets;
        return processedShares > 0 && processedAssets > 0;
    }

    /// @inheritdoc IOsTokenRedeemer
    function calculateExitedAssets(address receiver, uint256 positionTicket, uint256 exitQueueIndex)
        public
        view
        override
        returns (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets)
    {
        uint256 exitingTickets = exitRequests[keccak256(abi.encode(receiver, positionTicket))];
        if (exitingTickets == 0) return (0, 0, 0);

        // calculate exited tickets and assets
        (exitedTickets, exitedAssets) =
            ExitQueue.calculateExitedAssets(_exitQueue, exitQueueIndex, positionTicket, exitingTickets);
        leftTickets = exitingTickets - exitedTickets;
        if (leftTickets == 1) {
            // if only one ticket is left round it to zero
            leftTickets = 0;
            exitedTickets += 1; // round up exited tickets
        }
    }

    /// @inheritdoc IOsTokenRedeemer
    function setPositionsManager(address positionsManager_) external override onlyOwner {
        if (positionsManager_ == address(0)) {
            revert Errors.ZeroAddress();
        }
        if (positionsManager_ == positionsManager) {
            revert Errors.ValueNotChanged();
        }
        positionsManager = positionsManager_;
        emit PositionsManagerUpdated(positionsManager_);
    }

    /// @inheritdoc IOsTokenRedeemer
    function setRedemptionFeePercent(uint256 redemptionFeePercent_) external override onlyOwner {
        if (redemptionFeePercent_ > maxRedemptionFeePercent) {
            revert Errors.InvalidFeePercent();
        }
        if (redemptionFeePercent_ == redemptionFeePercent) {
            revert Errors.ValueNotChanged();
        }
        redemptionFeePercent = redemptionFeePercent_;
        emit FeeUpdated(redemptionFeePercent_);
    }

    /// @inheritdoc IOsTokenRedeemer
    function claimFees(address receiver) external override onlyOwner {
        if (receiver == address(0)) revert Errors.ZeroAddress();

        // SLOAD to memory
        uint256 fees = accumulatedFees;
        if (fees == 0) revert Errors.InvalidShares();

        // update state
        accumulatedFees = 0;

        // transfer OsToken shares to the receiver
        SafeERC20.safeTransfer(_osToken, receiver, fees);
        emit FeesClaimed(receiver, fees);
    }

    /// @inheritdoc IOsTokenRedeemer
    function getExitQueueMissingAssets(uint256 targetCumulativeTickets)
        external
        view
        override
        returns (uint256 missingAssets)
    {
        // SLOAD to memory
        (uint256 _queuedShares,, uint256 totalTickets) = getExitQueueData();

        // check whether already covered
        if (totalTickets >= targetCumulativeTickets || _queuedShares == 0) {
            return 0;
        }

        // calculate the amount of tickets that need to be covered
        uint256 totalTicketsToCover = targetCumulativeTickets - totalTickets;

        // calculate missing assets
        missingAssets = _osTokenVaultController.convertToAssets(Math.min(totalTicketsToCover, _queuedShares));
    }

    /// @inheritdoc IOsTokenRedeemer
    function setRedeemablePositions(RedeemablePositions calldata newPositions) external override onlyOwner {
        if (newPositions.merkleRoot == bytes32(0) || bytes(newPositions.ipfsHash).length == 0) {
            revert Errors.InvalidRedeemablePositions();
        }

        if (newPositions.merkleRoot == _redeemablePositions.merkleRoot) {
            revert Errors.ValueNotChanged();
        }

        // update state
        nonce += 1;
        _redeemablePositions = newPositions;

        // emit event
        emit RedeemablePositionsUpdated(newPositions.merkleRoot, newPositions.ipfsHash);
    }

    /// @inheritdoc IOsTokenRedeemer
    function permitOsToken(uint256 shares, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override {
        try IERC20Permit(address(_osToken)).permit(msg.sender, address(this), shares, deadline, v, r, s) {} catch {}
    }

    /// @inheritdoc IOsTokenRedeemer
    function enterExitQueue(uint256 shares, address receiver) external override returns (uint256 positionTicket) {
        if (shares == 0) revert Errors.InvalidShares();
        if (receiver == address(0)) revert Errors.ZeroAddress();

        // deduct redemption fee in OsToken shares, rounded up in favor of the protocol
        uint256 fee = Math.mulDiv(shares, redemptionFeePercent, _maxPercent, Math.Rounding.Ceil);
        uint256 exitingShares = shares - fee;
        if (exitingShares == 0) revert Errors.InvalidShares();

        // SLOAD to memory
        uint256 _queuedShares = queuedShares;

        // calculate position ticket
        positionTicket = ExitQueue.getLatestTotalTickets(_exitQueue) + swappedShares + redeemedShares + _queuedShares;

        // add to the exit requests
        exitRequests[keccak256(abi.encode(receiver, positionTicket))] = exitingShares;

        // reverts if owner does not have enough shares
        SafeERC20.safeTransferFrom(_osToken, msg.sender, address(this), shares);

        unchecked {
            // cannot overflow as it is capped with OsToken total supply
            queuedShares = SafeCast.toUint128(_queuedShares + exitingShares);
        }
        if (fee > 0) accumulatedFees += fee;

        // emit event
        emit ExitQueueEntered(msg.sender, receiver, positionTicket, exitingShares, fee);
    }

    /// @inheritdoc IOsTokenRedeemer
    function claimExitedAssets(uint256 positionTicket, uint256 exitQueueIndex) external override {
        // calculate exited tickets and assets
        (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets) =
            calculateExitedAssets(msg.sender, positionTicket, exitQueueIndex);
        if (exitedTickets == 0 || exitedAssets == 0) {
            revert Errors.ExitRequestNotProcessed();
        }

        // update unclaimed assets
        unclaimedAssets -= SafeCast.toUint128(exitedAssets);

        // clean up current exit request
        delete exitRequests[keccak256(abi.encode(msg.sender, positionTicket))];

        // create new position if there are left tickets
        uint256 newPositionTicket;
        if (leftTickets > 0) {
            // update user's queue position
            newPositionTicket = positionTicket + exitedTickets;
            exitRequests[keccak256(abi.encode(msg.sender, newPositionTicket))] = leftTickets;
        }

        // transfer assets to the receiver
        _transferAssets(msg.sender, exitedAssets);
        emit ExitedAssetsClaimed(msg.sender, positionTicket, newPositionTicket, exitedAssets);
    }

    /// @inheritdoc IOsTokenRedeemer
    function redeemSubVaultsAssets(address metaVault, uint256 assetsToRedeem)
        external
        override
        returns (uint256 totalRedeemedAssets)
    {
        if (msg.sender != positionsManager) {
            revert Errors.AccessDenied();
        }

        if (!_isMetaVault(metaVault)) {
            revert Errors.InvalidVault();
        }

        return ISubVaultsRegistry(IVaultSubVaults(metaVault).subVaultsRegistry()).redeemSubVaultsAssets(assetsToRedeem);
    }

    /// @inheritdoc IOsTokenRedeemer
    function redeemSubVaultOsToken(address subVault, uint256 osTokenShares) external override returns (uint256) {
        if (!_vaultsRegistry.vaults(subVault) || !_isMetaVault(msg.sender)) {
            revert Errors.AccessDenied();
        }
        if (osTokenShares == 0) {
            revert Errors.InvalidShares();
        }

        uint256 _vaultAssetsBefore = _getAssets(msg.sender);

        // redeem osToken shares from sub vault to meta vault
        IVaultOsToken(subVault).redeemOsToken(osTokenShares, msg.sender, msg.sender);

        // calculate redeemed assets
        return _getAssets(msg.sender) - _vaultAssetsBefore;
    }

    /// @inheritdoc IOsTokenRedeemer
    function redeemOsTokenPositions(
        OsTokenPosition[] memory positions,
        bytes32[] calldata proof,
        bool[] calldata proofFlags
    ) external override {
        if (msg.sender != positionsManager) {
            revert Errors.AccessDenied();
        }

        // SLOAD to memory
        uint256 _queuedShares = queuedShares;
        uint256 positionsCount = positions.length;
        if (_queuedShares == 0 || positionsCount == 0) {
            return; // nothing to redeem
        }

        // calculate leaves and total osTokenShares to redeem
        bytes32[] memory leaves = new bytes32[](positionsCount);

        // SLOAD to memory
        uint256 _nonce = nonce - 1; // use nonce - 1 to match the leaf calculation
        for (uint256 i = 0; i < positionsCount;) {
            OsTokenPosition memory position = positions[i];

            // calculate leaf
            bytes32 leaf = keccak256(
                bytes.concat(keccak256(abi.encode(_nonce, position.vault, position.leafShares, position.owner)))
            );
            leaves[i] = leaf;

            // SLOAD processed osToken shares
            uint256 processedPositionShares = leafToProcessedShares[leaf];

            // calculate osToken shares to redeem and corresponding assets
            uint256 sharesToRedeem = Math.min(
                Math.min(position.leafShares - processedPositionShares, position.sharesToRedeem),
                Math.min(_queuedShares, IVaultOsToken(position.vault).osTokenPositions(position.owner))
            );
            // update state
            if (sharesToRedeem > 0) {
                unchecked {
                    // sharesToRedeem <= _queuedShares checked above
                    _queuedShares -= sharesToRedeem;
                    // cannot realistically overflow
                    leafToProcessedShares[leaf] = processedPositionShares + sharesToRedeem;
                }
            }
            position.sharesToRedeem = sharesToRedeem;

            unchecked {
                // cannot realistically overflow
                ++i;
            }
        }

        // verify the proof
        bytes32 positionsRoot = _redeemablePositions.merkleRoot;
        if (positionsRoot == bytes32(0)) {
            revert Errors.InvalidRedeemablePositions();
        }
        if (!MerkleProof.multiProofVerifyCalldata(proof, proofFlags, positionsRoot, leaves)) {
            revert Errors.InvalidProof();
        }

        // redeem positions
        uint256 availableAssetsBefore = _getAssets(address(this));
        for (uint256 i = 0; i < positionsCount;) {
            OsTokenPosition memory position = positions[i];
            if (position.sharesToRedeem > 0) {
                // redeem osToken shares
                IVaultOsToken(position.vault).redeemOsToken(position.sharesToRedeem, position.owner, address(this));
            }

            unchecked {
                // cannot realistically overflow
                ++i;
            }
        }

        // calculate processed assets and shares
        uint256 processedAssets = _getAssets(address(this)) - availableAssetsBefore;
        uint256 processedShares = queuedShares - _queuedShares;

        // update state
        redeemedShares += SafeCast.toUint128(processedShares);
        redeemedAssets += SafeCast.toUint128(processedAssets);
        queuedShares = SafeCast.toUint128(_queuedShares);

        // emit event
        emit OsTokenPositionsRedeemed(processedShares, processedAssets);
    }

    /// @inheritdoc IOsTokenRedeemer
    function processExitQueue() external override {
        if (exitQueueTimestamp + exitQueueUpdateDelay > block.timestamp) {
            revert Errors.TooEarlyUpdate();
        }

        // update state
        uint256 processedShares = swappedShares + redeemedShares;
        uint256 processedAssets = swappedAssets + redeemedAssets;
        if (processedShares == 0) {
            revert Errors.InvalidShares();
        }
        if (processedAssets == 0) {
            revert Errors.InvalidAssets();
        }
        swappedShares = 0;
        swappedAssets = 0;
        redeemedShares = 0;
        redeemedAssets = 0;

        unclaimedAssets += SafeCast.toUint128(processedAssets);

        // push checkpoint so that exited assets could be claimed
        ExitQueue.push(_exitQueue, processedShares, processedAssets);
        exitQueueTimestamp = block.timestamp;
        emit CheckpointCreated(processedShares, processedAssets);
    }

    /// @inheritdoc IOsTokenRedeemer
    function updateVaultState(address vault, IKeeperRewards.HarvestParams calldata harvestParams) external override {
        // must be a registered vault
        if (!_vaultsRegistry.vaults(vault)) {
            revert Errors.InvalidVault();
        }
        IVaultState(vault).updateState(harvestParams);
    }

    /**
     * @dev Internal function to swap assets to OsToken shares
     * @param receiver The address that will receive the OsToken shares
     * @param assets The number of assets to swap
     * @return osTokenShares The number of OsToken shares swapped
     */
    function _swapAssetsToOsTokenShares(address receiver, uint256 assets) internal returns (uint256 osTokenShares) {
        if (assets == 0) {
            revert Errors.InvalidAssets();
        }
        if (receiver == address(0)) revert Errors.ZeroAddress();

        osTokenShares = _osTokenVaultController.convertToShares(assets);
        if (osTokenShares == 0) {
            revert Errors.InvalidShares();
        }

        // update state
        queuedShares -= SafeCast.toUint128(osTokenShares);
        swappedShares += SafeCast.toUint128(osTokenShares);
        swappedAssets += SafeCast.toUint128(assets);

        // transfer OsToken shares to the receiver
        SafeERC20.safeTransfer(_osToken, receiver, osTokenShares);

        // emit event
        emit OsTokenSharesSwapped(msg.sender, receiver, osTokenShares, assets);
    }

    /**
     * @dev Internal function to check whether the caller is a meta vault
     * @param vault The address of the vault to check
     * @return True if the caller is a meta vault, false otherwise
     */
    function _isMetaVault(address vault) private view returns (bool) {
        // must be a registered vault
        if (!_vaultsRegistry.vaults(vault)) {
            return false;
        }

        // must be a meta vault
        try IVaultSubVaults(vault).subVaultsRegistry() {
            return true;
        } catch {
            return false;
        }
    }

    /**
     * @dev Internal function that must be implemented to return the account assets
     * @param account The address of the account
     * @return The amount of assets in the vault
     */
    function _getAssets(address account) internal view virtual returns (uint256);

    /**
     * @dev Internal function for transferring assets to the receiver
     * @dev IMPORTANT: because control is transferred to the receiver, care must be
     *    taken to not create reentrancy vulnerabilities. The Vault must follow the checks-effects-interactions pattern:
     *    https://docs.soliditylang.org/en/v0.8.22/security-considerations.html#use-the-checks-effects-interactions-pattern
     * @param receiver The address that will receive the assets
     * @param assets The number of assets to transfer
     */
    function _transferAssets(address receiver, uint256 assets) internal virtual;
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/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-upgradeable/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-upgradeable/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-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol

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

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/openzeppelin-contracts-upgradeable/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-upgradeable/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-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.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, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

lib/openzeppelin-contracts-upgradeable/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-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

lib/openzeppelin-contracts-upgradeable/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-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/openzeppelin-contracts-upgradeable/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))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "contracts/tokens/EthOsTokenRedeemer.sol": {
      "ExitQueue": "0x723399c5a3503a53af1bdf89bda7d6d1025cab97"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.