// File: src/OmniPool.sol



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

import "openzeppelin-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import "openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol";
import "openzeppelin-upgradeable/contracts/security/PausableUpgradeable.sol";
import "openzeppelin/contracts/utils/math/Math.sol";

import "./interfaces/IOmniOracle.sol";
import "./interfaces/IOmniPool.sol";
import "./interfaces/IOmniToken.sol";
import "./interfaces/IOmniTokenNoBorrow.sol";
import "./interfaces/IWithUnderlying.sol";
import "./SubAccount.sol";

/**
 * @title OmniPool
 * @notice This contract implements a manager for handling loans, protocol market, mode, and account configurations, and liquidations.
 * @dev This contract implements a lending pool with various modes and market configurations.
 * It utilizes different structs to keep track of market, mode, account configurations, evaluations,
 * and liquidation bonuses. It has a variety of external and public functions to manage and interact with
 * the lending pool, along with internal utility functions. Includes AccessContral, Pausable, and ReentrancyGuardUpgradeable (includes Initializable)
 * from OpenZeppelin.
 */
contract OmniPool is IOmniPool, AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable {
    using SubAccount for address;

    bytes32 public constant SOFT_LIQUIDATION_ROLE = keccak256("SOFT_LIQUIDATION_ROLE");
    bytes32 public constant MARKET_CONFIGURATOR_ROLE = keccak256("MARKET_CONFIGURATOR_ROLE");

    uint256 public constant SELF_COLLATERALIZATION_FACTOR = 0.96e9; // 0.96
    uint256 public constant FACTOR_PRECISION_SCALE = 1e9;
    uint256 public constant LIQ_BONUS_PRECISION_SCALE = 1e9;
    uint256 public constant HEALTH_FACTOR_SCALE = 1e9;
    uint256 public constant MAX_BASE_SOFT_LIQUIDATION = 1.4e9;
    uint256 public constant MAX_LIQ_KINK = 0.2e9; // Borrow value exceeds deposit value by 20%
    uint256 public constant PRICE_SCALE = 1e18; // Must match up with PRICE_SCALE in OmniOracle
    uint256 public constant MAX_MARKETS_PER_ACCOUNT = 9; // Will be 10 including isolated collateral market

    mapping(bytes32 => AccountInfo) public accountInfos;
    mapping(bytes32 => address[]) public accountMarkets;

    uint256 public modeCount;
    mapping(uint256 => ModeConfiguration) public modeConfigurations;
    mapping(address => MarketConfiguration) public marketConfigurations;
    mapping(address => LiquidationBonusConfiguration) public liquidationBonusConfigurations;

    address public oracle;
    uint8 public pauseTranche;
    bytes32 public reserveReceiver;

    /**
     * @notice Initializes a new instance of the contract, setting up the oracle, reserve receiver, pause tranche, and various roles.
     * This constructor sets the oracle address, initializes the pause tranche to its maximum value, and sets the reserve receiver to the provided address.
     * It also sets up the DEFAULT_ADMIN_ROLE, SOFT_LIQUIDATION_ROLE, and MARKET_CONFIGURATOR_ROLE, assigning them to the account deploying the contract.
     * @param _oracle The address of the oracle contract to be used for price information.
     * @param _reserveReceiver The address of the reserve receiver. This address will be converted to an account with a subId of 0.
     * @param _admin The address of the multisig admin
     */
    function initialize(address _oracle, address _reserveReceiver, address _admin) external initializer {
        __ReentrancyGuard_init();
        __AccessControl_init();
        __Pausable_init();
        oracle = _oracle;
        pauseTranche = type(uint8).max;
        reserveReceiver = _reserveReceiver.toAccount(0);
        _setupRole(DEFAULT_ADMIN_ROLE, _admin); // Additionally set up other roles?
        _setupRole(SOFT_LIQUIDATION_ROLE, _admin);
        _setupRole(MARKET_CONFIGURATOR_ROLE, _admin);
    }

    /**
     * @notice Allows a user to enter an isolated market, the market configuration must be for isolated collateral.
     * @dev The function checks whether the market is valid for isolation and updates the account's isolatedCollateralMarket field.
     * A subaccount is only allowed to have 1 isolated collateral market at a time.
     * @param _subId The sub-account identifier.
     * @param _isolatedMarket The address of the isolated market to enter.
     */
    function enterIsolatedMarket(uint96 _subId, address _isolatedMarket) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        require(account.modeId == 0, "OmniPool::enterIsolatedMarket: Already in a mode.");
        require(
            account.isolatedCollateralMarket == address(0),
            "OmniPool::enterIsolatedMarket: Already has isolated collateral."
        );
        MarketConfiguration memory marketConfig = marketConfigurations[_isolatedMarket];
        if (marketConfig.expirationTimestamp <= block.timestamp || !marketConfig.isIsolatedCollateral) {
            revert("OmniPool::enterIsolatedMarket: Isolated market invalid.");
        }
        Evaluation memory eval = evaluateAccount(accountId);
        require(eval.numBorrow == 0, "OmniPool::enterIsolatedMarket: Non-zero borrow count.");
        accountInfos[accountId].isolatedCollateralMarket = _isolatedMarket;
        emit EnteredIsolatedMarket(accountId, _isolatedMarket);
    }

    /**
     * @notice Allows a user to enter multiple unique markets, none of them are isolated collateral markets.
     * @dev The function checks the validity of each market and updates the account's market list. Markets must not already be entered.
     * @param _subId The sub-account identifier.
     * @param _markets The addresses of the markets to enter.
     */
    function enterMarkets(uint96 _subId, address[] calldata _markets) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        require(accountInfos[accountId].modeId == 0, "OmniPool::enterMarkets: Already in a mode.");
        address[] memory existingMarkets = accountMarkets[accountId];
        address[] memory newMarkets = new address[](existingMarkets.length + _markets.length);
        require(newMarkets.length <= MAX_MARKETS_PER_ACCOUNT, "OmniPool::enterMarkets: Too many markets.");
        for (uint256 i = 0; i < existingMarkets.length; ++i) {
            // Copy over existing markets
            newMarkets[i] = existingMarkets[i];
        }
        for (uint256 i = 0; i < _markets.length; ++i) {
            address market = _markets[i];
            MarketConfiguration memory marketConfig = marketConfigurations[market];
            require(
                marketConfig.expirationTimestamp > block.timestamp && !marketConfig.isIsolatedCollateral,
                "OmniPool::enterMarkets: Market invalid."
            );
            require(!_contains(newMarkets, market), "OmniPool::enterMarkets: Already in the market.");
            require(
                IOmniToken(market).getBorrowCap(0) > 0,
                "OmniPool::enterMarkets: Market has no borrow cap for 0 tranche."
            );
            newMarkets[i + existingMarkets.length] = market;
        }
        accountMarkets[accountId] = newMarkets;
        emit EnteredMarkets(accountId, _markets);
    }

    /**
     * @notice Allows a user to exit multiple markets including their isolated market. There must be no borrows active on the subaccount to exit a market.
     * @dev The function removes the specified markets from the account's market list after ensuring the account has no outstanding borrows.
     * @param _subId The sub-account identifier.
     * @param _market The address of the market to exit.
     */
    function exitMarket(uint96 _subId, address _market) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        require(account.modeId == 0, "OmniPool::exitMarkets: In a mode, need to call exitMode.");
        address[] memory markets_ = getAccountPoolMarkets(accountId, account);
        Evaluation memory eval = _evaluateAccountInternal(accountId, markets_, account);
        require(eval.numBorrow == 0, "OmniPool::exitMarkets: Non-zero borrow count.");
        if (_market == account.isolatedCollateralMarket) {
            accountInfos[accountId].isolatedCollateralMarket = address(0);
        } else {
            require(markets_.length > 0, "OmniPool::exitMarkets: No markets to exit");
            require(_contains(markets_, _market), "OmniPool::exitMarkets: Market not entered");
            uint256 newMarketsLength = markets_.length - 1;
            if (newMarketsLength > 0) {
                address[] memory newMarkets = new address[](markets_.length - 1);
                uint256 newIndex = 0;
                for (uint256 i = 0; i < markets_.length; ++i) {
                    if (markets_[i] != _market) {
                        newMarkets[newIndex] = markets_[i];
                        ++newIndex;
                    }
                }
                delete accountMarkets[accountId]; // Gas refund?
                accountMarkets[accountId] = newMarkets;
            } else {
                delete accountMarkets[accountId];
            }
        }
        emit ExitedMarket(accountId, _market);
    }

    /**
     * @notice Clears all markets for a user including isolated collateral. The subaccount must have no active borrows to clear markets.
     * @dev The function checks that the account has no outstanding borrows before clearing all markets.
     * @param _subId The sub-account identifier.
     */
    function clearMarkets(uint96 _subId) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        require(account.modeId == 0, "OmniPool::clearMarkets: Already in a mode.");
        Evaluation memory eval = evaluateAccount(accountId);
        require(eval.numBorrow == 0, "OmniPool::clearMarkets: Non-zero borrow count.");
        accountInfos[accountId].isolatedCollateralMarket = address(0);
        delete accountMarkets[accountId];
        emit ClearedMarkets(accountId);
    }

    /**
     * @notice Allows a user to enter a mode. The subaccount must not already be in a mode. The mode must not have expired.
     * @dev The function sets the modeId field in the account's info and emits an EnteredMode event.
     * @param _subId The sub-account identifier.
     * @param _modeId The mode identifier to enter.
     */
    function enterMode(uint96 _subId, uint8 _modeId) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        require(_modeId > 0 && _modeId <= modeCount, "OmniPool::enterMode: Invalid mode ID.");
        AccountInfo memory account = accountInfos[accountId];
        require(account.modeId == 0, "OmniPool::enterMode: Already in a mode.");
        require(
            accountMarkets[accountId].length == 0 && account.isolatedCollateralMarket == address(0),
            "OmniPool::enterMode: Non-zero market count."
        );
        require(modeConfigurations[_modeId].expirationTimestamp > block.timestamp, "OmniPool::enterMode: Mode expired.");
        account.modeId = _modeId;
        accountInfos[accountId] = account;
        emit EnteredMode(accountId, _modeId);
    }

    /**
     * @notice Allows a user to exit a mode. There must be no active borrows in the subaccount to exit.
     * @dev The function resets the modeId field in the account's info and emits an ExitedMode event.
     * @param _subId The sub-account identifier.
     */
    function exitMode(uint96 _subId) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        require(account.modeId != 0, "OmniPool::exitMode: Not in a mode.");
        Evaluation memory eval = evaluateAccount(accountId);
        require(eval.numBorrow == 0, "OmniPool::exitMode: Non-zero borrow count.");
        account.modeId = 0;
        accountInfos[accountId] = account;
        emit ExitedMode(accountId);
    }

    /**
     * @notice Evaluates an account's deposits and borrows values.
     * @dev The function computes the true and adjusted values of deposits and borrows for the account.
     * @param _accountId The account identifier.
     * @return eval An Evaluation struct containing the account's financial information.
     */
    function evaluateAccount(bytes32 _accountId) public returns (Evaluation memory eval) {
        AccountInfo memory account = accountInfos[_accountId];
        address[] memory poolMarkets = getAccountPoolMarkets(_accountId, account);
        return _evaluateAccountInternal(_accountId, poolMarkets, account);
    }

    /**
     * @notice Evaluates an account's financial standing within a lending pool.
     * @dev This function accrues interest, computes market prices, deposit and borrow balances, and calculates the adjusted values of
     * deposits and borrows based on the account's mode and market configurations.
     * @param _accountId The unique identifier of the account to be evaluated.
     * @param _poolMarkets An array of addresses representing the markets in which the account has activity. Excludes the isolated collateral market if it exists.
     * @param _account The AccountInfo struct containing the account's mode, isolated collateral market, and other relevant data.
     * @return eval An Evaluation struct containing data on the account's deposit and borrow balances, both true and adjusted values.
     */
    function _evaluateAccountInternal(bytes32 _accountId, address[] memory _poolMarkets, AccountInfo memory _account)
        internal
        returns (Evaluation memory eval)
    {
        ModeConfiguration memory mode;
        if (_account.modeId != 0) mode = modeConfigurations[_account.modeId];
        for (uint256 i = 0; i < _poolMarkets.length; ++i) {
            // Accrue interest for all borrowable markets
            IOmniToken(_poolMarkets[i]).accrue();
        }
        uint256 marketCount = _poolMarkets.length;
        if (_account.isolatedCollateralMarket != address(0)) {
            ++marketCount;
        }
        for (uint256 i = 0; i < marketCount; ++i) {
            address market;
            // A market is either a pool market or the isolated collateral market (last index).
            if (i < _poolMarkets.length) {
                market = _poolMarkets[i];
            } else {
                market = _account.isolatedCollateralMarket;
            }
            MarketConfiguration memory marketConfiguration_ = marketConfigurations[market];
            if (marketConfiguration_.expirationTimestamp <= block.timestamp) {
                eval.isExpired = true; // Must repay all debts and exit market to get rid of unhealthy account status if expired
            }
            address underlying = IWithUnderlying(market).underlying();
            uint256 price = IOmniOracle(oracle).getPrice(underlying); // Returns price in base units multiplied by 1e36
            uint256 depositAmount = IOmniTokenBase(market).getAccountDepositInUnderlying(_accountId);
            if (depositAmount != 0) {
                ++eval.numDeposit;
                uint256 depositValue = (depositAmount * price) / PRICE_SCALE; // Rounds down
                eval.depositTrueValue += depositValue;
                uint256 collateralFactor = marketCount == 1
                    ? SELF_COLLATERALIZATION_FACTOR
                    : _account.modeId == 0 ? uint256(marketConfiguration_.collateralFactor) : uint256(mode.collateralFactor);
                eval.depositAdjValue += (depositValue * collateralFactor) / FACTOR_PRECISION_SCALE; // Rounds down
            }
            if (i >= _poolMarkets.length) {
                // Isolated collateral market. No borrow.
                continue;
            }
            uint8 borrowTier = getAccountBorrowTier(_account);
            uint256 borrowAmount = IOmniToken(market).getAccountBorrowInUnderlying(_accountId, borrowTier);
            if (borrowAmount != 0) {
                ++eval.numBorrow;
                uint256 borrowValue = (borrowAmount * price) / PRICE_SCALE; // Rounds down
                eval.borrowTrueValue += borrowValue;
                uint256 borrowFactor = marketCount == 1
                    ? SELF_COLLATERALIZATION_FACTOR
                    : _account.modeId == 0 ? uint256(marketConfiguration_.borrowFactor) : uint256(mode.borrowFactor);
                eval.borrowAdjValue += (borrowValue * FACTOR_PRECISION_SCALE) / borrowFactor; // Rounds down
            }
        }
    }

    /**
     * @notice Allows an account to borrow funds from a specified market the subaccount has entered, provided the account remains in a healthy financial standing post-borrow.
     * @param _subId The sub-account identifier from which to borrow.
     * @param _market The address of the market from which to borrow.
     * @param _amount The amount of funds to borrow.
     */
    function borrow(uint96 _subId, address _market, uint256 _amount) external nonReentrant whenNotPaused {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        address[] memory poolMarkets = getAccountPoolMarkets(accountId, account);
        require(_contains(poolMarkets, _market), "OmniPool::borrow: Not in pool markets.");
        uint8 borrowTier = getAccountBorrowTier(account);
        IOmniToken(_market).borrow(accountId, borrowTier, _amount);
        Evaluation memory eval = _evaluateAccountInternal(accountId, poolMarkets, account);
        require(
            eval.depositAdjValue >= eval.borrowAdjValue && !eval.isExpired,
            "OmniPool::borrow: Not healthy after borrow."
        );
    }

    /**
     * @notice Allows an account to repay borrowed funds to a specified market the subaccount has entered.
     * @param _subId The sub-account identifier from which to repay.
     * @param _market The address of the market to which to repay.
     * @param _amount The amount of funds to repay. If _amount is 0, the contract will repay the entire borrow balance.
     */
    function repay(uint96 _subId, address _market, uint256 _amount) external {
        bytes32 accountId = msg.sender.toAccount(_subId);
        AccountInfo memory account = accountInfos[accountId];
        address[] memory poolMarkets = getAccountPoolMarkets(accountId, account);
        require(_contains(poolMarkets, _market), "OmniPool::repay: Not in pool markets.");
        uint8 borrowTier = getAccountBorrowTier(account);
        IOmniToken(_market).repay(accountId, msg.sender, borrowTier, _amount);
    }

    /**
     * @notice Initiates the liquidation process on an undercollateralized or expired account, repaying some or all of the target account's borrow balance
     * while seizing a portion of the target's collateral. The amount of collateral seized is determined by the liquidation bonus and the price of the
     * assets involved. Soft liquidation is only allowed if there is no bad debt, otherwise if bad debt exists a full liquidation is bypassed.
     * @dev Liquidation configuration must be set for the _collateralMarket or else will revert.
     * The seized amount of shares is not guaranteed to compensate the value of the repayment during liquidation. Liquidators should check the returned value if they have a
     * minimum expectation of payout from liquidating, and perform necessary logic to revert if necessary.
     * @param _params The LiquidationParams struct containing the target account's identifier, the liquidator's identifier, the market to be liquidated,
     * @return seizedShares The amount of shares seized from the liquidated account.
     */
    function liquidate(LiquidationParams calldata _params)
        external
        whenNotPaused
        nonReentrant
        returns (uint256[] memory seizedShares)
    {
        AccountInfo memory targetAccount = accountInfos[_params.targetAccountId];
        address[] memory poolMarkets = getAccountPoolMarkets(_params.targetAccountId, targetAccount);
        require(
            _contains(poolMarkets, _params.liquidateMarket), "OmniPool::liquidate: LiquidateMarket not in pool markets."
        );
        require(
            _contains(poolMarkets, _params.collateralMarket)
                || targetAccount.isolatedCollateralMarket == _params.collateralMarket,
            "OmniPool::liquidate: CollateralMarket not available to seize."
        );
        Evaluation memory evalBefore = _evaluateAccountInternal(_params.targetAccountId, poolMarkets, targetAccount);
        require(evalBefore.numBorrow > 0, "OmniPool::liquidate: No borrow to liquidate.");
        require(
            (evalBefore.depositAdjValue < evalBefore.borrowAdjValue)
                || marketConfigurations[_params.collateralMarket].expirationTimestamp <= block.timestamp,
            "OmniPool::liquidate: Account still healthy."
        );
        uint8 borrowTier = getAccountBorrowTier(targetAccount);
        uint256 amount =
            IOmniToken(_params.liquidateMarket).repay(_params.targetAccountId, msg.sender, borrowTier, _params.amount);
        (uint256 liquidationBonus, uint256 softThreshold) = getLiquidationBonusAndThreshold(
            evalBefore.depositAdjValue, evalBefore.borrowAdjValue, _params.collateralMarket
        );
        {
            // Avoid stack too deep
            uint256 borrowPrice = IOmniOracle(oracle).getPrice(IWithUnderlying(_params.liquidateMarket).underlying());
            uint256 depositPrice = IOmniOracle(oracle).getPrice(IWithUnderlying(_params.collateralMarket).underlying());
            uint256 seizeAmount = Math.ceilDiv(
                Math.ceilDiv(amount * borrowPrice, depositPrice) * (LIQ_BONUS_PRECISION_SCALE + liquidationBonus), // Need to add base since liquidationBonus < LIQ_BONUS_PRECISION_SCALE
                LIQ_BONUS_PRECISION_SCALE
            ); // round up
            seizedShares = IOmniTokenBase(_params.collateralMarket).seize(
                _params.targetAccountId, _params.liquidatorAccountId, seizeAmount
            );
        }
        Evaluation memory evalAfter = _evaluateAccountInternal(_params.targetAccountId, poolMarkets, targetAccount);
        if (evalAfter.borrowTrueValue > evalAfter.depositTrueValue) {
            pauseTranche = borrowTier > pauseTranche ? pauseTranche : borrowTier;
            emit PausedTranche(pauseTranche);
        } else if (!evalAfter.isExpired) {
            // If expired, no liquidation threshold
            require(
                checkSoftLiquidation(evalAfter.depositAdjValue, evalAfter.borrowAdjValue, softThreshold, targetAccount),
                "OmniPool::liquidate: Too much has been liquidated."
            );
        }
        emit Liquidated(
            msg.sender,
            _params.targetAccountId,
            _params.liquidatorAccountId,
            _params.liquidateMarket,
            _params.collateralMarket,
            amount
        );
    }

    /**
     * @notice Checks whether a soft liquidation condition is met based on the account's adjusted deposit and borrow values.
     * @param _depositAdjValue The adjusted value of the account's deposits.
     * @param _borrowAdjValue The adjusted value of the account's borrows.
     * @param _softThreshold The threshold value for soft liquidation.
     * @param _account The AccountInfo struct containing the account's mode, isolated collateral market, and other relevant data.
     * @return A boolean indicating whether a soft liquidation condition is met.
     */
    function checkSoftLiquidation(
        uint256 _depositAdjValue,
        uint256 _borrowAdjValue,
        uint256 _softThreshold,
        AccountInfo memory _account
    ) public pure returns (bool) {
        if (_borrowAdjValue == 0) {
            return false;
        }
        uint256 healthFactor = (_depositAdjValue * HEALTH_FACTOR_SCALE) / _borrowAdjValue; // Round down
        uint256 threshold = _account.softThreshold != 0 ? _account.softThreshold : _softThreshold;
        return healthFactor <= threshold;
    }

    /**
     * @notice Initiates the process of socializing a fully liquidated account's remaining loss to the users of the specified market and tranche, discretion to admin.
     * @dev There is a separate call that must be made to unpause the tranches, discretion to admin. Due to potential problems w/ a full liquidation
     * allow for 0.1bps ($10 for $1M) difference in deposit and borrow values. However, it is expected that admin calls liquidate prior to calling socializeLoss in script.
     * @param _market The address of the market in which the loss is socialized.
     * @param _account The unique identifier of the fully liquidated account.
     */
    function socializeLoss(address _market, bytes32 _account) external onlyRole(DEFAULT_ADMIN_ROLE) {
        uint8 borrowTier = getAccountBorrowTier(accountInfos[_account]);
        Evaluation memory eval = evaluateAccount(_account);
        uint256 percentDiff = eval.depositTrueValue * 1e18 / eval.borrowTrueValue;
        require(
            percentDiff < 0.00001e18,
            "OmniPool::socializeLoss: Account not fully liquidated, please call liquidate prior to fully liquidate account."
        );
        IOmniToken(_market).socializeLoss(_account, borrowTier);
        emit SocializedLoss(_market, borrowTier, _account);
    }

    /**
     * @notice Determines the risk tier associated with an subaccount's borrow activity. The tier is derived from the subaccount's isolated collateral market.
     * @param _account The AccountInfo struct containing the subaccount's mode, isolated collateral market, and other relevant data.
     * @return The risk tier associated with the subaccount's borrow activity.
     */
    function getAccountBorrowTier(AccountInfo memory _account) public view returns (uint8) {
        address isolatedCollateralMarket = _account.isolatedCollateralMarket;
        if (_account.modeId == 0) {
            if (isolatedCollateralMarket == address(0)) {
                // Account has no isolated collateral market. Use tier 0 (lowest risk).
                return 0;
            } else {
                // Account has isolated collateral market. Use the market's risk tranche.
                return marketConfigurations[isolatedCollateralMarket].riskTranche;
            }
        } else {
            // Account is in a mode. Use the mode's risk tranche.
            return modeConfigurations[_account.modeId].modeTranche;
        }
    }

    /**
     * @notice Retrieves all markets, except for the isolated collateral market, associated with an subaccount.
     * @param _accountId The unique identifier of the subaccount whose markets are to be retrieved.
     * @param _account The AccountInfo struct containing the subaccount's mode, isolated collateral market, and other relevant data.
     * @return An array of addresses representing the markets associated with the subaccount.
     */
    function getAccountPoolMarkets(bytes32 _accountId, AccountInfo memory _account)
        public
        view
        returns (address[] memory)
    {
        if (_account.modeId == 0) {
            // Account is not in a mode. Use the account's markets.
            return accountMarkets[_accountId];
        } else {
            // Account is in a mode. Use the mode's markets.
            assert(_account.modeId <= modeCount);
            return modeConfigurations[_account.modeId].markets;
        }
    }

    /**
     * @notice Computes the liquidation bonus and soft threshold values based on the account's adjusted deposit and borrow values and the specified collateral market.
     * @param _depositAdjValue The adjusted value of the account's deposits.
     * @param _borrowAdjValue The adjusted value of the account's borrows.
     * @param _collateralMarket The address of the collateral market.
     * @return bonus The computed liquidation bonus value.
     * @return softThreshold The computed soft threshold value.
     */
    function getLiquidationBonusAndThreshold(
        uint256 _depositAdjValue,
        uint256 _borrowAdjValue,
        address _collateralMarket
    ) public view returns (uint256 bonus, uint256 softThreshold) {
        if (_borrowAdjValue > _depositAdjValue) {
            // Prioritize unhealthiness over expiry in case where is expired and unhealthy is true
            LiquidationBonusConfiguration memory liquidationBonusConfiguration_ =
                liquidationBonusConfigurations[_collateralMarket];
            softThreshold = liquidationBonusConfiguration_.softThreshold;
            uint256 pctDiff =
                Math.ceilDiv(_borrowAdjValue * LIQ_BONUS_PRECISION_SCALE, _depositAdjValue) - LIQ_BONUS_PRECISION_SCALE; // Round up
            if (pctDiff <= liquidationBonusConfiguration_.kink) {
                bonus = liquidationBonusConfiguration_.start;
                bonus += Math.ceilDiv(
                    pctDiff * (liquidationBonusConfiguration_.end - liquidationBonusConfiguration_.start),
                    liquidationBonusConfiguration_.kink
                );
            } else {
                bonus = liquidationBonusConfiguration_.end;
            }
        } else if (marketConfigurations[_collateralMarket].expirationTimestamp <= block.timestamp) {
            LiquidationBonusConfiguration memory liquidationBonusConfiguration_ =
                liquidationBonusConfigurations[_collateralMarket];
            softThreshold = liquidationBonusConfiguration_.softThreshold;
            bonus = liquidationBonusConfiguration_.expiredBonus;
        } else {
            revert("OmniPool::getLiquidationBonus: No liquidation bonus, account is not liquidatable ");
        }
    }

    /**
     * @notice Determines if an account is healthy by comparing the factor adjusted price weighted values of deposits and borrows.
     * @dev The function evaluates the account and returns true if the account is healthy. Intentionally do not check expiration here.
     * @param _accountId The account identifier.
     * @return A boolean indicating whether the account is healthy.
     */
    function isAccountHealthy(bytes32 _accountId) external returns (bool) {
        Evaluation memory eval = evaluateAccount(_accountId);
        return eval.depositAdjValue >= eval.borrowAdjValue && !eval.isExpired;
    }

    /**
     * @notice Resets the pause tranche to its default value. This function should only be called after all bad debt is resolved.
     * Must be called by an account with the DEFAULT_ADMIN_ROLE.
     */
    function resetPauseTranche() public onlyRole(DEFAULT_ADMIN_ROLE) {
        pauseTranche = type(uint8).max;
        emit UnpausedTranche();
    }

    /**
     * @notice Configures a market with specific parameters. This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * It validates the configuration provided especially focusing on isolated collateral settings, borrow factors and risk tranches.
     * Should never configure a IOmniTokenNoBorrow (non-borrwable) token with a borrowFactor > 0 and not as isolated, otherwise will break.
     * @dev Setting markets to the 0 riskTranche comes with special privileges and should be used carefully after strict risk analysis.
     * @param _market The address of the market to be configured.
     * @param _marketConfig The MarketConfiguration struct containing the market's configurations.
     */
    function setMarketConfiguration(address _market, MarketConfiguration calldata _marketConfig)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        // Set to block.timestamp value to have the market expire in that block for emergencies
        if (_marketConfig.expirationTimestamp <= block.timestamp) {
            revert("OmniPool::setMarketConfiguration: Bad expiration timestamp.");
        }
        if (_marketConfig.isIsolatedCollateral && (_marketConfig.borrowFactor > 0 || _marketConfig.riskTranche == 0)) {
            revert("OmniPool::setMarketConfiguration: Bad configuration for isolated collateral.");
        }
        if (
            _marketConfig.collateralFactor == 0
                && (_marketConfig.borrowFactor == 0 || _marketConfig.riskTranche != type(uint8).max)
        ) {
            revert("OmniPool::setMarketConfiguration: Invalid configuration for borrowable long tail asset.");
        }
        MarketConfiguration memory currentConfig = marketConfigurations[_market];
        if (currentConfig.collateralFactor != 0) {
            require(
                _marketConfig.isIsolatedCollateral == currentConfig.isIsolatedCollateral,
                "OmniPool::setMarketConfiguration: Cannot change isolated collateral status."
            );
        }
        marketConfigurations[_market] = _marketConfig;
        emit SetMarketConfiguration(_market, _marketConfig);
    }

    /**
     * @notice Removes the market configuration for a specified market.
     * @dev This function can only be called by an account with the `MARKET_CONFIGURATOR_ROLE` role.
     * It checks if the market's underlying asset balance is zero before allowing removal.
     * @param _market The address of the market whose configuration is to be removed.
     */
    function removeMarketConfiguration(address _market) external onlyRole(MARKET_CONFIGURATOR_ROLE) {
        require(
            IERC20(IWithUnderlying(_market).underlying()).balanceOf(_market) == 0,
            "OmniPool::removeMarketConfiguration: Market still has balance."
        );
        delete marketConfigurations[_market];
        emit RemovedMarketConfiguration(_market);
    }

    /**
     * @notice Sets the configurations for a mode. This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * Each mode configuration overrides all borrow and collateral factors for markets within that mode and should be used cautiously.
     * @dev This is a privileged function that should be used carefully after strict risk analysis, as it overrides factors for all markets in the mode.
     * Modes should never include markets that are considered isolated assets.
     * @param _modeConfiguration A ModeConfiguration struct containing the configuration for the mode.
     */
    function setModeConfiguration(ModeConfiguration calldata _modeConfiguration)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        if (_modeConfiguration.expirationTimestamp <= block.timestamp) {
            revert("OmniPool::setModeConfiguration: Bad expiration timestamp.");
        }
        for (uint256 i = 0; i < _modeConfiguration.markets.length; ++i) {
            for (uint256 j = i + 1; j < _modeConfiguration.markets.length; j++) {
                if (_modeConfiguration.markets[i] == _modeConfiguration.markets[j]) {
                    revert("OmniPool:setModeConfiguration: No duplicate markets allowed.");
                }
            }
        }
        modeCount++;
        modeConfigurations[modeCount] = _modeConfiguration;
        emit SetModeConfiguration(modeCount, _modeConfiguration);
    }

    /**
     * @notice Sets the expiration timestamp for a specified mode. This expiration only signifies the mode can no longer be entered, but does not force exit exisitng subaccounts from the mode.
     * This function allows for updating the expiration timestamp of a specific mode, given its mode ID.
     * It reverts if the provided expiration timestamp is in the past or if the mode ID is invalid.
     * Only an account with the MARKET_CONFIGURATOR_ROLE can call this function.
     * @param _modeId The ID of the mode whose expiration timestamp is to be updated.
     * @param _expirationTimestamp The new expiration timestamp for the mode.
     */
    function setModeExpiration(uint256 _modeId, uint32 _expirationTimestamp)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        require(_expirationTimestamp > block.timestamp, "OmniPool::setModeExpiration: Bad expiration timestamp.");
        require(_modeId != 0 && _modeId <= modeCount, "OmniPool::setModeExpiration: Bad mode ID.");
        modeConfigurations[_modeId].expirationTimestamp = _expirationTimestamp;
    }

    /**
     * @notice Sets a specific soft liquidation threshold for an account. This function can only be called by an account with the SOFT_LIQUIDATION_ROLE.
     * The soft liquidation threshold determines the health factor below which an account is considered for soft liquidation.
     * @dev The soft liquidation role should only be assigned to the admin or a smart contract that implements a strategy for why a user should receive a special soft liquidation.
     * @param _accountId The unique identifier of the account for which to set the soft liquidation threshold.
     * @param _softThreshold The soft liquidation threshold to set for the account.
     */
    function setAccountSoftLiquidation(bytes32 _accountId, uint32 _softThreshold)
        external
        onlyRole(SOFT_LIQUIDATION_ROLE)
    {
        if (_softThreshold > MAX_BASE_SOFT_LIQUIDATION || _softThreshold < HEALTH_FACTOR_SCALE) {
            revert(
                "OmniPool::setSoftLiquidation: Soft liquidation health factor threshold cannot be greater than the standard max and must be greater than 1."
            );
        }
        accountInfos[_accountId].softThreshold = _softThreshold;
    }

    /**
     * @notice Sets the configuration for liquidation bonuses for a specific market. This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * The configuration includes parameters that affect the calculation of liquidation bonuses during the liquidation process.
     * @param _market The address of the market for which to set the liquidation bonus configuration.
     * @param _config The LiquidationBonusConfiguration struct containing the configuration for liquidation bonuses.
     */
    function setLiquidationBonusConfiguration(address _market, LiquidationBonusConfiguration calldata _config)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        require(
            _config.kink <= MAX_LIQ_KINK,
            "OmniPool::setLiquidationBonusConfiguration: Bad kink for maximum liquidation."
        );
        require(
            _config.start <= _config.end && _config.end <= LIQ_BONUS_PRECISION_SCALE,
            "OmniPool::setLiquidationBonusConfiguration: Bad start and end bonus values."
        );
        if (_config.expiredBonus > LIQ_BONUS_PRECISION_SCALE) {
            revert("OmniPool::setLiquidationBonusConfiguration: Bad expired bonus value.");
        }
        if (_config.softThreshold > MAX_BASE_SOFT_LIQUIDATION || _config.softThreshold < HEALTH_FACTOR_SCALE) {
            revert(
                "OmniPool::setSoftLiquidation: Soft liquidation health factor threshold cannot be greater than the standard max and must be greater than 1."
            );
        }
        liquidationBonusConfigurations[_market] = _config;
    }

    /**
     * @notice Sets the tranche count for a specific market.
     * @dev This function allows to set the number of tranches for a given market.
     * It's an external function that can only be called by an account with the `MARKET_CONFIGURATOR_ROLE`.
     * @param _market The address of the market contract.
     * @param _trancheCount The number of tranches to be set for the market.
     */
    function setTrancheCount(address _market, uint8 _trancheCount) external onlyRole(MARKET_CONFIGURATOR_ROLE) {
        IOmniToken(_market).setTrancheCount(_trancheCount);
    }

    /**
     * @notice Sets the borrow cap for each tranche of a specific market.
     * @dev This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * It invokes the setTrancheBorrowCaps function of the IOmniToken contract associated with the specified market.
     * @param _market The address of the market for which to set the borrow caps.
     * @param _borrowCaps An array of borrow cap values, one for each tranche of the market.
     */
    function setBorrowCap(address _market, uint256[] calldata _borrowCaps)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        for (uint256 i = 0; i < _borrowCaps.length - 1; ++i) {
            require(_borrowCaps[i] >= _borrowCaps[i + 1], "OmniPool::setBorrowCap: Invalid borrow cap.");
        }
        IOmniToken(_market).setTrancheBorrowCaps(_borrowCaps);
    }

    /**
     * @notice Sets the supply cap for a market that doesn't allow borrowing.
     * @dev This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * It invokes the setSupplyCap function of the IOmniTokenNoBorrow contract associated with the specified market.
     * @param _market The address of the market for which to set the no-borrow supply cap.
     * @param _noBorrowSupplyCap The value of the no-borrow supply cap to set.
     */
    function setNoBorrowSupplyCap(address _market, uint256 _noBorrowSupplyCap)
        external
        onlyRole(MARKET_CONFIGURATOR_ROLE)
    {
        IOmniTokenNoBorrow(_market).setSupplyCap(_noBorrowSupplyCap);
    }

    /**
     * @notice Sets the reserve receiver's address. This function can only be called by an account with the DEFAULT_ADMIN_ROLE.
     * @dev The reserve receiver's address is converted to a bytes32 account identifier using the toAccount function with a subId of 0.
     * @param _reserveReceiver The address of the reserve receiver to be set.
     */
    function setReserveReceiver(address _reserveReceiver) external onlyRole(DEFAULT_ADMIN_ROLE) {
        reserveReceiver = _reserveReceiver.toAccount(0);
    }

    /**
     * @notice Pauses the protocol, halting certain functionalities, i.e. withdraw, borrow, repay, liquidate.
     * @dev This function triggers the `_pause()` internal function and sets `pauseTranche` to 0.
     * It's an external function that can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * The function can only be executed when the contract is not already paused,
     * which is checked by the `whenNotPaused` modifier.
     */
    function pause() external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
        pauseTranche = 0;
        emit PausedTranche(0);
    }

    /**
     * @notice Unpauses the protocol, re-enabling certain functionalities, i.e. withdraw, borrow, repay, liquidate.
     * @dev This function triggers the `_unpause()` internal function and calls `resetPauseTranche()` to reset tranche pause state.
     * It's an external function that can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * The function can only be executed when the contract is paused,
     * which is checked by the `whenPaused` modifier.
     */
    function unpause() external whenPaused onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
        resetPauseTranche();
    }

    /**
     * @dev Internal utility function to check if a specific value exists within an array of addresses.
     * @param _arr The array of addresses to search.
     * @param _value The address value to look for within the array.
     * @return A boolean indicating whether the value exists within the array.
     */
    function _contains(address[] memory _arr, address _value) internal pure returns (bool) {
        for (uint256 i = 0; i < _arr.length; ++i) {
            if (_arr[i] == _value) {
                return true;
            }
        }
        return false;
    }
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

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

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

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: lib/openzeppelin-contracts/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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 10, 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 * 8) < value ? 1 : 0);
        }
    }
}

