Skip to content
Verified contractPartialBUSL-1.1

TokenVault

Address0xcfc0a589c81f5bf719240240286f1e2fdf1f2002
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,485,254
Creation transaction
0x093935b40b…9040278e34
Libraries
contracts/protocol/TokenVault.sol:DepositManagementLogic0xa9d5…697637

52 files

contracts/protocol/TokenVault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

// dependencies
import {IERC20Permit} from "../dependencies/openzeppelin/token/ERC20/extensions/IERC20Permit.sol";
import {EnumerableSet} from "../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";
import {Multicall} from "../dependencies/openzeppelin/utils/Multicall.sol";
// libraries
import {Contracts} from "./libraries/Contracts.sol";
import {Constants} from "./libraries/Constants.sol";
import {TransferHelper} from "./libraries/TransferHelper.sol";
import {DepositManagementLogic} from "./libraries/logics/DepositManagementLogic.sol";
// interfaces
import {ITokenVault} from "./interfaces/ITokenVault.sol";
import {ILendingMarketController} from "./interfaces/ILendingMarketController.sol";
// mixins
import {MixinAccessControl} from "./mixins/MixinAccessControl.sol";
import {MixinAddressResolver} from "./mixins/MixinAddressResolver.sol";
import {MixinLiquidationConfiguration} from "./mixins/MixinLiquidationConfiguration.sol";
// types
import {ProtocolTypes} from "./types/ProtocolTypes.sol";
// utils
import {Ownable} from "./utils/Ownable.sol";
import {Pausable} from "./utils/Pausable.sol";
import {Proxyable} from "./utils/Proxyable.sol";
// storages
import {TokenVaultStorage as Storage} from "./storages/TokenVaultStorage.sol";

/**
 * @notice Implements the management of the token in each currency for users.
 *
 * This contract manages the following data related to tokens.
 * - Deposited token amount as the collateral
 * - Parameters related to the liquidation
 *   - Liquidation threshold rate
 *   - Liquidation fee rate received by protocol
 *   - Liquidation fee rate received by liquidators
 */
contract TokenVault is
    ITokenVault,
    MixinLiquidationConfiguration,
    MixinAccessControl,
    MixinAddressResolver,
    Pausable,
    Proxyable,
    Multicall
{
    using EnumerableSet for EnumerableSet.Bytes32Set;

    /**
     * @notice Modifier to check if currency hasn't been registered yet
     * @param _ccy Currency name in bytes32
     */
    modifier onlyRegisteredCurrency(bytes32 _ccy) {
        if (!isRegisteredCurrency(_ccy)) revert UnregisteredCurrency();
        _;
    }

    /**
     * @notice Modifier to check if the protocol is active.
     */
    modifier ifActive() {
        if (lendingMarketController().isTerminated()) revert MarketTerminated();
        _;
    }

    /**
     * @notice Initializes the contract.
     * @dev Function is invoked by the proxy contract when the contract is added to the ProxyController.
     * @param _owner The address of the contract owner
     * @param _resolver The address of the Address Resolver contract
     * @param _liquidationThresholdRate The liquidation threshold rate
     * @param _fullLiquidationThresholdRate  The full liquidation threshold rate
     * @param _liquidationProtocolFeeRate The liquidation fee rate received by protocol
     * @param _liquidatorFeeRate The liquidation fee rate received by liquidators
     * @param _nativeToken The address of wrapped token of native currency
     */
    function initialize(
        address _owner,
        address _resolver,
        uint256 _liquidationThresholdRate,
        uint256 _fullLiquidationThresholdRate,
        uint256 _liquidationProtocolFeeRate,
        uint256 _liquidatorFeeRate,
        address _nativeToken
    ) public initializer onlyProxy {
        _transferOwnership(_owner);
        registerAddressResolver(_resolver);

        TransferHelper.initialize(_nativeToken);
        MixinAccessControl._setupInitialRoles(_owner);
        MixinLiquidationConfiguration._initialize(
            _owner,
            _liquidationThresholdRate,
            _fullLiquidationThresholdRate,
            _liquidationProtocolFeeRate,
            _liquidatorFeeRate
        );
    }

    // @inheritdoc MixinAddressResolver
    function requiredContracts() public pure override returns (bytes32[] memory contracts) {
        contracts = new bytes32[](3);
        contracts[0] = Contracts.CURRENCY_CONTROLLER;
        contracts[1] = Contracts.LENDING_MARKET_CONTROLLER;
        contracts[2] = Contracts.RESERVE_FUND;
    }

    receive() external payable {
        if (!TransferHelper.isNative(msg.sender)) {
            revert CallerNotBaseCurrency({caller: msg.sender});
        }
    }

    /**
     * @notice Gets if the collateral is sufficient or not
     * @param _user User's address
     * @return isEnoughCollateral The boolean if the user has enough collateral or not
     * @return isEnoughDepositInOrderCcy The boolean if the user has enough deposit in the order currency or not
     */
    function isCovered(
        address _user,
        bytes32 _orderCcy
    ) public view override returns (bool isEnoughCollateral, bool isEnoughDepositInOrderCcy) {
        return DepositManagementLogic.isCovered(_user, _orderCcy);
    }

    /**
     * @notice Gets if the currency is acceptable as collateral
     * @param _ccy Currency name in bytes32
     * @return The boolean if the currency has been registered or not
     */
    function isCollateral(bytes32 _ccy) public view override returns (bool) {
        return Storage.slot().collateralCurrencies.contains(_ccy);
    }

    /**
     * @notice Gets if the currencies are acceptable as collateral
     * @param _ccys Currency name list in bytes32
     * @return isCollateralCurrencies Array of the boolean if the currency has been registered or not
     */
    function isCollateral(
        bytes32[] calldata _ccys
    ) external view override returns (bool[] memory isCollateralCurrencies) {
        uint256 length = _ccys.length;
        isCollateralCurrencies = new bool[](length);
        for (uint256 i; i < length; i++) {
            isCollateralCurrencies[i] = isCollateral(_ccys[i]);
        }
    }

    /**
     * @notice Gets if the currency has been registered
     * @param _ccy Currency name in bytes32
     * @return The boolean if the currency has been registered or not
     */
    function isRegisteredCurrency(bytes32 _ccy) public view override returns (bool) {
        return Storage.slot().tokenAddresses[_ccy] != address(0);
    }

    /**
     * @notice Checks if a deposit currency can be added for the user.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     * @return True if the currency can be added, false otherwise
     */
    function canDepositCurrency(address _user, bytes32 _ccy) external view override returns (bool) {
        return DepositManagementLogic.canDepositCurrency(_user, _ccy);
    }

    // @inheritdoc Proxyable
    function getRevision() external pure override returns (uint256) {
        return 0x3;
    }

    /**
     * @notice Gets the token contract address
     * @param _ccy Currency name in bytes32
     * @return The token contract address
     */
    function getTokenAddress(bytes32 _ccy) public view override returns (address) {
        return Storage.slot().tokenAddresses[_ccy];
    }

    /**
     * @notice Gets the currencies accepted as collateral
     * @return Array of the currency accepted as collateral
     */
    function getCollateralCurrencies() external view override returns (bytes32[] memory) {
        return Storage.slot().collateralCurrencies.values();
    }

    /**
     * @notice Gets the maximum amount of the base currency that can be withdrawn from user collateral.
     * @param _user User's address
     * @return Maximum amount of the base currency that can be withdrawn
     */
    function getWithdrawableCollateral(address _user) external view override returns (uint256) {
        return DepositManagementLogic.getWithdrawableCollateral(_user);
    }

    /**
     * @notice Gets the maximum amount of the selected currency that can be withdrawn from user collateral.
     * @param _ccy Currency name in bytes32
     * @param _user User's address
     * @return Maximum amount of the selected currency that can be withdrawn
     */
    function getWithdrawableCollateral(
        bytes32 _ccy,
        address _user
    ) external view override returns (uint256) {
        return DepositManagementLogic.getWithdrawableCollateral(_ccy, _user);
    }

    /**
     * @notice Gets the rate of collateral used.
     * @param _user User's address
     * @return The rate of collateral used
     */
    function getCoverage(address _user) external view override returns (uint256) {
        return DepositManagementLogic.getCoverage(_user);
    }

    /**
     * @notice Gets the total amount of the unused collateral in the base currency
     * @param _user User's address
     * @return The total amount of unused collateral
     */
    function getTotalUnusedCollateralAmount(
        address _user
    ) external view override returns (uint256) {
        return DepositManagementLogic.getTotalUnusedCollateralAmount(_user);
    }

    /**
     * @notice Gets the total collateral amount using valuation prices.
     * @dev Preserves the single-argument interface used by existing SDK clients.
     * @param _user User's address
     * @return totalCollateralAmount The total collateral amount in the base currency
     */
    function getTotalCollateralAmount(
        address _user
    ) external view override returns (uint256 totalCollateralAmount) {
        (totalCollateralAmount, , ) = DepositManagementLogic.getTotalCollateralAmount(_user, false);
    }

    /**
     * @notice Gets the total collateral amount.
     * @param _user User's address
     * @param _useConservativePrice Use conservative prices for risk-increasing actions
     * @return totalCollateralAmount The total collateral amount in the base currency
     */
    function getTotalCollateralAmount(
        address _user,
        bool _useConservativePrice
    ) external view override returns (uint256 totalCollateralAmount) {
        (totalCollateralAmount, , ) = DepositManagementLogic.getTotalCollateralAmount(
            _user,
            _useConservativePrice
        );
    }

    /**
     * @notice Gets the collateral detail.
     * @param _user User's address
     * @param _useConservativePrice Use conservative prices for risk-increasing actions
     * @return totalCollateral The total collateral amount in the base currency
     * @return totalUsedCollateral The total used collateral amount in the base currency
     * @return totalDeposit The total deposit amount in the base currency
     */
    function getCollateralDetail(
        address _user,
        bool _useConservativePrice
    )
        external
        view
        override
        returns (uint256 totalCollateral, uint256 totalUsedCollateral, uint256 totalDeposit)
    {
        (totalCollateral, totalUsedCollateral, totalDeposit) = DepositManagementLogic
            .getTotalCollateralAmount(_user, _useConservativePrice);
    }

    /**
     * @notice Gets the total collateral amount of the selected currency.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     * @return amount The collateral amount
     */
    function getCollateralAmount(
        address _user,
        bytes32 _ccy
    ) external view override returns (uint256 amount) {
        (amount, , ) = DepositManagementLogic.getCollateralAmount(_user, _ccy);
    }

    /**
     * @notice Gets the borrowable amount in the selected currency.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     * @return amount The borrowable amount
     */
    function getBorrowableAmount(
        address _user,
        bytes32 _ccy
    ) external view override returns (uint256) {
        return DepositManagementLogic.getBorrowableAmount(_user, _ccy);
    }

    /**
     * @notice Gets the amount to be liquidated.
     * @param _user User's address
     * @return liquidationAmount The the amount to be liquidated
     */
    function getLiquidationAmount(
        address _user,
        bytes32 _liquidationCcy,
        uint256 _liquidationAmountMaximum
    )
        external
        view
        override
        returns (uint256 liquidationAmount, uint256 protocolFee, uint256 liquidatorFee)
    {
        return
            DepositManagementLogic.getLiquidationAmount(
                _user,
                _liquidationCcy,
                _liquidationAmountMaximum
            );
    }

    /**
     * @notice Gets the total amount deposited of the selected currency
     * @param _ccy Currency name in bytes32
     * @return The total deposited amount
     */
    function getTotalDepositAmount(bytes32 _ccy) external view override returns (uint256) {
        return Storage.slot().totalDepositAmount[_ccy];
    }

    /**
     * @notice Gets the amount deposited in the user's collateral.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     * @return The deposited amount
     */
    function getDepositAmount(
        address _user,
        bytes32 _ccy
    ) external view override returns (uint256) {
        return DepositManagementLogic.getDepositAmount(_user, _ccy);
    }

    /**
     * @notice Gets the currencies that the user used as collateral.
     * @param _user User's address
     * @return The currency names in bytes32
     */
    function getUsedCurrencies(address _user) public view override returns (bytes32[] memory) {
        return DepositManagementLogic.getUsedCurrencies(_user);
    }

    /**
     * @notice Gets the liquidation threshold rate.
     * @return rate The liquidation threshold rate
     */
    function getLiquidationThresholdRate() public view override returns (uint256 rate) {
        (rate, , , ) = getLiquidationConfiguration();
    }

    /**
     * @notice Calculates the collateral rate used when additional funds are had by the user.
     * @param _user User's address
     * @param _additionalFunds Additional funds for calculating the coverage
     * @return coverage The rate of collateral used
     * @return isInsufficientDepositAmount The boolean if the lent amount in the selected currency is insufficient for the deposit amount or not
     */
    function calculateCoverage(
        address _user,
        ILendingMarketController.AdditionalFunds memory _additionalFunds
    ) external view override returns (uint256 coverage, bool isInsufficientDepositAmount) {
        return DepositManagementLogic.calculateCoverage(_user, _additionalFunds);
    }

    /**
     * @notice Gets the actual fee amounts calculated by rates.
     * @param _amount Liquidation amount
     * @return protocolFee Liquidation fee amount received by protocol
     * @return liquidatorFee Liquidation fee amount received by liquidators
     */
    function calculateLiquidationFees(
        uint256 _amount
    ) external view override returns (uint256 protocolFee, uint256 liquidatorFee) {
        return DepositManagementLogic.calculateLiquidationFees(_amount);
    }

    /**
     * @notice Registers new currency and sets if it is acceptable as collateral.
     * @param _ccy Currency name in bytes32
     * @param _tokenAddress Token contract address of the selected currency
     * @param _isCollateral Boolean if the selected currency is acceptable as collateral.
     */
    function registerCurrency(
        bytes32 _ccy,
        address _tokenAddress,
        bool _isCollateral
    ) external override ifActive onlyOwner {
        if (!currencyController().currencyExists(_ccy) || isRegisteredCurrency(_ccy)) {
            revert InvalidCurrency();
        }

        if (_tokenAddress == address(0)) {
            revert InvalidToken();
        }

        Storage.slot().tokenAddresses[_ccy] = _tokenAddress;
        if (_isCollateral) {
            Storage.slot().collateralCurrencies.add(_ccy);
        }

        emit CurrencyRegistered(_ccy, _tokenAddress, _isCollateral);
    }

    /**
     * @notice Updates the currency if it is acceptable as collateral.
     * @param _ccy Currency name in bytes32
     * @param _isCollateral Boolean if the selected currency is acceptable as collateral.
     */
    function updateCurrency(
        bytes32 _ccy,
        bool _isCollateral
    ) external override ifActive onlyOwner onlyRegisteredCurrency(_ccy) {
        if (_isCollateral) {
            Storage.slot().collateralCurrencies.add(_ccy);
        } else {
            Storage.slot().collateralCurrencies.remove(_ccy);
        }

        emit CurrencyUpdated(_ccy, _isCollateral);
    }

    /**
     * @dev Deposits funds by the caller into collateral.
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to deposit
     */
    function deposit(
        bytes32 _ccy,
        uint256 _amount
    ) external payable override ifActive whenNotPaused onlyRegisteredCurrency(_ccy) {
        _deposit(msg.sender, _ccy, _amount, msg.sender);
    }

    /**
     * @dev Deposits funds by the caller into collateral.
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to deposit
     * @param _onBehalfOf The beneficiary of the supplied deposits
     */
    function depositTo(
        bytes32 _ccy,
        uint256 _amount,
        address _onBehalfOf
    ) external payable override ifActive whenNotPaused onlyRegisteredCurrency(_ccy) {
        _deposit(msg.sender, _ccy, _amount, _onBehalfOf);
    }

    /**
     * @dev Deposits funds by the `from` into collateral.
     * @param _from Address of the user
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to deposit
     */
    function depositFrom(
        address _from,
        bytes32 _ccy,
        uint256 _amount
    ) external payable override ifActive whenNotPaused onlyLendingMarketController {
        _deposit(_from, _ccy, _amount, _from);
    }

    /**
     * @dev Deposits funds by the caller into collateral with transfer approval of asset via permit function
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to deposit
     * @param _onBehalfOf The beneficiary of the supplied deposits
     * @param _deadline The deadline timestamp that the permit is valid
     * @param _permitV The V parameter of ERC712 permit sig
     * @param _permitR The R parameter of ERC712 permit sig
     * @param _permitS The S parameter of ERC712 permit sig
     */
    function depositWithPermitTo(
        bytes32 _ccy,
        uint256 _amount,
        address _onBehalfOf,
        uint256 _deadline,
        uint8 _permitV,
        bytes32 _permitR,
        bytes32 _permitS
    ) external override ifActive whenNotPaused onlyRegisteredCurrency(_ccy) {
        IERC20Permit(getTokenAddress(_ccy)).permit(
            msg.sender,
            address(this),
            _amount,
            _deadline,
            _permitV,
            _permitR,
            _permitS
        );

        _deposit(msg.sender, _ccy, _amount, _onBehalfOf);
    }

    /**
     * @dev Deposits funds by the `from` into collateral with transfer approval of asset via permit function
     * @param _from Address of the user
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to deposit
     * @param _deadline The deadline timestamp that the permit is valid
     * @param _permitV The V parameter of ERC712 permit sig
     * @param _permitR The R parameter of ERC712 permit sig
     * @param _permitS The S parameter of ERC712 permit sig
     */
    function depositWithPermitFrom(
        address _from,
        bytes32 _ccy,
        uint256 _amount,
        uint256 _deadline,
        uint8 _permitV,
        bytes32 _permitR,
        bytes32 _permitS
    ) external override ifActive whenNotPaused onlyLendingMarketController {
        IERC20Permit(getTokenAddress(_ccy)).permit(
            _from,
            address(this),
            _amount,
            _deadline,
            _permitV,
            _permitR,
            _permitS
        );

        _deposit(_from, _ccy, _amount, _from);
    }

    /**
     * @notice Withdraws funds by the caller from unused collateral.
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to withdraw.
     * @return withdrawnAmount Actual amount withdrawn
     */
    function withdraw(
        bytes32 _ccy,
        uint256 _amount
    )
        external
        override
        whenNotPaused
        onlyRegisteredCurrency(_ccy)
        returns (uint256 withdrawnAmount)
    {
        return _withdraw(msg.sender, _ccy, _amount);
    }

    /**
     * @dev Adds deposit amount.
     * @param _user User's address
     * @param _amount Amount of funds to deposit
     * @param _ccy Currency name in bytes32
     */
    function addDepositAmount(
        address _user,
        bytes32 _ccy,
        uint256 _amount
    ) external override whenNotPaused onlyLendingMarketController onlyRegisteredCurrency(_ccy) {
        DepositManagementLogic.addDepositAmount(_user, _ccy, _amount);
    }

    /**
     * @notice Removes deposit amount.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     * @param _amount Amount of funds to withdraw.
     */
    function removeDepositAmount(
        address _user,
        bytes32 _ccy,
        uint256 _amount
    ) external override whenNotPaused onlyLendingMarketController onlyRegisteredCurrency(_ccy) {
        DepositManagementLogic.removeDepositAmount(_user, _ccy, _amount);
    }

    /**
     * @notice Forces a reset of the user's deposit amount.
     * @param _user User's address
     * @param _ccy Currency name in bytes32
     */
    function executeForcedReset(
        address _user,
        bytes32 _ccy
    ) external override onlyLendingMarketController onlyRegisteredCurrency(_ccy) returns (uint256) {
        return DepositManagementLogic.executeForcedReset(_user, _ccy);
    }

    /**
     * @notice Transfers the token from sender to receiver.
     * @param _ccy Currency name in bytes32
     * @param _from Sender's address
     * @param _to Receiver's address
     * @param _amount Amount of funds to sent
     */
    function transferFrom(
        bytes32 _ccy,
        address _from,
        address _to,
        uint256 _amount
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        onlyRegisteredCurrency(_ccy)
        returns (uint256 untransferredAmount)
    {
        untransferredAmount = DepositManagementLogic.transferFrom(_ccy, _from, _to, _amount);
        emit Transfer(_ccy, _from, _to, _amount - untransferredAmount);
    }

    /**
     * @notice Pauses the token vault.
     */
    function pause() external override onlyOperator {
        _pause();
    }

    /**
     * @notice Unpauses the token vault.
     */
    function unpause() external override onlyOperator {
        _unpause();
    }

    function _deposit(
        address _caller,
        bytes32 _ccy,
        uint256 _amount,
        address _onBehalfOf
    ) internal {
        if (_amount == 0) revert AmountIsZero();
        if (_onBehalfOf == address(0)) revert InvalidAddress();

        address tokenAddress = Storage.slot().tokenAddresses[_ccy];
        if (
            (TransferHelper.isNative(tokenAddress) && msg.value != _amount) ||
            (!TransferHelper.isNative(tokenAddress) && msg.value != 0)
        ) {
            revert InvalidAmount(_ccy, _amount, msg.value);
        }

        lendingMarketController().cleanUpFunds(_ccy, _onBehalfOf);

        DepositManagementLogic.deposit(_caller, _ccy, _amount, _onBehalfOf);

        emit Deposit(_onBehalfOf, _ccy, _amount, _caller);
    }

    function _withdraw(
        address _user,
        bytes32 _ccy,
        uint256 _amount
    ) internal returns (uint256 withdrawableAmount) {
        if (_amount == 0) revert AmountIsZero();
        if (lendingMarketController().isRedemptionRequired(_user)) revert RedemptionIsRequired();

        lendingMarketController().cleanUpFunds(_ccy, _user);

        withdrawableAmount = DepositManagementLogic.withdraw(_user, _ccy, _amount);

        emit Withdraw(_user, _ccy, withdrawableAmount);
    }
}

contracts/dependencies/chainlink/AggregatorV3Interface.sol

// SPDX-License-Identifier: MIT
// Chainlink Contracts v0.4.0 (v0.8/interfaces/AggregatorV3Interface.sol)
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function version() external view returns (uint256);

    // getRoundData and latestRoundData should both raise "No data present"
    // if they do not have data to report, instead of returning unset values
    // which could be misinterpreted as actual reported values.
    function getRoundData(
        uint80 _roundId
    )
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );

    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

contracts/dependencies/openzeppelin/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(
        bytes32 indexed role,
        bytes32 indexed previousAdminRole,
        bytes32 indexed newAdminRole
    );

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

contracts/dependencies/openzeppelin/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) ||
                (!Address.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(
            !_initializing && _initialized < version,
            "Initializable: contract is already initialized"
        );
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

contracts/dependencies/openzeppelin/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

contracts/dependencies/openzeppelin/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

contracts/dependencies/openzeppelin/utils/Address.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return
            functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data
    ) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data
    ) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

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

contracts/dependencies/openzeppelin/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

contracts/dependencies/openzeppelin/utils/Multicall.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Multicall.sol)

pragma solidity ^0.8.0;

import "./Address.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * _Available since v4.1._
 */
abstract contract Multicall {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), data[i]);
        }
        return results;
    }
}

contracts/dependencies/openzeppelin/utils/StorageSlot.sol

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

pragma solidity ^0.8.0;

/**
 * @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 ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

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

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

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

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

contracts/dependencies/openzeppelin/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

contracts/dependencies/openzeppelin/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

contracts/dependencies/openzeppelin/utils/math/Math.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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 up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * 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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

contracts/dependencies/openzeppelin/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

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

pragma solidity ^0.8.0;

/**
 * @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.
 *
 * ```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 of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @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._indexes[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 read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 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 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

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

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

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

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @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._indexes[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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

contracts/protocol/interfaces/IAddressResolver.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

interface IAddressResolver {
    error UnmatchedInputs();

    event AddressImported(bytes32 name, address destination);

    function getAddress(bytes32 name, string calldata reason) external view returns (address);

    function getAddress(bytes32 name) external view returns (address);

    function getAddresses() external view returns (address[] memory);

    function getNames() external view returns (bytes32[] memory);
}

contracts/protocol/interfaces/IBeaconProxyController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

interface IBeaconProxyController {
    error NoBeaconProxyContract();
    error InvalidProxyContract();

    event BeaconProxyUpdated(
        bytes32 indexed id,
        address indexed proxyAddress,
        address indexed newImplementationAddress,
        address oldImplementationAddress
    );

    function getBeaconProxyAddress(bytes32 beaconName) external view returns (address);

    function setFutureValueVaultImpl(address newImpl) external;

    function setLendingMarketImpl(address newImpl) external;

    function setZCTokenImpl(address newImpl) external;

    function deployFutureValueVault() external returns (address futureValueVault);

    function deployLendingMarket(
        bytes32 ccy,
        uint256 orderFeeRate,
        uint256 cbLimitRange
    ) external returns (address market);

    function deployZCToken(
        string memory name,
        string memory symbol,
        uint8 decimals,
        address asset,
        uint256 maturity
    ) external returns (address futureValueToken);
}

contracts/protocol/interfaces/ICurrencyController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {PriceFeed} from "../storages/CurrencyControllerStorage.sol";

/**
 * @dev Currency Controller contract is responsible for managing supported
 * currencies in Secured Finance Protocol
 *
 * Contract links new currencies to ETH Chainlink price feeds, without existing price feed
 * contract owner is not able to add a new currency into the protocol
 */
