Skip to content
Verified contractExactBUSL-1.1

AaveDeloopAdapter

Address0x2568a12524c037658fbfee1f3e16bc06c8e9546c
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 4,000 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,628,689
Creation transaction
0x92e9915cdd…3416e6a8a2

31 files

contracts/adapters/AaveDeloopAdapter.sol

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

import { UtilLib } from "../utils/UtilLib.sol";
import { LRTConstants } from "../utils/LRTConstants.sol";
import { LRTConfigRoleChecker, ILRTConfig } from "../utils/LRTConfigRoleChecker.sol";

import { IAaveDeloopAdapter } from "../interfaces/IAaveDeloopAdapter.sol";
import { ILRTDepositPool } from "../interfaces/ILRTDepositPool.sol";
import { ILRTWithdrawalManager } from "../interfaces/ILRTWithdrawalManager.sol";
import { ILRTOracle } from "../interfaces/ILRTOracle.sol";
import { IWstETH } from "../external/lido/IWstETH.sol";
import { IWETH } from "../external/weth/IWETH.sol";

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {
    ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { ReserveConfiguration } from "../external/aave/ReserveConfiguration.sol";
import { UserConfiguration } from "../external/aave/UserConfiguration.sol";
import { DataTypes } from "../external/aave/DataTypes.sol";

import { EModeConfiguration } from "../external/aave/EModeConfiguration.sol";

import { IPool } from "../external/aave/IPool.sol";
import { IPoolAddressesProvider } from "../external/aave/IPoolAddressesProvider.sol";

import { IPriceOracleGetter } from "../external/aave/IPriceOracleGetter.sol";

interface IVariableDebtDelegationToken {
    function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}

/**
 * @title AaveDeloopAdapter
 * @notice Coordinates iterative loop and deloop actions for rsETH positions on Aave V3.
 */
contract AaveDeloopAdapter is
    IAaveDeloopAdapter,
    LRTConfigRoleChecker,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable
{
    using SafeERC20 for IERC20;
    using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
    using UserConfiguration for DataTypes.UserConfigurationMap;

    /// @dev Aggregates the user account fields needed for max-withdraw math (avoids stack-too-deep in callers).
    struct AccountData {
        uint256 totalCollateralBase; // Sum of (collateral balance × price) for all collateral, in base currency
        uint256 totalDebtBase; // Sum of (debt balance × price) for all borrows, in base currency
        uint256 currentLiquidationThreshold; // Weighted-average liquidation threshold in bps (from getUserAccountData)
    }

    struct DeloopState {
        address user;
        address debtAsset;
        address withdrawalAsset;
        uint256 remainingRsETHBudget;
        uint256 totalRsETHWithdrawn;
        uint256 iterations;
        uint256 remainingDebt;
    }

    struct LoopState {
        address user;
        address debtAsset;
        uint256 targetDebtIncrease;
        uint256 maxRsETHInput;
        uint256 minHealthFactor;
        uint256 minDebtPerIteration;
        uint256 totalDebtIncreased;
        uint256 totalRsETHSupplied;
        uint256 iterations;
    }

    /*//////////////////////////////////////////////////////////////
                              CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Default deployment value for loop/deloop iteration caps.
    uint256 public constant MAX_ITERATIONS = 20;

    /// @dev Aave variable-rate mode identifier (used in repay calls)
    uint256 private constant VARIABLE_RATE_MODE = 2;

    /// @dev Hard upper bound on loop/deloop iteration caps to protect against misconfiguration
    uint256 private constant ABS_MAX_ITERATIONS = 100;

    /*//////////////////////////////////////////////////////////////
                            STATE VARIABLES
    //////////////////////////////////////////////////////////////*/

    uint256 public minHealthFactorFloor;

    IPool public aavePool;

    address public weth;

    address public wstETH;

    address public stETH;

    address public rsETH;

    address public aRsETH;

    address public variableDebtWETH;

    address public variableDebtWstETH;

    uint256 public maxLoopIterations;

    uint256 public maxDeloopIterations;

    uint256 public boostLiquidity;

    /*//////////////////////////////////////////////////////////////
                              CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /*//////////////////////////////////////////////////////////////
                              INITIALIZER
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Initialize the adapter
     * @param lrtConfigAddr LRT config address
     * @param aavePool_ AAVE V3 Pool address
     * @param weth_ WETH token address
     * @param wstETH_ wstETH token address
     * @param stETH_ stETH token address
     * @param aRsETH_ AAVE aToken for rsETH
     * @param variableDebtWETH_ AAVE variable debt token for WETH
     * @param variableDebtWstETH_ AAVE variable debt token for wstETH
     * @param maxDeloopIterations_ Initial cap for deloop iterations (1–ABS_MAX_ITERATIONS)
     * @param maxLoopIterations_ Initial cap for loop iterations (1–ABS_MAX_ITERATIONS)
     * @param minHealthFactorFloor_ Minimum health factor for collateral withdrawals (>= 1e18)
     */
    function initialize(
        address lrtConfigAddr,
        address aavePool_,
        address weth_,
        address wstETH_,
        address stETH_,
        address aRsETH_,
        address variableDebtWETH_,
        address variableDebtWstETH_,
        uint256 maxDeloopIterations_,
        uint256 maxLoopIterations_,
        uint256 minHealthFactorFloor_
    )
        external
        initializer
    {
        UtilLib.checkNonZeroAddress(lrtConfigAddr);
        UtilLib.checkNonZeroAddress(aavePool_);
        UtilLib.checkNonZeroAddress(weth_);
        UtilLib.checkNonZeroAddress(wstETH_);
        UtilLib.checkNonZeroAddress(stETH_);
        UtilLib.checkNonZeroAddress(aRsETH_);
        UtilLib.checkNonZeroAddress(variableDebtWETH_);
        UtilLib.checkNonZeroAddress(variableDebtWstETH_);

        if (maxDeloopIterations_ == 0 || maxDeloopIterations_ > ABS_MAX_ITERATIONS) {
            revert MaxDeloopIterationsInvalid();
        }
        if (maxLoopIterations_ == 0 || maxLoopIterations_ > ABS_MAX_ITERATIONS) {
            revert MaxLoopIterationsInvalid();
        }
        if (minHealthFactorFloor_ < 1e18) revert MinHealthFactorTooLow();
        __Pausable_init();
        __ReentrancyGuard_init();

        lrtConfig = ILRTConfig(lrtConfigAddr);
        aavePool = IPool(aavePool_);
        weth = weth_;
        wstETH = wstETH_;
        stETH = stETH_;
        rsETH = lrtConfig.rsETH();

        aRsETH = aRsETH_;
        variableDebtWETH = variableDebtWETH_;
        variableDebtWstETH = variableDebtWstETH_;

        maxDeloopIterations = maxDeloopIterations_;
        maxLoopIterations = maxLoopIterations_;
        minHealthFactorFloor = minHealthFactorFloor_;

        emit UpdatedLRTConfig(lrtConfigAddr);
        emit AdapterInitialized(
            aavePool_, weth_, wstETH_, stETH_, rsETH, aRsETH_, variableDebtWETH_, variableDebtWstETH_
        );
        emit MaxDeloopIterationsUpdated(0, maxDeloopIterations_);
        emit MaxLoopIterationsUpdated(0, maxLoopIterations_);
        emit MinHealthFactorUpdated(0, minHealthFactorFloor_);
    }

    /*//////////////////////////////////////////////////////////////
                            RECEIVE FUNCTION
    //////////////////////////////////////////////////////////////*/

    receive() external payable { }

    /*//////////////////////////////////////////////////////////////
                            CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function deloop(
        address debtAsset,
        uint256 debtAmount,
        uint256 maxRsETHAmount,
        uint256 minHealthFactor
    )
        external
        override
        nonReentrant
        whenNotPaused
    {
        DeloopState memory state;
        state.user = msg.sender;
        state.debtAsset = debtAsset;
        state.withdrawalAsset = _getWithdrawalAssetFromDebt(debtAsset);

        _validateInstantWithdrawalEnabled(state.withdrawalAsset);
        uint256 initialDebtAssetBalance = IERC20(debtAsset).balanceOf(address(this));
        uint256 healthFactorBeforeDeloop = _getHealthFactor(state.user);
        uint256 userDebtBeforeDeloop = _getUserDebt(state.user, debtAsset);

        uint256 targetDebtToRepay = debtAmount > userDebtBeforeDeloop ? userDebtBeforeDeloop : debtAmount;

        if (targetDebtToRepay == 0) revert NoDebtToRepay();

        uint256 rsETHForDebt = _calculateRsETHForDebt(targetDebtToRepay, state.withdrawalAsset);
        if (rsETHForDebt > maxRsETHAmount) {
            revert MaxRsETHExceeded();
        }
        _validateATokenApproval(state.user, rsETHForDebt);
        uint256 preBoostRsETHBalance = IERC20(rsETH).balanceOf(address(this));
        _supplyBoostLiquidity(state.user);

        state.remainingRsETHBudget = maxRsETHAmount;
        state.remainingDebt = targetDebtToRepay;
        while (state.remainingDebt > 0 && state.iterations < maxDeloopIterations) {
            state.iterations++;
            if (!_executeDeloopIteration(state)) break;
            if (state.iterations >= maxDeloopIterations && state.remainingDebt > 0) {
                revert MaxIterationsExceeded();
            }
        }

        _withdrawAndValidateBoost(state.user, preBoostRsETHBalance);

        uint256 remainingDebtAfterDeloop = _getUserDebt(state.user, debtAsset);

        _validateMinHealthFactor(state.user, Math.max(healthFactorBeforeDeloop, minHealthFactor));

        _returnExcessToUser(debtAsset, state.user, initialDebtAssetBalance);

        if (state.remainingDebt > 0) {
            emit DeloopExitedEarly(state.user, state.remainingDebt, debtAsset);
        }

        emit Deloop(
            state.user,
            state.totalRsETHWithdrawn,
            userDebtBeforeDeloop - remainingDebtAfterDeloop, // total debt repaid
            debtAsset,
            state.iterations
        );
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function loop(
        address debtAsset,
        uint256 targetDebtIncrease,
        uint256 maxRsETHInput,
        uint256 minHealthFactor,
        uint256 minDebtPerIteration
    )
        external
        override
        nonReentrant
        whenNotPaused
    {
        minHealthFactor = minHealthFactor == 0 ? minHealthFactorFloor : minHealthFactor;
        _beforeLoop(debtAsset, targetDebtIncrease, maxRsETHInput, minDebtPerIteration, minHealthFactor);

        LoopState memory state;
        state.user = msg.sender;
        state.debtAsset = debtAsset;
        state.targetDebtIncrease = targetDebtIncrease;
        state.maxRsETHInput = maxRsETHInput;
        state.minHealthFactor = minHealthFactor;
        state.minDebtPerIteration = minDebtPerIteration;

        uint256 initialDebtAssetBalance = IERC20(debtAsset).balanceOf(address(this));
        uint256 preBoostRsETHBalance = IERC20(rsETH).balanceOf(address(this));
        _supplyBoostLiquidity(state.user);

        while (state.iterations < maxLoopIterations && state.totalDebtIncreased < state.targetDebtIncrease) {
            (uint256 debtToBorrow, uint256 remainingRsETHBudget, uint256 minRsETHOut) = _beforeLoopIteration(state);
            if (debtToBorrow == 0) break;

            (uint256 debtBorrowed, uint256 rsEthSupplied) =
                _executeLoopIteration(state.user, state.debtAsset, debtToBorrow, minRsETHOut);
            if (rsEthSupplied > remainingRsETHBudget) revert MaxRsETHExceeded();

            state.totalDebtIncreased += debtBorrowed;
            state.totalRsETHSupplied += rsEthSupplied;
            state.iterations++;
        }

        if (state.totalDebtIncreased < state.targetDebtIncrease) {
            if (state.iterations >= maxLoopIterations) revert MaxIterationsExceeded();
            emit LoopExitedEarly(state.user, state.totalDebtIncreased, state.targetDebtIncrease, state.debtAsset);
        }
        _withdrawAndValidateBoost(state.user, preBoostRsETHBalance);
        _validateMinHealthFactor(state.user, state.minHealthFactor);
        _returnExcessToUser(debtAsset, state.user, initialDebtAssetBalance);

        emit Loop(state.user, state.totalDebtIncreased, state.totalRsETHSupplied, state.debtAsset, state.iterations);
    }

    /**
     * @dev Validates all loop() inputs. minHealthFactor must already be resolved by the caller.
     */
    function _beforeLoop(
        address debtAsset,
        uint256 targetDebtIncrease,
        uint256 maxRsETHInput,
        uint256 minDebtPerIteration,
        uint256 minHealthFactor
    )
        internal
        view
    {
        _validateDebtAsset(debtAsset);
        if (targetDebtIncrease == 0 || maxRsETHInput == 0 || minDebtPerIteration == 0) revert InvalidAmount();
        if (minDebtPerIteration > targetDebtIncrease) revert InvalidAmount();
        if (minHealthFactor < minHealthFactorFloor) revert MinHealthFactorTooLow();
        _validateATokenApproval(msg.sender, 0);
    }

    /**
     * @dev Prepare a loop iteration. Reverts if the target cannot be reached — the only acceptable
     *      soft stop is when the remaining debt falls below the dust threshold (minDebtPerIteration).
     *
     * @param state  Packed loop configuration and running totals (avoids stack-too-deep).
     * @return debtToBorrow         Debt to borrow this iteration (0 = dust soft-stop, break the loop).
     * @return remainingRsETHBudget Remaining rsETH budget after this iteration.
     * @return minRsETHOut          Minimum rsETH that must be minted (slippage floor).
     */
    function _beforeLoopIteration(LoopState memory state)
        internal
        view
        returns (uint256 debtToBorrow, uint256 remainingRsETHBudget, uint256 minRsETHOut)
    {
        uint256 remainingDebtTarget = state.targetDebtIncrease - state.totalDebtIncreased;
        remainingRsETHBudget = state.maxRsETHInput - state.totalRsETHSupplied;

        // Only acceptable soft exit: dust remaining — not worth another iteration's gas
        if (remainingDebtTarget < state.minDebtPerIteration) {
            return (0, remainingRsETHBudget, 0);
        }

        uint256 maxBorrowableDebt = _calculateMaxBorrowableDebt(state.user, state.debtAsset, state.minHealthFactor);
        if (maxBorrowableDebt == 0) revert LoopNoBorrowCapacity();

        debtToBorrow = remainingDebtTarget < maxBorrowableDebt ? remainingDebtTarget : maxBorrowableDebt;
        uint256 rsETHQuote = _quoteRsETHFromDebtAsset(state.debtAsset, debtToBorrow);

        if (rsETHQuote > remainingRsETHBudget) {
            revert LoopBudgetExhausted();
        }

        minRsETHOut = rsETHQuote * 9999 / 10_000;
    }

    /**
     * @dev Borrow debt asset, convert to rsETH and resupply for user collateral.
     * @param minRsETHOut Minimum rsETH that must be minted from the deposit (slippage guard).
     */
    function _executeLoopIteration(
        address user,
        address debtAsset,
        uint256 debtToBorrow,
        uint256 minRsETHOut
    )
        internal
        returns (uint256 debtBorrowed, uint256 rsEthSupplied)
    {
        debtBorrowed = _borrowDebt(user, debtAsset, debtToBorrow);
        rsEthSupplied = _convertDebtAssetToRsETH(debtAsset, debtBorrowed, minRsETHOut);
        IERC20(rsETH).forceApprove(address(aavePool), rsEthSupplied);
        aavePool.supply(rsETH, rsEthSupplied, user, 0);
    }

    /**
     * @dev Get the current health factor of the user
     */
    function _getHealthFactor(address user) internal view returns (uint256 currentHF) {
        (,,,,, currentHF) = aavePool.getUserAccountData(user);
    }

    /**
     * @dev Supply tracked manager boost rsETH to user's position
     */
    function _supplyBoostLiquidity(address user) internal {
        if (boostLiquidity > 0) {
            IERC20(rsETH).forceApprove(address(aavePool), boostLiquidity);
            aavePool.supply(rsETH, boostLiquidity, user, 0);
        }
    }

    /**
     * @dev Withdraw boost rsETH and validate it was fully returned
     */
    function _withdrawAndValidateBoost(address user, uint256 preBoostRsETHBalance) internal {
        if (boostLiquidity > 0) {
            _withdrawRsETHFromAave(user, boostLiquidity);
        }
        if (IERC20(rsETH).balanceOf(address(this)) < preBoostRsETHBalance) revert BoostNotRepaid();
    }

    /**
     * @dev Validate that user's health factor meets minimum requirement
     */
    function _validateMinHealthFactor(address user, uint256 minHealthFactor) internal view {
        if (minHealthFactor > 0) {
            uint256 currentHF = _getHealthFactor(user);
            if (currentHF < minHealthFactor) revert HealthFactorTooLow();
        }
    }

    /**
     * @dev Fail early if user hasn't approved enough aRsETH to cover both the boost withdrawal and
     *      any additional deloop collateral pulls. Pass deloopRsETH = 0 for the loop() path where
     *      only the boost needs covering.
     * @param deloopRsETH Extra aRsETH the adapter will pull during deloop iterations.
     */
    function _validateATokenApproval(address user, uint256 deloopRsETH) internal view {
        uint256 required = boostLiquidity + deloopRsETH;
        if (required > 0) {
            uint256 approved = IERC20(aRsETH).allowance(user, address(this));
            if (approved < required) revert InsufficientATokenApproval(required, approved);
        }
    }

    /**
     * @dev Executes one deloop iteration by unwinding part of the caller's Aave position.
     *
     * @param state Current loop state including user, debt/withdrawal assets, budget, and running totals
     * @return shouldContinue true if debt remains and the loop should continue; false to stop
     */
    function _executeDeloopIteration(DeloopState memory state) internal returns (bool shouldContinue) {
        // Maximum rsETH Aave will release while keeping HF >= minHealthFactorFloor.
        // Zero means the position is already at or below the HF floor — nothing can be withdrawn
        uint256 maxWithdrawableRsETH = _calculateMaxWithdrawableRsETH(state.user);
        if (maxWithdrawableRsETH == 0) revert NoWithdrawableCollateral();

        uint256 rsETHToWithdraw = maxWithdrawableRsETH;
        {
            uint256 rsETHNeeded = _calculateRsETHForDebt(state.remainingDebt, state.withdrawalAsset);
            if (rsETHNeeded < rsETHToWithdraw) rsETHToWithdraw = rsETHNeeded;
        }
        if (rsETHToWithdraw < _getMinInstantWithdrawAmount(state.withdrawalAsset)) return false;
        if (state.remainingRsETHBudget < rsETHToWithdraw) revert MaxRsETHExceeded();

        uint256 rsETHWithdrawn = _withdrawRsETHFromAave(state.user, rsETHToWithdraw);
        uint256 withdrawalAssetAmount = _instantWithdrawFromKelp(rsETHWithdrawn, state.withdrawalAsset);
        // stETH => wstETH or ETH => WETH
        uint256 debtAssetAmount = _wrapToDebtAsset(withdrawalAssetAmount, state.debtAsset);
        uint256 debtRepaid = _repayDebt(
            state.debtAsset, debtAssetAmount > state.remainingDebt ? state.remainingDebt : debtAssetAmount, state.user
        );
        state.remainingDebt -= debtRepaid;
        state.remainingRsETHBudget -= rsETHWithdrawn;
        state.totalRsETHWithdrawn += rsETHWithdrawn;
        return state.remainingDebt != 0;
    }

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function getUserPosition(address user) public view override returns (UserPosition memory position) {
        position.rsETHCollateral = IERC20(aRsETH).balanceOf(user);

        position.wethDebt = IERC20(variableDebtWETH).balanceOf(user);

        position.wstETHDebt = IERC20(variableDebtWstETH).balanceOf(user);

        (,,,,, uint256 healthFactor) = aavePool.getUserAccountData(user);
        position.healthFactor = healthFactor;
    }

    /*//////////////////////////////////////////////////////////////
                            ADMIN FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function pause() external override onlyRole(LRTConstants.PAUSER_ROLE) {
        _pause();
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function unpause() external override onlyLRTAdmin {
        _unpause();
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function setMinHealthFactor(uint256 newMinHealthFactor) external override onlyLRTManager {
        if (newMinHealthFactor < 1e18) revert MinHealthFactorTooLow();
        uint256 oldMinHealthFactorFloor = minHealthFactorFloor;
        minHealthFactorFloor = newMinHealthFactor;
        emit MinHealthFactorUpdated(oldMinHealthFactorFloor, newMinHealthFactor);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function setMaxDeloopIterations(uint256 newMax) external override onlyLRTManager {
        if (newMax == 0 || newMax > ABS_MAX_ITERATIONS) revert MaxDeloopIterationsInvalid();
        uint256 old = maxDeloopIterations;
        maxDeloopIterations = newMax;
        emit MaxDeloopIterationsUpdated(old, newMax);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function setMaxLoopIterations(uint256 newMax) external override onlyLRTManager {
        if (newMax == 0 || newMax > ABS_MAX_ITERATIONS) revert MaxLoopIterationsInvalid();
        uint256 old = maxLoopIterations;
        maxLoopIterations = newMax;
        emit MaxLoopIterationsUpdated(old, newMax);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function depositBoostLiquidity(uint256 amount) external override onlyLRTManager {
        IERC20(rsETH).safeTransferFrom(msg.sender, address(this), amount);
        boostLiquidity += amount;
        emit BoostLiquidityDeposited(msg.sender, amount);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function withdrawBoostLiquidity(uint256 amount, address recipient) external override onlyLRTManager {
        UtilLib.checkNonZeroAddress(recipient);
        if (amount > boostLiquidity) revert InvalidAmount();
        boostLiquidity -= amount;
        IERC20(rsETH).safeTransfer(recipient, amount);
        emit BoostLiquidityWithdrawn(recipient, amount);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function getBoostLiquidity() external view override returns (uint256) {
        return boostLiquidity;
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function recoverToken(address token, address recipient, uint256 amount) external override onlyLRTManager {
        UtilLib.checkNonZeroAddress(recipient);
        if (token == rsETH) {
            uint256 rsETHBalance = IERC20(rsETH).balanceOf(address(this));
            uint256 recoverableRsETH = rsETHBalance > boostLiquidity ? rsETHBalance - boostLiquidity : 0;
            if (amount > recoverableRsETH) revert InvalidAmount();
        }
        IERC20(token).safeTransfer(recipient, amount);
        emit TokenRecovered(token, recipient, amount);
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function recoverETH(address payable recipient, uint256 amount) external override onlyLRTManager {
        UtilLib.checkNonZeroAddress(recipient);
        (bool success,) = recipient.call{ value: amount }("");
        if (!success) revert ETHTransferFailed();
        emit ETHRecovered(recipient, amount);
    }

    /*//////////////////////////////////////////////////////////////
                          INTERNAL FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Get minimum rsETH amount required for instant withdrawal
     */
    function _getMinInstantWithdrawAmount(address withdrawalAsset) internal view returns (uint256) {
        ILRTWithdrawalManager withdrawalManager =
            ILRTWithdrawalManager(lrtConfig.getContract(LRTConstants.LRT_WITHDRAW_MANAGER));
        return withdrawalManager.minRsEthAmountToWithdraw(withdrawalAsset);
    }

    /**
     * @dev Validate that instant withdrawal is enabled for the chosen withdrawal asset.
     */
    function _validateInstantWithdrawalEnabled(address withdrawalAsset) internal view {
        ILRTWithdrawalManager withdrawalManager =
            ILRTWithdrawalManager(lrtConfig.getContract(LRTConstants.LRT_WITHDRAW_MANAGER));
        if (!withdrawalManager.isInstantWithdrawalEnabled(withdrawalAsset)) revert InstantWithdrawalDisabled();
    }

    /**
     * @dev Validate debt asset supported by both deloop and loop flows.
     */
    function _validateDebtAsset(address debtAsset) internal view {
        if (debtAsset != weth && debtAsset != wstETH) revert InvalidDebtAsset();
    }

    /**
     * @dev Get the withdrawal asset (ETH/stETH) from debt asset (WETH/wstETH)
     */
    function _getWithdrawalAssetFromDebt(address debtAsset) internal view returns (address) {
        if (debtAsset == weth) {
            return LRTConstants.ETH_TOKEN;
        } else if (debtAsset == wstETH) {
            return stETH;
        } else {
            revert InvalidDebtAsset();
        }
    }

    /**
     * @dev Get user's debt for a specific asset
     */
    function _getUserDebt(address user, address debtAsset) internal view returns (uint256) {
        if (debtAsset == weth) {
            return IERC20(variableDebtWETH).balanceOf(user);
        } else if (debtAsset == wstETH) {
            return IERC20(variableDebtWstETH).balanceOf(user);
        }
        revert InvalidDebtAsset();
    }

    /**
     * @dev Repay variable-rate debt on Aave
     */
    function _repayDebt(address debtAsset, uint256 amount, address user) internal returns (uint256 repaid) {
        IERC20(debtAsset).forceApprove(address(aavePool), amount);
        repaid = aavePool.repay(debtAsset, amount, VARIABLE_RATE_MODE, user);
    }

    /**
     * @dev Withdraw rsETH collateral from AAVE
     */
    function _withdrawRsETHFromAave(address user, uint256 amountToWithdraw) internal returns (uint256 withdrawn) {
        if (amountToWithdraw == 0) revert InvalidAmount();

        IERC20(aRsETH).safeTransferFrom(user, address(this), amountToWithdraw);

        withdrawn = aavePool.withdraw(rsETH, amountToWithdraw, address(this));
    }

    /**
     * @dev Perform instant withdrawal via LRTWithdrawalManager, which burns rsETH directly from this contract.
     */
    function _instantWithdrawFromKelp(
        uint256 rsETHAmount,
        address targetAsset
    )
        internal
        returns (uint256 outputReceived)
    {
        ILRTWithdrawalManager withdrawalManager =
            ILRTWithdrawalManager(lrtConfig.getContract(LRTConstants.LRT_WITHDRAW_MANAGER));

        uint256 balanceBefore;
        if (targetAsset == LRTConstants.ETH_TOKEN) {
            balanceBefore = address(this).balance;
        } else {
            balanceBefore = IERC20(targetAsset).balanceOf(address(this));
        }

        withdrawalManager.instantWithdrawal(targetAsset, rsETHAmount, "deloop-adapter");

        if (targetAsset == LRTConstants.ETH_TOKEN) {
            outputReceived = address(this).balance - balanceBefore;
        } else {
            outputReceived = IERC20(targetAsset).balanceOf(address(this)) - balanceBefore;
        }
    }

    /**
     * @dev Return excess funds to user
     */
    function _returnExcessToUser(address asset, address user, uint256 initialAssetBalance) internal {
        uint256 currentBalance = IERC20(asset).balanceOf(address(this));
        if (currentBalance <= initialAssetBalance) return;
        uint256 amount = currentBalance - initialAssetBalance;
        // Return net excess as the debt asset token (e.g. WETH stays WETH).
        IERC20(asset).safeTransfer(user, amount);
    }

    /**
     * @dev Calculate the maximum rsETH that can be withdrawn while keeping HF >= minHealthFactorFloor.
     * Uses Aave base-currency accounting and rsETH liquidation threshold, so it remains valid with
     * mixed collateral positions.
     */
    function _calculateMaxWithdrawableRsETH(address user) internal view returns (uint256 maxWithdrawable) {
        maxWithdrawable = getMaxWithdraw(user, rsETH, minHealthFactorFloor);
    }

    /// @dev Fetches total collateral, total debt, and weighted-average liquidation threshold (bps) from the pool.
    function _getAccountData(IPool poolContract, address user) internal view returns (AccountData memory) {
        (uint256 totalCollateralBase, uint256 totalDebtBase,, uint256 currentLiquidationThreshold,,) =
            poolContract.getUserAccountData(user);
        return AccountData({
            totalCollateralBase: totalCollateralBase,
            totalDebtBase: totalDebtBase,
            currentLiquidationThreshold: currentLiquidationThreshold
        });
    }

    /**
     * @inheritdoc IAaveDeloopAdapter
     */
    function getMaxWithdraw(
        address user,
        address asset,
        uint256 minHealthFactor
    )
        public
        view
        override
        returns (uint256)
    {
        IPool poolContract = aavePool;
        AccountData memory account = _getAccountData(poolContract, user);

        DataTypes.ReserveDataLegacy memory reserveData = poolContract.getReserveData(asset);
        if (reserveData.aTokenAddress == address(0)) return 0;

        uint256 userBalanceAsset = IERC20(reserveData.aTokenAddress).balanceOf(user);
        if (userBalanceAsset == 0) return 0;

        if (!poolContract.getUserConfiguration(user).isUsingAsCollateral(reserveData.id)) {
            return userBalanceAsset;
        }
        if (account.totalDebtBase == 0) return userBalanceAsset;

        uint256 liquidationThresholdAsset =
            _getLiquidationThresholdForAsset(poolContract, reserveData.id, reserveData.configuration, user); //bps
        if (liquidationThresholdAsset == 0) return userBalanceAsset;

        uint256 assetUnit = 10 ** reserveData.configuration.getDecimals(); // [wei] e.g. 1e18 for rsETH
        uint256 price = IPriceOracleGetter(poolContract.ADDRESSES_PROVIDER().getPriceOracle()).getAssetPrice(asset); // [base]
        // Aave oracle price, 8-decimal

        // Collateral value counted toward backing debt (liquidation at HF < 1)
        uint256 liqWeightedCollateral = account.totalCollateralBase * account.currentLiquidationThreshold; // [base·bps]
        // Minimum collateral value required to maintain target HF
        uint256 minLiqWeightedCollateral = (minHealthFactor * account.totalDebtBase * 10_000) / 1e18; // [base·bps]
        if (liqWeightedCollateral <= minLiqWeightedCollateral) return 0;

        // W = withdrawable
        // 1. Aave HF definition:
        // HF = Σ(balance_i * price_i * liqThreshold_i) / totalDebt
        // 2. Removing W reduces the numerator by W * price * liqThresholdAsset:
        // (totalCollateral * avgLiqThreshold - W * price * liqThresholdAsset) / totalDebt >= minHF
        // 3. Isolate W:
        // => W <= (totalCollateral * avgLiqThreshold - minHF * totalDebt) / (liqThresholdAsset * price)
        // 4. liqWeightedCollateral = totalCollateral * avgLiqThreshold And minLiqWeightedCollateral = minHF * totalDebt
        // => W <= (liqWeightedCollateral - minLiqWeightedCollateral) / (liqThresholdAsset * price)
        uint256 maxWithdrawAmount =
            (liqWeightedCollateral - minLiqWeightedCollateral) * assetUnit / (liquidationThresholdAsset * price); // [wei]
        return maxWithdrawAmount >= userBalanceAsset ? userBalanceAsset : maxWithdrawAmount;
    }

    /**
     * @dev Returns liquidation threshold for the asset in bps.
     *      If the user is in an eMode category and this asset is in that category's collateral bitmap,
     *      returns the category's liquidation threshold; otherwise returns the reserve's liquidation threshold.
     *      NOTE: eMode category is cast to uint8 to match Aave V3's getEModeCategoryCollateralBitmap /
     *      getEModeCategoryCollateralConfig signatures. If Aave ever supports category IDs > 255 this
     *      will need updating.
     */
    function _getLiquidationThresholdForAsset(
        IPool poolContract,
        uint256 reserveId,
        DataTypes.ReserveConfigurationMap memory configuration,
        address user
    )
        internal
        view
        returns (uint256)
    {
        uint256 userEMode = poolContract.getUserEMode(user);
        if (userEMode != 0) {
            uint128 collateralBitmap = poolContract.getEModeCategoryCollateralBitmap(uint8(userEMode));
            if (EModeConfiguration.isReserveEnabledOnBitmap(collateralBitmap, reserveId)) {
                DataTypes.CollateralConfig memory collateralConfig =
                    poolContract.getEModeCategoryCollateralConfig(uint8(userEMode));
                return collateralConfig.liquidationThreshold;
            }
        }
        return configuration.getLiquidationThreshold();
    }

    /**
     * @dev Calculate rsETH needed to cover a debt amount
     * @param debtAmount The debt amount in debt asset terms (WETH or wstETH)
     * @param targetAsset The output asset (ETH or stETH)
     * @return rsETHRequired The rsETH needed
     */
    function _calculateRsETHForDebt(
        uint256 debtAmount,
        address targetAsset
    )
        internal
        view
        returns (uint256 rsETHRequired)
    {
        ILRTWithdrawalManager withdrawalManager =
            ILRTWithdrawalManager(lrtConfig.getContract(LRTConstants.LRT_WITHDRAW_MANAGER));
        uint256 instantFee = withdrawalManager.instantWithdrawalFee();
        if (instantFee > 1000) revert InstantFeeExceedsMax(instantFee);

        uint256 outputNeeded;
        if (targetAsset == LRTConstants.ETH_TOKEN) {
            outputNeeded = debtAmount;
        } else {
            outputNeeded = IWstETH(wstETH).getStETHByWstETH(debtAmount);
        }

        ILRTOracle lrtOracle = ILRTOracle(lrtConfig.getContract(LRTConstants.LRT_ORACLE));
        uint256 rsETHPrice = lrtOracle.rsETHPrice();
        uint256 assetPrice = lrtOracle.getAssetPrice(targetAsset);
        if (rsETHPrice == 0 || assetPrice == 0) revert OraclePriceZero();

        uint256 rsEthToOutputRate = Math.mulDiv(rsETHPrice, (10_000 - instantFee) * 1e18, assetPrice * 10_000);
        rsETHRequired = Math.mulDiv(outputNeeded, 1e18, rsEthToOutputRate, Math.Rounding.Up);
    }

    /**
     * @dev Wrap withdrawal output into the debt asset (ETH → WETH, stETH → wstETH)
     * @param amount Amount of ETH or stETH to wrap
     * @param debtAsset The debt asset to wrap into (WETH or wstETH)
     * @return debtAssetAmount Amount of debt asset obtained
     */
    function _wrapToDebtAsset(uint256 amount, address debtAsset) internal returns (uint256 debtAssetAmount) {
        if (debtAsset == weth) {
            IWETH(weth).deposit{ value: amount }();
            debtAssetAmount = amount;
        } else if (debtAsset == wstETH) {
            IERC20(stETH).forceApprove(wstETH, amount);
            debtAssetAmount = IWstETH(wstETH).wrap(amount);
        } else {
            revert InvalidDebtAsset();
        }
    }

    /**
     * @dev Estimate rsETH minted by converting a debt-asset amount through Kelp deposit paths.
     */
    function _quoteRsETHFromDebtAsset(
        address debtAsset,
        uint256 debtAmount
    )
        internal
        view
        returns (uint256 rsEthAmount)
    {
        ILRTDepositPool depositPool = ILRTDepositPool(lrtConfig.getContract(LRTConstants.LRT_DEPOSIT_POOL));
        if (debtAsset == weth) {
            rsEthAmount = depositPool.getRsETHAmountToMint(LRTConstants.ETH_TOKEN, debtAmount);
        } else if (debtAsset == wstETH) {
            uint256 stETHAmount = IWstETH(wstETH).getStETHByWstETH(debtAmount);
            rsEthAmount = depositPool.getRsETHAmountToMint(stETH, stETHAmount);
        } else {
            revert InvalidDebtAsset();
        }
    }

    /**
     * @dev Calculate max additional debt (in debt-asset units) while preserving min health factor.
     *
     * Two constraints are applied and the tighter one wins:
     *   1. LTV cap  — `availableBorrowsBase` from Aave already accounts for the reserve's LTV and
     *      existing debt, matching exactly what `aavePool.borrow()` will enforce.
     *   2. HF floor — derived from `minHealthFactor` via the liquidation-threshold math (liquidation
     *      threshold >= LTV, so this constraint is only binding when a high minHealthFactor is set).
     */
    function _calculateMaxBorrowableDebt(
        address user,
        address debtAsset,
        uint256 minHealthFactor
    )
        internal
        view
        returns (uint256 maxBorrowableDebt)
    {
        (
            uint256 totalCollateralBase,
            uint256 totalDebtBase,
            uint256 availableBorrowsBase,
            uint256 currentLiquidationThreshold,,
        ) = aavePool.getUserAccountData(user);
        if (totalCollateralBase == 0 || currentLiquidationThreshold == 0 || availableBorrowsBase == 0) return 0;

        // HF-constrained capacity (uses liquidation threshold, may be stricter than LTV at high minHealthFactor).
        uint256 liquidationBufferBase = totalCollateralBase * currentLiquidationThreshold / 10_000;
        uint256 maxTotalDebtBase = Math.mulDiv(liquidationBufferBase, 1e18, minHealthFactor);
        uint256 hfConstrainedBase = maxTotalDebtBase > totalDebtBase ? maxTotalDebtBase - totalDebtBase : 0;

        // Take the binding (lower) constraint: LTV cap vs HF floor.
        uint256 maxBorrowBase = availableBorrowsBase < hfConstrainedBase ? availableBorrowsBase : hfConstrainedBase;
        if (maxBorrowBase == 0) return 0;

        uint256 price = IPriceOracleGetter(IPoolAddressesProvider(aavePool.ADDRESSES_PROVIDER()).getPriceOracle())
            .getAssetPrice(debtAsset);
        if (price == 0) revert OraclePriceZero();

        uint8 decimals = IERC20Metadata(debtAsset).decimals();
        maxBorrowableDebt = Math.mulDiv(maxBorrowBase, 10 ** decimals, price);
    }

    /**
     * @dev Borrow debt asset through Aave on behalf of user.
     */
    function _borrowDebt(address user, address debtAsset, uint256 amount) internal returns (uint256 borrowedAmount) {
        address variableDebtToken = debtAsset == weth ? variableDebtWETH : variableDebtWstETH;
        uint256 delegatedAmount = IVariableDebtDelegationToken(variableDebtToken).borrowAllowance(user, address(this));
        if (delegatedAmount < amount) revert InsufficientBorrowDelegation(amount, delegatedAmount);

        uint256 balanceBefore = IERC20(debtAsset).balanceOf(address(this));
        aavePool.borrow(debtAsset, amount, VARIABLE_RATE_MODE, 0, user);
        borrowedAmount = IERC20(debtAsset).balanceOf(address(this)) - balanceBefore;
    }

    /**
     * @dev Convert borrowed debt asset into rsETH via Kelp deposit pool.
     * @param minRsETHOut Minimum rsETH that must be received from the deposit (slippage guard).
     */
    function _convertDebtAssetToRsETH(
        address debtAsset,
        uint256 debtAmount,
        uint256 minRsETHOut
    )
        internal
        returns (uint256 rsEthMinted)
    {
        ILRTDepositPool depositPool = ILRTDepositPool(lrtConfig.getContract(LRTConstants.LRT_DEPOSIT_POOL));
        uint256 rsEthBefore = IERC20(rsETH).balanceOf(address(this));

        if (debtAsset == weth) {
            IWETH(weth).withdraw(debtAmount);
            depositPool.depositETH{ value: debtAmount }(minRsETHOut, "loop-adapter");
        } else if (debtAsset == wstETH) {
            uint256 stETHAmount = IWstETH(wstETH).unwrap(debtAmount);
            IERC20(stETH).forceApprove(address(depositPool), stETHAmount);
            depositPool.depositAsset(stETH, stETHAmount, minRsETHOut, "loop-adapter");
        } else {
            revert InvalidDebtAsset();
        }

        rsEthMinted = IERC20(rsETH).balanceOf(address(this)) - rsEthBefore;
        if (rsEthMinted == 0) revert LoopFailed();
    }
}

contracts/external/aave/DataTypes.sol

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

library DataTypes {
    /**
     * This exists specifically to maintain the `getReserveData()` interface, since the new, internal
     * `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`.
     */
    struct ReserveDataLegacy {
        //stores the reserve configuration
        ReserveConfigurationMap configuration;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        //the current supply rate. Expressed in ray
        uint128 currentLiquidityRate;
        //variable borrow index. Expressed in ray
        uint128 variableBorrowIndex;
        //the current variable borrow rate. Expressed in ray
        uint128 currentVariableBorrowRate;
        // DEPRECATED on v3.2.0
        uint128 currentStableBorrowRate;
        //timestamp of last update
        uint40 lastUpdateTimestamp;
        //the id of the reserve. Represents the position in the list of the active reserves
        uint16 id;
        //aToken address
        address aTokenAddress;
        // DEPRECATED on v3.2.0
        address stableDebtTokenAddress;
        //variableDebtToken address
        address variableDebtTokenAddress;
        // DEPRECATED on v3.4.0, should use the `RESERVE_INTEREST_RATE_STRATEGY` variable from the Pool contract
        address interestRateStrategyAddress;
        //the current treasury balance, scaled
        uint128 accruedToTreasury;
        // DEPRECATED on v3.4.0
        uint128 unbacked;
        //the outstanding debt borrowed against this asset in isolation mode
        uint128 isolationModeTotalDebt;
    }

    struct ReserveData {
        //stores the reserve configuration
        ReserveConfigurationMap configuration;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        //the current supply rate. Expressed in ray
        uint128 currentLiquidityRate;
        //variable borrow index. Expressed in ray
        uint128 variableBorrowIndex;
        //the current variable borrow rate. Expressed in ray
        uint128 currentVariableBorrowRate;
        /// @notice reused `__deprecatedStableBorrowRate` storage from pre 3.2
        // the current accumulate deficit in underlying tokens
        uint128 deficit;
        //timestamp of last update
        uint40 lastUpdateTimestamp;
        //the id of the reserve. Represents the position in the list of the active reserves
        uint16 id;
        //timestamp until when liquidations are not allowed on the reserve, if set to past liquidations will be allowed
        uint40 liquidationGracePeriodUntil;
        //aToken address
        address aTokenAddress;
        // DEPRECATED on v3.2.0
        address __deprecatedStableDebtTokenAddress;
        //variableDebtToken address
        address variableDebtTokenAddress;
        // DEPRECATED on v3.4.0, should use the `RESERVE_INTEREST_RATE_STRATEGY` variable from the Pool contract
        address __deprecatedInterestRateStrategyAddress;
        //the current treasury balance, scaled
        uint128 accruedToTreasury;
        // In aave 3.3.0 this storage slot contained the `unbacked`
        uint128 virtualUnderlyingBalance;
        //the outstanding debt borrowed against this asset in isolation mode
        uint128 isolationModeTotalDebt;
        //the amount of underlying accounted for by the protocol
        // DEPRECATED on v3.4.0. Moved into the same slot as accruedToTreasury for optimized storage access.
        uint128 __deprecatedVirtualUnderlyingBalance;
    }

    struct ReserveConfigurationMap {
        //bit 0-15: LTV
        //bit 16-31: Liq. threshold
        //bit 32-47: Liq. bonus
        //bit 48-55: Decimals
        //bit 56: reserve is active
        //bit 57: reserve is frozen
        //bit 58: borrowing is enabled
        //bit 59: DEPRECATED: stable rate borrowing enabled
        //bit 60: asset is paused
        //bit 61: borrowing in isolation mode is enabled
        //bit 62: siloed borrowing enabled
        //bit 63: flashloaning enabled
        //bit 64-79: reserve factor
        //bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap
        //bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap
        //bit 152-167: liquidation protocol fee
        //bit 168-175: DEPRECATED: eMode category
        //bit 176-211: DEPRECATED: unbacked mint cap
        //bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
        //bit 252: DEPRECATED: virtual accounting is enabled for the reserve
        //bit 253-255 unused

        uint256 data;
    }

    struct UserConfigurationMap {
        /**
         * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
         * The first bit indicates if an asset is used as collateral by the user, the second whether an
         * asset is borrowed by the user.
         */
        uint256 data;
    }

    // DEPRECATED: kept for backwards compatibility, might be removed in a future version
    struct EModeCategoryLegacy {
        // each eMode category has a custom ltv and liquidation threshold
        uint16 ltv;
        uint16 liquidationThreshold;
        uint16 liquidationBonus;
        // DEPRECATED
        address priceSource;
        string label;
    }

    struct CollateralConfig {
        uint16 ltv;
        uint16 liquidationThreshold;
        uint16 liquidationBonus;
    }

    struct EModeCategoryBaseConfiguration {
        uint16 ltv;
        uint16 liquidationThreshold;
        uint16 liquidationBonus;
        string label;
    }

    struct EModeCategory {
        // each eMode category has a custom ltv and liquidation threshold
        uint16 ltv;
        uint16 liquidationThreshold;
        uint16 liquidationBonus;
        uint128 collateralBitmap;
        string label;
        uint128 borrowableBitmap;
        uint128 ltvzeroBitmap; // if true, the asset will be treated as ltv0 and ltv0 rules apply
    }

    enum InterestRateMode {
        NONE,
        __DEPRECATED,
        VARIABLE
    }

    struct ReserveCache {
        uint256 currScaledVariableDebt;
        uint256 nextScaledVariableDebt;
        uint256 currLiquidityIndex;
        uint256 nextLiquidityIndex;
        uint256 currVariableBorrowIndex;
        uint256 nextVariableBorrowIndex;
        uint256 currLiquidityRate;
        uint256 currVariableBorrowRate;
        uint256 reserveFactor;
        ReserveConfigurationMap reserveConfiguration;
        address aTokenAddress;
        address variableDebtTokenAddress;
        uint40 reserveLastUpdateTimestamp;
    }

    struct ExecuteLiquidationCallParams {
        address liquidator;
        uint256 debtToCover;
        address collateralAsset;
        address debtAsset;
        address borrower;
        bool receiveAToken;
        address priceOracle;
        uint8 borrowerEModeCategory;
        address priceOracleSentinel;
        address interestRateStrategyAddress;
    }

    struct ExecuteSupplyParams {
        address user;
        address asset;
        address interestRateStrategyAddress;
        uint256 amount;
        address onBehalfOf;
        uint16 referralCode;
        uint8 supplierEModeCategory;
    }

    struct ExecuteBorrowParams {
        address asset;
        address user;
        address onBehalfOf;
        address interestRateStrategyAddress;
        uint256 amount;
        InterestRateMode interestRateMode;
        uint16 referralCode;
        bool releaseUnderlying;
        address oracle;
        uint8 userEModeCategory;
        address priceOracleSentinel;
    }

    struct ExecuteRepayParams {
        address asset;
        address user;
        address interestRateStrategyAddress;
        uint256 amount;
        InterestRateMode interestRateMode;
        address onBehalfOf;
        bool useATokens;
        address oracle;
        uint8 userEModeCategory;
    }

    struct ExecuteWithdrawParams {
        address user;
        address asset;
        address interestRateStrategyAddress;
        uint256 amount;
        address to;
        address oracle;
        uint8 userEModeCategory;
    }

    struct ExecuteEliminateDeficitParams {
        address user;
        address asset;
        address interestRateStrategyAddress;
        uint256 amount;
    }

    struct FinalizeTransferParams {
        address asset;
        address from;
        address to;
        uint256 scaledAmount;
        uint256 scaledBalanceFromBefore;
        address oracle;
        uint8 fromEModeCategory;
    }

    struct FlashloanParams {
        address user;
        address receiverAddress;
        address[] assets;
        uint256[] amounts;
        uint256[] interestRateModes;
        address interestRateStrategyAddress;
        address onBehalfOf;
        bytes params;
        uint16 referralCode;
        uint256 flashLoanPremium;
        address addressesProvider;
        address pool;
        uint8 userEModeCategory;
        bool isAuthorizedFlashBorrower;
    }

    struct FlashloanSimpleParams {
        address user;
        address receiverAddress;
        address asset;
        address interestRateStrategyAddress;
        uint256 amount;
        bytes params;
        uint16 referralCode;
        uint256 flashLoanPremium;
    }

    struct FlashLoanRepaymentParams {
        address user;
        uint256 amount;
        uint256 totalPremium;
        address asset;
        address interestRateStrategyAddress;
        address receiverAddress;
        uint16 referralCode;
    }

    struct CalculateUserAccountDataParams {
        UserConfigurationMap userConfig;
        address user;
        address oracle;
        uint8 userEModeCategory;
    }

    struct GetMaxWithdrawParams {
        address user;
        address asset;
        uint256 minHealthFactor;
        address oracle;
        UserConfigurationMap userConfig;
        uint8 userEModeCategory;
    }

    struct ValidateBorrowParams {
        ReserveCache reserveCache;
        UserConfigurationMap userConfig;
        address asset;
        address userAddress;
        uint256 amountScaled;
        InterestRateMode interestRateMode;
        address oracle;
        uint8 userEModeCategory;
        address priceOracleSentinel;
    }

    struct ValidateLiquidationCallParams {
        ReserveCache debtReserveCache;
        uint256 totalDebt;
        uint256 healthFactor;
        address priceOracleSentinel;
        address borrower;
        address liquidator;
    }

    struct CalculateInterestRatesParams {
        uint256 unbacked;
        uint256 liquidityAdded;
        uint256 liquidityTaken;
        uint256 totalDebt;
        uint256 reserveFactor;
        address reserve;
        // @notice DEPRECATED in 3.4, but kept for backwards compatibility
        bool usingVirtualBalance;
        uint256 virtualUnderlyingBalance;
    }

    struct InitReserveParams {
        address asset;
        address aTokenAddress;
        address variableDebtAddress;
        uint16 reservesCount;
        uint16 maxNumberReserves;
    }
}

contracts/external/aave/EModeConfiguration.sol

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

import { Errors } from "./Errors.sol";
import { ReserveConfiguration } from "./ReserveConfiguration.sol";

/**
 * @title EModeConfiguration library
 * @author BGD Labs
 * @notice Implements the bitmap logic to handle the eMode configuration
 */
library EModeConfiguration {
    /**
     * @notice Sets a bit in a given bitmap that represents the reserve index range
     * @dev The supplied bitmap is supposed to be a uint128 in which each bit represents a reserve
     * @param bitmap The bitmap
     * @param reserveIndex The index of the reserve in the bitmap
     * @param enabled True if the reserveIndex should be enabled on the bitmap, false otherwise
     * @return The altered bitmap
     */
    function setReserveBitmapBit(uint128 bitmap, uint256 reserveIndex, bool enabled) internal pure returns (uint128) {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            uint128 bit = uint128(1 << reserveIndex);
            if (enabled) {
                return bitmap | bit;
            } else {
                return bitmap & ~bit;
            }
        }
    }

    /**
     * @notice Validates if a reserveIndex is flagged as enabled on a given bitmap
     * @param bitmap The bitmap
     * @param reserveIndex The index of the reserve in the bitmap
     * @return True if the reserveindex is flagged true
     */
    function isReserveEnabledOnBitmap(uint128 bitmap, uint256 reserveIndex) internal pure returns (bool) {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            return (bitmap >> reserveIndex) & 1 != 0;
        }
    }
}