// File: src/interfaces/IOmniOracle.sol



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

/**
 * @title IOmniOracle Interface
 * @notice Interface for the OmniOracle contract.
 */
interface IOmniOracle {
    /// Events
    event SetOracle(
        address indexed underlying,
        address indexed oracle,
        Provider provider,
        uint32 delay,
        uint32 delayQuote,
        uint8 underlyingDecimals
    );
    event RemoveOracle(address indexed underlying);

    /// Structs
    enum Provider {
        Invalid,
        Band,
        Chainlink,
        Other // Must implement the ICustomOmniOracle interface, use very carefully should return 1 full unit price multiplied by 1e18
    }

    struct OracleConfig {
        // One storage slot
        address oracleAddress; // 160 bits
        Provider provider; // 8 bits
        uint32 delay; // 32 bits, because this is time-based in unix
        uint32 delayQuote; // 32 bits, for Band quote delay
        uint8 underlyingDecimals; // 8 bits, decimals of underlying token
    }

    /**
     * @notice Fetches the price of the specified asset.
     * @param _underlying The address of the asset.
     * @return The price of the asset, normalized to 1e18.
     */
    function getPrice(address _underlying) external view returns (uint256);
}

// File: src/interfaces/IOmniPool.sol



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

/**
 * @title IOmniPool Interface
 * @dev This interface outlines the functions available in the OmniPool contract.
 */