interface ICurrencyController {
    error InvalidCurrency();
    error InvalidHaircut();
    error InvalidPriceFeed();
    error InvalidDecimals(address priceFeed, uint8 decimals);
    error InvalidPriceFeedInputs();
    error StalePriceFeed(
        address priceFeed,
        uint256 heartbeat,
        uint256 updatedAt,
        uint256 blockTimestamp
    );
    error PriceFeedNotRegistered(bytes32 ccy);

    event CurrencyAdded(bytes32 indexed ccy, uint256 haircut);
    event CurrencyRemoved(bytes32 indexed ccy);

    event HaircutUpdated(bytes32 indexed ccy, uint256 haircut);

    event PriceFeedUpdated(bytes32 ccy, uint256 decimals, address[] indexed priceFeeds);

    function convert(
        bytes32 _fromCcy,
        bytes32 _toCcy,
        uint256 _amount
    ) external view returns (uint256 amount);

    function convert(
        bytes32 _fromCcy,
        bytes32 _toCcy,
        uint256[] calldata _amounts
    ) external view returns (uint256[] memory amounts);

    function convertToBaseCurrency(
        bytes32 _ccy,
        uint256 _amount
    ) external view returns (uint256 amount);

    function convertToBaseCurrency(
        bytes32 _ccy,
        int256 _amount
    ) external view returns (int256 amount);

    function convertToBaseCurrency(
        bytes32 _ccy,
        uint256[] calldata _amounts
    ) external view returns (uint256[] memory amounts);

    function convertFromBaseCurrency(
        bytes32 _ccy,
        uint256 _amountETH
    ) external view returns (uint256 amount);

    function convertFromBaseCurrency(
        bytes32 _ccy,
        uint256 _amount,
        bool _roundUp
    ) external view returns (uint256 amount);

    function convertFromBaseCurrency(
        bytes32 _ccy,
        uint256[] calldata _amounts
    ) external view returns (uint256[] memory amounts);

    function getDecimals(bytes32) external view returns (uint8);

    function getCurrencies() external view returns (bytes32[] memory);

    function getHaircut(bytes32 _ccy) external view returns (uint256);

    function getPriceFeed(bytes32 _ccy) external view returns (PriceFeed memory);

    function getLastPrice(bytes32 _ccy) external view returns (int256 price);

    function getAggregatedLastPrice(bytes32 _ccy) external view returns (int256);

    function currencyExists(bytes32 _ccy) external view returns (bool);

    function updatePriceFeed(
        bytes32 _ccy,
        uint8 _decimals,
        address[] calldata _priceFeeds,
        uint256[] calldata _heartbeats
    ) external;

    function addCurrency(
        bytes32 _ccy,
        uint8 _decimals,
        uint256 _haircut,
        address[] calldata _priceFeeds,
        uint256[] calldata _heartbeats
    ) external;

    function updateHaircut(bytes32 _ccy, uint256 _haircut) external;

    function removeCurrency(bytes32 _ccy) external;
}

contracts/protocol/interfaces/IGenesisValueVault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {AutoRollLog} from "../storages/GenesisValueVaultStorage.sol";

interface IGenesisValueVault {
    error NoCompoundFactorExists(uint256 maturity);
    error CompoundFactorIsZero();
    error ResidualAmountIsNotZero();
    error UnitPriceIsZero();
    error InvalidMaturity();
    error InvalidAmount();
    error InvalidOrderFeeRate();
    error CurrencyAlreadyInitialized();
    error InitialCompoundFactorAlreadyFinalized();
    error AutoRollLogAlreadyUpdated(uint256 currentMaturity, uint256 nextMaturity);
    error InsufficientBalance();
    error InsufficientLockedBalance();

    event Transfer(bytes32 indexed ccy, address indexed from, address indexed to, int256 value);
    event AutoRollExecuted(
        bytes32 indexed ccy,
        uint256 lendingCompoundFactor,
        uint256 borrowingCompoundFactor,
        uint256 unitPrice,
        uint256 currentMaturity,
        uint256 previousMaturity
    );
    event BalanceLocked(bytes32 indexed ccy, address indexed user, uint256 value);
    event BalanceUnlocked(bytes32 indexed ccy, address indexed user, uint256 value);

    function isAutoRolled(bytes32 _ccy, uint256 _maturity) external view returns (bool);

    function isInitialized(bytes32 ccy) external view returns (bool);

    function decimals(bytes32 ccy) external view returns (uint8);

    function getTotalLendingSupply(bytes32 ccy) external view returns (uint256);

    function getTotalBorrowingSupply(bytes32 ccy) external view returns (uint256);

    function getBalance(bytes32 ccy, address user, uint256 maturity) external view returns (int256);

    function getMaturityGenesisValue(bytes32 ccy, uint256 maturity) external view returns (int256);

    function getCurrentMaturity(bytes32 ccy) external view returns (uint256);

    function getLendingCompoundFactor(bytes32 ccy) external view returns (uint256);

    function getBorrowingCompoundFactor(bytes32 ccy) external view returns (uint256);

    function getAutoRollLog(
        bytes32 ccy,
        uint256 maturity
    ) external view returns (AutoRollLog memory);

    function getLatestAutoRollLog(bytes32 ccy) external view returns (AutoRollLog memory);

    function getTotalLockedBalance(bytes32 ccy) external view returns (uint256);

    function calculateFVFromFV(
        bytes32 ccy,
        uint256 basisMaturity,
        uint256 destinationMaturity,
        int256 futureValue
    ) external view returns (int256);

    function calculateGVFromFV(
        bytes32 ccy,
        uint256 basisMaturity,
        int256 futureValue
    ) external view returns (int256);

    function calculateFVFromGV(
        bytes32 ccy,
        uint256 basisMaturity,
        int256 genesisValue
    ) external view returns (int256);

    function calculateGVFromFV(
        bytes32 ccy,
        uint256 basisMaturity,
        int256 futureValue,
        bool roundUp
    ) external view returns (int256);

    function getBalanceFluctuationByAutoRolls(
        bytes32 ccy,
        address user,
        uint256 maturity
    ) external view returns (int256 fluctuation);

    function calculateBalanceFluctuationByAutoRolls(
        bytes32 ccy,
        int256 balance,
        uint256 fromMaturity,
        uint256 toMaturity
    ) external view returns (int256 fluctuation);

    function initializeCurrencySetting(
        bytes32 ccy,
        uint8 decimals,
        uint256 compoundFactor,
        uint256 maturity
    ) external;

    function updateInitialCompoundFactor(bytes32 ccy, uint256 unitPrice) external;

    function updateDecimals(bytes32 _ccy, uint8 _decimals) external;

    function executeAutoRoll(
        bytes32 ccy,
        uint256 maturity,
        uint256 nextMaturity,
        uint256 unitPrice,
        uint256 orderFeeRate
    ) external;

    function updateGenesisValueWithFutureValue(
        bytes32 ccy,
        address user,
        uint256 basisMaturity,
        int256 fvAmount
    ) external;

    function updateGenesisValueWithResidualAmount(
        bytes32 ccy,
        address user,
        uint256 basisMaturity
    ) external;

    function lock(
        bytes32 ccy,
        address user,
        uint256 amount
    ) external returns (uint256 lockedAmount);

    function unlock(bytes32 ccy, address user, uint256 amount) external;

    function transferFrom(bytes32 ccy, address sender, address receiver, int256 amount) external;

    function cleanUpBalance(bytes32 ccy, address user, uint256 maturity) external;

    function executeForcedReset(bytes32 _ccy, address _user) external;

    function executeForcedReset(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        int256 _amountInFV
    ) external returns (int256 removedAmount, int256 balance);
}

contracts/protocol/interfaces/ILendingMarket.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../types/ProtocolTypes.sol";
import {ItayoseLog} from "../storages/LendingMarketStorage.sol";
import {OrderBookLib, FilledOrder, PartiallyFilledOrder} from "../libraries/OrderBookLib.sol";
import {ItayoseFinalizeResult, ItayoseProcessStatus, ItayoseSettlementResult} from "../libraries/logics/OrderBookLogic.sol";

interface ILendingMarket {
    error NoOrderExists();
    error CallerNotMaker();
    error MarketNotOpened();
    error AlreadyItayosePeriod();
    error NotItayosePeriod();
    error NotPreOrderPeriod();

    event ItayoseExecuted(
        bytes32 ccy,
        uint256 maturity,
        uint256 openingUnitPrice,
        uint256 lastLendUnitPrice,
        uint256 lastBorrowUnitPrice,
        uint256 offsetAmount
    );

    function minimumReliableAmountInBaseCurrency() external view returns (uint256);

    function getOrderBookDetail(
        uint8 orderBookId
    )
        external
        view
        returns (bytes32 ccy, uint256 maturity, uint256 openingDate, uint256 preOpeningDate);

    function getCircuitBreakerThresholds(
        uint8 orderBookId
    )
        external
        view
        returns (
            uint256 lendCircuitBreakerThreshold,
            uint256 borrowCircuitBreakerThreshold,
            uint256 referenceUnitPrice
        );

    function getBestLendUnitPrice(uint8 orderBookId) external view returns (uint256 unitPrice);

    function getBestLendUnitPrices(
        uint8[] calldata orderBookIds
    ) external view returns (uint256[] memory);

    function getBestBorrowUnitPrice(uint8 orderBookId) external view returns (uint256 unitPrice);

    function getBestBorrowUnitPrices(
        uint8[] calldata orderBookIds
    ) external view returns (uint256[] memory);

    function getLiveUnitPrice(uint8 orderBookId) external view returns (uint256);

    function getMarketUnitPrice(uint8 orderBookId) external view returns (uint256);

    function getLastOrderTimestamp(uint8 orderBookId) external view returns (uint48);

    function getBlockUnitPriceHistory(
        uint8 orderBookId
    ) external view returns (uint256[] memory unitPrices, uint48 timestamp);

    function getBlockUnitPriceAverage(
        uint8 orderBookId,
        uint256 count
    ) external view returns (uint256);

    function getBorrowOrderBook(
        uint8 orderBookId,
        uint256 start,
        uint256 limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        );

    function getLendOrderBook(
        uint8 orderBookId,
        uint256 start,
        uint256 limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        );

    function getItayoseEstimation(
        uint8 orderBookId
    )
        external
        view
        returns (
            uint256 openingUnitPrice,
            uint256 lastLendUnitPrice,
            uint256 lastBorrowUnitPrice,
            uint256 totalOffsetAmount
        );

    function getMaturity(uint8 orderBookId) external view returns (uint256);

    function getMaturities(
        uint8[] calldata orderBookIds
    ) external view returns (uint256[] memory maturities);

    function getCurrency() external view returns (bytes32);

    function getOrderFeeRate() external view returns (uint256);

    function getCircuitBreakerLimitRange() external view returns (uint256);

    function getMinPreOrderAmount() external view returns (uint256);

    function getOpeningDate(uint8 orderBookId) external view returns (uint256);

    function isReady(uint8 orderBookId) external view returns (bool);

    function isMatured(uint8 orderBookId) external view returns (bool);

    function isOpened(uint8 orderBookId) external view returns (bool);

    function isItayosePeriod(uint8 orderBookId) external view returns (bool);

    function isPreOrderPeriod(uint8 orderBookId) external view returns (bool);

    /**
     * @notice Gets the immutable price-discovery result once an Itayose process is initialized.
     * @dev A non-zero log does not mean the process is finalized. Use isReady for completion.
     */
    function getItayoseLog(uint256 maturity) external view returns (ItayoseLog memory);

    function getItayoseProcessStatus(
        uint8 orderBookId
    ) external view returns (ItayoseProcessStatus memory);

    function getOrder(
        uint8 orderBookId,
        uint48 orderId
    )
        external
        view
        returns (
            ProtocolTypes.Side,
            uint256 unitPrice,
            uint256 maturity,
            address maker,
            uint256 amount,
            uint256 timestamp,
            bool isPreOrder
        );

    function getTotalAmountFromLendOrders(
        uint8 orderBookId,
        address user
    )
        external
        view
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        );

    function getTotalAmountFromBorrowOrders(
        uint8 orderBookId,
        address user,
        uint256 _minUnitPrice
    )
        external
        view
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        );

    function getLendOrderIds(
        uint8 orderBookId,
        address user
    ) external view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds);

    function getBorrowOrderIds(
        uint8 orderBookId,
        address user
    ) external view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds);

    function calculateFilledAmount(
        uint8 orderBookId,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 feeInFV,
            uint256 placedAmount
        );

    function calculateFilledAmountFromFV(
        uint8 orderBookId,
        ProtocolTypes.Side side,
        uint256 amountInFV
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV
        );

    function createOrderBook(
        uint256 maturity,
        uint256 openingDate,
        uint256 preOpeningDate
    ) external returns (uint8 orderBookId);

    function executeAutoRoll(
        uint8 maturedOrderBookId,
        uint8 newNearestOrderBookId,
        uint256 autoRollUnitPrice
    ) external;

    function cancelOrder(uint8 orderBookId, address user, uint48 orderId) external;

    function executeOrder(
        uint8 orderBookId,
        ProtocolTypes.Side side,
        address account,
        uint256 amount,
        uint256 unitPrice
    )
        external
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        );

    function executePreOrder(
        uint8 orderBookId,
        ProtocolTypes.Side side,
        address user,
        uint256 amount,
        uint256 unitPrice
    ) external;

    function unwindPosition(
        uint8 orderBookId,
        ProtocolTypes.Side side,
        address user,
        uint256 futureValue
    )
        external
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        );

    function initializeItayose(uint8 orderBookId) external returns (ItayoseProcessStatus memory);

    function executeItayoseSettlement(
        uint8 orderBookId
    ) external returns (ItayoseSettlementResult memory);

    function finalizeItayose(uint8 orderBookId) external returns (ItayoseFinalizeResult memory);

    function cleanUpOrders(
        uint8 orderBookId,
        address user
    )
        external
        returns (
            uint256 activeLendOrderCount,
            uint256 activeBorrowOrderCount,
            uint256 removedLendOrderFutureValue,
            uint256 removedBorrowOrderFutureValue,
            uint256 removedLendOrderAmount,
            uint256 removedBorrowOrderAmount,
            uint256 maturity
        );

    function updateOrderFeeRate(uint256 orderFeeRate) external;

    function updateCircuitBreakerLimitRange(uint256 limitRange) external;

    function updateMinPreOrderAmount(uint256 minPreOrderAmount) external;

    function pause() external;

    function unpause() external;
}

contracts/protocol/interfaces/ILendingMarketController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {ProtocolTypes} from "../types/ProtocolTypes.sol";
import {ItayoseProcessStatus} from "../libraries/logics/OrderBookLogic.sol";
import {ZCTokenInfo, TerminationCurrencyCache} from "../storages/LendingMarketControllerStorage.sol";

interface ILendingMarketController {
    error InvalidMaturity();
    error MarketTerminated();
    error NotTerminated();
    error AlreadyInitialized();

    event ItayoseProcessInitialized(
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 openingUnitPrice,
        uint256 lastLendUnitPrice,
        uint256 lastBorrowUnitPrice,
        uint256 totalOffsetAmount
    );

    event ItayoseSettlementProgress(
        bytes32 indexed ccy,
        uint256 indexed maturity,
        ProtocolTypes.Side makerSide,
        uint256 batchFilledAmount,
        uint256 remainingLendOffsetAmount,
        uint256 remainingBorrowOffsetAmount
    );

    event ItayoseProcessFinalized(bytes32 indexed ccy, uint256 indexed maturity);

    struct AdditionalFunds {
        bytes32 ccy;
        uint256 workingLendOrdersAmount;
        uint256 claimableAmount;
        uint256 workingBorrowOrdersAmount;
        uint256 debtAmount;
        uint256 lentAmount;
        uint256 borrowedAmount;
    }

    struct CalculatedTotalFunds {
        uint256 plusDepositAmountInAdditionalFundsCcy;
        uint256 minusDepositAmountInAdditionalFundsCcy;
        uint256 workingLendOrdersAmount;
        uint256 claimableAmount;
        uint256 collateralAmount;
        uint256 lentAmount;
        uint256 workingBorrowOrdersAmount;
        uint256 debtAmount;
        uint256 borrowedAmount;
    }

    struct CalculatedFunds {
        uint256 workingLendOrdersAmount;
        uint256 claimableAmount;
        uint256 collateralAmount;
        uint256 unallocatedCollateralAmount;
        uint256 lentAmount;
        uint256 workingBorrowOrdersAmount;
        uint256 debtAmount;
        uint256 borrowedAmount;
    }

    struct GetOrderEstimationParams {
        bytes32 ccy;
        uint256 maturity;
        address user;
        ProtocolTypes.Side side;
        uint256 amount;
        uint256 unitPrice;
        uint256 additionalDepositAmount;
        bool ignoreBorrowedAmount;
    }

    struct GetOrderEstimationFromFVParams {
        bytes32 ccy;
        uint256 maturity;
        address user;
        ProtocolTypes.Side side;
        uint256 amountInFV;
        uint256 additionalDepositAmount;
        bool ignoreBorrowedAmount;
    }

    function isValidMaturity(bytes32 _ccy, uint256 _maturity) external view returns (bool);

    function isTerminated() external view returns (bool);

    function isRedemptionRequired(address _user) external view returns (bool);

    function getMarketBasePeriod() external view returns (uint256);

    function getTerminationDate() external view returns (uint256);

    function getTerminationCurrencyCache(
        bytes32 _ccy
    ) external view returns (TerminationCurrencyCache memory);

    function getTerminationCollateralRatio(bytes32 _ccy) external view returns (uint256);

    function getMinDebtUnitPrice(bytes32 _ccy) external view returns (uint256);

    function getCurrentMinDebtUnitPrice(
        bytes32 _ccy,
        uint256 _maturity
    ) external view returns (uint256);

    function getMinDebtUnitPriceAt(
        bytes32 ccy,
        uint256 maturity,
        uint256 referenceTimestamp
    ) external view returns (uint256);

    function getOrderUnitPriceRange(
        bytes32 ccy,
        uint256 maturity
    )
        external
        view
        returns (
            uint256 minLendUnitPrice,
            uint256 maxLendUnitPrice,
            uint256 minBorrowUnitPrice,
            uint256 maxBorrowUnitPrice,
            uint256 referenceUnitPrice,
            bool isMinDebtUnitPriceReference
        );

    function getItayoseProcessStatus(
        bytes32 ccy,
        uint256 maturity
    ) external view returns (ItayoseProcessStatus memory);

    function getGenesisDate(bytes32 ccy) external view returns (uint256);

    function getLendingMarket(bytes32 ccy) external view returns (address);

    function getFutureValueVault(bytes32 ccy) external view returns (address);

    function getOrderBookId(bytes32 _ccy, uint256 _maturity) external view returns (uint8);

    function getPendingOrderAmount(bytes32 _ccy, uint256 _maturity) external view returns (uint256);

    function getOrderEstimation(
        GetOrderEstimationParams calldata params
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV,
            uint256 placedAmount,
            uint256 coverage,
            bool isInsufficientDepositAmount
        );

    function getOrderEstimationFromFV(
        GetOrderEstimationFromFVParams calldata _params
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV,
            uint256 coverage,
            bool isInsufficientDepositAmount
        );

    function getMaturities(bytes32 ccy) external view returns (uint256[] memory);

    function getOrderBookIds(bytes32 ccy) external view returns (uint8[] memory);

    function getUsedCurrencies(address user) external view returns (bytes32[] memory);

    function getUsedMaturities(bytes32 ccy, address user) external view returns (uint256[] memory);

    function getTotalPresentValue(bytes32 ccy, address user) external view returns (int256);

    function getTotalPresentValueInBaseCurrency(
        address user
    ) external view returns (int256 totalPresentValue);

    function getGenesisValue(
        bytes32 ccy,
        address user
    ) external view returns (int256 amount, int256 amountInPV, int256 amountInFV);

    function getPosition(
        bytes32 _ccy,
        uint256 _maturity,
        address _user
    ) external view returns (int256 presentValue, int256 futureValue);

    function getZCToken(bytes32 ccy, uint256 maturity) external view returns (address);

    function getZCTokenInfo(address zcToken) external view returns (ZCTokenInfo memory);

    function getWithdrawableZCTokenAmount(
        bytes32 ccy,
        uint256 maturity,
        address user
    ) external view returns (uint256 amount);

    function calculateFunds(
        bytes32 ccy,
        address user,
        uint256 liquidationThresholdRate
    ) external view returns (CalculatedFunds memory funds);

    function calculateTotalFundsInBaseCurrency(
        address user,
        AdditionalFunds calldata additionalFunds,
        uint256 liquidationThresholdRate,
        bool useConservativePrice
    ) external view returns (CalculatedTotalFunds memory calculatedFunds);

    function isInitializedLendingMarket(bytes32 ccy) external view returns (bool);

    function initializeLendingMarket(
        bytes32 ccy,
        uint256 genesisDate,
        uint256 compoundFactor,
        uint256 orderFeeRate,
        uint256 circuitBreakerLimitRange,
        uint256 minDebtUnitPrice
    ) external;

    function createOrderBook(bytes32 ccy, uint256 openingDate, uint256 preOpeningDate) external;

    function executeOrder(
        bytes32 ccy,
        uint256 maturity,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    ) external returns (bool);

    function depositAndExecuteOrder(
        bytes32 ccy,
        uint256 maturity,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    ) external payable returns (bool);

    function depositWithPermitAndExecuteOrder(
        bytes32 ccy,
        uint256 maturity,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice,
        uint256 deadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external returns (bool);

    function executePreOrder(
        bytes32 ccy,
        uint256 maturity,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    ) external returns (bool);

    function depositAndExecutesPreOrder(
        bytes32 ccy,
        uint256 maturity,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    ) external payable returns (bool);

    function depositWithPermitAndExecutePreOrder(
        bytes32 _ccy,
        uint256 _maturity,
        ProtocolTypes.Side _side,
        uint256 _amount,
        uint256 _unitPrice,
        uint256 _deadline,
        uint8 _permitV,
        bytes32 _permitR,
        bytes32 _permitS
    ) external returns (bool);

    function unwindPosition(bytes32 ccy, uint256 maturity) external returns (bool);

    function unwindPositionWithCap(
        bytes32 ccy,
        uint256 maturity,
        uint256 maxFutureValue
    ) external returns (uint256 filledAmount, uint256 filledAmountInFV, uint256 feeInFV);

    function executeItayoseCall(bytes32 ccy, uint256 maturity) external returns (bool);

    function executeItayoseStep(bytes32 ccy, uint256 maturity) external returns (bool completed);

    function executeRedemption(bytes32 _ccy, uint256 _maturity) external returns (bool);

    function executeRepayment(bytes32 _ccy, uint256 _maturity) external returns (bool);

    function executeEmergencySettlement() external returns (bool);

    function executeLiquidationCall(
        bytes32 collateralCcy,
        bytes32 debtCcy,
        uint256 debtMaturity,
        address user
    ) external returns (bool);

    function executeForcedRepayment(
        bytes32 _collateralCcy,
        bytes32 _debtCcy,
        uint256 _debtMaturity,
        address _user
    ) external returns (bool);

    function cancelOrder(bytes32 ccy, uint256 maturity, uint48 orderId) external returns (bool);

    function rotateOrderBooks(bytes32 ccy) external;

    function executeEmergencyTermination() external;

    function pauseLendingMarket(bytes32 ccy) external returns (bool);

    function unpauseLendingMarket(bytes32 ccy) external returns (bool);

    function cleanUpFunds(bytes32 ccy, address user) external returns (uint256 activeOrderCount);

    function updateMinDebtUnitPrice(bytes32 _ccy, uint256 _minDebtUnitPrice) external;

    function withdrawZCToken(
        bytes32 _ccy,
        uint256 _maturity,
        uint256 _amount
    ) external returns (uint256 withdrawnAmount);

    function depositZCToken(bytes32 _ccy, uint256 _maturity, uint256 _amount) external;
}

contracts/protocol/interfaces/INativeToken.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../../dependencies/openzeppelin/token/ERC20/IERC20.sol";

interface INativeToken is IERC20 {
    event Deposit(address user, uint256 amount);
    event Withdrawal(address user, uint256 amount);

    function deposit() external payable;

    function withdraw(uint256 amount) external;
}

contracts/protocol/interfaces/IReserveFund.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

interface IReserveFund {
    event Pause(address account);
    event Unpause(address account);

    function isPaused() external view returns (bool);

    function pause() external;

    function unpause() external;

    function deposit(bytes32 ccy, uint256 amount) external payable;

    function withdraw(bytes32 ccy, uint256 amount) external returns (uint256 withdrawnAmount);
}

contracts/protocol/interfaces/ITokenVault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {ProtocolTypes} from "../types/ProtocolTypes.sol";
import {ILendingMarketController} from "../interfaces/ILendingMarketController.sol";

interface ITokenVault {
    error UnregisteredCurrency();
    error InvalidCurrency();
    error InvalidToken();
    error InvalidAmount(bytes32 ccy, uint256 amount, uint256 msgValue);
    error AmountIsZero();
    error InvalidAddress();
    error CallerNotBaseCurrency(address caller);
    error MarketTerminated();
    error RedemptionIsRequired();