contracts/external/aave/Errors.sol

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

/**
 * @title Errors library
 * @author Aave
 * @notice Defines the error messages emitted by the different contracts of the Aave protocol
 */
library Errors {
    error CallerNotPoolAdmin(); // 'The caller of the function is not a pool admin'
    error CallerNotPoolOrEmergencyAdmin(); // 'The caller of the function is not a pool or emergency admin'
    error CallerNotRiskOrPoolAdmin(); // 'The caller of the function is not a risk or pool admin'
    error CallerNotAssetListingOrPoolAdmin(); // 'The caller of the function is not an asset listing or pool admin'
    error AddressesProviderNotRegistered(); // 'Pool addresses provider is not registered'
    error InvalidAddressesProviderId(); // 'Invalid id for the pool addresses provider'
    error NotContract(); // 'Address is not a contract'
    error CallerNotPoolConfigurator(); // 'The caller of the function is not the pool configurator'
    error CallerNotAToken(); // 'The caller of the function is not an AToken'
    error InvalidAddressesProvider(); // 'The address of the pool addresses provider is invalid'
    error InvalidFlashloanExecutorReturn(); // 'Invalid return value of the flashloan executor function'
    error ReserveAlreadyAdded(); // 'Reserve has already been added to reserve list'
    error NoMoreReservesAllowed(); // 'Maximum amount of reserves in the pool reached'
    error EModeCategoryReserved(); // 'Zero eMode category is reserved for volatile heterogeneous assets'
    error ReserveLiquidityNotZero(); // 'The liquidity of the reserve needs to be 0'
    error FlashloanPremiumInvalid(); // 'Invalid flashloan premium'
    error InvalidReserveParams(); // 'Invalid risk parameters for the reserve'
    error InvalidEmodeCategoryParams(); // 'Invalid risk parameters for the eMode category'
    error CallerMustBePool(); // 'The caller of this function must be a pool'
    error InvalidMintAmount(); // 'Invalid amount to mint'
    error InvalidBurnAmount(); // 'Invalid amount to burn'
    error InvalidAmount(); // 'Amount must be greater than 0'
    error ReserveInactive(); // 'Action requires an active reserve'
    error ReserveFrozen(); // 'Action cannot be performed because the reserve is frozen'
    error ReservePaused(); // 'Action cannot be performed because the reserve is paused'
    error BorrowingNotEnabled(); // 'Borrowing is not enabled'
    error NotEnoughAvailableUserBalance(); // 'User cannot withdraw more than the available balance'
    error InvalidInterestRateModeSelected(); // 'Invalid interest rate mode selected'
    error HealthFactorLowerThanLiquidationThreshold(); // 'Health factor is below the liquidation threshold'
    error CollateralCannotCoverNewBorrow(); // 'There is not enough collateral to cover a new borrow'
    error NoDebtOfSelectedType(); // 'For repayment of a specific type of debt, the user needs to have debt that type'
    error NoExplicitAmountToRepayOnBehalf(); // 'To repay on behalf of a user an explicit amount to repay is needed'
    error UnderlyingBalanceZero(); // 'The underlying balance needs to be greater than 0'
    error HealthFactorNotBelowThreshold(); // 'Health factor is not below the threshold'
    error CollateralCannotBeLiquidated(); // 'The collateral chosen cannot be liquidated'
    error SpecifiedCurrencyNotBorrowedByUser(); // 'User did not borrow the specified currency'
    error InconsistentFlashloanParams(); // 'Inconsistent flashloan parameters'
    error BorrowCapExceeded(); // 'Borrow cap is exceeded'
    error SupplyCapExceeded(); // 'Supply cap is exceeded'
    error DebtCeilingExceeded(); // 'Debt ceiling is exceeded'
    error UnderlyingClaimableRightsNotZero(); // 'Claimable rights over underlying not zero (aToken supply or
    // accruedToTreasury)'
    error VariableDebtSupplyNotZero(); // 'Variable debt supply is not zero'
    error LtvValidationFailed(); // 'Ltv validation failed'
    error InconsistentEModeCategory(); // 'Inconsistent eMode category'
    error PriceOracleSentinelCheckFailed(); // 'Price oracle sentinel validation failed'
    error AssetNotBorrowableInIsolation(); // 'Asset is not borrowable in isolation mode'
    error ReserveAlreadyInitialized(); // 'Reserve has already been initialized'
    error UserInIsolationModeOrLtvZero(); // 'User is in isolation mode or ltv is zero'
    error InvalidLtv(); // 'Invalid ltv parameter for the reserve'
    error InvalidLiquidationThreshold(); // 'Invalid liquidity threshold parameter for the reserve'
    error InvalidLiquidationBonus(); // 'Invalid liquidity bonus parameter for the reserve'
    error InvalidDecimals(); // 'Invalid decimals parameter of the underlying asset of the reserve'
    error InvalidReserveFactor(); // 'Invalid reserve factor parameter for the reserve'
    error InvalidBorrowCap(); // 'Invalid borrow cap for the reserve'
    error InvalidSupplyCap(); // 'Invalid supply cap for the reserve'
    error InvalidLiquidationProtocolFee(); // 'Invalid liquidation protocol fee for the reserve'
    error InvalidDebtCeiling(); // 'Invalid debt ceiling for the reserve'
    error InvalidReserveIndex(); // 'Invalid reserve index'
    error AclAdminCannotBeZero(); // 'ACL admin cannot be set to the zero address'
    error InconsistentParamsLength(); // 'Array parameters that should be equal length are not'
    error ZeroAddressNotValid(); // 'Zero address not valid'
    error InvalidExpiration(); // 'Invalid expiration'
    error InvalidSignature(); // 'Invalid signature'
    error OperationNotSupported(); // 'Operation not supported'
    error DebtCeilingNotZero(); // 'Debt ceiling is not zero'
    error AssetNotListed(); // 'Asset is not listed'
    error InvalidOptimalUsageRatio(); // 'Invalid optimal usage ratio'
    error UnderlyingCannotBeRescued(); // 'The underlying asset cannot be rescued'
    error AddressesProviderAlreadyAdded(); // 'Reserve has already been added to reserve list'
    error PoolAddressesDoNotMatch(); // 'The token implementation pool address and the pool address provided by the
    // initializing pool do not match'
    error SiloedBorrowingViolation(); // 'User is trying to borrow multiple assets including a siloed one'
    error ReserveDebtNotZero(); // the total debt of the reserve needs to be 0
    error FlashloanDisabled(); // FlashLoaning for this asset is disabled
    error InvalidMaxRate(); // The expect maximum borrow rate is invalid
    error WithdrawToAToken(); // Withdrawing to the aToken is not allowed
    error SupplyToAToken(); // Supplying to the aToken is not allowed
    error Slope2MustBeGteSlope1(); // Variable interest rate slope 2 can not be lower than slope 1
    error CallerNotRiskOrPoolOrEmergencyAdmin(); // 'The caller of the function is not a risk, pool or emergency admin'
    error LiquidationGraceSentinelCheckFailed(); // 'Liquidation grace sentinel validation failed'
    error InvalidGracePeriod(); // Grace period above a valid range
    error InvalidFreezeState(); // Reserve is already in the passed freeze state
    error InvalidLtvzeroState(); // Reserve is already in the passed ltvzero state
    error NotBorrowableInEMode(); // Asset not borrowable in eMode
    error CallerNotUmbrella(); // The caller of the function is not the umbrella contract
    error ReserveNotInDeficit(); // The reserve is not in deficit
    error MustNotLeaveDust(); // Below a certain threshold liquidators need to take the full position
    error UserCannotHaveDebt(); // Thrown when a user tries to interact with a method that requires a position without
    // debt
    error SelfLiquidation(); // Thrown when a user tries to liquidate themselves
    error CallerNotPositionManager(); // Thrown when the caller has not been enabled as a position manager of the
    // on-behalf-of user
    error InvalidCollateralInEmode(address reserve, uint256 categoryId); /// Thrown when trying to enter an eMode with
    /// an invalid collateral asset
    error InvalidDebtInEmode(address reserve, uint256 categoryId); /// Thrown when trying to enter an eMode with an
    /// invalid debt asset
    error MustBeEmodeCollateral(address reserve, uint256 categoryId); /// Thrown when trying to configure an asset as
    /// eMode-ltvzero that is not an eMode collateral
}