interface IOmniPool {
    /// Events
    event ClearedMarkets(bytes32 indexed account);
    event EnteredIsolatedMarket(bytes32 indexed account, address market);
    event EnteredMarkets(bytes32 indexed account, address[] markets);
    event EnteredMode(bytes32 indexed account, uint256 modeId);
    event ExitedMarket(bytes32 indexed account, address market);
    event ExitedMode(bytes32 indexed account);
    event Liquidated(
        address indexed liquidator,
        bytes32 indexed targetAccount,
        bytes32 liquidatorAccount,
        address liquidateMarket,
        address collateralMarket,
        uint256 amount
    );
    event PausedTranche(uint8 trancheId);
    event UnpausedTranche();
    event SetMarketConfiguration(address indexed market, MarketConfiguration marketConfig);
    event RemovedMarketConfiguration(address indexed market);
    event SetModeConfiguration(uint256 indexed modeId, ModeConfiguration modeConfig);
    event SocializedLoss(address indexed market, uint8 trancheId, bytes32 account);

    // Structs
    /**
     * @dev Structure to hold market configuration data.
     */
    struct MarketConfiguration {
        uint32 collateralFactor;
        uint32 borrowFactor; // Set to 0 if not borrowable.
        uint32 expirationTimestamp;
        uint8 riskTranche;
        bool isIsolatedCollateral; // If this is false, riskTranche must be 0
    }