    event Deposit(address indexed user, bytes32 ccy, uint256 amount, address caller);
    event Withdraw(address indexed user, bytes32 ccy, uint256 amount);
    event Transfer(bytes32 indexed ccy, address indexed from, address indexed to, uint256 amount);
    event CurrencyRegistered(bytes32 ccy, address tokenAddress, bool isCollateral);
    event CurrencyUpdated(bytes32 ccy, bool isCollateral);

    function isCovered(
        address user,
        bytes32 ccy
    ) external view returns (bool isEnoughCollateral, bool isEnoughDepositInOrderCcy);

    function isCollateral(bytes32 ccy) external view returns (bool);

    function isCollateral(bytes32[] calldata ccys) external view returns (bool[] memory);

    function isRegisteredCurrency(bytes32 ccy) external view returns (bool);

    function canDepositCurrency(address user, bytes32 ccy) external view returns (bool);

    function getTokenAddress(bytes32 ccy) external view returns (address);

    function getCollateralCurrencies() external view returns (bytes32[] memory);

    function getWithdrawableCollateral(address user) external view returns (uint256);

    function getWithdrawableCollateral(bytes32 ccy, address user) external view returns (uint256);

    function getCoverage(address user) external view returns (uint256);

    function getTotalUnusedCollateralAmount(address user) external view returns (uint256);

    function getTotalCollateralAmount(address user) external view returns (uint256);

    function getTotalCollateralAmount(
        address user,
        bool useConservativePrice
    ) external view returns (uint256);

    function getCollateralDetail(
        address user,
        bool useConservativePrice
    )
        external
        view
        returns (uint256 totalCollateral, uint256 totalUsedCollateral, uint256 totalDeposit);

    function getCollateralAmount(address user, bytes32 ccy) external view returns (uint256);

    function getBorrowableAmount(address user, bytes32 ccy) external view returns (uint256);

    function getLiquidationAmount(
        address user,
        bytes32 liquidationCcy,
        uint256 liquidationAmountMaximum
    ) external view returns (uint256 liquidationAmount, uint256 protocolFee, uint256 liquidatorFee);

    function getTotalDepositAmount(bytes32 ccy) external view returns (uint256);

    function getDepositAmount(address user, bytes32 ccy) external view returns (uint256);

    function getUsedCurrencies(address user) external view returns (bytes32[] memory);

    function calculateCoverage(
        address user,
        ILendingMarketController.AdditionalFunds memory funds
    ) external view returns (uint256 coverage, bool isInsufficientDepositAmount);

    function calculateLiquidationFees(
        uint256 liquidationAmount
    ) external view returns (uint256 protocolFee, uint256 liquidatorFee);

    function registerCurrency(bytes32 ccy, address tokenAddress, bool isCollateral) external;

    function updateCurrency(bytes32 ccy, bool isCollateral) external;

    function deposit(bytes32 ccy, uint256 amount) external payable;

    function depositTo(bytes32 ccy, uint256 amount, address onBehalfOf) external payable;

    function depositFrom(address user, bytes32 ccy, uint256 amount) external payable;

    function depositWithPermitTo(
        bytes32 ccy,
        uint256 amount,
        address onBehalfOf,
        uint256 deadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external;

    function depositWithPermitFrom(
        address user,
        bytes32 ccy,
        uint256 amount,
        uint256 deadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external;

    function withdraw(bytes32 ccy, uint256 amount) external returns (uint256 withdrawnAmount);

    function addDepositAmount(address user, bytes32 ccy, uint256 amount) external;

    function removeDepositAmount(address user, bytes32 ccy, uint256 amount) external;

    function executeForcedReset(address user, bytes32 ccy) external returns (uint256 removedAmount);

    function transferFrom(
        bytes32 ccy,
        address sender,
        address receiver,
        uint256 amount
    ) external returns (uint256 untransferredAmount);

    function pause() external;

    function unpause() external;

    function getLiquidationThresholdRate() external view returns (uint256 rate);
}

contracts/protocol/libraries/AddressResolverLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {Contracts} from "../libraries/Contracts.sol";
import {IBeaconProxyController} from "../interfaces/IBeaconProxyController.sol";
import {ICurrencyController} from "../interfaces/ICurrencyController.sol";
import {IGenesisValueVault} from "../interfaces/IGenesisValueVault.sol";
import {ILendingMarketController} from "../interfaces/ILendingMarketController.sol";
import {IReserveFund} from "../interfaces/IReserveFund.sol";
import {ITokenVault} from "../interfaces/ITokenVault.sol";
import {MixinAddressResolverStorage as Storage} from "../storages/mixins/MixinAddressResolverStorage.sol";

library AddressResolverLib {
    error MissingAddress(string name);

    function getAddress(bytes32 name) internal view returns (address) {
        address _foundAddress = Storage.slot().addressCache[name];
        if (_foundAddress == address(0)) revert MissingAddress(string(abi.encodePacked(name)));
        return _foundAddress;
    }

    function beaconProxyController() internal view returns (IBeaconProxyController) {
        return IBeaconProxyController(getAddress(Contracts.BEACON_PROXY_CONTROLLER));
    }

    function currencyController() internal view returns (ICurrencyController) {
        return ICurrencyController(getAddress(Contracts.CURRENCY_CONTROLLER));
    }

    function genesisValueVault() internal view returns (IGenesisValueVault) {
        return IGenesisValueVault(getAddress(Contracts.GENESIS_VALUE_VAULT));
    }

    function lendingMarketController() internal view returns (ILendingMarketController) {
        return ILendingMarketController(getAddress(Contracts.LENDING_MARKET_CONTROLLER));
    }

    function reserveFund() internal view returns (IReserveFund) {
        return IReserveFund(getAddress(Contracts.RESERVE_FUND));
    }

    function tokenVault() internal view returns (ITokenVault) {
        return ITokenVault(getAddress(Contracts.TOKEN_VAULT));
    }
}

contracts/protocol/libraries/Constants.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library Constants {
    /// @dev Used for price digits in the basis (10000 -> 1)
    uint256 internal constant PRICE_DIGIT = 10000;

    /// @dev Used for percentage digits in the basis (10000 -> 100%)
    uint256 internal constant PCT_DIGIT = 10000;

    /// @dev Used for seconds in year (60 * 60 * 24 * 365)
    uint256 internal constant SECONDS_IN_YEAR = 31536000;

    /// @dev Used for maximum order count per currency
    uint256 internal constant MAXIMUM_ORDER_COUNT = 20;
}

contracts/protocol/libraries/Contracts.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library Contracts {
    bytes32 internal constant BEACON_PROXY_CONTROLLER = "BeaconProxyController";
    bytes32 internal constant CURRENCY_CONTROLLER = "CurrencyController";
    bytes32 internal constant GENESIS_VALUE_VAULT = "GenesisValueVault";
    bytes32 internal constant LENDING_MARKET_CONTROLLER = "LendingMarketController";
    bytes32 internal constant RESERVE_FUND = "ReserveFund";
    bytes32 internal constant TOKEN_VAULT = "TokenVault";
}

library BeaconContracts {
    bytes32 internal constant FUTURE_VALUE_VAULT = "FutureValueVault";
    bytes32 internal constant LENDING_MARKET = "LendingMarket";
    bytes32 internal constant ZC_TOKEN = "ZCToken";
}

contracts/protocol/libraries/OrderBookLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {Constants} from "./Constants.sol";
import {ProtocolTypes} from "../types/ProtocolTypes.sol";
import {OrderStatisticsTreeLib, PartiallyRemovedOrder} from "./OrderStatisticsTreeLib.sol";
import {RoundingUint256} from "./math/RoundingUint256.sol";

struct PlacedOrder {
    ProtocolTypes.Side side;
    uint256 unitPrice;
    uint256 maturity;
    uint256 timestamp;
}

struct FilledOrder {
    uint256 amount;
    uint256 unitPrice;
    uint256 futureValue;
    uint256 ignoredAmount;
}

struct PartiallyFilledOrder {
    uint48 orderId;
    address maker;
    uint256 amount;
    uint256 futureValue;
}

library OrderBookLib {
    using OrderStatisticsTreeLib for OrderStatisticsTreeLib.Tree;
    using RoundingUint256 for uint256;

    uint256 public constant PRE_ORDER_BASE_PERIOD = 7 days;
    uint256 public constant ITAYOSE_PERIOD = 1 hours;
    uint256 public constant CIRCUIT_BREAKER_MINIMUM_LEND_RANGE = 500;
    uint256 public constant CIRCUIT_BREAKER_MINIMUM_BORROW_RANGE = 200;

    error EmptyOrderBook();
    error PastMaturityOrderExists();

    struct OrderBook {
        uint256 maturity;
        uint256 openingDate;
        uint256 preOpeningDate;
        uint48 lastOrderId;
        uint48 lastOrderTimestamp;
        bool isReliableBlock;
        // Micro slots for block unit price history
        uint80 blockUnitPriceHistory;
        uint48 lastBlockUnitPriceTimestamp;
        uint256 blockTotalAmount;
        uint256 blockTotalFutureValue;
        mapping(address user => uint48[] orderIds) activeLendOrderIds;
        mapping(address user => uint48[] orderIds) activeBorrowOrderIds;
        // Maturity when user last executes order
        mapping(address user => uint256 maturity) userCurrentMaturities;
        // Micro slots for order
        mapping(uint48 orderId => uint256 slots) orders;
        mapping(uint48 orderId => bool isPreOrder) isPreOrder;
        mapping(uint256 maturity => OrderStatisticsTreeLib.Tree orders) lendOrders;
        mapping(uint256 maturity => OrderStatisticsTreeLib.Tree orders) borrowOrders;
    }

    function initialize(
        OrderBook storage self,
        uint256 _maturity,
        uint256 _openingDate,
        uint256 _preOpeningDate
    ) internal returns (bool isReady) {
        self.maturity = _maturity;
        self.openingDate = _openingDate;
        self.preOpeningDate = _preOpeningDate;

        self.blockTotalAmount = 0;
        self.blockTotalFutureValue = 0;
        self.blockUnitPriceHistory = 0;
        self.lastOrderTimestamp = 0;
        self.lastBlockUnitPriceTimestamp = 0;
        self.isReliableBlock = false;

        if (block.timestamp >= (_openingDate - ITAYOSE_PERIOD)) {
            isReady = true;
        }
    }

    function isMatured(OrderBook storage self) internal view returns (bool) {
        return block.timestamp >= self.maturity;
    }

    function getBestBorrowUnitPrice(OrderBook storage self) internal view returns (uint256) {
        return self.lendOrders[self.maturity].last();
    }

    function getBestLendUnitPrice(OrderBook storage self) internal view returns (uint256) {
        uint256 unitPrice = self.borrowOrders[self.maturity].first();
        return unitPrice == 0 ? Constants.PRICE_DIGIT : unitPrice;
    }

    function hasBorrowOrder(OrderBook storage self, address _user) internal view returns (bool) {
        return self.activeBorrowOrderIds[_user].length != 0;
    }

    function hasLendOrder(OrderBook storage self, address _user) internal view returns (bool) {
        return self.activeLendOrderIds[_user].length != 0;
    }

    function getOrder(
        OrderBook storage self,
        uint48 _orderId
    ) internal view returns (PlacedOrder memory order) {
        (
            ProtocolTypes.Side side,
            uint256 unitPrice,
            uint256 maturity,
            uint256 timestamp
        ) = _unpackOrder(self.orders[_orderId]);
        order = PlacedOrder(side, unitPrice, maturity, timestamp);
    }

    function getBlockUnitPriceHistory(
        OrderBook storage self,
        bool _isReadOnly
    ) internal view returns (uint256[] memory prices, uint48 timestamp) {
        prices = _unpackBlockUnitPriceHistory(self.blockUnitPriceHistory);

        // NOTE: If an order is in the first block of the order book, the block unit price history is empty.
        // In this case, the first history record is calculated from the current block total amount and total future value
        // along with the `getMarketUnitPrice` function logic.
        if (
            (self.lastOrderTimestamp != block.timestamp || prices[0] == 0 || _isReadOnly) &&
            self.isReliableBlock
        ) {
            for (uint256 i = prices.length - 1; i > 0; i--) {
                prices[i] = prices[i - 1];
            }

            prices[0] = (self.blockTotalAmount * Constants.PRICE_DIGIT).div(
                self.blockTotalFutureValue
            );
            timestamp = self.lastOrderTimestamp;
        } else {
            timestamp = self.lastBlockUnitPriceTimestamp;
        }
    }

    function getMarketUnitPrice(
        OrderBook storage self,
        bool _includeCurrentBlock
    ) internal view returns (uint256 unitPrice) {
        unitPrice = _unpackBlockUnitPriceHistory(self.blockUnitPriceHistory)[0];

        // NOTE: If an order is in the first block of the order book, the block unit price history is empty.
        // In this case, the market unit price is calculated from the current block total amount and total future value
        // to avoid unwinding or liquidation the order in the same block using 0 as the market unit price.
        if (
            (self.lastOrderTimestamp != block.timestamp ||
                unitPrice == 0 ||
                _includeCurrentBlock) && self.isReliableBlock
        ) {
            unitPrice = (self.blockTotalAmount * Constants.PRICE_DIGIT).div(
                self.blockTotalFutureValue
            );
        }
    }

    function getBlockUnitPriceAverage(
        OrderBook storage self,
        uint256 maxCount,
        bool _isReadOnly
    ) internal view returns (uint256 unitPrice) {
        uint256[] memory unitPrices = _unpackBlockUnitPriceHistory(self.blockUnitPriceHistory);
        uint256 length = unitPrices.length;
        uint256 sum;
        uint256 count;

        if ((self.lastOrderTimestamp != block.timestamp || _isReadOnly) && self.isReliableBlock) {
            sum = (self.blockTotalAmount * Constants.PRICE_DIGIT).div(self.blockTotalFutureValue);
            count = 1;
            maxCount--;
        }

        for (uint256 i; i < maxCount; i++) {
            if (i >= length || unitPrices[i] == 0) {
                break;
            }

            sum += unitPrices[i];
            count++;
        }

        unitPrice = count > 0 ? sum.div(count) : 0;
    }

    function getLendOrderBook(
        OrderBook storage self,
        uint256 _start,
        uint256 _limit
    )
        internal
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        unitPrices = new uint256[](_limit);
        amounts = new uint256[](_limit);
        quantities = new uint256[](_limit);

        if (_limit == 0) {
            return (unitPrices, amounts, quantities, 0);
        }

        uint256 unitPrice;

        if (_start == 0) {
            unitPrice = self.lendOrders[self.maturity].last();
        } else {
            (bool exists, uint256 parent) = self.lendOrders[self.maturity].search(_start);

            if (exists) {
                unitPrice = _start;
            } else if (parent < _start) {
                unitPrice = parent;
            } else {
                unitPrice = self.lendOrders[self.maturity].prev(parent);
            }
        }

        unitPrices[0] = unitPrice;
        amounts[0] = self.lendOrders[self.maturity].getNodeTotalAmount(unitPrice);
        quantities[0] = self.lendOrders[self.maturity].getNodeCount(unitPrice);

        for (uint256 i = 1; i < unitPrices.length; i++) {
            if (unitPrice == 0) {
                break;
            }

            unitPrice = self.lendOrders[self.maturity].prev(unitPrice);
            unitPrices[i] = unitPrice;
            amounts[i] = self.lendOrders[self.maturity].getNodeTotalAmount(unitPrice);
            quantities[i] = self.lendOrders[self.maturity].getNodeCount(unitPrice);
        }

        if (unitPrice != 0) {
            next = self.lendOrders[self.maturity].prev(unitPrice);
        }
    }

    function getBorrowOrderBook(
        OrderBook storage self,
        uint256 _start,
        uint256 _limit
    )
        internal
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        unitPrices = new uint256[](_limit);
        amounts = new uint256[](_limit);
        quantities = new uint256[](_limit);

        if (_limit == 0) {
            return (unitPrices, amounts, quantities, 0);
        }

        uint256 unitPrice;

        if (_start == 0) {
            unitPrice = self.borrowOrders[self.maturity].first();
        } else {
            (bool exists, uint256 parent) = self.borrowOrders[self.maturity].search(_start);

            if (exists) {
                unitPrice = _start;
            } else if (parent > _start) {
                unitPrice = parent;
            } else {
                unitPrice = self.borrowOrders[self.maturity].next(parent);
            }
        }

        unitPrices[0] = unitPrice;
        amounts[0] = self.borrowOrders[self.maturity].getNodeTotalAmount(unitPrice);
        quantities[0] = self.borrowOrders[self.maturity].getNodeCount(unitPrice);

        for (uint256 i = 1; i < unitPrices.length; i++) {
            if (unitPrice == 0) {
                break;
            }

            unitPrice = self.borrowOrders[self.maturity].next(unitPrice);
            unitPrices[i] = unitPrice;
            amounts[i] = self.borrowOrders[self.maturity].getNodeTotalAmount(unitPrice);
            quantities[i] = self.borrowOrders[self.maturity].getNodeCount(unitPrice);
        }

        if (unitPrice != 0) {
            next = self.borrowOrders[self.maturity].next(unitPrice);
        }
    }

    function getLendOrderIds(
        OrderBook storage self,
        address _user
    ) internal view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) {
        uint256 activeOrderCount = 0;
        uint256 inActiveOrderCount = 0;
        uint256 userMaturity = self.userCurrentMaturities[_user];
        bool isPastMaturity = block.timestamp >= userMaturity;

        uint48[] memory orderIds = self.activeLendOrderIds[_user];
        uint256 orderIdLength = orderIds.length;
        activeOrderIds = new uint48[](isPastMaturity ? 0 : orderIdLength);
        inActiveOrderIds = new uint48[](orderIdLength);

        for (uint256 i; i < orderIdLength; i++) {
            uint48 orderId = orderIds[i];
            (, uint256 unitPrice, , ) = _unpackOrder(self.orders[orderId]);

            if (!self.lendOrders[userMaturity].isActiveOrderId(unitPrice, orderId)) {
                unchecked {
                    inActiveOrderCount += 1;
                }
                inActiveOrderIds[i - activeOrderCount] = orderId;
                if (!isPastMaturity) {
                    assembly {
                        mstore(activeOrderIds, sub(mload(activeOrderIds), 1))
                    }
                }
            } else {
                unchecked {
                    activeOrderCount += 1;
                }
                if (!isPastMaturity) {
                    activeOrderIds[i - inActiveOrderCount] = orderId;
                }
                assembly {
                    mstore(inActiveOrderIds, sub(mload(inActiveOrderIds), 1))
                }
            }
        }
    }

