Skip to content
Verified contractExactBUSL-1.1

FutureValueVault

Address0xa06874630ffda119affd1bdf414d6ce2352d78ee
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

9 more contracts

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,049,423
Creation transaction
0x55aefd04a6…75002de04e

31 files

contracts/protocol/FutureValueVault.sol

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

// dependencies
import {SafeCast} from "../dependencies/openzeppelin/utils/math/SafeCast.sol";
// interfaces
import {IFutureValueVault} from "./interfaces/IFutureValueVault.sol";
// libraries
import {Contracts} from "./libraries/Contracts.sol";
// mixins
import {MixinAddressResolver} from "./mixins/MixinAddressResolver.sol";
// types
import {ProtocolTypes} from "./types/ProtocolTypes.sol";
// utils
import {Proxyable} from "./utils/Proxyable.sol";
// storages
import {FutureValueVaultStorage as Storage} from "./storages/FutureValueVaultStorage.sol";

/**
 * @notice Implements the management of the future value as an amount for Lending positions in each currency.
 */
contract FutureValueVault is IFutureValueVault, MixinAddressResolver, Proxyable {
    using SafeCast for uint256;
    using SafeCast for int256;

    /**
     * @notice Initializes the contract.
     * @dev Function is invoked by the proxy contract when the contract is added to the ProxyController.
     * @param _resolver The address of the Address Resolver contract
     */
    function initialize(address _resolver) external initializer onlyBeacon {
        registerAddressResolver(_resolver);
        buildCache();
    }

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

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

    /**
     * @notice Gets the total supply of lending orders.
     * @dev This function returns the total supply of only orders that have been added
     * through the `increase` of `decrease` function.
     * @param _maturity The maturity of the market
     */
    function getTotalLendingSupply(uint256 _maturity) external view override returns (uint256) {
        return Storage.slot().totalLendingSupplies[_maturity];
    }

    /**
     * @notice Gets the total supply of borrowing orders.
     * @dev This function returns the total supply of only orders that have been added
     * through the `increase` of `decrease` function.
     * @param _maturity The maturity of the market
     */
    function getTotalBorrowingSupply(uint256 _maturity) external view override returns (uint256) {
        return Storage.slot().totalBorrowingSupplies[_maturity];
    }

    /**
     * @notice Gets the user balance.
     * @param _user User's address
     * @return balance The user balance
     * @return maturity The maturity of the market that the future value was added
     */
    function getBalance(
        uint8 _orderBookId,
        address _user
    ) public view override returns (int256 balance, uint256 maturity) {
        return (
            Storage.slot().balances[_orderBookId][_user],
            Storage.slot().balanceMaturities[_orderBookId][_user]
        );
    }

    /**
     * @notice Gets the total locked balance.
     * @param _orderBookId The order book id
     * @return The total locked balance
     */
    function getTotalLockedBalance(uint8 _orderBookId) external view override returns (uint256) {
        return Storage.slot().totalLockedBalances[_orderBookId];
    }

    /**
     * @notice Gets if the account has past maturity balance at the selected maturity.
     * @param _user User's address
     * @param _maturity The maturity of the market
     * @return The boolean if the lending market is initialized or not
     */
    function hasBalanceAtPastMaturity(
        uint8 _orderBookId,
        address _user,
        uint256 _maturity
    ) public view override returns (bool) {
        if (Storage.slot().balanceMaturities[_orderBookId][_user] == _maturity) {
            return false;
        } else {
            return Storage.slot().balances[_orderBookId][_user] != 0;
        }
    }

    /**
     * @notice Increases amount for lending deals.
     * @dev Since the total supply can be determined by totaling only the amounts on one side of the order
     * when the order is fulfilled, the total supply is incremented only when the executor of the original order
     * is the taker.
     * @param _user User's address
     * @param _amount The amount to add
     * @param _maturity The maturity of the market
     */
    function increase(
        uint8 _orderBookId,
        address _user,
        uint256 _amount,
        uint256 _maturity
    ) public override onlyLendingMarketController {
        if (_user == address(0)) revert UserIsZero();
        if (hasBalanceAtPastMaturity(_orderBookId, _user, _maturity))
            revert PastMaturityBalanceExists({user: _user});

        int256 previousBalance = Storage.slot().balances[_orderBookId][_user];
        Storage.slot().balanceMaturities[_orderBookId][_user] = _maturity;
        Storage.slot().balances[_orderBookId][_user] += _amount.toInt256();
        emit Transfer(address(0), _user, _orderBookId, _maturity, _amount.toInt256());

        _updateTotalSupply(_maturity, _amount.toInt256(), previousBalance);
    }

    /**
     * @notice Decreases amount for borrowing deals.
     * @dev Since the total supply can be determined by totaling only the amounts on one side of the order
     * when the order is fulfilled, the total supply is incremented only when the executor of the original order
     * is the taker.
     * @param _user User's address
     * @param _amount The amount to add
     * @param _maturity The maturity of the market
     */
    function decrease(
        uint8 _orderBookId,
        address _user,
        uint256 _amount,
        uint256 _maturity
    ) public override onlyLendingMarketController {
        if (_user == address(0)) revert UserIsZero();
        if (hasBalanceAtPastMaturity(_orderBookId, _user, _maturity))
            revert PastMaturityBalanceExists({user: _user});

        int256 previousBalance = Storage.slot().balances[_orderBookId][_user];
        Storage.slot().balanceMaturities[_orderBookId][_user] = _maturity;
        Storage.slot().balances[_orderBookId][_user] -= _amount.toInt256();
        emit Transfer(address(0), _user, _orderBookId, _maturity, -(_amount.toInt256()));

        _updateTotalSupply(_maturity, -_amount.toInt256(), previousBalance);
    }

    /**
     * @notice Locks user's balance.
     * @param _user User's address
     * @param _amount The amount to lock
     * @param _maturity The maturity of the market
     * @return lockedAmount The amount locked
     */
    function lock(
        uint8 _orderBookId,
        address _user,
        uint256 _amount,
        uint256 _maturity
    ) public override onlyLendingMarketController returns (uint256 lockedAmount) {
        int256 balance = Storage.slot().balances[_orderBookId][_user];

        if (balance <= 0) revert InsufficientBalance();

        lockedAmount = _amount == 0 ? balance.toUint256() : _amount;

        if (balance.toUint256() < lockedAmount) revert InsufficientBalance();

        Storage.slot().balances[_orderBookId][_user] -= lockedAmount.toInt256();
        Storage.slot().totalLockedBalances[_orderBookId] += lockedAmount;

        emit BalanceLocked(_orderBookId, _maturity, _user, lockedAmount);
    }

    /**
     * @notice Unlocks user's balance.
     * @param _user User's address
     * @param _amount The amount to lock
     * @param _maturity The maturity of the market
     */
    function unlock(
        uint8 _orderBookId,
        address _user,
        uint256 _amount,
        uint256 _maturity
    ) public override onlyLendingMarketController {
        if (_amount > Storage.slot().totalLockedBalances[_orderBookId]) {
            revert InsufficientLockedBalance();
        }

        Storage.slot().totalLockedBalances[_orderBookId] -= _amount;
        Storage.slot().balanceMaturities[_orderBookId][_user] = _maturity;
        Storage.slot().balances[_orderBookId][_user] += _amount.toInt256();

        emit BalanceUnlocked(_orderBookId, _maturity, _user, _amount);
    }

    /**
     * @notice Transfers the future value from sender to receiver.
     * @param _sender Sender's address
     * @param _receiver Receiver's address
     * @param _amount Amount of funds to sent
     * @param _maturity The maturity of the market
     */
    function transferFrom(
        uint8 _orderBookId,
        address _sender,
        address _receiver,
        int256 _amount,
        uint256 _maturity
    ) external override onlyLendingMarketController {
        if (hasBalanceAtPastMaturity(_orderBookId, _sender, _maturity))
            revert PastMaturityBalanceExists({user: _sender});
        if (hasBalanceAtPastMaturity(_orderBookId, _receiver, _maturity))
            revert PastMaturityBalanceExists({user: _receiver});

        int256 senderBalance = Storage.slot().balances[_orderBookId][_sender];
        int256 receiverBalance = Storage.slot().balances[_orderBookId][_receiver];
        Storage.slot().balanceMaturities[_orderBookId][_receiver] = _maturity;
        Storage.slot().balances[_orderBookId][_sender] -= _amount;
        Storage.slot().balances[_orderBookId][_receiver] += _amount;

        _updateTotalSupply(_maturity, -_amount, senderBalance);
        _updateTotalSupply(_maturity, _amount, receiverBalance);

        emit Transfer(_sender, _receiver, _orderBookId, _maturity, _amount);
    }

    /**
     * @notice Reset all amount if there is an amount in the past maturity.
     * @param _user User's address
     * @return removedAmount Removed future value amount
     * @return currentAmount Current future value amount after update
     * @return maturity Maturity of future value
     * @return isAllRemoved The boolean if the all future value amount in the selected maturity is removed
     */
    function reset(
        uint8 _orderBookId,
        address _user
    )
        external
        override
        onlyLendingMarketController
        returns (int256 removedAmount, int256 currentAmount, uint256 maturity, bool isAllRemoved)
    {
        currentAmount = Storage.slot().balances[_orderBookId][_user];
        maturity = Storage.slot().balanceMaturities[_orderBookId][_user];

        if (currentAmount != 0) {
            removedAmount = currentAmount;

            isAllRemoved = false;
            if (removedAmount >= 0) {
                Storage.slot().removedLendingSupply[maturity] += removedAmount.toUint256();
            } else {
                Storage.slot().removedBorrowingSupply[maturity] += (-removedAmount).toUint256();
            }

            Storage.slot().balances[_orderBookId][_user] = 0;
            currentAmount = 0;

            emit Transfer(_user, address(0), _orderBookId, maturity, removedAmount);
        }

        isAllRemoved =
            (Storage.slot().removedLendingSupply[maturity] ==
                Storage.slot().totalLendingSupplies[maturity]) &&
            (Storage.slot().removedBorrowingSupply[maturity] ==
                Storage.slot().totalBorrowingSupplies[maturity]);
    }

    /**
     * @notice Forces a reset of the user's future value.
     * @param _user User's address
     */
    function executeForcedReset(
        uint8 _orderBookId,
        address _user
    ) external override onlyLendingMarketController {
        int256 removedAmount = Storage.slot().balances[_orderBookId][_user];

        if (removedAmount != 0) {
            Storage.slot().balances[_orderBookId][_user] = 0;
            uint256 maturity = Storage.slot().balanceMaturities[_orderBookId][_user];

            emit Transfer(_user, address(0), _orderBookId, maturity, removedAmount);
        }
    }

    /**
     * @notice Forces a reset of the user's future value.
     * @param _user User's address
     * @param _amount The amount to reset
     */
    function executeForcedReset(
        uint8 _orderBookId,
        address _user,
        int256 _amount
    ) external override onlyLendingMarketController returns (int256 removedAmount, int256 balance) {
        removedAmount = Storage.slot().balances[_orderBookId][_user];

        if ((_amount > 0 && removedAmount < 0) || (_amount < 0 && removedAmount > 0)) {
            revert InvalidResetAmount();
        }

        if ((_amount > 0 && _amount < removedAmount) || (_amount < 0 && _amount > removedAmount)) {
            removedAmount = _amount;
        }

        if (removedAmount != 0) {
            Storage.slot().balances[_orderBookId][_user] -= removedAmount;
            uint256 maturity = Storage.slot().balanceMaturities[_orderBookId][_user];

            emit Transfer(_user, address(0), _orderBookId, maturity, removedAmount);
        }

        balance = Storage.slot().balances[_orderBookId][_user];
    }

    function _updateTotalSupply(uint256 _maturity, int256 _amount, int256 _balance) private {
        if (_amount >= 0) {
            uint256 absAmount = _amount.toUint256();
            if (_balance >= 0) {
                Storage.slot().totalLendingSupplies[_maturity] += absAmount;
            } else {
                int256 diff = _amount + _balance;
                if (diff >= 0) {
                    Storage.slot().totalLendingSupplies[_maturity] += diff.toUint256();
                    Storage.slot().totalBorrowingSupplies[_maturity] -= (-_balance).toUint256();
                } else {
                    Storage.slot().totalBorrowingSupplies[_maturity] -= absAmount;
                }
            }
        } else {
            uint256 absAmount = (-_amount).toUint256();
            if (_balance <= 0) {
                Storage.slot().totalBorrowingSupplies[_maturity] += absAmount;
            } else {
                int256 diff = _amount + _balance;
                if (diff <= 0) {
                    Storage.slot().totalBorrowingSupplies[_maturity] += (-diff).toUint256();
                    Storage.slot().totalLendingSupplies[_maturity] -= _balance.toUint256();
                } else {
                    Storage.slot().totalLendingSupplies[_maturity] -= absAmount;
                }
            }
        }
    }
}

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/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/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/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/math/SafeCast.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

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[] 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/IFutureValueVault.sol

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

