Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

LiquidationLogic

Адрес0xb1963d4535e6ffa7a1b4fbef0965f77b93fd93ea
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.19

 

Тот же код

ещё 1 контракт

 

Подробности

Компилятор
solc 0.8.19+commit.7dd6d404
Язык
solidity
Оптимизация
Да, 200 прогонов
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 485 246
Транзакция создания
0x13c79bd5fb…55835eb1c0
Библиотеки
contracts/protocol/libraries/logics/LiquidationLogic.sol:FundManagementLogic0xdcf7…be81bb

31 файл

contracts/protocol/libraries/logics/LiquidationLogic.sol

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

// dependencies
import {SafeCast} from "../../../dependencies/openzeppelin/utils/math/SafeCast.sol";
// interfaces
import {IFutureValueVault} from "../../interfaces/IFutureValueVault.sol";
import {ILiquidationReceiver} from "../../interfaces/ILiquidationReceiver.sol";
// libraries
import {AddressResolverLib} from "../AddressResolverLib.sol";
import {FundManagementLogic} from "./FundManagementLogic.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";
// storages
import {LendingMarketControllerStorage as Storage} from "../../storages/LendingMarketControllerStorage.sol";

library LiquidationLogic {
    using RoundingUint256 for uint256;
    using SafeCast for uint256;
    using SafeCast for int256;

    error NoDebt(address user, bytes32 ccy, uint256 maturity);
    error NoLiquidationAmount(address user, bytes32 ccy);
    error InvalidLiquidation();
    error InvalidCurrency(bytes32 ccy);
    error NotRepaymentPeriod();
    error InsufficientRepayment(
        address executor,
        bytes32 ccy,
        uint256 requiredAmount,
        uint256 untransferredAmount
    );

    struct ExecuteLiquidationVars {
        uint256 liquidationAmountInCollateralCcy;
        uint256 liquidationAmountInDebtCcy;
        uint256 protocolFeeInCollateralCcy;
        uint256 liquidatorFeeInCollateralCcy;
        bool isDefaultMarket;
        uint256 receivedCollateralAmount;
    }

    event LiquidationExecuted(
        address indexed user,
        bytes32 collateralCcy,
        bytes32 indexed debtCcy,
        uint256 indexed debtMaturity,
        uint256 debtAmount
    );

    event ForcedRepaymentExecuted(
        address indexed user,
        bytes32 collateralCcy,
        bytes32 indexed debtCcy,
        uint256 indexed debtMaturity,
        uint256 debtAmount
    );

    function executeLiquidation(
        address _liquidator,
        address _user,
        bytes32 _collateralCcy,
        bytes32 _debtCcy,
        uint256 _debtMaturity
    ) external {
        if (!AddressResolverLib.currencyController().currencyExists(_collateralCcy)) {
            revert InvalidCurrency(_collateralCcy);
        }

        ExecuteLiquidationVars memory vars;

        vars.isDefaultMarket =
            Storage.slot().maturityOrderBookIds[_debtCcy][_debtMaturity] ==
            Storage.slot().orderBookIdLists[_debtCcy][0];

        // In order to liquidate using user collateral, inactive order IDs must be cleaned
        // and converted to actual funds first.
        FundManagementLogic.cleanUpFunds(_collateralCcy, _user);
        FundManagementLogic.cleanUpFunds(_debtCcy, _user);

        uint256 debtAmount = FundManagementLogic
            .getActualFunds(_debtCcy, _debtMaturity, _user, 0, false)
            .debtAmount;

        if (debtAmount == 0) revert NoDebt(_user, _debtCcy, _debtMaturity);

        (
            vars.liquidationAmountInCollateralCcy,
            vars.protocolFeeInCollateralCcy,
            vars.liquidatorFeeInCollateralCcy
        ) = AddressResolverLib.tokenVault().getLiquidationAmount(
            _user,
            _collateralCcy,
            AddressResolverLib.currencyController().convert(_debtCcy, _collateralCcy, debtAmount)
        );

        if (vars.liquidationAmountInCollateralCcy == 0) {
            revert NoLiquidationAmount(_user, _collateralCcy);
        }

        vars.liquidationAmountInDebtCcy = AddressResolverLib.currencyController().convert(
            _collateralCcy,
            _debtCcy,
            vars.liquidationAmountInCollateralCcy
        );

        // Transfer collateral from users to liquidators and reserve funds.
        vars.receivedCollateralAmount =
            vars.liquidationAmountInCollateralCcy +
            vars.liquidatorFeeInCollateralCcy;

        uint256 untransferredAmount = _transferCollateral(
            _user,
            _liquidator,
            _collateralCcy,
            vars.receivedCollateralAmount
        );

        if (untransferredAmount == 0) {
            _transferCollateral(
                _user,
                address(AddressResolverLib.reserveFund()),
                _collateralCcy,
                vars.protocolFeeInCollateralCcy
            );
        } else if (untransferredAmount > 0) {
            (
                uint256 untransferredAmountInDebtCcy,
                uint256 receivedCollateralAmountInDebtCcy,
                uint256 liquidatorFeeInDebtCcy
            ) = _convertLiquidationAmounts(
                    _collateralCcy,
                    _debtCcy,
                    untransferredAmount,
                    vars.receivedCollateralAmount,
                    vars.liquidatorFeeInCollateralCcy
                );

            // Use reserve funds to cover insolvent amounts if user does not have collateral in other currencies.
            if (
                !AddressResolverLib.reserveFund().isPaused() &&
                AddressResolverLib.tokenVault().getTotalCollateralAmount(_user, false) == 0
            ) {
                untransferredAmountInDebtCcy = _transferPositionsPerMaturity(
                    address(AddressResolverLib.reserveFund()),
                    _liquidator,
                    _debtCcy,
                    _debtMaturity,
                    untransferredAmountInDebtCcy.toInt256(),
                    vars.isDefaultMarket
                ).toUint256();
            }

            // Adjust the liquidation amount for debt.
            vars.liquidationAmountInDebtCcy = _calculateTransferredAmount(
                receivedCollateralAmountInDebtCcy,
                untransferredAmountInDebtCcy,
                liquidatorFeeInDebtCcy
            );
        }

        if (_liquidator.code.length > 0) {
            if (
                ILiquidationReceiver(_liquidator).executeOperationForCollateral(
                    _liquidator,
                    _user,
                    _collateralCcy,
                    vars.receivedCollateralAmount - untransferredAmount
                ) == false
            ) revert ILiquidationReceiver.InvalidOperationExecution();
        }

        // Transfer the debt from users to liquidators
        if (vars.liquidationAmountInDebtCcy > 0) {
            _transferPositionsPerMaturity(
                _user,
                _liquidator,
                _debtCcy,
                _debtMaturity,
                -vars.liquidationAmountInDebtCcy.toInt256(),
                vars.isDefaultMarket
            );

            if (_liquidator.code.length > 0) {
                if (
                    ILiquidationReceiver(_liquidator).executeOperationForDebt(
                        _liquidator,
                        _user,
                        _collateralCcy,
                        vars.receivedCollateralAmount - untransferredAmount,
                        _debtCcy,
                        _debtMaturity,
                        vars.liquidationAmountInDebtCcy
                    ) == false
                ) revert ILiquidationReceiver.InvalidOperationExecution();
            }
        }

        (bool isEnoughCollateral, ) = AddressResolverLib.tokenVault().isCovered(
            _liquidator,
            bytes32(0)
        );
        if (!isEnoughCollateral) revert InvalidLiquidation();

        emit LiquidationExecuted(
            _user,
            _collateralCcy,
            _debtCcy,
            _debtMaturity,
            vars.liquidationAmountInDebtCcy
        );
    }

    function executeForcedRepayment(
        address _executor,
        address _user,
        bytes32 _collateralCcy,
        bytes32 _debtCcy,
        uint256 _debtMaturity
    ) external {
        if (
            AddressResolverLib.currencyController().currencyExists(_debtCcy) ||
            block.timestamp < _debtMaturity + 1 weeks
        ) {
            revert NotRepaymentPeriod();
        }

        if (!AddressResolverLib.currencyController().currencyExists(_collateralCcy)) {
            revert InvalidCurrency(_collateralCcy);
        }

        // In order to liquidate using user collateral, inactive order IDs must be cleaned
        // and converted to actual funds first.
        FundManagementLogic.cleanUpFunds(_collateralCcy, _user);
        FundManagementLogic.cleanUpFunds(_debtCcy, _user);

        FundManagementLogic.ActualFunds memory funds = FundManagementLogic.getActualFunds(
            _debtCcy,
            _debtMaturity,
            _user,
            0,
            false
        );

        if (funds.futureValue >= 0) revert NoDebt(_user, _debtCcy, _debtMaturity);

        uint256 liquidationAmountInDebtCcy = (-funds.futureValue).toUint256();
        uint256 liquidationAmountInCollateralCcy = AddressResolverLib.currencyController().convert(
            _debtCcy,
            _collateralCcy,
            liquidationAmountInDebtCcy
        );

        (
            uint256 protocolFeeInCollateralCcy,
            uint256 liquidatorFeeInCollateralCcy
        ) = AddressResolverLib.tokenVault().calculateLiquidationFees(
                liquidationAmountInCollateralCcy
            );

        uint256 receivedCollateralAmount = liquidationAmountInCollateralCcy +
            liquidatorFeeInCollateralCcy;

        uint256 untransferredAmount = _transferCollateral(
            _user,
            _executor,
            _collateralCcy,
            receivedCollateralAmount
        );

        if (untransferredAmount == 0) {
            _transferCollateral(
                _user,
                address(AddressResolverLib.reserveFund()),
                _collateralCcy,
                protocolFeeInCollateralCcy
            );
        } else {
            (
                uint256 untransferredAmountInDebtCcy,
                uint256 receivedCollateralAmountInDebtCcy,
                uint256 liquidatorFeeInDebtCcy
            ) = _convertLiquidationAmounts(
                    _collateralCcy,
                    _debtCcy,
                    untransferredAmount,
                    receivedCollateralAmount,
                    liquidatorFeeInCollateralCcy
                );

            // Adjust the liquidation amount for debt.
            liquidationAmountInDebtCcy = _calculateTransferredAmount(
                receivedCollateralAmountInDebtCcy,
                untransferredAmountInDebtCcy,
                liquidatorFeeInDebtCcy
            );
        }

        if (_executor.code.length > 0) {
            if (
                ILiquidationReceiver(_executor).executeOperationForCollateral(
                    _executor,
                    _user,
                    _collateralCcy,
                    receivedCollateralAmount - untransferredAmount
                ) == false
            ) revert ILiquidationReceiver.InvalidOperationExecution();

            if (
                ILiquidationReceiver(_executor).executeOperationForDebt(
                    _executor,
                    _user,
                    _collateralCcy,
                    receivedCollateralAmount - untransferredAmount,
                    _debtCcy,
                    _debtMaturity,
                    liquidationAmountInDebtCcy
                ) == false
            ) revert ILiquidationReceiver.InvalidOperationExecution();
        }

        untransferredAmount = AddressResolverLib.tokenVault().transferFrom(
            _debtCcy,
            _executor,
            _user,
            liquidationAmountInDebtCcy
        );

        if (untransferredAmount != 0) {
            revert InsufficientRepayment(
                _executor,
                _debtCcy,
                liquidationAmountInDebtCcy,
                untransferredAmount
            );
        }

        uint256 repaymentAmount = FundManagementLogic.executeRepayment(
            _debtCcy,
            _debtMaturity,
            _user,
            liquidationAmountInDebtCcy
        );

        emit ForcedRepaymentExecuted(
            _user,
            _collateralCcy,
            _debtCcy,
            _debtMaturity,
            repaymentAmount
        );
    }

    function _transferCollateral(
        address _from,
        address _to,
        bytes32 _ccy,
        uint256 _amount
    ) internal returns (uint256 untransferredAmount) {
        untransferredAmount = AddressResolverLib.tokenVault().transferFrom(
            _ccy,
            _from,
            _to,
            _amount
        );

        // If `untransferredAmount` is not 0, the user has not enough deposit in the collateral currency.
        // Therefore, the liquidators and the reserve fund obtain zero-coupon bonds instead of the user's collateral.
        if (untransferredAmount > 0) {
            untransferredAmount = _transferPositionsPerCurrency(
                _from,
                _to,
                _ccy,
                untransferredAmount.toInt256()
            ).toUint256();
        }
    }

    function _transferPositionsPerCurrency(
        address _from,
        address _to,
        bytes32 _ccy,
        int256 _amount
    ) internal returns (int256 untransferredAmount) {
        untransferredAmount = _transferGenesisValue(_from, _to, _ccy, _amount);

        uint256[] memory maturities = FundManagementLogic.getUsedMaturities(_ccy, _from);

        for (uint256 i; i < maturities.length; i++) {
            if (untransferredAmount == 0) {
                break;
            }

            untransferredAmount = _transferFutureValues(
                _from,
                _to,
                _ccy,
                maturities[i],
                untransferredAmount
            );
        }
    }

    function _transferPositionsPerMaturity(
        address _from,
        address _to,
        bytes32 _ccy,
        uint256 _maturity,
        int256 _amount,
        bool _isDefaultMarket
    ) internal returns (int256 untransferredAmount) {
        untransferredAmount = _isDefaultMarket
            ? _transferGenesisValue(_from, _to, _ccy, _amount)
            : _amount;

        untransferredAmount = _transferFutureValues(
            _from,
            _to,
            _ccy,
            _maturity,
            untransferredAmount
        );
    }

    function _transferGenesisValue(
        address _from,
        address _to,
        bytes32 _ccy,
        int256 _amount
    ) internal returns (int256 untransferredAmount) {
        untransferredAmount = _amount;
        bool isDebt = _amount < 0;

        int256 userGVAmount = AddressResolverLib.genesisValueVault().getBalance(_ccy, _from, 0);

        if ((isDebt && userGVAmount < 0) || (!isDebt && userGVAmount > 0)) {
            uint256 currentMaturity = AddressResolverLib.genesisValueVault().getCurrentMaturity(
                _ccy
            );

            int256 gvAmount = AddressResolverLib.genesisValueVault().calculateGVFromFV(
                _ccy,
                0,
                FundManagementLogic.calculateFVFromPV(
                    _ccy,
                    currentMaturity,
                    untransferredAmount,
                    false,
                    isDebt
                ),
                isDebt
            );

            if ((isDebt && userGVAmount > gvAmount) || (!isDebt && userGVAmount < gvAmount)) {
                gvAmount = userGVAmount;
            }

            // Due to the negative genesis value, the liquidator's genesis value is decreased.
            AddressResolverLib.genesisValueVault().transferFrom(_ccy, _from, _to, gvAmount);

            untransferredAmount -= FundManagementLogic.calculatePVFromFV(
                _ccy,
                currentMaturity,
                AddressResolverLib.genesisValueVault().calculateFVFromGV(_ccy, 0, gvAmount)
            );

            if ((isDebt && untransferredAmount > 0) || (!isDebt && untransferredAmount < 0)) {
                untransferredAmount = 0;
            }

            FundManagementLogic.registerCurrency(_ccy, _to);
        }
    }

    function _transferFutureValues(
        address _from,
        address _to,
        bytes32 _ccy,
        uint256 _maturity,
        int256 _amount
    ) internal returns (int256 untransferredAmount) {
        untransferredAmount = _amount;
        bool isDebt = _amount < 0;

        IFutureValueVault futureValueVault = IFutureValueVault(
            Storage.slot().futureValueVaults[_ccy]
        );
        uint8 orderBookId = Storage.slot().maturityOrderBookIds[_ccy][_maturity];

        (int256 userFVAmount, ) = futureValueVault.getBalance(orderBookId, _from);

        if ((isDebt && userFVAmount < 0) || (!isDebt && userFVAmount > 0)) {
            int256 fvAmount = FundManagementLogic.calculateFVFromPV(
                _ccy,
                _maturity,
                untransferredAmount,
                false,
                isDebt
            );

            if ((isDebt && userFVAmount > fvAmount) || (!isDebt && userFVAmount < fvAmount)) {
                fvAmount = userFVAmount;
            }

            futureValueVault.transferFrom(orderBookId, _from, _to, fvAmount, _maturity);
            untransferredAmount -= FundManagementLogic.calculatePVFromFV(_ccy, _maturity, fvAmount);

            if ((isDebt && untransferredAmount > 0) || (!isDebt && untransferredAmount < 0)) {
                untransferredAmount = 0;
            }

            FundManagementLogic.registerCurrencyAndMaturity(_ccy, _maturity, _to);
        }
    }

    function _convertLiquidationAmounts(
        bytes32 _collateralCcy,
        bytes32 _debtCcy,
        uint256 _untransferredAmount,
        uint256 _receivedCollateralAmount,
        uint256 _liquidatorFeeInCollateralCcy
    )
        internal
        view
        returns (
            uint256 untransferredAmountInDebtCcy,
            uint256 receivedCollateralAmountInDebtCcy,
            uint256 liquidatorFeeInDebtCcy
        )
    {
        uint256[] memory amountsInCollateralCcy = new uint256[](3);
        amountsInCollateralCcy[0] = _untransferredAmount;
        amountsInCollateralCcy[1] = _receivedCollateralAmount;
        amountsInCollateralCcy[2] = _liquidatorFeeInCollateralCcy;

        uint256[] memory amountsInDebtCcy = AddressResolverLib.currencyController().convert(
            _collateralCcy,
            _debtCcy,
            amountsInCollateralCcy
        );

        untransferredAmountInDebtCcy = amountsInDebtCcy[0];
        receivedCollateralAmountInDebtCcy = amountsInDebtCcy[1];
        liquidatorFeeInDebtCcy = amountsInDebtCcy[2];
    }

    function _calculateTransferredAmount(
        uint256 totalAmount,
        uint256 untransferredAmount,
        uint256 feeAmount
    ) internal pure returns (uint256) {
        // NOTE: The formula is:
        // transferredTotalAmount = totalAmount - untransferredAmount;
        // untransferredFeeAmount = feeAmount * (transferredTotalAmount / totalAmount);
        uint256 transferredTotalAmount = totalAmount - untransferredAmount;
        uint256 untransferredFeeAmount = (feeAmount * transferredTotalAmount).div(totalAmount);

        return transferredTotalAmount - untransferredFeeAmount;
    }
}

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

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

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

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

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

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

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

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

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

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

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

