Skip to content
Verified contractPartialBUSL-1.1

LendingMarket

Address0xbe6e63bea4707ebe1487a5004e144e755476bb5e
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,485,262
Creation transaction
0x19e9b730c8…cb402650f5
Libraries
contracts/protocol/LendingMarket.sol:OrderBookLogic0xc490…563e75contracts/protocol/LendingMarket.sol:OrderActionLogic0x82f2…11f6fecontracts/protocol/LendingMarket.sol:OrderReaderLogic0xd583…e358ba

34 files

contracts/protocol/LendingMarket.sol

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

// interfaces
import {ILendingMarket} from "./interfaces/ILendingMarket.sol";
// libraries
import {Contracts} from "./libraries/Contracts.sol";
import {Constants} from "./libraries/Constants.sol";
import {OrderActionLogic} from "./libraries/logics/OrderActionLogic.sol";
import {OrderBookLogic, ItayoseFinalizeResult, ItayoseProcessStatus, ItayoseSettlementResult} from "./libraries/logics/OrderBookLogic.sol";
import {OrderReaderLogic} from "./libraries/logics/OrderReaderLogic.sol";
import {RoundingUint256} from "./libraries/math/RoundingUint256.sol";
import {FilledOrder, PartiallyFilledOrder} from "./libraries/OrderBookLib.sol";
// mixins
import {MixinAddressResolver} from "./mixins/MixinAddressResolver.sol";
// types
import {ProtocolTypes} from "./types/ProtocolTypes.sol";
// utils
import {Pausable} from "./utils/Pausable.sol";
import {Proxyable} from "./utils/Proxyable.sol";
// storages
import {LendingMarketStorage as Storage, ItayoseLog} from "./storages/LendingMarketStorage.sol";

/**
 * @notice Implements the module that allows order book participants to execute/cancel/unwind orders.
 *
 * For updates, this contract is basically called from `LendingMarketController.sol`instead of being called
 * directly by the user.
 *
 * @dev Open orders is stored in structured red-black trees and doubly linked lists in each node.
 */