    /**
     * @dev Structure to hold mode configuration data.
     */
    struct ModeConfiguration {
        uint32 collateralFactor;
        uint32 borrowFactor;
        uint8 modeTranche;
        uint32 expirationTimestamp; // Only prevents people from entering a mode, does not affect users already in existing mode
        address[] markets;
    }

    /**
     * @dev Structure to hold account specific data.
     */
    struct AccountInfo {
        uint8 modeId;
        address isolatedCollateralMarket;
        uint32 softThreshold;
    }

    /**
     * @dev Structure to hold evaluation data for an account.
     */
    struct Evaluation {
        uint256 depositTrueValue;
        uint256 borrowTrueValue;
        uint256 depositAdjValue;
        uint256 borrowAdjValue;
        uint64 numDeposit; // To combine into 1 storage slot
        uint64 numBorrow;
        bool isExpired;
    }

    /**
     * @dev Structure to hold liquidation bonus configuration data.
     */
    struct LiquidationBonusConfiguration {
        uint64 start; // 1e9 precision
        uint64 end; // 1e9 precision
        uint64 kink; // 1e9 precision
        uint32 expiredBonus; // 1e9 precision
        uint32 softThreshold; // 1e9 precision
    }

    /**
     * @dev Structure to hold liquidation arguments.
     */
    struct LiquidationParams {
        bytes32 targetAccountId; // The unique identifier of the target account to be liquidated.
        bytes32 liquidatorAccountId; // The unique identifier of the account initiating the liquidation.
        address liquidateMarket; // The address of the market from which to repay the borrow.
        address collateralMarket; // The address of the market from which to seize collateral.
        uint256 amount; // The amount of the target account's borrow balance to repay. If _amount is 0, liquidator will repay the entire borrow balance, and will error if the repayment is too large.
    }