interface IFutureValueVault {
    error UserIsZero();
    error PastMaturityBalanceExists(address user);
    error TotalSupplyNotZero();
    error InvalidResetAmount();
    error InsufficientBalance();
    error InsufficientLockedBalance();

    event Transfer(
        address indexed from,
        address indexed to,
        uint8 orderBookId,
        uint256 maturity,
        int256 value
    );
    event BalanceLocked(
        uint8 indexed orderBookId,
        uint256 indexed maturity,
        address indexed user,
        uint256 value
    );
    event BalanceUnlocked(
        uint8 indexed orderBookId,
        uint256 indexed maturity,
        address indexed user,
        uint256 value
    );

    function getTotalLendingSupply(uint256 maturity) external view returns (uint256);

    function getTotalBorrowingSupply(uint256 maturity) external view returns (uint256);

    function getBalance(
        uint8 orderBookId,
        address user
    ) external view returns (int256 futureValue, uint256 maturity);

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

    function hasBalanceAtPastMaturity(
        uint8 orderBookId,
        address user,
        uint256 maturity
    ) external view returns (bool);

    function increase(uint8 orderBookId, address user, uint256 amount, uint256 maturity) external;

    function decrease(uint8 orderBookId, address user, uint256 amount, uint256 maturity) external;

    function lock(
        uint8 orderBookId,
        address user,
        uint256 amount,
        uint256 maturity
    ) external returns (uint256 lockedAmount);