contract LendingMarket is ILendingMarket, MixinAddressResolver, Pausable, Proxyable {
    using RoundingUint256 for uint256;

    /// @dev Used for minimum reliable amount in base currency for block unit price
    uint256 immutable MINIMUM_RELIABLE_AMOUNT_IN_BASE_CURRENCY;

    /**
     * @notice Modifier to make a function callable only by order maker.
     * @param _orderBookId The order book id
     * @param _user User's address
     * @param _orderId Market order id
     */
    modifier onlyMaker(
        uint8 _orderBookId,
        address _user,
        uint48 _orderId
    ) {
        (, , , address maker, , , ) = getOrder(_orderBookId, _orderId);
        if (maker == address(0)) revert NoOrderExists();
        if (_user != maker) revert CallerNotMaker();
        _;
    }

    /**
     * @notice Modifier to check if the market is opened.
     * @param _orderBookId The order book id
     */
    modifier ifOpened(uint8 _orderBookId) {
        if (!isOpened(_orderBookId)) revert MarketNotOpened();
        _;
    }

    /**
     * @notice Modifier to check if the market is under the Itayose period.
     * @param _orderBookId The order book id
     */
    modifier ifItayosePeriod(uint8 _orderBookId) {
        if (!isItayosePeriod(_orderBookId)) revert NotItayosePeriod();
        _;
    }

    /**
     * @notice Modifier to check if the market is not under the Itayose period.
     * @param _orderBookId The order book id
     */
    modifier ifNotItayosePeriod(uint8 _orderBookId) {
        if (isItayosePeriod(_orderBookId)) revert AlreadyItayosePeriod();
        _;
    }

    /**
     * @notice Modifier to check if the market is under the pre-order period.
     * @param _orderBookId The order book id
     */
    modifier ifPreOrderPeriod(uint8 _orderBookId) {
        if (!isPreOrderPeriod(_orderBookId)) revert NotPreOrderPeriod();
        _;
    }

    /**
     * @notice Contract constructor function.
     * @param _minimumReliableAmount The minimum reliable amount the base currency for calculating block unit price
     */
    constructor(uint256 _minimumReliableAmount) {
        MINIMUM_RELIABLE_AMOUNT_IN_BASE_CURRENCY = _minimumReliableAmount;
    }

    /**
     * @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
     * @param _ccy The main currency for the order book
     */
    function initialize(
        address _resolver,
        bytes32 _ccy,
        uint256 _orderFeeRate,
        uint256 _cbLimitRange
    ) public initializer onlyBeacon {
        registerAddressResolver(_resolver);
        Storage.slot().ccy = _ccy;

        OrderBookLogic.updateOrderFeeRate(_orderFeeRate);
        OrderBookLogic.updateCircuitBreakerLimitRange(_cbLimitRange);

        buildCache();
    }

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

    /**
     * @notice Gets if the market is ready.
     * @param _orderBookId The order book id
     * @return The boolean if the market is ready or not
     */
    function isReady(uint8 _orderBookId) public view override returns (bool) {
        return OrderBookLogic.isReady(_orderBookId);
    }

    /**
     * @notice Gets if the market is matured.
     * @param _orderBookId The order book id
     * @return The boolean if the market is matured or not
     */
    function isMatured(uint8 _orderBookId) public view override returns (bool) {
        return OrderBookLogic.isMatured(_orderBookId);
    }

    /**
     * @notice Gets if the market is opened.
     * @param _orderBookId The order book id
     * @return The boolean if the market is opened or not
     */
    function isOpened(uint8 _orderBookId) public view override returns (bool) {
        return OrderBookLogic.isOpened(_orderBookId);
    }

    /**
     * @notice Gets if the market is under the Itayose period.
     * @param _orderBookId The order book id
     * @return The boolean if the market is under the Itayose period.
     */
    function isItayosePeriod(uint8 _orderBookId) public view returns (bool) {
        return OrderBookLogic.isItayosePeriod(_orderBookId);
    }

    /**
     * @notice Gets if the market is under the pre-order period.
     * @param _orderBookId The order book id
     * @return The boolean if the market is under the pre-order period.
     */
    function isPreOrderPeriod(uint8 _orderBookId) public view override returns (bool) {
        return OrderBookLogic.isPreOrderPeriod(_orderBookId);
    }

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

    /**
     * @notice Gets the minimum reliable amount in base currency for calculating block unit price.
     * @return The minimum reliable amount in base currency
     */
    function minimumReliableAmountInBaseCurrency() external view override returns (uint256) {
        return MINIMUM_RELIABLE_AMOUNT_IN_BASE_CURRENCY;
    }

    /**
     * @notice Gets the order book detail.
     * @param _orderBookId The order book id
     * @return ccy The currency of the order book
     * @return maturity The maturity of the order book
     * @return openingDate The opening date of the order book
     * @return preOpeningDate The pre-opening date of the order book
     */
    function getOrderBookDetail(
        uint8 _orderBookId
    )
        public
        view
        override
        returns (bytes32 ccy, uint256 maturity, uint256 openingDate, uint256 preOpeningDate)
    {
        return OrderBookLogic.getOrderBookDetail(_orderBookId);
    }

    /**
     * @notice Gets unit price Thresholds by CircuitBreaker.
     * @param _orderBookId The order book id
     * @return maxLendUnitPrice The maximum unit price for lending
     * @return minBorrowUnitPrice The minimum unit price for borrowing
     * @return referenceUnitPrice The unit price used as the circuit breaker reference
     */
    function getCircuitBreakerThresholds(
        uint8 _orderBookId
    )
        external
        view
        override
        returns (uint256 maxLendUnitPrice, uint256 minBorrowUnitPrice, uint256 referenceUnitPrice)
    {
        return OrderBookLogic.getCircuitBreakerThresholds(_orderBookId);
    }

    /**
     * @notice Gets the best price for lending.
     * @param _orderBookId The order book id
     * @return The best price for lending
     */
    function getBestLendUnitPrice(uint8 _orderBookId) public view override returns (uint256) {
        return OrderBookLogic.getBestLendUnitPrice(_orderBookId);
    }

    /**
     * @notice Gets the best prices for lending.
     * @return The array of the best price for lending
     */
    function getBestLendUnitPrices(
        uint8[] calldata _orderBookIds
    ) external view override returns (uint256[] memory) {
        return OrderBookLogic.getBestLendUnitPrices(_orderBookIds);
    }

    /**
     * @notice Gets the best price for borrowing.
     * @param _orderBookId The order book id
     * @return The best price for borrowing
     */
    function getBestBorrowUnitPrice(uint8 _orderBookId) public view override returns (uint256) {
        return OrderBookLogic.getBestBorrowUnitPrice(_orderBookId);
    }

    /**
     * @notice Gets the best prices for borrowing.
     * @return The array of the best price for borrowing
     */
    function getBestBorrowUnitPrices(
        uint8[] calldata _orderBookIds
    ) external view override returns (uint256[] memory) {
        return OrderBookLogic.getBestBorrowUnitPrices(_orderBookIds);
    }

    /**
     * @notice Gets the live unit price, including reliable current-block fills
     * @param _orderBookId The order book id
     * @return The live unit price
     */
    function getLiveUnitPrice(uint8 _orderBookId) external view override returns (uint256) {
        return OrderBookLogic.getMarketUnitPrice(_orderBookId, true);
    }

    /**
     * @notice Gets the market unit price used for position valuation.
     * @dev Excludes current-block fills once a reference price exists.
     *      An unpriced book uses its first reliable block price immediately.
     * @param _orderBookId The order book id
     * @return The unit price used for collateral valuation and liquidation conversion
     */
    function getMarketUnitPrice(uint8 _orderBookId) external view override returns (uint256) {
        return OrderBookLogic.getMarketUnitPrice(_orderBookId, false);
    }

    /**
     * @notice Gets the block timestamp of the last filled order.
     * @param _orderBookId The order book id
     * @return The block number
     */
    function getLastOrderTimestamp(uint8 _orderBookId) external view override returns (uint48) {
        return OrderBookLogic.getLastOrderTimestamp(_orderBookId);
    }

    /**
     * @notice Gets the block unit price history
     * @param _orderBookId The order book id
     * @return unitPrices The array of the block unit price
     * @return timestamp Timestamp of the last block unit price
     */
    function getBlockUnitPriceHistory(
        uint8 _orderBookId
    ) external view override returns (uint256[] memory unitPrices, uint48 timestamp) {
        return OrderBookLogic.getBlockUnitPriceHistory(_orderBookId);
    }

    /**
     * @notice Gets the block unit price average.
     * @param _orderBookId The order book id
     * @param _count Count of data used for averaging
     * @return The block unit price average
     */
    function getBlockUnitPriceAverage(
        uint8 _orderBookId,
        uint256 _count
    ) external view override returns (uint256) {
        return OrderBookLogic.getBlockUnitPriceAverage(_orderBookId, _count);
    }

    /**
     * @notice Gets the order book of borrow orders.
     * This function supports pagination. If a unit price is specified in `_start`,
     * the orders are returned for the _limit from there. The unit price that can be
     * set to `_start` of the next data fetching is set to the return value, `next`.
     * If `_start` is 0, this function returns from the first order.
     * @param _orderBookId The order book id
     * @param _start The starting unit price to get order book
     * @param _limit The max limit for getting unit prices
     * @return unitPrices The array of order unit prices
     * @return amounts The array of order amounts
     * @return quantities The array of order quantities
     * @return next The next starting unit price to get order book
     */
    function getBorrowOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        override
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return OrderBookLogic.getBorrowOrderBook(_orderBookId, _start, _limit);
    }

    /**
     * @notice Gets the order book of lend orders.
     * This function supports pagination. If a unit price is specified in `_start`,
     * the orders are returned for the _limit from there. The unit price that can be
     * set to `_start` of the next data fetching is set to the return value, `next`.
     * If `_start` is 0, this function returns from the first order.
     * @param _orderBookId The order book id
     * @param _start The starting unit price to get order book
     * @param _limit The max limit for getting unit prices
     * @return unitPrices The array of order unit prices
     * @return amounts The array of order amounts
     * @return quantities The array of order quantities
     * @return next The next starting unit price to get order book
     */
    function getLendOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        override
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return OrderBookLogic.getLendOrderBook(_orderBookId, _start, _limit);
    }

    /**
     * @notice Gets the estimation of the Itayose process.
     * @param _orderBookId The order book id
     * @return openingUnitPrice The opening price when Itayose is executed
     * @return lastLendUnitPrice The price of the last lend order filled by Itayose.
     * @return lastBorrowUnitPrice The price of the last borrow order filled by Itayose.
     * @return totalOffsetAmount The total amount of the orders filled by Itayose.
     */
    function getItayoseEstimation(
        uint8 _orderBookId
    )
        external
        view
        returns (
            uint256 openingUnitPrice,
            uint256 lastLendUnitPrice,
            uint256 lastBorrowUnitPrice,
            uint256 totalOffsetAmount
        )
    {
        return OrderBookLogic.getItayoseEstimation(_orderBookId);
    }

    /**
     * @notice Gets the current market maturity.
     * @param _orderBookId The order book id
     * @return maturity The market maturity
     */
    function getMaturity(uint8 _orderBookId) public view override returns (uint256 maturity) {
        return Storage.slot().orderBooks[_orderBookId].maturity;
    }

    /**
     * @notice Gets the order book maturities.
     * @return maturities The array of maturity
     */
    function getMaturities(
        uint8[] calldata _orderBookIds
    ) external view override returns (uint256[] memory maturities) {
        return OrderBookLogic.getMaturities(_orderBookIds);
    }

    /**
     * @notice Gets the market currency.
     * @return currency The market currency
     */
    function getCurrency() external view override returns (bytes32 currency) {
        return Storage.slot().ccy;
    }

    /**
     * @notice Gets the order fee rate
     * @return The order fee rate received by protocol
     */
    function getOrderFeeRate() external view override returns (uint256) {
        return Storage.slot().orderFeeRate;
    }

    /**
     * @notice Gets the limit range in unit price for the circuit breaker
     * @return The limit range in unit price for the circuit breaker
     */
    function getCircuitBreakerLimitRange() external view override returns (uint256) {
        return Storage.slot().circuitBreakerLimitRange;
    }

    /**
     * @notice Gets the minimum amount required to place a pre-order
     * @return The minimum pre-order amount in the currency's smallest unit. Zero disables the limit
     */
    function getMinPreOrderAmount() external view override returns (uint256) {
        return Storage.slot().minPreOrderAmount;
    }

    /**
     * @notice Gets the market opening date.
     * @param _orderBookId The order book id
     * @return openingDate The market opening date
     */
    function getOpeningDate(uint8 _orderBookId) public view override returns (uint256 openingDate) {
        return Storage.slot().orderBooks[_orderBookId].openingDate;
    }

    /**
     * @notice Gets the immutable price-discovery result once an Itayose process is initialized.
     * @dev A non-zero log does not mean the process is finalized. Use isReady for completion.
     * @param _maturity The market maturity
     */
    function getItayoseLog(uint256 _maturity) external view override returns (ItayoseLog memory) {
        return Storage.slot().itayoseLogs[_maturity];
    }

    /**
     * @notice Gets the resumable Itayose process status.
     * @param _orderBookId The order book id
     */
    function getItayoseProcessStatus(
        uint8 _orderBookId
    ) external view override returns (ItayoseProcessStatus memory) {
        return OrderBookLogic.getItayoseProcessStatus(_orderBookId);
    }

    /**
     * @notice Gets the market order from the order book.
     * @param _orderBookId The order book id
     * @param _orderId The market order id
     * @return side Order position type, Borrow or Lend
     * @return unitPrice Amount of interest unit price
     * @return maturity The maturity of the selected order
     * @return maker The order maker
     * @return amount Order amount
     * @return timestamp Timestamp when the order was created
     * @return isPreOrder The boolean if the order is a pre-order.
     */
    function getOrder(
        uint8 _orderBookId,
        uint48 _orderId
    )
        public
        view
        override
        returns (
            ProtocolTypes.Side side,
            uint256 unitPrice,
            uint256 maturity,
            address maker,
            uint256 amount,
            uint256 timestamp,
            bool isPreOrder
        )
    {
        return OrderReaderLogic.getOrder(_orderBookId, _orderId);
    }

    /**
     * @notice Calculates and gets the active and inactive amounts from the user orders of lending deals.
     * @param _orderBookId The order book id
     * @param _user User's address
     * @return activeAmount The total amount of active order on the order book
     * @return inactiveAmount The total amount of inactive orders filled on the order book
     * @return inactiveFutureValue The total future value amount of inactive orders filled on the order book
     * @return maturity The maturity of market that orders were placed.
     */
    function getTotalAmountFromLendOrders(
        uint8 _orderBookId,
        address _user
    )
        external
        view
        override
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        )
    {
        return OrderReaderLogic.getTotalAmountFromLendOrders(_orderBookId, _user);
    }

    /**
     * @notice Calculates and gets the active and inactive amounts from the user orders of borrowing deals.
     * @param _orderBookId The order book id
     * @param _user User's address
     * @return activeAmount The total amount of active order on the order book
     * @return inactiveAmount The total amount of inactive orders filled on the order book
     * @return inactiveFutureValue The total future value amount of inactive orders filled on the order book
     * @return maturity The maturity of market that orders were placed.
     */
    function getTotalAmountFromBorrowOrders(
        uint8 _orderBookId,
        address _user,
        uint256 _minUnitPrice
    )
        external
        view
        override
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        )
    {
        return OrderReaderLogic.getTotalAmountFromBorrowOrders(_orderBookId, _user, _minUnitPrice);
    }

    /**
     * @notice Gets active and inactive order IDs in the lending order book.
     * @param _orderBookId The order book id
     * @param _user User's address
     */
    function getLendOrderIds(
        uint8 _orderBookId,
        address _user
    )
        external
        view
        override
        returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds)
    {
        return OrderReaderLogic.getLendOrderIds(_orderBookId, _user);
    }

    /**
     * @notice Gets active and inactive order IDs in the borrowing order book.
     * @param _orderBookId The order book id
     * @param _user User's address
     */
    function getBorrowOrderIds(
        uint8 _orderBookId,
        address _user
    )
        external
        view
        override
        returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds)
    {
        return OrderReaderLogic.getBorrowOrderIds(_orderBookId, _user);
    }

    /**
     * @notice Calculates the amount to be filled when executing an order in the order book.
     * @param _orderBookId The order book id
     * @param _side Order position type, Borrow or Lend
     * @param _amount Amount of funds the user wants to borrow/lend
     * @param _unitPrice Unit price user want to borrow/lend
     * @return lastUnitPrice The last unit price that is filled on the order book
     * @return filledAmount The amount that is filled on the order book
     * @return filledAmountInFV The amount in the future value that is filled on the order book
     * @return orderFeeInFV The order fee amount in the future value
     * @return placedAmount The amount that is placed to the order book
     */
    function calculateFilledAmount(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _amount,
        uint256 _unitPrice
    )
        external
        view
        override
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV,
            uint256 placedAmount
        )
    {
        return OrderReaderLogic.calculateFilledAmount(_orderBookId, _side, _amount, _unitPrice);
    }

    /**
     * @notice Calculates the amount to be filled when executing an order in the order book from the future value.
     * @param _orderBookId The order book id
     * @param _side Order position type, Borrow or Lend
     * @param _amountInFV Amount of funds the user wants to borrow/lend in future value
     * @return lastUnitPrice The last unit price that is filled on the order book
     * @return filledAmount The amount that is filled on the order book
     * @return filledAmountInFV The amount in the future value that is filled on the order book
     * @return orderFeeInFV The order fee amount in the future value
     */
    function calculateFilledAmountFromFV(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _amountInFV
    )
        external
        view
        override
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV
        )
    {
        return OrderReaderLogic.calculateFilledAmountFromFV(_orderBookId, _side, _amountInFV);
    }

    /**
     * @notice Builds chunk metadata for a legacy price level after the chunk-index upgrade.
     * @dev Permissionless and callable only while the price level has orders and no chunk metadata.
     * @param _orderBookId The order book id
     * @param _side The order side to migrate
     * @param _unitPrice The unit price to migrate
     */
    function migrateOrderChunks(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _unitPrice
    ) external {
        OrderBookLogic.migrateOrderChunks(_orderBookId, _side, _unitPrice);
    }

    /**
     * @notice Creates a new order book.
     * @param _maturity The initial maturity of the order book
     * @param _openingDate The timestamp when the order book opens
     * @param _preOpeningDate The timestamp when the order book pre-opens
     */
    function createOrderBook(
        uint256 _maturity,
        uint256 _openingDate,
        uint256 _preOpeningDate
    ) external override onlyLendingMarketController returns (uint8 orderBookId) {
        return OrderBookLogic.createOrderBook(_maturity, _openingDate, _preOpeningDate);
    }

    function executeAutoRoll(
        uint8 _maturedOrderBookId,
        uint8 _newNearestOrderBookId,
        uint256 _autoRollUnitPrice
    ) external override whenNotPaused onlyLendingMarketController {
        OrderBookLogic.executeAutoRoll(
            _maturedOrderBookId,
            _newNearestOrderBookId,
            _autoRollUnitPrice
        );
    }

    /**
     * @notice Cancels the order.
     * @param _orderBookId The order book id
     * @param _user User address
     * @param _orderId Market order id
     */
    function cancelOrder(
        uint8 _orderBookId,
        address _user,
        uint48 _orderId
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        onlyMaker(_orderBookId, _user, _orderId)
        ifNotItayosePeriod(_orderBookId)
    {
        OrderActionLogic.cancelOrder(_orderBookId, _user, _orderId);
    }

    /**
     * @notice Cleans up own orders to remove order ids that are already filled on the order book.
     * @dev The order list per user is not updated in real-time when an order is filled.
     * This function removes the filled order from that order list per user to reduce gas costs
     * for lazy evaluation if the collateral is enough or not.
     *
     * @param _user User address
     * @return activeLendOrderCount The total amount of active lend order on the order book
     * @return activeBorrowOrderCount The total amount of active borrow order on the order book
     * @return removedLendOrderFutureValue The total FV amount of the removed lend order amount from the order book
     * @return removedBorrowOrderFutureValue The total FV amount of the removed borrow order amount from the order book
     * @return removedLendOrderAmount The total PV amount of the removed lend order amount from the order book
     * @return removedBorrowOrderAmount The total PV amount of the removed borrow order amount from the order book
     * @return maturity The maturity of the removed orders
     */
    function cleanUpOrders(
        uint8 _orderBookId,
        address _user
    )
        external
        override
        onlyLendingMarketController
        returns (
            uint256 activeLendOrderCount,
            uint256 activeBorrowOrderCount,
            uint256 removedLendOrderFutureValue,
            uint256 removedBorrowOrderFutureValue,
            uint256 removedLendOrderAmount,
            uint256 removedBorrowOrderAmount,
            uint256 maturity
        )
    {
        return OrderActionLogic.cleanUpOrders(_orderBookId, _user);
    }

    /**
     * @notice Executes an order. Takes orders if the order is matched,
     * and places new order if not match it.
     * @param _orderBookId The order book id
     * @param _side Order position type, Borrow or Lend
     * @param _user User's address
     * @param _amount Amount of funds the user wants to borrow/lend
     * @param _unitPrice Unit price user wish to borrow/lend
     * @return filledOrder User's Filled order of the user
     * @return partiallyFilledOrder Partially filled order on the order book
     */
    function executeOrder(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        ifOpened(_orderBookId)
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        )
    {
        return
            OrderActionLogic.executeOrder(
                _orderBookId,
                _side,
                _user,
                _amount,
                _unitPrice,
                currencyController().convertFromBaseCurrency(
                    Storage.slot().ccy,
                    MINIMUM_RELIABLE_AMOUNT_IN_BASE_CURRENCY
                )
            );
    }

    /**
     * @notice Executes a pre-order. A pre-order will only be accepted from 168 hours (7 days) to 1 hour
     * before the market opens (Pre-order period). At the end of this period, Itayose will be executed.
     *
     * @param _orderBookId The order book id
     * @param _side Order position type, Borrow or Lend
     * @param _amount Amount of funds the maker wants to borrow/lend
     * @param _unitPrice Unit price taker wish to borrow/lend
     */
    function executePreOrder(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice
    ) external override whenNotPaused onlyLendingMarketController ifPreOrderPeriod(_orderBookId) {
        OrderActionLogic.executePreOrder(_orderBookId, _side, _user, _amount, _unitPrice);
    }

    /**
     * @notice Unwinds lending or borrowing positions by a specified future value amount.
     * @param _orderBookId The order book id
     * @param _side Order position type, Borrow or Lend
     * @param _user User's address
     * @param _futureValue Amount of future value unwound
     * @return filledOrder User's Filled order of the user
     * @return partiallyFilledOrder Partially filled order
     */
    function unwindPosition(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _futureValue
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        ifOpened(_orderBookId)
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        )
    {
        return
            OrderActionLogic.unwindPosition(
                _orderBookId,
                _side,
                _user,
                _futureValue,
                currencyController().convertFromBaseCurrency(
                    Storage.slot().ccy,
                    MINIMUM_RELIABLE_AMOUNT_IN_BASE_CURRENCY
                )
            );
    }

    /**
     * @notice Initializes an Itayose process and fixes its price-discovery result.
     */
    function initializeItayose(
        uint8 _orderBookId
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        ifItayosePeriod(_orderBookId)
        returns (ItayoseProcessStatus memory)
    {
        return OrderBookLogic.initializeItayose(_orderBookId);
    }

    /**
     * @notice Settles one bounded Itayose batch.
     */
    function executeItayoseSettlement(
        uint8 _orderBookId
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        ifItayosePeriod(_orderBookId)
        returns (ItayoseSettlementResult memory)
    {
        return OrderBookLogic.executeItayoseSettlement(_orderBookId);
    }

    /**
     * @notice Finalizes a fully settled Itayose process and opens the market.
     */
    function finalizeItayose(
        uint8 _orderBookId
    )
        external
        override
        whenNotPaused
        onlyLendingMarketController
        ifItayosePeriod(_orderBookId)
        returns (ItayoseFinalizeResult memory)
    {
        return OrderBookLogic.finalizeItayose(_orderBookId);
    }

    /**
     * @notice Updates the order fee rate
     * @param _orderFeeRate The order fee rate received by protocol
     */
    function updateOrderFeeRate(
        uint256 _orderFeeRate
    ) external override onlyLendingMarketController {
        OrderBookLogic.updateOrderFeeRate(_orderFeeRate);
    }

    /**
     * @notice Updates the auto-roll fee rate
     * @param _cbLimitRange The circuit breaker limit range
     */
    function updateCircuitBreakerLimitRange(
        uint256 _cbLimitRange
    ) external override onlyLendingMarketController {
        OrderBookLogic.updateCircuitBreakerLimitRange(_cbLimitRange);
    }

    /**
     * @notice Updates the minimum amount required to place a pre-order
     * @param _minPreOrderAmount The minimum pre-order amount in the currency's smallest unit. Zero disables the limit
     */
    function updateMinPreOrderAmount(
        uint256 _minPreOrderAmount
    ) external override onlyLendingMarketController {
        OrderBookLogic.updateMinPreOrderAmount(_minPreOrderAmount);
    }

    /**
     * @notice Pauses the lending market.
     */
    function pause() external override onlyLendingMarketController {
        _pause();
    }

    /**
     * @notice Unpauses the lending market.
     */
    function unpause() external override onlyLendingMarketController {
        _unpause();
    }
}

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

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

pragma solidity ^0.8.0;

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

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

contracts/dependencies/openzeppelin/utils/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/structs/EnumerableSet.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

contracts/protocol/interfaces/IAddressResolver.sol

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

interface IAddressResolver {
    error UnmatchedInputs();

    event AddressImported(bytes32 name, address destination);

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

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

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

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

contracts/protocol/interfaces/IBeaconProxyController.sol

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

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

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

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

    function setFutureValueVaultImpl(address newImpl) external;

    function setLendingMarketImpl(address newImpl) external;

    function setZCTokenImpl(address newImpl) external;

    function deployFutureValueVault() external returns (address futureValueVault);

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

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

contracts/protocol/interfaces/ICurrencyController.sol

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

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

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

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

    event HaircutUpdated(bytes32 indexed ccy, uint256 haircut);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function updateHaircut(bytes32 _ccy, uint256 _haircut) external;

    function removeCurrency(bytes32 _ccy) external;
}

contracts/protocol/interfaces/IGenesisValueVault.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function updateInitialCompoundFactor(bytes32 ccy, uint256 unitPrice) external;

    function updateDecimals(bytes32 _ccy, uint8 _decimals) external;

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

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

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

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

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

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

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

    function executeForcedReset(bytes32 _ccy, address _user) external;

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

contracts/protocol/interfaces/ILendingMarket.sol

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

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

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

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

    function minimumReliableAmountInBaseCurrency() external view returns (uint256);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function getCurrency() external view returns (bytes32);

    function getOrderFeeRate() external view returns (uint256);

    function getCircuitBreakerLimitRange() external view returns (uint256);

    function getMinPreOrderAmount() external view returns (uint256);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function updateOrderFeeRate(uint256 orderFeeRate) external;

    function updateCircuitBreakerLimitRange(uint256 limitRange) external;

    function updateMinPreOrderAmount(uint256 minPreOrderAmount) external;

    function pause() external;

    function unpause() external;
}

contracts/protocol/interfaces/ILendingMarketController.sol

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

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

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

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

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

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

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

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

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

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

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

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

    function isTerminated() external view returns (bool);

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

    function getMarketBasePeriod() external view returns (uint256);

    function getTerminationDate() external view returns (uint256);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function executeEmergencySettlement() external returns (bool);

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

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

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

    function rotateOrderBooks(bytes32 ccy) external;

    function executeEmergencyTermination() external;

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

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

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

    function updateMinDebtUnitPrice(bytes32 _ccy, uint256 _minDebtUnitPrice) external;

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

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

contracts/protocol/interfaces/IReserveFund.sol

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

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

    function isPaused() external view returns (bool);

    function pause() external;

    function unpause() external;

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

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

contracts/protocol/interfaces/ITokenVault.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function updateCurrency(bytes32 ccy, bool isCollateral) external;

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

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

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

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

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

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

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

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

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

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

    function pause() external;

    function unpause() external;

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

contracts/protocol/libraries/AddressResolverLib.sol

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

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

library AddressResolverLib {
    error MissingAddress(string name);

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

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

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

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

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

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

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

contracts/protocol/libraries/Constants.sol

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

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

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

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

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

contracts/protocol/libraries/Contracts.sol

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

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

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

contracts/protocol/libraries/OrderBookLib.sol

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

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

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

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

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

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

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

    error EmptyOrderBook();
    error PastMaturityOrderExists();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 unitPrice;

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

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

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

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

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

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

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

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

        uint256 unitPrice;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            self.userCurrentMaturities[_user] = orderBookMaturity;
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        delete self.orders[_orderId];

        return (side, removedAmount, unitPrice);
    }

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

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

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

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

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

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

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

        orderExists = bestUnitPrice != 0;

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

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

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

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

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

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

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

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

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

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

                orders.pop();
                break;
            }
        }
    }

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

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

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

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