    // Function Signatures
    /**
     * @dev Returns the address of the oracle contract.
     * @return The address of the oracle.
     */
    function oracle() external view returns (address);

    /**
     * @dev Returns the pause tranche value.
     * @return The pause tranche value.
     */
    function pauseTranche() external view returns (uint8);

    /**
     * @dev Returns the reserve receiver.
     * @return The reserve receiver identifier.
     */
    function reserveReceiver() external view returns (bytes32);

    /**
     * @dev Allows a user to enter an isolated market, the market configuration must be for isolated collateral.
     * @param _subId The identifier of the sub-account.
     * @param _isolatedMarket The address of the isolated market to enter.
     */
    function enterIsolatedMarket(uint96 _subId, address _isolatedMarket) external;

    /**
     * @dev Allows a user to enter multiple unique markets, none of them are isolated collateral markets.
     * @param _subId The identifier of the sub-account.
     * @param _markets The addresses of the markets to enter.
     */
    function enterMarkets(uint96 _subId, address[] calldata _markets) external;

    /**
     * @dev Allows a user to exit a single market including their isolated market. There must be no borrows active on the subaccount to exit a market.
     * @param _subId The identifier of the sub-account.
     * @param _market The addresses of the markets to exit.
     */
    function exitMarket(uint96 _subId, address _market) external;