    function getBorrowOrderIds(
        OrderBook storage self,
        address _user
    ) internal view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) {
        uint256 activeOrderCount = 0;
        uint256 inActiveOrderCount = 0;
        uint256 userMaturity = self.userCurrentMaturities[_user];
        bool isPastMaturity = block.timestamp >= userMaturity;

        uint48[] memory orderIds = self.activeBorrowOrderIds[_user];
        uint256 orderIdLength = orderIds.length;
        activeOrderIds = new uint48[](isPastMaturity ? 0 : orderIdLength);
        inActiveOrderIds = new uint48[](orderIdLength);

        for (uint256 i; i < orderIdLength; i++) {
            uint48 orderId = orderIds[i];
            (, uint256 unitPrice, , ) = _unpackOrder(self.orders[orderId]);

            if (!self.borrowOrders[userMaturity].isActiveOrderId(unitPrice, orderId)) {
                unchecked {
                    inActiveOrderCount += 1;
                }
                inActiveOrderIds[i - activeOrderCount] = orderId;
                if (!isPastMaturity) {
                    assembly {
                        mstore(activeOrderIds, sub(mload(activeOrderIds), 1))
                    }
                }
            } else {
                unchecked {
                    activeOrderCount += 1;
                }
                if (!isPastMaturity) {
                    activeOrderIds[i - inActiveOrderCount] = orderId;
                }
                assembly {
                    mstore(inActiveOrderIds, sub(mload(inActiveOrderIds), 1))
                }
            }
        }
    }

    function calculateFilledAmount(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        uint256 _amount,
        uint256 _unitPrice
    )
        internal
        view
        returns (uint256 lastUnitPrice, uint256 filledAmount, uint256 filledAmountInFV)
    {
        if (_amount == 0) return (0, 0, 0);

        if (_side == ProtocolTypes.Side.LEND) {
            return
                self.borrowOrders[self.maturity].calculateDroppedAmountFromLeft(
                    _amount,
                    0,
                    _unitPrice
                );
        } else {
            return
                self.lendOrders[self.maturity].calculateDroppedAmountFromRight(
                    _amount,
                    0,
                    _unitPrice
                );
        }
    }

    function calculateFilledAmountFromFV(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        uint256 _amountInFV,
        uint256 _unitPrice
    )
        internal
        view
        returns (uint256 lastUnitPrice, uint256 filledAmount, uint256 filledAmountInFV)
    {
        if (_amountInFV == 0) return (0, 0, 0);

        if (_side == ProtocolTypes.Side.LEND) {
            return
                self.borrowOrders[self.maturity].calculateDroppedAmountFromLeft(
                    0,
                    _amountInFV,
                    _unitPrice
                );
        } else {
            return
                self.lendOrders[self.maturity].calculateDroppedAmountFromRight(
                    0,
                    _amountInFV,
                    _unitPrice
                );
        }
    }

    function updateUserMaturity(OrderBook storage self, address _user) internal {
        uint256 userMaturity = self.userCurrentMaturities[_user];
        uint256 orderBookMaturity = self.maturity;

        if (userMaturity != orderBookMaturity) {
            if (
                self.activeLendOrderIds[_user].length > 0 ||
                self.activeBorrowOrderIds[_user].length > 0
            ) {
                revert PastMaturityOrderExists();
            }

            self.userCurrentMaturities[_user] = orderBookMaturity;
        }
    }

    function placeOrder(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice
    ) internal returns (uint48 orderId) {
        orderId = _nextOrderId(self);
        self.orders[orderId] = _packOrder(_side, _unitPrice, self.maturity, block.timestamp);

        if (_side == ProtocolTypes.Side.LEND) {
            self.lendOrders[self.maturity].insertOrder(_unitPrice, orderId, _user, _amount);
            self.activeLendOrderIds[_user].push(orderId);
        } else if (_side == ProtocolTypes.Side.BORROW) {
            self.borrowOrders[self.maturity].insertOrder(_unitPrice, orderId, _user, _amount);
            self.activeBorrowOrderIds[_user].push(orderId);
        }
    }

    function fillOrders(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        uint256 _amount,
        uint256 _amountInFV,
        uint256 _unitPrice
    )
        internal
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 remainingAmount,
            bool orderExists
        )
    {
        PartiallyRemovedOrder memory partiallyRemovedOrder;

        if (_side == ProtocolTypes.Side.BORROW) {
            OrderStatisticsTreeLib.Tree storage orders = self.lendOrders[self.maturity];
            (
                filledOrder.unitPrice,
                filledOrder.amount,
                filledOrder.futureValue,
                remainingAmount,
                partiallyRemovedOrder
            ) = orders.dropRight(_amount, _amountInFV, _unitPrice);
            orderExists = orders.hasOrders();
        } else if (_side == ProtocolTypes.Side.LEND) {
            OrderStatisticsTreeLib.Tree storage orders = self.borrowOrders[self.maturity];
            (
                filledOrder.unitPrice,
                filledOrder.amount,
                filledOrder.futureValue,
                remainingAmount,
                partiallyRemovedOrder
            ) = orders.dropLeft(_amount, _amountInFV, _unitPrice);
            orderExists = orders.hasOrders();
        }

        partiallyFilledOrder = PartiallyFilledOrder(
            partiallyRemovedOrder.orderId,
            partiallyRemovedOrder.maker,
            partiallyRemovedOrder.amount,
            partiallyRemovedOrder.futureValue
        );
    }

    function getItayoseBoundaryUnitPrice(
        OrderBook storage self,
        ProtocolTypes.Side _takerSide,
        uint256 _maxPriceLevels
    ) internal view returns (uint256 boundaryUnitPrice) {
        if (_takerSide == ProtocolTypes.Side.LEND) {
            OrderStatisticsTreeLib.Tree storage orders = self.borrowOrders[self.maturity];
            boundaryUnitPrice = orders.first();

            for (uint256 i = 1; i < _maxPriceLevels; i++) {
                uint256 nextUnitPrice = orders.next(boundaryUnitPrice);
                if (nextUnitPrice == 0) break;
                boundaryUnitPrice = nextUnitPrice;
            }
        } else {
            OrderStatisticsTreeLib.Tree storage orders = self.lendOrders[self.maturity];
            boundaryUnitPrice = orders.last();

            for (uint256 i = 1; i < _maxPriceLevels; i++) {
                uint256 previousUnitPrice = orders.prev(boundaryUnitPrice);
                if (previousUnitPrice == 0) break;
                boundaryUnitPrice = previousUnitPrice;
            }
        }
    }

    function migrateOrderChunks(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        uint256 _unitPrice
    ) internal {
        if (_side == ProtocolTypes.Side.LEND) {
            self.lendOrders[self.maturity].migrateOrderChunks(_unitPrice);
        } else {
            self.borrowOrders[self.maturity].migrateOrderChunks(_unitPrice);
        }
    }

    function setInitialBlockUnitPrice(OrderBook storage self, uint256 _unitPrice) internal {
        self.blockUnitPriceHistory = uint16(_unitPrice);
        self.lastBlockUnitPriceTimestamp = uint48(block.timestamp);
        self.lastOrderTimestamp = uint48(block.timestamp);
    }

    function updateBlockUnitPriceHistory(
        OrderBook storage self,
        uint256 _filledAmount,
        uint256 _filledFutureValue,
        uint256 _minimumReliableAmount
    ) internal returns (uint256 latestBlockUnitPrice, bool isUpdated) {
        latestBlockUnitPrice = _unpackBlockUnitPriceHistory(self.blockUnitPriceHistory)[0];

        if (self.lastOrderTimestamp != block.timestamp) {
            if (self.isReliableBlock) {
                latestBlockUnitPrice = (self.blockTotalAmount * Constants.PRICE_DIGIT).div(
                    self.blockTotalFutureValue
                );

                // Remove the oldest block unit price and add the latest block unit price
                self.blockUnitPriceHistory =
                    uint16(latestBlockUnitPrice) |
                    (self.blockUnitPriceHistory << 16);
                self.lastBlockUnitPriceTimestamp = uint48(block.timestamp);
                isUpdated = true;
            }

            self.lastOrderTimestamp = uint48(block.timestamp);
            self.blockTotalAmount = _filledAmount;
            self.blockTotalFutureValue = _filledFutureValue;
            self.isReliableBlock = false;
        } else {
            self.blockTotalAmount += _filledAmount;
            self.blockTotalFutureValue += _filledFutureValue;
        }

        if (
            self.blockTotalAmount >= _minimumReliableAmount ||
            (self.blockTotalAmount > 0 && latestBlockUnitPrice == 0)
        ) {
            self.isReliableBlock = true;
        }
    }

    function removeOrder(
        OrderBook storage self,
        address _user,
        uint48 _orderId
    ) internal returns (ProtocolTypes.Side, uint256, uint256) {
        (ProtocolTypes.Side side, uint256 unitPrice, , ) = _unpackOrder(self.orders[_orderId]);
        uint256 removedAmount;

        if (side == ProtocolTypes.Side.LEND) {
            removedAmount = self.lendOrders[self.maturity].removeOrder(unitPrice, _orderId);
            _removeOrderIdFromOrders(self.activeLendOrderIds[_user], _orderId);
        } else if (side == ProtocolTypes.Side.BORROW) {
            removedAmount = self.borrowOrders[self.maturity].removeOrder(unitPrice, _orderId);
            _removeOrderIdFromOrders(self.activeBorrowOrderIds[_user], _orderId);
        }

        delete self.orders[_orderId];

        return (side, removedAmount, unitPrice);
    }

    function calculateItayoseResult(
        OrderBook storage self
    )
        internal
        view
        returns (
            uint256 openingUnitPrice,
            uint256 lastLendUnitPrice,
            uint256 lastBorrowUnitPrice,
            uint256 totalOffsetAmount
        )
    {
        uint256 lendUnitPrice = self.lendOrders[self.maturity].last();
        uint256 borrowUnitPrice = self.borrowOrders[self.maturity].first();
        uint256 lendAmount = self.lendOrders[self.maturity].getNodeTotalAmount(lendUnitPrice);
        uint256 borrowAmount = self.borrowOrders[self.maturity].getNodeTotalAmount(borrowUnitPrice);

        OrderStatisticsTreeLib.Tree storage borrowOrders = self.borrowOrders[self.maturity];
        OrderStatisticsTreeLib.Tree storage lendOrders = self.lendOrders[self.maturity];

        // Return 0 if no orders is filled
        if (borrowUnitPrice > lendUnitPrice || borrowUnitPrice == 0 || lendUnitPrice == 0) {
            return (0, 0, 0, 0);
        }

        while (borrowUnitPrice <= lendUnitPrice && borrowUnitPrice > 0 && lendUnitPrice > 0) {
            lastLendUnitPrice = lendUnitPrice;
            lastBorrowUnitPrice = borrowUnitPrice;

            if (lendAmount > borrowAmount) {
                openingUnitPrice = lendUnitPrice;
                totalOffsetAmount += borrowAmount;
                lendAmount -= borrowAmount;
                (borrowUnitPrice, borrowAmount) = borrowOrders.nextWithTotalAmount(borrowUnitPrice);
            } else if (lendAmount < borrowAmount) {
                openingUnitPrice = borrowUnitPrice;
                totalOffsetAmount += lendAmount;
                borrowAmount -= lendAmount;
                (lendUnitPrice, lendAmount) = lendOrders.prevWithTotalAmount(lendUnitPrice);
            } else {
                openingUnitPrice = (lendUnitPrice + borrowUnitPrice).div(2);
                totalOffsetAmount += lendAmount;
                (lendUnitPrice, lendAmount) = lendOrders.prevWithTotalAmount(lendUnitPrice);
                (borrowUnitPrice, borrowAmount) = borrowOrders.nextWithTotalAmount(borrowUnitPrice);
            }
        }
    }

    function getOrderExecutionConditions(
        OrderBook storage self,
        ProtocolTypes.Side _side,
        uint256 _unitPrice,
        uint256 _circuitBreakerLimitRange,
        bool _isReadOnly
    )
        internal
        view
        returns (
            bool isFilled,
            uint256 executedUnitPrice,
            bool ignoreRemainingAmount,
            bool orderExists
        )
    {
        bool isLend = _side == ProtocolTypes.Side.LEND;
        uint256 cbThresholdUnitPrice;
        uint256 bestUnitPrice;
        uint256 blockUnitPriceAverage = getBlockUnitPriceAverage(self, 3, _isReadOnly);

        if (isLend) {
            bestUnitPrice = self.borrowOrders[self.maturity].first();
            cbThresholdUnitPrice = calculateLendCircuitBreakerThreshold(
                blockUnitPriceAverage,
                _circuitBreakerLimitRange
            );
        } else {
            bestUnitPrice = self.lendOrders[self.maturity].last();
            cbThresholdUnitPrice = calculateBorrowCircuitBreakerThreshold(
                blockUnitPriceAverage,
                _circuitBreakerLimitRange
            );
        }

        orderExists = bestUnitPrice != 0;

        if (
            _unitPrice == 0 ||
            (orderExists &&
                cbThresholdUnitPrice != 0 &&
                ((isLend && _unitPrice > cbThresholdUnitPrice) ||
                    (!isLend && _unitPrice < cbThresholdUnitPrice)))
        ) {
            executedUnitPrice = cbThresholdUnitPrice;
            ignoreRemainingAmount = true;
        } else {
            executedUnitPrice = _unitPrice;
            ignoreRemainingAmount = false;
        }

        if (orderExists) {
            isFilled = isLend
                ? bestUnitPrice <= executedUnitPrice
                : bestUnitPrice >= executedUnitPrice;
        }
    }

    function calculateLendCircuitBreakerThreshold(
        uint256 _blockUnitPriceAverage,
        uint256 _circuitBreakerLimitRange
    ) internal pure returns (uint256 cbThresholdUnitPrice) {
        if (_blockUnitPriceAverage == 0) return Constants.PRICE_DIGIT;

        cbThresholdUnitPrice = (_blockUnitPriceAverage *
            (Constants.PCT_DIGIT + _circuitBreakerLimitRange * 2)).div(Constants.PCT_DIGIT);

        if (cbThresholdUnitPrice < _blockUnitPriceAverage + CIRCUIT_BREAKER_MINIMUM_LEND_RANGE) {
            cbThresholdUnitPrice = _blockUnitPriceAverage + CIRCUIT_BREAKER_MINIMUM_LEND_RANGE;
        }

        if (cbThresholdUnitPrice > Constants.PRICE_DIGIT) {
            cbThresholdUnitPrice = Constants.PRICE_DIGIT;
        }
    }

    function calculateBorrowCircuitBreakerThreshold(
        uint256 _blockUnitPriceAverage,
        uint256 _circuitBreakerLimitRange
    ) internal pure returns (uint256 cbThresholdUnitPrice) {
        cbThresholdUnitPrice = (_blockUnitPriceAverage *
            (Constants.PCT_DIGIT - _circuitBreakerLimitRange)).div(Constants.PCT_DIGIT);

        if (
            cbThresholdUnitPrice == 0 ||
            _blockUnitPriceAverage == 0 ||
            _blockUnitPriceAverage <= CIRCUIT_BREAKER_MINIMUM_BORROW_RANGE
        ) {
            cbThresholdUnitPrice = 1;
        } else if (
            _blockUnitPriceAverage < cbThresholdUnitPrice + CIRCUIT_BREAKER_MINIMUM_BORROW_RANGE
        ) {
            cbThresholdUnitPrice = _blockUnitPriceAverage - CIRCUIT_BREAKER_MINIMUM_BORROW_RANGE;
        }
    }

    /**
     * @notice Increases and returns id of last order in order book.
     * @return The new order id
     */
    function _nextOrderId(OrderBook storage self) private returns (uint48) {
        self.lastOrderId++;
        return self.lastOrderId;
    }

    function _removeOrderIdFromOrders(uint48[] storage orders, uint256 orderId) private {
        uint256 lastOrderIndex = orders.length - 1;
        for (uint256 i; i <= lastOrderIndex; i++) {
            if (orders[i] == orderId) {
                if (i != lastOrderIndex) {
                    uint48 lastOrderId = orders[lastOrderIndex];
                    orders[i] = lastOrderId;
                }

                orders.pop();
                break;
            }
        }
    }

    /**
     * @notice Packs order parameters into uint256
     */
    function _packOrder(
        ProtocolTypes.Side _side,
        uint256 _unitPrice,
        uint256 _maturity,
        uint256 _timestamp
    ) private pure returns (uint256) {
        return uint256(_side) | (_unitPrice << 8) | (_maturity << 24) | (_timestamp << 88);
    }

    /**
     * @notice Unpacks order parameters from uint256
     */
    function _unpackOrder(
        uint256 _order
    )
        private
        pure
        returns (ProtocolTypes.Side side, uint256 unitPrice, uint256 maturity, uint256 timestamp)
    {
        side = ProtocolTypes.Side(uint8(_order));
        unitPrice = uint16(_order >> 8);
        maturity = uint64(_order >> 24);
        timestamp = uint64(_order >> 88);
    }

    function _unpackBlockUnitPriceHistory(
        uint80 _blockUnitPriceHistory
    ) private pure returns (uint256[] memory prices) {
        prices = new uint256[](5);

        prices[0] = uint16(_blockUnitPriceHistory);
        prices[1] = uint16(_blockUnitPriceHistory >> 16);
        prices[2] = uint16(_blockUnitPriceHistory >> 32);
        prices[3] = uint16(_blockUnitPriceHistory >> 48);
        prices[4] = uint16(_blockUnitPriceHistory >> 64);
    }
}

contracts/protocol/libraries/OrderStatisticsTreeLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

// libraries
import {Constants} from "../libraries/Constants.sol";
// types
import {RoundingUint256} from "./math/RoundingUint256.sol";

struct RemainingOrder {
    uint48 orderId;
    address maker;
    uint256 amount;
    uint256 unitPrice;
}

struct PartiallyRemovedOrder {
    uint48 orderId;
    address maker;
    uint256 amount;
    uint256 futureValue;
}

/**
 * @notice OrderStatisticsTreeLib is a Red-Black Tree binary search library
 * based on the following library that is extended to manage order data.
 *
 * https://github.com/rob-Hitchens/OrderStatisticsTree
 *
 */