contracts/protocol/libraries/OrderStatisticsTreeLib.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        valueExists = cursor != EMPTY;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        _setBlackIfNotEmpty(self, value);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        vars.cursor = parent;
                    }

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

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

        uint256 lastNode = last(self);

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

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

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

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

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

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

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

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

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

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

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

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

                        vars.cursor = parent;
                    }

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

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

        uint256 firstNode = first(self);

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

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

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

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

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

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

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

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

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

                if (targetChangedByFix) {
                    break;
                }
            }

            if (targetChangedByFix) {
                continue;
            }

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

        _setBlackIfNotEmpty(self, self.root);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 sibling = _rightOf(self, target);

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

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

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

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

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

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

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

        rotateLeft(self, target);
        return target;
    }

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

        uint256 sibling = _leftOf(self, target);

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

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

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

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

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

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

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

        rotateRight(self, target);
        return target;
    }

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

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

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

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

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

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

        insert(self, value);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            cursor = next(self, cursor);
        }

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

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

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

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

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

            cursor = prev(self, cursor);
        }

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

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

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

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

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

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

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

        gn.head = orderId;
    }

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

        gn.tail = orderId;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return metadata.orderChunkIds[orderId];
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

        metadata.activeChunkCount -= 1;

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

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

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

contracts/protocol/libraries/logics/OrderActionLogic.sol

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

