Skip to content
Verified contractExactLGPL-3.0-only

YearnModule

Address0x20caccb5e28bcbf6d0bbb68bf6dfc58548113c29
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.30

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
LGPL-3.0-only
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,454,270
Creation transaction
0x695ee16a9c…3c49516205

31 files

contracts/modules/YearnModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

import {IBaseModule} from "../interfaces/modules/IBaseModule.sol";
import {IYearnModule} from "../interfaces/modules/IYearnModule.sol";

import {IYearn4626Router} from "../interfaces/yearn/IYearn4626Router.sol";
import {IYearnRegistry} from "../interfaces/yearn/IYearnRegistry.sol";
import {IYearn4626} from "../interfaces/yearn/IYearn4626.sol";

import {Permissions} from "../libs/Permissions.sol";

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

contract YearnModule is IYearnModule, BaseModule {
    address public immutable yearn4626Router;

    constructor(address addressProvider, address yearn4626RouterAddr) BaseModule(addressProvider) {
        yearn4626Router = yearn4626RouterAddr;
    }

    /// @inheritdoc IYearnModule
    function executeYearnDeposit(
        address safe,
        DepositParams calldata params
    ) external onlyWhitelistedVault(safe, address(params.vault)) {
        address asset = params.vault.asset();

        _onlyWhitelistedToken(safe, asset);

        if (params.withWrap) {
            _executeWrapNative(safe, asset, params.amount);
        }
        if (params.withApproval) {
            _executeApproval(safe, asset, yearn4626Router, params.amount);
        }

        _yearnDeposit(safe, params);
    }

    /// @inheritdoc IYearnModule
    function executeYearnRedeem(
        address safe,
        RedeemParams calldata params
    ) external onlyWhitelistedVault(safe, address(params.vault)) {
        _onlyWhitelistedToken(safe, address(params.vault));

        if (params.withApproval) {
            _executeApproval(safe, address(params.vault), yearn4626Router, params.shares);
        }

        (address asset, uint256 redeemedAmount) = _yearnRedeem(safe, params);

        if (params.withUnwrap) {
            _executeUnwrapNative(safe, asset, redeemedAmount);
        }
    }

    /// @inheritdoc IYearnModule
    function executeYearnApproval(
        address safe,
        ApprovalParams calldata params
    ) external onlyWhitelistedToken(safe, params.token) {
        _executeApproval(safe, params.token, yearn4626Router, params.amount);
    }

    /// @inheritdoc IBaseModule
    function getModuleName()
        public
        pure
        override(BaseModule, IBaseModule)
        returns (string memory)
    {
        return "YearnModule";
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            interfaceId == type(IYearnModule).interfaceId || super.supportsInterface(interfaceId);
    }

    function _yearnDeposit(address safe, DepositParams calldata params) internal {
        address delegate = _getDelegate();

        _checkPermission(safe, delegate, Permissions.DEPOSIT_PERMISSION);

        IYearn4626Router(yearn4626Router).approve(
            params.vault.asset(),
            address(params.vault),
            params.amount
        );

        bytes memory depositData = abi.encodeCall(
            IYearn4626Router.depositToVault,
            (params.vault, params.amount, safe, params.minSharesOut)
        );

        bytes memory depositReturnData = _safeCallWithReturnData(
            safe,
            yearn4626Router,
            0,
            depositData,
            "deposit"
        );

        uint256 sharesReceived = abi.decode(depositReturnData, (uint256));

        emit YearnDepositExecuted(
            safe,
            delegate,
            address(params.vault),
            params.amount,
            sharesReceived
        );
    }

    function _yearnRedeem(
        address safe,
        RedeemParams calldata params
    ) internal returns (address asset, uint256 redeemedAmount) {
        address delegate = _getDelegate();

        _checkPermission(safe, delegate, Permissions.WITHDRAW_PERMISSION);

        asset = params.vault.asset();

        _onlyWhitelistedToken(safe, asset);

        bytes memory redeemData = abi.encodeCall(
            IYearn4626Router.redeem,
            (params.vault, params.shares, safe, params.maxLoss)
        );

        bytes memory redeemReturnData = _safeCallWithReturnData(
            safe,
            yearn4626Router,
            0,
            redeemData,
            "redeem"
        );

        redeemedAmount = abi.decode(redeemReturnData, (uint256));

        emit YearnRedeemExecuted(
            safe,
            delegate,
            address(params.vault),
            params.shares,
            redeemedAmount,
            params.maxLoss
        );
    }
}

@openzeppelin/contracts/interfaces/IERC4626.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

@openzeppelin/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);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Arrays.sol

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

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

@openzeppelin/contracts/utils/Comparators.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

@openzeppelin/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)
        }
    }
}

@openzeppelin/contracts/utils/SlotDerivation.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/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);
}

@openzeppelin/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;
    }
}

@openzeppelin/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))
        }
    }
}

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

@solarity/solidity-lib/libs/arrays/Paginator.sol

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

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {DynamicSet} from "../data-structures/DynamicSet.sol";

/**
 * @notice Library for pagination.
 *
 * Supports the following data types `uint256[]`, `address[]`, `bytes32[]`, `UintSet`,
 * `AddressSet`, `Bytes32Set`, `BytesSet`, `StringSet`.
 */