library OrderStatisticsTreeLib {
    using RoundingUint256 for uint256;
    uint256 private constant EMPTY = 0;
    uint16 private constant ORDER_CHUNK_SIZE = 100;
    uint32 private constant MAX_ACTIVE_CHUNKS_PER_PRICE = 1000;

    struct Node {
        uint256 parent;
        uint256 left;
        uint256 right;
        bool red;
        uint48 head;
        uint48 tail;
        uint256 orderCounter;
        uint256 orderTotalAmount;
        mapping(uint48 orderId => OrderItem) orders;
    }

    struct OrderChunk {
        uint256 totalAmount;
        uint48 firstOrderId;
        uint32 prevChunkId;
        uint32 nextChunkId;
        uint16 orderCount;
    }

    struct PriceChunkMetadata {
        uint32 firstChunkId;
        uint32 lastChunkId;
        uint32 lastAllocatedChunkId;
        uint48 explicitMappingStartOrderId;
        uint32 activeChunkCount;
        mapping(uint32 chunkId => OrderChunk chunk) chunks;
        mapping(uint48 orderId => uint32 chunkId) orderChunkIds;
    }

    struct Tree {
        uint256 root;
        mapping(uint256 value => Node) nodes;
        mapping(uint256 value => PriceChunkMetadata metadata) chunkMetadata;
    }

    struct OrderItem {
        uint48 orderId;
        uint48 next;
        uint48 prev;
        address maker;
        uint256 amount;
    }

    function first(Tree storage self) internal view returns (uint256 value) {
        value = self.root;
        if (value == EMPTY) return 0;
        uint256 left = self.nodes[value].left;
        while (left != EMPTY) {
            value = left;
            left = self.nodes[value].left;
        }
    }

    function last(Tree storage self) internal view returns (uint256 value) {
        value = self.root;
        if (value == EMPTY) return 0;
        uint256 right = self.nodes[value].right;
        while (right != EMPTY) {
            value = right;
            right = self.nodes[value].right;
        }
    }

    function hasOrders(Tree storage self) internal view returns (bool) {
        return self.root != EMPTY;
    }

    function next(Tree storage self, uint256 value) internal view returns (uint256 cursor) {
        require(value != EMPTY, "OSTLib: Value cannot be zero");
        Node storage node = self.nodes[value];
        uint256 right = node.right;
        if (right != EMPTY) {
            cursor = treeMinimum(self, right);
        } else {
            cursor = node.parent;
            while (cursor != EMPTY) {
                Node storage cursorNode = self.nodes[cursor];
                if (value != cursorNode.right) break;

                value = cursor;
                cursor = cursorNode.parent;
            }
        }
    }

    function prev(Tree storage self, uint256 value) internal view returns (uint256 cursor) {
        require(value != EMPTY, "OSTLib: Value cannot be zero");
        Node storage node = self.nodes[value];
        uint256 left = node.left;
        if (left != EMPTY) {
            cursor = treeMaximum(self, left);
        } else {
            cursor = node.parent;
            while (cursor != EMPTY) {
                Node storage cursorNode = self.nodes[cursor];
                if (value != cursorNode.left) break;

                value = cursor;
                cursor = cursorNode.parent;
            }
        }
    }

    function nextWithTotalAmount(
        Tree storage self,
        uint256 value
    ) internal view returns (uint256 cursor, uint256 totalAmount) {
        require(value != EMPTY, "OSTLib: Value cannot be zero");

        // Probe only the adjacent price so dense trees avoid traversal without scanning sparse gaps.
        if (value < Constants.PRICE_DIGIT) {
            cursor = value + 1;
            totalAmount = self.nodes[cursor].orderTotalAmount;
            if (totalAmount > 0) return (cursor, totalAmount);
        }

        cursor = next(self, value);
        totalAmount = self.nodes[cursor].orderTotalAmount;
    }

    function prevWithTotalAmount(
        Tree storage self,
        uint256 value
    ) internal view returns (uint256 cursor, uint256 totalAmount) {
        require(value != EMPTY, "OSTLib: Value cannot be zero");

        // Probe only the adjacent price so dense trees avoid traversal without scanning sparse gaps.
        if (value > 1) {
            cursor = value - 1;
            totalAmount = self.nodes[cursor].orderTotalAmount;
            if (totalAmount > 0) return (cursor, totalAmount);
        }

        cursor = prev(self, value);
        totalAmount = self.nodes[cursor].orderTotalAmount;
    }

    function search(
        Tree storage self,
        uint256 value
    ) internal view returns (bool valueExists, uint256 parent) {
        uint256 cursor = self.root;

        while (cursor != EMPTY) {
            if (value < cursor) {
                parent = cursor;
                cursor = self.nodes[cursor].left;
            } else if (value > cursor) {
                parent = cursor;
                cursor = self.nodes[cursor].right;
            }

            if (value == cursor) {
                break;
            }
        }

        valueExists = cursor != EMPTY;
    }

    function exists(Tree storage self, uint256 value) internal view returns (bool) {
        if (value == self.root) return true;

        uint256 cursor = value;
        while (self.nodes[cursor].parent != EMPTY) {
            uint256 parent = self.nodes[cursor].parent;
            Node storage gn = self.nodes[parent];
            if (gn.left != cursor && gn.right != cursor) {
                return false;
            }
            if (parent == self.root) {
                return true;
            }
            cursor = parent;
        }
        return false;
    }

    function isActiveOrderId(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal view returns (bool) {
        return orderIdExists(self, value, orderId) && exists(self, value);
    }

    function getNode(
        Tree storage self,
        uint256 value
    ) internal view returns (uint256, uint256, uint256, bool, uint256, uint256, uint256, uint256) {
        require(exists(self, value), "OSTLib: Value does not exist");
        Node storage gn = self.nodes[value];
        return (
            gn.parent,
            gn.left,
            gn.right,
            gn.red,
            gn.head,
            gn.tail,
            gn.orderCounter,
            gn.orderTotalAmount
        );
    }

    function getNodeCount(Tree storage self, uint256 value) internal view returns (uint256) {
        Node storage gn = self.nodes[value];
        return gn.orderCounter;
    }

    function getNodeTotalAmount(
        Tree storage self,
        uint256 value
    ) internal view returns (uint256 totalAmount) {
        return self.nodes[value].orderTotalAmount;
    }

    function getNodeOrderIds(
        Tree storage self,
        uint256 value
    ) internal view returns (uint48[] memory orderIds) {
        Node storage gn = self.nodes[value];
        OrderItem memory order = gn.orders[gn.head];
        orderIds = new uint48[](gn.orderCounter);

        for (uint256 i; i < gn.orderCounter; i++) {
            orderIds[i] = order.orderId;
            order = gn.orders[order.next];
        }
    }

    function count(Tree storage self) internal view returns (uint256) {
        return getNodeCount(self, self.root);
    }

    function insert(Tree storage self, uint256 value) internal {
        require(value != EMPTY, "OSTLib: Value cannot be zero");
        uint256 cursor;
        uint256 probe = self.root;
        while (probe != EMPTY) {
            cursor = probe;
            if (value < probe) {
                probe = self.nodes[probe].left;
            } else if (value > probe) {
                probe = self.nodes[probe].right;
            } else if (value == probe) {
                return;
            }
        }

        Node storage nValue = self.nodes[value];
        // Update order info as a new one if there is already an old node
        if (self.root == EMPTY || nValue.orderCounter != 0) {
            nValue.orderCounter = 0;
            nValue.orderTotalAmount = 0;
            _setHead(self, value, 0);
            _setTail(self, value, 0);

            // Reset scalar metadata for a reused price level. Nested mappings remain in storage.
            delete self.chunkMetadata[value];
        }
        nValue.parent = cursor;
        nValue.left = EMPTY;
        nValue.right = EMPTY;
        nValue.red = true;

        if (cursor == EMPTY) {
            self.root = value;
        } else if (value < cursor) {
            self.nodes[cursor].left = value;
        } else {
            self.nodes[cursor].right = value;
        }
        insertFixup(self, value);
    }

    function remove(Tree storage self, uint256 value) internal {
        require(value != EMPTY, "OSTLib: Value cannot be zero");
        Node storage nValue = self.nodes[value];
        uint256 probe;
        uint256 cursor;
        if (nValue.orderCounter == 0) {
            if (self.nodes[value].left == EMPTY || self.nodes[value].right == EMPTY) {
                cursor = value;
            } else {
                cursor = self.nodes[value].right;
                while (self.nodes[cursor].left != EMPTY) {
                    cursor = self.nodes[cursor].left;
                }
            }

            if (self.nodes[cursor].left != EMPTY) {
                probe = self.nodes[cursor].left;
            } else {
                probe = self.nodes[cursor].right;
            }

            uint256 cursorParent = self.nodes[cursor].parent;
            bool probeIsLeftChild = cursorParent != EMPTY &&
                cursor == self.nodes[cursorParent].left;

            if (probe != EMPTY) {
                self.nodes[probe].parent = cursorParent;
            }

            if (cursorParent != EMPTY) {
                if (probeIsLeftChild) {
                    self.nodes[cursorParent].left = probe;
                } else {
                    self.nodes[cursorParent].right = probe;
                }
            } else {
                self.root = probe;
            }

            bool doFixup = !self.nodes[cursor].red;
            uint256 probeParent = cursorParent;

            if (cursor != value) {
                replaceParent(self, cursor, value);

                uint256 valueLeft = self.nodes[value].left;
                self.nodes[cursor].left = valueLeft;
                if (valueLeft != EMPTY) {
                    self.nodes[valueLeft].parent = cursor;
                }

                uint256 valueRight = self.nodes[value].right;
                self.nodes[cursor].right = valueRight;
                if (valueRight != EMPTY) {
                    self.nodes[valueRight].parent = cursor;
                }

                self.nodes[cursor].red = self.nodes[value].red;

                if (probeParent == value) {
                    probeParent = cursor;
                }

                (cursor, value) = (value, cursor);
            }

            if (doFixup) {
                removeFixup(self, probe, probeParent, probeIsLeftChild);
            }
            delete self.nodes[cursor];
        }
    }

    function treeMinimum(Tree storage self, uint256 value) private view returns (uint256) {
        uint256 left = self.nodes[value].left;
        while (left != EMPTY) {
            value = left;
            left = self.nodes[value].left;
        }
        return value;
    }

    function treeMaximum(Tree storage self, uint256 value) private view returns (uint256) {
        uint256 right = self.nodes[value].right;
        while (right != EMPTY) {
            value = right;
            right = self.nodes[value].right;
        }
        return value;
    }

    function rotateLeft(Tree storage self, uint256 value) private {
        uint256 cursor = self.nodes[value].right;
        uint256 parent = self.nodes[value].parent;
        uint256 cursorLeft = self.nodes[cursor].left;
        self.nodes[value].right = cursorLeft;
        if (cursorLeft != EMPTY) {
            self.nodes[cursorLeft].parent = value;
        }
        self.nodes[cursor].parent = parent;
        if (parent == EMPTY) {
            self.root = cursor;
        } else if (value == self.nodes[parent].left) {
            self.nodes[parent].left = cursor;
        } else {
            self.nodes[parent].right = cursor;
        }
        self.nodes[cursor].left = value;
        self.nodes[value].parent = cursor;
    }

    function rotateRight(Tree storage self, uint256 value) private {
        uint256 cursor = self.nodes[value].left;
        uint256 parent = self.nodes[value].parent;
        uint256 cursorRight = self.nodes[cursor].right;
        self.nodes[value].left = cursorRight;
        if (cursorRight != EMPTY) {
            self.nodes[cursorRight].parent = value;
        }
        self.nodes[cursor].parent = parent;
        if (parent == EMPTY) {
            self.root = cursor;
        } else if (value == self.nodes[parent].right) {
            self.nodes[parent].right = cursor;
        } else {
            self.nodes[parent].left = cursor;
        }
        self.nodes[cursor].right = value;
        self.nodes[value].parent = cursor;
    }

    function insertFixup(Tree storage self, uint256 value) private {
        uint256 cursor;

        while (value != self.root && _isRed(self, self.nodes[value].parent)) {
            uint256 valueParent = self.nodes[value].parent;
            uint256 valueGrandParent = self.nodes[valueParent].parent;

            if (valueParent == self.nodes[valueGrandParent].left) {
                cursor = self.nodes[valueGrandParent].right;
                if (_isRed(self, cursor)) {
                    self.nodes[valueParent].red = false;
                    self.nodes[cursor].red = false;
                    self.nodes[valueGrandParent].red = true;
                    value = valueGrandParent;
                } else {
                    if (value == self.nodes[valueParent].right) {
                        value = valueParent;
                        rotateLeft(self, value);
                    }
                    valueParent = self.nodes[value].parent;
                    valueGrandParent = self.nodes[valueParent].parent;
                    self.nodes[valueParent].red = false;
                    self.nodes[valueGrandParent].red = true;
                    rotateRight(self, valueGrandParent);
                }
            } else {
                cursor = self.nodes[valueGrandParent].left;
                if (_isRed(self, cursor)) {
                    self.nodes[valueParent].red = false;
                    self.nodes[cursor].red = false;
                    self.nodes[valueGrandParent].red = true;
                    value = valueGrandParent;
                } else {
                    if (value == self.nodes[valueParent].left) {
                        value = valueParent;
                        rotateRight(self, value);
                    }
                    valueParent = self.nodes[value].parent;
                    valueGrandParent = self.nodes[valueParent].parent;
                    self.nodes[valueParent].red = false;
                    self.nodes[valueGrandParent].red = true;
                    rotateLeft(self, valueGrandParent);
                }
            }
        }

        self.nodes[self.root].red = false;
    }

    function replaceParent(Tree storage self, uint256 a, uint256 b) private {
        uint256 bParent = self.nodes[b].parent;
        self.nodes[a].parent = bParent;
        if (bParent == EMPTY) {
            self.root = a;
        } else {
            if (b == self.nodes[bParent].left) {
                self.nodes[bParent].left = a;
            } else {
                self.nodes[bParent].right = a;
            }
        }
    }

    function removeFixup(
        Tree storage self,
        uint256 value,
        uint256 parent,
        bool valueIsLeftChild
    ) private {
        uint256 cursor;
        while (value != self.root && !_isRed(self, value)) {
            uint256 valueParent = value == EMPTY ? parent : self.nodes[value].parent;
            if (valueParent == EMPTY) {
                break;
            }

            bool isLeftChild = value == EMPTY
                ? valueIsLeftChild
                : value == self.nodes[valueParent].left;

            if (isLeftChild) {
                cursor = self.nodes[valueParent].right;
                if (_isRed(self, cursor)) {
                    self.nodes[cursor].red = false;
                    self.nodes[valueParent].red = true;
                    rotateLeft(self, valueParent);
                    cursor = self.nodes[valueParent].right;
                }

                if (!_isRed(self, _leftOf(self, cursor)) && !_isRed(self, _rightOf(self, cursor))) {
                    _setRedIfNotEmpty(self, cursor);
                    value = valueParent;
                    parent = self.nodes[value].parent;
                    valueIsLeftChild = parent != EMPTY && value == self.nodes[parent].left;
                } else {
                    if (!_isRed(self, _rightOf(self, cursor))) {
                        _setBlackIfNotEmpty(self, _leftOf(self, cursor));
                        _setRedIfNotEmpty(self, cursor);
                        rotateRight(self, cursor);
                        cursor = self.nodes[valueParent].right;
                    }
                    self.nodes[cursor].red = self.nodes[valueParent].red;
                    self.nodes[valueParent].red = false;
                    _setBlackIfNotEmpty(self, _rightOf(self, cursor));
                    rotateLeft(self, valueParent);
                    value = self.root;
                    parent = EMPTY;
                }
            } else {
                cursor = self.nodes[valueParent].left;
                if (_isRed(self, cursor)) {
                    self.nodes[cursor].red = false;
                    self.nodes[valueParent].red = true;
                    rotateRight(self, valueParent);
                    cursor = self.nodes[valueParent].left;
                }

                if (!_isRed(self, _rightOf(self, cursor)) && !_isRed(self, _leftOf(self, cursor))) {
                    _setRedIfNotEmpty(self, cursor);
                    value = valueParent;
                    parent = self.nodes[value].parent;
                    valueIsLeftChild = parent != EMPTY && value == self.nodes[parent].left;
                } else {
                    if (!_isRed(self, _leftOf(self, cursor))) {
                        _setBlackIfNotEmpty(self, _rightOf(self, cursor));
                        _setRedIfNotEmpty(self, cursor);
                        rotateLeft(self, cursor);
                        cursor = self.nodes[valueParent].left;
                    }
                    self.nodes[cursor].red = self.nodes[valueParent].red;
                    self.nodes[valueParent].red = false;
                    _setBlackIfNotEmpty(self, _leftOf(self, cursor));
                    rotateRight(self, valueParent);
                    value = self.root;
                    parent = EMPTY;
                }
            }
        }

        _setBlackIfNotEmpty(self, value);
    }

    function _leftOf(Tree storage self, uint256 value) private view returns (uint256) {
        return value == EMPTY ? EMPTY : self.nodes[value].left;
    }

    function _rightOf(Tree storage self, uint256 value) private view returns (uint256) {
        return value == EMPTY ? EMPTY : self.nodes[value].right;
    }

    function _isRed(Tree storage self, uint256 value) private view returns (bool) {
        return value != EMPTY && self.nodes[value].red;
    }

    function _setRedIfNotEmpty(Tree storage self, uint256 value) private {
        if (value != EMPTY) {
            self.nodes[value].red = true;
        }
    }

    function _setBlackIfNotEmpty(Tree storage self, uint256 value) private {
        if (value != EMPTY) {
            self.nodes[value].red = false;
        }
    }

    function calculateDroppedAmountFromLeft(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue
    )
        internal
        view
        returns (uint256 droppedValue, uint256 droppedAmount, uint256 droppedAmountInFV)
    {
        (droppedValue, , , droppedAmount, droppedAmountInFV, , ) = _calculateDroppedAmountFromLeft(
            self,
            amount,
            amountInFV,
            limitValue,
            first(self)
        );
    }

    function calculateDroppedAmountFromRight(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue
    )
        internal
        view
        returns (uint256 droppedValue, uint256 droppedAmount, uint256 droppedAmountInFV)
    {
        (droppedValue, , , droppedAmount, droppedAmountInFV, , ) = _calculateDroppedAmountFromRight(
            self,
            amount,
            amountInFV,
            limitValue,
            last(self)
        );
    }

    struct DropVars {
        uint256 cursor;
        uint256 cursorNodeAmount;
        uint256 exceededAmount;
        uint256 exceededAmountInFV;
        uint256 totalNodeAmount;
        uint256 fixupParent;
        uint256 removedChild;
        uint256 relinkFixupStart;
        uint256 relinkFixupStopParent;
    }

    function dropLeft(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue
    )
        internal
        returns (
            uint256 droppedValue,
            uint256 droppedAmount,
            uint256 droppedAmountInFV,
            uint256 remainingAmount,
            PartiallyRemovedOrder memory partiallyRemovedOrder
        )
    {
        DropVars memory vars;
        vars.cursor = first(self);

        require(vars.cursor <= limitValue || limitValue == 0, "OSTLib: Insufficient limit value");

        (
            droppedValue,
            vars.cursor,
            vars.cursorNodeAmount,
            droppedAmount,
            droppedAmountInFV,
            vars.exceededAmount,
            vars.exceededAmountInFV
        ) = _calculateDroppedAmountFromLeft(self, amount, amountInFV, limitValue, vars.cursor);

        vars.totalNodeAmount = droppedAmount + vars.exceededAmount;
        vars.fixupParent = EMPTY;

        if (vars.totalNodeAmount > 0) {
            if (vars.exceededAmount > 0) {
                vars.cursor = droppedValue;
                // Update order ids in the node.
                partiallyRemovedOrder = removeOrders(
                    self,
                    vars.cursor,
                    vars.cursorNodeAmount - vars.exceededAmount
                );
            } else if (vars.exceededAmountInFV > 0) {
                vars.cursor = droppedValue;
                // Update order ids in the node.
                partiallyRemovedOrder = removeOrders(
                    self,
                    vars.cursor,
                    vars.cursorNodeAmount -
                        _calculatePresentValue(vars.cursor, vars.exceededAmountInFV)
                );
            }

            vars.removedChild = self.nodes[vars.cursor].left;
            self.nodes[vars.cursor].left = EMPTY;
            if (_blackHeight(self, vars.removedChild) > _blackHeight(self, EMPTY)) {
                vars.fixupParent = vars.cursor;
            }

            uint256 parent = self.nodes[vars.cursor].parent;

            if (vars.cursor != EMPTY) {
                while (parent != EMPTY) {
                    if (parent > vars.cursor) {
                        // Relink the nodes
                        if (self.nodes[vars.cursor].parent != parent) {
                            uint256 oldLeft = self.nodes[parent].left;
                            uint256 newLeft = vars.cursor;

                            self.nodes[vars.cursor].parent = parent;
                            self.nodes[parent].left = newLeft;

                            if (_blackHeight(self, oldLeft) > _blackHeight(self, newLeft)) {
                                if (vars.relinkFixupStart == EMPTY) {
                                    vars.relinkFixupStart = parent;
                                }
                                vars.relinkFixupStopParent = self.nodes[parent].parent;
                            }
                        }

                        vars.cursor = parent;
                    }

                    parent = self.nodes[parent].parent;
                }
            }
        }

        if (amount > vars.totalNodeAmount) {
            remainingAmount = amount - vars.totalNodeAmount;
        }

        uint256 lastNode = last(self);

        if (lastNode == droppedValue && self.nodes[lastNode].orderTotalAmount == 0) {
            // The case that all node is dropped.
            self.root = EMPTY;
        } else if (
            droppedValue > self.root ||
            (droppedValue == self.root && droppedAmount == vars.totalNodeAmount)
        ) {
            // The case that the root node is dropped
            self.root = vars.cursor;
            self.nodes[vars.cursor].parent = 0;
        }

        if (self.root != EMPTY) {
            _rebalanceBlackHeights(
                self,
                vars.fixupParent != EMPTY ? vars.fixupParent : vars.relinkFixupStart,
                vars.relinkFixupStopParent
            );
        }
    }

    function dropRight(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue
    )
        internal
        returns (
            uint256 droppedValue,
            uint256 droppedAmount,
            uint256 droppedAmountInFV,
            uint256 remainingAmount,
            PartiallyRemovedOrder memory partiallyRemovedOrder
        )
    {
        DropVars memory vars;
        vars.cursor = last(self);

        require(vars.cursor >= limitValue || limitValue == 0, "OSTLib: Insufficient limit value");

        (
            droppedValue,
            vars.cursor,
            vars.cursorNodeAmount,
            droppedAmount,
            droppedAmountInFV,
            vars.exceededAmount,
            vars.exceededAmountInFV
        ) = _calculateDroppedAmountFromRight(self, amount, amountInFV, limitValue, vars.cursor);

        vars.totalNodeAmount = droppedAmount + vars.exceededAmount;
        vars.fixupParent = EMPTY;

        if (vars.totalNodeAmount > 0) {
            if (vars.exceededAmount > 0) {
                vars.cursor = droppedValue;
                // Update order ids in the node.
                partiallyRemovedOrder = removeOrders(
                    self,
                    vars.cursor,
                    vars.cursorNodeAmount - vars.exceededAmount
                );
            } else if (vars.exceededAmountInFV > 0) {
                vars.cursor = droppedValue;
                // Update order ids in the node.
                partiallyRemovedOrder = removeOrders(
                    self,
                    vars.cursor,
                    vars.cursorNodeAmount -
                        _calculatePresentValue(vars.cursor, vars.exceededAmountInFV)
                );
            }

            vars.removedChild = self.nodes[vars.cursor].right;
            self.nodes[vars.cursor].right = EMPTY;
            if (_blackHeight(self, vars.removedChild) > _blackHeight(self, EMPTY)) {
                vars.fixupParent = vars.cursor;
            }

            uint256 parent = self.nodes[vars.cursor].parent;

            if (vars.cursor != EMPTY) {
                while (parent != EMPTY) {
                    if (parent < vars.cursor) {
                        // Relink the nodes
                        if (self.nodes[vars.cursor].parent != parent) {
                            uint256 oldRight = self.nodes[parent].right;
                            uint256 newRight = vars.cursor;

                            self.nodes[vars.cursor].parent = parent;
                            self.nodes[parent].right = newRight;

                            if (_blackHeight(self, oldRight) > _blackHeight(self, newRight)) {
                                if (vars.relinkFixupStart == EMPTY) {
                                    vars.relinkFixupStart = parent;
                                }
                                vars.relinkFixupStopParent = self.nodes[parent].parent;
                            }
                        }

                        vars.cursor = parent;
                    }

                    parent = self.nodes[parent].parent;
                }
            }
        }

        if (amount > vars.totalNodeAmount) {
            remainingAmount = amount - vars.totalNodeAmount;
        }

        uint256 firstNode = first(self);

        if (firstNode == droppedValue && self.nodes[firstNode].orderTotalAmount == 0) {
            // The case that all node is dropped.
            self.root = EMPTY;
        } else if (
            droppedValue < self.root ||
            (droppedValue == self.root && droppedAmount == vars.totalNodeAmount)
        ) {
            // The case that the root node is dropped
            self.root = vars.cursor;
            self.nodes[vars.cursor].parent = 0;
        }

        if (self.root != EMPTY) {
            _rebalanceBlackHeights(
                self,
                vars.fixupParent != EMPTY ? vars.fixupParent : vars.relinkFixupStart,
                vars.relinkFixupStopParent
            );
        }
    }

    function _hasBlackDeficitFromLeft(
        Tree storage self,
        uint256 target
    ) private view returns (bool) {
        return
            target != EMPTY &&
            _blackHeight(self, _leftOf(self, target)) < _blackHeight(self, _rightOf(self, target));
    }

    function _hasBlackDeficitFromRight(
        Tree storage self,
        uint256 target
    ) private view returns (bool) {
        return
            target != EMPTY &&
            _blackHeight(self, _rightOf(self, target)) < _blackHeight(self, _leftOf(self, target));
    }

    function _rebalanceBlackHeights(
        Tree storage self,
        uint256 target,
        uint256 stopParent
    ) private returns (uint256 processedUntil) {
        bool reachedStopParent;

        while (target != EMPTY) {
            processedUntil = target;

            if (stopParent != EMPTY && target == stopParent) {
                reachedStopParent = true;
            }

            (uint256 leftBlackHeight, uint256 rightBlackHeight) = _childBlackHeights(self, target);
            bool fixedAtTarget;
            bool targetChangedByFix;

            while (leftBlackHeight != rightBlackHeight) {
                // The two child subtrees have different black heights. Fix the side that has
                // the black deficit. dropLeft/dropRight can remove a whole subtree, so the
                // deficit may be larger than one black level; after one fix, the same node
                // can still be locally imbalanced and must be rechecked before moving upward.
                fixedAtTarget = true;
                (target, leftBlackHeight, rightBlackHeight, targetChangedByFix) = _fixBlackDeficit(
                    self,
                    target,
                    leftBlackHeight,
                    rightBlackHeight
                );

                if (targetChangedByFix) {
                    break;
                }
            }

            if (targetChangedByFix) {
                continue;
            }

            if (leftBlackHeight == rightBlackHeight) {
                if (fixedAtTarget) {
                    // This target was just rebalanced. Even if its local black heights now match,
                    // the fix may have changed this subtree's effective black height, so continue
                    // upward and let the parent verify whether the change propagated.
                    target = self.nodes[target].parent;
                } else if (reachedStopParent) {
                    // We reached the first node above the relink-affected path, and no fix was
                    // needed at this node. Its subtree black height is unchanged, so no further
                    // ancestor can be affected.
                    target = EMPTY;
                } else {
                    // This node is locally balanced, but it is still within the relink-affected
                    // path. Continue upward until the stop parent is reached.
                    target = self.nodes[target].parent;
                }
            }
        }

        _setBlackIfNotEmpty(self, self.root);
    }

    function _fixBlackDeficit(
        Tree storage self,
        uint256 target,
        uint256 leftBlackHeight,
        uint256 rightBlackHeight
    )
        private
        returns (
            uint256 nextTarget,
            uint256 newLeftBlackHeight,
            uint256 newRightBlackHeight,
            bool targetChangedByFix
        )
    {
        uint256 deficitBefore = _absDiff(leftBlackHeight, rightBlackHeight);

        if (leftBlackHeight < rightBlackHeight) {
            // The left subtree is missing black height after a drop/relink from the left.
            nextTarget = _fixBlackDeficitFromLeft(self, target);
        } else {
            // The right subtree is missing black height after a drop/relink from the right.
            nextTarget = _fixBlackDeficitFromRight(self, target);
        }

        (newLeftBlackHeight, newRightBlackHeight) = _childBlackHeights(self, target);

        if (newLeftBlackHeight != newRightBlackHeight) {
            require(
                _absDiff(newLeftBlackHeight, newRightBlackHeight) < deficitBefore,
                "OSTLib: Rebalance did not converge"
            );

            // The original node still has a local black-height mismatch. Reprocess it
            // using the newly calculated black heights instead of recalculating them at
            // the top of the outer loop.
            return (target, newLeftBlackHeight, newRightBlackHeight, false);
        }

        if (nextTarget != target) {
            // The original node is locally balanced and the fix propagated the remaining
            // effect to another node, usually the parent. Restart the outer loop because
            // the cached black heights belong to the original target, not to nextTarget.
            return (nextTarget, 0, 0, true);
        }

        return (target, newLeftBlackHeight, newRightBlackHeight, false);
    }

    function _childBlackHeights(
        Tree storage self,
        uint256 target
    ) private view returns (uint256 leftBlackHeight, uint256 rightBlackHeight) {
        leftBlackHeight = _blackHeight(self, _leftOf(self, target));
        rightBlackHeight = _blackHeight(self, _rightOf(self, target));
    }

    function _absDiff(uint256 a, uint256 b) private pure returns (uint256) {
        return a > b ? a - b : b - a;
    }

    function _blackHeight(Tree storage self, uint256 value) private view returns (uint256 height) {
        while (value != EMPTY) {
            if (!_isRed(self, value)) {
                height++;
            }

            uint256 left = self.nodes[value].left;
            if (left != EMPTY) {
                value = left;
            } else {
                value = self.nodes[value].right;
            }
        }

        // EMPTY leaf is treated as black.
        return height + 1;
    }

    function _fixBlackDeficitFromLeft(
        Tree storage self,
        uint256 target
    ) private returns (uint256 nextTarget) {
        if (target == EMPTY) {
            return EMPTY;
        }

        uint256 sibling = _rightOf(self, target);

        if (_isRed(self, sibling)) {
            self.nodes[sibling].red = false;
            self.nodes[target].red = true;
            rotateLeft(self, target);
            sibling = _rightOf(self, target);
        }

        uint256 siblingLeft = _leftOf(self, sibling);
        uint256 siblingRight = _rightOf(self, sibling);

        if (!_isRed(self, siblingLeft) && !_isRed(self, siblingRight)) {
            _setRedIfNotEmpty(self, sibling);

            if (_isRed(self, target)) {
                self.nodes[target].red = false;
                return target;
            }

            uint256 parent = self.nodes[target].parent;
            return parent == EMPTY ? target : parent;
        }

        if (!_isRed(self, siblingRight)) {
            _setBlackIfNotEmpty(self, siblingLeft);
            _setRedIfNotEmpty(self, sibling);
            rotateRight(self, sibling);
            sibling = _rightOf(self, target);
        }

        self.nodes[sibling].red = _isRed(self, target);
        self.nodes[target].red = false;
        _setBlackIfNotEmpty(self, _rightOf(self, sibling));

        rotateLeft(self, target);
        return target;
    }

    function _fixBlackDeficitFromRight(
        Tree storage self,
        uint256 target
    ) private returns (uint256 nextTarget) {
        if (target == EMPTY) {
            return EMPTY;
        }

        uint256 sibling = _leftOf(self, target);

        if (_isRed(self, sibling)) {
            self.nodes[sibling].red = false;
            self.nodes[target].red = true;
            rotateRight(self, target);
            sibling = _leftOf(self, target);
        }

        uint256 siblingLeft = _leftOf(self, sibling);
        uint256 siblingRight = _rightOf(self, sibling);

        if (!_isRed(self, siblingLeft) && !_isRed(self, siblingRight)) {
            _setRedIfNotEmpty(self, sibling);

            if (_isRed(self, target)) {
                self.nodes[target].red = false;
                return target;
            }

            uint256 parent = self.nodes[target].parent;
            return parent == EMPTY ? target : parent;
        }

        if (!_isRed(self, siblingLeft)) {
            _setBlackIfNotEmpty(self, siblingRight);
            _setRedIfNotEmpty(self, sibling);
            rotateLeft(self, sibling);
            sibling = _leftOf(self, target);
        }

        self.nodes[sibling].red = _isRed(self, target);
        self.nodes[target].red = false;
        _setBlackIfNotEmpty(self, _leftOf(self, sibling));

        rotateRight(self, target);
        return target;
    }

    function getFutureValue(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal view returns (uint256) {
        return _calculateFutureValue(value, self.nodes[value].orders[orderId].amount);
    }

    // Double linked list functions
    /**
     * @dev Retrieves the Object denoted by `_id`.
     */
    function getOrderById(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal view returns (address maker, uint256 amount) {
        Node storage gn = self.nodes[value];
        OrderItem memory order = gn.orders[orderId];

        maker = order.maker;
        amount = order.amount;
    }

    /**
     * @dev Return boolean if value, amount and orderId exist in doubly linked list
     * Order IDs must increase monotonically because prefix removals leave old orders in storage
     * and use the current head order ID to distinguish them from active orders.
     */
    function orderIdExists(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal view returns (bool) {
        Node storage gn = self.nodes[value];

        return gn.head != 0 && orderId >= gn.head && gn.orders[orderId].orderId == orderId;
    }

    function insertOrder(
        Tree storage self,
        uint256 value,
        uint48 orderId,
        address user,
        uint256 amount
    ) internal {
        require(amount > 0, "OSTLib: Insufficient amount");
        require(value <= Constants.PRICE_DIGIT, "OSTLib: Value too high");

        insert(self, value);

        // TODO: Remove this check after the migration is complete.
        // This is to ensure that the chunk metadata is created for existing orders.
        _ensureChunkMetadata(self, value);

        addTail(self, value, orderId, user, amount);
        _addOrderToChunk(self.chunkMetadata[value], orderId, amount);
    }

    function removeOrder(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal returns (uint256 amount) {
        // TODO: Remove this check after the migration is complete.
        // This is to ensure that the chunk metadata is created for existing orders.
        _ensureChunkMetadata(self, value);

        Node storage gn = self.nodes[value];
        OrderItem storage order = gn.orders[orderId];
        _removeOrderFromChunk(self.chunkMetadata[value], orderId, order.amount, order.next);

        amount = _removeOrder(self, value, orderId);
        remove(self, value);
    }

    function removeOrders(
        Tree storage self,
        uint256 value,
        uint256 amount
    ) internal returns (PartiallyRemovedOrder memory partiallyRemovedOrder) {
        Node storage gn = self.nodes[value];
        require(gn.orderTotalAmount >= amount, "OSTLib: Amount to remove is insufficient");

        // TODO: Remove this check after the migration is complete.
        // This is to ensure that the chunk metadata is created for existing orders.
        _ensureChunkMetadata(self, value);

        PriceChunkMetadata storage metadata = self.chunkMetadata[value];
        uint256 remainingAmount = amount;
        uint256 fullyRemovedCount;
        uint256 fullyRemovedAmount;
        uint48 partiallyRemovedOrderId;
        uint256 partiallyRemovedAmount;
        uint32 removedChunkCount;
        uint32 chunkId = metadata.firstChunkId;

        while (chunkId != 0 && remainingAmount > 0) {
            OrderChunk storage chunk = metadata.chunks[chunkId];
            uint32 nextChunkId = chunk.nextChunkId;

            if (chunk.totalAmount > remainingAmount) {
                break;
            }

            remainingAmount -= chunk.totalAmount;
            fullyRemovedAmount += chunk.totalAmount;
            fullyRemovedCount += chunk.orderCount;
            removedChunkCount += 1;
            chunkId = nextChunkId;
        }

        if (chunkId != 0 && remainingAmount > 0) {
            uint256 removedAmount;
            uint256 removedCount;

            (
                removedAmount,
                removedCount,
                partiallyRemovedOrderId,
                partiallyRemovedAmount,
                remainingAmount
            ) = _removeOrdersFromBoundaryChunk(gn, metadata.chunks[chunkId], remainingAmount);
            fullyRemovedAmount += removedAmount;
            fullyRemovedCount += removedCount;
        }

        require(remainingAmount == 0, "OSTLib: Insufficient chunk amount");

        if (removedChunkCount > 0) {
            _unlinkChunkPrefix(metadata, chunkId, removedChunkCount);
        }

        if (fullyRemovedCount > 0) {
            uint48 newHeadOrderId = metadata.firstChunkId == 0
                ? 0
                : metadata.chunks[metadata.firstChunkId].firstOrderId;

            if (newHeadOrderId == 0) {
                _setHead(self, value, 0);
                _setTail(self, value, 0);
            } else {
                _setHead(self, value, newHeadOrderId);
                gn.orders[newHeadOrderId].prev = 0;
            }

            gn.orderCounter -= fullyRemovedCount;
            gn.orderTotalAmount -= fullyRemovedAmount;
        }

        if (partiallyRemovedAmount > 0) {
            OrderItem storage partialOrder = gn.orders[partiallyRemovedOrderId];
            require(
                partialOrder.orderId == partiallyRemovedOrderId &&
                    partialOrder.amount > partiallyRemovedAmount,
                "OSTLib: Invalid partial removal"
            );

            partialOrder.amount -= partiallyRemovedAmount;
            gn.orderTotalAmount -= partiallyRemovedAmount;
            partiallyRemovedOrder = PartiallyRemovedOrder(
                partiallyRemovedOrderId,
                partialOrder.maker,
                partiallyRemovedAmount,
                _calculateFutureValue(value, partiallyRemovedAmount)
            );
        }
    }

    function migrateOrderChunks(Tree storage self, uint256 value) internal {
        Node storage gn = self.nodes[value];
        PriceChunkMetadata storage metadata = self.chunkMetadata[value];

        require(exists(self, value), "Value does not exist");
        require(gn.orderCounter > 0, "No orders to migrate");

        require(metadata.firstChunkId == 0, "Already migrated");
        _migrateChunkMetadata(self, value);
    }

    /**
     * @dev Insert a new OrderItem as the new Head with `_amount` in the amount field, and orderId.
     */
    function addHead(
        Tree storage self,
        uint256 _value,
        uint48 _orderId,
        address _user,
        uint256 _amount
    ) internal {
        Node storage gn = self.nodes[_value];
        uint48 orderId = _createOrder(self, _value, _orderId, _user, _amount);
        _link(self, _value, orderId, gn.head);
        _setHead(self, _value, orderId);
        if (gn.tail == 0) _setTail(self, _value, orderId);
    }

    /**
     * @dev Insert a new OrderItem as the new Tail with `_amount` in the amount field, and orderId.
     */
    function addTail(
        Tree storage self,
        uint256 _value,
        uint48 _orderId,
        address _user,
        uint256 _amount
    ) internal {
        Node storage gn = self.nodes[_value];

        if (gn.head == 0) {
            addHead(self, _value, _orderId, _user, _amount);
        } else {
            uint48 orderId = _createOrder(self, _value, _orderId, _user, _amount);
            _link(self, _value, gn.tail, orderId);
            _setTail(self, _value, orderId);
        }
    }

    function _calculateDroppedAmountFromLeft(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue,
        uint256 firstValue
    )
        private
        view
        returns (
            uint256 droppedValue,
            uint256 cursor,
            uint256 cursorNodeAmount,
            uint256 droppedAmount,
            uint256 droppedAmountInFV,
            uint256 exceededAmount,
            uint256 exceededAmountInFV
        )
    {
        cursor = firstValue;

        while (
            (droppedAmount < amount || amount == EMPTY) &&
            (droppedAmountInFV < amountInFV || amountInFV == EMPTY) &&
            cursor != EMPTY &&
            (cursor <= limitValue || limitValue == EMPTY)
        ) {
            cursorNodeAmount = self.nodes[cursor].orderTotalAmount;
            droppedValue = cursor;

            droppedAmountInFV += _calculateFutureValue(cursor, cursorNodeAmount);
            droppedAmount += cursorNodeAmount;

            if (droppedAmount > amount && amount != EMPTY) {
                exceededAmount = droppedAmount - amount;
                exceededAmountInFV = _calculateFutureValue(cursor, exceededAmount);
            } else if (droppedAmountInFV > amountInFV && amountInFV != EMPTY) {
                exceededAmountInFV = droppedAmountInFV - amountInFV;
                exceededAmount = _calculatePresentValue(cursor, exceededAmountInFV);
            }

            cursor = next(self, cursor);
        }

        if (exceededAmount > 0) {
            droppedAmount -= exceededAmount;
        }
        if (exceededAmountInFV > 0) {
            droppedAmountInFV -= exceededAmountInFV;
        }
    }

    function _calculateDroppedAmountFromRight(
        Tree storage self,
        uint256 amount,
        uint256 amountInFV,
        uint256 limitValue,
        uint256 lastValue
    )
        private
        view
        returns (
            uint256 droppedValue,
            uint256 cursor,
            uint256 cursorNodeAmount,
            uint256 droppedAmount,
            uint256 droppedAmountInFV,
            uint256 exceededAmount,
            uint256 exceededAmountInFV
        )
    {
        cursor = lastValue;

        while (
            (droppedAmount < amount || amount == EMPTY) &&
            (droppedAmountInFV < amountInFV || amountInFV == EMPTY) &&
            cursor != EMPTY &&
            (cursor >= limitValue || limitValue == EMPTY)
        ) {
            cursorNodeAmount = self.nodes[cursor].orderTotalAmount;
            droppedValue = cursor;

            droppedAmountInFV += _calculateFutureValue(cursor, cursorNodeAmount);
            droppedAmount += cursorNodeAmount;

            if (droppedAmount > amount && amount != EMPTY) {
                exceededAmount = droppedAmount - amount;
                exceededAmountInFV = _calculateFutureValue(cursor, exceededAmount);
            } else if (droppedAmountInFV > amountInFV && amountInFV != EMPTY) {
                exceededAmountInFV = droppedAmountInFV - amountInFV;
                exceededAmount = _calculatePresentValue(cursor, exceededAmountInFV);
            }

            cursor = prev(self, cursor);
        }

        if (exceededAmount > 0) {
            droppedAmount -= exceededAmount;
        }
        if (exceededAmountInFV > 0) {
            droppedAmountInFV -= exceededAmountInFV;
        }
    }

    /**
     * @dev Internal function to create an unlinked Order.
     */
    function _createOrder(
        Tree storage self,
        uint256 value,
        uint48 orderId,
        address user,
        uint256 amount
    ) internal returns (uint48) {
        Node storage gn = self.nodes[value];
        require(gn.orders[orderId].maker == address(0), "OSTLib: Order id already exists");

        gn.orderCounter += 1;
        gn.orderTotalAmount += amount;
        OrderItem memory order = OrderItem(orderId, 0, 0, user, amount);
        gn.orders[orderId] = order;
        return order.orderId;
    }

    /**
     * @dev Remove the OrderItem denoted by `_id` from the list.
     */
    function _removeOrder(
        Tree storage self,
        uint256 value,
        uint48 orderId
    ) internal returns (uint256 amount) {
        require(isActiveOrderId(self, value, orderId), "OSTLib: Order does not exist");
        Node storage gn = self.nodes[value];

        OrderItem memory order = gn.orders[orderId];
        amount = order.amount;

        if (gn.head == orderId && gn.tail == orderId) {
            _setHead(self, value, 0);
            _setTail(self, value, 0);
        } else if (gn.head == orderId) {
            _setHead(self, value, order.next);
            gn.orders[order.next].prev = 0;
        } else if (gn.tail == orderId) {
            _setTail(self, value, order.prev);
            gn.orders[order.prev].next = 0;
        } else {
            _link(self, value, order.prev, order.next);
        }
        delete gn.orders[order.orderId];
        gn.orderCounter -= 1;
        gn.orderTotalAmount -= order.amount;
    }

    /**
     * @dev Internal function to update the Head pointer.
     */
    function _setHead(Tree storage self, uint256 value, uint48 orderId) internal {
        Node storage gn = self.nodes[value];

        gn.head = orderId;
    }

    /**
     * @dev Internal function to update the Tail pointer.
     */
    function _setTail(Tree storage self, uint256 value, uint48 orderId) internal {
        Node storage gn = self.nodes[value];

        gn.tail = orderId;
    }

    /**
     * @dev Internal function to link an Object to another.
     */
    function _link(Tree storage self, uint256 value, uint48 prevId, uint48 nextId) internal {
        Node storage gn = self.nodes[value];

        gn.orders[prevId].next = nextId;
        gn.orders[nextId].prev = prevId;
    }

    function _ensureChunkMetadata(Tree storage self, uint256 value) private {
        PriceChunkMetadata storage metadata = self.chunkMetadata[value];

        if (self.nodes[value].orderCounter > 0 && metadata.firstChunkId == 0) {
            _migrateChunkMetadata(self, value);
        }
    }

    function _migrateChunkMetadata(Tree storage self, uint256 value) private {
        Node storage gn = self.nodes[value];
        PriceChunkMetadata storage metadata = self.chunkMetadata[value];

        uint48 orderId = gn.head;
        while (orderId != 0) {
            OrderItem storage order = gn.orders[orderId];
            _addOrderToChunk(metadata, orderId, order.amount);
            orderId = order.next;
        }
    }

    function _addOrderToChunk(
        PriceChunkMetadata storage metadata,
        uint48 orderId,
        uint256 amount
    ) private {
        uint32 chunkId = metadata.lastChunkId;

        if (chunkId == 0 || metadata.chunks[chunkId].orderCount == ORDER_CHUNK_SIZE) {
            require(
                metadata.activeChunkCount < MAX_ACTIVE_CHUNKS_PER_PRICE,
                "OSTLib: Too many orders"
            );

            uint32 newChunkId = metadata.lastAllocatedChunkId + 1;
            delete metadata.chunks[newChunkId];

            OrderChunk storage newChunk = metadata.chunks[newChunkId];
            newChunk.prevChunkId = metadata.lastChunkId;

            bool wasSingleChunk = metadata.firstChunkId == metadata.lastChunkId &&
                metadata.lastChunkId != 0;

            if (metadata.lastChunkId != 0) {
                metadata.chunks[metadata.lastChunkId].nextChunkId = newChunkId;
            } else {
                metadata.firstChunkId = newChunkId;
            }

            metadata.lastChunkId = newChunkId;
            metadata.lastAllocatedChunkId = newChunkId;
            metadata.activeChunkCount += 1;
            chunkId = newChunkId;

            if (wasSingleChunk) {
                metadata.explicitMappingStartOrderId = orderId;
            }
        }

        OrderChunk storage chunk = metadata.chunks[chunkId];
        if (chunk.orderCount == 0) {
            chunk.firstOrderId = orderId;
        }
        chunk.totalAmount += amount;
        chunk.orderCount += 1;

        if (metadata.firstChunkId != metadata.lastChunkId) {
            metadata.orderChunkIds[orderId] = chunkId;
        }
    }

    /**
     * @dev Orders created before explicitMappingStartOrderId belong to the first chunk.
     * This lookup relies on order IDs increasing monotonically.
     */
    function _getActiveOrderChunkId(
        PriceChunkMetadata storage metadata,
        uint48 orderId
    ) private view returns (uint32 chunkId) {
        uint32 firstChunkId = metadata.firstChunkId;

        if (
            firstChunkId == metadata.lastChunkId || orderId < metadata.explicitMappingStartOrderId
        ) {
            return firstChunkId;
        }

        return metadata.orderChunkIds[orderId];
    }

    function _removeOrderFromChunk(
        PriceChunkMetadata storage metadata,
        uint48 orderId,
        uint256 amount,
        uint48 nextOrderId
    ) private {
        uint32 chunkId = _getActiveOrderChunkId(metadata, orderId);
        require(chunkId != 0, "OSTLib: Chunk not found");

        OrderChunk storage chunk = metadata.chunks[chunkId];
        chunk.totalAmount -= amount;
        chunk.orderCount -= 1;

        if (chunk.orderCount == 0) {
            _unlinkChunk(metadata, chunkId);
        } else if (chunk.firstOrderId == orderId) {
            chunk.firstOrderId = nextOrderId;
        }
    }

    function _removeOrdersFromBoundaryChunk(
        Node storage gn,
        OrderChunk storage chunk,
        uint256 amount
    )
        private
        returns (
            uint256 removedAmount,
            uint256 removedCount,
            uint48 partiallyRemovedOrderId,
            uint256 partiallyRemovedAmount,
            uint256 remainingAmount
        )
    {
        remainingAmount = amount;
        uint48 orderId = chunk.firstOrderId;

        while (orderId != 0 && remainingAmount > 0) {
            OrderItem storage currentOrder = gn.orders[orderId];
            uint48 nextOrderId = currentOrder.next;

            if (currentOrder.amount <= remainingAmount) {
                remainingAmount -= currentOrder.amount;
                removedAmount += currentOrder.amount;
                removedCount += 1;
                orderId = nextOrderId;
            } else {
                partiallyRemovedOrderId = orderId;
                partiallyRemovedAmount = remainingAmount;
                remainingAmount = 0;
            }
        }

        chunk.totalAmount -= removedAmount + partiallyRemovedAmount;
        chunk.orderCount -= uint16(removedCount);
        chunk.firstOrderId = partiallyRemovedOrderId != 0 ? partiallyRemovedOrderId : orderId;
    }

    function _unlinkChunkPrefix(
        PriceChunkMetadata storage metadata,
        uint32 firstRemainingChunkId,
        uint32 removedChunkCount
    ) private {
        metadata.activeChunkCount -= removedChunkCount;

        if (firstRemainingChunkId == 0) {
            metadata.firstChunkId = 0;
            metadata.lastChunkId = 0;
            metadata.explicitMappingStartOrderId = 0;
        } else {
            metadata.firstChunkId = firstRemainingChunkId;
            metadata.chunks[firstRemainingChunkId].prevChunkId = 0;

            if (metadata.firstChunkId == metadata.lastChunkId) {
                metadata.explicitMappingStartOrderId = 0;
            }
        }
    }

    function _unlinkChunk(PriceChunkMetadata storage metadata, uint32 chunkId) private {
        OrderChunk storage chunk = metadata.chunks[chunkId];
        uint32 prevChunkId = chunk.prevChunkId;
        uint32 nextChunkId = chunk.nextChunkId;

        if (prevChunkId == 0) {
            metadata.firstChunkId = nextChunkId;
        } else {
            metadata.chunks[prevChunkId].nextChunkId = nextChunkId;
        }

        if (nextChunkId == 0) {
            metadata.lastChunkId = prevChunkId;
        } else {
            metadata.chunks[nextChunkId].prevChunkId = prevChunkId;
        }

        metadata.activeChunkCount -= 1;

        if (metadata.firstChunkId == metadata.lastChunkId) {
            metadata.explicitMappingStartOrderId = 0;
        }
    }

    function _calculateFutureValue(
        uint256 unitPrice,
        uint256 amount
    ) internal pure returns (uint256) {
        return (amount * Constants.PRICE_DIGIT).div(unitPrice);
    }

    function _calculatePresentValue(
        uint256 unitPrice,
        uint256 amount
    ) internal pure returns (uint256) {
        return (amount * unitPrice).div(Constants.PRICE_DIGIT);
    }
}

contracts/protocol/libraries/TransferHelper.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {INativeToken} from "../interfaces/INativeToken.sol";
import {TransferHelperStorage as Storage} from "../storages/libraries/TransferHelperStorage.sol";

library TransferHelper {
    function initialize(address _nativeToken) internal {
        require(Storage.slot().nativeToken == address(0), "TransferHelper: Already initialized");
        Storage.slot().nativeToken = _nativeToken;
    }

    function nativeToken() internal view returns (address) {
        return Storage.slot().nativeToken;
    }

    function isNative(address _token) internal view returns (bool) {
        return _token == Storage.slot().nativeToken;
    }

    function depositAssets(
        address _token,
        address _payer,
        address _receiver,
        uint256 _amount
    ) internal {
        if (address(_token) == Storage.slot().nativeToken) {
            convertToWrappedToken(_receiver, _amount);
        } else {
            safeTransferFrom(_token, _payer, _receiver, _amount);
        }
    }

    function withdrawAssets(address _token, address _receiver, uint256 _amount) internal {
        if (address(_token) == Storage.slot().nativeToken) {
            convertFromWrappedToken(_receiver, _amount);
        } else {
            safeTransfer(_token, _receiver, _amount);
        }
    }

    function convertToWrappedToken(address _receiver, uint256 _amount) internal {
        require(address(this).balance >= _amount, "TransferHelper: Insufficient balance");

        INativeToken(Storage.slot().nativeToken).deposit{value: _amount}();
        safeTransfer(Storage.slot().nativeToken, _receiver, _amount);
    }

    function convertFromWrappedToken(address _receiver, uint256 _amount) internal {
        uint256 balance = INativeToken(Storage.slot().nativeToken).balanceOf(address(this));
        require(balance >= _amount, "TransferHelper: Insufficient balance");

        if (balance > 0) {
            INativeToken(Storage.slot().nativeToken).withdraw(_amount);
            safeTransferETH(_receiver, _amount);
        }
    }

    /// @dev Transfer helper from UniswapV2 Router
    function safeApprove(address token, address to, uint256 value) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(0x095ea7b3, to, value)
        );
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            "TransferHelper: APPROVE_FAILED"
        );
    }

    /**
     * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2
     * Im trying to make it a habit to put external calls last (reentrancy)
     * You can put this in an internal function if you like.
     */
    function safeTransfer(address token, address to, uint256 amount) internal {
        // solium-disable-next-line security/no-low-level-calls
        (bool success, bytes memory data) = token.call(
            // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)"))
            abi.encodeWithSelector(0xa9059cbb, to, amount)
        );
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            "TransferHelper: TRANSFER_FAILED"
        ); // ERC20 Transfer failed
    }

    function safeTransferFrom(address token, address from, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(0x23b872dd, from, to, value)
        );
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            "TransferHelper: TRANSFER_FROM_FAILED"
        );
    }

    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, "TransferHelper: ETH_TRANSFER_FAILED");
    }
}