    /**
     * @dev Clears all markets for a user. The subaccount must have no active borrows to clear markets.
     * @param _subId The identifier of the sub-account.
     */
    function clearMarkets(uint96 _subId) external;

    /**
     * @dev Sets a mode for a sub-account.
     * @param _subId The identifier of the sub-account.
     * @param _modeId The identifier of the mode to enter.
     */
    function enterMode(uint96 _subId, uint8 _modeId) external;

    /**
     * @dev Exits the mode currently set for a sub-account.
     * @param _subId The identifier of the sub-account.
     */
    function exitMode(uint96 _subId) external;

    /**
     * @dev Evaluates an account's financial metrics.
     * @param _accountId The identifier of the account.
     * @return eval A struct containing the evaluated metrics of the account.
     */
    function evaluateAccount(bytes32 _accountId) external returns (Evaluation memory eval);

    /**
     * @dev Allows a sub-account to borrow assets from a specified market.
     * @param _subId The identifier of the sub-account.
     * @param _market The address of the market to borrow from.
     * @param _amount The amount of assets to borrow.
     */
    function borrow(uint96 _subId, address _market, uint256 _amount) external;

    /**
     * @dev Allows a sub-account to repay borrowed assets to a specified market.
     * @param _subId The identifier of the sub-account.
     * @param _market The address of the market to repay to.
     * @param _amount The amount of assets to repay.
     */
    function repay(uint96 _subId, address _market, uint256 _amount) external;

    /**
     * @dev Initiates a liquidation process to recover assets from an under-collateralized account.
     * @param _params The liquidation parameters.
     * @return seizedShares The amount of shares seized from the liquidated account.
     */
    function liquidate(
        LiquidationParams calldata _params
    ) external returns (uint256[] memory seizedShares);

    /**
     * @dev Distributes loss incurred in a market to a specified tranche of accounts.
     * @param _market The address of the market where the loss occurred.
     * @param _account The account identifier to record the loss.
     */
    function socializeLoss(address _market, bytes32 _account) external;