import {OrderBookLib, FilledOrder, PartiallyFilledOrder} from "../OrderBookLib.sol";
import {ProtocolTypes} from "../../types/ProtocolTypes.sol";
import {LendingMarketStorage as Storage} from "../../storages/LendingMarketStorage.sol";
// libraries
import {Constants} from "../Constants.sol";
import {AddressResolverLib} from "../AddressResolverLib.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";
import {OrderReaderLogic} from "./OrderReaderLogic.sol";

library OrderActionLogic {
    using OrderBookLib for OrderBookLib.OrderBook;
    using RoundingUint256 for uint256;

    error InvalidAmount();
    error InvalidPreOrderUnitPrice();
    error InvalidFutureValue();
    error EmptyOrderBook();
    error OppositeSideOrderExists();
    error PreOrderAmountTooSmall(uint256 amount, uint256 minimumAmount);

    struct OrderExecutionConditions {
        bool isFilled;
        uint256 executedUnitPrice;
        bool ignoreRemainingAmount;
        bool orderExists;
    }

    struct PlacedOrder {
        uint48 orderId;
        uint256 amount;
        uint256 unitPrice;
    }

    struct ExecuteOrderVars {
        OrderExecutionConditions conditions;
        PlacedOrder placedOrder;
        bool isCircuitBreakerTriggered;
        uint256 maturity;
    }

    struct FillOrdersVars {
        uint8 orderBookId;
        uint256 remainingAmount;
        bool orderExists;
    }

    event OrderCanceled(
        uint48 orderId,
        address indexed maker,
        ProtocolTypes.Side side,
        bytes32 ccy,
        uint256 maturity,
        uint256 amount,
        uint256 unitPrice
    );

    event OrdersCleaned(
        uint48[] orderIds,
        address indexed maker,
        ProtocolTypes.Side side,
        bytes32 indexed ccy,
        uint256 maturity,
        uint256 amount,
        uint256 futureValue
    );

    event OrderExecuted(
        address indexed user,
        ProtocolTypes.Side side,
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 inputAmount,
        uint256 inputUnitPrice,
        uint256 filledAmount,
        uint256 filledUnitPrice,
        uint256 filledAmountInFV,
        uint256 feeInFV,
        uint48 placedOrderId,
        uint256 placedAmount,
        uint256 placedUnitPrice,
        bool isCircuitBreakerTriggered
    );

    event PreOrderExecuted(
        address indexed user,
        ProtocolTypes.Side side,
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 amount,
        uint256 unitPrice,
        uint48 orderId
    );

    event PositionUnwound(
        address indexed user,
        ProtocolTypes.Side side,
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 inputFutureValue,
        uint256 filledAmount,
        uint256 filledUnitPrice,
        uint256 filledAmountInFV,
        uint256 feeInFV,
        bool isCircuitBreakerTriggered
    );

    event BlockUnitPriceHistoryUpdated(
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 blockUnitPrice
    );

    function cancelOrder(uint8 _orderBookId, address _user, uint48 _orderId) external {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (ProtocolTypes.Side side, uint256 removedAmount, uint256 unitPrice) = orderBook.removeOrder(
            _user,
            _orderId
        );

        emit OrderCanceled(
            _orderId,
            _user,
            side,
            Storage.slot().ccy,
            orderBook.maturity,
            removedAmount,
            unitPrice
        );
    }

    function cleanUpOrders(
        uint8 _orderBookId,
        address _user
    )
        external
        returns (
            uint256 activeLendOrderCount,
            uint256 activeBorrowOrderCount,
            uint256 removedLendOrderFutureValue,
            uint256 removedBorrowOrderFutureValue,
            uint256 removedLendOrderAmount,
            uint256 removedBorrowOrderAmount,
            uint256 maturity
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        maturity = orderBook.userCurrentMaturities[_user];

        uint48[] memory lendOrderIds;
        uint48[] memory borrowOrderIds;

        (
            lendOrderIds,
            activeLendOrderCount,
            removedLendOrderFutureValue,
            removedLendOrderAmount
        ) = _cleanLendOrders(_orderBookId, _user);

        (
            borrowOrderIds,
            activeBorrowOrderCount,
            removedBorrowOrderFutureValue,
            removedBorrowOrderAmount
        ) = _cleanBorrowOrders(_orderBookId, _user);

        if (removedLendOrderAmount > 0) {
            emit OrdersCleaned(
                lendOrderIds,
                _user,
                ProtocolTypes.Side.LEND,
                Storage.slot().ccy,
                orderBook.maturity,
                removedLendOrderAmount,
                removedLendOrderFutureValue
            );
        }

        if (removedBorrowOrderAmount > 0) {
            emit OrdersCleaned(
                borrowOrderIds,
                _user,
                ProtocolTypes.Side.BORROW,
                Storage.slot().ccy,
                orderBook.maturity,
                removedBorrowOrderAmount,
                removedBorrowOrderFutureValue
            );
        }
    }

    function executeOrder(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice,
        uint256 _minimumReliableAmount
    )
        external
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        )
    {
        if (_amount == 0) revert InvalidAmount();

        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        orderBook.updateUserMaturity(_user);

        ExecuteOrderVars memory vars;
        vars.maturity = orderBook.maturity;

        (
            vars.conditions.isFilled,
            vars.conditions.executedUnitPrice,
            vars.conditions.ignoreRemainingAmount,
            vars.conditions.orderExists
        ) = orderBook.getOrderExecutionConditions(
            _side,
            _unitPrice,
            Storage.slot().circuitBreakerLimitRange,
            false
        );

        if (_unitPrice == 0 && !vars.conditions.orderExists) revert EmptyOrderBook();

        if (vars.conditions.isFilled) {
            (
                filledOrder,
                partiallyFilledOrder,
                vars.placedOrder,
                vars.isCircuitBreakerTriggered
            ) = _fillOrders(
                _orderBookId,
                _side,
                _user,
                _amount,
                vars.conditions.executedUnitPrice,
                vars.conditions.ignoreRemainingAmount
            );
            feeInFV = OrderReaderLogic.calculateOrderFeeAmount(
                vars.maturity,
                filledOrder.futureValue
            );
            (uint256 latestBlockUnitPrice, bool isUpdated) = orderBook.updateBlockUnitPriceHistory(
                filledOrder.amount,
                filledOrder.futureValue,
                _minimumReliableAmount
            );

            if (isUpdated) {
                emit BlockUnitPriceHistoryUpdated(
                    Storage.slot().ccy,
                    vars.maturity,
                    latestBlockUnitPrice
                );
            }
        } else {
            if (!vars.conditions.ignoreRemainingAmount) {
                vars.placedOrder = PlacedOrder(
                    orderBook.placeOrder(_side, _user, _amount, vars.conditions.executedUnitPrice),
                    _amount,
                    vars.conditions.executedUnitPrice
                );
            }

            vars.isCircuitBreakerTriggered = _unitPrice == 0
                ? vars.conditions.orderExists
                : _unitPrice != vars.conditions.executedUnitPrice;
        }

        emit OrderExecuted(
            _user,
            _side,
            Storage.slot().ccy,
            vars.maturity,
            _amount,
            _unitPrice,
            filledOrder.amount,
            filledOrder.unitPrice,
            filledOrder.futureValue,
            feeInFV,
            vars.placedOrder.orderId,
            vars.placedOrder.amount,
            vars.placedOrder.unitPrice,
            vars.isCircuitBreakerTriggered
        );
    }

    function executePreOrder(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice
    ) external {
        if (_unitPrice == 0) revert InvalidPreOrderUnitPrice();
        if (_amount == 0) revert InvalidAmount();

        uint256 minimumAmount = Storage.slot().minPreOrderAmount;
        if (_amount < minimumAmount) revert PreOrderAmountTooSmall(_amount, minimumAmount);

        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        orderBook.updateUserMaturity(_user);

        if (
            (_side == ProtocolTypes.Side.LEND && orderBook.hasBorrowOrder(_user)) ||
            (_side == ProtocolTypes.Side.BORROW && orderBook.hasLendOrder(_user))
        ) {
            revert OppositeSideOrderExists();
        }

        uint48 orderId = orderBook.placeOrder(_side, _user, _amount, _unitPrice);
        orderBook.isPreOrder[orderId] = true;

        emit PreOrderExecuted(
            _user,
            _side,
            Storage.slot().ccy,
            orderBook.maturity,
            _amount,
            _unitPrice,
            orderId
        );
    }

    function unwindPosition(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _futureValue,
        uint256 _minimumReliableAmount
    )
        external
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            uint256 feeInFV
        )
    {
        if (_futureValue == 0) revert InvalidFutureValue();

        OrderExecutionConditions memory conditions;
        bool isCircuitBreakerTriggered;
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 maturity = orderBook.maturity;

        (
            conditions.isFilled,
            conditions.executedUnitPrice,
            conditions.ignoreRemainingAmount,
            conditions.orderExists
        ) = orderBook.getOrderExecutionConditions(
            _side,
            0,
            Storage.slot().circuitBreakerLimitRange,
            false
        );

        if (!conditions.orderExists) revert EmptyOrderBook();

        if (conditions.isFilled) {
            (
                filledOrder,
                partiallyFilledOrder,
                isCircuitBreakerTriggered,
                feeInFV
            ) = _unwindPosition(_orderBookId, _side, _futureValue, conditions.executedUnitPrice);
            (uint256 latestBlockUnitPrice, bool isUpdated) = orderBook.updateBlockUnitPriceHistory(
                filledOrder.amount,
                filledOrder.futureValue,
                _minimumReliableAmount
            );

            if (isUpdated) {
                emit BlockUnitPriceHistoryUpdated(
                    Storage.slot().ccy,
                    maturity,
                    latestBlockUnitPrice
                );
            }
        } else {
            isCircuitBreakerTriggered = true;
        }

        emit PositionUnwound(
            _user,
            _side,
            Storage.slot().ccy,
            maturity,
            _futureValue,
            filledOrder.amount,
            filledOrder.unitPrice,
            filledOrder.futureValue,
            feeInFV,
            isCircuitBreakerTriggered
        );
    }

    function _cleanLendOrders(
        uint8 _orderBookId,
        address _user
    )
        internal
        returns (
            uint48[] memory orderIds,
            uint256 activeOrderCount,
            uint256 removedFutureValue,
            uint256 removedOrderAmount
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (uint48[] memory activeLendOrderIds, uint48[] memory inActiveLendOrderIds) = orderBook
            .getLendOrderIds(_user);

        orderBook.activeLendOrderIds[_user] = activeLendOrderIds;
        activeOrderCount = activeLendOrderIds.length;
        uint256 inactiveOrderCount = inActiveLendOrderIds.length;
        orderIds = new uint48[](inactiveOrderCount);

        for (uint256 i; i < inactiveOrderCount; i++) {
            (uint256 presentValue, uint256 futureValue) = OrderReaderLogic.getLendOrderAmounts(
                orderBook,
                inActiveLendOrderIds[i]
            );

            removedOrderAmount += presentValue;
            removedFutureValue += futureValue;
            orderIds[i] = inActiveLendOrderIds[i];
        }
    }

    function _cleanBorrowOrders(
        uint8 _orderBookId,
        address _user
    )
        internal
        returns (
            uint48[] memory orderIds,
            uint256 activeOrderCount,
            uint256 removedFutureValue,
            uint256 removedOrderAmount
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (uint48[] memory activeBorrowOrderIds, uint48[] memory inActiveBorrowOrderIds) = orderBook
            .getBorrowOrderIds(_user);

        orderBook.activeBorrowOrderIds[_user] = activeBorrowOrderIds;
        activeOrderCount = activeBorrowOrderIds.length;
        uint256 inactiveOrderCount = inActiveBorrowOrderIds.length;
        orderIds = new uint48[](inactiveOrderCount);

        for (uint256 i; i < inactiveOrderCount; i++) {
            (uint256 presentValue, uint256 futureValue, ) = OrderReaderLogic.getBorrowOrderAmounts(
                orderBook,
                inActiveBorrowOrderIds[i]
            );

            removedOrderAmount += presentValue;
            removedFutureValue += futureValue;
            orderIds[i] = inActiveBorrowOrderIds[i];
        }
    }

    /**
     * @notice Fills orders in the order book.
     * @param _side Order position type, Borrow or Lend
     * @param _user User's address
     * @param _amount Amount of funds the maker wants to borrow/lend
     * @param _unitPrice Unit price taken
     * @param _ignoreRemainingAmount Boolean for whether to ignore the remaining amount after filling orders
     */
    function _fillOrders(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        address _user,
        uint256 _amount,
        uint256 _unitPrice,
        bool _ignoreRemainingAmount
    )
        private
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            PlacedOrder memory placedOrder,
            bool isCircuitBreakerTriggered
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        FillOrdersVars memory vars;
        vars.orderBookId = _orderBookId;

        (filledOrder, partiallyFilledOrder, vars.remainingAmount, vars.orderExists) = orderBook
            .fillOrders(_side, _amount, 0, _unitPrice);

        if (vars.remainingAmount > 0) {
            if (_ignoreRemainingAmount) {
                filledOrder.ignoredAmount = vars.remainingAmount;
            } else {
                // Place a new order with the remaining amount of the input amount
                placedOrder = PlacedOrder(
                    orderBook.placeOrder(_side, _user, vars.remainingAmount, _unitPrice),
                    vars.remainingAmount,
                    _unitPrice
                );
            }
        }

        isCircuitBreakerTriggered =
            vars.orderExists &&
            _ignoreRemainingAmount &&
            _amount != filledOrder.amount;
    }

    function _unwindPosition(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _futureValue,
        uint256 _unitPrice
    )
        private
        returns (
            FilledOrder memory filledOrder,
            PartiallyFilledOrder memory partiallyFilledOrder,
            bool isCircuitBreakerTriggered,
            uint256 feeInFV
        )
    {
        bool orderExists;
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 futureValueWithFee = OrderReaderLogic.calculateFutureValueWithFee(
            _futureValue,
            _side,
            orderBook.maturity
        );

        (filledOrder, partiallyFilledOrder, , orderExists) = orderBook.fillOrders(
            _side,
            0,
            futureValueWithFee,
            _unitPrice
        );

        isCircuitBreakerTriggered = orderExists && futureValueWithFee != filledOrder.futureValue;

        if (futureValueWithFee == filledOrder.futureValue) {
            // Full unwind: use the difference between original futureValue and futureValueWithFee
            // to avoid leaving dust amounts by rounding
            feeInFV = _side == ProtocolTypes.Side.BORROW
                ? _futureValue - futureValueWithFee
                : futureValueWithFee - _futureValue;
        } else {
            // Partial unwind: calculate fee based on actually filled amount
            feeInFV = OrderReaderLogic.calculateOrderFeeAmount(
                orderBook.maturity,
                filledOrder.futureValue
            );
        }
    }

    function _getOrderBook(
        uint8 _orderBookId
    ) private view returns (OrderBookLib.OrderBook storage) {
        return Storage.slot().orderBooks[_orderBookId];
    }
}