contracts/protocol/libraries/logics/DepositManagementLogic.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

// dependencies
import {EnumerableSet} from "../../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";
// interfaces
import {ILendingMarket} from "../../interfaces/ILendingMarket.sol";
import {ILendingMarketController} from "../../interfaces/ILendingMarketController.sol";
// libraries
import {AddressResolverLib} from "../AddressResolverLib.sol";
import {TransferHelper} from "../TransferHelper.sol";
import {Constants} from "../Constants.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";
// storages
import {TokenVaultStorage as Storage} from "../../storages/TokenVaultStorage.sol";

library DepositManagementLogic {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using RoundingUint256 for uint256;

    uint256 public constant MAX_DEPOSIT_CURRENCIES = 10;

    error NotEnoughDeposit(bytes32 ccy);
    error ProtocolIsInsolvent(bytes32 ccy);
    error TooManyDepositCurrencies();

    struct CalculatedFundVars {
        uint256 plusDepositAmountInAdditionalFundsCcy;
        uint256 minusDepositAmountInAdditionalFundsCcy;
        uint256 workingLendOrdersAmount;
        uint256 collateralAmount;
        uint256 lentAmount;
        uint256 workingBorrowOrdersAmount;
        uint256 debtAmount;
        uint256 borrowedAmount;
    }

    function isCovered(
        address _user,
        bytes32 _orderCcy
    ) public view returns (bool isEnoughCollateral, bool isEnoughDepositInOrderCcy) {
        ILendingMarketController.AdditionalFunds memory _funds;
        _funds.ccy = _orderCcy;

        (
            uint256 totalCollateral,
            uint256 totalUsedCollateral,
            ,
            bool isInsufficientDepositAmount
        ) = _calculateCollateral(_user, _funds, true);

        isEnoughDepositInOrderCcy = !isInsufficientDepositAmount;
        isEnoughCollateral = _isEnoughCollateral(totalCollateral, totalUsedCollateral);
    }

    function getUsedCurrencies(address _user) public view returns (bytes32[] memory) {
        bytes32[] memory depositCurrencies = Storage.slot().usedCurrencies[_user].values();
        ILendingMarketController lendingMarketController = AddressResolverLib
            .lendingMarketController();
        bytes32[] memory lendingCurrencies = lendingMarketController.getUsedCurrencies(_user);

        uint256 depositLength = depositCurrencies.length;
        uint256 lendingLength = lendingCurrencies.length;

        if (lendingLength == 0) {
            return depositCurrencies;
        }

        bytes32[] memory usedCurrencies = new bytes32[](depositLength + lendingLength);
        uint256 count = depositLength;

        for (uint256 i; i < depositLength; i++) {
            usedCurrencies[i] = depositCurrencies[i];
        }

        for (uint256 i; i < lendingLength; i++) {
            bytes32 ccy = lendingCurrencies[i];

            // Check for duplicates in depositCurrencies
            bool isDuplicate;
            for (uint256 k; k < depositLength; k++) {
                if (depositCurrencies[k] == ccy) {
                    isDuplicate = true;
                    break;
                }
            }

            if (isDuplicate) {
                continue;
            }

            // Check if there are any inactive borrow orders for this currency
            if (_hasInactiveBorrowOrders(lendingMarketController, ccy, _user)) {
                usedCurrencies[count++] = ccy;
            }
        }

        assembly {
            mstore(usedCurrencies, count)
        }

        return usedCurrencies;
    }

    function _hasInactiveBorrowOrders(
        ILendingMarketController lendingMarketController,
        bytes32 ccy,
        address user
    ) private view returns (bool) {
        ILendingMarket market = ILendingMarket(lendingMarketController.getLendingMarket(ccy));
        uint256[] memory maturities = lendingMarketController.getUsedMaturities(ccy, user);
        uint256 maturitiesLength = maturities.length;

        for (uint256 j; j < maturitiesLength; j++) {
            uint8 orderBookId = lendingMarketController.getOrderBookId(ccy, maturities[j]);
            (, uint48[] memory inActiveBorrowOrderIds) = market.getBorrowOrderIds(
                orderBookId,
                user
            );

            if (inActiveBorrowOrderIds.length != 0) {
                return true;
            }
        }

        return false;
    }

    function getDepositAmount(address _user, bytes32 _ccy) public view returns (uint256) {
        ILendingMarketController.CalculatedFunds memory funds = AddressResolverLib
            .lendingMarketController()
            .calculateFunds(_ccy, _user, Storage.slot().liquidationThresholdRate);

        return
            Storage.slot().depositAmounts[_user][_ccy] +
            funds.borrowedAmount -
            funds.lentAmount -
            funds.workingLendOrdersAmount;
    }

    function getTotalCollateralAmount(
        address _user,
        bool _useConservativePrice
    )
        public
        view
        returns (uint256 totalCollateral, uint256 totalUsedCollateral, uint256 totalDeposit)
    {
        ILendingMarketController.AdditionalFunds memory _funds;
        (totalCollateral, totalUsedCollateral, totalDeposit, ) = _calculateCollateral(
            _user,
            _funds,
            _useConservativePrice
        );
    }

    function getCollateralAmount(
        address _user,
        bytes32 _ccy
    )
        public
        view
        returns (uint256 totalCollateral, uint256 totalUsedCollateral, uint256 totalDeposit)
    {
        ILendingMarketController.CalculatedFunds memory funds = AddressResolverLib
            .lendingMarketController()
            .calculateFunds(_ccy, _user, Storage.slot().liquidationThresholdRate);

        uint256 plusDeposit = Storage.slot().depositAmounts[_user][_ccy] + funds.borrowedAmount;
        uint256 minusDeposit = funds.workingLendOrdersAmount + funds.lentAmount;
        uint256 plusCollateral = plusDeposit + funds.collateralAmount;

        totalCollateral = plusCollateral >= minusDeposit ? plusCollateral - minusDeposit : 0;
        totalUsedCollateral = funds.workingBorrowOrdersAmount + funds.debtAmount;
        totalDeposit = plusDeposit >= minusDeposit ? plusDeposit - minusDeposit : 0;
    }

    function getCoverage(address _user) external view returns (uint256 coverage) {
        ILendingMarketController.AdditionalFunds memory _emptyAdditionalFunds;
        (coverage, ) = calculateCoverage(_user, _emptyAdditionalFunds);
    }

    function getTotalUnusedCollateralAmount(address _user) public view returns (uint256) {
        (uint256 totalCollateral, uint256 totalUsedCollateral, ) = getTotalCollateralAmount(
            _user,
            false
        );

        return totalCollateral > totalUsedCollateral ? totalCollateral - totalUsedCollateral : 0;
    }

    function getBorrowableAmount(address _user, bytes32 _ccy) external view returns (uint256) {
        uint256[] memory amounts = new uint256[](2);
        (amounts[0], amounts[1], ) = getTotalCollateralAmount(_user, false);
        amounts = AddressResolverLib.currencyController().convertFromBaseCurrency(_ccy, amounts);

        uint256 totalCollateralAmount = amounts[0];
        uint256 totalUsedCollateral = amounts[1];
        uint256 liquidationThresholdRate = Storage.slot().liquidationThresholdRate;

        ILendingMarketController.CalculatedFunds memory funds = AddressResolverLib
            .lendingMarketController()
            .calculateFunds(_ccy, _user, liquidationThresholdRate);

        uint256 unusedCollateralAmount = funds.claimableAmount > funds.collateralAmount
            ? funds.claimableAmount - funds.collateralAmount
            : 0;

        uint256 borrowableAmount = ((totalCollateralAmount + unusedCollateralAmount) *
            Constants.PCT_DIGIT).div(liquidationThresholdRate);

        return borrowableAmount > totalUsedCollateral ? borrowableAmount - totalUsedCollateral : 0;
    }

    function calculateCoverage(
        address _user,
        ILendingMarketController.AdditionalFunds memory _additionalFunds
    ) public view returns (uint256 coverage, bool isInsufficientDepositAmount) {
        uint256 totalCollateral;
        uint256 totalUsedCollateral;

        (
            totalCollateral,
            totalUsedCollateral,
            ,
            isInsufficientDepositAmount
        ) = _calculateCollateral(_user, _additionalFunds, true);

        if (totalCollateral == 0) {
            coverage = totalUsedCollateral == 0 ? 0 : type(uint256).max;
        } else {
            coverage = (totalUsedCollateral * Constants.PCT_DIGIT) / totalCollateral;
        }
    }

    function _calculateCollateral(
        address _user,
        ILendingMarketController.AdditionalFunds memory _funds,
        bool _useConservativePrice
    )
        internal
        view
        returns (
            uint256 totalCollateral,
            uint256 totalUsedCollateral,
            uint256 totalDeposit,
            bool isInsufficientDepositAmount
        )
    {
        CalculatedFundVars memory vars;

        ILendingMarketController.CalculatedTotalFunds memory funds = AddressResolverLib
            .lendingMarketController()
            .calculateTotalFundsInBaseCurrency(
                _user,
                _funds,
                Storage.slot().liquidationThresholdRate,
                _useConservativePrice
            );

        vars.plusDepositAmountInAdditionalFundsCcy = funds.plusDepositAmountInAdditionalFundsCcy;
        vars.minusDepositAmountInAdditionalFundsCcy = funds.minusDepositAmountInAdditionalFundsCcy;
        vars.workingLendOrdersAmount = funds.workingLendOrdersAmount;
        vars.collateralAmount = funds.collateralAmount;
        vars.lentAmount = funds.lentAmount;
        vars.workingBorrowOrdersAmount = funds.workingBorrowOrdersAmount;
        vars.debtAmount = funds.debtAmount;
        vars.borrowedAmount = funds.borrowedAmount;

        // Check if the user has enough deposit amount in the selected currency.
        if (
            vars.plusDepositAmountInAdditionalFundsCcy +
                Storage.slot().depositAmounts[_user][_funds.ccy] <
            vars.minusDepositAmountInAdditionalFundsCcy
        ) {
            isInsufficientDepositAmount = true;
        }

        uint256 totalInternalDepositAmount = _getTotalInternalDepositAmountInBaseCurrency(_user);

        uint256 plusDeposit = totalInternalDepositAmount + vars.borrowedAmount;
        uint256 minusDeposit = vars.workingLendOrdersAmount + vars.lentAmount;
        uint256 plusCollateral = plusDeposit + vars.collateralAmount;

        totalCollateral = plusCollateral >= minusDeposit ? plusCollateral - minusDeposit : 0;
        totalUsedCollateral = vars.workingBorrowOrdersAmount + vars.debtAmount;
        totalDeposit = plusDeposit >= minusDeposit ? plusDeposit - minusDeposit : 0;
    }

    function getWithdrawableCollateral(address _user) public view returns (uint256) {
        (
            uint256 totalCollateral,
            uint256 totalUsedCollateral,
            uint256 totalDeposit
        ) = getTotalCollateralAmount(_user, true);

        return
            totalUsedCollateral == 0
                ? totalDeposit
                : _calculateWithdrawableCollateral(
                    totalCollateral,
                    totalUsedCollateral,
                    totalDeposit
                );
    }

    function getWithdrawableCollateral(
        bytes32 _ccy,
        address _user
    ) public view returns (uint256 withdrawableAmount) {
        uint256 depositAmount = getDepositAmount(_user, _ccy);
        if (Storage.slot().collateralCurrencies.contains(_ccy)) {
            (
                uint256 totalCollateral,
                uint256 totalUsedCollateral,
                uint256 totalDeposit
            ) = getTotalCollateralAmount(_user, true);

            if (
                totalUsedCollateral == 0 ||
                _isCoveredAfterWithdrawal(
                    _user,
                    _ccy,
                    depositAmount,
                    totalCollateral,
                    totalUsedCollateral
                )
            ) {
                return depositAmount;
            }

            uint256 maxWithdrawInBaseCurrency = _calculateWithdrawableCollateral(
                totalCollateral,
                totalUsedCollateral,
                totalDeposit
            );

            uint256 maxWithdraw = AddressResolverLib.currencyController().convertFromBaseCurrency(
                _ccy,
                maxWithdrawInBaseCurrency
            );

            withdrawableAmount = depositAmount >= maxWithdraw ? maxWithdraw : depositAmount;
        } else {
            withdrawableAmount = depositAmount;
        }
    }

    function _calculateWithdrawableCollateral(
        uint256 _totalCollateral,
        uint256 _totalUsedCollateral,
        uint256 _totalDeposit
    ) private view returns (uint256) {
        if (
            _totalCollateral * Constants.PCT_DIGIT <=
            _totalUsedCollateral * Storage.slot().liquidationThresholdRate
        ) {
            return 0;
        }

        // NOTE: The formula is:
        // maxWithdraw = totalCollateral - (totalUsedCollateral * liquidationThresholdRate)
        uint256 maxWithdraw = (_totalCollateral *
            Constants.PCT_DIGIT -
            _totalUsedCollateral *
            Storage.slot().liquidationThresholdRate).div(Constants.PCT_DIGIT);

        return maxWithdraw >= _totalDeposit ? _totalDeposit : maxWithdraw;
    }

    function _isCoveredAfterWithdrawal(
        address _user,
        bytes32 _ccy,
        uint256 _withdrawalAmount,
        uint256 _totalCollateral,
        uint256 _totalUsedCollateral
    ) private view returns (bool) {
        uint256 depositAmount = Storage.slot().depositAmounts[_user][_ccy];
        if (_withdrawalAmount > depositAmount) {
            return false;
        }

        // Compare the collateral value of the deposit before and after the withdrawal to get the
        // exact reduction in base currency. Converting the withdrawal amount itself is not
        // equivalent because each conversion is rounded independently.
        uint256[] memory collateralAmounts = new uint256[](2);
        collateralAmounts[0] = depositAmount;
        collateralAmounts[1] = depositAmount - _withdrawalAmount;
        collateralAmounts = AddressResolverLib.currencyController().convertToBaseCurrency(
            _ccy,
            collateralAmounts
        );

        uint256 collateralAmountBefore = collateralAmounts[0];
        uint256 collateralAmountAfter = collateralAmounts[1];
        uint256 collateralReduction = collateralAmountBefore > collateralAmountAfter
            ? collateralAmountBefore - collateralAmountAfter
            : 0;
        uint256 remainingCollateral = _totalCollateral > collateralReduction
            ? _totalCollateral - collateralReduction
            : 0;

        return _isEnoughCollateral(remainingCollateral, _totalUsedCollateral);
    }

    function _isEnoughCollateral(
        uint256 _totalCollateral,
        uint256 _totalUsedCollateral
    ) private view returns (bool) {
        return
            _totalUsedCollateral == 0 ||
            _totalCollateral * Constants.PCT_DIGIT >=
            _totalUsedCollateral * Storage.slot().liquidationThresholdRate;
    }

    function canDepositCurrency(address _user, bytes32 _ccy) public view returns (bool) {
        EnumerableSet.Bytes32Set storage currencySet = Storage.slot().usedCurrencies[_user];
        return currencySet.contains(_ccy) || currencySet.length() < MAX_DEPOSIT_CURRENCIES;
    }

    function addDepositAmount(address _user, bytes32 _ccy, uint256 _amount) public {
        Storage.slot().depositAmounts[_user][_ccy] += _amount;
        Storage.slot().usedCurrencies[_user].add(_ccy);
    }

    function removeDepositAmount(address _user, bytes32 _ccy, uint256 _amount) public {
        uint256 currentAmount = Storage.slot().depositAmounts[_user][_ccy];
        if (currentAmount < _amount) {
            revert NotEnoughDeposit({ccy: _ccy});
        }

        if (currentAmount == _amount) {
            Storage.slot().usedCurrencies[_user].remove(_ccy);
        }

        Storage.slot().depositAmounts[_user][_ccy] -= _amount;
    }

    function executeForcedReset(
        address _user,
        bytes32 _ccy
    ) external returns (uint256 removedAmount) {
        removedAmount = Storage.slot().depositAmounts[_user][_ccy];
        Storage.slot().depositAmounts[_user][_ccy] = 0;

        Storage.slot().usedCurrencies[_user].remove(_ccy);
    }

    function deposit(address _caller, bytes32 _ccy, uint256 _amount, address _onBehalfOf) public {
        if (!canDepositCurrency(_onBehalfOf, _ccy)) {
            revert TooManyDepositCurrencies();
        }

        TransferHelper.depositAssets(
            Storage.slot().tokenAddresses[_ccy],
            _caller,
            address(this),
            _amount
        );

        addDepositAmount(_onBehalfOf, _ccy, _amount);
        Storage.slot().totalDepositAmount[_ccy] += _amount;
    }

    function withdraw(
        address _user,
        bytes32 _ccy,
        uint256 _amount
    ) public returns (uint256 withdrawableAmount) {
        withdrawableAmount = getWithdrawableCollateral(_ccy, _user);
        withdrawableAmount = _amount > withdrawableAmount ? withdrawableAmount : _amount;

        if (Storage.slot().totalDepositAmount[_ccy] < withdrawableAmount) {
            revert ProtocolIsInsolvent({ccy: _ccy});
        }

        Storage.slot().totalDepositAmount[_ccy] -= withdrawableAmount;
        removeDepositAmount(_user, _ccy, withdrawableAmount);

        TransferHelper.withdrawAssets(
            Storage.slot().tokenAddresses[_ccy],
            _user,
            withdrawableAmount
        );

        return withdrawableAmount;
    }

    function getLiquidationAmount(
        address _user,
        bytes32 _liquidationCcy,
        uint256 _liquidationAmountMaximum
    ) public view returns (uint256 liquidationAmount, uint256 protocolFee, uint256 liquidatorFee) {
        (
            uint256 totalCollateralInBaseCcy,
            uint256 totalUsedCollateralInBaseCcy,

        ) = getTotalCollateralAmount(_user, false);

        if (totalUsedCollateralInBaseCcy == 0) {
            return (0, 0, 0);
        }

        (uint256 collateralAmount, , ) = getCollateralAmount(_user, _liquidationCcy);

        if (collateralAmount == 0) {
            return (0, 0, 0);
        }

        uint256 liquidationAmountInBaseCcy = 0;
        uint256 coveredRatio = (totalCollateralInBaseCcy * Constants.PCT_DIGIT).div(
            totalUsedCollateralInBaseCcy
        );

        if (coveredRatio < Storage.slot().fullLiquidationThresholdRate) {
            liquidationAmountInBaseCcy = totalUsedCollateralInBaseCcy;
        } else if (coveredRatio < Storage.slot().liquidationThresholdRate) {
            liquidationAmountInBaseCcy = totalUsedCollateralInBaseCcy.div(2);
        }

        uint256[] memory amountsInBaseCcy = new uint256[](2);
        amountsInBaseCcy[0] = liquidationAmountInBaseCcy;
        amountsInBaseCcy[1] = totalCollateralInBaseCcy;

        uint256[] memory amounts = AddressResolverLib.currencyController().convertFromBaseCurrency(
            _liquidationCcy,
            amountsInBaseCcy
        );

        liquidationAmount = amounts[0];
        uint256 totalCollateralAmount = amounts[1];

        if (liquidationAmount > _liquidationAmountMaximum) {
            liquidationAmount = _liquidationAmountMaximum;
        }

        (protocolFee, liquidatorFee) = calculateLiquidationFees(liquidationAmount);

        uint256 liquidationTotalAmount = liquidationAmount + protocolFee + liquidatorFee;

        // NOTE: If `totalCollateralAmount > collateralAmount` is true, it means that a user has collateral in other currencies
        // In this case, this liquidation is not covered by the reserve fund.
        // Therefore, we need to keep the total liquidation amount within the maximum amount.
        if (liquidationTotalAmount > collateralAmount && totalCollateralAmount > collateralAmount) {
            liquidationTotalAmount = collateralAmount;
            uint256 liquidatorFeeRate = Storage.slot().liquidatorFeeRate;
            uint256 liquidationProtocolFeeRate = Storage.slot().liquidationProtocolFeeRate;

            protocolFee = (liquidationTotalAmount * liquidationProtocolFeeRate).div(
                Constants.PCT_DIGIT + liquidatorFeeRate + liquidationProtocolFeeRate
            );
            liquidatorFee = (liquidationTotalAmount * liquidatorFeeRate).div(
                Constants.PCT_DIGIT + liquidatorFeeRate + liquidationProtocolFeeRate
            );
            liquidationAmount = liquidationTotalAmount - protocolFee - liquidatorFee;
        }
    }

    function calculateLiquidationFees(
        uint256 _amount
    ) public view returns (uint256 protocolFee, uint256 liquidatorFee) {
        protocolFee = (_amount * Storage.slot().liquidationProtocolFeeRate).div(
            Constants.PCT_DIGIT
        );
        liquidatorFee = (_amount * Storage.slot().liquidatorFeeRate).div(Constants.PCT_DIGIT);
    }

    function transferFrom(
        bytes32 _ccy,
        address _from,
        address _to,
        uint256 _amount
    ) external returns (uint256 untransferredAmount) {
        uint256 depositAmount = getDepositAmount(_from, _ccy);
        uint256 amount = depositAmount >= _amount ? _amount : depositAmount;
        untransferredAmount = _amount - amount;

        removeDepositAmount(_from, _ccy, amount);
        addDepositAmount(_to, _ccy, amount);
    }

    /**
     * @notice Gets the total of amount deposited in the user's collateral of all currencies
     *  in this contract by converting it to ETH.
     * @param _user Address of collateral user
     * @return totalDepositAmount The total deposited amount in the base currency
     */
    function _getTotalInternalDepositAmountInBaseCurrency(
        address _user
    ) internal view returns (uint256 totalDepositAmount) {
        EnumerableSet.Bytes32Set storage currencies = Storage.slot().usedCurrencies[_user];
        uint256 length = currencies.length();

        for (uint256 i; i < length; i++) {
            bytes32 ccy = currencies.at(i);
            if (Storage.slot().collateralCurrencies.contains(ccy)) {
                uint256 depositAmount = Storage.slot().depositAmounts[_user][ccy];
                totalDepositAmount += AddressResolverLib.currencyController().convertToBaseCurrency(
                    ccy,
                    depositAmount
                );
            }
        }

        return totalDepositAmount;
    }
}