contracts/external/aave/IPool.sol

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

import { IPoolAddressesProvider } from "./IPoolAddressesProvider.sol";
import { DataTypes } from "./DataTypes.sol";

/**
 * @title IPool
 * @author Aave
 * @notice Defines the basic interface for an Aave Pool.
 */
interface IPool {
    /**
     * @dev Emitted on supply()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address initiating the supply
     * @param onBehalfOf The beneficiary of the supply, receiving the aTokens
     * @param amount The amount supplied
     * @param referralCode The referral code used
     */
    event Supply(
        address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referralCode
    );

    /**
     * @dev Emitted on withdraw()
     * @param reserve The address of the underlying asset being withdrawn
     * @param user The address initiating the withdrawal, owner of aTokens
     * @param to The address that will receive the underlying
     * @param amount The amount to be withdrawn
     */
    event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);

    /**
     * @dev Emitted on borrow() and flashLoan() when debt needs to be opened
     * @param reserve The address of the underlying asset being borrowed
     * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
     * initiator of the transaction on flashLoan()
     * @param onBehalfOf The address that will be getting the debt
     * @param amount The amount borrowed out
     * @param interestRateMode The rate mode: 2 for Variable, 1 is deprecated (changed on v3.2.0)
     * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray
     * @param referralCode The referral code used
     */
    event Borrow(
        address indexed reserve,
        address user,
        address indexed onBehalfOf,
        uint256 amount,
        DataTypes.InterestRateMode interestRateMode,
        uint256 borrowRate,
        uint16 indexed referralCode
    );

    /**
     * @dev Emitted on repay()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The beneficiary of the repayment, getting his debt reduced
     * @param repayer The address of the user initiating the repay(), providing the funds
     * @param amount The amount repaid
     * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly
     */
    event Repay(
        address indexed reserve, address indexed user, address indexed repayer, uint256 amount, bool useATokens
    );

    /**
     * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets
     * @param asset The address of the underlying asset of the reserve
     * @param totalDebt The total isolation mode debt for the reserve
     */
    event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);

    /**
     * @dev Emitted when the user selects a certain asset category for eMode
     * @param user The address of the user
     * @param categoryId The category id
     */
    event UserEModeSet(address indexed user, uint8 categoryId);

    /**
     * @dev Emitted on setUserUseReserveAsCollateral()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user enabling the usage as collateral
     */
    event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);

    /**
     * @dev Emitted on setUserUseReserveAsCollateral()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user enabling the usage as collateral
     */
    event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);

    /**
     * @dev Emitted on flashLoan()
     * @param target The address of the flash loan receiver contract
     * @param initiator The address initiating the flash loan
     * @param asset The address of the asset being flash borrowed
     * @param amount The amount flash borrowed
     * @param interestRateMode The flashloan mode: 0 for regular flashloan,
     *        1 for Stable (Deprecated on v3.2.0), 2 for Variable
     * @param premium The fee flash borrowed
     * @param referralCode The referral code used
     */
    event FlashLoan(
        address indexed target,
        address initiator,
        address indexed asset,
        uint256 amount,
        DataTypes.InterestRateMode interestRateMode,
        uint256 premium,
        uint16 indexed referralCode
    );

    /**
     * @dev Emitted when a borrower is liquidated.
     * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the
     * liquidation
     * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
     * @param user The address of the borrower getting liquidated
     * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
     * @param liquidatedCollateralAmount The amount of collateral received by the liquidator
     * @param liquidator The address of the liquidator
     * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
     * to receive the underlying collateral asset directly
     */
    event LiquidationCall(
        address indexed collateralAsset,
        address indexed debtAsset,
        address indexed user,
        uint256 debtToCover,
        uint256 liquidatedCollateralAmount,
        address liquidator,
        bool receiveAToken
    );

    /**
     * @dev Emitted when the state of a reserve is updated.
     * @param reserve The address of the underlying asset of the reserve
     * @param liquidityRate The next liquidity rate
     * @param stableBorrowRate The next stable borrow rate @note deprecated on v3.2.0
     * @param variableBorrowRate The next variable borrow rate
     * @param liquidityIndex The next liquidity index
     * @param variableBorrowIndex The next variable borrow index
     */
    event ReserveDataUpdated(
        address indexed reserve,
        uint256 liquidityRate,
        uint256 stableBorrowRate,
        uint256 variableBorrowRate,
        uint256 liquidityIndex,
        uint256 variableBorrowIndex
    );

    /**
     * @dev Emitted when the deficit of a reserve is covered.
     * @param reserve The address of the underlying asset of the reserve
     * @param caller The caller that triggered the DeficitCovered event
     * @param amountCovered The amount of deficit covered
     */
    event DeficitCovered(address indexed reserve, address caller, uint256 amountCovered);

    /**
     * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.
     * @param reserve The address of the reserve
     * @param amountMinted The amount minted to the treasury
     */
    event MintedToTreasury(address indexed reserve, uint256 amountMinted);

    /**
     * @dev Emitted when deficit is realized on a liquidation.
     * @param user The user address where the bad debt will be burned
     * @param debtAsset The address of the underlying borrowed asset to be burned
     * @param amountCreated The amount of deficit created
     */
    event DeficitCreated(address indexed user, address indexed debtAsset, uint256 amountCreated);

    /**
     * @dev Emitted when a position manager is approved by the user.
     * @param user The user address
     * @param positionManager The address of the position manager
     */
    event PositionManagerApproved(address indexed user, address indexed positionManager);

    /**
     * @dev Emitted when a position manager is revoked by the user.
     * @param user The user address
     * @param positionManager The address of the position manager
     */
    event PositionManagerRevoked(address indexed user, address indexed positionManager);

    /**
     * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
     * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
     * @param asset The address of the underlying asset to supply
     * @param amount The amount to be supplied
     * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
     *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
     *   is a different wallet
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     */
    function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

    /**
     * @notice Supply with transfer approval of asset to be supplied done via permit function
     * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
     * @param asset The address of the underlying asset to supply
     * @param amount The amount to be supplied
     * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
     *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
     *   is a different wallet
     * @param deadline The deadline timestamp that the permit is valid
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     * @param permitV The V parameter of ERC712 permit sig
     * @param permitR The R parameter of ERC712 permit sig
     * @param permitS The S parameter of ERC712 permit sig
     */
    function supplyWithPermit(
        address asset,
        uint256 amount,
        address onBehalfOf,
        uint16 referralCode,
        uint256 deadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    )
        external;

    /**
     * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
     * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
     * @param asset The address of the underlying asset to withdraw
     * @param amount The underlying amount to be withdrawn
     *   - Send the value type(uint256).max in order to withdraw the whole aToken balance
     * @param to The address that will receive the underlying, same as msg.sender if the user
     *   wants to receive it on his own wallet, or a different address if the beneficiary is a
     *   different wallet
     * @return The final amount withdrawn
     */
    function withdraw(address asset, uint256 amount, address to) external returns (uint256);

    /**
     * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
     * already supplied enough collateral, or he was given enough allowance by a credit delegator on the
     * VariableDebtToken
     * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
     *   and 100 variable debt tokens
     * @param asset The address of the underlying asset to borrow
     * @param amount The amount to be borrowed
     * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0
     * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself
     * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
     * if he has been given credit delegation allowance
     */
    function borrow(
        address asset,
        uint256 amount,
        uint256 interestRateMode,
        uint16 referralCode,
        address onBehalfOf
    )
        external;

    /**
     * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
     * - E.g. User repays 100 USDC, burning 100 variable debt tokens of the `onBehalfOf` address
     * @param asset The address of the borrowed underlying asset previously borrowed
     * @param amount The amount to repay
     * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
     * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0
     * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the
     * user calling the function if he wants to reduce/remove his own debt, or the address of any other
     * other borrower whose debt should be removed
     * @return The final amount repaid
     */
    function repay(
        address asset,
        uint256 amount,
        uint256 interestRateMode,
        address onBehalfOf
    )
        external
        returns (uint256);

    /**
     * @notice Repay with transfer approval of asset to be repaid done via permit function
     * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
     * @param asset The address of the borrowed underlying asset previously borrowed
     * @param amount The amount to repay
     * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
     * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0
     * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
     * user calling the function if he wants to reduce/remove his own debt, or the address of any other
     * other borrower whose debt should be removed
     * @param deadline The deadline timestamp that the permit is valid
     * @param permitV The V parameter of ERC712 permit sig
     * @param permitR The R parameter of ERC712 permit sig
     * @param permitS The S parameter of ERC712 permit sig
     * @return The final amount repaid
     */
    function repayWithPermit(
        address asset,
        uint256 amount,
        uint256 interestRateMode,
        address onBehalfOf,
        uint256 deadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    )
        external
        returns (uint256);

    /**
     * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the
     * equivalent debt tokens
     * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens
     * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken
     * balance is not enough to cover the whole debt
     * @param asset The address of the borrowed underlying asset previously borrowed
     * @param amount The amount to repay
     * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
     * @param interestRateMode DEPRECATED in v3.2.0
     * @return The final amount repaid
     */
    function repayWithATokens(address asset, uint256 amount, uint256 interestRateMode) external returns (uint256);

    /**
     * @notice Allows suppliers to enable/disable a specific supplied asset as collateral
     * @param asset The address of the underlying asset supplied
     * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise
     */
    function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

    /**
     * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
     * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
     *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
     * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the
     * liquidation
     * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
     * @param borrower The address of the borrower getting liquidated
     * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
     * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
     * to receive the underlying collateral asset directly
     */
    function liquidationCall(
        address collateralAsset,
        address debtAsset,
        address borrower,
        uint256 debtToCover,
        bool receiveAToken
    )
        external;

    /**
     * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
     * as long as the amount taken plus a fee is returned.
     * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
     * into consideration. For further details please visit https://docs.aave.com/developers/
     * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface
     * @param assets The addresses of the assets being flash-borrowed
     * @param amounts The amounts of the assets being flash-borrowed
     * @param interestRateModes Types of the debt to open if the flash loan is not returned:
     *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
     *   1 -> Deprecated on v3.2.0
     *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
     * @param onBehalfOf The address  that will receive the debt in the case of using 2 on `modes`
     * @param params Variadic packed params to pass to the receiver as extra information
     * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     */
    function flashLoan(
        address receiverAddress,
        address[] calldata assets,
        uint256[] calldata amounts,
        uint256[] calldata interestRateModes,
        address onBehalfOf,
        bytes calldata params,
        uint16 referralCode
    )
        external;

    /**
     * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
     * as long as the amount taken plus a fee is returned.
     * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
     * into consideration. For further details please visit https://docs.aave.com/developers/
     * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver
     * interface
     * @param asset The address of the asset being flash-borrowed
     * @param amount The amount of the asset being flash-borrowed
     * @param params Variadic packed params to pass to the receiver as extra information
     * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     */
    function flashLoanSimple(
        address receiverAddress,
        address asset,
        uint256 amount,
        bytes calldata params,
        uint16 referralCode
    )
        external;

    /**
     * @notice Returns the user account data across all the reserves
     * @param user The address of the user
     * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed
     * @return totalDebtBase The total debt of the user in the base currency used by the price feed
     * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed
     * @return currentLiquidationThreshold The liquidation threshold of the user
     * @return ltv The loan to value of The user
     * @return healthFactor The current health factor of the user
     */
    function getUserAccountData(address user)
        external
        view
        returns (
            uint256 totalCollateralBase,
            uint256 totalDebtBase,
            uint256 availableBorrowsBase,
            uint256 currentLiquidationThreshold,
            uint256 ltv,
            uint256 healthFactor
        );

    /**
     * @notice Returns the maximum amount of a collateral asset that a user can withdraw while keeping health factor >=
     * minHealthFactor
     * @param user The user address
     * @param asset The collateral asset to withdraw
     * @param minHealthFactor Minimum health factor to maintain (18 decimals, e.g. 1.01e18 for 1.01)
     * @return The max withdrawable amount in asset units
     */
    function getMaxWithdraw(address user, address asset, uint256 minHealthFactor) external view returns (uint256);

    /**
     * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens
     * @dev Only callable by the PoolConfigurator contract
     * @param asset The address of the underlying asset of the reserve
     * @param aTokenAddress The address of the aToken that will be assigned to the reserve
     * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve
     */
    function initReserve(address asset, address aTokenAddress, address variableDebtAddress) external;

    /**
     * @notice Drop a reserve
     * @dev Only callable by the PoolConfigurator contract
     * @dev Does not reset eMode flags, which must be considered when reusing the same reserve id for a different
     * reserve.
     * @param asset The address of the underlying asset of the reserve
     */
    function dropReserve(address asset) external;

    /**
     * @notice Accumulates interest to all indexes of the reserve
     * @dev Only callable by the PoolConfigurator contract
     * @dev To be used when required by the configurator, for example when updating interest rates strategy data
     * @param asset The address of the underlying asset of the reserve
     */
    function syncIndexesState(address asset) external;

    /**
     * @notice Updates interest rates on the reserve data
     * @dev Only callable by the PoolConfigurator contract
     * @dev To be used when required by the configurator, for example when updating interest rates strategy data
     * @param asset The address of the underlying asset of the reserve
     */
    function syncRatesState(address asset) external;

    /**
     * @notice Sets the configuration bitmap of the reserve as a whole
     * @dev Only callable by the PoolConfigurator contract
     * @param asset The address of the underlying asset of the reserve
     * @param configuration The new configuration bitmap
     */
    function setConfiguration(address asset, DataTypes.ReserveConfigurationMap calldata configuration) external;

    /**
     * @notice Returns the configuration of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The configuration of the reserve
     */
    function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);

    /**
     * @notice Returns the configuration of the user across all the reserves
     * @param user The user address
     * @return The configuration of the user
     */
    function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);

    /**
     * @notice Returns the normalized income of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The reserve's normalized income
     */
    function getReserveNormalizedIncome(address asset) external view returns (uint256);

    /**
     * @notice Returns the normalized variable debt per unit of asset
     * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a
     * "dynamic" variable index based on time, current stored index and virtual rate at the current
     * moment (approx. a borrower would get if opening a position). This means that is always used in
     * combination with variable debt supply/balances.
     * If using this function externally, consider that is possible to have an increasing normalized
     * variable debt that is not equivalent to how the variable debt index would be updated in storage
     * (e.g. only updates with non-zero variable debt supply)
     * @param asset The address of the underlying asset of the reserve
     * @return The reserve normalized variable debt
     */
    function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);

    /**
     * @notice Returns the state and configuration of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The state and configuration data of the reserve
     */
    function getReserveData(address asset) external view returns (DataTypes.ReserveDataLegacy memory);

    /**
     * @notice Returns the virtual underlying balance of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The reserve virtual underlying balance
     */
    function getVirtualUnderlyingBalance(address asset) external view returns (uint128);

    /**
     * @notice Validates and finalizes an aToken transfer
     * @dev Only callable by the overlying aToken of the `asset`
     * @param asset The address of the underlying asset of the aToken
     * @param from The user from which the aTokens are transferred
     * @param to The user receiving the aTokens
     * @param scaledAmount The scaled amount being transferred/withdrawn
     * @param scaledBalanceFromBefore The aToken scaled balance of the `from` user before the transfer
     */
    function finalizeTransfer(
        address asset,
        address from,
        address to,
        uint256 scaledAmount,
        uint256 scaledBalanceFromBefore
    )
        external;

    /**
     * @notice Returns the list of the underlying assets of all the initialized reserves
     * @dev It does not include dropped reserves
     * @return The addresses of the underlying assets of the initialized reserves
     */
    function getReservesList() external view returns (address[] memory);

    /**
     * @notice Returns the number of initialized reserves
     * @dev It includes dropped reserves
     * @return The count
     */
    function getReservesCount() external view returns (uint256);

    /**
     * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the
     * DataTypes.ReserveData struct
     * @param id The id of the reserve as stored in the DataTypes.ReserveData struct
     * @return The address of the reserve associated with id
     */
    function getReserveAddressById(uint16 id) external view returns (address);

    /**
     * @notice Returns the PoolAddressesProvider connected to this contract
     * @return The address of the PoolAddressesProvider
     */
    function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);

    /**
     * @notice Returns the ReserveInterestRateStrategy connected to all the reserves
     * @return The address of the ReserveInterestRateStrategy contract
     */
    function RESERVE_INTEREST_RATE_STRATEGY() external view returns (address);

    /**
     * @notice Updates flash loan premium. All this premium is collected by the protocol treasury.
     * @dev The premium is calculated on the total borrowed amount
     * @dev Only callable by the PoolConfigurator contract
     * @param flashLoanPremium The flash loan premium, expressed in bps
     */
    function updateFlashloanPremium(uint128 flashLoanPremium) external;

    /**
     * @notice Configures a new or alters an existing collateral configuration of an eMode.
     * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.
     * The category 0 is reserved as it's the default for volatile assets
     * @param id The id of the category
     * @param config The configuration of the category
     */
    function configureEModeCategory(uint8 id, DataTypes.EModeCategoryBaseConfiguration memory config) external;

    /**
     * @notice Replaces the current eMode collateralBitmap.
     * @param id The id of the category
     * @param collateralBitmap The collateralBitmap of the category
     */
    function configureEModeCategoryCollateralBitmap(uint8 id, uint128 collateralBitmap) external;

    /**
     * @notice Replaces the current eMode borrowableBitmap.
     * @param id The id of the category
     * @param borrowableBitmap The borrowableBitmap of the category
     */
    function configureEModeCategoryBorrowableBitmap(uint8 id, uint128 borrowableBitmap) external;

    /**
     * @notice Replaces the current eMode ltvzeroBitmap.
     * @param id The id of the category
     * @param ltvzeroBitmap The ltvzeroBitmap of the category
     */
    function configureEModeCategoryLtvzeroBitmap(uint8 id, uint128 ltvzeroBitmap) external;

    /**
     * @notice Returns the data of an eMode category
     * @dev DEPRECATED use independent getters instead
     * @param id The id of the category
     * @return The configuration data of the category
     */
    function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategoryLegacy memory);

    /**
     * @notice Returns the label of an eMode category
     * @dev This function is deprecated and will be removed in a future version.
     * @custom:deprecated
     * @param id The id of the category
     * @return The label of the category
     */
    function getEModeCategoryLabel(uint8 id) external view returns (string memory);

    /**
     * @notice Returns the collateral config of an eMode category
     * @param id The id of the category
     * @return The ltv,lt,lb of the category
     */
    function getEModeCategoryCollateralConfig(uint8 id) external view returns (DataTypes.CollateralConfig memory);

    /**
     * @notice Returns the collateralBitmap of an eMode category
     * @param id The id of the category
     * @return The collateralBitmap of the category
     */
    function getEModeCategoryCollateralBitmap(uint8 id) external view returns (uint128);

    /**
     * @notice Returns the borrowableBitmap of an eMode category
     * @param id The id of the category
     * @return The borrowableBitmap of the category
     */
    function getEModeCategoryBorrowableBitmap(uint8 id) external view returns (uint128);

    /**
     * @notice Returns the ltvzero of an eMode category
     * @param id The id of the category
     * @return The ltvzeroBitmap of the category
     */
    function getEModeCategoryLtvzeroBitmap(uint8 id) external view returns (uint128);

    /**
     * @notice Allows a user to use the protocol in eMode
     * @param categoryId The id of the category
     */
    function setUserEMode(uint8 categoryId) external;

    /**
     * @notice Returns the eMode the user is using
     * @param user The address of the user
     * @return The eMode id
     */
    function getUserEMode(address user) external view returns (uint256);

    /**
     * @notice Resets the isolation mode total debt of the given asset to zero
     * @dev It requires the given asset has zero debt ceiling
     * @param asset The address of the underlying asset to reset the isolationModeTotalDebt
     */
    function resetIsolationModeTotalDebt(address asset) external;

    /**
     * @notice Sets the liquidation grace period of the given asset
     * @dev To enable a liquidation grace period, a timestamp in the future should be set,
     *      To disable a liquidation grace period, any timestamp in the past works, like 0
     * @param asset The address of the underlying asset to set the liquidationGracePeriod
     * @param until Timestamp when the liquidation grace period will end
     *
     */
    function setLiquidationGracePeriod(address asset, uint40 until) external;

    /**
     * @notice Returns the liquidation grace period of the given asset
     * @param asset The address of the underlying asset
     * @return Timestamp when the liquidation grace period will end
     *
     */
    function getLiquidationGracePeriod(address asset) external view returns (uint40);

    /**
     * @notice Returns the total fee on flash loans.
     * @dev From v3.4 all flashloan fees will be send to the treasury.
     * @return The total fee on flashloans
     */
    function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);

    /**
     * @notice Returns the part of the flashloan fees sent to protocol
     * @dev From v3.4 all flashloan fees will be send to the treasury and this value
     *      is always 100_00.
     * @return The flashloan fee sent to the protocol treasury
     */
    function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);

    /**
     * @notice Returns the maximum number of reserves supported to be listed in this Pool
     * @return The maximum number of reserves supported
     */
    function MAX_NUMBER_RESERVES() external view returns (uint16);

    /**
     * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens
     * @param assets The list of reserves for which the minting needs to be executed
     */
    function mintToTreasury(address[] calldata assets) external;

    /**
     * @notice Rescue and transfer tokens locked in this contract
     * @param token The address of the token
     * @param to The address of the recipient
     * @param amount The amount of token to transfer
     */
    function rescueTokens(address token, address to, uint256 amount) external;

    /**
     * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
     * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
     * @dev Deprecated: Use the `supply` function instead
     * @param asset The address of the underlying asset to supply
     * @param amount The amount to be supplied
     * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
     *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
     *   is a different wallet
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     */
    function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

    /**
     * @notice It covers the deficit of a specified reserve by burning the equivalent aToken `amount` for assets
     * @dev The deficit of a reserve can occur due to situations where borrowed assets are not repaid, leading to bad
     * debt.
     * @param asset The address of the underlying asset to cover the deficit.
     * @param amount The amount to be covered, in aToken
     * @return The amount of tokens burned
     */
    function eliminateReserveDeficit(address asset, uint256 amount) external returns (uint256);

    /**
     * @notice Approves or disapproves a position manager. This position manager will be able
     * to call the `setUserUseReserveAsCollateralOnBehalfOf` and the
     * `setUserEModeOnBehalfOf` function on behalf of the user.
     * @param positionManager The address of the position manager
     * @param approve True if the position manager should be approved, false otherwise
     */
    function approvePositionManager(address positionManager, bool approve) external;

    /**
     * @notice Renounces a position manager role for a given user.
     * @param user The address of the user
     */
    function renouncePositionManagerRole(address user) external;

    /**
     * @notice Sets the use as collateral flag for the user on the specific reserve on behalf of the user.
     * @param asset The address of the underlying asset of the reserve
     * @param useAsCollateral True if the user wants to use the reserve as collateral, false otherwise
     * @param onBehalfOf The address of the user
     */
    function setUserUseReserveAsCollateralOnBehalfOf(address asset, bool useAsCollateral, address onBehalfOf) external;

    /**
     * @notice Sets the eMode category for the user on the specific reserve on behalf of the user.
     * @param categoryId The id of the category
     * @param onBehalfOf The address of the user
     */
    function setUserEModeOnBehalfOf(uint8 categoryId, address onBehalfOf) external;

    /*
     * @notice Returns true if the `positionManager` address is approved to use the position manager role on behalf of the user.
     * @param user The address of the user
     * @param positionManager The address of the position manager
     * @return True if the user is approved to use the position manager, false otherwise
     */
    function isApprovedPositionManager(address user, address positionManager) external view returns (bool);

    /**
     * @notice Returns the current deficit of a reserve.
     * @param asset The address of the underlying asset of the reserve
     * @return The current deficit of the reserve
     */
    function getReserveDeficit(address asset) external view returns (uint256);

    /**
     * @notice Returns the aToken address of a reserve.
     * @param asset The address of the underlying asset of the reserve
     * @return The address of the aToken
     */
    function getReserveAToken(address asset) external view returns (address);

    /**
     * @notice Returns the variableDebtToken address of a reserve.
     * @param asset The address of the underlying asset of the reserve
     * @return The address of the variableDebtToken
     */
    function getReserveVariableDebtToken(address asset) external view returns (address);

    /**
     * @notice Gets the address of the external FlashLoanLogic
     */
    function getFlashLoanLogic() external view returns (address);

    /**
     * @notice Gets the address of the external BorrowLogic
     */
    function getBorrowLogic() external view returns (address);

    /**
     * @notice Gets the address of the external LiquidationLogic
     */
    function getLiquidationLogic() external view returns (address);

    /**
     * @notice Gets the address of the external PoolLogic
     */
    function getPoolLogic() external view returns (address);

    /**
     * @notice Gets the address of the external SupplyLogic
     */
    function getSupplyLogic() external view returns (address);
}