contracts/protocol/libraries/logics/OrderBookLogic.sol

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

import {Constants} from "../Constants.sol";
import {OrderBookLib, FilledOrder, PartiallyFilledOrder} from "../OrderBookLib.sol";
import {ProtocolTypes} from "../../types/ProtocolTypes.sol";
import {LendingMarketStorage as Storage, ItayoseLog, ItayoseProcess} from "../../storages/LendingMarketStorage.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";

struct ItayoseSettlementResult {
    ProtocolTypes.Side makerSide;
    uint256 batchFilledAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
    PartiallyFilledOrder partiallyFilledOrder;
}

struct ItayoseFinalizeResult {
    uint256 openingUnitPrice;
    uint256 totalOffsetAmount;
    uint256 openingDate;
}

struct ItayoseProcessStatus {
    uint256 openingUnitPrice;
    uint256 lastLendUnitPrice;
    uint256 lastBorrowUnitPrice;
    uint256 totalOffsetAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
    bool isInProgress;
    bool isFinalizable;
    bool isReady;
}

library OrderBookLogic {
    using OrderBookLib for OrderBookLib.OrderBook;
    using RoundingUint256 for uint256;

    error InvalidOrderFeeRate();
    error InvalidCircuitBreakerLimitRange();
    error OrderBookNotMatured();
    error ItayoseProcessAlreadyInitialized();
    error ItayoseProcessNotInitialized();
    error ItayoseSettlementAlreadyCompleted();
    error ItayoseProcessNotFinalizable();
    error ItayoseSettlementDidNotProgress();
    error UnexpectedPartialFill();

    // Provisional value based on the existing performance measurement where 500 price levels
    // consumed approximately 8M gas. The performance test phase may tune this value.
    uint256 internal constant MAX_ITAYOSE_PRICE_LEVELS_PER_CALL = 500;

    event OrderFeeRateUpdated(bytes32 ccy, uint256 previousRate, uint256 rate);
    event CircuitBreakerLimitRangeUpdated(bytes32 ccy, uint256 previousRate, uint256 rate);
    event MinPreOrderAmountUpdated(bytes32 indexed ccy, uint256 previousAmount, uint256 newAmount);
    event OrderBookCreated(uint8 orderBookId, uint256 maturity, uint256 openingDate);

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

    function migrateOrderChunks(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _unitPrice
    ) external {
        _getOrderBook(_orderBookId).migrateOrderChunks(_side, _unitPrice);
    }

    function isReady(uint8 _orderBookId) public view returns (bool) {
        return Storage.slot().isReady[_getOrderBook(_orderBookId).maturity];
    }

    function isMatured(uint8 _orderBookId) public view returns (bool) {
        return _getOrderBook(_orderBookId).isMatured();
    }

    function isOpened(uint8 _orderBookId) public view returns (bool) {
        return
            isReady(_orderBookId) &&
            !isMatured(_orderBookId) &&
            block.timestamp >= _getOrderBook(_orderBookId).openingDate;
    }

    function isItayosePeriod(uint8 _orderBookId) public view returns (bool) {
        return
            block.timestamp >=
            (_getOrderBook(_orderBookId).openingDate - OrderBookLib.ITAYOSE_PERIOD) &&
            !isReady(_orderBookId);
    }

    function isPreOrderPeriod(uint8 _orderBookId) public view returns (bool) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        return
            block.timestamp >= orderBook.preOpeningDate &&
            block.timestamp < (orderBook.openingDate - OrderBookLib.ITAYOSE_PERIOD);
    }

    function getOrderBookDetail(
        uint8 _orderBookId
    )
        public
        view
        returns (bytes32 ccy, uint256 maturity, uint256 openingDate, uint256 preOpeningDate)
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        ccy = Storage.slot().ccy;
        maturity = orderBook.maturity;
        openingDate = orderBook.openingDate;
        preOpeningDate = orderBook.preOpeningDate;
    }

    function getLastOrderTimestamp(uint8 _orderBookId) external view returns (uint48) {
        return _getOrderBook(_orderBookId).lastOrderTimestamp;
    }

    function getBlockUnitPriceHistory(
        uint8 _orderBookId
    ) external view returns (uint256[] memory unitPrices, uint48 timestamp) {
        return _getOrderBook(_orderBookId).getBlockUnitPriceHistory(true);
    }

    function getMarketUnitPrice(
        uint8 _orderBookId,
        bool _includeCurrentBlock
    ) external view returns (uint256) {
        return _getOrderBook(_orderBookId).getMarketUnitPrice(_includeCurrentBlock);
    }

    function getBlockUnitPriceAverage(
        uint8 _orderBookId,
        uint256 _count
    ) external view returns (uint256) {
        return _getOrderBook(_orderBookId).getBlockUnitPriceAverage(_count, true);
    }

    function getCircuitBreakerThresholds(
        uint8 _orderBookId
    )
        external
        view
        returns (uint256 maxLendUnitPrice, uint256 minBorrowUnitPrice, uint256 referenceUnitPrice)
    {
        referenceUnitPrice = _getOrderBook(_orderBookId).getBlockUnitPriceAverage(3, false);
        maxLendUnitPrice = OrderBookLib.calculateLendCircuitBreakerThreshold(
            referenceUnitPrice,
            Storage.slot().circuitBreakerLimitRange
        );
        minBorrowUnitPrice = OrderBookLib.calculateBorrowCircuitBreakerThreshold(
            referenceUnitPrice,
            Storage.slot().circuitBreakerLimitRange
        );
    }

    function getBestLendUnitPrice(uint8 _orderBookId) public view returns (uint256) {
        return _getOrderBook(_orderBookId).getBestLendUnitPrice();
    }

    function getBestLendUnitPrices(
        uint8[] memory _orderBookIds
    ) external view returns (uint256[] memory unitPrices) {
        unitPrices = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            unitPrices[i] = _getOrderBook(_orderBookIds[i]).getBestLendUnitPrice();
        }
    }

    function getBestBorrowUnitPrice(uint8 _orderBookId) public view returns (uint256) {
        return _getOrderBook(_orderBookId).getBestBorrowUnitPrice();
    }

    function getBestBorrowUnitPrices(
        uint8[] memory _orderBookIds
    ) external view returns (uint256[] memory unitPrices) {
        unitPrices = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            unitPrices[i] = _getOrderBook(_orderBookIds[i]).getBestBorrowUnitPrice();
        }
    }

    function getBorrowOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return _getOrderBook(_orderBookId).getBorrowOrderBook(_start, _limit);
    }

    function getLendOrderBook(
        uint8 _orderBookId,
        uint256 _start,
        uint256 _limit
    )
        external
        view
        returns (
            uint256[] memory unitPrices,
            uint256[] memory amounts,
            uint256[] memory quantities,
            uint256 next
        )
    {
        return _getOrderBook(_orderBookId).getLendOrderBook(_start, _limit);
    }

    function getItayoseEstimation(
        uint8 _orderBookId
    )
        external
        view
        returns (
            uint256 openingUnitPrice,
            uint256 lastLendUnitPrice,
            uint256 lastBorrowUnitPrice,
            uint256 totalOffsetAmount
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];

        if (process.isInProgress) {
            ItayoseLog storage log = Storage.slot().itayoseLogs[orderBook.maturity];
            return (
                log.openingUnitPrice,
                log.lastLendUnitPrice,
                log.lastBorrowUnitPrice,
                process.totalOffsetAmount
            );
        }

        return orderBook.calculateItayoseResult();
    }

    function getItayoseProcessStatus(
        uint8 _orderBookId
    ) external view returns (ItayoseProcessStatus memory status) {
        return _getItayoseProcessStatus(_getOrderBook(_orderBookId));
    }

    function getMaturities(
        uint8[] memory _orderBookIds
    ) public view returns (uint256[] memory maturities) {
        maturities = new uint256[](_orderBookIds.length);

        for (uint256 i; i < _orderBookIds.length; i++) {
            maturities[i] = _getOrderBook(_orderBookIds[i]).maturity;
        }
    }

    function updateOrderFeeRate(uint256 _orderFeeRate) external {
        if (_orderFeeRate >= Constants.PCT_DIGIT) revert InvalidOrderFeeRate();

        uint256 previousRate = Storage.slot().orderFeeRate;

        if (_orderFeeRate != previousRate) {
            Storage.slot().orderFeeRate = _orderFeeRate;

            emit OrderFeeRateUpdated(Storage.slot().ccy, previousRate, _orderFeeRate);
        }
    }

    function updateCircuitBreakerLimitRange(uint256 _cbLimitRange) external {
        if (_cbLimitRange >= Constants.PCT_DIGIT) revert InvalidCircuitBreakerLimitRange();

        uint256 previousRange = Storage.slot().circuitBreakerLimitRange;

        if (_cbLimitRange != previousRange) {
            Storage.slot().circuitBreakerLimitRange = _cbLimitRange;

            emit CircuitBreakerLimitRangeUpdated(Storage.slot().ccy, previousRange, _cbLimitRange);
        }
    }

    function updateMinPreOrderAmount(uint256 _minPreOrderAmount) external {
        uint256 previousAmount = Storage.slot().minPreOrderAmount;
        Storage.slot().minPreOrderAmount = _minPreOrderAmount;

        emit MinPreOrderAmountUpdated(Storage.slot().ccy, previousAmount, _minPreOrderAmount);
    }

    function createOrderBook(
        uint256 _maturity,
        uint256 _openingDate,
        uint256 _preOpeningDate
    ) public returns (uint8 orderBookId) {
        orderBookId = _nextOrderBookId();

        Storage.slot().isReady[_maturity] = _getOrderBook(orderBookId).initialize(
            _maturity,
            _openingDate,
            _preOpeningDate
        );

        emit OrderBookCreated(orderBookId, _maturity, _openingDate);
    }

    function executeAutoRoll(
        uint8 _maturedOrderBookId,
        uint8 _destinationOrderBookId,
        uint256 _autoRollUnitPrice
    ) external {
        OrderBookLib.OrderBook storage maturedOrderBook = Storage.slot().orderBooks[
            _maturedOrderBookId
        ];

        if (!maturedOrderBook.isMatured()) revert OrderBookNotMatured();

        OrderBookLib.OrderBook storage destinationOrderBook = Storage.slot().orderBooks[
            _destinationOrderBookId
        ];

        // NOTE: The auto-roll destination order book has no market unit price if the order has never been filled before.
        // In this case, the market unit price is updated with the unit price of the auto-roll.
        if (destinationOrderBook.getMarketUnitPrice(false) == 0) {
            destinationOrderBook.setInitialBlockUnitPrice(_autoRollUnitPrice);
        }
    }

    function initializeItayose(uint8 _orderBookId) external returns (ItayoseProcessStatus memory) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 maturity = orderBook.maturity;
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[maturity];

        if (process.isInProgress || Storage.slot().isReady[maturity]) {
            revert ItayoseProcessAlreadyInitialized();
        }

        ItayoseLog memory log;
        (
            log.openingUnitPrice,
            log.lastLendUnitPrice,
            log.lastBorrowUnitPrice,
            process.totalOffsetAmount
        ) = orderBook.calculateItayoseResult();

        process.isInProgress = true;
        process.remainingLendOffsetAmount = process.totalOffsetAmount;
        process.remainingBorrowOffsetAmount = process.totalOffsetAmount;
        Storage.slot().itayoseLogs[maturity] = log;

        if (process.totalOffsetAmount > 0) {
            orderBook.setInitialBlockUnitPrice(log.openingUnitPrice);
        }

        return _getItayoseProcessStatus(orderBook);
    }

    function executeItayoseSettlement(
        uint8 _orderBookId
    ) external returns (ItayoseSettlementResult memory result) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];

        if (!process.isInProgress) revert ItayoseProcessNotInitialized();

        if (process.remainingBorrowOffsetAmount > 0) {
            // fillOrders receives the taker side. LEND therefore settles BORROW makers.
            result = _settleItayoseSide(orderBook, process, ProtocolTypes.Side.LEND);
        } else if (process.remainingLendOffsetAmount > 0) {
            // fillOrders receives the taker side. BORROW therefore settles LEND makers.
            result = _settleItayoseSide(orderBook, process, ProtocolTypes.Side.BORROW);
        } else {
            revert ItayoseSettlementAlreadyCompleted();
        }

        result.remainingLendOffsetAmount = process.remainingLendOffsetAmount;
        result.remainingBorrowOffsetAmount = process.remainingBorrowOffsetAmount;
    }

    function finalizeItayose(
        uint8 _orderBookId
    ) external returns (ItayoseFinalizeResult memory result) {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        uint256 maturity = orderBook.maturity;
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[maturity];

        if (!process.isInProgress) revert ItayoseProcessNotInitialized();
        if (process.remainingLendOffsetAmount != 0 || process.remainingBorrowOffsetAmount != 0)
            revert ItayoseProcessNotFinalizable();

        ItayoseLog storage log = Storage.slot().itayoseLogs[maturity];
        result.openingUnitPrice = log.openingUnitPrice;
        result.totalOffsetAmount = process.totalOffsetAmount;
        result.openingDate = orderBook.openingDate;

        Storage.slot().isReady[maturity] = true;
        process.isInProgress = false;

        if (process.totalOffsetAmount > 0) {
            emit ItayoseExecuted(
                Storage.slot().ccy,
                maturity,
                log.openingUnitPrice,
                log.lastLendUnitPrice,
                log.lastBorrowUnitPrice,
                process.totalOffsetAmount
            );
        }
    }

    function _settleItayoseSide(
        OrderBookLib.OrderBook storage orderBook,
        ItayoseProcess storage process,
        ProtocolTypes.Side takerSide
    ) private returns (ItayoseSettlementResult memory result) {
        uint256 remainingOffsetAmount = takerSide == ProtocolTypes.Side.LEND
            ? process.remainingBorrowOffsetAmount
            : process.remainingLendOffsetAmount;
        uint256 boundaryUnitPrice = orderBook.getItayoseBoundaryUnitPrice(
            takerSide,
            MAX_ITAYOSE_PRICE_LEVELS_PER_CALL
        );

        FilledOrder memory filledOrder;
        (filledOrder, result.partiallyFilledOrder, , ) = orderBook.fillOrders(
            takerSide,
            remainingOffsetAmount,
            0,
            boundaryUnitPrice
        );

        if (filledOrder.amount == 0) revert ItayoseSettlementDidNotProgress();

        remainingOffsetAmount -= filledOrder.amount;
        if (
            remainingOffsetAmount > 0 &&
            (result.partiallyFilledOrder.orderId != 0 ||
                result.partiallyFilledOrder.maker != address(0) ||
                result.partiallyFilledOrder.amount != 0 ||
                result.partiallyFilledOrder.futureValue != 0)
        ) revert UnexpectedPartialFill();

        if (takerSide == ProtocolTypes.Side.LEND) {
            process.remainingBorrowOffsetAmount = remainingOffsetAmount;
        } else {
            process.remainingLendOffsetAmount = remainingOffsetAmount;
        }

        result.makerSide = takerSide == ProtocolTypes.Side.LEND
            ? ProtocolTypes.Side.BORROW
            : ProtocolTypes.Side.LEND;
        result.batchFilledAmount = filledOrder.amount;
    }

    function _getItayoseProcessStatus(
        OrderBookLib.OrderBook storage orderBook
    ) private view returns (ItayoseProcessStatus memory status) {
        ItayoseProcess storage process = Storage.slot().itayoseProcesses[orderBook.maturity];
        ItayoseLog storage log = Storage.slot().itayoseLogs[orderBook.maturity];

        status.openingUnitPrice = log.openingUnitPrice;
        status.lastLendUnitPrice = log.lastLendUnitPrice;
        status.lastBorrowUnitPrice = log.lastBorrowUnitPrice;
        status.totalOffsetAmount = process.totalOffsetAmount;
        status.remainingLendOffsetAmount = process.remainingLendOffsetAmount;
        status.remainingBorrowOffsetAmount = process.remainingBorrowOffsetAmount;
        status.isInProgress = process.isInProgress;
        status.isFinalizable =
            process.isInProgress &&
            process.remainingLendOffsetAmount == 0 &&
            process.remainingBorrowOffsetAmount == 0;
        status.isReady = Storage.slot().isReady[orderBook.maturity];
    }

    function _nextOrderBookId() internal returns (uint8) {
        // NOTE: Originally, matured ordebooks were reused as new orderbooks after auto-rolls, but this reusing logic has been removed.
        // This means that `orderBookId` is increased in proportion to the number of auto-rolls executed. To avoid overflow of `orderBookId`,
        // `orderBookId` circulate between 1 and 255.
        if (Storage.slot().lastOrderBookId == type(uint8).max) {
            Storage.slot().lastOrderBookId = 1;
        } else {
            Storage.slot().lastOrderBookId++;
        }
        return Storage.slot().lastOrderBookId;
    }

    function _getOrderBook(
        uint8 _orderBookId
    ) private view returns (OrderBookLib.OrderBook storage) {
        return Storage.slot().orderBooks[_orderBookId];
    }
}