contracts/protocol/libraries/logics/OrderBookLogic.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {Constants} from "../Constants.sol";
import {OrderBookLib, FilledOrder, PartiallyFilledOrder} from "../OrderBookLib.sol";
import {ProtocolTypes} from "../../types/ProtocolTypes.sol";
import {LendingMarketStorage as Storage, ItayoseLog, ItayoseProcess} from "../../storages/LendingMarketStorage.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";

struct ItayoseSettlementResult {
    ProtocolTypes.Side makerSide;
    uint256 batchFilledAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
    PartiallyFilledOrder partiallyFilledOrder;
}

struct ItayoseFinalizeResult {
    uint256 openingUnitPrice;
    uint256 totalOffsetAmount;
    uint256 openingDate;
}

struct ItayoseProcessStatus {
    uint256 openingUnitPrice;
    uint256 lastLendUnitPrice;
    uint256 lastBorrowUnitPrice;
    uint256 totalOffsetAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
    bool isInProgress;
    bool isFinalizable;
    bool isReady;
}

library OrderBookLogic {
    using OrderBookLib for OrderBookLib.OrderBook;
    using RoundingUint256 for uint256;

    error InvalidOrderFeeRate();
    error InvalidCircuitBreakerLimitRange();
    error OrderBookNotMatured();
    error ItayoseProcessAlreadyInitialized();
    error ItayoseProcessNotInitialized();
    error ItayoseSettlementAlreadyCompleted();
    error ItayoseProcessNotFinalizable();
    error ItayoseSettlementDidNotProgress();
    error UnexpectedPartialFill();

    // Provisional value based on the existing performance measurement where 500 price levels
    // consumed approximately 8M gas. The performance test phase may tune this value.
    uint256 internal constant MAX_ITAYOSE_PRICE_LEVELS_PER_CALL = 500;

    event OrderFeeRateUpdated(bytes32 ccy, uint256 previousRate, uint256 rate);
    event CircuitBreakerLimitRangeUpdated(bytes32 ccy, uint256 previousRate, uint256 rate);
    event MinPreOrderAmountUpdated(bytes32 indexed ccy, uint256 previousAmount, uint256 newAmount);
    event OrderBookCreated(uint8 orderBookId, uint256 maturity, uint256 openingDate);

    event ItayoseExecuted(
        bytes32 ccy,
        uint256 maturity,
        uint256 openingUnitPrice,
        uint256 lastLendUnitPrice,
        uint256 lastBorrowUnitPrice,
        uint256 offsetAmount
    );

    function migrateOrderChunks(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _unitPrice
    ) external {
        _getOrderBook(_orderBookId).migrateOrderChunks(_side, _unitPrice);
    }

    function isReady(uint8 _orderBookId) public view returns (bool) {
        return Storage.slot().isReady[_getOrderBook(_orderBookId).maturity];
    }

    function isMatured(uint8 _orderBookId) public view returns (bool) {
        return _getOrderBook(_orderBookId).isMatured();
    }

    function isOpened(uint8 _orderBookId) public view returns (bool) {
        return
            isReady(_orderBookId) &&
            !isMatured(_orderBookId) &&
            block.timestamp >= _getOrderBook(_orderBookId).openingDate;
    }

    function isItayosePeriod(uint8 _orderBookId) public view returns (bool) {
        return
            block.timestamp >=
            (_getOrderBook(_orderBookId).openingDate - OrderBookLib.ITAYOSE_PERIOD) &&
            !isReady(_orderBookId);
    }

    function isPreOrderPeriod(uint8 _orderBookId) public view returns (bool) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        return
            block.timestamp >= orderBook.preOpeningDate &&
            block.timestamp < (orderBook.openingDate - OrderBookLib.ITAYOSE_PERIOD);
    }

    function getOrderBookDetail(
        uint8 _orderBookId
    )
        public
        view
        returns (bytes32 ccy, uint256 maturity, uint256 openingDate, uint256 preOpeningDate)
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        ccy = Storage.slot().ccy;
        maturity = orderBook.maturity;
        openingDate = orderBook.openingDate;
        preOpeningDate = orderBook.preOpeningDate;
    }

    function getLastOrderTimestamp(uint8 _orderBookId) external view returns (uint48) {
        return _getOrderBook(_orderBookId).lastOrderTimestamp;
    }

    function getBlockUnitPriceHistory(
        uint8 _orderBookId
    ) external view returns (uint256[] memory unitPrices, uint48 timestamp) {
        return _getOrderBook(_orderBookId).getBlockUnitPriceHistory(true);
    }

    function getMarketUnitPrice(
        uint8 _orderBookId,
        bool _includeCurrentBlock
    ) external view returns (uint256) {
        return _getOrderBook(_orderBookId).getMarketUnitPrice(_includeCurrentBlock);
    }

    function getBlockUnitPriceAverage(
        uint8 _orderBookId,
        uint256 _count
    ) external view returns (uint256) {
        return _getOrderBook(_orderBookId).getBlockUnitPriceAverage(_count, true);
    }

    function getCircuitBreakerThresholds(
        uint8 _orderBookId
    )
        external
        view
        returns (uint256 maxLendUnitPrice, uint256 minBorrowUnitPrice, uint256 referenceUnitPrice)
    {
        referenceUnitPrice = _getOrderBook(_orderBookId).getBlockUnitPriceAverage(3, false);
        maxLendUnitPrice = OrderBookLib.calculateLendCircuitBreakerThreshold(
            referenceUnitPrice,
            Storage.slot().circuitBreakerLimitRange
        );
        minBorrowUnitPrice = OrderBookLib.calculateBorrowCircuitBreakerThreshold(
            referenceUnitPrice,
            Storage.slot().circuitBreakerLimitRange
        );
    }

    function getBestLendUnitPrice(uint8 _orderBookId) public view returns (uint256) {
        return _getOrderBook(_orderBookId).getBestLendUnitPrice();
    }

    function getBestLendUnitPrices(
        uint8[] memory _orderBookIds
    ) external view returns (uint256[] memory unitPrices) {
        unitPrices = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            unitPrices[i] = _getOrderBook(_orderBookIds[i]).getBestLendUnitPrice();
        }
    }

    function getBestBorrowUnitPrice(uint8 _orderBookId) public view returns (uint256) {
        return _getOrderBook(_orderBookId).getBestBorrowUnitPrice();
    }

    function getBestBorrowUnitPrices(
        uint8[] memory _orderBookIds
    ) external view returns (uint256[] memory unitPrices) {
        unitPrices = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            unitPrices[i] = _getOrderBook(_orderBookIds[i]).getBestBorrowUnitPrice();
        }
    }

    function getBorrowOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return _getOrderBook(_orderBookId).getBorrowOrderBook(_start, _limit);
    }

    function getLendOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return _getOrderBook(_orderBookId).getLendOrderBook(_start, _limit);
    }

    function getItayoseEstimation(
        uint8 _orderBookId
    )
        external
        view
        returns (
            uint256 openingUnitPrice,
            uint256 lastLendUnitPrice,
            uint256 lastBorrowUnitPrice,
            uint256 totalOffsetAmount
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];

        if (process.isInProgress) {
            ItayoseLog storage log = Storage.slot().itayoseLogs[orderBook.maturity];
            return (
                log.openingUnitPrice,
                log.lastLendUnitPrice,
                log.lastBorrowUnitPrice,
                process.totalOffsetAmount
            );
        }

        return orderBook.calculateItayoseResult();
    }

    function getItayoseProcessStatus(
        uint8 _orderBookId
    ) external view returns (ItayoseProcessStatus memory status) {
        return _getItayoseProcessStatus(_getOrderBook(_orderBookId));
    }

    function getMaturities(
        uint8[] memory _orderBookIds
    ) public view returns (uint256[] memory maturities) {
        maturities = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            maturities[i] = _getOrderBook(_orderBookIds[i]).maturity;
        }
    }

    function updateOrderFeeRate(uint256 _orderFeeRate) external {
        if (_orderFeeRate >= Constants.PCT_DIGIT) revert InvalidOrderFeeRate();

        uint256 previousRate = Storage.slot().orderFeeRate;

        if (_orderFeeRate != previousRate) {
            Storage.slot().orderFeeRate = _orderFeeRate;

            emit OrderFeeRateUpdated(Storage.slot().ccy, previousRate, _orderFeeRate);
        }
    }

    function updateCircuitBreakerLimitRange(uint256 _cbLimitRange) external {
        if (_cbLimitRange >= Constants.PCT_DIGIT) revert InvalidCircuitBreakerLimitRange();

        uint256 previousRange = Storage.slot().circuitBreakerLimitRange;

        if (_cbLimitRange != previousRange) {
            Storage.slot().circuitBreakerLimitRange = _cbLimitRange;

            emit CircuitBreakerLimitRangeUpdated(Storage.slot().ccy, previousRange, _cbLimitRange);
        }
    }

    function updateMinPreOrderAmount(uint256 _minPreOrderAmount) external {
        uint256 previousAmount = Storage.slot().minPreOrderAmount;
        Storage.slot().minPreOrderAmount = _minPreOrderAmount;

        emit MinPreOrderAmountUpdated(Storage.slot().ccy, previousAmount, _minPreOrderAmount);
    }

    function createOrderBook(
        uint256 _maturity,
        uint256 _openingDate,
        uint256 _preOpeningDate
    ) public returns (uint8 orderBookId) {
        orderBookId = _nextOrderBookId();

        Storage.slot().isReady[_maturity] = _getOrderBook(orderBookId).initialize(
            _maturity,
            _openingDate,
            _preOpeningDate
        );

        emit OrderBookCreated(orderBookId, _maturity, _openingDate);
    }

    function executeAutoRoll(
        uint8 _maturedOrderBookId,
        uint8 _destinationOrderBookId,
        uint256 _autoRollUnitPrice
    ) external {
        OrderBookLib.OrderBook storage maturedOrderBook = Storage.slot().orderBooks[
            _maturedOrderBookId
        ];

        if (!maturedOrderBook.isMatured()) revert OrderBookNotMatured();

        OrderBookLib.OrderBook storage destinationOrderBook = Storage.slot().orderBooks[
            _destinationOrderBookId
        ];

        // NOTE: The auto-roll destination order book has no market unit price if the order has never been filled before.
        // In this case, the market unit price is updated with the unit price of the auto-roll.
        if (destinationOrderBook.getMarketUnitPrice(false) == 0) {
            destinationOrderBook.setInitialBlockUnitPrice(_autoRollUnitPrice);
        }
    }

    function initializeItayose(uint8 _orderBookId) external returns (ItayoseProcessStatus memory) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 maturity = orderBook.maturity;
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[maturity];

        if (process.isInProgress || Storage.slot().isReady[maturity]) {
            revert ItayoseProcessAlreadyInitialized();
        }

        ItayoseLog memory log;
        (
            log.openingUnitPrice,
            log.lastLendUnitPrice,
            log.lastBorrowUnitPrice,
            process.totalOffsetAmount
        ) = orderBook.calculateItayoseResult();

        process.isInProgress = true;
        process.remainingLendOffsetAmount = process.totalOffsetAmount;
        process.remainingBorrowOffsetAmount = process.totalOffsetAmount;
        Storage.slot().itayoseLogs[maturity] = log;

        if (process.totalOffsetAmount > 0) {
            orderBook.setInitialBlockUnitPrice(log.openingUnitPrice);
        }

        return _getItayoseProcessStatus(orderBook);
    }

    function executeItayoseSettlement(
        uint8 _orderBookId
    ) external returns (ItayoseSettlementResult memory result) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];

        if (!process.isInProgress) revert ItayoseProcessNotInitialized();

        if (process.remainingBorrowOffsetAmount > 0) {
            // fillOrders receives the taker side. LEND therefore settles BORROW makers.
            result = _settleItayoseSide(orderBook, process, ProtocolTypes.Side.LEND);
        } else if (process.remainingLendOffsetAmount > 0) {
            // fillOrders receives the taker side. BORROW therefore settles LEND makers.
            result = _settleItayoseSide(orderBook, process, ProtocolTypes.Side.BORROW);
        } else {
            revert ItayoseSettlementAlreadyCompleted();
        }

        result.remainingLendOffsetAmount = process.remainingLendOffsetAmount;
        result.remainingBorrowOffsetAmount = process.remainingBorrowOffsetAmount;
    }

    function finalizeItayose(
        uint8 _orderBookId
    ) external returns (ItayoseFinalizeResult memory result) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 maturity = orderBook.maturity;
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[maturity];

        if (!process.isInProgress) revert ItayoseProcessNotInitialized();
        if (process.remainingLendOffsetAmount != 0 || process.remainingBorrowOffsetAmount != 0)
            revert ItayoseProcessNotFinalizable();

        ItayoseLog storage log = Storage.slot().itayoseLogs[maturity];
        result.openingUnitPrice = log.openingUnitPrice;
        result.totalOffsetAmount = process.totalOffsetAmount;
        result.openingDate = orderBook.openingDate;

        Storage.slot().isReady[maturity] = true;
        process.isInProgress = false;

        if (process.totalOffsetAmount > 0) {
            emit ItayoseExecuted(
                Storage.slot().ccy,
                maturity,
                log.openingUnitPrice,
                log.lastLendUnitPrice,
                log.lastBorrowUnitPrice,
                process.totalOffsetAmount
            );
        }
    }

    function _settleItayoseSide(
        OrderBookLib.OrderBook storage orderBook,
        ItayoseProcess storage process,
        ProtocolTypes.Side takerSide
    ) private returns (ItayoseSettlementResult memory result) {
        uint256 remainingOffsetAmount = takerSide == ProtocolTypes.Side.LEND
            ? process.remainingBorrowOffsetAmount
            : process.remainingLendOffsetAmount;
        uint256 boundaryUnitPrice = orderBook.getItayoseBoundaryUnitPrice(
            takerSide,
            MAX_ITAYOSE_PRICE_LEVELS_PER_CALL
        );

        FilledOrder memory filledOrder;
        (filledOrder, result.partiallyFilledOrder, , ) = orderBook.fillOrders(
            takerSide,
            remainingOffsetAmount,
            0,
            boundaryUnitPrice
        );

        if (filledOrder.amount == 0) revert ItayoseSettlementDidNotProgress();

        remainingOffsetAmount -= filledOrder.amount;
        if (
            remainingOffsetAmount > 0 &&
            (result.partiallyFilledOrder.orderId != 0 ||
                result.partiallyFilledOrder.maker != address(0) ||
                result.partiallyFilledOrder.amount != 0 ||
                result.partiallyFilledOrder.futureValue != 0)
        ) revert UnexpectedPartialFill();

        if (takerSide == ProtocolTypes.Side.LEND) {
            process.remainingBorrowOffsetAmount = remainingOffsetAmount;
        } else {
            process.remainingLendOffsetAmount = remainingOffsetAmount;
        }

        result.makerSide = takerSide == ProtocolTypes.Side.LEND
            ? ProtocolTypes.Side.BORROW
            : ProtocolTypes.Side.LEND;
        result.batchFilledAmount = filledOrder.amount;
    }

    function _getItayoseProcessStatus(
        OrderBookLib.OrderBook storage orderBook
    ) private view returns (ItayoseProcessStatus memory status) {
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];
        ItayoseLog storage log = Storage.slot().itayoseLogs[orderBook.maturity];

        status.openingUnitPrice = log.openingUnitPrice;
        status.lastLendUnitPrice = log.lastLendUnitPrice;
        status.lastBorrowUnitPrice = log.lastBorrowUnitPrice;
        status.totalOffsetAmount = process.totalOffsetAmount;
        status.remainingLendOffsetAmount = process.remainingLendOffsetAmount;
        status.remainingBorrowOffsetAmount = process.remainingBorrowOffsetAmount;
        status.isInProgress = process.isInProgress;
        status.isFinalizable =
            process.isInProgress &&
            process.remainingLendOffsetAmount == 0 &&
            process.remainingBorrowOffsetAmount == 0;
        status.isReady = Storage.slot().isReady[orderBook.maturity];
    }

    function _nextOrderBookId() internal returns (uint8) {
        // NOTE: Originally, matured ordebooks were reused as new orderbooks after auto-rolls, but this reusing logic has been removed.
        // This means that `orderBookId` is increased in proportion to the number of auto-rolls executed. To avoid overflow of `orderBookId`,
        // `orderBookId` circulate between 1 and 255.
        if (Storage.slot().lastOrderBookId == type(uint8).max) {
            Storage.slot().lastOrderBookId = 1;
        } else {
            Storage.slot().lastOrderBookId++;
        }
        return Storage.slot().lastOrderBookId;
    }

    function _getOrderBook(
        uint8 _orderBookId
    ) private view returns (OrderBookLib.OrderBook storage) {
        return Storage.slot().orderBooks[_orderBookId];
    }
}