    /**
     * @dev Retrieves the borrow tier of an account.
     * @param _account The account info struct containing the account's details.
     * @return The borrowing tier of the account.
     */
    function getAccountBorrowTier(AccountInfo memory _account) external view returns (uint8);

    /**
     * @dev Retrieves the market addresses associated with an account.
     * @param _accountId The identifier of the account.
     * @param _account The account info struct containing the account's details.
     * @return A list of market addresses associated with the account.
     */
    function getAccountPoolMarkets(bytes32 _accountId, AccountInfo memory _account)
        external
        view
        returns (address[] memory);

    /**
     * @dev Retrieves the liquidation bonus and soft threshold values for a market.
     * @param _depositAdjValue The adjusted value of deposits in the market.
     * @param _borrowAdjValue The adjusted value of borrows in the market.
     * @param _collateralMarket The address of the collateral market.
     * @return bonus The liquidation bonus value.
     * @return softThreshold The soft liquidation threshold value.
     */
    function getLiquidationBonusAndThreshold(
        uint256 _depositAdjValue,
        uint256 _borrowAdjValue,
        address _collateralMarket
    ) external view returns (uint256 bonus, uint256 softThreshold);

    /**
     * @dev Checks if an account is healthy based on its financial metrics.
     * @param _accountId The identifier of the account.
     * @return A boolean indicating whether the account is healthy.
     */
    function isAccountHealthy(bytes32 _accountId) external returns (bool);

    /**
     * @dev Resets the pause tranche to its initial state.
     */
    function resetPauseTranche() external;

    /**
     * @dev Updates the market configuration.
     * @param _market The address of the market.
     * @param _marketConfig The market configuration data.
     */
    function setMarketConfiguration(address _market, MarketConfiguration calldata _marketConfig) external;

    /**
     * @dev Updates mode configurations one at a time.
     * @param _modeConfiguration An single mode configuration.
     */
    function setModeConfiguration(ModeConfiguration calldata _modeConfiguration) external;

    /**
     * @dev Updates the soft liquidation threshold for an account.
     * @param _accountId The account identifier.
     * @param _softThreshold The soft liquidation threshold value.
     */
    function setAccountSoftLiquidation(bytes32 _accountId, uint32 _softThreshold) external;

    /**
     * @dev Updates the liquidation bonus configuration for a market.
     * @param _market The address of the market.
     * @param _config The liquidation bonus configuration data.
     */
    function setLiquidationBonusConfiguration(address _market, LiquidationBonusConfiguration calldata _config) external;

    /**
     * @notice Sets the tranche count for a specific market.
     * @dev This function allows to set the number of tranches for a given market.
     * It's an external function that can only be called by an account with the `MARKET_CONFIGURATOR_ROLE`.
     * @param _market The address of the market contract.
     * @param _trancheCount The number of tranches to be set for the market.
     */
    function setTrancheCount(address _market, uint8 _trancheCount) external;

    /**
     * @dev This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * It invokes the setTrancheBorrowCaps function of the IOmniToken contract associated with the specified market.
     * @param _market The address of the market for which to set the borrow caps.
     * @param _borrowCaps An array of borrow cap values, one for each tranche of the market.
     */
    function setBorrowCap(address _market, uint256[] calldata _borrowCaps) external;

    /**
     * @dev This function can only be called by an account with the MARKET_CONFIGURATOR_ROLE.
     * It invokes the setSupplyCap function of the IOmniTokenNoBorrow contract associated with the specified market.
     * @param _market The address of the market for which to set the no-borrow supply cap.
     * @param _noBorrowSupplyCap The value of the no-borrow supply cap to set.
     */
    function setNoBorrowSupplyCap(address _market, uint256 _noBorrowSupplyCap) external;

    /**
     * @notice Sets the reserve receiver's address. This function can only be called by an account with the DEFAULT_ADMIN_ROLE.
     * @dev The reserve receiver's address is converted to a bytes32 account identifier using the toAccount function with a subId of 0.
     * @param _reserveReceiver The address of the reserve receiver to be set.
     */
    function setReserveReceiver(address _reserveReceiver) external;
}

// File: src/interfaces/IOmniToken.sol



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

import "./IOmniTokenBase.sol";

/**
 * @title IOmniToken
 * @notice Interface for the OmniToken contract which manages deposits, withdrawals, borrowings, and repayments within the Omni protocol.
 */
interface IOmniToken is IOmniTokenBase {
    /// Events
    event Accrue();
    event Deposit(bytes32 indexed account, uint8 indexed trancheId, uint256 amount, uint256 share);
    event Withdraw(bytes32 indexed account, uint8 indexed trancheId, uint256 amount, uint256 share);
    event Borrow(bytes32 indexed account, uint8 indexed trancheId, uint256 amount, uint256 share);
    event Repay(bytes32 indexed account, address indexed payer, uint8 indexed trancheId, uint256 amount, uint256 share);
    event Seize(bytes32 indexed account, bytes32 indexed to, uint256 amount, uint256[] seizedShares);
    event SetTrancheCount(uint8 trancheCount);
    event SetTrancheBorrowCaps(uint256[] borrowCaps);
    event SocializedLoss(bytes32 indexed account, uint8 indexed trancheId, uint256 amount, uint256 share);
    event Transfer(bytes32 indexed from, bytes32 indexed to, uint8 indexed trancheId, uint256 share);

    /**
     * @notice Gets the address of the OmniPool contract.
     * @return The address of the OmniPool contract.
     */
    function omniPool() external view returns (address);

    /**
     * @notice Gets the address of the Interest Rate Model (IRM) contract.
     * @return The address of the IRM contract.
     */
    function irm() external view returns (address);

    /**
     * @notice Gets the last accrual time.
     * @return The timestamp of the last accrual time.
     */
    function lastAccrualTime() external view returns (uint256);

    /**
     * @notice Gets the count of tranches.
     * @return The total number of tranches.
     */
    function trancheCount() external view returns (uint8);

    /**
     * @notice Gets the reserve receiver.
     * @return The bytes32 identifier of the reserve receiver.
     */
    function reserveReceiver() external view returns (bytes32);

    /**
     * @notice Gets the borrow cap for a specific tranche.
     * @param _trancheId The ID of the tranche for which to retrieve the borrow cap.
     * @return The borrow cap for the specified tranche.
     */
    function getBorrowCap(uint8 _trancheId) external view returns (uint256);

    /**
     * @notice Accrues interest for all tranches, calculates and distributes the interest among the depositors and updates tranche balances.
     * The function also handles reserve payments. This method needs to be called before any deposit, withdrawal, borrow, or repayment actions to update the state of the contract.
     * @dev Interest is paid out proportionately to more risky tranche deposits per tranche
     */
    function accrue() external;

    /**
     * @notice Deposits a specified amount into a specified tranche.
     * @param _subId Sub-account identifier for the depositor.
     * @param _trancheId Identifier of the tranche to deposit into.
     * @param _amount Amount to deposit.
     * @return share Amount of deposit shares received in exchange for the deposit.
     */
    function deposit(uint96 _subId, uint8 _trancheId, uint256 _amount) external returns (uint256 share);

    /**
     * @notice Withdraws funds from a specified tranche.
     * @param _subId The ID of the sub-account.
     * @param _trancheId The ID of the tranche.
     * @param _share The share of the user in the tranche.
     * @return amount The amount of funds withdrawn.
     */
    function withdraw(uint96 _subId, uint8 _trancheId, uint256 _share) external returns (uint256 amount);

    /**
     * @notice Borrows funds from a specified tranche.
     * @param _account The account of the user.
     * @param _trancheId The ID of the tranche.
     * @param _amount The amount to borrow.
     * @return share The share of the borrowed amount in the tranche.
     */
    function borrow(bytes32 _account, uint8 _trancheId, uint256 _amount) external returns (uint256 share);