contracts/protocol/libraries/logics/OrderReaderLogic.sol

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

import {Constants} from "../Constants.sol";
import {OrderBookLib, PlacedOrder} from "../OrderBookLib.sol";
import {ProtocolTypes} from "../../types/ProtocolTypes.sol";
import {LendingMarketStorage as Storage, ItayoseLog} from "../../storages/LendingMarketStorage.sol";
import {OrderStatisticsTreeLib} from "../OrderStatisticsTreeLib.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";

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

    function getOrder(
        uint8 _orderBookId,
        uint48 _orderId
    )
        external
        view
        returns (
            ProtocolTypes.Side side,
            uint256 unitPrice,
            uint256 maturity,
            address maker,
            uint256 amount,
            uint256 timestamp,
            bool isPreOrder
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);
        PlacedOrder memory order = orderBook.getOrder(_orderId);

        if (order.side == ProtocolTypes.Side.LEND) {
            (maker, amount) = orderBook.lendOrders[order.maturity].getOrderById(
                order.unitPrice,
                _orderId
            );
        } else {
            (maker, amount) = orderBook.borrowOrders[order.maturity].getOrderById(
                order.unitPrice,
                _orderId
            );
        }

        if (maker != address(0)) {
            side = order.side;
            maturity = order.maturity;
            timestamp = order.timestamp;
            isPreOrder = orderBook.isPreOrder[_orderId];
            unitPrice = _getOrderUnitPrice(side, maturity, order.unitPrice, isPreOrder);
        }
    }

    function getTotalAmountFromLendOrders(
        uint8 _orderBookId,
        address _user
    )
        external
        view
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) = orderBook
            .getLendOrderIds(_user);
        maturity = orderBook.userCurrentMaturities[_user];

        for (uint256 i; i < activeOrderIds.length; ) {
            PlacedOrder memory order = orderBook.getOrder(activeOrderIds[i]);
            // Sum future values in the current maturity.
            // If the market is rotated and maturity is updated, it will be 0 by treating it
            // as an order canceled in the past market.
            (, uint256 orderAmount) = orderBook.lendOrders[orderBook.maturity].getOrderById(
                order.unitPrice,
                activeOrderIds[i]
            );
            activeAmount += orderAmount;

            unchecked {
                i++;
            }
        }

        for (uint256 i; i < inActiveOrderIds.length; ) {
            // Sum future values in the maturity of orders.
            // It will be the future value when the order is created, even if the market is rotated
            // and maturity is updated.
            (uint256 presentValue, uint256 futureValue) = getLendOrderAmounts(
                orderBook,
                inActiveOrderIds[i]
            );
            inactiveAmount += presentValue;
            inactiveFutureValue += futureValue;

            unchecked {
                i++;
            }
        }
    }

    function getTotalAmountFromBorrowOrders(
        uint8 _orderBookId,
        address _user,
        uint256 _minUnitPrice
    )
        external
        view
        returns (
            uint256 activeAmount,
            uint256 inactiveAmount,
            uint256 inactiveFutureValue,
            uint256 maturity
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) = orderBook
            .getBorrowOrderIds(_user);
        maturity = orderBook.userCurrentMaturities[_user];

        for (uint256 i; i < activeOrderIds.length; ) {
            // Sum future values in the current maturity.
            // If the market is rotated and maturity is updated, it will be 0 by treating it
            // as an order canceled in the past market.
            (uint256 presentValue, uint256 futureValue, uint256 unitPrice) = getBorrowOrderAmounts(
                orderBook,
                activeOrderIds[i]
            );

            activeAmount += unitPrice >= _minUnitPrice
                ? presentValue
                : (futureValue * _minUnitPrice).div(Constants.PRICE_DIGIT);

            unchecked {
                i++;
            }
        }

        for (uint256 i; i < inActiveOrderIds.length; ) {
            // Sum future values in the maturity of orders
            // It will be the future value when the order is created, even if the market is rotated
            // and maturity is updated.
            (uint256 presentValue, uint256 futureValue, ) = getBorrowOrderAmounts(
                orderBook,
                inActiveOrderIds[i]
            );

            inactiveAmount += presentValue;
            inactiveFutureValue += futureValue;

            unchecked {
                i++;
            }
        }
    }

    function getLendOrderIds(
        uint8 _orderBookId,
        address _user
    ) external view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) {
        (activeOrderIds, inActiveOrderIds) = _getOrderBook(_orderBookId).getLendOrderIds(_user);
    }

    function getBorrowOrderIds(
        uint8 _orderBookId,
        address _user
    ) external view returns (uint48[] memory activeOrderIds, uint48[] memory inActiveOrderIds) {
        (activeOrderIds, inActiveOrderIds) = _getOrderBook(_orderBookId).getBorrowOrderIds(_user);
    }

    function calculateFilledAmount(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _amount,
        uint256 _unitPrice
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV,
            uint256 placedAmount
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (bool isFilled, uint256 executedUnitPrice, bool ignoreRemainingAmount, ) = orderBook
            .getOrderExecutionConditions(
                _side,
                _unitPrice,
                Storage.slot().circuitBreakerLimitRange,
                true
            );

        if (isFilled) {
            (lastUnitPrice, filledAmount, filledAmountInFV) = orderBook.calculateFilledAmount(
                _side,
                _amount,
                executedUnitPrice
            );
            if (!ignoreRemainingAmount) {
                placedAmount = _amount - filledAmount;
            }
            orderFeeInFV = calculateOrderFeeAmount(orderBook.maturity, filledAmountInFV);
        } else {
            if (!ignoreRemainingAmount) {
                placedAmount = _amount;
            }
        }
    }

    function calculateFilledAmountFromFV(
        uint8 _orderBookId,
        ProtocolTypes.Side _side,
        uint256 _amountInFV
    )
        external
        view
        returns (
            uint256 lastUnitPrice,
            uint256 filledAmount,
            uint256 filledAmountInFV,
            uint256 orderFeeInFV
        )
    {
        OrderBookLib.OrderBook storage orderBook = _getOrderBook(_orderBookId);

        (bool isFilled, uint256 executedUnitPrice, , ) = orderBook.getOrderExecutionConditions(
            _side,
            0,
            Storage.slot().circuitBreakerLimitRange,
            true
        );

        if (isFilled) {
            uint256 amountInFVWithFee = calculateFutureValueWithFee(
                _amountInFV,
                _side,
                orderBook.maturity
            );
            (lastUnitPrice, filledAmount, filledAmountInFV) = orderBook.calculateFilledAmountFromFV(
                _side,
                amountInFVWithFee,
                executedUnitPrice
            );
            orderFeeInFV = calculateOrderFeeAmount(orderBook.maturity, filledAmountInFV);
        }
    }

    function calculateOrderFeeAmount(
        uint256 _maturity,
        uint256 _amount
    ) public view returns (uint256 orderFeeAmount) {
        if (block.timestamp >= _maturity) return 0;

        uint256 currentMaturity = _maturity - block.timestamp;

        // NOTE: The formula is:
        // actualRate = feeRate * (currentMaturity / SECONDS_IN_YEAR)
        // orderFeeAmount = amount * actualRate
        orderFeeAmount = (Storage.slot().orderFeeRate * currentMaturity * _amount).div(
            Constants.SECONDS_IN_YEAR * Constants.PCT_DIGIT
        );
    }

    function calculateFutureValueWithFee(
        uint256 _futureValue,
        ProtocolTypes.Side _side,
        uint256 _maturity
    ) public view returns (uint256 futureValueWithFee) {
        if (block.timestamp >= _maturity) return _futureValue;

        uint256 duration = _maturity - block.timestamp;

        if (_side == ProtocolTypes.Side.BORROW) {
            // To unwind all positions, calculate the future value taking into account
            // the added portion of the fee.
            // NOTE: The formula is:
            // actualRate = feeRate * (duration / SECONDS_IN_YEAR)
            // amount = totalAmountInFV / (1 + actualRate)
            futureValueWithFee = (_futureValue * Constants.SECONDS_IN_YEAR * Constants.PCT_DIGIT)
                .div(
                    Constants.SECONDS_IN_YEAR *
                        Constants.PCT_DIGIT +
                        (Storage.slot().orderFeeRate * duration)
                );
        } else {
            // To unwind all positions, calculate the future value taking into account
            // the subtracted portion of the fee.
            // NOTE: The formula is:
            // actualRate = feeRate * (duration / SECONDS_IN_YEAR)
            // amount = totalAmountInFV / (1 - actualRate)
            futureValueWithFee = (_futureValue * Constants.SECONDS_IN_YEAR * Constants.PCT_DIGIT)
                .div(
                    Constants.SECONDS_IN_YEAR *
                        Constants.PCT_DIGIT -
                        (Storage.slot().orderFeeRate * duration)
                );
        }
    }

    function getLendOrderAmounts(
        OrderBookLib.OrderBook storage orderBook,
        uint48 _orderId
    ) public view returns (uint256 presentValue, uint256 futureValue) {
        PlacedOrder memory order = orderBook.getOrder(_orderId);
        (, uint256 orderAmount) = orderBook.lendOrders[order.maturity].getOrderById(
            order.unitPrice,
            _orderId
        );

        uint256 unitPrice = _getOrderUnitPrice(
            order.side,
            order.maturity,
            order.unitPrice,
            orderBook.isPreOrder[_orderId]
        );

        presentValue = orderAmount;
        futureValue = (orderAmount * Constants.PRICE_DIGIT).div(unitPrice);
    }

    function getBorrowOrderAmounts(
        OrderBookLib.OrderBook storage orderBook,
        uint48 _orderId
    ) public view returns (uint256 presentValue, uint256 futureValue, uint256 unitPrice) {
        PlacedOrder memory order = orderBook.getOrder(_orderId);
        (, uint256 orderAmount) = orderBook.borrowOrders[order.maturity].getOrderById(
            order.unitPrice,
            _orderId
        );
        unitPrice = _getOrderUnitPrice(
            order.side,
            order.maturity,
            order.unitPrice,
            orderBook.isPreOrder[_orderId]
        );

        presentValue = orderAmount;
        futureValue = (orderAmount * Constants.PRICE_DIGIT).div(unitPrice);
    }

    function _getOrderUnitPrice(
        ProtocolTypes.Side _side,
        uint256 _maturity,
        uint256 _unitPrice,
        bool _isPreOrder
    ) private view returns (uint256) {
        if (!_isPreOrder) return _unitPrice;
        ItayoseLog memory itayoseLog = Storage.slot().itayoseLogs[_maturity];
        if (
            itayoseLog.openingUnitPrice != 0 &&
            ((_side == ProtocolTypes.Side.BORROW && _unitPrice <= itayoseLog.lastBorrowUnitPrice) ||
                (_side == ProtocolTypes.Side.LEND && _unitPrice >= itayoseLog.lastLendUnitPrice))
        ) {
            return itayoseLog.openingUnitPrice;
        } else {
            return _unitPrice;
        }
    }

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

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