contracts/protocol/libraries/math/RoundingUint256.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library RoundingUint256 {
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0);

        if ((a * 10) / b - (a / b) * 10 < 5) {
            return a / b;
        } else {
            return (a / b) + 1;
        }
    }
}

contracts/protocol/mixins/MixinAccessControl.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

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

/**
 * @notice Implements functions to add  role-based access control mechanisms.
 */
contract MixinAccessControl is AccessControl {
    error CallerNotOperator();
    error NotAllowedAccess(bytes32 role, address account);

    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    /**
     * @dev Throws if called by any account other than the admin.
     */
    modifier onlyOperator() {
        if (!hasRole(OPERATOR_ROLE, msg.sender)) revert CallerNotOperator();
        _;
    }

    /**
     * @dev Initializes the roles.
     * @param _admin The address of the admin role
     */
    function _setupInitialRoles(address _admin) internal {
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(OPERATOR_ROLE, _admin);
    }

    /**
     * @notice Adds a new admin as Operator
     * @param admin The address of the new admin
     */
    function addOperator(address admin) external {
        super.grantRole(OPERATOR_ROLE, admin);
    }

    /**
     * @notice Removes an admin as Operator
     * @param admin The address of the admin to remove
     */
    function removeOperator(address admin) external {
        revokeRole(OPERATOR_ROLE, admin);
    }

    /**
     * @dev Revokes `role` from `account`.
     * @param role The role to be revoked
     * @param account The address of the account to revoke the role from
     */
    function revokeRole(bytes32 role, address account) public override {
        if (account == msg.sender) revert NotAllowedAccess(role, account);

        super.revokeRole(role, account);
    }

    /**
     * @notice Revokes `role` from the calling account. This function is disabled by overriding it with a revert.
     * @param role The role to be revoked
     * @param account The address of the account to revoke the role from
     */
    function renounceRole(bytes32 role, address account) public pure override {
        revert NotAllowedAccess(role, account);
    }
}

contracts/protocol/mixins/MixinAddressResolver.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {AddressResolverLib} from "../libraries/AddressResolverLib.sol";
import {IAddressResolver} from "../interfaces/IAddressResolver.sol";
import {IBeaconProxyController} from "../interfaces/IBeaconProxyController.sol";
import {ICurrencyController} from "../interfaces/ICurrencyController.sol";
import {IGenesisValueVault} from "../interfaces/IGenesisValueVault.sol";
import {ILendingMarketController} from "../interfaces/ILendingMarketController.sol";
import {IReserveFund} from "../interfaces/IReserveFund.sol";
import {ITokenVault} from "../interfaces/ITokenVault.sol";
import {MixinAddressResolverStorage as Storage} from "../storages/mixins/MixinAddressResolverStorage.sol";

contract MixinAddressResolver {
    event CacheUpdated(bytes32 name, address destination);

    error OnlyAcceptedContract(string name);
    error ResolverAlreadyRegistered();

    modifier onlyLendingMarketController() {
        if (msg.sender != address(AddressResolverLib.lendingMarketController()))
            revert OnlyAcceptedContract("LendingMarketController");
        _;
    }

    /**
     * @notice Returns the contract names used in this contract.
     * @dev The contract name list is in `./libraries/Contracts.sol`.
     */
    function requiredContracts() public pure virtual returns (bytes32[] memory contracts) {}

    function buildCache() public {
        // The resolver must call this function whenever it updates its state
        bytes32[] memory contractNames = requiredContracts();
        for (uint256 i; i < contractNames.length; i++) {
            bytes32 name = contractNames[i];
            // Note: can only be invoked once the resolver has all the targets needed added
            address destination = Storage.slot().resolver.getAddress(
                name,
                string(abi.encodePacked("Resolver missing target: ", name))
            );
            Storage.slot().addressCache[name] = destination;
            emit CacheUpdated(name, destination);
        }
    }

    function isResolverCached() external view returns (bool) {
        bytes32[] memory contractNames = requiredContracts();
        for (uint256 i; i < contractNames.length; i++) {
            bytes32 name = contractNames[i];
            // false if our cache is invalid or if the resolver doesn't have the required address
            if (
                Storage.slot().resolver.getAddress(name) != Storage.slot().addressCache[name] ||
                Storage.slot().addressCache[name] == address(0)
            ) {
                return false;
            }
        }

        return true;
    }

    /**
     * @dev Register the Address Resolver contract
     * @param _resolver The address of the Address Resolver contract
     */
    function registerAddressResolver(address _resolver) internal {
        if (address(Storage.slot().resolver) != address(0)) revert ResolverAlreadyRegistered();
        Storage.slot().resolver = IAddressResolver(_resolver);
    }

    function getAddress(bytes32 name) internal view returns (address) {
        return AddressResolverLib.getAddress(name);
    }

    function resolver() public view returns (IAddressResolver) {
        return Storage.slot().resolver;
    }

    function beaconProxyController() internal view returns (IBeaconProxyController) {
        return AddressResolverLib.beaconProxyController();
    }

    function currencyController() internal view returns (ICurrencyController) {
        return AddressResolverLib.currencyController();
    }

    function genesisValueVault() internal view returns (IGenesisValueVault) {
        return AddressResolverLib.genesisValueVault();
    }

    function reserveFund() internal view returns (IReserveFund) {
        return AddressResolverLib.reserveFund();
    }

    function lendingMarketController() internal view returns (ILendingMarketController) {
        return AddressResolverLib.lendingMarketController();
    }

    function tokenVault() internal view returns (ITokenVault) {
        return AddressResolverLib.tokenVault();
    }
}

contracts/protocol/mixins/MixinLiquidationConfiguration.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

// libraries
import {Constants} from "../libraries/Constants.sol";
// utils
import {Ownable} from "../utils/Ownable.sol";
// storages
import {TokenVaultStorage as Storage} from "../storages/TokenVaultStorage.sol";

contract MixinLiquidationConfiguration is Ownable {
    error InvalidLiquidationThresholdRate();
    error InvalidFullLiquidationThresholdRate();
    error InvalidLiquidationProtocolFeeRate();
    error InvalidLiquidatorFeeRate();

    event LiquidationThresholdRateUpdated(uint256 previousRate, uint256 ratio);
    event FullLiquidationThresholdRateUpdated(uint256 previousRate, uint256 ratio);
    event LiquidationProtocolFeeRateUpdated(uint256 previousRate, uint256 ratio);
    event LiquidatorFeeRateUpdated(uint256 previousRate, uint256 ratio);

    function _initialize(
        address _owner,
        uint256 _liquidationThresholdRate,
        uint256 _fullLiquidationThresholdRate,
        uint256 _liquidationProtocolFeeRate,
        uint256 _liquidatorFeeRate
    ) internal {
        _transferOwnership(_owner);
        _updateLiquidationConfiguration(
            _liquidationThresholdRate,
            _fullLiquidationThresholdRate,
            _liquidationProtocolFeeRate,
            _liquidatorFeeRate
        );
    }

    /**
     * @dev Gets the liquidation configuration
     * @return liquidationThresholdRate The liquidation threshold rate
     * @return fullLiquidationThresholdRate The full liquidation threshold rate
     * @return liquidationProtocolFeeRate The liquidation fee received by liquidators
     * @return liquidatorFeeRate The liquidation protocol fee received by protocol
     */
    function getLiquidationConfiguration()
        public
        view
        returns (
            uint256 liquidationThresholdRate,
            uint256 fullLiquidationThresholdRate,
            uint256 liquidationProtocolFeeRate,
            uint256 liquidatorFeeRate
        )
    {
        liquidationThresholdRate = Storage.slot().liquidationThresholdRate;
        fullLiquidationThresholdRate = Storage.slot().fullLiquidationThresholdRate;
        liquidationProtocolFeeRate = Storage.slot().liquidationProtocolFeeRate;
        liquidatorFeeRate = Storage.slot().liquidatorFeeRate;
    }

    /**
     * @dev Update the liquidation configuration
     * @param _liquidationThresholdRate The liquidation threshold rate
     * @param _liquidationProtocolFeeRate The liquidation fee rate received by protocol
     * @param _liquidatorFeeRate The liquidation fee rate received by liquidators
     * @notice Triggers only be contract owner
     */
    function updateLiquidationConfiguration(
        uint256 _liquidationThresholdRate,
        uint256 _fullLiquidationThresholdRate,
        uint256 _liquidationProtocolFeeRate,
        uint256 _liquidatorFeeRate
    ) external onlyOwner {
        _updateLiquidationConfiguration(
            _liquidationThresholdRate,
            _fullLiquidationThresholdRate,
            _liquidationProtocolFeeRate,
            _liquidatorFeeRate
        );
    }

    /**
     * @dev Update the liquidation configuration
     * @param _liquidationThresholdRate The liquidation threshold rate
     * @param _liquidationProtocolFeeRate The liquidation fee rate received by protocol
     * @param _liquidatorFeeRate The liquidation fee rate received by liquidators
     * @notice Triggers only be contract owner
     */
    function _updateLiquidationConfiguration(
        uint256 _liquidationThresholdRate,
        uint256 _fullLiquidationThresholdRate,
        uint256 _liquidationProtocolFeeRate,
        uint256 _liquidatorFeeRate
    ) private {
        if (_liquidationThresholdRate <= Constants.PCT_DIGIT)
            revert InvalidLiquidationThresholdRate();
        if (
            _fullLiquidationThresholdRate <= Constants.PCT_DIGIT ||
            _fullLiquidationThresholdRate > _liquidationThresholdRate
        ) revert InvalidFullLiquidationThresholdRate();
        if (_liquidationProtocolFeeRate > Constants.PCT_DIGIT)
            revert InvalidLiquidationProtocolFeeRate();
        if (_liquidatorFeeRate > Constants.PCT_DIGIT) revert InvalidLiquidatorFeeRate();

        if (_liquidationThresholdRate != Storage.slot().liquidationThresholdRate) {
            emit LiquidationThresholdRateUpdated(
                Storage.slot().liquidationThresholdRate,
                _liquidationThresholdRate
            );
            Storage.slot().liquidationThresholdRate = _liquidationThresholdRate;
        }

        if (_fullLiquidationThresholdRate != Storage.slot().fullLiquidationThresholdRate) {
            emit FullLiquidationThresholdRateUpdated(
                Storage.slot().fullLiquidationThresholdRate,
                _fullLiquidationThresholdRate
            );
            Storage.slot().fullLiquidationThresholdRate = _fullLiquidationThresholdRate;
        }

        if (_liquidationProtocolFeeRate != Storage.slot().liquidationProtocolFeeRate) {
            emit LiquidationProtocolFeeRateUpdated(
                Storage.slot().liquidationProtocolFeeRate,
                _liquidationProtocolFeeRate
            );
            Storage.slot().liquidationProtocolFeeRate = _liquidationProtocolFeeRate;
        }

        if (_liquidatorFeeRate != Storage.slot().liquidatorFeeRate) {
            emit LiquidatorFeeRateUpdated(Storage.slot().liquidatorFeeRate, _liquidatorFeeRate);
            Storage.slot().liquidatorFeeRate = _liquidatorFeeRate;
        }
    }
}

contracts/protocol/storages/CurrencyControllerStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../../dependencies/chainlink/AggregatorV3Interface.sol";
import "../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";

struct PriceFeed {
    AggregatorV3Interface[] instances;
    uint256[] heartbeats;
}

library CurrencyControllerStorage {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.currencyController")) - 1);

    struct Storage {
        // Protocol currencies
        EnumerableSet.Bytes32Set currencies;
        mapping(bytes32 ccy => uint256 haircut) haircuts;
        // Total cached decimals of the price feeds
        mapping(bytes32 ccy => uint8 decimals) decimalsCaches;
        mapping(bytes32 ccy => PriceFeed priceFeed) priceFeeds;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/GenesisValueVaultStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

struct MaturityUnitPrice {
    uint256 unitPrice;
    uint256 compoundFactor;
    uint256 next;
    uint256 prev;
}

struct AutoRollLog {
    uint256 unitPrice;
    uint256 lendingCompoundFactor;
    uint256 borrowingCompoundFactor;
    uint256 next;
    uint256 prev;
}

library GenesisValueVaultStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.genesisValueVault")) - 1);

    struct Storage {
        mapping(bytes32 ccy => bool isInitialized) isInitialized;
        mapping(bytes32 ccy => uint256 compoundFactor) initialCompoundFactors;
        mapping(bytes32 ccy => uint256 compoundFactor) lendingCompoundFactors;
        mapping(bytes32 ccy => uint256 compoundFactor) borrowingCompoundFactors;
        mapping(bytes32 ccy => uint256 maturity) currentMaturity;
        mapping(bytes32 ccy => uint8 decimals) decimals;
        mapping(bytes32 ccy => mapping(address user => int256 balance)) balances;
        mapping(bytes32 ccy => uint256 amount) totalLendingSupplies;
        mapping(bytes32 ccy => uint256 amount) totalBorrowingSupplies;
        // Total amount supplied per maturity
        mapping(bytes32 ccy => mapping(uint256 maturity => int256 balance)) maturityBalances;
        mapping(bytes32 ccy => mapping(uint256 maturity => AutoRollLog log)) autoRollLogs;
        // Maturity when the user receives the balance on the target currency
        mapping(bytes32 ccy => mapping(address user => uint256 maturity)) userMaturities;
        mapping(bytes32 ccy => uint256 balance) totalLockedBalances;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/LendingMarketControllerStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";

struct ObservationPeriodLog {
    uint256 totalAmount;
    uint256 totalFutureValue;
}

struct TerminationCurrencyCache {
    int256 price;
    uint8 decimals;
}

struct ZCTokenInfo {
    bytes32 ccy;
    uint256 maturity;
}

library LendingMarketControllerStorage {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.UintSet;

    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.lendingMarketController")) - 1);

    struct Storage {
        uint256 marketBasePeriod;
        uint256 terminationDate;
        mapping(bytes32 ccy => TerminationCurrencyCache currency) terminationCurrencyCaches;
        mapping(bytes32 ccy => uint256 ratio) terminationCollateralRatios;
        mapping(bytes32 ccy => uint8[] orderBookIds) orderBookIdLists;
        mapping(bytes32 ccy => address lendingMarket) lendingMarkets;
        mapping(bytes32 ccy => address futureValueVault) futureValueVaults;
        mapping(bytes32 ccy => uint256 unitPrice) minDebtUnitPrices;
        mapping(bytes32 ccy => uint256 genesisDate) genesisDates;
        mapping(bytes32 ccy => mapping(uint256 maturity => uint256 amount)) pendingOrderAmounts;
        // Order book id history to get order book id from maturity
        mapping(bytes32 ccy => mapping(uint256 maturity => uint8 orderBookIds)) maturityOrderBookIds;
        // List of maturity that the user has open orders or positions
        mapping(bytes32 ccy => mapping(address user => EnumerableSet.UintSet maturities)) usedMaturities;
        // Observation period logs that is used for auto-rolls
        mapping(bytes32 ccy => mapping(uint256 maturity => ObservationPeriodLog log)) observationPeriodLogs;
        // List of currency that the user has open orders or positions
        mapping(address user => EnumerableSet.Bytes32Set currency) usedCurrencies;
        mapping(address user => bool isRedeemed) isRedeemed;
        mapping(bytes32 ccy => mapping(uint256 maturity => address token)) zcTokens;
        mapping(address token => ZCTokenInfo) zcTokenInfo;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/LendingMarketStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {OrderBookLib} from "../libraries/OrderBookLib.sol";

struct ItayoseLog {
    uint256 openingUnitPrice;
    uint256 lastLendUnitPrice;
    uint256 lastBorrowUnitPrice;
}

struct ItayoseProcess {
    bool isInProgress;
    uint256 totalOffsetAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
}

library LendingMarketStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.lendingMarket")) - 1);

    struct Storage {
        bytes32 ccy;
        uint8 lastOrderBookId;
        // Order fee rate received by protocol (in basis point)
        uint256 orderFeeRate;
        // Rate limit range of yield for the circuit breaker
        uint256 circuitBreakerLimitRange;
        // Mapping from order book id to order book
        mapping(uint8 orderBookId => OrderBookLib.OrderBook orderBook) orderBooks;
        mapping(uint256 maturity => bool isReady) isReady;
        mapping(uint256 maturity => ItayoseLog log) itayoseLogs;
        mapping(uint256 maturity => ItayoseProcess process) itayoseProcesses;
        // Minimum amount required to place a pre-order. Zero disables the limit.
        uint256 minPreOrderAmount;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/TokenVaultStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

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

library TokenVaultStorage {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.tokenVault")) - 1);

    struct Storage {
        // Liquidation threshold rate (in basis point)
        uint256 liquidationThresholdRate;
        // Liquidation fee rate received by protocol (in basis point)
        uint256 liquidationProtocolFeeRate;
        // Liquidation fee rate received by liquidators (in basis point)
        uint256 liquidatorFeeRate;
        // Currencies accepted as collateral
        EnumerableSet.Bytes32Set collateralCurrencies;
        mapping(bytes32 ccy => address tokenAddress) tokenAddresses;
        // List of currency that the user has deposit amounts
        mapping(address user => EnumerableSet.Bytes32Set currency) usedCurrencies;
        mapping(bytes32 ccy => uint256 totalDepositAmount) totalDepositAmount;
        mapping(address user => mapping(bytes32 currency => uint256 depositAmount)) depositAmounts;
        // Full liquidation threshold rate (in basis point)
        uint256 fullLiquidationThresholdRate;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/libraries/TransferHelperStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library TransferHelperStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.transferHelper")) - 1);

    struct Storage {
        address nativeToken;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/mixins/MixinAddressResolverStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {IAddressResolver} from "../../interfaces/IAddressResolver.sol";

library MixinAddressResolverStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.mixinAddressResolver")) - 1);

    struct Storage {
        IAddressResolver resolver;
        mapping(bytes32 contractName => address contractAddress) addressCache;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/utils/AccessControlStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

struct RoleData {
    mapping(address => bool) members;
    bytes32 adminRole;
}

library AccessControlStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.accessControl")) - 1);

    struct Storage {
        mapping(bytes32 role => RoleData roleData) roles;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/utils/OwnableStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library OwnableStorage {
    bytes32 internal constant STORAGE_SLOT = bytes32(uint256(keccak256("sf.storage.ownable")) - 1);

    struct Storage {
        address owner;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/utils/PausableStorage.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

library PausableStorage {
    bytes32 internal constant STORAGE_SLOT = bytes32(uint256(keccak256("sf.storage.pausable")) - 1);

    struct Storage {
        bool paused;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/types/ProtocolTypes.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

/**
 * @dev ProtocolTypes is a base-level contract that holds common Secured Finance protocol types
 * @author Secured Finance
 */
library ProtocolTypes {
    enum Side {
        LEND,
        BORROW
    }
}

contracts/protocol/utils/AccessControl.sol

// SPDX-License-Identifier: BUSL-1.1
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "../../dependencies/openzeppelin/access/IAccessControl.sol";
import "../../dependencies/openzeppelin/utils/Context.sol";
import "../../dependencies/openzeppelin/utils/Strings.sol";
import "../../dependencies/openzeppelin/utils/introspection/ERC165.sol";
import "../storages/utils/AccessControlStorage.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return AccessControlStorage.slot().roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return AccessControlStorage.slot().roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(
        bytes32 role,
        address account
    ) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(
        bytes32 role,
        address account
    ) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        AccessControlStorage.slot().roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            AccessControlStorage.slot().roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            AccessControlStorage.slot().roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

contracts/protocol/utils/Ownable.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.19;

import "../../dependencies/openzeppelin/utils/Context.sol";
import "../storages/utils/OwnableStorage.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

contracts/protocol/utils/Pausable.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.0;

import "../../dependencies/openzeppelin/utils/Context.sol";
import "../storages/utils/PausableStorage.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return PausableStorage.slot().paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage.slot().paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage.slot().paused = false;
        emit Unpaused(_msgSender());
    }
}

contracts/protocol/utils/Proxyable.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../../dependencies/openzeppelin/utils/StorageSlot.sol";
import "../../dependencies/openzeppelin/proxy/utils/Initializable.sol";

abstract contract Proxyable is Initializable {
    bytes32 internal constant _IMPLEMENTATION_SLOT =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
    bytes32 internal constant _BEACON_SLOT =
        0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    modifier onlyProxy() {
        require(_getImplementation() != address(0), "Must be called from proxy contract");
        _;
    }

    modifier onlyBeacon() {
        require(_getBeacon() != address(0), "Must be called from beacon contract");
        _;
    }

    /**
     * @notice Gets the revision number of the contract
     * @return The revision number
     */
    function getRevision() external pure virtual returns (uint256) {
        return 0x1;
    }

    function _getImplementation() private view returns (address) {
        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    function _getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
    }
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {
    "contracts/protocol/TokenVault.sol": {
      "DepositManagementLogic": "0xa9d5c1246b67ed567e9fc44ad17665f376697637"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.