    /**
     * @notice Repays borrowed funds.
     * @param _account The account of the user.
     * @param _payer The account that will pay the borrowed amount.
     * @param _trancheId The ID of the tranche.
     * @param _amount The amount to repay.
     * @return amount The amount of the repaid amount in the tranche.
     */
    function repay(bytes32 _account, address _payer, uint8 _trancheId, uint256 _amount)
        external
        returns (uint256 amount);

    /**
     * @notice Transfers specified shares from one account to another within a specified tranche.
     * @param _subId The subscription ID related to the sender's account.
     * @param _to The account identifier to which shares are being transferred.
     * @param _trancheId The identifier of the tranche where the transfer is occurring.
     * @param _shares The amount of shares to transfer.
     * @return A boolean value indicating whether the transfer was successful.
     */
    function transfer(uint96 _subId, bytes32 _to, uint8 _trancheId, uint256 _shares) external returns (bool);

    /**
     * @notice Distributes the bad debt loss in a tranche among all tranche members. This function should only be called by the OmniPool.
     * @param _account The account that incurred a loss.
     * @param _trancheId The ID of the tranche.
     */
    function socializeLoss(bytes32 _account, uint8 _trancheId) external;

    /**
     * @notice Computes the borrowing amount of a specific account in the underlying asset for a given borrow tier.
     * @dev The division is ceiling division.
     * @param _account The account identifier for which the borrowing amount is to be computed.
     * @param _borrowTier The borrow tier identifier from which the borrowing amount is to be computed.
     * @return The borrowing amount of the account in the underlying asset for the given borrow tier.
     */
    function getAccountBorrowInUnderlying(bytes32 _account, uint8 _borrowTier) external view returns (uint256);

    /**
     * @notice Retrieves the deposit and borrow shares for a specific account in a specific tranche.
     * @param _account The account identifier.
     * @param _trancheId The tranche identifier.
     * @return depositShare The deposit share.
     * @return borrowShare The borrow share.
     */
    function getAccountSharesByTranche(bytes32 _account, uint8 _trancheId)
        external
        view
        returns (uint256 depositShare, uint256 borrowShare);

    /**
     * @notice Sets the borrow caps for each tranche.
     * @param _borrowCaps An array of borrow caps in the underlying's decimals.
     */
    function setTrancheBorrowCaps(uint256[] calldata _borrowCaps) external;

    /**
     * @notice Sets the number of tranches.
     * @param _trancheCount The new tranche count.
     */
    function setTrancheCount(uint8 _trancheCount) external;

    /**
     * @notice Fetches and updates the reserve receiver from the OmniPool contract.
     */
    function fetchReserveReceiver() external;
}

// File: src/interfaces/IOmniTokenNoBorrow.sol



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

import "./IOmniTokenBase.sol";

/**
 * @title IOmniTokenNoBorrow
 * @notice Interface for the OmniTokenNoBorrow contract which provides deposit and withdrawal features, without borrowing features.
 */
interface IOmniTokenNoBorrow is IOmniTokenBase {
    /// Events
    event Deposit(bytes32 indexed account, uint256 amount);
    event Withdraw(bytes32 indexed account, uint256 amount);
    event Seize(bytes32 indexed account, bytes32 indexed to, uint256 amount, uint256[] seizeShares);
    event SetSupplyCap(uint256 supplyCap);
    event Transfer(bytes32 indexed from, bytes32 indexed to, uint256 amount);
    
    /**
     * @notice Deposits a specified amount to the account.
     * @param _subId The sub-account identifier.
     * @param _amount The amount to deposit.
     * @return amount The actual amount deposited.
     */
    function deposit(uint96 _subId, uint256 _amount) external returns (uint256 amount);

    /**
     * @notice Withdraws a specified amount from the account.
     * @param _subId The sub-account identifier.
     * @param _amount The amount to withdraw.
     * @return amount The actual amount withdrawn.
     */
    function withdraw(uint96 _subId, uint256 _amount) external returns (uint256 amount);

    /**
     * @notice Transfers a specified amount of tokens from the sender's account to another account.
     * @param _subId The subscription ID associated with the sender's account.
     * @param _to The account identifier to which the tokens are being transferred.
     * @param _amount The amount of tokens to transfer.
     * @return A boolean value indicating whether the transfer was successful.
     */
    function transfer(uint96 _subId, bytes32 _to, uint256 _amount) external returns (bool);

    /**
     * @notice Sets a new supply cap for the contract.
     * @param _supplyCap The new supply cap amount.
     */
    function setSupplyCap(uint256 _supplyCap) external;
}

// File: src/interfaces/IWithUnderlying.sol



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

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

/**
 * @title IWithUnderlying
 * @notice Interface for the WithUnderlying contract to handle the inflow and outflow of ERC20 tokens.
 */
interface IWithUnderlying {
    /**
     * @notice Gets the address of the underlying ERC20 token.
     * @return The address of the underlying ERC20 token.
     */
    function underlying() external view returns (address);
}

// File: src/SubAccount.sol



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

/**
 * @title SubAccount
 * @notice This library provides utility functions to handle sub-accounts using bytes32 types, where id is most significant bytes.
 */
library SubAccount {
    /**
     * @notice Combines an address and a sub-account identifier into a bytes32 account representation.
     * @param _sender The address component.
     * @param _subId The sub-account identifier component.
     * @return A bytes32 representation of the account.
     */
    function toAccount(address _sender, uint96 _subId) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(_sender)) | (uint256(_subId) << 160));
    }

    /**
     * @notice Extracts the address component from a bytes32 account representation.
     * @param _account The bytes32 representation of the account.
     * @return The address component.
     */
    function toAddress(bytes32 _account) internal pure returns (address) {
        return address(uint160(uint256(_account)));
    }

    /**
     * @notice Extracts the sub-account identifier component from a bytes32 account representation.
     * @param _account The bytes32 representation of the account.
     * @return The sub-account identifier component.
     */
    function toSubId(bytes32 _account) internal pure returns (uint96) {
        return uint96(uint256(_account) >> 160);
    }
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/access/IAccessControlUpgradeable.sol



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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol



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

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol



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

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";

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

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

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

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

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

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol



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

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol



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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

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

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

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

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

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

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

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

    /**
     * @dev Internal function that returns the initialized version. Returns `_initialized`
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initializing`
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

// File: src/interfaces/IOmniTokenBase.sol



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

/**
 * @title IOmniTokenBase
 * @notice Base interface shared by the IOmniToken and IOmniTokenNoBorrow interfaces.
 */
interface IOmniTokenBase {
    /**
     * @notice Retrieves the total deposit amount for a specific account.
     * @param _account The account identifier.
     * @return The total deposit amount.
     */
    function getAccountDepositInUnderlying(bytes32 _account) external view returns (uint256);

    /**
     * @notice Calculates the total deposited amount for a specific owner across sub-accounts. This funciton is for wallets and Etherscan to pick up balances.
     * @param _owner The address of the owner.
     * @return The total deposited amount.
     */
    function balanceOf(address _owner) external view returns (uint256);

    /**
     * @notice Seizes funds from a user's account in the event of a liquidation. This is a priveleged function only callable by the OmniPool and must be implemented carefully.
     * @param _account The account from which funds will be seized.
     * @param _to The account to which seized funds will be sent.
     * @param _amount The amount of funds to seize.
     * @return The shares seized from each tranche.
     */
    function seize(bytes32 _account, bytes32 _to, uint256 _amount) external returns (uint256[] memory);
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    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) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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 10, 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 * 8) < value ? 1 : 0);
        }
    }
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol



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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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