library Paginator {
    using EnumerableSet for *;
    using DynamicSet for *;

    /**
     * @notice Returns part of a uint256 array
     *
     * Examples:
     * - part([4, 5, 6, 7], 0, 4) will return [4, 5, 6, 7]
     * - part([4, 5, 6, 7], 2, 4) will return [6, 7]
     * - part([4, 5, 6, 7], 2, 1) will return [6]
     *
     * @param arr the storage array
     * @param offset_ the starting index in the array
     * @param limit_ the number of elements after the `offset_`
     */
    function part(
        uint256[] storage arr,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (uint256[] memory list_) {
        uint256 to_ = getTo(arr.length, offset_, limit_);

        list_ = new uint256[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = arr[i];
        }
    }

    /**
     * @notice Returns part of an address array
     */
    function part(
        address[] storage arr,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (address[] memory list_) {
        uint256 to_ = getTo(arr.length, offset_, limit_);

        list_ = new address[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = arr[i];
        }
    }

    /**
     * @notice Returns part of a bytes32 array
     */
    function part(
        bytes32[] storage arr,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (bytes32[] memory list_) {
        uint256 to_ = getTo(arr.length, offset_, limit_);

        list_ = new bytes32[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = arr[i];
        }
    }

    /**
     * @notice Returns part of a uint256 set
     * @param set the storage set
     * @param offset_ the starting index in the set
     * @param limit_ the number of elements after the `offset`
     */
    function part(
        EnumerableSet.UintSet storage set,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (uint256[] memory list_) {
        uint256 to_ = getTo(set.length(), offset_, limit_);

        list_ = new uint256[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = set.at(i);
        }
    }

    /**
     * @notice Returns part of an address set
     */
    function part(
        EnumerableSet.AddressSet storage set,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (address[] memory list_) {
        uint256 to_ = getTo(set.length(), offset_, limit_);

        list_ = new address[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = set.at(i);
        }
    }

    /**
     * @notice Returns part of a bytes32 set
     */
    function part(
        EnumerableSet.Bytes32Set storage set,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (bytes32[] memory list_) {
        uint256 to_ = getTo(set.length(), offset_, limit_);

        list_ = new bytes32[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = set.at(i);
        }
    }

    /**
     * @notice Returns part of a bytes set
     */
    function part(
        DynamicSet.BytesSet storage set,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (bytes[] memory list_) {
        uint256 to_ = getTo(set.length(), offset_, limit_);

        list_ = new bytes[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = set.at(i);
        }
    }

    /**
     * @notice Returns part of a string set
     */
    function part(
        DynamicSet.StringSet storage set,
        uint256 offset_,
        uint256 limit_
    ) internal view returns (string[] memory list_) {
        uint256 to_ = getTo(set.length(), offset_, limit_);

        list_ = new string[](to_ - offset_);

        for (uint256 i = offset_; i < to_; i++) {
            list_[i - offset_] = set.at(i);
        }
    }

    /**
     * @notice Returns the exclusive index of the element to iterate to
     * @param length_ the length of the array
     * @param offset_ the starting index
     * @param limit_ the number of elements
     */
    function getTo(
        uint256 length_,
        uint256 offset_,
        uint256 limit_
    ) internal pure returns (uint256 to_) {
        to_ = offset_ + limit_;

        if (to_ > length_) {
            to_ = length_;
        }

        if (offset_ > to_) {
            to_ = offset_;
        }
    }
}

@solarity/solidity-lib/libs/data-structures/DynamicSet.sol

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

/**
 * @notice Dynamic Set Library
 *
 * This library provides implementation of two sets with dynamic data types: `BytesSet` and `StingSet`.
 * The library can also be used to create sets that store custom structures via ABI encoding.
 *
 * ## Usage example:
 *
 * ```
 * using DynamicSet for DynamicSet.BytesSet;
 *
 * DynamicSet.BytesSet internal _set;
 * ```
 */
library DynamicSet {
    /**
     *********************
     *      BytesSet     *
     *********************
     */

    struct BytesSet {
        Set _inner;
    }

    /**
     * @notice The function to add a bytes value to the set
     * @param set The BytesSet storage reference
     * @param value_ The value to be added
     * @return True if the value was added successfully, false otherwise
     */
    function add(BytesSet storage set, bytes memory value_) internal returns (bool) {
        return _add(set._inner, value_);
    }

    /**
     * @notice The function to remove a bytes value from the set
     * @param set The BytesSet storage reference
     * @param value_ The value to be removed
     * @return True if the value was removed successfully, false otherwise
     */
    function remove(BytesSet storage set, bytes memory value_) internal returns (bool) {
        return _remove(set._inner, value_);
    }

    /**
     * @notice The function to check if a value is contained in the set
     * @param set The BytesSet storage reference
     * @param value_ The value to be checked
     * @return True if the value is contained in the set, false otherwise
     */
    function contains(BytesSet storage set, bytes memory value_) internal view returns (bool) {
        return _contains(set._inner, value_);
    }

    /**
     * @notice The function to get the number of values in the set
     * @param set The BytesSet storage reference
     * @return The number of values in the set
     */
    function length(BytesSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @notice The function to get the value at the specified index in the set
     * @param set The BytesSet storage reference
     * @param index_ The index of the value to retrieve
     * @return The value at the specified index
     */
    function at(BytesSet storage set, uint256 index_) internal view returns (bytes memory) {
        return _at(set._inner, index_);
    }

    /**
     * @notice The function to get an array containing all values in the set
     * @param set The BytesSet storage reference
     * @return An array containing all values in the set
     */
    function values(BytesSet storage set) internal view returns (bytes[] memory) {
        return _values(set._inner);
    }

    /**
     *********************
     *     StringSet     *
     *********************
     */

    struct StringSet {
        Set _inner;
    }

    /**
     * @notice The function to add a string value to the set
     * @param set The StringSet storage reference
     * @param value_ The value to be added
     * @return True if the value was added successfully, false otherwise
     */
    function add(StringSet storage set, string memory value_) internal returns (bool) {
        return _add(set._inner, bytes(value_));
    }

    /**
     * @notice The function to remove a string value from the set
     * @param set The StringSet storage reference
     * @param value_ The value to be removed
     * @return True if the value was removed successfully, false otherwise
     */
    function remove(StringSet storage set, string memory value_) internal returns (bool) {
        return _remove(set._inner, bytes(value_));
    }

    /**
     * @notice The function to check if a value is contained in the set
     * @param set The StringSet storage reference
     * @param value_ The value to be checked
     * @return True if the value is contained in the set, false otherwise
     */
    function contains(StringSet storage set, string memory value_) internal view returns (bool) {
        return _contains(set._inner, bytes(value_));
    }

    /**
     * @notice The function to get the number of values in the set
     * @param set The StringSet storage reference
     * @return The number of values in the set
     */
    function length(StringSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @notice The function to get the value at the specified index in the set
     * @param set The StringSet storage reference
     * @param index_ The index of the value to retrieve
     * @return The value at the specified index
     */
    function at(StringSet storage set, uint256 index_) internal view returns (string memory) {
        return string(_at(set._inner, index_));
    }

    /**
     * @notice The function to get an array containing all values in the set
     * @param set The StringSet storage reference
     * @return values_ An array containing all values in the set
     */
    function values(StringSet storage set) internal view returns (string[] memory values_) {
        bytes[] memory store_ = _values(set._inner);

        assembly {
            values_ := store_
        }
    }

    struct Set {
        bytes[] _values;
        mapping(bytes32 => uint256) _indexes;
    }

    function _add(Set storage set, bytes memory value_) internal returns (bool) {
        if (!_contains(set, value_)) {
            set._values.push(value_);
            set._indexes[keccak256(value_)] = set._values.length;

            return true;
        } else {
            return false;
        }
    }

    function _remove(Set storage set, bytes memory value_) internal returns (bool) {
        bytes32 valueKey_ = keccak256(value_);
        uint256 valueIndex_ = set._indexes[valueKey_];

        if (valueIndex_ != 0) {
            uint256 toDeleteIndex_ = valueIndex_ - 1;
            uint256 lastIndex_ = set._values.length - 1;

            if (lastIndex_ != toDeleteIndex_) {
                bytes memory lastValue_ = set._values[lastIndex_];

                set._values[toDeleteIndex_] = lastValue_;
                set._indexes[keccak256(lastValue_)] = valueIndex_;
            }

            set._values.pop();

            delete set._indexes[valueKey_];

            return true;
        } else {
            return false;
        }
    }

    function _contains(Set storage set, bytes memory value_) internal view returns (bool) {
        return set._indexes[keccak256(value_)] != 0;
    }

    function _length(Set storage set) internal view returns (uint256) {
        return set._values.length;
    }

    function _at(Set storage set, uint256 index_) internal view returns (bytes memory) {
        return set._values[index_];
    }

    function _values(Set storage set) internal view returns (bytes[] memory) {
        return set._values;
    }
}

@solarity/solidity-lib/utils/Globals.sol

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

uint256 constant PRECISION = 10 ** 25;
uint256 constant DECIMAL = 10 ** 18;
uint256 constant PERCENTAGE_100 = 10 ** 27;

contracts/interfaces/IAddressProvider.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title IAddressProvider
 * @notice Resolves canonical protocol contract addresses (delegate bundler, permissions manager, protocol whitelist, WETH)
 * for modules and other system components.
 */
interface IAddressProvider {
    /**
     * @notice Returns the deployed `DelegateBundler` contract address.
     * @return The delegate bundler address.
     */
    function getDelegateBundler() external view returns (address);

    /**
     * @notice Returns the deployed permissions manager contract address.
     * @return The permissions manager address.
     */
    function getPermissionsManager() external view returns (address);

    /**
     * @notice Returns the deployed protocol whitelist contract address.
     * @return The protocol whitelist address.
     */
    function getProtocolWhitelist() external view returns (address);

    /**
     * @notice Returns the wrapped native token (WETH) address for the chain.
     * @return The WETH contract address.
     */
    function getWETH() external view returns (address);
}

contracts/interfaces/IDelegateBundler.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title IDelegateBundler
 * @notice An interface for a contract that enables a single transaction
 * to bundle and execute multiple calls on behalf of a delegate.
 */
interface IDelegateBundler {
    /**
     * @notice A struct representing a single call with its destination, data, and value.
     * @param to The address of the contract to call.
     * @param data The calldata to be sent with the call.
     * @param value The amount of native currency (e.g., ETH) to send with the call.
     */
    struct Call {
        address to;
        bytes data;
        uint256 value;
    }

    /**
     * @notice The result of a single call execution within a batch.
     * @param success True if the call was successful, false otherwise.
     * @param returnData The returned data from the call execution.
     */
    struct CallResult {
        bool success;
        bytes returnData;
    }

    /**
     * @notice Thrown when the provided array of calls is empty.
     */
    error ZeroCallsArr();
    /**
     * @notice Thrown when the signature provided by the delegate is invalid.
     */
    error InvalidDelegateSignature();
    /**
     * @notice Thrown when the signature provided has expired.
     * @param deadline The expiration timestamp for the signature.
     */
    error SignatureExpired(uint256 deadline);

    /**
     * @notice Thrown after simulating a batch execution, returning the array of success flags for each call.
     * @param successArr Array indicating success (true) or failure (false) for each simulated call.
     */
    error SimulationResult(bool[] successArr);

    /**
     * @notice Executes a batch of calls as a single transaction after verifying the delegate's signature and deadline.
     * @param delegate The address of the delegate on whose behalf the calls are executed.
     * @param deadline The expiration timestamp for the signature.
     * @param callsArr An array of `Call` structs to be executed sequentially.
     * @param signature The EIP-712 signature from the delegate authorizing the execution.
     */
    function execute(
        address delegate,
        uint256 deadline,
        Call[] calldata callsArr,
        bytes calldata signature
    ) external payable;

    /**
     * @notice Simulates the execution of a batch of calls and reverts, returning the success status for each call.
     * @param delegate The address of the delegate on whose behalf the calls are simulated.
     * @param deadline The expiration timestamp for the signature.
     * @param callsArr An array of `Call` structs to be simulated sequentially.
     * @param signature The EIP-712 signature from the delegate authorizing the simulation.
     */
    function simulateExecuteAndRevert(
        address delegate,
        uint256 deadline,
        Call[] calldata callsArr,
        bytes calldata signature
    ) external payable;

    /**
     * @notice Retrieves the address of the current delegate.
     * @return delegate The address of the delegate.
     */
    function currentDelegate() external view returns (address);

    /**
     * @notice Computes the hash of the provided calls, which the delegate must sign to authorize execution.
     * @param callsArr An array of `Call` structs to be hashed.
     * @param nonce A unique value used to prevent replay attacks and ensure each hash is distinct.
     * @param deadline The expiration timestamp for the signature.
     * @return hash The `bytes32` hash of the calls, ready for signing.
     */
    function getExecuteHash(
        Call[] calldata callsArr,
        uint256 nonce,
        uint256 deadline
    ) external view returns (bytes32);

    /**
     * @notice Computes the hash of an array of calls, which can be used to verify the integrity of the call batch.
     * @param callsArr An array of `Call` structs to be hashed.
     * @return The `bytes32` hash of the entire `callsArr`.
     */
    function getCallsArrHash(Call[] calldata callsArr) external pure returns (bytes32);
}

contracts/interfaces/IPermissionsManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {DynamicSet} from "@solarity/solidity-lib/libs/data-structures/DynamicSet.sol";

/**
 * @title IPermissionsManager
 * @notice A foundational interface that establishes a common structure for modules
 * enabling delegated and permissioned actions on behalf of a Gnosis Safe. It defines
 * standard data structures, errors, and events for tracking permissioned approvals.
 */
interface IPermissionsManager {
    /**
     * @notice Thrown when a required address parameter is the zero address (0x0).
     */
    error ZeroAddress();

    /**
     * @notice Thrown when an address is not recognized as a valid module.
     * @param module The address that failed the module check.
     */
    error NotAModule(address module);

    /**
     * @notice Thrown when a module is not whitelisted in the protocol whitelist.
     * @param module The address of the module that is not whitelisted.
     */
    error ModuleNotWhitelisted(address module);

    /**
     * @notice Thrown when an attempt is made to add a delegate who is already registered.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate who already exists.
     */
    error DelegateAlreadyExists(address safe, address delegate);

    /**
     * @notice Thrown when an action is performed on a delegate who is not registered.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the non-existent delegate.
     */
    error DelegateDoesNotExist(address safe, address delegate);

    /**
     * @notice Thrown when an attempt is made to grant a permission that a delegate already holds.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate.
     * @param module The address of the module for which permission is being granted.
     * @param permission The string identifier of the permission that already exists.
     */
    error PermissionAlreadyGranted(
        address safe,
        address delegate,
        address module,
        string permission
    );

    /**
     * @notice Thrown when an attempt is made to revoke a permission that a delegate does not have.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate.
     * @param module The address of the module for which permission is being revoked.
     * @param permission The string identifier of the permission that does not exist.
     */
    error PermissionDoesNotExist(
        address safe,
        address delegate,
        address module,
        string permission
    );

    /**
     * @notice Thrown when a delegate attempts an action for which they lack the required permission.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate.
     * @param permission The bytes32 hash of the permission that was denied.
     */
    error PermissionDenied(address safe, address delegate, bytes32 permission);

    /**
     * @notice Thrown when the protocol is already globally paused.
     */
    error GlobalPauseAlreadyActive();

    /**
     * @notice Thrown when the protocol is not globally paused.
     */
    error GlobalPauseNotActive();

    /**
     * @notice Thrown when a Safe is already paused.
     * @param safe The address of the Gnosis Safe.
     */
    error SafePauseAlreadyActive(address safe);

    /**
     * @notice Thrown when a Safe is not paused.
     * @param safe The address of the Gnosis Safe.
     */
    error SafePauseNotActive(address safe);

    /**
     * @notice Thrown when a caller is not authorized to pause a Safe.
     * @param caller The address that attempted to pause.
     * @param safe The address of the Gnosis Safe.
     */
    error UnauthorizedPauseActivator(address caller, address safe);

    /**
     * @notice Thrown when a caller is not authorized to unpause a Safe.
     * @param caller The address that attempted to unpause.
     * @param safe The address of the Gnosis Safe.
     */
    error UnauthorizedPauseDeactivator(address caller, address safe);

    /**
     * @notice Emitted when the protocol is globally paused.
     * @param operator The operator that paused the protocol.
     */
    event GlobalPaused(address indexed operator);

    /**
     * @notice Emitted when the global pause is lifted.
     * @param guardian The guardian that unpaused the protocol.
     */
    event GlobalUnpaused(address indexed guardian);

    /**
     * @notice Emitted when a Safe is paused.
     * @param safe The address of the Gnosis Safe.
     * @param pauser The address that paused the Safe.
     */
    event SafePaused(address indexed safe, address indexed pauser);

    /**
     * @notice Emitted when a Safe is unpaused.
     * @param safe The address of the Gnosis Safe.
     * @param unpauser The address that unpaused the Safe.
     */
    event SafeUnpaused(address indexed safe, address indexed unpauser);

    /**
     * @notice Emitted when a new delegate is successfully added to a safe.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the new delegate.
     */
    event DelegateAdded(address indexed safe, address indexed delegate);

    /**
     * @notice Emitted when a delegate is successfully removed from a safe.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the removed delegate.
     */
    event DelegateRemoved(address indexed safe, address indexed delegate);

    /**
     * @notice Emitted when a specific permission is successfully granted to a delegate.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate receiving the permission.
     * @param module The address of the module associated with the permission.
     * @param permission The string identifier of the permission that was granted.
     */
    event PermissionGranted(
        address indexed safe,
        address indexed delegate,
        address module,
        string permission
    );

    /**
     * @notice Emitted when a specific permission is successfully revoked from a delegate.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate from whom the permission was revoked.
     * @param module The address of the module associated with the permission.
     * @param permission The string identifier of the permission that was revoked.
     */
    event PermissionRevoked(
        address indexed safe,
        address indexed delegate,
        address module,
        string permission
    );

    /**
     * @notice A struct to encapsulate a delegate's address and their associated module permissions.
     * @param delegate The address of the delegate.
     * @param modulesInfo An array of `ModulePermissionsInfo` structs containing module and permission details.
     */
    struct DelegateInfo {
        address delegate;
        ModulePermissionsInfo[] modulesInfo;
    }

    /**
     * @notice A struct to hold the permissions granted to a delegate for a specific module.
     * @param module The address of the module.
     * @param permissions An array of string identifiers for the permissions granted.
     */
    struct ModulePermissionsInfo {
        address module;
        string[] permissions;
    }

    /**
     * @notice A struct to pair a module's address with a specific permission string.
     * @param moduleAddr The address of the module.
     * @param permission The string identifier of the permission.
     */
    struct PermissionEntry {
        address moduleAddr;
        string permission;
    }

    /**
     * @notice A struct to store all permissions data for a single delegate.
     * @param modules A set of module addresses for which the delegate has permissions.
     * @param modulePermissions A mapping from a module address to a set of permission strings.
     */
    struct DelegatePermissionsData {
        EnumerableSet.AddressSet modules;
        mapping(address => DynamicSet.StringSet) modulePermissions;
    }

    /**
     * @notice A struct to store all delegate permissions data for a single account.
     * @param delegators A set of delegate addresses for the account.
     * @param delegatorsData A mapping from a delegate address to their `DelegatePermissionsData`.
     */
    struct AccountData {
        EnumerableSet.AddressSet delegators;
        mapping(address => DelegatePermissionsData) delegatorsData;
    }

    /**
     * @notice Pauses the protocol globally, blocking all module actions for every Safe.
     */
    function pauseGlobal() external;

    /**
     * @notice Lifts the global pause.
     */
    function unpauseGlobal() external;

    /**
     * @notice Pauses module actions for the given Safe.
     * @param safe The address of the Gnosis Safe to pause.
     */
    function pauseSafe(address safe) external;

    /**
     * @notice Lifts the pause for the given Safe.
     * @param safe The address of the Gnosis Safe to unpause.
     */
    function unpauseSafe(address safe) external;

    /**
     * @notice Grants an array of permissions to a specified delegate.
     * @param delegate The address of the delegate to whom permissions are being granted.
     * @param permissions An array of `PermissionEntry` structs, each specifying a module and permission string to be granted.
     */
    function grantPermissions(address delegate, PermissionEntry[] calldata permissions) external;

    /**
     * @notice Revokes an array of permissions from a specified delegate.
     * @param delegate The address of the delegate from whom permissions are being revoked.
     * @param permissions An array of `PermissionEntry` structs, each specifying a module and permission string to be revoked.
     */
    function revokePermissions(address delegate, PermissionEntry[] calldata permissions) external;

    /**
     * @notice Retrieves information about all delegates associated with a given account.
     * @param account The address of the account (e.g., a Gnosis Safe).
     * @return delegatorsInfo An array of `DelegateInfo` structs,
     * each containing the delegate's address and their module permissions.
     */
    function getAccountDelegatorsInfo(
        address account
    ) external view returns (DelegateInfo[] memory delegatorsInfo);

    /**
     * @notice Retrieves all permissions granted to a specific delegate for all modules.
     * @param account The address of the account that owns the permissions.
     * @param delegate The address of the delegate to query.
     * @return modulesInfo An array of `ModulePermissionsInfo` structs,
     * providing the module address and its granted permissions.
     */
    function getModulesPermissionsInfo(
        address account,
        address delegate
    ) external view returns (ModulePermissionsInfo[] memory modulesInfo);

    /**
     * @notice Returns whether the protocol is globally paused.
     */
    function isGlobalPaused() external view returns (bool);

    /**
     * @notice Returns whether the given Safe is paused.
     * @param safe The address of the Gnosis Safe to query.
     */
    function isSafePaused(address safe) external view returns (bool);

    /**
     * @notice Returns whether module actions are blocked for the given account.
     * @param account The address of the account (e.g., a Gnosis Safe).
     */
    function isPaused(address account) external view returns (bool);

    /**
     * @notice Checks if a specific delegate has a given permission.
     * @param account The address of the account (e.g., a Gnosis Safe).
     * @param delegate The address of the delegate to check.
     * @param permission A `PermissionEntry` struct representing the permission to be checked.
     * @return `true` if the delegate has the permission, `false` otherwise.
     */
    function hasPermission(
        address account,
        address delegate,
        PermissionEntry calldata permission
    ) external view returns (bool);

    /**
     * @notice Checks if a given address is a registered delegate for a specific account.
     * @param account The address of the account (e.g., a Gnosis Safe).
     * @param delegate The address to check for delegate status.
     * @return `true` if the address is a delegate for the account, `false` otherwise.
     */
    function hasDelegate(address account, address delegate) external view returns (bool);

    /**
     * @notice Checks if a delegate has any permissions associated with a specific module.
     * @param account The address of the account (e.g., a Gnosis Safe).
     * @param delegate The address of the delegate to check.
     * @param module The address of the module to check for permissions.
     * @return `true` if the delegate has permissions for the module, `false` otherwise.
     */
    function hasModulePermission(
        address account,
        address delegate,
        address module
    ) external view returns (bool);
}

contracts/interfaces/IProtocolWhitelist.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title IProtocolWhitelist
 * @notice An interface for managing protocol-wide and per-user whitelists of tokens, vaults, and modules.
 * The default whitelist (stored under `address(0)`) applies to all users. Each user may also maintain a
 * personal whitelist via `updateUserWhitelists`. Checks combine both lists: an address is allowed when
 * it appears in either the default or the user-specific list.
 */
interface IProtocolWhitelist {
    /**
     * @notice Thrown when the guardian address provided during deployment is the zero address.
     */
    error ZeroGuardianAddress();

    /**
     * @notice Thrown when a caller other than the guardian attempts to update the default whitelist.
     * @param sender The address that attempted the unauthorized call.
     */
    error NotAGuardian(address sender);

    /**
     * @notice Thrown when a user attempts to update a whitelist type that is not allowed for user whitelists.
     * @param whitelistType The disallowed whitelist type (e.g., `MODULES`).
     */
    error InvalidWhitelistType(WhitelistType whitelistType);

    /**
     * @notice Emitted when addresses are added to or removed from a whitelist.
     * @param user The owner of the updated whitelist (`address(0)` for the default protocol whitelist).
     * @param whitelistType The type of whitelist that was modified.
     * @param addresses The addresses that were added or removed.
     * @param isAdding True if addresses were added, false if they were removed.
     */
    event WhitelistUpdated(
        address user,
        WhitelistType whitelistType,
        address[] addresses,
        bool isAdding
    );

    /**
     * @notice Identifies which protocol whitelist category an address belongs to.
     */
    enum WhitelistType {
        TOKENS,
        VAULTS,
        MODULES
    }

    /**
     * @notice A batch entry describing a single add or remove operation on a whitelist.
     * @param whitelistType The whitelist category to update.
     * @param addresses The addresses to add or remove.
     * @param isAdding True to add addresses, false to remove them.
     */
    struct UpdateWhitelistEntry {
        WhitelistType whitelistType;
        address[] addresses;
        bool isAdding;
    }

    /**
     * @notice Updates the default protocol whitelist. Callable only by the guardian.
     * @param updateEntries An array of whitelist update operations to apply.
     */
    function updateWhitelists(UpdateWhitelistEntry[] memory updateEntries) external;

    /**
     * @notice Updates the caller's personal whitelist for tokens and vaults.
     * @dev The `MODULES` whitelist type cannot be updated through this function.
     * @param updateEntries An array of whitelist update operations to apply to `msg.sender`.
     */
    function updateUserWhitelists(UpdateWhitelistEntry[] memory updateEntries) external;

    /**
     * @notice Returns the number of addresses in the default whitelist for the given type.
     * @param whitelistType The whitelist category to query.
     * @return The size of the default whitelist.
     */
    function getWhitelistSize(WhitelistType whitelistType) external view returns (uint256);

    /**
     * @notice Returns the number of addresses in a user's personal whitelist for the given type.
     * @param user The address whose personal whitelist is queried.
     * @param whitelistType The whitelist category to query.
     * @return The size of the user's whitelist.
     */
    function getUserWhitelistSize(
        address user,
        WhitelistType whitelistType
    ) external view returns (uint256);

    /**
     * @notice Returns a paginated slice of the default whitelist for the given type.
     * @param whitelistType The whitelist category to query.
     * @param offset The starting index of the slice.
     * @param limit The maximum number of addresses to return.
     * @return A slice of whitelisted addresses.
     */
    function getWhitelistPart(
        WhitelistType whitelistType,
        uint256 offset,
        uint256 limit
    ) external view returns (address[] memory);

    /**
     * @notice Returns a paginated slice of a user's personal whitelist for the given type.
     * @param user The address whose personal whitelist is queried.
     * @param whitelistType The whitelist category to query.
     * @param offset The starting index of the slice.
     * @param limit The maximum number of addresses to return.
     * @return A slice of whitelisted addresses for the user.
     */
    function getUserWhitelistPart(
        address user,
        WhitelistType whitelistType,
        uint256 offset,
        uint256 limit
    ) external view returns (address[] memory);

    /**
     * @notice Checks whether a token is whitelisted for a user.
     * @dev Returns true if the token is in the default token whitelist or the user's personal token whitelist.
     * @param user The address for which the check is performed (typically a Gnosis Safe).
     * @param token The ERC-20 token address to check.
     * @return True if the token is whitelisted for the user.
     */
    function isTokenWhitelisted(address user, address token) external view returns (bool);

    /**
     * @notice Checks whether a vault is whitelisted for a user.
     * @dev Returns true if the vault is in the default vault whitelist or the user's personal vault whitelist.
     * @param user The address for which the check is performed (typically a Gnosis Safe).
     * @param vault The vault contract address to check.
     * @return True if the vault is whitelisted for the user.
     */
    function isVaultWhitelisted(address user, address vault) external view returns (bool);

    /**
     * @notice Checks whether a module is whitelisted for a user.
     * @dev Returns true if the module is in the default module whitelist
     * @param module The module contract address to check.
     * @return True if the module is whitelisted for the user.
     */
    function isModuleWhitelisted(address module) external view returns (bool);
}

contracts/interfaces/ISafe.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title ISafe
 * @notice An interface defining the core functions that a module can use to execute transactions
 * and interact with the assets of a Gnosis Safe. It provides methods for executing transactions
 * with and without retrieving the return data from the called contract.
 */
interface ISafe {
    /**
     * @notice Executes a transaction on behalf of the safe from a trusted module.
     * @dev The return value only indicates if the call was successful (`true`) or if it reverted (`false`).
     * It does not provide the return data of the external call.
     * @param to The address of the target of the transaction.
     * @param value The amount of native currency (e.g., ETH) to send.
     * @param data The encoded function call data.
     * @param operation The type of operation to perform (e.g., `CALL`, `DELEGATECALL`).
     * @return success A boolean indicating whether the external call succeeded.
     */
    function execTransactionFromModule(
        address to,
        uint256 value,
        bytes calldata data,
        uint8 operation
    ) external returns (bool success);

    /**
     * @notice Executes a transaction on behalf of the safe from a trusted module and returns the raw return data.
     * @dev This function is a more versatile version of `execTransactionFromModule` as it also returns the
     * raw data of the executed call, which can be useful for modules that need to read return values.
     * @param to The address of the target of the transaction.
     * @param value The amount of native currency (e.g., ETH) to send.
     * @param data The encoded function call data.
     * @param operation The type of operation to perform (e.g., `CALL`, `DELEGATECALL`).
     * @return success A boolean indicating whether the external call succeeded.
     * @return returnData The raw return data from the external call.
     */
    function execTransactionFromModuleReturnData(
        address to,
        uint256 value,
        bytes memory data,
        uint8 operation
    ) external returns (bool success, bytes memory returnData);
}

contracts/interfaces/IWETH.sol

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

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

/**
 * @title IWETH
 * @notice An interface for the Wrapped Ether (WETH) token, which is a key component for
 * enabling Ether to be used within decentralized applications that require the ERC-20 standard.
 * It allows for the seamless wrapping of native Ether into an ERC-20 compliant token and vice versa.
 */
interface IWETH is IERC20 {
    /**
     * @notice Deposits native Ether to receive an equivalent amount of WETH tokens.
     * @dev The WETH tokens are minted and sent to the address that called this function.
     * This is a payable function, allowing it to receive and convert the native Ether.
     */
    function deposit() external payable;

    /**
     * @notice Burns WETH tokens to withdraw an equivalent amount of native Ether.
     * @dev The specified amount of WETH is burned from the caller's balance, and the corresponding
     * Ether is sent back to their address.
     * @param amount The quantity of WETH tokens to burn and convert back to Ether.
     */
    function withdraw(uint256 amount) external;
}

contracts/interfaces/modules/IBaseModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title IBaseModule
 * @notice A foundational interface that establishes a common structure for modules
 * enabling delegated and permissioned actions on behalf of a Gnosis Safe. It defines
 * standard data structures, errors, and events for tracking permissioned approvals.
 */
interface IBaseModule {
    /**
     * @notice A struct to encapsulate the parameters for a token approval operation.
     * @param token The address of the ERC-20 token to approve.
     * @param amount The maximum amount of tokens that can be spent by the spender.
     */
    struct ApprovalParams {
        address token;
        uint256 amount;
    }

    /**
     * @notice Thrown when an external function call initiated by the module fails.
     * @param callName A string identifier for the failed function call, which aids in debugging.
     */
    error CallExecutionFailed(string callName);
    /**
     * @notice Thrown when a delegate attempts an action for which they do not have explicit permission.
     * @param safe The address of the Gnosis Safe that is the subject of the action.
     * @param delegate The address of the user or contract attempting the action.
     * @param permission A string identifier for the permission that was denied.
     */
    error PermissionDenied(address safe, address delegate, string permission);
    /**
     * @notice Thrown when the provided amount does not match the expected amount after applying slippage.
     * @param passedAmount The amount provided by the user or caller.
     * @param amountWithSlippage The calculated amount after applying slippage tolerance.
     */
    error InvalidAmountSlippage(uint256 passedAmount, uint256 amountWithSlippage);

    /**
     * @notice Thrown when a token address is not the configured wrapped native token (WETH).
     * @param token The address that was passed instead of WETH.
     */
    error TokenIsNotAWETH(address token);

    /**
     * @notice Thrown when the native value attached to a wrap operation is insufficient.
     * @param actualValue The native value actually provided.
     * @param neededValue The native value required for the operation.
     */
    error NotEnoughValueToWrap(uint256 actualValue, uint256 neededValue);

    /**
     * @notice Thrown when a token is not whitelisted for the specified user.
     * @param user The address for which the whitelist check was performed.
     * @param token The token address that is not whitelisted.
     */
    error TokenIsNotWhitelistedForUser(address user, address token);

    /**
     * @notice Thrown when a vault is not whitelisted for the specified user.
     * @param user The address for which the whitelist check was performed.
     * @param vault The vault address that is not whitelisted.
     */
    error VaultIsNotWhitelistedForUser(address user, address vault);

    /**
     * @notice Emitted to signal that a token approval has been successfully executed by a delegate.
     * @param safe The address of the Gnosis Safe that owns the tokens.
     * @param delegate The address of the user or contract that called the permissioned function.
     * @param token The address of the approved token.
     * @param spender The address of the contract or account that is now authorized to spend the tokens.
     * @param amount The amount for which the approval was granted.
     */
    event PermissionedApprovalExecuted(
        address indexed safe,
        address indexed delegate,
        address token,
        address spender,
        uint256 amount
    );

    /**
     * @notice Emitted when native tokens are wrapped into WETH on behalf of a safe.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate who initiated the wrap.
     * @param amount The amount of native tokens wrapped.
     */
    event NativeTokensWrapped(address indexed safe, address indexed delegate, uint256 amount);

    /**
     * @notice Emitted when WETH is unwrapped back to native tokens on behalf of a safe.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate who initiated the unwrap.
     * @param amount The amount of WETH unwrapped.
     */
    event NativeTokensUnwrapped(address indexed safe, address indexed delegate, uint256 amount);

    /**
     * @notice Retrieves the name of the module.
     * @return A string representing the module's name.
     */
    function getModuleName() external view returns (string memory);
}

contracts/interfaces/modules/IYearnModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

import {IBaseModule} from "./IBaseModule.sol";
import {IYearn4626} from "../yearn/IYearn4626.sol";

/**
 * @title IYearnModule
 * @notice An interface for a Gnosis Safe module that enables permissioned and delegated
 * interactions with Yearn Finance vaults. This module allows a safe to securely
 * deposit assets and redeem shares from Yearn's ERC-4626 compliant vaults.
 */
interface IYearnModule is IBaseModule {
    /**
     * @notice A struct containing the parameters for a deposit into a Yearn vault.
     * @param vault The address of the Yearn vault.
     * @param amount The amount of the underlying asset to deposit.
     * @param minSharesOut The minimum number of shares expected from the deposit, mitigating slippage.
     * @param withApproval Whether to perform token approval before deposit.
     * @param withWrap Whether to wrap native tokens before deposit.
     */
    struct DepositParams {
        IYearn4626 vault;
        uint256 amount;
        uint256 minSharesOut;
        bool withApproval;
        bool withWrap;
    }

    /**
     * @notice A struct containing the parameters for a redemption from a Yearn vault.
     * @param vault The address of the Yearn vault.
     * @param shares The number of vault shares to redeem.
     * @param maxLoss The maximum acceptable loss of the underlying asset, mitigating slippage.
     * @param withApproval Whether to perform token approval before redemption.
     * @param withUnwrap Whether to unwrap received tokens to native assets upon redemption.
     */
    struct RedeemParams {
        IYearn4626 vault;
        uint256 shares;
        uint256 maxLoss;
        bool withApproval;
        bool withUnwrap;
    }

    /**
     * @notice Emitted when a deposit operation is successfully executed in a Yearn vault.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate who initiated the transaction.
     * @param vault The address of the Yearn vault where the deposit was made.
     * @param amount The amount of the underlying asset that was deposited.
     * @param shares The number of shares minted for the deposit.
     */
    event YearnDepositExecuted(
        address indexed safe,
        address indexed delegate,
        address vault,
        uint256 amount,
        uint256 shares
    );

    /**
     * @notice Emitted when a redemption operation is successfully executed from a Yearn vault.
     * @param safe The address of the Gnosis Safe.
     * @param delegate The address of the delegate who initiated the transaction.
     * @param vault The address of the Yearn vault from which shares were redeemed.
     * @param shares The number of vault shares that were redeemed.
     * @param redeemedAmount The amount of underlying asset received from the redemption.
     * @param maxLoss The maximum loss of the underlying asset specified for the transaction.
     */
    event YearnRedeemExecuted(
        address indexed safe,
        address indexed delegate,
        address vault,
        uint256 shares,
        uint256 redeemedAmount,
        uint256 maxLoss
    );

    /**
     * @notice Executes a single deposit operation into a Yearn vault.
     * @dev This function assumes that the necessary token approval has already been granted.
     * @param safe The address of the Gnosis Safe.
     * @param params A `DepositParams` struct for the deposit.
     */
    function executeYearnDeposit(address safe, DepositParams calldata params) external;

    /**
     * @notice Executes a single redemption operation from a Yearn vault.
     * @dev This function assumes that the necessary token approval has already been granted.
     * @param safe The address of the Gnosis Safe.
     * @param params A `RedeemParams` struct for the redemption.
     */
    function executeYearnRedeem(address safe, RedeemParams calldata params) external;

    /**
     * @notice Executes a single token approval for a Yearn vault.
     * @param safe The address of the Gnosis Safe.
     * @param params An `ApprovalParams` struct for the approval.
     */
    function executeYearnApproval(address safe, ApprovalParams calldata params) external;
}

contracts/interfaces/yearn/IYearn4626.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

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

/**
 * @title IYearn4626
 * @notice An interface for a Yearn Finance vault that extends the standard ERC-4626 tokenized vault
 * interface. It includes a custom `redeem` function that provides additional functionality
 * specific to Yearn's vault architecture, such as controlling for slippage with a `maxLoss` parameter.
 */
interface IYearn4626 is IERC4626 {
    /**
     * @notice Redeems a specified number of shares from the vault, returning the corresponding underlying assets.
     * @dev This function overrides the standard ERC-4626 `redeem` by including an explicit `owner` parameter
     * and a `maxLoss` parameter to protect against unexpected slippage or losses.
     * @param shares The number of vault shares to redeem.
     * @param receiver The address that will receive the underlying assets.
     * @param owner The address that holds the vault shares to be redeemed.
     * @param maxLoss The maximum acceptable loss of the underlying asset during redemption, specified in basis points of the total redemption value.
     * @return assets The amount of underlying assets transferred to the `receiver`.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner,
        uint256 maxLoss
    ) external returns (uint256 assets);
}

contracts/interfaces/yearn/IYearn4626Router.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

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

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

/**
 * @title IYearn4626Router
 * @notice An interface for a router contract that simplifies and aggregates interactions
 * with Yearn Finance's ERC-4626 compliant vaults. It serves as a single entry point
 * for common operations like approving, depositing, and redeeming assets.
 */
interface IYearn4626Router {
    /**
     * @notice Approves a spender to transfer a specific amount of tokens.
     * @param token The address of the ERC-20 token to approve.
     * @param to The address of the spender to grant approval to.
     * @param amount The amount of tokens to approve.
     */
    function approve(address token, address to, uint256 amount) external payable;

    /**
     * @notice Deposits a specified amount of the underlying asset into a Yearn vault.
     * @dev The transaction will revert if the number of minted shares is less than `minSharesOut`.
     * This function is `payable` to handle ETH deposits if the vault supports them.
     * @param vault The address of the Yearn vault.
     * @param amount The amount of the underlying asset to deposit.
     * @param to The address that will receive the minted shares.
     * @param minSharesOut The minimum number of shares to be received, mitigating slippage.
     * @return The number of shares that were minted and transferred.
     */
    function depositToVault(
        IYearn4626 vault,
        uint256 amount,
        address to,
        uint256 minSharesOut
    ) external payable returns (uint256);

    /**
     * @notice Redeems a specified number of vault shares for the underlying asset.
     * @dev The transaction will revert if the value of assets received falls below the accepted loss threshold.
     * This function is `payable` to handle cases where the vault needs to send ETH.
     * @param vault The address of the Yearn vault.
     * @param shares The number of shares to redeem.
     * @param to The address that will receive the underlying assets.
     * @param maxLoss The maximum acceptable loss of the underlying asset due to slippage.
     * @return The amount of underlying assets that were redeemed and transferred.
     */
    function redeem(
        IYearn4626 vault,
        uint256 shares,
        address to,
        uint256 maxLoss
    ) external payable returns (uint256);
}

contracts/interfaces/yearn/IYearnRegistry.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

/**
 * @title IYearnRegistry
 * @notice Yearn registry used to verify whether a vault address is endorsed by Yearn Finance.
 */
interface IYearnRegistry {
    /**
     * @notice Returns whether a vault is endorsed in this registry.
     * @param vault The vault contract address to check.
     * @return True if the vault is endorsed.
     */
    function isEndorsed(address vault) external view returns (bool);
}

contracts/libs/AddressWhitelist.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {Paginator} from "@solarity/solidity-lib/libs/arrays/Paginator.sol";

library AddressWhitelist {
    using EnumerableSet for EnumerableSet.AddressSet;

    address internal constant DEFAULT_USER = address(0);

    struct AddressWhitelistData {
        mapping(address => EnumerableSet.AddressSet) whitelists;
        bool isInitialized;
    }

    error AddressWhitelistDataAlreadyInitialized();
    error AddressWhitelistDataNotInitialized();
    error ZeroAddress(string addressType);
    error AddressAlreadyInWhitelist(address user, address whitelistedAddress);
    error AddressNotInWhitelist(address user, address whitelistedAddress);

    modifier onlyInitialized(AddressWhitelistData storage self) {
        _onlyInitialized(self);
        _;
    }

    function initialize(
        AddressWhitelistData storage self,
        address[] memory defaultAddressesToWhitelist
    ) internal {
        require(!self.isInitialized, AddressWhitelistDataAlreadyInitialized());

        self.isInitialized = true;

        _addAddressesToWhitelist(self, DEFAULT_USER, defaultAddressesToWhitelist);
    }

    function addAddressesToWhitelist(
        AddressWhitelistData storage self,
        address user,
        address[] memory addressesToAdd
    ) internal onlyInitialized(self) {
        _addAddressesToWhitelist(self, user, addressesToAdd);
    }

    function removeAddressesFromWhitelist(
        AddressWhitelistData storage self,
        address user,
        address[] memory addressesToRemove
    ) internal onlyInitialized(self) {
        _removeAddressesFromWhitelist(self, user, addressesToRemove);
    }

    function getDefaultWhitelistSize(
        AddressWhitelistData storage self
    ) internal view returns (uint256) {
        return getWhitelistSize(self, DEFAULT_USER);
    }

    function getDefaultWhitelist(
        AddressWhitelistData storage self
    ) internal view returns (address[] memory) {
        return getWhitelist(self, DEFAULT_USER);
    }

    function getDefaultWhitelistPart(
        AddressWhitelistData storage self,
        uint256 offset,
        uint256 limit
    ) internal view returns (address[] memory) {
        return getWhitelistPart(self, DEFAULT_USER, offset, limit);
    }

    function getWhitelistSize(
        AddressWhitelistData storage self,
        address user
    ) internal view returns (uint256) {
        return self.whitelists[user].length();
    }

    function getWhitelist(
        AddressWhitelistData storage self,
        address user
    ) internal view returns (address[] memory) {
        return self.whitelists[user].values();
    }

    function getWhitelistPart(
        AddressWhitelistData storage self,
        address user,
        uint256 offset,
        uint256 limit
    ) internal view returns (address[] memory) {
        return Paginator.part(self.whitelists[user], offset, limit);
    }

    function isInWhitelist(
        AddressWhitelistData storage self,
        address user,
        address addressToCheck
    ) internal view returns (bool) {
        return
            isInDefaultWhitelist(self, addressToCheck) ||
            isInUserWhitelist(self, user, addressToCheck);
    }

    function isInDefaultWhitelist(
        AddressWhitelistData storage self,
        address addressToCheck
    ) internal view returns (bool) {
        return self.whitelists[DEFAULT_USER].contains(addressToCheck);
    }

    function isInUserWhitelist(
        AddressWhitelistData storage self,
        address user,
        address addressToCheck
    ) internal view returns (bool) {
        return self.whitelists[user].contains(addressToCheck);
    }

    function _addAddressesToWhitelist(
        AddressWhitelistData storage self,
        address user,
        address[] memory addressesToAdd
    ) private {
        for (uint256 i = 0; i < addressesToAdd.length; ++i) {
            _checkZeroAddress(addressesToAdd[i], "whitelistedAddress");

            require(
                !isInWhitelist(self, user, addressesToAdd[i]),
                AddressAlreadyInWhitelist(user, addressesToAdd[i])
            );

            self.whitelists[user].add(addressesToAdd[i]);
        }
    }

    function _removeAddressesFromWhitelist(
        AddressWhitelistData storage self,
        address user,
        address[] memory addressesToRemove
    ) private {
        for (uint256 i = 0; i < addressesToRemove.length; ++i) {
            require(
                isInUserWhitelist(self, user, addressesToRemove[i]),
                AddressNotInWhitelist(user, addressesToRemove[i])
            );

            self.whitelists[user].remove(addressesToRemove[i]);
        }
    }

    function _onlyInitialized(AddressWhitelistData storage self) private view {
        require(self.isInitialized, AddressWhitelistDataNotInitialized());
    }

    function _checkZeroAddress(address addressToCheck, string memory addressType) private pure {
        require(addressToCheck != address(0), ZeroAddress(addressType));
    }
}

contracts/libs/Permissions.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

library Permissions {
    string internal constant ALL_PERMISSION = "*";
    string internal constant APPROVAL_PERMISSION = "APPROVE";
    string internal constant DEPOSIT_PERMISSION = "DEPOSIT";
    string internal constant WITHDRAW_PERMISSION = "WITHDRAW";
    string internal constant SWAP_PERMISSION = "SWAP";
    string internal constant BRIDGE_DEPOSIT_PERMISSION = "BRIDGE_DEPOSIT";
    string internal constant WRAP_NATIVE_PERMISSION = "WRAP";
    string internal constant UNWRAP_NATIVE_PERMISSION = "UNWRAP";
    string internal constant SIGN_PERMISSION = "SIGN";
    string internal constant UNSIGN_PERMISSION = "UNSIGN";
    string internal constant COLLECT_PERMISSION = "COLLECT";
}

contracts/modules/BaseModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;

import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {PRECISION, PERCENTAGE_100} from "@solarity/solidity-lib/utils/Globals.sol";

import {ISafe} from "../interfaces/ISafe.sol";
import {IAddressProvider} from "../interfaces/IAddressProvider.sol";
import {IDelegateBundler} from "../interfaces/IDelegateBundler.sol";
import {IPermissionsManager} from "../interfaces/IPermissionsManager.sol";
import {IProtocolWhitelist} from "../interfaces/IProtocolWhitelist.sol";
import {IWETH} from "../interfaces/IWETH.sol";

import {IBaseModule} from "../interfaces/modules/IBaseModule.sol";

import {Permissions} from "../libs/Permissions.sol";
import {AddressWhitelist} from "../libs/AddressWhitelist.sol";

abstract contract BaseModule is IBaseModule, ERC165 {
    using AddressWhitelist for AddressWhitelist.AddressWhitelistData;

    uint256 public constant SLIPPAGE_PERCENTAGE = 5 * PRECISION;

    IPermissionsManager public immutable permissionsManager;
    IProtocolWhitelist public immutable protocolWhitelist;
    IDelegateBundler public immutable delegateBundler;
    IWETH public immutable WETH;

    modifier onlyWhitelistedToken(address safe, address token) {
        _onlyWhitelistedToken(safe, token);
        _;
    }

    modifier onlyWhitelistedTokenPair(address safe, address tokenA, address tokenB) {
        _onlyWhitelistedTokenPair(safe, tokenA, tokenB);
        _;
    }

    modifier onlyWhitelistedVault(address safe, address vault) {
        _onlyWhitelistedVault(safe, vault);
        _;
    }

    constructor(address addressProviderAddr) {
        IAddressProvider addressProvider = IAddressProvider(addressProviderAddr);

        permissionsManager = IPermissionsManager(addressProvider.getPermissionsManager());
        protocolWhitelist = IProtocolWhitelist(addressProvider.getProtocolWhitelist());
        delegateBundler = IDelegateBundler(addressProvider.getDelegateBundler());
        WETH = IWETH(addressProvider.getWETH());
    }

    function getModuleName() public view virtual returns (string memory);

    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            interfaceId == type(IBaseModule).interfaceId || super.supportsInterface(interfaceId);
    }

    function _executeApproval(
        address safe,
        address token,
        address spender,
        uint256 amount
    ) internal virtual {
        address delegate = _getDelegate();

        _checkPermission(safe, delegate, Permissions.APPROVAL_PERMISSION);

        // Use safe approval in all cases
        _callApprove(safe, token, spender, 0);
        _callApprove(safe, token, spender, amount);

        emit PermissionedApprovalExecuted(safe, delegate, token, spender, amount);
    }

    function _executeWrapNative(
        address safe,
        address token,
        uint256 amountToWrap
    ) internal virtual {
        _onlyWETHToken(token);

        address delegate = _getDelegate();

        _checkPermission(safe, delegate, Permissions.WRAP_NATIVE_PERMISSION);

        bytes memory depositData = abi.encodeCall(IWETH.deposit, ());

        _safeCall(safe, address(WETH), amountToWrap, depositData, "wrap");

        emit NativeTokensWrapped(safe, delegate, amountToWrap);
    }

    function _executeUnwrapNative(
        address safe,
        address token,
        uint256 amountToUnwrap
    ) internal virtual {
        _onlyWETHToken(token);

        address delegate = _getDelegate();

        _checkPermission(safe, delegate, Permissions.UNWRAP_NATIVE_PERMISSION);

        bytes memory withdrawData = abi.encodeCall(IWETH.withdraw, (amountToUnwrap));

        _safeCall(safe, address(WETH), 0, withdrawData, "unwrap");

        emit NativeTokensUnwrapped(safe, delegate, amountToUnwrap);
    }

    function _safeCall(
        address safe,
        address to,
        uint256 value,
        bytes memory data,
        string memory callName
    ) internal {
        require(
            ISafe(safe).execTransactionFromModule(to, value, data, 0),
            CallExecutionFailed(callName)
        );
    }

    function _trySafeCall(
        address safe,
        address to,
        uint256 value,
        bytes memory data
    ) internal returns (bool) {
        return ISafe(safe).execTransactionFromModule(to, value, data, 0);
    }

    function _safeCallWithReturnData(
        address safe,
        address to,
        uint256 value,
        bytes memory data,
        string memory callName
    ) internal returns (bytes memory) {
        (bool success, bytes memory returnData) = ISafe(safe).execTransactionFromModuleReturnData(
            to,
            value,
            data,
            0
        );

        require(success, CallExecutionFailed(callName));

        return returnData;
    }

    function _callApprove(address safe, address token, address spender, uint256 amount) private {
        bytes memory approvalData = abi.encodeWithSignature(
            "approve(address,uint256)",
            spender,
            amount
        );

        _safeCall(safe, token, 0, approvalData, "approve");
    }

    function _checkPermission(
        address safe,
        address delegate,
        string memory permissionName
    ) internal view virtual {
        require(
            permissionsManager.hasPermission(safe, delegate, _getPermissionEntry(permissionName)),
            PermissionDenied(safe, delegate, permissionName)
        );
    }

    function _getDelegate() internal view returns (address) {
        return
            msg.sender == address(delegateBundler)
                ? delegateBundler.currentDelegate()
                : msg.sender;
    }

    function _getPermissionEntry(
        string memory permissionName
    ) internal view returns (IPermissionsManager.PermissionEntry memory) {
        return
            IPermissionsManager.PermissionEntry({
                moduleAddr: address(this),
                permission: permissionName
            });
    }

    function _isWETH(address token) internal view returns (bool) {
        return address(WETH) == token;
    }

    function _onlyWETHToken(address token) internal view {
        require(_isWETH(token), TokenIsNotAWETH(token));
    }

    function _onlyWhitelistedTokenPair(
        address safe,
        address tokenA,
        address tokenB
    ) internal view {
        _onlyWhitelistedToken(safe, tokenA);
        _onlyWhitelistedToken(safe, tokenB);
    }

    function _onlyWhitelistedToken(address safe, address token) internal view {
        require(
            protocolWhitelist.isTokenWhitelisted(safe, token),
            TokenIsNotWhitelistedForUser(safe, token)
        );
    }

    function _onlyWhitelistedVault(address safe, address vault) internal view {
        require(
            protocolWhitelist.isVaultWhitelisted(safe, vault),
            VaultIsNotWhitelistedForUser(safe, vault)
        );
    }

    function _checkAmountSlippage(uint256 amountPassed, uint256 amountExpected) internal pure {
        uint256 expectedAmountWithSlippage = _applySlippage(amountExpected);

        require(
            amountPassed >= expectedAmountWithSlippage,
            InvalidAmountSlippage(amountPassed, expectedAmountWithSlippage)
        );
    }

    function _applySlippage(uint256 amount) internal pure returns (uint256) {
        return Math.mulDiv(amount, PERCENTAGE_100 - SLIPPAGE_PERCENTAGE, PERCENTAGE_100);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.