contracts/external/aave/IPoolAddressesProvider.sol

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

/**
 * @title IPoolAddressesProvider
 * @author Aave
 * @notice Defines the basic interface for a Pool Addresses Provider.
 */
interface IPoolAddressesProvider {
    /**
     * @dev Emitted when the market identifier is updated.
     * @param oldMarketId The old id of the market
     * @param newMarketId The new id of the market
     */
    event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);

    /**
     * @dev Emitted when the pool is updated.
     * @param oldAddress The old address of the Pool
     * @param newAddress The new address of the Pool
     */
    event PoolUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the pool configurator is updated.
     * @param oldAddress The old address of the PoolConfigurator
     * @param newAddress The new address of the PoolConfigurator
     */
    event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the price oracle is updated.
     * @param oldAddress The old address of the PriceOracle
     * @param newAddress The new address of the PriceOracle
     */
    event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the ACL manager is updated.
     * @param oldAddress The old address of the ACLManager
     * @param newAddress The new address of the ACLManager
     */
    event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the ACL admin is updated.
     * @param oldAddress The old address of the ACLAdmin
     * @param newAddress The new address of the ACLAdmin
     */
    event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the price oracle sentinel is updated.
     * @param oldAddress The old address of the PriceOracleSentinel
     * @param newAddress The new address of the PriceOracleSentinel
     */
    event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the pool data provider is updated.
     * @param oldAddress The old address of the PoolDataProvider
     * @param newAddress The new address of the PoolDataProvider
     */
    event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when a new proxy is created.
     * @param id The identifier of the proxy
     * @param proxyAddress The address of the created proxy contract
     * @param implementationAddress The address of the implementation contract
     */
    event ProxyCreated(bytes32 indexed id, address indexed proxyAddress, address indexed implementationAddress);

    /**
     * @dev Emitted when a new non-proxied contract address is registered.
     * @param id The identifier of the contract
     * @param oldAddress The address of the old contract
     * @param newAddress The address of the new contract
     */
    event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);

    /**
     * @dev Emitted when the implementation of the proxy registered with id is updated
     * @param id The identifier of the contract
     * @param proxyAddress The address of the proxy contract
     * @param oldImplementationAddress The address of the old implementation contract
     * @param newImplementationAddress The address of the new implementation contract
     */
    event AddressSetAsProxy(
        bytes32 indexed id,
        address indexed proxyAddress,
        address oldImplementationAddress,
        address indexed newImplementationAddress
    );

    /**
     * @notice Returns the id of the Aave market to which this contract points to.
     * @return The market id
     */
    function getMarketId() external view returns (string memory);

    /**
     * @notice Associates an id with a specific PoolAddressesProvider.
     * @dev This can be used to create an onchain registry of PoolAddressesProviders to
     * identify and validate multiple Aave markets.
     * @param newMarketId The market id
     */
    function setMarketId(string calldata newMarketId) external;

    /**
     * @notice Returns an address by its identifier.
     * @dev The returned address might be an EOA or a contract, potentially proxied
     * @dev It returns ZERO if there is no registered address with the given id
     * @param id The id
     * @return The address of the registered for the specified id
     */
    function getAddress(bytes32 id) external view returns (address);

    /**
     * @notice General function to update the implementation of a proxy registered with
     * certain `id`. If there is no proxy registered, it will instantiate one and
     * set as implementation the `newImplementationAddress`.
     * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit
     * setter function, in order to avoid unexpected consequences
     * @param id The id
     * @param newImplementationAddress The address of the new implementation
     */
    function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;

    /**
     * @notice Sets an address for an id replacing the address saved in the addresses map.
     * @dev IMPORTANT Use this function carefully, as it will do a hard replacement
     * @param id The id
     * @param newAddress The address to set
     */
    function setAddress(bytes32 id, address newAddress) external;

    /**
     * @notice Returns the address of the Pool proxy.
     * @return The Pool proxy address
     */
    function getPool() external view returns (address);

    /**
     * @notice Updates the implementation of the Pool, or creates a proxy
     * setting the new `pool` implementation when the function is called for the first time.
     * @param newPoolImpl The new Pool implementation
     */
    function setPoolImpl(address newPoolImpl) external;

    /**
     * @notice Returns the address of the PoolConfigurator proxy.
     * @return The PoolConfigurator proxy address
     */
    function getPoolConfigurator() external view returns (address);

    /**
     * @notice Updates the implementation of the PoolConfigurator, or creates a proxy
     * setting the new `PoolConfigurator` implementation when the function is called for the first time.
     * @param newPoolConfiguratorImpl The new PoolConfigurator implementation
     */
    function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;

    /**
     * @notice Returns the address of the price oracle.
     * @return The address of the PriceOracle
     */
    function getPriceOracle() external view returns (address);

    /**
     * @notice Updates the address of the price oracle.
     * @param newPriceOracle The address of the new PriceOracle
     */
    function setPriceOracle(address newPriceOracle) external;

    /**
     * @notice Returns the address of the ACL manager.
     * @return The address of the ACLManager
     */
    function getACLManager() external view returns (address);

    /**
     * @notice Updates the address of the ACL manager.
     * @param newAclManager The address of the new ACLManager
     */
    function setACLManager(address newAclManager) external;

    /**
     * @notice Returns the address of the ACL admin.
     * @return The address of the ACL admin
     */
    function getACLAdmin() external view returns (address);

    /**
     * @notice Updates the address of the ACL admin.
     * @param newAclAdmin The address of the new ACL admin
     */
    function setACLAdmin(address newAclAdmin) external;

    /**
     * @notice Returns the address of the price oracle sentinel.
     * @return The address of the PriceOracleSentinel
     */
    function getPriceOracleSentinel() external view returns (address);

    /**
     * @notice Updates the address of the price oracle sentinel.
     * @param newPriceOracleSentinel The address of the new PriceOracleSentinel
     */
    function setPriceOracleSentinel(address newPriceOracleSentinel) external;

    /**
     * @notice Returns the address of the data provider.
     * @return The address of the DataProvider
     */
    function getPoolDataProvider() external view returns (address);

    /**
     * @notice Updates the address of the data provider.
     * @param newDataProvider The address of the new DataProvider
     */
    function setPoolDataProvider(address newDataProvider) external;
}