    function unlock(uint8 orderBookId, address user, uint256 amount, uint256 maturity) external;

    function transferFrom(
        uint8 orderBookId,
        address sender,
        address receiver,
        int256 amount,
        uint256 maturity
    ) external;

    function reset(
        uint8 orderBookId,
        address user
    )
        external
        returns (int256 removedAmount, int256 currentAmount, uint256 maturity, bool isAllRemoved);

    function executeForcedReset(uint8 orderBookId, address user) external;

    function executeForcedReset(
        uint8 orderBookId,
        address user,
        int256 amount
    ) external returns (int256 removedAmount, int256 balance);
}

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 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/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);

    // Temporarily disabled during incident recovery.
    // 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
    ) 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 cleanUpAllFunds(address user) external returns (bool);

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

    function addPendingOrderAmountForRecovery(
        bytes32 ccy,
        uint256 maturity,
        uint256 amount
    ) external;

    function cancelOrdersForRecovery(bytes32 ccy, address user) external;

    function recoverUserFunds(
        bytes32 ccy,
        uint256 maturity,
        address user,
        ProtocolTypes.Side side,
        uint256 amount,
        uint256 unitPrice
    ) external;

    function transferAssetsForRecovery(bytes32 ccy, address user, address receiver) external;

    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/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 getCollateralDetail(
        address user
    )
        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 = 700;
    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 _isReadOnly
    ) 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 || _isReadOnly) &&
            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;

        if (isLend) {
            bestUnitPrice = self.borrowOrders[self.maturity].first();
            cbThresholdUnitPrice = getLendCircuitBreakerThreshold(
                self,
                _circuitBreakerLimitRange,
                _isReadOnly
            );
        } else {
            bestUnitPrice = self.lendOrders[self.maturity].last();
            cbThresholdUnitPrice = getBorrowCircuitBreakerThreshold(
                self,
                _circuitBreakerLimitRange,
                _isReadOnly
            );
        }

        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 getLendCircuitBreakerThreshold(
        OrderBook storage self,
        uint256 _circuitBreakerLimitRange,
        bool _isReadOnly
    ) internal view returns (uint256 cbThresholdUnitPrice) {
        uint256 blockUnitPriceAverage = getBlockUnitPriceAverage(self, 3, _isReadOnly);
        cbThresholdUnitPrice = (blockUnitPriceAverage *
            (Constants.PCT_DIGIT + _circuitBreakerLimitRange * 2)).div(Constants.PCT_DIGIT);

        if (cbThresholdUnitPrice > Constants.PRICE_DIGIT || blockUnitPriceAverage == 0) {
            cbThresholdUnitPrice = Constants.PRICE_DIGIT;
        } else if (
            cbThresholdUnitPrice < blockUnitPriceAverage + CIRCUIT_BREAKER_MINIMUM_LEND_RANGE
        ) {
            cbThresholdUnitPrice = blockUnitPriceAverage + CIRCUIT_BREAKER_MINIMUM_LEND_RANGE;
        }
    }

    function getBorrowCircuitBreakerThreshold(
        OrderBook storage self,
        uint256 _circuitBreakerLimitRange,
        bool _isReadOnly
    ) internal view returns (uint256 cbThresholdUnitPrice) {
        uint256 blockUnitPriceAverage = getBlockUnitPriceAverage(self, 5, _isReadOnly);
        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/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 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) external view returns (uint256) {
        return _getOrderBook(_orderBookId).getMarketUnitPrice(true);
    }

    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) {
        maxLendUnitPrice = _getOrderBook(_orderBookId).getLendCircuitBreakerThreshold(
            Storage.slot().circuitBreakerLimitRange,
            true
        );
        minBorrowUnitPrice = _getOrderBook(_orderBookId).getBorrowCircuitBreakerThreshold(
            Storage.slot().circuitBreakerLimitRange,
            true
        );
    }

    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 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/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/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/FutureValueVaultStorage.sol

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

library FutureValueVaultStorage {
    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.futureValueVault")) - 1);

    struct Storage {
        // Mapping from user to balances per order book id
        mapping(uint8 orderBookId => mapping(address user => int256 balance)) balances;
        // Maturity when the user receives the balance on the target order book
        mapping(uint8 orderBookId => mapping(address user => uint256 maturity)) balanceMaturities;
        // Total lending amount supplied per maturity
        mapping(uint256 maturity => uint256 amount) totalLendingSupplies;
        // Total borrowing amount supplied per maturity
        mapping(uint256 maturity => uint256 amount) totalBorrowingSupplies;
        // Total lending amount removed per maturity
        mapping(uint256 maturity => uint256 amount) removedLendingSupply;
        // Total borrowing amount removed per maturity
        mapping(uint256 maturity => uint256 amount) removedBorrowingSupply;
        // Mapping from user to tokenized balances per order book id
        // NOTE: This mapping data doesn't use maturity because this field was added after contract upgrades.
        mapping(uint8 orderBookId => 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/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;
    }

    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/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/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
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.