contracts/protocol/interfaces/IAddressResolver.sol

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

interface IAddressResolver {
    error UnmatchedInputs();

    event AddressImported(bytes32 name, address destination);

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

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

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

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

contracts/protocol/interfaces/IBeaconProxyController.sol

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

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

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

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

    function setFutureValueVaultImpl(address newImpl) external;

    function setLendingMarketImpl(address newImpl) external;

    function setZCTokenImpl(address newImpl) external;

    function deployFutureValueVault() external returns (address futureValueVault);

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

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

contracts/protocol/interfaces/ICurrencyController.sol

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

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

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

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

    event HaircutUpdated(bytes32 indexed ccy, uint256 haircut);

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

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

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

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

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

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

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

    function convertFromBaseCurrency(
        bytes32 _ccy,
        uint256 _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/IFutureValueVault.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function executeForcedReset(uint8 orderBookId, address user) external;

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

contracts/protocol/interfaces/IGenesisValueVault.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function 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/ILiquidationReceiver.sol

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

interface ILiquidationReceiver {
    error InvalidOperationExecution();

    event OperationExecuteForCollateral(
        address liquidator,
        address user,
        bytes32 ccy,
        uint256 receivedAmount
    );
    event OperationExecuteForDebt(
        address liquidator,
        address user,
        bytes32 collateralCcy,
        uint256 receivedCollateralAmount,
        bytes32 debtCcy,
        uint256 debtMaturity,
        uint256 receivedDebtAmount
    );

    function executeOperationForCollateral(
        address liquidator,
        address user,
        bytes32 ccy,
        uint256 receivedAmount
    ) external returns (bool);

    function executeOperationForDebt(
        address liquidator,
        address user,
        bytes32 collateralCcy,
        uint256 receivedCollateralAmount,
        bytes32 debtCcy,
        uint256 debtMaturity,
        uint256 receivedDebtAmount
    ) external returns (bool);
}

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

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

library QuickSort {
    function sort(uint256[] memory data) public pure returns (uint256[] memory) {
        quickSort(data, int256(0), int256(data.length - 1));
        return data;
    }

    function quickSort(uint256[] memory arr, int256 left, int256 right) internal pure {
        int256 i = left;
        int256 j = right;
        if (i == j) return;
        uint256 pivot = arr[uint256(left + (right - left) / 2)];
        while (i <= j) {
            while (arr[uint256(i)] < pivot) i++;
            while (pivot < arr[uint256(j)]) j--;
            if (i <= j) {
                (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]);
                i++;
                j--;
            }
        }
        if (left < j) quickSort(arr, left, j);
        if (i < right) quickSort(arr, i, right);
    }
}

contracts/protocol/libraries/logics/FundManagementLogic.sol

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

// dependencies
import {EnumerableSet} from "../../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";
import {SafeCast} from "../../../dependencies/openzeppelin/utils/math/SafeCast.sol";
import {Math} from "../../../dependencies/openzeppelin/utils/math/Math.sol";
// interfaces
import {ILendingMarket} from "../../interfaces/ILendingMarket.sol";
import {ILendingMarketController} from "../../interfaces/ILendingMarketController.sol";
import {IFutureValueVault} from "../../interfaces/IFutureValueVault.sol";
import {IGenesisValueVault} from "../../interfaces/IGenesisValueVault.sol";
import {ILiquidationReceiver} from "../../interfaces/ILiquidationReceiver.sol";

// libraries
import {AddressResolverLib} from "../AddressResolverLib.sol";
import {QuickSort} from "../QuickSort.sol";
import {Constants} from "../Constants.sol";
import {PartiallyFilledOrder} from "../OrderBookLib.sol";
import {RoundingUint256} from "../math/RoundingUint256.sol";
import {RoundingInt256} from "../math/RoundingInt256.sol";
// types
import {ProtocolTypes} from "../../types/ProtocolTypes.sol";
// storages
import {LendingMarketControllerStorage as Storage, TerminationCurrencyCache} from "../../storages/LendingMarketControllerStorage.sol";

library FundManagementLogic {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.UintSet;
    using SafeCast for uint256;
    using SafeCast for int256;
    using RoundingUint256 for uint256;
    using RoundingInt256 for int256;

    uint256 public constant BASE_MIN_DEBT_UNIT_PRICE = 9600;
    uint256 public constant MAX_EXPOSURE_CURRENCIES = 5;

    error NotRedemptionPeriod();
    error NotRepaymentPeriod();
    error NoRedemptionAmount();
    error NoRepaymentAmount();
    error AlreadyRedeemed();
    error InsufficientCollateral();
    error TooManyExposureCurrencies();
    error ProtocolIsInsolvent();
    error InvalidFutureValueMaturity(
        uint8 orderBookId,
        uint256 expectedMaturity,
        uint256 actualMaturity
    );

    struct CalculatedTotalFundInBaseCurrencyVars {
        address user;
        ILendingMarketController.AdditionalFunds additionalFunds;
        uint256 liquidationThresholdRate;
        bool[] isCollateral;
        bytes32[] ccys;
    }

    struct ActualFunds {
        int256 presentValue;
        uint256 claimableAmount;
        uint256 debtAmount;
        int256 futureValue;
        uint256 workingLendOrdersAmount;
        uint256 lentAmount;
        uint256 workingBorrowOrdersAmount;
        uint256 borrowedAmount;
        int256 genesisValue;
        int256 genesisValueInPV;
        int256 genesisValueInFV;
    }

    struct CalculateActualFundsVars {
        bool isTotal;
        bool isDefaultMarket;
        uint8 orderBookId;
        uint8 defaultOrderBookId;
        uint256[] maturities;
        int256 presentValueOfDefaultMarket;
        ILendingMarket market;
        IFutureValueVault futureValueVault;
        uint256 minDebtUnitPrice;
        bool useConservativePrice;
    }

    struct PositionFunds {
        int256 genesisValue;
        int256 presentValue;
        int256 futureValue;
        uint256 workingBorrowOrdersAmount;
        uint256 workingLendOrdersAmount;
        uint256 borrowedAmount;
        uint256 lentAmount;
    }

    event OrderFilled(
        address indexed taker,
        bytes32 indexed ccy,
        ProtocolTypes.Side side,
        uint256 indexed maturity,
        uint256 amount,
        uint256 amountInFV,
        uint256 feeInFV
    );

    event OrdersFilledInAsync(
        address indexed taker,
        bytes32 indexed ccy,
        ProtocolTypes.Side side,
        uint256 indexed maturity,
        uint256 amount,
        uint256 amountInFV
    );

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

    event RedemptionExecuted(
        address indexed user,
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 amount
    );

    event RepaymentExecuted(
        address indexed user,
        bytes32 indexed ccy,
        uint256 indexed maturity,
        uint256 amount
    );

    event EmergencySettlementExecuted(address indexed user, uint256 amount);

    /**
     * @notice Converts the future value to the genesis value if there is balance in the past maturity.
     * @param _ccy Currency for pausing all lending markets
     * @param _user User's address
     * @return Current future value amount after update
     */
    function convertFutureValueToGenesisValue(
        bytes32 _ccy,
        uint8 _orderBookId,
        uint256 _maturity,
        address _user
    ) public returns (int256) {
        address futureValueVault = Storage.slot().futureValueVaults[_ccy];
        bool isAutoRolled = AddressResolverLib.genesisValueVault().isAutoRolled(_ccy, _maturity);

        if (!isAutoRolled) {
            (int256 amount, ) = IFutureValueVault(futureValueVault).getBalance(_orderBookId, _user);
            return amount;
        }

        (
            int256 removedAmount,
            int256 currentAmount,
            uint256 basisMaturity,
            bool isAllRemoved
        ) = IFutureValueVault(futureValueVault).reset(_orderBookId, _user);

        if (removedAmount != 0) {
            // Overwrite the `removedAmount` with the unsettled amount left of the Genesis Value
            // to handle the fractional amount generated by the lazy evaluation when the user is
            // the last user who is converting their own future value in the selected maturity.
            if (isAllRemoved && Storage.slot().pendingOrderAmounts[_ccy][basisMaturity] == 0) {
                AddressResolverLib.genesisValueVault().updateGenesisValueWithResidualAmount(
                    _ccy,
                    _user,
                    basisMaturity
                );
            } else {
                AddressResolverLib.genesisValueVault().updateGenesisValueWithFutureValue(
                    _ccy,
                    _user,
                    basisMaturity,
                    removedAmount
                );
            }
        }

        return currentAmount;
    }

    function _updateFunds(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        ProtocolTypes.Side _side,
        uint256 _filledAmount,
        uint256 _filledAmountInFV,
        uint256 _feeInFV
    ) private {
        address futureValueVault = Storage.slot().futureValueVaults[_ccy];
        uint8 orderBookId = Storage.slot().maturityOrderBookIds[_ccy][_maturity];

        if (_side == ProtocolTypes.Side.BORROW) {
            AddressResolverLib.tokenVault().addDepositAmount(_user, _ccy, _filledAmount);
            IFutureValueVault(futureValueVault).decrease(
                orderBookId,
                _user,
                _filledAmountInFV + _feeInFV,
                _maturity
            );
        } else {
            AddressResolverLib.tokenVault().removeDepositAmount(_user, _ccy, _filledAmount);
            IFutureValueVault(futureValueVault).increase(
                orderBookId,
                _user,
                _filledAmountInFV - _feeInFV,
                _maturity
            );
        }

        if (_feeInFV > 0) {
            address reserveFundAddr = address(AddressResolverLib.reserveFund());
            IFutureValueVault(futureValueVault).increase(
                orderBookId,
                reserveFundAddr,
                _feeInFV,
                _maturity
            );

            // NOTE: Register without checking `MAX_EXPOSURE_CURRENCIES` to ensure that ReserveFund always receives fees.
            // en: By skipping the check of `MAX_EXPOSURE_CURRENCIES`, it is expected that the gas cost will increase
            // due to the increase of `usedCurrencies`, but since the `cleanUpFunds` function is called for ReserveFund
            // every time the `rotateOrderBooks` function is called, the increase in gas cost is limited.
            if (Storage.slot().usedMaturities[_ccy][reserveFundAddr].add(_maturity)) {
                Storage.slot().usedCurrencies[reserveFundAddr].add(_ccy);
            }
        }
    }

    function updateFundsForTaker(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        ProtocolTypes.Side _side,
        uint256 _filledAmount,
        uint256 _filledAmountInFV,
        uint256 _feeInFV
    ) public returns (bool updated) {
        if (_filledAmountInFV == 0) return false;

        _updateFunds(_ccy, _maturity, _user, _side, _filledAmount, _filledAmountInFV, _feeInFV);

        emit OrderFilled(_user, _ccy, _side, _maturity, _filledAmount, _filledAmountInFV, _feeInFV);
        return true;
    }

    function updateFundsForMaker(
        bytes32 _ccy,
        uint256 _maturity,
        ProtocolTypes.Side _side,
        PartiallyFilledOrder memory _partiallyFilledOrder
    ) public {
        if (_partiallyFilledOrder.futureValue == 0) return;

        _updateFunds(
            _ccy,
            _maturity,
            _partiallyFilledOrder.maker,
            _side,
            _partiallyFilledOrder.amount,
            _partiallyFilledOrder.futureValue,
            0
        );

        emit OrderPartiallyFilled(
            _partiallyFilledOrder.orderId,
            _partiallyFilledOrder.maker,
            _ccy,
            _side,
            _maturity,
            _partiallyFilledOrder.amount,
            _partiallyFilledOrder.futureValue
        );
    }

    function registerCurrencyAndMaturity(
        bytes32 _ccy,
        uint256 _maturity,
        address _user
    ) public returns (bool isNewCurrency) {
        if (Storage.slot().usedMaturities[_ccy][_user].add(_maturity)) {
            return registerCurrency(_ccy, _user);
        }
        return false;
    }

    function registerCurrency(bytes32 _ccy, address _user) public returns (bool isNewCurrency) {
        EnumerableSet.Bytes32Set storage currencySet = Storage.slot().usedCurrencies[_user];
        if (!currencySet.contains(_ccy)) {
            if (currencySet.length() >= MAX_EXPOSURE_CURRENCIES) {
                revert TooManyExposureCurrencies();
            }

            currencySet.add(_ccy);
            return true;
        }
        return false;
    }

    function executeRedemption(bytes32 _ccy, uint256 _maturity, address _user) external {
        if (
            AddressResolverLib.currencyController().currencyExists(_ccy) ||
            block.timestamp < _maturity + 1 weeks
        ) revert NotRedemptionPeriod();

        cleanUpFunds(_ccy, _user);

        int256 amount = getActualFunds(_ccy, _maturity, _user, 0, false).futureValue;
        if (amount <= 0) revert NoRedemptionAmount();

        uint256 redemptionAmount = _resetFundsPerMaturity(_ccy, _maturity, _user, amount)
            .toUint256();
        AddressResolverLib.tokenVault().addDepositAmount(_user, _ccy, redemptionAmount);

        emit RedemptionExecuted(_user, _ccy, _maturity, redemptionAmount);
    }

    function executeRepayment(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        uint256 _amount
    ) public returns (uint256 repaymentAmount) {
        if (
            AddressResolverLib.currencyController().currencyExists(_ccy) ||
            block.timestamp < _maturity
        ) revert NotRepaymentPeriod();

        cleanUpFunds(_ccy, _user);

        int256 resetAmount = _amount == 0
            ? getActualFunds(_ccy, _maturity, _user, 0, false).futureValue
            : -_amount.toInt256();

        if (resetAmount >= 0) revert NoRepaymentAmount();

        repaymentAmount = (-_resetFundsPerMaturity(_ccy, _maturity, _user, resetAmount))
            .toUint256();
        AddressResolverLib.tokenVault().removeDepositAmount(_user, _ccy, repaymentAmount);

        emit RepaymentExecuted(_user, _ccy, _maturity, repaymentAmount);
    }

    function executeEmergencySettlement(address _user) external {
        if (Storage.slot().isRedeemed[_user]) revert AlreadyRedeemed();

        int256 redemptionAmountInBaseCurrency;

        bytes32[] memory currencies = Storage.slot().usedCurrencies[_user].values();

        for (uint256 i; i < currencies.length; i++) {
            bytes32 ccy = currencies[i];
            // First, clean up future values and genesis values to redeem those amounts.
            cleanUpFunds(ccy, _user);

            int256 amountInCcy = _resetFundsPerCurrency(ccy, _user);
            redemptionAmountInBaseCurrency += _convertToBaseCurrencyAtMarketTerminationPrice(
                ccy,
                amountInCcy
            );
        }

        bytes32[] memory collateralCurrencies = AddressResolverLib
            .tokenVault()
            .getCollateralCurrencies();

        for (uint256 i; i < collateralCurrencies.length; i++) {
            int256 amountInCcy = AddressResolverLib
                .tokenVault()
                .executeForcedReset(_user, collateralCurrencies[i])
                .toInt256();

            redemptionAmountInBaseCurrency += _convertToBaseCurrencyAtMarketTerminationPrice(
                collateralCurrencies[i],
                amountInCcy
            );
        }

        if (redemptionAmountInBaseCurrency > 0) {
            uint256[] memory terminationCollateralRatios = new uint256[](
                collateralCurrencies.length
            );
            uint256 terminationRatioTotal;

            for (uint256 i; i < collateralCurrencies.length; i++) {
                bytes32 ccy = collateralCurrencies[i];
                terminationCollateralRatios[i] = Storage.slot().terminationCollateralRatios[ccy];
                terminationRatioTotal += terminationCollateralRatios[i];
            }

            // If all collateral ratios are zero, the protocol is completely insolvent
            if (terminationRatioTotal == 0) {
                revert ProtocolIsInsolvent();
            }

            for (uint256 i; i < collateralCurrencies.length; i++) {
                bytes32 ccy = collateralCurrencies[i];
                uint256 addedAmount = _convertFromBaseCurrencyAtMarketTerminationPrice(
                    ccy,
                    (redemptionAmountInBaseCurrency.toUint256() * terminationCollateralRatios[i])
                        .div(terminationRatioTotal)
                );

                AddressResolverLib.tokenVault().addDepositAmount(_user, ccy, addedAmount);
            }
        } else if (redemptionAmountInBaseCurrency < 0) {
            revert InsufficientCollateral();
        }

        Storage.slot().isRedeemed[_user] = true;
        emit EmergencySettlementExecuted(_user, redemptionAmountInBaseCurrency.toUint256());
    }

    function getActualFunds(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        uint256 _minDebtUnitPrice,
        bool _useConservativePrice
    ) public view returns (ActualFunds memory actualFunds) {
        uint8[] memory orderBookIdList = Storage.slot().orderBookIdLists[_ccy];

        // Return empty funds if no order book exists for this currency
        if (orderBookIdList.length == 0) {
            return actualFunds;
        }

        CalculateActualFundsVars memory vars;
        vars.market = ILendingMarket(Storage.slot().lendingMarkets[_ccy]);
        vars.futureValueVault = IFutureValueVault(Storage.slot().futureValueVaults[_ccy]);
        vars.defaultOrderBookId = orderBookIdList[0];
        vars.minDebtUnitPrice = _minDebtUnitPrice;
        vars.useConservativePrice = _useConservativePrice;

        if (_maturity == 0) {
            vars.isTotal = true;
            vars.orderBookId = vars.defaultOrderBookId;
            vars.isDefaultMarket = true;
        } else {
            vars.isTotal = false;
            vars.orderBookId = Storage.slot().maturityOrderBookIds[_ccy][_maturity];
            vars.isDefaultMarket = vars.orderBookId == vars.defaultOrderBookId;
        }

        vars.maturities = getUsedMaturities(_ccy, _user);

        // Get genesis value from Genesis Value Vault including pending fluctuations amount up to the first maturity.
        // The remaining fluctuation amount is calculated in the following loop.
        actualFunds.genesisValue = AddressResolverLib.genesisValueVault().getBalance(
            _ccy,
            _user,
            vars.maturities.length == 0 ? 0 : vars.maturities[0]
        );

        for (uint256 i; i < vars.maturities.length; i++) {
            uint256 currentMaturity = vars.maturities[i];
            uint8 currentOrderBookId = Storage.slot().maturityOrderBookIds[_ccy][currentMaturity];

            if (vars.isDefaultMarket || currentOrderBookId == vars.orderBookId) {
                {
                    bool isDefaultMarket = currentOrderBookId == vars.defaultOrderBookId;

                    PositionFunds memory positionFunds = _getNetPositionFunds(
                        _ccy,
                        _user,
                        vars,
                        currentOrderBookId,
                        currentMaturity
                    );

                    // Set genesis value.
                    actualFunds.genesisValue += positionFunds.genesisValue;

                    // Set present value.
                    int256 presentValue = positionFunds.presentValue;

                    actualFunds.presentValue += presentValue;

                    if (isDefaultMarket) {
                        vars.presentValueOfDefaultMarket = presentValue;
                    }

                    if (presentValue > 0) {
                        actualFunds.claimableAmount += presentValue.toUint256();
                    } else if (presentValue < 0) {
                        actualFunds.debtAmount += (-presentValue).toUint256();
                    }

                    // Set future value.
                    // Note: When calculating total funds, total future value will be 0 because different maturities can not be added.
                    if (!vars.isTotal) {
                        actualFunds.futureValue += positionFunds.futureValue;
                    }

                    actualFunds.workingBorrowOrdersAmount += positionFunds
                        .workingBorrowOrdersAmount;
                    actualFunds.workingLendOrdersAmount += positionFunds.workingLendOrdersAmount;
                    actualFunds.borrowedAmount += positionFunds.borrowedAmount;
                    actualFunds.lentAmount += positionFunds.lentAmount;
                }

                // Get balance fluctuation amount by auto-rolls
                if (actualFunds.genesisValue < 0) {
                    actualFunds.genesisValue += AddressResolverLib
                        .genesisValueVault()
                        .calculateBalanceFluctuationByAutoRolls(
                            _ccy,
                            actualFunds.genesisValue,
                            vars.maturities[i],
                            i == vars.maturities.length - 1 ? 0 : vars.maturities[i + 1]
                        );
                }
            }
        }

        // Add GV to PV & FV if the market is that the lending position is rolled to.
        if (vars.isDefaultMarket && actualFunds.genesisValue != 0) {
            int256 futureValue = AddressResolverLib.genesisValueVault().calculateFVFromGV(
                _ccy,
                0,
                actualFunds.genesisValue
            );

            uint256 unitPrice = getUnitPriceForValuation(
                vars.market,
                vars.useConservativePrice,
                vars.defaultOrderBookId,
                futureValue >= 0
            );
            uint256 defaultOrderBookMinDebtUnitPrice = futureValue < 0 && vars.minDebtUnitPrice != 0
                ? getCurrentMinDebtUnitPrice(
                    vars.market.getMaturity(vars.defaultOrderBookId),
                    vars.minDebtUnitPrice
                )
                : 0;

            int256 presentValue = _calculatePVFromFVWithMinDebtUnitPrice(
                futureValue,
                unitPrice,
                defaultOrderBookMinDebtUnitPrice
            );

            actualFunds.presentValue += presentValue;
            actualFunds.genesisValueInPV = presentValue;

            // Add GV to the claimable amount or debt amount.
            // Before that, offset the present value of the default market and the genesis value in addition.
            if (presentValue > 0) {
                if (vars.presentValueOfDefaultMarket < 0) {
                    int256 offsetAmount = presentValue > -vars.presentValueOfDefaultMarket
                        ? -vars.presentValueOfDefaultMarket
                        : presentValue;
                    actualFunds.debtAmount -= (offsetAmount).toUint256();
                    presentValue -= offsetAmount;
                }

                actualFunds.claimableAmount += presentValue.toUint256();
            } else if (presentValue < 0) {
                if (vars.presentValueOfDefaultMarket > 0) {
                    int256 offsetAmount = -presentValue > vars.presentValueOfDefaultMarket
                        ? vars.presentValueOfDefaultMarket
                        : -presentValue;

                    actualFunds.claimableAmount -= (offsetAmount).toUint256();
                    presentValue += offsetAmount;
                }

                actualFunds.debtAmount += (-presentValue).toUint256();
            }

            actualFunds.genesisValueInFV = futureValue;
            if (!vars.isTotal) {
                actualFunds.futureValue += futureValue;
            }
        }
    }

    function getCurrentMinDebtUnitPrice(
        uint256 _maturity,
        uint256 _minDebtUnitPrice
    ) public view returns (uint256) {
        return getMinDebtUnitPriceAt(_maturity, _minDebtUnitPrice, block.timestamp);
    }

    function getMinDebtUnitPriceAt(
        uint256 _maturity,
        uint256 _minDebtUnitPrice,
        uint256 _referenceTimestamp
    ) public pure returns (uint256) {
        if (_minDebtUnitPrice == 0) return 0;
        if (_minDebtUnitPrice >= BASE_MIN_DEBT_UNIT_PRICE) {
            return BASE_MIN_DEBT_UNIT_PRICE;
        }

        if (_maturity <= _referenceTimestamp) return BASE_MIN_DEBT_UNIT_PRICE;

        uint256 reduction = ((BASE_MIN_DEBT_UNIT_PRICE - _minDebtUnitPrice) *
            (_maturity - _referenceTimestamp)) / Constants.SECONDS_IN_YEAR;

        return reduction >= BASE_MIN_DEBT_UNIT_PRICE ? 1 : BASE_MIN_DEBT_UNIT_PRICE - reduction;
    }

    function calculateFunds(
        bytes32 _ccy,
        address _user,
        ILendingMarketController.AdditionalFunds memory _additionalFunds,
        uint256 _liquidationThresholdRate,
        bool _useConservativePrice
    ) public view returns (ILendingMarketController.CalculatedFunds memory funds) {
        ActualFunds memory actualFunds = getActualFunds(
            _ccy,
            0,
            _user,
            Storage.slot().minDebtUnitPrices[_ccy],
            _useConservativePrice
        );

        funds.workingLendOrdersAmount =
            actualFunds.workingLendOrdersAmount +
            _additionalFunds.workingLendOrdersAmount;
        funds.claimableAmount = actualFunds.claimableAmount + _additionalFunds.claimableAmount;
        funds.lentAmount = actualFunds.lentAmount + _additionalFunds.lentAmount;
        funds.workingBorrowOrdersAmount =
            actualFunds.workingBorrowOrdersAmount +
            _additionalFunds.workingBorrowOrdersAmount;
        funds.debtAmount = actualFunds.debtAmount + _additionalFunds.debtAmount;
        funds.borrowedAmount = actualFunds.borrowedAmount + _additionalFunds.borrowedAmount;

        if (funds.claimableAmount > 0) {
            // If the debt and claimable amount are in the same currency, the claimable amount can be allocated
            // as collateral up to the amount that the liquidation threshold is reached.
            // For calculation purposes, the working amount for borrowing orders is treated as potential debt in addition.
            uint256 maxAllocableCollateralAmountInSameCcy = ((funds.debtAmount +
                funds.workingBorrowOrdersAmount) * _liquidationThresholdRate).div(
                    Constants.PCT_DIGIT
                );

            // If the claimable amount is over the allocable amount as collateral, the over amount is used as collateral
            // for the other currency after being multiplied by a haircut.
            if (funds.claimableAmount > maxAllocableCollateralAmountInSameCcy) {
                uint256 haircut = AddressResolverLib.currencyController().getHaircut(_ccy);
                funds.unallocatedCollateralAmount =
                    funds.claimableAmount -
                    maxAllocableCollateralAmountInSameCcy;
                funds.collateralAmount =
                    maxAllocableCollateralAmountInSameCcy +
                    (haircut * (funds.unallocatedCollateralAmount)).div(Constants.PCT_DIGIT);
            } else {
                funds.collateralAmount = funds.claimableAmount;
                funds.unallocatedCollateralAmount = 0;
            }
        }
    }

    function calculateTotalFundsInBaseCurrency(
        address _user,
        ILendingMarketController.AdditionalFunds calldata _additionalFunds,
        uint256 _liquidationThresholdRate,
        bool _useConservativePrice
    ) external view returns (ILendingMarketController.CalculatedTotalFunds memory totalFunds) {
        EnumerableSet.Bytes32Set storage currencySet = Storage.slot().usedCurrencies[_user];
        CalculatedTotalFundInBaseCurrencyVars memory vars;

        if (
            !currencySet.contains(_additionalFunds.ccy) &&
            AddressResolverLib.currencyController().currencyExists(_additionalFunds.ccy)
        ) {
            uint256 length = currencySet.length();
            vars.ccys = new bytes32[](length + 1);
            for (uint256 i; i < length; i++) {
                vars.ccys[i] = currencySet.at(i);
            }
            vars.ccys[length] = _additionalFunds.ccy;
        } else {
            vars.ccys = currencySet.values();
        }

        vars.user = _user;
        vars.additionalFunds = _additionalFunds;
        vars.liquidationThresholdRate = _liquidationThresholdRate;
        vars.isCollateral = AddressResolverLib.tokenVault().isCollateral(vars.ccys);

        // Calculate total funds from the user's order list
        for (uint256 i; i < vars.ccys.length; i++) {
            // bytes32 ccy = vars.ccys[i];
            ILendingMarketController.AdditionalFunds memory additionalFunds;

            if (vars.ccys[i] == vars.additionalFunds.ccy) {
                additionalFunds = vars.additionalFunds;
            }

            uint256[] memory amounts = new uint256[](7);

            // 0: workingLendOrdersAmount
            // 1: claimableAmount
            // 2: collateralAmount
            // 3: lentAmount
            // 4: workingBorrowOrdersAmount
            // 5: debtAmount
            // 6: borrowedAmount
            ILendingMarketController.CalculatedFunds memory funds = calculateFunds(
                vars.ccys[i],
                vars.user,
                additionalFunds,
                vars.liquidationThresholdRate,
                _useConservativePrice
            );

            amounts[0] = funds.workingLendOrdersAmount;
            amounts[1] = funds.claimableAmount;
            amounts[2] = funds.collateralAmount;
            amounts[3] = funds.lentAmount;
            amounts[4] = funds.workingBorrowOrdersAmount;
            amounts[5] = funds.debtAmount;
            amounts[6] = funds.borrowedAmount;

            if (vars.ccys[i] == vars.additionalFunds.ccy) {
                // plusDepositAmount: borrowedAmount
                // minusDepositAmount: workingLendOrdersAmount + lentAmount
                totalFunds.plusDepositAmountInAdditionalFundsCcy += amounts[6];
                totalFunds.minusDepositAmountInAdditionalFundsCcy += amounts[0] + amounts[3];
            }

            uint256[] memory amountsInBaseCurrency = AddressResolverLib
                .currencyController()
                .convertToBaseCurrency(vars.ccys[i], amounts);

            totalFunds.claimableAmount += amountsInBaseCurrency[1];
            totalFunds.collateralAmount += amountsInBaseCurrency[2];

            // A non-zero liability must not disappear when it is converted to the base currency.
            // Keep the existing rounding behavior for every other converted amount.
            totalFunds.workingBorrowOrdersAmount += _ensureNonZeroLiability(
                amounts[4],
                amountsInBaseCurrency[4]
            );
            totalFunds.debtAmount += _ensureNonZeroLiability(amounts[5], amountsInBaseCurrency[5]);

            // NOTE: Lent amount and working lend orders amount are excluded here as they are not used
            // for the collateral calculation.
            // Those amounts need only to check whether there is enough deposit amount in the selected currency.
            if (vars.isCollateral[i]) {
                totalFunds.workingLendOrdersAmount += amountsInBaseCurrency[0];
                totalFunds.lentAmount += amountsInBaseCurrency[3];
                totalFunds.borrowedAmount += amountsInBaseCurrency[6];
            }
        }
    }

    function _ensureNonZeroLiability(
        uint256 _amount,
        uint256 _amountInBaseCurrency
    ) private pure returns (uint256) {
        return _amount > 0 && _amountInBaseCurrency == 0 ? 1 : _amountInBaseCurrency;
    }

    function getUsedMaturities(
        bytes32 _ccy,
        address _user
    ) public view returns (uint256[] memory maturities) {
        maturities = Storage.slot().usedMaturities[_ccy][_user].values();
        if (maturities.length > 0) {
            maturities = QuickSort.sort(maturities);
        }
    }

    function getGenesisValue(
        bytes32 _ccy,
        address _user
    ) public view returns (int256 amount, int256 amountInPV, int256 amountInFV) {
        ActualFunds memory funds = getActualFunds(_ccy, 0, _user, 0, false);
        amount = funds.genesisValue;
        amountInPV = funds.genesisValueInPV;
        amountInFV = funds.genesisValueInFV;
    }

    function getPosition(
        bytes32 _ccy,
        uint256 _maturity,
        address _user
    ) public view returns (int256 presentValue, int256 futureValue) {
        ActualFunds memory funds = getActualFunds(_ccy, _maturity, _user, 0, false);
        presentValue = funds.presentValue;
        futureValue = funds.futureValue;
    }

    function cleanUpFunds(
        bytes32 _ccy,
        address _user
    ) public returns (uint256 totalActiveOrderCount) {
        bool futureValueExists = false;
        uint256[] memory maturities = getUsedMaturities(_ccy, _user);

        for (uint256 i; i < maturities.length; i++) {
            uint256 maturity = maturities[i];
            uint8 orderBookId = Storage.slot().maturityOrderBookIds[_ccy][maturity];
            uint256 activeOrderCount = _cleanUpOrders(_ccy, orderBookId, _user);
            totalActiveOrderCount += activeOrderCount;

            int256 currentFutureValue = convertFutureValueToGenesisValue(
                _ccy,
                orderBookId,
                maturity,
                _user
            );

            if (currentFutureValue != 0) {
                futureValueExists = true;
            }

            if (currentFutureValue == 0 && activeOrderCount == 0) {
                Storage.slot().usedMaturities[_ccy][_user].remove(maturity);
            }

            AddressResolverLib.genesisValueVault().cleanUpBalance(
                _ccy,
                _user,
                i == maturities.length - 1 ? 0 : maturities[i + 1]
            );
        }

        if (totalActiveOrderCount == 0) {
            if (
                !futureValueExists &&
                AddressResolverLib.genesisValueVault().getBalance(_ccy, _user, 0) == 0
            ) {
                Storage.slot().usedCurrencies[_user].remove(_ccy);
            }
        }
    }

    function _cleanUpOrders(
        bytes32 _ccy,
        uint8 _orderBookId,
        address _user
    ) internal returns (uint256 activeOrderCount) {
        (
            uint256 activeLendOrderCount,
            uint256 activeBorrowOrderCount,
            uint256 removedLendOrderFutureValue,
            uint256 removedBorrowOrderFutureValue,
            uint256 removedLendOrderAmount,
            uint256 removedBorrowOrderAmount,
            uint256 userCurrentMaturity
        ) = ILendingMarket(Storage.slot().lendingMarkets[_ccy]).cleanUpOrders(_orderBookId, _user);

        if (removedLendOrderAmount > removedBorrowOrderAmount) {
            AddressResolverLib.tokenVault().removeDepositAmount(
                _user,
                _ccy,
                removedLendOrderAmount - removedBorrowOrderAmount
            );
        } else if (removedLendOrderAmount < removedBorrowOrderAmount) {
            AddressResolverLib.tokenVault().addDepositAmount(
                _user,
                _ccy,
                removedBorrowOrderAmount - removedLendOrderAmount
            );
        }

        if (removedLendOrderFutureValue > 0) {
            IFutureValueVault(Storage.slot().futureValueVaults[_ccy]).increase(
                _orderBookId,
                _user,
                removedLendOrderFutureValue,
                userCurrentMaturity
            );
            emit OrdersFilledInAsync(
                _user,
                _ccy,
                ProtocolTypes.Side.LEND,
                userCurrentMaturity,
                removedLendOrderAmount,
                removedLendOrderFutureValue
            );
        }

        if (removedBorrowOrderFutureValue > 0) {
            IFutureValueVault(Storage.slot().futureValueVaults[_ccy]).decrease(
                _orderBookId,
                _user,
                removedBorrowOrderFutureValue,
                userCurrentMaturity
            );
            emit OrdersFilledInAsync(
                _user,
                _ccy,
                ProtocolTypes.Side.BORROW,
                userCurrentMaturity,
                removedBorrowOrderAmount,
                removedBorrowOrderFutureValue
            );
        }

        Storage.slot().pendingOrderAmounts[_ccy][userCurrentMaturity] -=
            removedLendOrderAmount +
            removedBorrowOrderAmount;

        activeOrderCount = activeLendOrderCount + activeBorrowOrderCount;
    }

    function _getNetPositionFunds(
        bytes32 _ccy,
        address _user,
        CalculateActualFundsVars memory vars,
        uint8 currentOrderBookId,
        uint256 currentMaturity
    ) internal view returns (PositionFunds memory funds) {
        // Cleanup transfers filled-order FV into FutureValueVault. Net the raw FVs belonging
        // to the same maturity before applying its market price or debt floor so valuation is
        // unchanged by whether cleanup has run.
        (int256 futureValueInVault, uint256 futureValueMaturity) = vars.futureValueVault.getBalance(
            currentOrderBookId,
            _user
        );

        // NOTE: Position valuation no longer assumes that an order book may be rotated, so a
        // non-zero balance should always be recorded for `currentMaturity`. Keep this guard to
        // detect inconsistent legacy or upgraded state rather than treating it as another maturity.
        if (futureValueInVault != 0 && futureValueMaturity != currentMaturity) {
            revert InvalidFutureValueMaturity(
                currentOrderBookId,
                currentMaturity,
                futureValueMaturity
            );
        }

        uint256 borrowedFutureValue;
        uint256 currentMinDebtUnitPrice = getCurrentMinDebtUnitPrice(
            currentMaturity,
            vars.minDebtUnitPrice
        );

        (funds.workingBorrowOrdersAmount, funds.borrowedAmount, borrowedFutureValue, ) = vars
            .market
            .getTotalAmountFromBorrowOrders(currentOrderBookId, _user, currentMinDebtUnitPrice);
        uint256 lentFutureValue;
        (funds.workingLendOrdersAmount, funds.lentAmount, lentFutureValue, ) = vars
            .market
            .getTotalAmountFromLendOrders(currentOrderBookId, _user);

        bool isAutoRolled = AddressResolverLib.genesisValueVault().isAutoRolled(
            _ccy,
            currentMaturity
        );

        if (isAutoRolled) {
            funds.workingBorrowOrdersAmount = 0;
            funds.workingLendOrdersAmount = 0;
        }

        int256 netFutureValue = futureValueInVault +
            lentFutureValue.toInt256() -
            borrowedFutureValue.toInt256();

        if (netFutureValue == 0) return funds;

        if (isAutoRolled) {
            if (vars.isDefaultMarket) {
                funds.genesisValue = AddressResolverLib.genesisValueVault().calculateGVFromFV(
                    _ccy,
                    currentMaturity,
                    netFutureValue
                );
            }
            return funds;
        }

        bool isDefaultMarket = currentOrderBookId == vars.defaultOrderBookId;

        if (vars.isTotal && !isDefaultMarket) {
            funds.presentValue = _calculatePVFromFVForTotalFunds(
                _ccy,
                vars,
                currentMaturity,
                netFutureValue
            );
            return funds;
        }

        if (!vars.isTotal) {
            // A single-maturity query exposes FV only for the queried maturity. A default-market
            // query also visits other maturities to collect order amounts and rolled GV, so exclude
            // unrolled positions that still belong to those maturities.
            if (vars.isDefaultMarket && !isDefaultMarket) {
                return funds;
            }

            funds.futureValue = netFutureValue;
        }

        uint256 unitPrice = getUnitPriceForValuation(
            vars.market,
            vars.useConservativePrice,
            currentOrderBookId,
            netFutureValue >= 0
        );
        funds.presentValue = _calculatePVFromFVWithMinDebtUnitPrice(
            netFutureValue,
            unitPrice,
            netFutureValue < 0 ? currentMinDebtUnitPrice : 0
        );
    }

    function _calculatePVFromFVForTotalFunds(
        bytes32 _ccy,
        CalculateActualFundsVars memory vars,
        uint256 _fromMaturity,
        int256 _fromFutureValue
    ) internal view returns (int256 presentValue) {
        IGenesisValueVault genesisValueVault = AddressResolverLib.genesisValueVault();

        if (genesisValueVault.getAutoRollLog(_ccy, _fromMaturity).unitPrice == 0) {
            uint256 fromUnitPrice = getUnitPriceForValuation(
                vars.market,
                vars.useConservativePrice,
                Storage.slot().maturityOrderBookIds[_ccy][_fromMaturity],
                _fromFutureValue >= 0
            );
            uint256 currentMinDebtUnitPrice = _fromFutureValue < 0
                ? getCurrentMinDebtUnitPrice(_fromMaturity, vars.minDebtUnitPrice)
                : 0;

            // The position still belongs to the source maturity, so its own debt floor applies.
            presentValue = _calculatePVFromFVWithMinDebtUnitPrice(
                _fromFutureValue,
                fromUnitPrice,
                currentMinDebtUnitPrice
            );
        } else {
            int256 convertedFutureValue = genesisValueVault.calculateFVFromFV(
                _ccy,
                _fromMaturity,
                0,
                _fromFutureValue
            );
            uint256 destinationUnitPrice = getUnitPriceForValuation(
                vars.market,
                vars.useConservativePrice,
                vars.defaultOrderBookId,
                convertedFutureValue >= 0
            );
            uint256 currentMinDebtUnitPrice = convertedFutureValue < 0
                ? getCurrentMinDebtUnitPrice(
                    genesisValueVault.getCurrentMaturity(_ccy),
                    vars.minDebtUnitPrice
                )
                : 0;

            // Lazy evaluation has converted the position to the destination maturity, so the
            // destination debt floor applies to the converted future value.
            presentValue = _calculatePVFromFVWithMinDebtUnitPrice(
                convertedFutureValue,
                destinationUnitPrice,
                currentMinDebtUnitPrice
            );
        }
    }

    function calculatePVFromFV(
        bytes32 _ccy,
        uint256 _maturity,
        int256 _futureValue
    ) public view returns (int256 presentValue) {
        presentValue = _calculatePVFromFV(
            ILendingMarket(Storage.slot().lendingMarkets[_ccy]),
            Storage.slot().maturityOrderBookIds[_ccy][_maturity],
            _futureValue
        );
    }

    /// @param _useConservativePrice Use the less favorable of the valuation and live prices.
    /// @param _roundUp True to round the absolute value up, false to round it down.
    function calculateFVFromPV(
        bytes32 _ccy,
        uint256 _maturity,
        int256 _presentValue,
        bool _useConservativePrice,
        bool _roundUp
    ) public view returns (int256 futureValue) {
        uint256 magnitude = _calculateFVFromPVWithRounding(
            _ccy,
            _maturity,
            (_presentValue < 0 ? -_presentValue : _presentValue).toUint256(),
            _useConservativePrice,
            _presentValue >= 0,
            _roundUp
        );
        // Rounding applies to the magnitude, including for negative debt.
        futureValue = _presentValue < 0 ? -magnitude.toInt256() : magnitude.toInt256();
    }

    /// @param _useConservativePrice Use the less favorable of the valuation and live prices.
    /// @param _roundUp True to round up, false to round down.
    function calculateFVFromPV(
        bytes32 _ccy,
        uint256 _maturity,
        uint256 _presentValue,
        bool _useConservativePrice,
        bool _roundUp
    ) public view returns (uint256 futureValue) {
        futureValue = _calculateFVFromPVWithRounding(
            _ccy,
            _maturity,
            _presentValue,
            _useConservativePrice,
            true,
            _roundUp
        );
    }

    function _calculateFVFromPVWithRounding(
        bytes32 _ccy,
        uint256 _maturity,
        uint256 _presentValue,
        bool _useConservativePrice,
        bool _isLend,
        bool _roundUp
    ) private view returns (uint256 futureValue) {
        uint256 unitPrice = getUnitPriceForValuation(
            ILendingMarket(Storage.slot().lendingMarkets[_ccy]),
            _useConservativePrice,
            Storage.slot().maturityOrderBookIds[_ccy][_maturity],
            _isLend
        );
        futureValue = Math.mulDiv(
            _presentValue,
            Constants.PRICE_DIGIT,
            unitPrice == 0 ? Constants.PRICE_DIGIT : unitPrice,
            _roundUp ? Math.Rounding.Up : Math.Rounding.Down
        );
    }

    function _convertToBaseCurrencyAtMarketTerminationPrice(
        bytes32 _ccy,
        int256 _amount
    ) internal view returns (int256) {
        TerminationCurrencyCache memory currency = Storage.slot().terminationCurrencyCaches[_ccy];
        return (_amount * currency.price).div((10 ** currency.decimals).toInt256());
    }

    function _convertFromBaseCurrencyAtMarketTerminationPrice(
        bytes32 _ccy,
        uint256 _amount
    ) internal view returns (uint256) {
        TerminationCurrencyCache memory currency = Storage.slot().terminationCurrencyCaches[_ccy];
        return (_amount * 10 ** currency.decimals).div(currency.price.toUint256());
    }

    function _resetFundsPerCurrency(bytes32 _ccy, address _user) internal returns (int256 amount) {
        amount = getActualFunds(_ccy, 0, _user, 0, false).presentValue;

        uint256[] memory maturities = Storage.slot().usedMaturities[_ccy][_user].values();
        for (uint256 j; j < maturities.length; j++) {
            IFutureValueVault(Storage.slot().futureValueVaults[_ccy]).executeForcedReset(
                Storage.slot().maturityOrderBookIds[_ccy][maturities[j]],
                _user
            );
        }

        AddressResolverLib.genesisValueVault().executeForcedReset(_ccy, _user);

        Storage.slot().usedCurrencies[_user].remove(_ccy);
    }

    function _resetFundsPerMaturity(
        bytes32 _ccy,
        uint256 _maturity,
        address _user,
        int256 _amount
    ) internal returns (int256 totalRemovedAmount) {
        int256 currentFVAmount;
        int256 currentGVAmount;

        (totalRemovedAmount, currentFVAmount) = IFutureValueVault(
            Storage.slot().futureValueVaults[_ccy]
        ).executeForcedReset(Storage.slot().maturityOrderBookIds[_ccy][_maturity], _user, _amount);

        int256 remainingAmount = _amount - totalRemovedAmount;

        // Note: orderBookIdList is guaranteed to be non-empty here because
        // this function is only called from executeRedemption/executeRepayment
        // which have the ifValidMaturity modifier that ensures the maturity exists.
        bool isDefaultMarket = Storage.slot().maturityOrderBookIds[_ccy][_maturity] ==
            Storage.slot().orderBookIdLists[_ccy][0];

        if (isDefaultMarket && remainingAmount != 0) {
            int256 removedAmount;
            (removedAmount, currentGVAmount) = AddressResolverLib
                .genesisValueVault()
                .executeForcedReset(_ccy, _maturity, _user, remainingAmount);
            totalRemovedAmount += removedAmount;
        }

        if (currentFVAmount == 0 && currentGVAmount == 0) {
            Storage.slot().usedMaturities[_ccy][_user].remove(_maturity);

            if (Storage.slot().usedMaturities[_ccy][_user].length() == 0) {
                Storage.slot().usedCurrencies[_user].remove(_ccy);
            }
        }
    }

    /**
     * @notice Selects the standard price, or the adverse price for a lending or borrowing position.
     * @dev Returns zero if neither price exists; callers retain their own unpriced-book fallback.
     */
    function getUnitPriceForValuation(
        ILendingMarket _market,
        bool _useConservativePrice,
        uint8 _orderBookId,
        bool _isLend
    ) public view returns (uint256) {
        if (!_useConservativePrice) {
            return _market.getMarketUnitPrice(_orderBookId);
        } else {
            uint256 referencePrice = _market.getMarketUnitPrice(_orderBookId);
            uint256 liveUnitPrice = _market.getLiveUnitPrice(_orderBookId);

            // A zero value means no price exists for that source. Use the available price.
            if (referencePrice == 0) return liveUnitPrice;
            if (liveUnitPrice == 0) return referencePrice;

            // For risk-increasing actions, value claims at the lower price and debts at the higher price.
            return
                _isLend
                    ? (referencePrice < liveUnitPrice ? referencePrice : liveUnitPrice)
                    : (referencePrice > liveUnitPrice ? referencePrice : liveUnitPrice);
        }
    }

    function _calculatePVFromFV(
        ILendingMarket _market,
        uint8 _orderBookId,
        int256 _futureValue
    ) internal view returns (int256 presentValue) {
        uint256 unitPrice = _market.getMarketUnitPrice(_orderBookId);
        presentValue = _calculatePVFromFV(_futureValue, unitPrice);
    }

    function _calculatePVFromFV(
        int256 _futureValue,
        uint256 _unitPrice
    ) internal pure returns (int256) {
        uint256 unitPrice = _unitPrice == 0 ? Constants.PRICE_DIGIT : _unitPrice;
        // NOTE: The formula is: presentValue = futureValue * unitPrice.
        return (_futureValue * unitPrice.toInt256()).div(Constants.PRICE_DIGIT.toInt256());
    }

    /**
     * @dev Calculates PV using the debt floor while preserving the zero-price convention.
     * A zero market unit price means that no price has been established and is valued at par.
     * The minimum debt unit price therefore applies only to a non-zero market unit price.
     */
    function _calculatePVFromFVWithMinDebtUnitPrice(
        int256 _futureValue,
        uint256 _unitPrice,
        uint256 _minDebtUnitPrice
    ) internal pure returns (int256) {
        uint256 unitPrice = _unitPrice != 0 && _unitPrice < _minDebtUnitPrice
            ? _minDebtUnitPrice
            : _unitPrice;
        return _calculatePVFromFV(_futureValue, unitPrice);
    }
}

contracts/protocol/libraries/logics/OrderBookLogic.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return orderBook.calculateItayoseResult();
    }

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

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

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

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

        uint256 previousRate = Storage.slot().orderFeeRate;

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

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

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

        uint256 previousRange = Storage.slot().circuitBreakerLimitRange;

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

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

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

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

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

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

        emit OrderBookCreated(orderBookId, _maturity, _openingDate);
    }

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

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

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

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

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

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

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

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

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

        return _getItayoseProcessStatus(orderBook);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

contracts/protocol/libraries/math/RoundingInt256.sol

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

library RoundingInt256 {
    function div(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0);

        int256 diff = (a * 10) / b - (a / b) * 10;
        if (diff >= 5) {
            return (a / b) + 1;
        } else if (diff <= -5) {
            return (a / b) - 1;
        } else {
            return a / b;
        }
    }
}

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/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/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
    }
}
Настройки компилятораПоказать
{
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {
    "contracts/protocol/libraries/logics/LiquidationLogic.sol": {
      "FundManagementLogic": "0xdcf7206154188660e46b8c8991e219736dbe81bb"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.