contracts/external/aave/IPriceOracleGetter.sol

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

/**
 * @title IPriceOracleGetter
 * @author Aave
 * @notice Interface for the Aave price oracle.
 */
interface IPriceOracleGetter {
    /**
     * @notice Returns the base currency address
     * @dev Address 0x0 is reserved for USD as base currency.
     * @return Returns the base currency address.
     */
    function BASE_CURRENCY() external view returns (address);

    /**
     * @notice Returns the base currency unit
     * @dev 1 ether for ETH, 1e8 for USD.
     * @return Returns the base currency unit.
     */
    function BASE_CURRENCY_UNIT() external view returns (uint256);

    /**
     * @notice Returns the asset price in the base currency
     * @param asset The address of the asset
     * @return The price of the asset
     */
    function getAssetPrice(address asset) external view returns (uint256);
}

contracts/external/aave/ReserveConfiguration.sol

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

import { Errors } from "./Errors.sol";
import { DataTypes } from "./DataTypes.sol";

/**
 * @title ReserveConfiguration library
 * @author Aave
 * @notice Implements the bitmap logic to handle the reserve configuration
 */
library ReserveConfiguration {
    uint256 internal constant LTV_MASK = 0x000000000000000000000000000000000000000000000000000000000000FFFF; // prettier-ignore
    uint256 internal constant LIQUIDATION_THRESHOLD_MASK =
        0x00000000000000000000000000000000000000000000000000000000FFFF0000; // prettier-ignore
    uint256 internal constant LIQUIDATION_BONUS_MASK =
        0x0000000000000000000000000000000000000000000000000000FFFF00000000; // prettier-ignore
    uint256 internal constant DECIMALS_MASK = 0x00000000000000000000000000000000000000000000000000FF000000000000; // prettier-ignore
    uint256 internal constant ACTIVE_MASK = 0x0000000000000000000000000000000000000000000000000100000000000000; // prettier-ignore
    uint256 internal constant FROZEN_MASK = 0x0000000000000000000000000000000000000000000000000200000000000000; // prettier-ignore
    uint256 internal constant BORROWING_MASK = 0x0000000000000000000000000000000000000000000000000400000000000000; // prettier-ignore
    // @notice there is an unoccupied hole of 1 bit at position 59 from pre 3.2 stableBorrowRateEnabled
    uint256 internal constant PAUSED_MASK = 0x0000000000000000000000000000000000000000000000001000000000000000; // prettier-ignore
    uint256 internal constant BORROWABLE_IN_ISOLATION_MASK =
        0x0000000000000000000000000000000000000000000000002000000000000000; // prettier-ignore
    uint256 internal constant SILOED_BORROWING_MASK =
        0x0000000000000000000000000000000000000000000000004000000000000000; // prettier-ignore
    uint256 internal constant FLASHLOAN_ENABLED_MASK =
        0x0000000000000000000000000000000000000000000000008000000000000000; // prettier-ignore
    uint256 internal constant RESERVE_FACTOR_MASK = 0x00000000000000000000000000000000000000000000FFFF0000000000000000; // prettier-ignore
    uint256 internal constant BORROW_CAP_MASK = 0x00000000000000000000000000000000000FFFFFFFFF00000000000000000000; // prettier-ignore
    uint256 internal constant SUPPLY_CAP_MASK = 0x00000000000000000000000000FFFFFFFFF00000000000000000000000000000; // prettier-ignore
    uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK =
        0x0000000000000000000000FFFF00000000000000000000000000000000000000; // prettier-ignore
    //@notice there is an unoccupied hole of 8 bits from 168 to 175 left from pre 3.2 eModeCategory
    //@notice there is an unoccupied hole of 34 bits from 176 to 211 left from pre 3.4 unbackedMintCap
    uint256 internal constant DEBT_CEILING_MASK = 0x0FFFFFFFFFF00000000000000000000000000000000000000000000000000000; // prettier-ignore
    //@notice DEPRECATED: in v3.4 all reserves have virtual accounting enabled
    uint256 internal constant VIRTUAL_ACC_ACTIVE_MASK =
        0x1000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore

    /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
    uint256 internal constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
    uint256 internal constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
    uint256 internal constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
    uint256 internal constant IS_ACTIVE_START_BIT_POSITION = 56;
    uint256 internal constant IS_FROZEN_START_BIT_POSITION = 57;
    uint256 internal constant BORROWING_ENABLED_START_BIT_POSITION = 58;
    uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60;
    uint256 internal constant BORROWABLE_IN_ISOLATION_START_BIT_POSITION = 61;
    uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62;
    uint256 internal constant FLASHLOAN_ENABLED_START_BIT_POSITION = 63;
    uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64;
    uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80;
    uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116;
    uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152;
    //@notice there is an unoccupied hole of 8 bits from 168 to 175 left from pre 3.2 eModeCategory
    //@notice there is an unoccupied hole of 34 bits from 176 to 211 left from pre 3.4 unbackedMintCap
    uint256 internal constant DEBT_CEILING_START_BIT_POSITION = 212;
    //@notice DEPRECATED: in v3.4 all reserves have virtual accounting enabled
    uint256 internal constant VIRTUAL_ACC_START_BIT_POSITION = 252;

    uint256 internal constant MAX_VALID_LTV = 65_535;
    uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65_535;
    uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65_535;
    uint256 internal constant MAX_VALID_DECIMALS = 255;
    uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65_535;
    uint256 internal constant MAX_VALID_BORROW_CAP = 68_719_476_735;
    uint256 internal constant MAX_VALID_SUPPLY_CAP = 68_719_476_735;
    uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65_535;
    uint256 internal constant MAX_VALID_DEBT_CEILING = 1_099_511_627_775;

    uint256 public constant DEBT_CEILING_DECIMALS = 2;
    uint16 public constant MAX_RESERVES_COUNT = 128;

    /**
     * @notice Sets the Loan to Value of the reserve
     * @param self The reserve configuration
     * @param ltv The new ltv
     */
    function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
        require(ltv <= MAX_VALID_LTV, Errors.InvalidLtv());

        self.data = (self.data & ~LTV_MASK) | ltv;
    }

    /**
     * @notice Gets the Loan to Value of the reserve
     * @param self The reserve configuration
     * @return The loan to value
     */
    function getLtv(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return self.data & LTV_MASK;
    }

    /**
     * @notice Sets the liquidation threshold of the reserve
     * @param self The reserve configuration
     * @param threshold The new liquidation threshold
     */
    function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure {
        require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.InvalidLiquidationThreshold());

        self.data = (self.data & ~LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
    }

    /**
     * @notice Gets the liquidation threshold of the reserve
     * @param self The reserve configuration
     * @return The liquidation threshold
     */
    function getLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
    }

    /**
     * @notice Sets the liquidation bonus of the reserve
     * @param self The reserve configuration
     * @param bonus The new liquidation bonus
     */
    function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {
        require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.InvalidLiquidationBonus());

        self.data = (self.data & ~LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
    }

    /**
     * @notice Gets the liquidation bonus of the reserve
     * @param self The reserve configuration
     * @return The liquidation bonus
     */
    function getLiquidationBonus(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
    }

    /**
     * @notice Sets the decimals of the underlying asset of the reserve
     * @param self The reserve configuration
     * @param decimals The decimals
     */
    function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {
        require(decimals <= MAX_VALID_DECIMALS, Errors.InvalidDecimals());

        self.data = (self.data & ~DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
    }

    /**
     * @notice Gets the decimals of the underlying asset of the reserve
     * @param self The reserve configuration
     * @return The decimals of the asset
     */
    function getDecimals(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
    }

    /**
     * @notice Sets the active state of the reserve
     * @param self The reserve configuration
     * @param active The active state
     */
    function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
        self.data = (self.data & ~ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
    }

    /**
     * @notice Gets the active state of the reserve
     * @param self The reserve configuration
     * @return The active state
     */
    function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & ACTIVE_MASK) != 0;
    }

    /**
     * @notice Sets the frozen state of the reserve
     * @param self The reserve configuration
     * @param frozen The frozen state
     */
    function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
        self.data = (self.data & ~FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
    }

    /**
     * @notice Gets the frozen state of the reserve
     * @param self The reserve configuration
     * @return The frozen state
     */
    function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & FROZEN_MASK) != 0;
    }

    /**
     * @notice Sets the paused state of the reserve
     * @param self The reserve configuration
     * @param paused The paused state
     */
    function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure {
        self.data = (self.data & ~PAUSED_MASK) | (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);
    }

    /**
     * @notice Gets the paused state of the reserve
     * @param self The reserve configuration
     * @return The paused state
     */
    function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & PAUSED_MASK) != 0;
    }

    /**
     * @notice Sets the borrowable in isolation flag for the reserve.
     * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed
     * amount will be accumulated in the isolated collateral's total debt exposure.
     * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep
     * consistency in the debt ceiling calculations.
     * @param self The reserve configuration
     * @param borrowable True if the asset is borrowable
     */
    function setBorrowableInIsolation(DataTypes.ReserveConfigurationMap memory self, bool borrowable) internal pure {
        self.data = (self.data & ~BORROWABLE_IN_ISOLATION_MASK)
            | (uint256(borrowable ? 1 : 0) << BORROWABLE_IN_ISOLATION_START_BIT_POSITION);
    }

    /**
     * @notice Gets the borrowable in isolation flag for the reserve.
     * @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with
     * isolated collateral is accounted for in the isolated collateral's total debt exposure.
     * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep
     * consistency in the debt ceiling calculations.
     * @param self The reserve configuration
     * @return The borrowable in isolation flag
     */
    function getBorrowableInIsolation(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & BORROWABLE_IN_ISOLATION_MASK) != 0;
    }

    /**
     * @notice Sets the siloed borrowing flag for the reserve.
     * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.
     * @param self The reserve configuration
     * @param siloed True if the asset is siloed
     */
    function setSiloedBorrowing(DataTypes.ReserveConfigurationMap memory self, bool siloed) internal pure {
        self.data =
            (self.data & ~SILOED_BORROWING_MASK) | (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);
    }

    /**
     * @notice Gets the siloed borrowing flag for the reserve.
     * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.
     * @param self The reserve configuration
     * @return The siloed borrowing flag
     */
    function getSiloedBorrowing(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & SILOED_BORROWING_MASK) != 0;
    }

    /**
     * @notice Enables or disables borrowing on the reserve
     * @param self The reserve configuration
     * @param enabled True if the borrowing needs to be enabled, false otherwise
     */
    function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
        self.data = (self.data & ~BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
    }

    /**
     * @notice Gets the borrowing state of the reserve
     * @param self The reserve configuration
     * @return The borrowing state
     */
    function getBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & BORROWING_MASK) != 0;
    }

    /**
     * @notice Sets the reserve factor of the reserve
     * @param self The reserve configuration
     * @param reserveFactor The reserve factor
     */
    function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure {
        require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.InvalidReserveFactor());

        self.data = (self.data & ~RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
    }

    /**
     * @notice Gets the reserve factor of the reserve
     * @param self The reserve configuration
     * @return The reserve factor
     */
    function getReserveFactor(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
    }

    /**
     * @notice Sets the borrow cap of the reserve
     * @param self The reserve configuration
     * @param borrowCap The borrow cap
     */
    function setBorrowCap(DataTypes.ReserveConfigurationMap memory self, uint256 borrowCap) internal pure {
        require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.InvalidBorrowCap());

        self.data = (self.data & ~BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION);
    }

    /**
     * @notice Gets the borrow cap of the reserve
     * @param self The reserve configuration
     * @return The borrow cap
     */
    function getBorrowCap(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;
    }

    /**
     * @notice Sets the supply cap of the reserve
     * @param self The reserve configuration
     * @param supplyCap The supply cap
     */
    function setSupplyCap(DataTypes.ReserveConfigurationMap memory self, uint256 supplyCap) internal pure {
        require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.InvalidSupplyCap());

        self.data = (self.data & ~SUPPLY_CAP_MASK) | (supplyCap << SUPPLY_CAP_START_BIT_POSITION);
    }

    /**
     * @notice Gets the supply cap of the reserve
     * @param self The reserve configuration
     * @return The supply cap
     */
    function getSupplyCap(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION;
    }

    /**
     * @notice Sets the debt ceiling in isolation mode for the asset
     * @param self The reserve configuration
     * @param ceiling The maximum debt ceiling for the asset
     */
    function setDebtCeiling(DataTypes.ReserveConfigurationMap memory self, uint256 ceiling) internal pure {
        require(ceiling <= MAX_VALID_DEBT_CEILING, Errors.InvalidDebtCeiling());

        self.data = (self.data & ~DEBT_CEILING_MASK) | (ceiling << DEBT_CEILING_START_BIT_POSITION);
    }

    /**
     * @notice Gets the debt ceiling for the asset if the asset is in isolation mode
     * @param self The reserve configuration
     * @return The debt ceiling (0 = isolation mode disabled)
     */
    function getDebtCeiling(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & DEBT_CEILING_MASK) >> DEBT_CEILING_START_BIT_POSITION;
    }

    /**
     * @notice Sets the liquidation protocol fee of the reserve
     * @param self The reserve configuration
     * @param liquidationProtocolFee The liquidation protocol fee
     */
    function setLiquidationProtocolFee(
        DataTypes.ReserveConfigurationMap memory self,
        uint256 liquidationProtocolFee
    )
        internal
        pure
    {
        require(liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE, Errors.InvalidLiquidationProtocolFee());

        self.data = (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK)
            | (liquidationProtocolFee << LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION);
    }

    /**
     * @dev Gets the liquidation protocol fee
     * @param self The reserve configuration
     * @return The liquidation protocol fee
     */
    function getLiquidationProtocolFee(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {
        return (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) >> LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION;
    }

    /**
     * @notice Sets the flashloanable flag for the reserve
     * @param self The reserve configuration
     * @param flashLoanEnabled True if the asset is flashloanable, false otherwise
     */
    function setFlashLoanEnabled(DataTypes.ReserveConfigurationMap memory self, bool flashLoanEnabled) internal pure {
        self.data = (self.data & ~FLASHLOAN_ENABLED_MASK)
            | (uint256(flashLoanEnabled ? 1 : 0) << FLASHLOAN_ENABLED_START_BIT_POSITION);
    }

    /**
     * @notice Gets the flashloanable flag for the reserve
     * @param self The reserve configuration
     * @return The flashloanable flag
     */
    function getFlashLoanEnabled(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & FLASHLOAN_ENABLED_MASK) != 0;
    }

    /**
     * @notice Forcefully set the virtual account active state of the reserve to `true`
     * @dev DEPRECATED: in v3.4 all reserves have virtual accounting enabled.
     * The flag is carried along for backward compatibility with integrations directly querying the configuration.
     * @param self The reserve configuration
     */
    function setVirtualAccActive(DataTypes.ReserveConfigurationMap memory self) internal pure {
        self.data = (self.data & ~VIRTUAL_ACC_ACTIVE_MASK) | (uint256(1) << VIRTUAL_ACC_START_BIT_POSITION);
    }

    /**
     * @notice Gets the configuration flags of the reserve
     * @param self The reserve configuration
     * @return The state flag representing active
     * @return The state flag representing frozen
     * @return The state flag representing borrowing enabled
     * @return The state flag representing paused
     */
    function getFlags(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool, bool, bool, bool) {
        uint256 dataLocal = self.data;

        return (
            (dataLocal & ACTIVE_MASK) != 0,
            (dataLocal & FROZEN_MASK) != 0,
            (dataLocal & BORROWING_MASK) != 0,
            (dataLocal & PAUSED_MASK) != 0
        );
    }

    /**
     * @notice Gets the configuration parameters of the reserve from storage
     * @param self The reserve configuration
     * @return The state param representing ltv
     * @return The state param representing liquidation threshold
     * @return The state param representing liquidation bonus
     * @return The state param representing reserve decimals
     * @return The state param representing reserve factor
     */
    function getParams(DataTypes.ReserveConfigurationMap memory self)
        internal
        pure
        returns (uint256, uint256, uint256, uint256, uint256)
    {
        uint256 dataLocal = self.data;

        return (
            dataLocal & LTV_MASK,
            (dataLocal & LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
            (dataLocal & LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
            (dataLocal & DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
            (dataLocal & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
        );
    }

    /**
     * @notice Gets the caps parameters of the reserve from storage
     * @param self The reserve configuration
     * @return The state param representing borrow cap
     * @return The state param representing supply cap.
     */
    function getCaps(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256, uint256) {
        uint256 dataLocal = self.data;

        return (
            (dataLocal & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION,
            (dataLocal & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION
        );
    }
}

contracts/external/aave/UserConfiguration.sol

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

import { IPool } from "./IPool.sol";
import { Errors } from "./Errors.sol";
import { DataTypes } from "./DataTypes.sol";
import { ReserveConfiguration } from "./ReserveConfiguration.sol";

/**
 * @title UserConfiguration library
 * @author Aave
 * @notice Implements the bitmap logic to handle the user configuration
 */
library UserConfiguration {
    using ReserveConfiguration for DataTypes.ReserveConfigurationMap;

    uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555;
    uint256 internal constant COLLATERAL_MASK = 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;

    /**
     * @notice Sets if the user is borrowing the reserve identified by reserveIndex
     * @param self The configuration object
     * @param reserveIndex The index of the reserve in the bitmap
     * @param borrowing True if the user is borrowing the reserve, false otherwise
     */
    function setBorrowing(DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing) internal {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            uint256 bit = 1 << (reserveIndex << 1);
            if (borrowing) {
                self.data |= bit;
            } else {
                self.data &= ~bit;
            }
        }
    }

    /**
     * @notice Sets if the user is using as collateral the reserve identified by reserveIndex
     * @param self The configuration object
     * @param reserveIndex The index of the reserve in the bitmap
     * @param asset The address of the reserve
     * @param user The address of the user
     * @param usingAsCollateral True if the user is using the reserve as collateral, false otherwise
     */
    function setUsingAsCollateral(
        DataTypes.UserConfigurationMap storage self,
        uint256 reserveIndex,
        address asset,
        address user,
        bool usingAsCollateral
    )
        internal
    {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            uint256 bit = 1 << ((reserveIndex << 1) + 1);
            if (usingAsCollateral) {
                self.data |= bit;
                emit IPool.ReserveUsedAsCollateralEnabled(asset, user);
            } else {
                self.data &= ~bit;
                emit IPool.ReserveUsedAsCollateralDisabled(asset, user);
            }
        }
    }

    /**
     * @notice Returns if a user has been using the reserve for borrowing or as collateral
     * @param self The configuration object
     * @param reserveIndex The index of the reserve in the bitmap
     * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise
     */
    function isUsingAsCollateralOrBorrowing(
        DataTypes.UserConfigurationMap memory self,
        uint256 reserveIndex
    )
        internal
        pure
        returns (bool)
    {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            return (self.data >> (reserveIndex << 1)) & 3 != 0;
        }
    }

    /**
     * @notice Validate a user has been using the reserve for borrowing
     * @param self The configuration object
     * @param reserveIndex The index of the reserve in the bitmap
     * @return True if the user has been using a reserve for borrowing, false otherwise
     */
    function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
        internal
        pure
        returns (bool)
    {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            return (self.data >> (reserveIndex << 1)) & 1 != 0;
        }
    }

    /**
     * @notice Validate a user has been using the reserve as collateral
     * @param self The configuration object
     * @param reserveIndex The index of the reserve in the bitmap
     * @return True if the user has been using a reserve as collateral, false otherwise
     */
    function isUsingAsCollateral(
        DataTypes.UserConfigurationMap memory self,
        uint256 reserveIndex
    )
        internal
        pure
        returns (bool)
    {
        unchecked {
            require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());
            return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0;
        }
    }

    /**
     * @notice Checks if a user has been supplying only one reserve as collateral
     * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0
     * @param self The configuration object
     * @return True if the user has been supplying as collateral one reserve, false otherwise
     */
    function isUsingAsCollateralOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
        uint256 collateralData = self.data & COLLATERAL_MASK;
        return collateralData != 0 && (collateralData & (collateralData - 1) == 0);
    }

    /**
     * @notice Checks if a user has been supplying any reserve as collateral
     * @param self The configuration object
     * @return True if the user has been supplying as collateral any reserve, false otherwise
     */
    function isUsingAsCollateralAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
        return self.data & COLLATERAL_MASK != 0;
    }

    /**
     * @notice Checks if a user has been borrowing only one asset
     * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0
     * @param self The configuration object
     * @return True if the user has been supplying as collateral one reserve, false otherwise
     */
    function isBorrowingOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
        uint256 borrowingData = self.data & BORROWING_MASK;
        return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0);
    }

    /**
     * @notice Checks if a user has been borrowing from any reserve
     * @param self The configuration object
     * @return True if the user has been borrowing any reserve, false otherwise
     */
    function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
        return self.data & BORROWING_MASK != 0;
    }

    /**
     * @notice Checks if a user has not been using any reserve for borrowing, or as collateral
     * @param self The configuration object
     * @return True if the user has not been borrowing, or using as collateral any reserve, false otherwise
     */
    function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
        return self.data == 0;
    }

    /**
     * @notice Returns the Isolation Mode state of the user
     * @param self The configuration object
     * @param reservesData The state of all the reserves
     * @param reservesList The addresses of all the active reserves
     * @return True if the user is in isolation mode, false otherwise
     * @return The address of the only asset used as collateral
     * @return The debt ceiling of the reserve
     */
    function getIsolationModeState(
        DataTypes.UserConfigurationMap memory self,
        mapping(address => DataTypes.ReserveData) storage reservesData,
        mapping(uint256 => address) storage reservesList
    )
        internal
        view
        returns (bool, address, uint256)
    {
        if (isUsingAsCollateralOne(self)) {
            uint256 assetId = _getFirstAssetIdByMask(self, COLLATERAL_MASK);

            address assetAddress = reservesList[assetId];
            uint256 ceiling = reservesData[assetAddress].configuration.getDebtCeiling();
            if (ceiling != 0) {
                return (true, assetAddress, ceiling);
            }
        }
        return (false, address(0), 0);
    }

    /**
     * @notice Returns the siloed borrowing state for the user
     * @param self The configuration object
     * @param reservesData The data of all the reserves
     * @param reservesList The reserve list
     * @return True if the user has borrowed a siloed asset, false otherwise
     * @return The address of the only borrowed asset
     */
    function getSiloedBorrowingState(
        DataTypes.UserConfigurationMap memory self,
        mapping(address => DataTypes.ReserveData) storage reservesData,
        mapping(uint256 => address) storage reservesList
    )
        internal
        view
        returns (bool, address)
    {
        if (isBorrowingOne(self)) {
            uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK);
            address assetAddress = reservesList[assetId];
            if (reservesData[assetAddress].configuration.getSiloedBorrowing()) {
                return (true, assetAddress);
            }
        }

        return (false, address(0));
    }

    /**
     * @notice Returns the borrowed and collateral flags for the first asset on the bitmap and the bitmap shifted by
     * two.
     * @dev This function mutates the input and the 2 bit slots in the bitmap will no longer correspond to the reserve
     * index.
     * This is useful in situations where we want to iterate the bitmap as it allows for early exit once the bitmap
     * turns zero.
     * @param data The configuration uint256
     * @return The bitmap shifted by 2 bits, so that the first asset points to the *next* asset.
     * @return True if the first asset in the bitmap is borrowed.
     * @return True if the first asset in the bitmap is a collateral.
     */
    function getNextFlags(uint256 data) internal pure returns (uint256, bool, bool) {
        bool isBorrowed = data & 1 == 1;
        bool isEnabledAsCollateral = data & 2 == 2;
        return (data >> 2, isBorrowed, isEnabledAsCollateral);
    }

    /**
     * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask
     * @param self The configuration object
     * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied
     */
    function _getFirstAssetIdByMask(
        DataTypes.UserConfigurationMap memory self,
        uint256 mask
    )
        internal
        pure
        returns (uint256)
    {
        unchecked {
            uint256 bitmapData = self.data & mask;
            uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1);
            uint256 id;

            while ((firstAssetPosition >>= 2) != 0) {
                id += 1;
            }
            return id;
        }
    }
}