struct MaturityUnitPrice {
    uint256 unitPrice;
    uint256 compoundFactor;
    uint256 next;
    uint256 prev;
}

struct AutoRollLog {
    uint256 unitPrice;
    uint256 lendingCompoundFactor;
    uint256 borrowingCompoundFactor;
    uint256 next;
    uint256 prev;
}

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

    struct Storage {
        mapping(bytes32 ccy => bool isInitialized) isInitialized;
        mapping(bytes32 ccy => uint256 compoundFactor) initialCompoundFactors;
        mapping(bytes32 ccy => uint256 compoundFactor) lendingCompoundFactors;
        mapping(bytes32 ccy => uint256 compoundFactor) borrowingCompoundFactors;
        mapping(bytes32 ccy => uint256 maturity) currentMaturity;
        mapping(bytes32 ccy => uint8 decimals) decimals;
        mapping(bytes32 ccy => mapping(address user => int256 balance)) balances;
        mapping(bytes32 ccy => uint256 amount) totalLendingSupplies;
        mapping(bytes32 ccy => uint256 amount) totalBorrowingSupplies;
        // Total amount supplied per maturity
        mapping(bytes32 ccy => mapping(uint256 maturity => int256 balance)) maturityBalances;
        mapping(bytes32 ccy => mapping(uint256 maturity => AutoRollLog log)) autoRollLogs;
        // Maturity when the user receives the balance on the target currency
        mapping(bytes32 ccy => mapping(address user => uint256 maturity)) userMaturities;
        mapping(bytes32 ccy => uint256 balance) totalLockedBalances;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/LendingMarketControllerStorage.sol

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

import "../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";

struct ObservationPeriodLog {
    uint256 totalAmount;
    uint256 totalFutureValue;
}

struct TerminationCurrencyCache {
    int256 price;
    uint8 decimals;
}

struct ZCTokenInfo {
    bytes32 ccy;
    uint256 maturity;
}

library LendingMarketControllerStorage {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.UintSet;

    bytes32 internal constant STORAGE_SLOT =
        bytes32(uint256(keccak256("sf.storage.lendingMarketController")) - 1);

    struct Storage {
        uint256 marketBasePeriod;
        uint256 terminationDate;
        mapping(bytes32 ccy => TerminationCurrencyCache currency) terminationCurrencyCaches;
        mapping(bytes32 ccy => uint256 ratio) terminationCollateralRatios;
        mapping(bytes32 ccy => uint8[] orderBookIds) orderBookIdLists;
        mapping(bytes32 ccy => address lendingMarket) lendingMarkets;
        mapping(bytes32 ccy => address futureValueVault) futureValueVaults;
        mapping(bytes32 ccy => uint256 unitPrice) minDebtUnitPrices;
        mapping(bytes32 ccy => uint256 genesisDate) genesisDates;
        mapping(bytes32 ccy => mapping(uint256 maturity => uint256 amount)) pendingOrderAmounts;
        // Order book id history to get order book id from maturity
        mapping(bytes32 ccy => mapping(uint256 maturity => uint8 orderBookIds)) maturityOrderBookIds;
        // List of maturity that the user has open orders or positions
        mapping(bytes32 ccy => mapping(address user => EnumerableSet.UintSet maturities)) usedMaturities;
        // Observation period logs that is used for auto-rolls
        mapping(bytes32 ccy => mapping(uint256 maturity => ObservationPeriodLog log)) observationPeriodLogs;
        // List of currency that the user has open orders or positions
        mapping(address user => EnumerableSet.Bytes32Set currency) usedCurrencies;
        mapping(address user => bool isRedeemed) isRedeemed;
        mapping(bytes32 ccy => mapping(uint256 maturity => address token)) zcTokens;
        mapping(address token => ZCTokenInfo) zcTokenInfo;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/LendingMarketStorage.sol

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

import {OrderBookLib} from "../libraries/OrderBookLib.sol";

struct ItayoseLog {
    uint256 openingUnitPrice;
    uint256 lastLendUnitPrice;
    uint256 lastBorrowUnitPrice;
}

struct ItayoseProcess {
    bool isInProgress;
    uint256 totalOffsetAmount;
    uint256 remainingLendOffsetAmount;
    uint256 remainingBorrowOffsetAmount;
}

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

    struct Storage {
        bytes32 ccy;
        uint8 lastOrderBookId;
        // Order fee rate received by protocol (in basis point)
        uint256 orderFeeRate;
        // Rate limit range of yield for the circuit breaker
        uint256 circuitBreakerLimitRange;
        // Mapping from order book id to order book
        mapping(uint8 orderBookId => OrderBookLib.OrderBook orderBook) orderBooks;
        mapping(uint256 maturity => bool isReady) isReady;
        mapping(uint256 maturity => ItayoseLog log) itayoseLogs;
        mapping(uint256 maturity => ItayoseProcess process) itayoseProcesses;
        // Minimum amount required to place a pre-order. Zero disables the limit.
        uint256 minPreOrderAmount;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/mixins/MixinAddressResolverStorage.sol

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

import {IAddressResolver} from "../../interfaces/IAddressResolver.sol";

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

    struct Storage {
        IAddressResolver resolver;
        mapping(bytes32 contractName => address contractAddress) addressCache;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/storages/utils/PausableStorage.sol

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

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

    struct Storage {
        bool paused;
    }

    function slot() internal pure returns (Storage storage r) {
        bytes32 _slot = STORAGE_SLOT;
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := _slot
        }
    }
}

contracts/protocol/types/ProtocolTypes.sol

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

/**
 * @dev ProtocolTypes is a base-level contract that holds common Secured Finance protocol types
 * @author Secured Finance
 */
library ProtocolTypes {
    enum Side {
        LEND,
        BORROW
    }
}

contracts/protocol/utils/Pausable.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.0;

import "../../dependencies/openzeppelin/utils/Context.sol";
import "../storages/utils/PausableStorage.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return PausableStorage.slot().paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage.slot().paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage.slot().paused = false;
        emit Unpaused(_msgSender());
    }
}

contracts/protocol/utils/Proxyable.sol

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

import "../../dependencies/openzeppelin/utils/StorageSlot.sol";
import "../../dependencies/openzeppelin/proxy/utils/Initializable.sol";

abstract contract Proxyable is Initializable {
    bytes32 internal constant _IMPLEMENTATION_SLOT =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
    bytes32 internal constant _BEACON_SLOT =
        0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    modifier onlyProxy() {
        require(_getImplementation() != address(0), "Must be called from proxy contract");
        _;
    }

    modifier onlyBeacon() {
        require(_getBeacon() != address(0), "Must be called from beacon contract");
        _;
    }

    /**
     * @notice Gets the revision number of the contract
     * @return The revision number
     */
    function getRevision() external pure virtual returns (uint256) {
        return 0x1;
    }

    function _getImplementation() private view returns (address) {
        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    function _getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
    }
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {
    "contracts/protocol/LendingMarket.sol": {
      "OrderBookLogic": "0xc490ec5abcb26f0ba843d2dc85df9d0771563e75",
      "OrderActionLogic": "0x82f2548f7cce40b2c6cf24378fab411c8711f6fe",
      "OrderReaderLogic": "0xd5834764c66e75a8db8ba267e6ee057f67e358ba"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.