contracts/external/lido/IWstETH.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;

/**
 * @title IWstETH
 * @notice Interface for the wstETH token
 */
interface IWstETH {
    /**
     * @notice Exchanges stETH to wstETH
     * @param _stETHAmount amount of stETH to wrap in exchange for wstETH
     * @dev Requirements:
     *  - `_stETHAmount` must be non-zero
     *  - msg.sender must have at least `_stETHAmount` stETH
     *  - msg.sender must approve this contract to spend `_stETHAmount` stETH
     * @return Amount of wstETH user receives after wrap
     */
    function wrap(uint256 _stETHAmount) external returns (uint256);

    /**
     * @notice Exchanges wstETH to stETH
     * @param _wstETHAmount amount of wstETH to uwrap in exchange for stETH
     * @dev Requirements:
     *  - `_wstETHAmount` must be non-zero
     *  - msg.sender must have at least `_wstETHAmount` wstETH.
     * @return Amount of stETH user receives after unwrap
     */
    function unwrap(uint256 _wstETHAmount) external returns (uint256);

    /**
     * @notice Get amount of wstETH for a given amount of stETH
     * @param _stETHAmount amount of stETH
     * @return Amount of wstETH for a given stETH amount
     */
    function getWstETHByStETH(uint256 _stETHAmount) external view returns (uint256);

    /**
     * @notice Get amount of stETH for a given amount of wstETH
     * @param _wstETHAmount amount of wstETH
     * @return Amount of stETH for a given wstETH amount
     */
    function getStETHByWstETH(uint256 _wstETHAmount) external view returns (uint256);
}

contracts/external/weth/IWETH.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint256 value) external returns (bool);
    function withdraw(uint256) external;
}

contracts/interfaces/IAaveDeloopAdapter.sol

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

interface IAaveDeloopAdapter {
    /*//////////////////////////////////////////////////////////////
                                STRUCTS
    //////////////////////////////////////////////////////////////*/

    /// @notice User's current position on AAVE
    struct UserPosition {
        uint256 rsETHCollateral; // rsETH collateral balance (aRsETH)
        uint256 wethDebt; // WETH variable debt balance
        uint256 wstETHDebt; // wstETH variable debt balance
        uint256 healthFactor; // Current health factor (18 decimals)
    }

    /*//////////////////////////////////////////////////////////////
                                 ERRORS
    //////////////////////////////////////////////////////////////*/

    error InvalidDebtAsset();
    error InvalidAmount();
    error OraclePriceZero();
    error InstantFeeExceedsMax(uint256 fee);
    error ETHTransferFailed();
    error MaxRsETHExceeded();
    error MaxIterationsExceeded();
    error NoDebtToRepay();
    error BoostNotRepaid();
    error HealthFactorTooLow();
    error NoWithdrawableCollateral();
    error MinHealthFactorTooLow();
    error InstantWithdrawalDisabled();
    error CannotRecoverRsETH();
    error MaxDeloopIterationsInvalid();
    error MaxLoopIterationsInvalid();
    error LoopBudgetExhausted();
    error LoopNoBorrowCapacity();
    error InsufficientATokenApproval(uint256 required, uint256 approved);
    error InsufficientBorrowDelegation(uint256 required, uint256 delegated);
    error LoopFailed();

    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted once on initialization with every configured address
    event AdapterInitialized(
        address indexed aavePool,
        address weth,
        address wstETH,
        address stETH,
        address rsETH,
        address aRsETH,
        address variableDebtWETH,
        address variableDebtWstETH
    );

    /// @notice Emitted when a deloop operation is executed
    event Deloop(
        address indexed user, uint256 rsETHWithdrawn, uint256 totalDebtRepaid, address debtAsset, uint256 iterations
    );

    /// @notice Emitted when rsETH boost liquidity is deposited to the contract
    event BoostLiquidityDeposited(address indexed depositor, uint256 amount);

    /// @notice Emitted when rsETH boost liquidity is withdrawn from the contract
    event BoostLiquidityWithdrawn(address indexed recipient, uint256 amount);

    /// @notice Emitted when deloop exits early with debt remaining (e.g. below minimum instant withdrawal)
    event DeloopExitedEarly(address indexed user, uint256 remainingDebt, address debtAsset);

    /// @notice Emitted when loop exits early without reaching the target debt increase
    event LoopExitedEarly(
        address indexed user, uint256 totalDebtIncreased, uint256 targetDebtIncrease, address debtAsset
    );

    /// @notice Emitted when a loop operation is executed
    event Loop(
        address indexed user,
        uint256 totalDebtIncreased,
        uint256 totalRsETHSupplied,
        address indexed debtAsset,
        uint256 iterations
    );

    /// @notice Emitted when the minimum health factor is updated
    event MinHealthFactorUpdated(uint256 oldValue, uint256 newValue);

    /// @notice Emitted when the deloop iteration cap is updated
    event MaxDeloopIterationsUpdated(uint256 oldValue, uint256 newValue);

    /// @notice Emitted when the loop iteration cap is updated
    event MaxLoopIterationsUpdated(uint256 oldValue, uint256 newValue);

    /// @notice Emitted when ERC20 tokens are recovered from the contract
    event TokenRecovered(address indexed token, address indexed recipient, uint256 amount);

    /// @notice Emitted when ETH is recovered from the contract
    event ETHRecovered(address indexed recipient, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Deloop a leveraged rsETH position iteratively
     * @dev Flow: supply boost (if any) → [withdraw rsETH → instant withdraw → repay]* → withdraw boost.
     *      Approve aRsETH to cover all iterative collateral pulls plus the boost withdrawal.
     *      NOTE: If the final remaining debt requires less rsETH than the minimum instant withdrawal
     *      amount, the loop exits early and leaves residual debt.
     * @param debtAsset The debt asset to repay (WETH or wstETH)
     * @param debtAmount Amount of debt to repay (type(uint256).max = full debt)
     * @param maxRsETHAmount Maximum rsETH the user is willing to spend from collateral.
     * @param minHealthFactor Minimum health factor to maintain (18 decimals, e.g. 1.5e18 for HF=1.5).
     *                        Use 0 to default to the pre-call HF as the floor.
     * @dev User must approve this contract to spend their aRsETH tokens before calling
     */
    function deloop(address debtAsset, uint256 debtAmount, uint256 maxRsETHAmount, uint256 minHealthFactor) external;

    /**
     * @notice Increase a leveraged rsETH position by iteratively borrowing debt asset and resupplying rsETH.
     * @dev If the adapter holds boost liquidity, it is temporarily supplied to the caller's Aave position
     *      to increase per-iteration borrow capacity, then withdrawn at the end of the call.
     *
     *      APPROVALS REQUIRED before calling:
     *        1. Variable-debt token (variableDebtWETH or variableDebtWstETH) — approveDelegation()
     *           with at least `targetDebtIncrease` so the adapter can borrow on the caller's behalf.
     *        2. aRsETH — approve() covering at least the adapter's current managed boost amount
     *           (call getBoostLiquidity()) so the adapter can withdraw the boost collateral at the end.
     *
     * @param debtAsset Debt asset to borrow each iteration (WETH or wstETH)
     * @param targetDebtIncrease Target cumulative debt increase in debt-asset units
     * @param maxRsETHInput Maximum cumulative rsETH minted/supplied during the loop
     * @param minHealthFactor Minimum health factor to preserve after the loop (0 = use protocol floor)
     * @param minDebtPerIteration Minimum debt amount per iteration in debt-asset units. The loop exits
     *        gracefully (without reverting) only when the remaining debt falls below this threshold.
     *        All other stop conditions (no borrow capacity, budget exhausted) revert. Must be > 0
     *        and <= targetDebtIncrease.
     */
    function loop(
        address debtAsset,
        uint256 targetDebtIncrease,
        uint256 maxRsETHInput,
        uint256 minHealthFactor,
        uint256 minDebtPerIteration
    )
        external;

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get user's current AAVE position
     * @param user The user address
     * @return position The user's position details
     */
    function getUserPosition(address user) external view returns (UserPosition memory position);

    /**
     * @notice Returns the maximum amount of a collateral asset the user can withdraw while keeping
     *         health factor >= minHealthFactor.
     * @param user User address.
     * @param asset Collateral asset to withdraw (underlying address).
     * @param minHealthFactor Minimum health factor to maintain (18 decimals, e.g. 1.01e18 for 1.01).
     * @return Max withdrawable amount in asset units (0 if invalid asset, no balance, or already below target HF).
     */
    function getMaxWithdraw(address user, address asset, uint256 minHealthFactor) external view returns (uint256);

    /**
     * @notice Get the current manager-tracked rsETH boost liquidity
     * @return The tracked boost amount (excludes unsolicited rsETH transfers to the adapter)
     */
    function getBoostLiquidity() external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                            ADMIN FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Set the minimum health factor for collateral withdrawals
     * @dev Only callable by manager. Must be >= 1e18.
     * @param newMinHealthFactor New minimum health factor (18 decimals)
     */
    function setMinHealthFactor(uint256 newMinHealthFactor) external;

    /**
     * @notice Set the maximum number of iterations for deloop operations
     * @dev Only callable by manager. Must be in [1, 100].
     * @param newMax New maximum iteration count
     */
    function setMaxDeloopIterations(uint256 newMax) external;

    /**
     * @notice Set the maximum number of iterations for loop operations
     * @dev Only callable by manager. Must be in [1, 100].
     * @param newMax New maximum iteration count
     */
    function setMaxLoopIterations(uint256 newMax) external;

    /**
     * @notice Deposit rsETH liquidity to the contract for boosting deloop operations
     * @dev Only callable by manager. The rsETH reduces the number of iterations needed for deloop.
     * @param amount Amount of rsETH to deposit
     */
    function depositBoostLiquidity(uint256 amount) external;

    /**
     * @notice Withdraw rsETH boost liquidity from the contract
     * @dev Only callable by manager
     * @param amount Amount of rsETH to withdraw
     * @param recipient Address to receive the rsETH
     */
    function withdrawBoostLiquidity(uint256 amount, address recipient) external;

    /**
     * @notice Pause the adapter
     * @dev Only callable by admin/pauser role
     */
    function pause() external;

    /**
     * @notice Unpause the adapter
     * @dev Only callable by admin
     */
    function unpause() external;

    /**
     * @notice Recover ERC20 tokens accidentally sent to this contract
     * @dev Only callable by manager. For rsETH, only non-boost balance is recoverable
     *      (i.e. current rsETH balance minus tracked boostLiquidity).
     * @param token The token address to recover
     * @param recipient Address to receive the tokens
     * @param amount Amount of tokens to recover
     */
    function recoverToken(address token, address recipient, uint256 amount) external;

    /**
     * @notice Recover ETH accidentally sent to this contract
     * @dev Only callable by manager
     * @param recipient Address to receive the ETH
     * @param amount Amount of ETH (in wei) to recover
     */
    function recoverETH(address payable recipient, uint256 amount) external;
}

contracts/interfaces/ILRTConfig.sol

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

interface ILRTConfig {
    // Errors
    error ValueAlreadyInUse();
    error AssetAlreadySupported();
    error AssetNotSupported();
    error ETHNotSupported();
    error CallerNotLRTConfigAdmin();
    error CallerNotLRTConfigManager();
    error CallerNotLRTConfigOperator();
    error CallerNotLRTConfigAssetTransferRole();
    error CallerNotLRTConfigOperatorOrAssetTransferRole();
    error CallerNotLRTConfigAllowedRole(string role);
    error CannotUpdateStrategyAsItHasFundsNDCFunds(address ndc, uint256 amount);
    error InvalidMaxRewardAmount();
    error ProtocolFeeExceedsLimit();
    error CannotRemoveAssetWithDeposits(address asset);
    error TokenNotFoundError();
    error InvalidDepositLimit();

    // Events

    event SetToken(bytes32 key, address indexed tokenAddr);
    event SetContract(bytes32 key, address indexed contractAddr);
    event AddedNewSupportedAsset(address indexed asset, uint256 depositLimit);
    event RemovedSupportedAsset(address indexed asset);
    event AssetDepositLimitUpdate(address indexed asset, uint256 depositLimit);
    event AssetStrategyUpdate(address indexed asset, address indexed strategy);
    event SetRSETH(address indexed rsETH);
    event UpdateMaxRewardAmount(uint256 maxRewardAmount);
    event MaxNegligibleAmountUpdated(uint256 maxNegligibleAmount);
    event UpdateFee(uint256 newFee);
    event SetEigenLayerRewardReceiver(address indexed eigenLayerRewardReceiver);
    event PausedAll(address indexed sender);

    // methods

    function rsETH() external view returns (address);

    function assetStrategy(address asset) external view returns (address);

    function isSupportedAsset(address asset) external view returns (bool);

    function getLSTToken(bytes32 tokenId) external view returns (address);

    function getContract(bytes32 contractId) external view returns (address);

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

    function depositLimitByAsset(address asset) external view returns (uint256);

    function protocolFeeInBPS() external view returns (uint256);

    function eigenLayerRewardReceiver() external view returns (address);
}

contracts/interfaces/ILRTDepositPool.sol

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

interface ILRTDepositPool {
    //errors
    error InvalidAmountToDeposit();
    error NotEnoughAssetToTransfer();
    error MaximumDepositLimitReached();
    error MaximumNodeDelegatorLimitReached();
    error InvalidMaximumNodeDelegatorLimit();
    error MinimumAmountToReceiveNotMet();
    error NodeDelegatorNotFound();
    error NodeDelegatorHasAssetBalance(address assetAddress, uint256 assetBalance);
    error NodeDelegatorHasETH();
    error EthTransferFailed();
    error NotEnoughETHToTransfer();
    error ZeroAssetAmount();
    error MinAssetAmountNotMet();
    //events

    event MaxNodeDelegatorLimitUpdated(uint256 maxNodeDelegatorLimit);
    event NodeDelegatorAddedinQueue(address nodeDelegatorContracts);
    event NodeDelegatorRemovedFromQueue(address nodeDelegatorContracts);
    event AssetDeposit(
        address indexed depositor,
        address indexed asset,
        uint256 depositAmount,
        uint256 rsethMintAmount,
        string referralId
    );
    event ETHDeposit(address indexed depositor, uint256 depositAmount, uint256 rsethMintAmount, string referralId);
    event MinAmountToDepositUpdated(uint256 minAmountToDeposit);
    event MaxNegligibleAmountUpdated(uint256 maxNegligibleAmount);
    event ETHSwappedForLST(uint256 ethAmount, address indexed toAsset, uint256 returnAmount);
    event AssetSwappedForETH(address indexed fromAsset, uint256 fromAssetAmount, uint256 returnAmount);
    event EthTransferred(address to, uint256 amount);
    event AssetStaked(address indexed asset, uint256 ethAmount, uint256 stETHShares);

    // functions
    function depositETH(uint256 minRSETHAmountExpected, string calldata referralId) external payable;

    function depositAsset(
        address asset,
        uint256 depositAmount,
        uint256 minRSETHAmountExpected,
        string calldata referralId
    )
        external;

    function getSwapETHToAssetReturnAmount(
        address toAsset,
        uint256 ethAmountToSend
    )
        external
        view
        returns (uint256 returnAmount);

    function getTotalAssetDeposits(address asset) external view returns (uint256);

    function getAssetCurrentLimit(address asset) external view returns (uint256);

    function getRsETHAmountToMint(address asset, uint256 depositAmount) external view returns (uint256);

    function addNodeDelegatorContractToQueue(address[] calldata nodeDelegatorContract) external;

    function transferAssetToNodeDelegator(uint256 ndcIndex, address asset, uint256 amount) external;

    function updateMaxNodeDelegatorLimit(uint256 maxNodeDelegatorLimit) external;

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

    function getAssetDistributionData(address asset)
        external
        view
        returns (
            uint256 assetLyingInDepositPool,
            uint256 assetLyingInNDCs,
            uint256 assetStakedInEigenLayer,
            uint256 assetUnstakingFromEigenLayer,
            uint256 assetLyingInConverter,
            uint256 assetLyingUnstakingVault
        );

    function getETHDistributionData()
        external
        view
        returns (
            uint256 ethLyingInDepositPool,
            uint256 ethLyingInNDCs,
            uint256 ethStakedInEigenLayer,
            uint256 ethUnstakingFromEigenLayer,
            uint256 ethLyingInConverter,
            uint256 ethLyingInUnstakingVault
        );

    function isNodeDelegator(address nodeDelegatorContract) external view returns (uint256);

    // receivers
    function receiveFromRewardReceiver() external payable;
    function receiveFromLRTConverter() external payable;
    function receiveFromNodeDelegator() external payable;
}

contracts/interfaces/ILRTOracle.sol

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

interface ILRTOracle {
    // errors
    error AssetOracleNotSupported();
    error InvalidPriceOracle();
    error PriceAboveDailyThreshold();
    error ProtocolFeeExceededTVLIncrease();
    error DailyFeeMintLimitExceeded(uint256 currentAmount, uint256 maxAmount);
    error ContractPaused();
    error ContractNotPaused();
    error PeriodStartTimeShouldBeWithin24Hours();

    // events
    event AssetPriceOracleUpdate(address indexed asset, address indexed priceOracle);
    event RsETHPriceUpdate(uint256 newPrice, uint256 oldPrice);
    event PricePercentageLimitUpdate(uint256 newLimit);
    event FeeMinted(address treasury, uint256 rsethAmount);
    event RsETHPriceBelowPeak(uint256 highestRsethPrice, uint256 newPrice);
    event RsETHPriceDecrease(uint256 newPrice, uint256 oldPrice);
    event PeriodInTimestampUpdate(uint256 newPeriod);
    event MaxFeeMintAmountPerDayUpdated(uint256 newLimit);
    event Paused(address account);
    event Unpaused(address account);
    event FeePeriodStartTimeSet(uint256 feePeriodStartTime);

    // methods
    function getAssetPrice(address asset) external view returns (uint256);
    function assetPriceOracle(address asset) external view returns (address);
    function rsETHPrice() external view returns (uint256);
}

contracts/interfaces/ILRTWithdrawalManager.sol

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

interface ILRTWithdrawalManager {
    //errors
    error EthTransferFailed();
    error InvalidAmountToWithdraw();
    error ExceedAmountToWithdraw();
    error WithdrawalLocked();
    error WithdrawalDelayNotPassed();
    error ExceedWithdrawalDelay();
    error NoPendingWithdrawals();
    error AmountMustBeGreaterThanZero();
    error StrategyNotSupported();

    error RsETHPriceOutOfPriceRange(uint256 rsEthPrice);
    error AssetPriceOutOfPriceRange(uint256 assetPrice);
    error CantInstantWithdrawMoreThanAvailable();
    error NotEnoughRsETH();
    error InstantWithdrawalNotEnabled();
    error FeeTooHigh();
    error PendingWithdrawalsExist();
    error TreasuryTransferFailed();
    error NoWithdrawalRequests(address user, address asset);
    error AaveIntegrationNotEnabled();
    error InsufficientAaveBalance();
    error InvalidAaveConfiguration();
    error AaveHealthCheckFailed();
    error InsufficientLiquidityForWithdrawal();
    error UnauthorizedCaller();
    error AaveIntegrationAlreadyInDesiredState(bool enabled);

    struct UnlockParams {
        uint256 rsETHPrice;
        uint256 assetPrice;
        uint256 totalAvailableAssets;
    }

    struct WithdrawalRequest {
        uint256 rsETHUnstaked;
        uint256 expectedAssetAmount;
        uint256 withdrawalStartBlock;
    }

    //events
    event AssetWithdrawalQueued(
        address indexed withdrawer, address indexed asset, uint256 rsETHUnstaked, uint256 indexed userNonce
    );

    event AssetWithdrawalFinalized(
        address indexed withdrawer, address indexed asset, uint256 amountBurned, uint256 amountReceived
    );
    event EtherReceived(address indexed depositor, uint256 ethAmount, uint256 sharesAmount);

    event AssetUnlocked(
        address indexed asset, uint256 rsEthAmount, uint256 assetAmount, uint256 rsEThPrice, uint256 assetPrice
    );

    event MinAmountToWithdrawUpdated(address asset, uint256 minRsEthAmountToWithdraw);
    event WithdrawalDelayBlocksUpdated(uint256 withdrawalDelayBlocks);

    event ReferralIdEmitted(string referralId);
    event InstantWithdrawalEnabledUpdated(address indexed asset, bool enabled);
    event InstantWithdrawalFeeUpdated(uint256 feeBasisPoints);
    event InstantWithdrawalFeeRecipientUpdated(address indexed feeRecipient);
    event InstantWithdrawalFeeCollected(address indexed user, address indexed asset, uint256 fee);
    event TreasuryWithdrawalSettled(address indexed asset, uint256 amount);
    event RemainingAssetsSwept(address indexed asset, uint256 amount, address indexed treasury);
    event AssetWithdrawalCompletedBy(address indexed user);
    event AaveIntegrationConfigured(
        address indexed aavePool, address indexed aaveWETHGateway, address indexed aaveAWETH, address aaveDataProvider
    );
    event AaveIntegrationEnabled(bool enabled);
    event ETHDepositedToAave(uint256 amount, uint256 totalDeposited);
    event ETHWithdrawnFromAave(uint256 amount, uint256 totalDeposited);
    event InterestCollectedToTreasury(uint256 interestAmount, address indexed treasury);
    event EmergencyWithdrawFromAave(uint256 amount, address indexed recipient);
    event AaveDepositFailed(uint256 amount, bytes reason);

    // methods
    function getExpectedAssetAmount(address asset, uint256 amount) external view returns (uint256);

    function getAvailableAssetAmount(address asset) external view returns (uint256 assetAmount);

    function getUserWithdrawalRequest(
        address asset,
        address user,
        uint256 index
    )
        external
        view
        returns (uint256 rsETHAmount, uint256 expectedAssetAmount, uint256 withdrawalStartBlock, uint256 userNonce);

    function initiateWithdrawal(address asset, uint256 withdrawAmount, string calldata referralId) external;

    function instantWithdrawal(address asset, uint256 rsETHUnstaked, string calldata referralId) external;

    function completeWithdrawal(address asset, string calldata referralId) external;

    function completeWithdrawalForUser(address asset, address user, string calldata referralId) external;

    function unlockQueue(
        address asset,
        uint256 index,
        uint256 minimumAssetPrice,
        uint256 minimumRsEthPrice,
        uint256 maximumAssetPrice,
        uint256 maximumRsEthPrice
    )
        external
        returns (uint256 rsETHBurned, uint256 assetAmountUnlocked);

    // receive functions
    function receiveFromLRTUnstakingVault() external payable;

    function setInstantWithdrawalEnabled(address asset, bool enabled) external;

    function setInstantWithdrawalFee(uint256 feeBasisPoints) external;

    function setInstantWithdrawalFeeRecipient(address feeRecipient) external;

    function instantWithdrawalFee() external view returns (uint256);

    function isInstantWithdrawalEnabled(address asset) external view returns (bool);

    function minRsEthAmountToWithdraw(address asset) external view returns (uint256);

    function assetsCommitted(address asset) external view returns (uint256);

    // Treasury withdrawal flow functions
    function hasUnlockedWithdrawals(address asset) external view returns (bool);

    function sweepRemainingAssets(address asset) external returns (uint256 transferredAmount);

    // Aave integration functions
    function configureAaveIntegration(
        address aavePool_,
        address aaveWETHGateway_,
        address aaveAWETH_,
        address aaveDataProvider_
    )
        external;

    function setAaveIntegrationEnabled(bool enabled) external;

    function depositIdleETHToAave(uint256 amount) external;

    function collectInterestToTreasury() external returns (uint256 interestAmount);

    function emergencyWithdrawFromAave(uint256 amount) external;

    function getAaveBalance() external view returns (uint256);

    function getAccruedInterest() external view returns (uint256);

    function aaveHealthCheck() external view returns (bool);
}

contracts/utils/LRTConfigRoleChecker.sol

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

import { LRTConstants } from "./LRTConstants.sol";

import { ILRTConfig } from "../interfaces/ILRTConfig.sol";

import { IAccessControl } from "@openzeppelin/contracts/access/IAccessControl.sol";

/// @title LRTConfigRoleChecker - LRT Config Role Checker Contract
/// @notice Handles LRT config role checks
abstract contract LRTConfigRoleChecker {
    ILRTConfig public lrtConfig;

    // events
    event UpdatedLRTConfig(address indexed lrtConfig);

    // modifiers
    modifier onlyRole(bytes32 role) {
        if (!IAccessControl(address(lrtConfig)).hasRole(role, msg.sender)) {
            string memory roleStr = string(abi.encodePacked(role));
            revert ILRTConfig.CallerNotLRTConfigAllowedRole(roleStr);
        }
        _;
    }

    modifier onlyLRTManager() {
        if (!IAccessControl(address(lrtConfig)).hasRole(LRTConstants.MANAGER, msg.sender)) {
            revert ILRTConfig.CallerNotLRTConfigManager();
        }
        _;
    }

    modifier onlyLRTOperator() {
        if (!IAccessControl(address(lrtConfig)).hasRole(LRTConstants.OPERATOR_ROLE, msg.sender)) {
            revert ILRTConfig.CallerNotLRTConfigOperator();
        }
        _;
    }

    modifier onlyAssetTransferRole() {
        if (!IAccessControl(address(lrtConfig)).hasRole(LRTConstants.ASSET_TRANSFER_ROLE, msg.sender)) {
            revert ILRTConfig.CallerNotLRTConfigAssetTransferRole();
        }
        _;
    }

    modifier onlyAssetTransferOrOperatorRole() {
        if (
            !IAccessControl(address(lrtConfig)).hasRole(LRTConstants.ASSET_TRANSFER_ROLE, msg.sender)
                && !IAccessControl(address(lrtConfig)).hasRole(LRTConstants.OPERATOR_ROLE, msg.sender)
        ) {
            revert ILRTConfig.CallerNotLRTConfigOperatorOrAssetTransferRole();
        }
        _;
    }

    modifier onlyLRTAdmin() {
        if (!IAccessControl(address(lrtConfig)).hasRole(LRTConstants.DEFAULT_ADMIN_ROLE, msg.sender)) {
            revert ILRTConfig.CallerNotLRTConfigAdmin();
        }
        _;
    }

    modifier onlySupportedAsset(address asset) {
        if (!lrtConfig.isSupportedAsset(asset)) {
            revert ILRTConfig.AssetNotSupported();
        }
        _;
    }

    modifier onlySupportedERC20Token(address asset) {
        if (!lrtConfig.isSupportedAsset(asset)) {
            revert ILRTConfig.AssetNotSupported();
        }
        if (asset == LRTConstants.ETH_TOKEN) {
            revert ILRTConfig.ETHNotSupported();
        }
        _;
    }
}

contracts/utils/LRTConstants.sol

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

import { ILRTConfig } from "../interfaces/ILRTConfig.sol";

library LRTConstants {
    //tokens
    bytes32 public constant ST_ETH_TOKEN = keccak256("ST_ETH_TOKEN");
    bytes32 public constant ETHX_TOKEN = keccak256("ETHX_TOKEN");
    bytes32 public constant SFRX_ETH_TOKEN = keccak256("SFRX_ETH_TOKEN");
    // native ETH as ERC20 for ease of implementation
    address public constant ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    //contracts
    bytes32 public constant LRT_ORACLE = keccak256("LRT_ORACLE");
    bytes32 public constant LRT_DEPOSIT_POOL = keccak256("LRT_DEPOSIT_POOL");
    bytes32 public constant LRT_WITHDRAW_MANAGER = keccak256("LRT_WITHDRAW_MANAGER");
    bytes32 public constant LRT_UNSTAKING_VAULT = keccak256("LRT_UNSTAKING_VAULT");
    bytes32 public constant LRT_CONVERTER = keccak256("LRT_CONVERTER");
    bytes32 public constant REWARD_RECEIVER = keccak256("REWARD_RECEIVER");
    bytes32 public constant PROTOCOL_TREASURY = keccak256("PROTOCOL_TREASURY");
    bytes32 public constant PUBKEY_REGISTRY = keccak256("PUBKEY_REGISTRY");
    bytes32 public constant UNLOCKED_WITHDRAWAL_INITIALIZER = keccak256("UNLOCKED_WITHDRAWAL_INITIALIZER");

    bytes32 public constant BEACON_CHAIN_ETH_STRATEGY = keccak256("BEACON_CHAIN_ETH_STRATEGY");
    bytes32 public constant EIGEN_STRATEGY_MANAGER = keccak256("EIGEN_STRATEGY_MANAGER");
    bytes32 public constant EIGEN_POD_MANAGER = keccak256("EIGEN_POD_MANAGER");
    bytes32 public constant EIGEN_DELEGATION_MANAGER = keccak256("EIGEN_DELEGATION_MANAGER");
    bytes32 public constant EIGEN_REWARDS_COORDINATOR = keccak256("EIGEN_REWARDS_COORDINATOR");

    //Roles
    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
    bytes32 public constant MANAGER = keccak256("MANAGER");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
    bytes32 public constant ASSET_TRANSFER_ROLE = keccak256("ASSET_TRANSFER_ROLE");
    bytes32 public constant TIME_LOCK_ROLE = keccak256("TIME_LOCK_ROLE");

    // constants
    uint256 public constant ONE_E_9 = 1e9;

    // Contract getters
    function unstakingVault(ILRTConfig config) internal view returns (address) {
        return config.getContract(LRT_UNSTAKING_VAULT);
    }

    function delegationManager(ILRTConfig config) internal view returns (address) {
        return config.getContract(EIGEN_DELEGATION_MANAGER);
    }

    function rewardsCoordinator(ILRTConfig config) internal view returns (address) {
        return config.getContract(EIGEN_REWARDS_COORDINATOR);
    }

    function strategyManager(ILRTConfig config) internal view returns (address) {
        return config.getContract(EIGEN_STRATEGY_MANAGER);
    }

    function lrtConverter(ILRTConfig config) internal view returns (address) {
        return config.getContract(LRT_CONVERTER);
    }

    function depositPool(ILRTConfig config) internal view returns (address) {
        return config.getContract(LRT_DEPOSIT_POOL);
    }

    function lrtOracle(ILRTConfig config) internal view returns (address) {
        return config.getContract(LRT_ORACLE);
    }

    function rewardReceiver(ILRTConfig config) internal view returns (address) {
        return config.getContract(REWARD_RECEIVER);
    }

    function protocolTreasury(ILRTConfig config) internal view returns (address) {
        return config.getContract(PROTOCOL_TREASURY);
    }

    function pubkeyRegistry(ILRTConfig config) internal view returns (address) {
        return config.getContract(PUBKEY_REGISTRY);
    }

    function beaconChainETHStrategy(ILRTConfig config) internal view returns (address) {
        return config.getContract(BEACON_CHAIN_ETH_STRATEGY);
    }

    function eigenPodManager(ILRTConfig config) internal view returns (address) {
        return config.getContract(EIGEN_POD_MANAGER);
    }

    function withdrawManager(ILRTConfig config) internal view returns (address) {
        return config.getContract(LRT_WITHDRAW_MANAGER);
    }
}

contracts/utils/UtilLib.sol

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

/// @title UtilLib - Utility library
/// @notice Utility functions
library UtilLib {
    error ZeroAddressNotAllowed();

    /// @dev zero address check modifier
    /// @param address_ address to check
    function checkNonZeroAddress(address address_) internal pure {
        if (address_ == address(0)) revert ZeroAddressNotAllowed();
    }

    function getMin(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a < b) return a;
        return b;
    }

    function getMax(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a > b) return a;
        return b;
    }
}

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

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

pragma solidity ^0.8.2;

import "../../utils/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]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

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

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!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 Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

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

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 {Initializable} from "../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;
}

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

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

pragma solidity ^0.8.0;
import {Initializable} from "../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 Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _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;
}

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

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library 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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;
import {Initializable} from "../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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }

    /**
     * @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;
}

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.0;

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 4000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=lib/forge-std/src/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@eigenlayer/contracts/=lib/eigenlayer-contracts/src/contracts/",
    "@openzeppelin-upgrades/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/",
    "eigenlayer-contracts/=lib/eigenlayer-contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "hardhat/=node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-v4.9.0/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "solidity-code-metrics/=node_modules/solidity-code-metrics/",
    "zeus-templates/=lib/eigenlayer-contracts/lib/zeus-templates/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.