creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/contracts/protocol/lendingpool/LendingPool.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {Address} from '../../dependencies/openzeppelin/contracts/Address.sol';\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {IAToken} from '../../interfaces/IAToken.sol';\nimport {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';\nimport {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol';\nimport {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';\nimport {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';\nimport {ILendingPool} from '../../interfaces/ILendingPool.sol';\nimport {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';\nimport {Helpers} from '../libraries/helpers/Helpers.sol';\nimport {Errors} from '../libraries/helpers/Errors.sol';\nimport {WadRayMath} from '../libraries/math/WadRayMath.sol';\nimport {PercentageMath} from '../libraries/math/PercentageMath.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {GenericLogic} from '../libraries/logic/GenericLogic.sol';\nimport {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\nimport {LendingPoolStorage} from './LendingPoolStorage.sol';\n\n/**\n * @title LendingPool contract\n * @dev Main point of interaction with an Aave protocol's market\n * - Users can:\n *   # Deposit\n *   # Withdraw\n *   # Borrow\n *   # Repay\n *   # Swap their loans between variable and stable rate\n *   # Enable/disable their deposits as collateral rebalance stable rate borrow positions\n *   # Liquidate positions\n *   # Execute Flash Loans\n * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market\n * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the\n *   LendingPoolAddressesProvider\n * @author Aave\n **/\ncontract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage {\n  using SafeMath for uint256;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeERC20 for IERC20;\n\n  //main configuration parameters\n  uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 2500;\n  uint256 public constant FLASHLOAN_PREMIUM_TOTAL = 9;\n  uint256 public constant MAX_NUMBER_RESERVES = 128;\n  uint256 public constant LENDINGPOOL_REVISION = 0x5;\n\n  modifier whenNotPaused() {\n    _whenNotPaused();\n    _;\n  }\n\n  modifier onlyLendingPoolConfigurator() {\n    _onlyLendingPoolConfigurator();\n    _;\n  }\n\n  modifier onlyPoolAdmin() {\n    _onlyLendingPoolAdmin();\n    _;\n  }\n\n  function _whenNotPaused() internal view {\n    require(!_paused, Errors.LP_IS_PAUSED);\n  }\n\n  function _onlyLendingPoolConfigurator() internal view {\n    require(\n      _addressesProvider.getLendingPoolConfigurator() == msg.sender,\n      Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR\n    );\n  }\n\n  function _onlyLendingPoolAdmin() internal view {\n    require(\n      _addressesProvider.getPoolAdmin() == msg.sender,\n      Errors.CALLER_NOT_POOL_ADMIN\n    );\n  }\n\n  function getRevision() internal pure override returns (uint256) {\n    return LENDINGPOOL_REVISION;\n  }\n\n  /**\n   * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the\n   * LendingPoolAddressesProvider of the market.\n   * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption\n   *   on subsequent operations\n   * @param provider The address of the LendingPoolAddressesProvider\n   **/\n  function initialize(ILendingPoolAddressesProvider provider) public initializer {\n    _addressesProvider = provider;\n  }\n\n  /**\n   * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to deposit\n   * @param amount The amount to be deposited\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   **/\n  function deposit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external override whenNotPaused {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    ValidationLogic.validateDeposit(reserve, amount);\n\n    address aToken = reserve.aTokenAddress;\n\n    reserve.updateState();\n    reserve.updateInterestRates(asset, aToken, amount, 0);\n\n    IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);\n\n    bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);\n\n    if (isFirstDeposit) {\n      _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);\n      emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);\n    }\n\n    emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);\n  }\n\n  /**\n   * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance\n   * @param to Address that will receive the underlying, same as msg.sender if the user\n   *   wants to receive it on his own wallet, or a different address if the beneficiary is a\n   *   different wallet\n   * @return The final amount withdrawn\n   **/\n  function withdraw(\n    address asset,\n    uint256 amount,\n    address to\n  ) external override whenNotPaused  returns (uint256) {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    address aToken = reserve.aTokenAddress;\n\n    uint256 userBalance = IAToken(aToken).balanceOf(msg.sender);\n\n    uint256 amountToWithdraw = amount;\n\n    if (amount == type(uint256).max) {\n      amountToWithdraw = userBalance;\n    }\n\n    ValidationLogic.validateWithdraw(\n      asset,\n      amountToWithdraw,\n      userBalance,\n      _reserves,\n      _usersConfig[msg.sender],\n      _reservesList,\n      _reservesCount,\n      _addressesProvider.getPriceOracle()\n    );\n\n    reserve.updateState();\n\n    reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw);\n\n    if (amountToWithdraw == userBalance) {\n      _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false);\n      emit ReserveUsedAsCollateralDisabled(asset, msg.sender);\n    }\n\n    IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex);\n\n    emit Withdraw(asset, msg.sender, to, amountToWithdraw);\n\n    return amountToWithdraw;\n  }\n\n  /**\n   * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n   * already deposited enough collateral, or he was given enough allowance by a credit delegator on the\n   * corresponding debt token (StableDebtToken or VariableDebtToken)\n   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself\n   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n   * if he has been given credit delegation allowance\n   **/\n  function borrow(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode,\n    address onBehalfOf\n  ) external override whenNotPaused {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    _executeBorrow(\n      ExecuteBorrowParams(\n        asset,\n        msg.sender,\n        onBehalfOf,\n        amount,\n        interestRateMode,\n        reserve.aTokenAddress,\n        referralCode,\n        true\n      )\n    );\n  }\n\n  /**\n   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n   * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n   * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n   * other borrower whose debt should be removed\n   * @return The final amount repaid\n   **/\n  function repay(\n    address asset,\n    uint256 amount,\n    uint256 rateMode,\n    address onBehalfOf\n  ) external override whenNotPaused returns (uint256) {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);\n\n    DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);\n\n    ValidationLogic.validateRepay(\n      reserve,\n      amount,\n      interestRateMode,\n      onBehalfOf,\n      stableDebt,\n      variableDebt\n    );\n\n    uint256 paybackAmount =\n      interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;\n\n    if (amount < paybackAmount) {\n      paybackAmount = amount;\n    }\n\n    reserve.updateState();\n\n    if (interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);\n    } else {\n      IVariableDebtToken(reserve.variableDebtTokenAddress).burn(\n        onBehalfOf,\n        paybackAmount,\n        reserve.variableBorrowIndex\n      );\n    }\n\n    address aToken = reserve.aTokenAddress;\n    reserve.updateInterestRates(asset, aToken, paybackAmount, 0);\n\n    if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) {\n      _usersConfig[onBehalfOf].setBorrowing(reserve.id, false);\n    }\n\n    IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount);\n\n    emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);\n\n    return paybackAmount;\n  }\n\n  /**\n   * @notice Allows a borrower to swap his debt between stable and variable mode,\n   * @dev introduce in a flavor stable rate deprecation\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be swapped\n   */\n  function swapToVariable(address asset, address user) external override whenNotPaused {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    (uint256 stableDebt,) = Helpers.getUserCurrentDebt(user, reserve);\n\n    ValidationLogic.validateSwapRateMode(\n      reserve,\n      _usersConfig[user],\n      stableDebt,\n      DataTypes.InterestRateMode.STABLE\n    );\n\n    reserve.updateState();\n\n    IStableDebtToken(reserve.stableDebtTokenAddress).burn(user, stableDebt);\n    IVariableDebtToken(reserve.variableDebtTokenAddress).mint(\n      user,\n      user,\n      stableDebt,\n      reserve.variableBorrowIndex\n    );\n\n    reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0);\n\n    emit Swap(asset, user, 1);\n  }\n\n  /**\n   * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa\n   * @param asset The address of the underlying asset borrowed\n   * @param rateMode The rate mode that the user wants to swap to\n   **/\n  function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    (uint256 stableDebt, ) = Helpers.getUserCurrentDebt(msg.sender, reserve);\n\n    DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);\n\n    ValidationLogic.validateSwapRateMode(\n      reserve,\n      _usersConfig[msg.sender],\n      stableDebt,\n      interestRateMode\n    );\n\n    reserve.updateState();\n\n    IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt);\n    IVariableDebtToken(reserve.variableDebtTokenAddress).mint(\n      msg.sender,\n      msg.sender,\n      stableDebt,\n      reserve.variableBorrowIndex\n    );\n\n    reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0);\n\n    emit Swap(asset, msg.sender, rateMode);\n  }\n\n  /**\n   * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n   * - Users can be rebalanced if the following conditions are satisfied:\n   *     1. Usage ratio is above 95%\n   *     2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been\n   *        borrowed at a stable rate and depositors are not earning enough\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be rebalanced\n   **/\n  function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress);\n    IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress);\n    address aTokenAddress = reserve.aTokenAddress;\n\n    uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user);\n\n    ValidationLogic.validateRebalanceStableBorrowRate(\n      reserve,\n      asset,\n      stableDebtToken,\n      variableDebtToken,\n      aTokenAddress\n    );\n\n    reserve.updateState();\n\n    IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt);\n    IStableDebtToken(address(stableDebtToken)).mint(\n      user,\n      user,\n      stableDebt,\n      reserve.currentStableBorrowRate\n    );\n\n    reserve.updateInterestRates(asset, aTokenAddress, 0, 0);\n\n    emit RebalanceStableBorrowRate(asset, user);\n  }\n\n  /**\n   * @dev Allows depositors to enable/disable a specific deposited asset as collateral\n   * @param asset The address of the underlying asset deposited\n   * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise\n   **/\n  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n    external\n    override\n    whenNotPaused\n  {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n\n    ValidationLogic.validateSetUseReserveAsCollateral(\n      reserve,\n      asset,\n      useAsCollateral,\n      _reserves,\n      _usersConfig[msg.sender],\n      _reservesList,\n      _reservesCount,\n      _addressesProvider.getPriceOracle()\n    );\n\n    _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral);\n\n    if (useAsCollateral) {\n      emit ReserveUsedAsCollateralEnabled(asset, msg.sender);\n    } else {\n      emit ReserveUsedAsCollateralDisabled(asset, msg.sender);\n    }\n  }\n\n  /**\n   * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   **/\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) external override whenNotPaused {\n    address collateralManager = _addressesProvider.getLendingPoolCollateralManager();\n\n    //solium-disable-next-line\n    (bool success, bytes memory result) =\n      collateralManager.delegatecall(\n        abi.encodeWithSignature(\n          'liquidationCall(address,address,address,uint256,bool)',\n          collateralAsset,\n          debtAsset,\n          user,\n          debtToCover,\n          receiveAToken\n        )\n      );\n    require(success, Errors.LP_LIQUIDATION_CALL_FAILED);\n\n    (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));\n\n    require(returnCode == 0, string(abi.encodePacked(returnMessage)));\n  }\n\n  struct FlashLoanLocalVars {\n    IFlashLoanReceiver receiver;\n    address oracle;\n    uint256 i;\n    address currentAsset;\n    address currentATokenAddress;\n    uint256 currentAmount;\n    uint256 currentPremium;\n    uint256 currentAmountPlusPremium;\n    address debtToken;\n  }\n\n  /**\n   * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\n   * For further details please visit https://developers.aave.com\n   * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface\n   * @param assets The addresses of the assets being flash-borrowed\n   * @param amounts The amounts amounts being flash-borrowed\n   * @param modes Types of the debt to open if the flash loan is not returned:\n   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   **/\n  function flashLoan(\n    address receiverAddress,\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata modes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) external override whenNotPaused {\n    FlashLoanLocalVars memory vars;\n\n    ValidationLogic.validateFlashloan(assets, amounts);\n\n    address[] memory aTokenAddresses = new address[](assets.length);\n    uint256[] memory premiums = new uint256[](assets.length);\n\n    vars.receiver = IFlashLoanReceiver(receiverAddress);\n\n    for (vars.i = 0; vars.i < assets.length; vars.i++) {\n      aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress;\n\n      premiums[vars.i] = amounts[vars.i].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000);\n\n      IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]);\n    }\n\n    require(\n      vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params),\n      Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN\n    );\n\n    for (vars.i = 0; vars.i < assets.length; vars.i++) {\n      vars.currentAsset = assets[vars.i];\n      vars.currentAmount = amounts[vars.i];\n      vars.currentPremium = premiums[vars.i];\n      vars.currentATokenAddress = aTokenAddresses[vars.i];\n      vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium);\n\n      if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) {\n        _reserves[vars.currentAsset].updateState();\n        _reserves[vars.currentAsset].cumulateToLiquidityIndex(\n          IERC20(vars.currentATokenAddress).totalSupply(),\n          vars.currentPremium\n        );\n        _reserves[vars.currentAsset].updateInterestRates(\n          vars.currentAsset,\n          vars.currentATokenAddress,\n          vars.currentAmountPlusPremium,\n          0\n        );\n\n        IERC20(vars.currentAsset).safeTransferFrom(\n          receiverAddress,\n          vars.currentATokenAddress,\n          vars.currentAmountPlusPremium\n        );\n      } else {\n        // If the user chose to not return the funds, the system checks if there is enough collateral and\n        // eventually opens a debt position\n        _executeBorrow(\n          ExecuteBorrowParams(\n            vars.currentAsset,\n            msg.sender,\n            onBehalfOf,\n            vars.currentAmount,\n            modes[vars.i],\n            vars.currentATokenAddress,\n            referralCode,\n            false\n          )\n        );\n      }\n      emit FlashLoan(\n        receiverAddress,\n        msg.sender,\n        vars.currentAsset,\n        vars.currentAmount,\n        vars.currentPremium,\n        referralCode\n      );\n    }\n  }\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   **/\n  function rescueTokens(address token, address to, uint256 amount) external override onlyPoolAdmin {\n    IERC20(token).safeTransfer(to, amount);\n    emit TokensRescued(token, to, amount);\n  }\n\n  /**\n   * @dev Returns the state and configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The state of the reserve\n   **/\n  function getReserveData(address asset)\n    external\n    view\n    override\n    returns (DataTypes.ReserveData memory)\n  {\n    return _reserves[asset];\n  }\n\n  /**\n   * @dev Returns the user account data across all the reserves\n   * @param user The address of the user\n   * @return totalCollateralETH the total collateral in ETH of the user\n   * @return totalDebtETH the total debt in ETH of the user\n   * @return availableBorrowsETH the borrowing power left of the user\n   * @return currentLiquidationThreshold the liquidation threshold of the user\n   * @return ltv the loan to value of the user\n   * @return healthFactor the current health factor of the user\n   **/\n  function getUserAccountData(address user)\n    external\n    view\n    override\n    returns (\n      uint256 totalCollateralETH,\n      uint256 totalDebtETH,\n      uint256 availableBorrowsETH,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    )\n  {\n    (\n      totalCollateralETH,\n      totalDebtETH,\n      ltv,\n      currentLiquidationThreshold,\n      healthFactor\n    ) = GenericLogic.calculateUserAccountData(\n      user,\n      _reserves,\n      _usersConfig[user],\n      _reservesList,\n      _reservesCount,\n      _addressesProvider.getPriceOracle()\n    );\n\n    availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(\n      totalCollateralETH,\n      totalDebtETH,\n      ltv\n    );\n  }\n\n  /**\n   * @dev Returns the configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The configuration of the reserve\n   **/\n  function getConfiguration(address asset)\n    external\n    view\n    override\n    returns (DataTypes.ReserveConfigurationMap memory)\n  {\n    return _reserves[asset].configuration;\n  }\n\n  /**\n   * @dev Returns the configuration of the user across all the reserves\n   * @param user The user address\n   * @return The configuration of the user\n   **/\n  function getUserConfiguration(address user)\n    external\n    view\n    override\n    returns (DataTypes.UserConfigurationMap memory)\n  {\n    return _usersConfig[user];\n  }\n\n  /**\n   * @dev Returns the normalized income per unit of asset\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve's normalized income\n   */\n  function getReserveNormalizedIncome(address asset)\n    external\n    view\n    virtual\n    override\n    returns (uint256)\n  {\n    return _reserves[asset].getNormalizedIncome();\n  }\n\n  /**\n   * @dev Returns the normalized variable debt per unit of asset\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve normalized variable debt\n   */\n  function getReserveNormalizedVariableDebt(address asset)\n    external\n    view\n    override\n    returns (uint256)\n  {\n    return _reserves[asset].getNormalizedDebt();\n  }\n\n  /**\n   * @dev Returns if the LendingPool is paused\n   */\n  function paused() external view override returns (bool) {\n    return _paused;\n  }\n\n  /**\n   * @dev Returns the list of the initialized reserves\n   **/\n  function getReservesList() external view override returns (address[] memory) {\n    address[] memory _activeReserves = new address[](_reservesCount);\n\n    for (uint256 i = 0; i < _reservesCount; i++) {\n      _activeReserves[i] = _reservesList[i];\n    }\n    return _activeReserves;\n  }\n\n  /**\n   * @dev Returns the cached LendingPoolAddressesProvider connected to this contract\n   **/\n  function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) {\n    return _addressesProvider;\n  }\n\n  /**\n   * @dev Validates and finalizes an aToken transfer\n   * - Only callable by the overlying aToken of the `asset`\n   * @param asset The address of the underlying asset of the aToken\n   * @param from The user from which the aTokens are transferred\n   * @param to The user receiving the aTokens\n   * @param amount The amount being transferred/withdrawn\n   * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n   * @param balanceToBefore The aToken balance of the `to` user before the transfer\n   */\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 amount,\n    uint256 balanceFromBefore,\n    uint256 balanceToBefore\n  ) external override whenNotPaused {\n    require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN);\n\n    ValidationLogic.validateTransfer(\n      from,\n      _reserves,\n      _usersConfig[from],\n      _reservesList,\n      _reservesCount,\n      _addressesProvider.getPriceOracle()\n    );\n\n    uint256 reserveId = _reserves[asset].id;\n\n    if (from != to) {\n      if (balanceFromBefore.sub(amount) == 0) {\n        DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];\n        fromConfig.setUsingAsCollateral(reserveId, false);\n        emit ReserveUsedAsCollateralDisabled(asset, from);\n      }\n\n      if (balanceToBefore == 0 && amount != 0) {\n        DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];\n        toConfig.setUsingAsCollateral(reserveId, true);\n        emit ReserveUsedAsCollateralEnabled(asset, to);\n      }\n    }\n  }\n\n  /**\n   * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n   * interest rate strategy\n   * - Only callable by the LendingPoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n   * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n   * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   **/\n  function initReserve(\n    address asset,\n    address aTokenAddress,\n    address stableDebtAddress,\n    address variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external override onlyLendingPoolConfigurator {\n    require(Address.isContract(asset), Errors.LP_NOT_CONTRACT);\n    _reserves[asset].init(\n      aTokenAddress,\n      stableDebtAddress,\n      variableDebtAddress,\n      interestRateStrategyAddress\n    );\n    _addReserveToList(asset);\n  }\n\n  /**\n   * @dev Updates the address of the interest rate strategy contract\n   * - Only callable by the LendingPoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param rateStrategyAddress The address of the interest rate strategy contract\n   **/\n  function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)\n    external\n    override\n    onlyLendingPoolConfigurator\n  {\n    _reserves[asset].interestRateStrategyAddress = rateStrategyAddress;\n  }\n\n  /**\n   * @dev Sets the configuration bitmap of the reserve as a whole\n   * - Only callable by the LendingPoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param configuration The new configuration bitmap\n   **/\n  function setConfiguration(address asset, uint256 configuration)\n    external\n    override\n    onlyLendingPoolConfigurator\n  {\n    _reserves[asset].configuration.data = configuration;\n  }\n\n  /**\n   * @dev Set the _pause state of a reserve\n   * - Only callable by the LendingPoolConfigurator contract\n   * @param val `true` to pause the reserve, `false` to un-pause it\n   */\n  function setPause(bool val) external override onlyLendingPoolConfigurator {\n    _paused = val;\n    if (_paused) {\n      emit Paused();\n    } else {\n      emit Unpaused();\n    }\n  }\n\n  struct ExecuteBorrowParams {\n    address asset;\n    address user;\n    address onBehalfOf;\n    uint256 amount;\n    uint256 interestRateMode;\n    address aTokenAddress;\n    uint16 referralCode;\n    bool releaseUnderlying;\n  }\n\n  function _executeBorrow(ExecuteBorrowParams memory vars) internal {\n    DataTypes.ReserveData storage reserve = _reserves[vars.asset];\n    DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf];\n\n    address oracle = _addressesProvider.getPriceOracle();\n\n    uint256 amountInETH =\n      IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div(\n        10**reserve.configuration.getDecimals()\n      );\n\n    ValidationLogic.validateBorrow(\n      vars.asset,\n      reserve,\n      vars.onBehalfOf,\n      vars.amount,\n      amountInETH,\n      vars.interestRateMode,\n      MAX_STABLE_RATE_BORROW_SIZE_PERCENT,\n      _reserves,\n      userConfig,\n      _reservesList,\n      _reservesCount,\n      oracle\n    );\n\n    reserve.updateState();\n\n    uint256 currentStableRate = 0;\n\n    bool isFirstBorrowing = false;\n    if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) {\n      currentStableRate = reserve.currentStableBorrowRate;\n\n      isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint(\n        vars.user,\n        vars.onBehalfOf,\n        vars.amount,\n        currentStableRate\n      );\n    } else {\n      isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint(\n        vars.user,\n        vars.onBehalfOf,\n        vars.amount,\n        reserve.variableBorrowIndex\n      );\n    }\n\n    if (isFirstBorrowing) {\n      userConfig.setBorrowing(reserve.id, true);\n    }\n\n    reserve.updateInterestRates(\n      vars.asset,\n      vars.aTokenAddress,\n      0,\n      vars.releaseUnderlying ? vars.amount : 0\n    );\n\n    if (vars.releaseUnderlying) {\n      IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount);\n    }\n\n    emit Borrow(\n      vars.asset,\n      vars.user,\n      vars.onBehalfOf,\n      vars.amount,\n      vars.interestRateMode,\n      DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE\n        ? currentStableRate\n        : reserve.currentVariableBorrowRate,\n      vars.referralCode\n    );\n  }\n\n  function _addReserveToList(address asset) internal {\n    uint256 reservesCount = _reservesCount;\n\n    require(reservesCount < MAX_NUMBER_RESERVES, Errors.LP_NO_MORE_RESERVES_ALLOWED);\n\n    bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset;\n\n    if (!reserveAlreadyAdded) {\n      _reserves[asset].id = uint8(reservesCount);\n      _reservesList[reservesCount] = asset;\n\n      _reservesCount = reservesCount + 1;\n    }\n  }\n}\n"
      },
      "src/contracts/dependencies/openzeppelin/contracts/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n  /**\n   * @dev Returns the addition of two unsigned integers, reverting on\n   * overflow.\n   *\n   * Counterpart to Solidity's `+` operator.\n   *\n   * Requirements:\n   * - Addition cannot overflow.\n   */\n  function add(uint256 a, uint256 b) internal pure returns (uint256) {\n    uint256 c = a + b;\n    require(c >= a, 'SafeMath: addition overflow');\n\n    return c;\n  }\n\n  /**\n   * @dev Returns the subtraction of two unsigned integers, reverting on\n   * overflow (when the result is negative).\n   *\n   * Counterpart to Solidity's `-` operator.\n   *\n   * Requirements:\n   * - Subtraction cannot overflow.\n   */\n  function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n    return sub(a, b, 'SafeMath: subtraction overflow');\n  }\n\n  /**\n   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n   * overflow (when the result is negative).\n   *\n   * Counterpart to Solidity's `-` operator.\n   *\n   * Requirements:\n   * - Subtraction cannot overflow.\n   */\n  function sub(\n    uint256 a,\n    uint256 b,\n    string memory errorMessage\n  ) internal pure returns (uint256) {\n    require(b <= a, errorMessage);\n    uint256 c = a - b;\n\n    return c;\n  }\n\n  /**\n   * @dev Returns the multiplication of two unsigned integers, reverting on\n   * overflow.\n   *\n   * Counterpart to Solidity's `*` operator.\n   *\n   * Requirements:\n   * - Multiplication cannot overflow.\n   */\n  function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n    // benefit is lost if 'b' is also tested.\n    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n    if (a == 0) {\n      return 0;\n    }\n\n    uint256 c = a * b;\n    require(c / a == b, 'SafeMath: multiplication overflow');\n\n    return c;\n  }\n\n  /**\n   * @dev Returns the integer division of two unsigned integers. Reverts on\n   * division by zero. The result is rounded towards zero.\n   *\n   * Counterpart to Solidity's `/` operator. Note: this function uses a\n   * `revert` opcode (which leaves remaining gas untouched) while Solidity\n   * uses an invalid opcode to revert (consuming all remaining gas).\n   *\n   * Requirements:\n   * - The divisor cannot be zero.\n   */\n  function div(uint256 a, uint256 b) internal pure returns (uint256) {\n    return div(a, b, 'SafeMath: division by zero');\n  }\n\n  /**\n   * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n   * division by zero. The result is rounded towards zero.\n   *\n   * Counterpart to Solidity's `/` operator. Note: this function uses a\n   * `revert` opcode (which leaves remaining gas untouched) while Solidity\n   * uses an invalid opcode to revert (consuming all remaining gas).\n   *\n   * Requirements:\n   * - The divisor cannot be zero.\n   */\n  function div(\n    uint256 a,\n    uint256 b,\n    string memory errorMessage\n  ) internal pure returns (uint256) {\n    // Solidity only automatically asserts when dividing by 0\n    require(b > 0, errorMessage);\n    uint256 c = a / b;\n    // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n    return c;\n  }\n\n  /**\n   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n   * Reverts when dividing by zero.\n   *\n   * Counterpart to Solidity's `%` operator. This function uses a `revert`\n   * opcode (which leaves remaining gas untouched) while Solidity uses an\n   * invalid opcode to revert (consuming all remaining gas).\n   *\n   * Requirements:\n   * - The divisor cannot be zero.\n   */\n  function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n    return mod(a, b, 'SafeMath: modulo by zero');\n  }\n\n  /**\n   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n   * Reverts with custom message when dividing by zero.\n   *\n   * Counterpart to Solidity's `%` operator. This function uses a `revert`\n   * opcode (which leaves remaining gas untouched) while Solidity uses an\n   * invalid opcode to revert (consuming all remaining gas).\n   *\n   * Requirements:\n   * - The divisor cannot be zero.\n   */\n  function mod(\n    uint256 a,\n    uint256 b,\n    string memory errorMessage\n  ) internal pure returns (uint256) {\n    require(b != 0, errorMessage);\n    return a % b;\n  }\n}\n"
      },
      "src/contracts/dependencies/openzeppelin/contracts/IERC20.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n  /**\n   * @dev Returns the amount of tokens in existence.\n   */\n  function totalSupply() external view returns (uint256);\n\n  /**\n   * @dev Returns the amount of tokens owned by `account`.\n   */\n  function balanceOf(address account) external view returns (uint256);\n\n  /**\n   * @dev Moves `amount` tokens from the caller's account to `recipient`.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transfer(address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Returns the remaining number of tokens that `spender` will be\n   * allowed to spend on behalf of `owner` through {transferFrom}. This is\n   * zero by default.\n   *\n   * This value changes when {approve} or {transferFrom} are called.\n   */\n  function allowance(address owner, address spender) external view returns (uint256);\n\n  /**\n   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * IMPORTANT: Beware that changing an allowance with this method brings the risk\n   * that someone may use both the old and the new allowance by unfortunate\n   * transaction ordering. One possible solution to mitigate this race\n   * condition is to first reduce the spender's allowance to 0 and set the\n   * desired value afterwards:\n   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n   *\n   * Emits an {Approval} event.\n   */\n  function approve(address spender, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Moves `amount` tokens from `sender` to `recipient` using the\n   * allowance mechanism. `amount` is then deducted from the caller's\n   * allowance.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transferFrom(\n    address sender,\n    address recipient,\n    uint256 amount\n  ) external returns (bool);\n\n  /**\n   * @dev Emitted when `value` tokens are moved from one account (`from`) to\n   * another (`to`).\n   *\n   * Note that `value` may be zero.\n   */\n  event Transfer(address indexed from, address indexed to, uint256 value);\n\n  /**\n   * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n   * a call to {approve}. `value` is the new allowance.\n   */\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "src/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport {IERC20} from './IERC20.sol';\nimport {SafeMath} from './SafeMath.sol';\nimport {Address} from './Address.sol';\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n  using SafeMath for uint256;\n  using Address for address;\n\n  function safeTransfer(\n    IERC20 token,\n    address to,\n    uint256 value\n  ) internal {\n    callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n  }\n\n  function safeTransferFrom(\n    IERC20 token,\n    address from,\n    address to,\n    uint256 value\n  ) internal {\n    callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n  }\n\n  function safeApprove(\n    IERC20 token,\n    address spender,\n    uint256 value\n  ) internal {\n    require(\n      (value == 0) || (token.allowance(address(this), spender) == 0),\n      'SafeERC20: approve from non-zero to non-zero allowance'\n    );\n    callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n  }\n\n  function callOptionalReturn(IERC20 token, bytes memory data) private {\n    require(address(token).isContract(), 'SafeERC20: call to non-contract');\n\n    // solhint-disable-next-line avoid-low-level-calls\n    (bool success, bytes memory returndata) = address(token).call(data);\n    require(success, 'SafeERC20: low-level call failed');\n\n    if (returndata.length > 0) {\n      // Return data is optional\n      // solhint-disable-next-line max-line-length\n      require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');\n    }\n  }\n}\n"
      },
      "src/contracts/dependencies/openzeppelin/contracts/Address.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n  /**\n   * @dev Returns true if `account` is a contract.\n   *\n   * [IMPORTANT]\n   * ====\n   * It is unsafe to assume that an address for which this function returns\n   * false is an externally-owned account (EOA) and not a contract.\n   *\n   * Among others, `isContract` will return false for the following\n   * types of addresses:\n   *\n   *  - an externally-owned account\n   *  - a contract in construction\n   *  - an address where a contract will be created\n   *  - an address where a contract lived, but was destroyed\n   * ====\n   */\n  function isContract(address account) internal view returns (bool) {\n    // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n    // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n    // for accounts without code, i.e. `keccak256('')`\n    bytes32 codehash;\n    bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      codehash := extcodehash(account)\n    }\n    return (codehash != accountHash && codehash != 0x0);\n  }\n\n  /**\n   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n   * `recipient`, forwarding all available gas and reverting on errors.\n   *\n   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n   * of certain opcodes, possibly making contracts go over the 2300 gas limit\n   * imposed by `transfer`, making them unable to receive funds via\n   * `transfer`. {sendValue} removes this limitation.\n   *\n   * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n   *\n   * IMPORTANT: because control is transferred to `recipient`, care must be\n   * taken to not create reentrancy vulnerabilities. Consider using\n   * {ReentrancyGuard} or the\n   * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n   */\n  function sendValue(address payable recipient, uint256 amount) internal {\n    require(address(this).balance >= amount, 'Address: insufficient balance');\n\n    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n    (bool success, ) = recipient.call{value: amount}('');\n    require(success, 'Address: unable to send value, recipient may have reverted');\n  }\n}\n"
      },
      "src/contracts/interfaces/ILendingPoolAddressesProvider.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title LendingPoolAddressesProvider contract\n * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles\n * - Acting also as factory of proxies and admin of those, so with right to change its implementations\n * - Owned by the Aave Governance\n * @author Aave\n **/\ninterface ILendingPoolAddressesProvider {\n  event MarketIdSet(string newMarketId);\n  event LendingPoolUpdated(address indexed newAddress);\n  event ConfigurationAdminUpdated(address indexed newAddress);\n  event EmergencyAdminUpdated(address indexed newAddress);\n  event LendingPoolConfiguratorUpdated(address indexed newAddress);\n  event LendingPoolCollateralManagerUpdated(address indexed newAddress);\n  event PriceOracleUpdated(address indexed newAddress);\n  event LendingRateOracleUpdated(address indexed newAddress);\n  event ProxyCreated(bytes32 id, address indexed newAddress);\n  event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);\n\n  function getMarketId() external view returns (string memory);\n\n  function setMarketId(string calldata marketId) external;\n\n  function setAddress(bytes32 id, address newAddress) external;\n\n  function setAddressAsProxy(bytes32 id, address impl) external;\n\n  function getAddress(bytes32 id) external view returns (address);\n\n  function getLendingPool() external view returns (address);\n\n  function setLendingPoolImpl(address pool) external;\n\n  function getLendingPoolConfigurator() external view returns (address);\n\n  function setLendingPoolConfiguratorImpl(address configurator) external;\n\n  function getLendingPoolCollateralManager() external view returns (address);\n\n  function setLendingPoolCollateralManager(address manager) external;\n\n  function getPoolAdmin() external view returns (address);\n\n  function setPoolAdmin(address admin) external;\n\n  function getEmergencyAdmin() external view returns (address);\n\n  function setEmergencyAdmin(address admin) external;\n\n  function getPriceOracle() external view returns (address);\n\n  function setPriceOracle(address priceOracle) external;\n\n  function getLendingRateOracle() external view returns (address);\n\n  function setLendingRateOracle(address lendingRateOracle) external;\n}\n"
      },
      "src/contracts/interfaces/IAToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\n\ninterface IAToken is IERC20, IScaledBalanceToken {\n  /**\n   * @dev Emitted after the mint action\n   * @param from The address performing the mint\n   * @param value The amount being\n   * @param index The new liquidity index of the reserve\n   **/\n  event Mint(address indexed from, uint256 value, uint256 index);\n\n  /**\n   * @dev Mints `amount` aTokens to `user`\n   * @param user The address receiving the minted tokens\n   * @param amount The amount of tokens getting minted\n   * @param index The new liquidity index of the reserve\n   * @return `true` if the the previous balance of the user was 0\n   */\n  function mint(\n    address user,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @dev Emitted after aTokens are burned\n   * @param from The owner of the aTokens, getting them burned\n   * @param target The address that will receive the underlying\n   * @param value The amount being burned\n   * @param index The new liquidity index of the reserve\n   **/\n  event Burn(address indexed from, address indexed target, uint256 value, uint256 index);\n\n  /**\n   * @dev Emitted during the transfer action\n   * @param from The user whose tokens are being transferred\n   * @param to The recipient\n   * @param value The amount being transferred\n   * @param index The new liquidity index of the reserve\n   **/\n  event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n  /**\n   * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n   * @param user The owner of the aTokens, getting them burned\n   * @param receiverOfUnderlying The address that will receive the underlying\n   * @param amount The amount being burned\n   * @param index The new liquidity index of the reserve\n   **/\n  function burn(\n    address user,\n    address receiverOfUnderlying,\n    uint256 amount,\n    uint256 index\n  ) external;\n\n  /**\n   * @dev Mints aTokens to the reserve treasury\n   * @param amount The amount of tokens getting minted\n   * @param index The new liquidity index of the reserve\n   */\n  function mintToTreasury(uint256 amount, uint256 index) external;\n\n  /**\n   * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken\n   * @param from The address getting liquidated, current owner of the aTokens\n   * @param to The recipient\n   * @param value The amount of tokens getting transferred\n   **/\n  function transferOnLiquidation(\n    address from,\n    address to,\n    uint256 value\n  ) external;\n\n  /**\n   * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer\n   * assets in borrow(), withdraw() and flashLoan()\n   * @param user The recipient of the aTokens\n   * @param amount The amount getting transferred\n   * @return The amount transferred\n   **/\n  function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);\n}\n"
      },
      "src/contracts/interfaces/IVariableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\n\n/**\n * @title IVariableDebtToken\n * @author Aave\n * @notice Defines the basic interface for a variable debt token.\n **/\ninterface IVariableDebtToken is IScaledBalanceToken {\n  /**\n   * @dev Emitted after the mint action\n   * @param from The address performing the mint\n   * @param onBehalfOf The address of the user on which behalf minting has been performed\n   * @param value The amount to be minted\n   * @param index The last index of the reserve\n   **/\n  event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);\n\n  /**\n   * @dev Mints debt token to the `onBehalfOf` address\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt being minted\n   * @param index The variable debt index of the reserve\n   * @return `true` if the the previous balance of the user is 0\n   **/\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @dev Emitted when variable debt is burnt\n   * @param user The user which debt has been burned\n   * @param amount The amount of debt being burned\n   * @param index The index of the user\n   **/\n  event Burn(address indexed user, uint256 amount, uint256 index);\n\n  /**\n   * @dev Burns user variable debt\n   * @param user The user which debt is burnt\n   * @param index The variable debt index of the reserve\n   **/\n  function burn(\n    address user,\n    uint256 amount,\n    uint256 index\n  ) external;\n}\n"
      },
      "src/contracts/flashloan/interfaces/IFlashLoanReceiver.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {ILendingPool} from '../../interfaces/ILendingPool.sol';\n\n/**\n * @title IFlashLoanReceiver interface\n * @notice Interface for the Aave fee IFlashLoanReceiver.\n * @author Aave\n * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n **/\ninterface IFlashLoanReceiver {\n  function executeOperation(\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata premiums,\n    address initiator,\n    bytes calldata params\n  ) external returns (bool);\n\n  function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);\n\n  function LENDING_POOL() external view returns (ILendingPool);\n}\n"
      },
      "src/contracts/interfaces/IPriceOracleGetter.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title IPriceOracleGetter interface\n * @notice Interface for the Aave price oracle.\n **/\n\ninterface IPriceOracleGetter {\n  /**\n   * @dev returns the asset price in ETH\n   * @param asset the address of the asset\n   * @return the ETH price of the asset\n   **/\n  function getAssetPrice(address asset) external view returns (uint256);\n}\n"
      },
      "src/contracts/interfaces/IStableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title IStableDebtToken\n * @notice Defines the interface for the stable debt token\n * @dev It does not inherit from IERC20 to save in code size\n * @author Aave\n **/\n\ninterface IStableDebtToken {\n  /**\n   * @dev Emitted when new stable debt is minted\n   * @param user The address of the user who triggered the minting\n   * @param onBehalfOf The recipient of stable debt tokens\n   * @param amount The amount minted\n   * @param currentBalance The current balance of the user\n   * @param balanceIncrease The increase in balance since the last action of the user\n   * @param newRate The rate of the debt after the minting\n   * @param avgStableRate The new average stable rate after the minting\n   * @param newTotalSupply The new total supply of the stable debt token after the action\n   **/\n  event Mint(\n    address indexed user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 newRate,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @dev Emitted when new stable debt is burned\n   * @param user The address of the user\n   * @param amount The amount being burned\n   * @param currentBalance The current balance of the user\n   * @param balanceIncrease The the increase in balance since the last action of the user\n   * @param avgStableRate The new average stable rate after the burning\n   * @param newTotalSupply The new total supply of the stable debt token after the action\n   **/\n  event Burn(\n    address indexed user,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @dev Mints debt token to the `onBehalfOf` address.\n   * - The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt tokens to mint\n   * @param rate The rate of the debt being minted\n   **/\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 rate\n  ) external returns (bool);\n\n  /**\n   * @dev Burns debt of `user`\n   * - The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @param user The address of the user getting his debt burned\n   * @param amount The amount of debt tokens getting burned\n   **/\n  function burn(address user, uint256 amount) external;\n\n  /**\n   * @dev Returns the average rate of all the stable rate loans.\n   * @return The average stable rate\n   **/\n  function getAverageStableRate() external view returns (uint256);\n\n  /**\n   * @dev Returns the stable rate of the user debt\n   * @return The stable rate of the user\n   **/\n  function getUserStableRate(address user) external view returns (uint256);\n\n  /**\n   * @dev Returns the timestamp of the last update of the user\n   * @return The timestamp\n   **/\n  function getUserLastUpdated(address user) external view returns (uint40);\n\n  /**\n   * @dev Returns the principal, the total supply and the average stable rate\n   **/\n  function getSupplyData()\n    external\n    view\n    returns (\n      uint256,\n      uint256,\n      uint256,\n      uint40\n    );\n\n  /**\n   * @dev Returns the timestamp of the last update of the total supply\n   * @return The timestamp\n   **/\n  function getTotalSupplyLastUpdated() external view returns (uint40);\n\n  /**\n   * @dev Returns the total supply and the average stable rate\n   **/\n  function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);\n\n  /**\n   * @dev Returns the principal debt balance of the user\n   * @return The debt balance of the user since the last burn/mint action\n   **/\n  function principalBalanceOf(address user) external view returns (uint256);\n}\n"
      },
      "src/contracts/interfaces/ILendingPool.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\nimport {IRescue} from './../../interfaces/IRescue.sol';\n\ninterface ILendingPool is IRescue {\n  /**\n   * @dev Emitted on deposit()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the deposit\n   * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens\n   * @param amount The amount deposited\n   * @param referral The referral code used\n   **/\n  event Deposit(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referral\n  );\n\n  /**\n   * @dev Emitted on withdraw()\n   * @param reserve The address of the underlyng asset being withdrawn\n   * @param user The address initiating the withdrawal, owner of aTokens\n   * @param to Address that will receive the underlying\n   * @param amount The amount to be withdrawn\n   **/\n  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n\n  /**\n   * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n   * @param reserve The address of the underlying asset being borrowed\n   * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n   * initiator of the transaction on flashLoan()\n   * @param onBehalfOf The address that will be getting the debt\n   * @param amount The amount borrowed out\n   * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable\n   * @param borrowRate The numeric rate at which the user has borrowed\n   * @param referral The referral code used\n   **/\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint256 borrowRateMode,\n    uint256 borrowRate,\n    uint16 indexed referral\n  );\n\n  /**\n   * @dev Emitted on repay()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The beneficiary of the repayment, getting his debt reduced\n   * @param repayer The address of the user initiating the repay(), providing the funds\n   * @param amount The amount repaid\n   **/\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount\n  );\n\n  /**\n   * @dev Emitted on swapBorrowRateMode()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user swapping his rate mode\n   * @param rateMode The rate mode that the user wants to swap to\n   **/\n  event Swap(address indexed reserve, address indexed user, uint256 rateMode);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   **/\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   **/\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on rebalanceStableBorrowRate()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user for which the rebalance has been executed\n   **/\n  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on flashLoan()\n   * @param target The address of the flash loan receiver contract\n   * @param initiator The address initiating the flash loan\n   * @param asset The address of the asset being flash borrowed\n   * @param amount The amount flash borrowed\n   * @param premium The fee flash borrowed\n   * @param referralCode The referral code used\n   **/\n  event FlashLoan(\n    address indexed target,\n    address indexed initiator,\n    address indexed asset,\n    uint256 amount,\n    uint256 premium,\n    uint16 referralCode\n  );\n\n  /**\n   * @dev Emitted when the pause is triggered.\n   */\n  event Paused();\n\n  /**\n   * @dev Emitted when the pause is lifted.\n   */\n  event Unpaused();\n\n  /**\n   * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via\n   * LendingPoolCollateral manager using a DELEGATECALL\n   * This allows to have the events in the generated ABI for LendingPool.\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator\n   * @param liquidator The address of the liquidator\n   * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   **/\n  event LiquidationCall(\n    address indexed collateralAsset,\n    address indexed debtAsset,\n    address indexed user,\n    uint256 debtToCover,\n    uint256 liquidatedCollateralAmount,\n    address liquidator,\n    bool receiveAToken\n  );\n\n  /**\n   * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared\n   * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,\n   * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it\n   * gets added to the LendingPool ABI\n   * @param reserve The address of the underlying asset of the reserve\n   * @param liquidityRate The new liquidity rate\n   * @param stableBorrowRate The new stable borrow rate\n   * @param variableBorrowRate The new variable borrow rate\n   * @param liquidityIndex The new liquidity index\n   * @param variableBorrowIndex The new variable borrow index\n   **/\n  event ReserveDataUpdated(\n    address indexed reserve,\n    uint256 liquidityRate,\n    uint256 stableBorrowRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  /**\n   * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to deposit\n   * @param amount The amount to be deposited\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   **/\n  function deposit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance\n   * @param to Address that will receive the underlying, same as msg.sender if the user\n   *   wants to receive it on his own wallet, or a different address if the beneficiary is a\n   *   different wallet\n   * @return The final amount withdrawn\n   **/\n  function withdraw(\n    address asset,\n    uint256 amount,\n    address to\n  ) external returns (uint256);\n\n  /**\n   * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n   * already deposited enough collateral, or he was given enough allowance by a credit delegator on the\n   * corresponding debt token (StableDebtToken or VariableDebtToken)\n   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself\n   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n   * if he has been given credit delegation allowance\n   **/\n  function borrow(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode,\n    address onBehalfOf\n  ) external;\n\n  /**\n   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n   * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n   * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n   * other borrower whose debt should be removed\n   * @return The final amount repaid\n   **/\n  function repay(\n    address asset,\n    uint256 amount,\n    uint256 rateMode,\n    address onBehalfOf\n  ) external returns (uint256);\n\n  /**\n   * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa\n   * @param asset The address of the underlying asset borrowed\n   * @param rateMode The rate mode that the user wants to swap to\n   **/\n  function swapBorrowRateMode(address asset, uint256 rateMode) external;\n\n  /**\n   * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n   * - Users can be rebalanced if the following conditions are satisfied:\n   *     1. Usage ratio is above 95%\n   *     2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been\n   *        borrowed at a stable rate and depositors are not earning enough\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be rebalanced\n   **/\n  function rebalanceStableBorrowRate(address asset, address user) external;\n\n  /**\n   * @dev Allows depositors to enable/disable a specific deposited asset as collateral\n   * @param asset The address of the underlying asset deposited\n   * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise\n   **/\n  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n  /**\n   * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   **/\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) external;\n\n  /**\n   * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\n   * For further details please visit https://developers.aave.com\n   * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface\n   * @param assets The addresses of the assets being flash-borrowed\n   * @param amounts The amounts amounts being flash-borrowed\n   * @param modes Types of the debt to open if the flash loan is not returned:\n   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   **/\n  function flashLoan(\n    address receiverAddress,\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata modes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @dev Returns the user account data across all the reserves\n   * @param user The address of the user\n   * @return totalCollateralETH the total collateral in ETH of the user\n   * @return totalDebtETH the total debt in ETH of the user\n   * @return availableBorrowsETH the borrowing power left of the user\n   * @return currentLiquidationThreshold the liquidation threshold of the user\n   * @return ltv the loan to value of the user\n   * @return healthFactor the current health factor of the user\n   **/\n  function getUserAccountData(address user)\n    external\n    view\n    returns (\n      uint256 totalCollateralETH,\n      uint256 totalDebtETH,\n      uint256 availableBorrowsETH,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    );\n\n  function initReserve(\n    address reserve,\n    address aTokenAddress,\n    address stableDebtAddress,\n    address variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external;\n\n  function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)\n    external;\n\n  function setConfiguration(address reserve, uint256 configuration) external;\n\n  /**\n   * @dev Returns the configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The configuration of the reserve\n   **/\n  function getConfiguration(address asset)\n    external\n    view\n    returns (DataTypes.ReserveConfigurationMap memory);\n\n  /**\n   * @dev Returns the configuration of the user across all the reserves\n   * @param user The user address\n   * @return The configuration of the user\n   **/\n  function getUserConfiguration(address user)\n    external\n    view\n    returns (DataTypes.UserConfigurationMap memory);\n\n  /**\n   * @dev Returns the normalized income normalized income of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve's normalized income\n   */\n  function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n  /**\n   * @dev Returns the normalized variable debt per unit of asset\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve normalized variable debt\n   */\n  function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\n\n  /**\n   * @dev Returns the state and configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The state of the reserve\n   **/\n  function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\n\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 amount,\n    uint256 balanceFromAfter,\n    uint256 balanceToBefore\n  ) external;\n\n  function getReservesList() external view returns (address[] memory);\n\n  function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);\n\n  function setPause(bool val) external;\n\n  function paused() external view returns (bool);\n\n  function swapToVariable(address asset, address user) external;\n}\n"
      },
      "src/contracts/protocol/libraries/aave-upgradeability/VersionedInitializable.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title VersionedInitializable\n *\n * @dev Helper contract to implement initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n *\n * @author Aave, inspired by the OpenZeppelin Initializable contract\n */\nabstract contract VersionedInitializable {\n  /**\n   * @dev Indicates that the contract has been initialized.\n   */\n  uint256 private lastInitializedRevision = 0;\n\n  /**\n   * @dev Indicates that the contract is in the process of being initialized.\n   */\n  bool private initializing;\n\n  /**\n   * @dev Modifier to use in the initializer function of a contract.\n   */\n  modifier initializer() {\n    uint256 revision = getRevision();\n    require(\n      initializing || isConstructor() || revision > lastInitializedRevision,\n      'Contract instance has already been initialized'\n    );\n\n    bool isTopLevelCall = !initializing;\n    if (isTopLevelCall) {\n      initializing = true;\n      lastInitializedRevision = revision;\n    }\n\n    _;\n\n    if (isTopLevelCall) {\n      initializing = false;\n    }\n  }\n\n  /**\n  * @dev returns the revision number of the contract\n  * Needs to be defined in the inherited class as a constant.\n  **/ \n  function getRevision() internal pure virtual returns (uint256);\n\n  /**\n  * @dev Returns true if and only if the function is running in the constructor\n  **/ \n  function isConstructor() private view returns (bool) {\n    // extcodesize checks the size of the code stored in an address, and\n    // address returns the current address. Since the code is still not\n    // deployed when running a constructor, any checks on its code size will\n    // yield zero, making it an effective way to detect if a contract is\n    // under construction or not.\n    uint256 cs;\n    //solium-disable-next-line\n    assembly {\n      cs := extcodesize(address())\n    }\n    return cs == 0;\n  }\n\n  // Reserved storage space to allow for layout changes in the future.\n  uint256[50] private ______gap;\n}\n"
      },
      "src/contracts/protocol/libraries/helpers/Helpers.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title Helpers library\n * @author Aave\n */\nlibrary Helpers {\n  /**\n   * @dev Fetches the user current stable and variable debt balances\n   * @param user The user address\n   * @param reserve The reserve data object\n   * @return The stable and variable debt balance\n   **/\n  function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve)\n    internal\n    view\n    returns (uint256, uint256)\n  {\n    return (\n      IERC20(reserve.stableDebtTokenAddress).balanceOf(user),\n      IERC20(reserve.variableDebtTokenAddress).balanceOf(user)\n    );\n  }\n\n  function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve)\n    internal\n    view\n    returns (uint256, uint256)\n  {\n    return (\n      IERC20(reserve.stableDebtTokenAddress).balanceOf(user),\n      IERC20(reserve.variableDebtTokenAddress).balanceOf(user)\n    );\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/helpers/Errors.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title Errors library\n * @author Aave\n * @notice Defines the error messages emitted by the different contracts of the Aave protocol\n * @dev Error messages prefix glossary:\n *  - VL = ValidationLogic\n *  - MATH = Math libraries\n *  - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)\n *  - AT = AToken\n *  - SDT = StableDebtToken\n *  - VDT = VariableDebtToken\n *  - LP = LendingPool\n *  - LPAPR = LendingPoolAddressesProviderRegistry\n *  - LPC = LendingPoolConfiguration\n *  - RL = ReserveLogic\n *  - LPCM = LendingPoolCollateralManager\n *  - P = Pausable\n */\nlibrary Errors {\n  //common errors\n  string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'\n  string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small\n\n  //contract specific errors\n  string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0'\n  string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve'\n  string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen'\n  string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough'\n  string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance'\n  string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.'\n  string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled'\n  string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected'\n  string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0'\n  string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold'\n  string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow'\n  string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled\n  string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed\n  string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode\n  string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'\n  string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed'\n  string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve'\n  string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve'\n  string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0'\n  string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral'\n  string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve'\n  string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met'\n  string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed'\n  string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow'\n  string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.'\n  string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent'\n  string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator'\n  string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28';\n  string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool'\n  string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself'\n  string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero'\n  string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized'\n  string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0'\n  string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve'\n  string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin'\n  string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered'\n  string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold'\n  string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated'\n  string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency'\n  string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // \"There isn't enough liquidity available to liquidate\"\n  string public constant LPCM_NO_ERRORS = '46'; // 'No errors'\n  string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected\n  string public constant MATH_MULTIPLICATION_OVERFLOW = '48';\n  string public constant MATH_ADDITION_OVERFLOW = '49';\n  string public constant MATH_DIVISION_BY_ZERO = '50';\n  string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; //  Liquidity index overflows uint128\n  string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; //  Variable borrow index overflows uint128\n  string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; //  Liquidity rate overflows uint128\n  string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; //  Variable borrow rate overflows uint128\n  string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; //  Stable borrow rate overflows uint128\n  string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint\n  string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57';\n  string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn\n  string public constant LP_FAILED_COLLATERAL_SWAP = '60';\n  string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61';\n  string public constant LP_REENTRANCY_NOT_ALLOWED = '62';\n  string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63';\n  string public constant LP_IS_PAUSED = '64'; // 'Pool is paused'\n  string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';\n  string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';\n  string public constant RC_INVALID_LTV = '67';\n  string public constant RC_INVALID_LIQ_THRESHOLD = '68';\n  string public constant RC_INVALID_LIQ_BONUS = '69';\n  string public constant RC_INVALID_DECIMALS = '70';\n  string public constant RC_INVALID_RESERVE_FACTOR = '71';\n  string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';\n  string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';\n  string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74';\n  string public constant UL_INVALID_INDEX = '77';\n  string public constant LP_NOT_CONTRACT = '78';\n  string public constant SDT_STABLE_DEBT_OVERFLOW = '79';\n  string public constant SDT_BURN_EXCEEDS_BALANCE = '80';\n\n  enum CollateralManagerErrors {\n    NO_ERROR,\n    NO_COLLATERAL_AVAILABLE,\n    COLLATERAL_CANNOT_BE_LIQUIDATED,\n    CURRRENCY_NOT_BORROWED,\n    HEALTH_FACTOR_ABOVE_THRESHOLD,\n    NOT_ENOUGH_LIQUIDITY,\n    NO_ACTIVE_RESERVE,\n    HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,\n    INVALID_EQUAL_ASSETS_TO_SWAP,\n    FROZEN_RESERVE\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/math/WadRayMath.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title WadRayMath library\n * @author Aave\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)\n **/\n\nlibrary WadRayMath {\n  uint256 internal constant WAD = 1e18;\n  uint256 internal constant halfWAD = WAD / 2;\n\n  uint256 internal constant RAY = 1e27;\n  uint256 internal constant halfRAY = RAY / 2;\n\n  uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n  /**\n   * @return One ray, 1e27\n   **/\n  function ray() internal pure returns (uint256) {\n    return RAY;\n  }\n\n  /**\n   * @return One wad, 1e18\n   **/\n\n  function wad() internal pure returns (uint256) {\n    return WAD;\n  }\n\n  /**\n   * @return Half ray, 1e27/2\n   **/\n  function halfRay() internal pure returns (uint256) {\n    return halfRAY;\n  }\n\n  /**\n   * @return Half ray, 1e18/2\n   **/\n  function halfWad() internal pure returns (uint256) {\n    return halfWAD;\n  }\n\n  /**\n   * @dev Multiplies two wad, rounding half up to the nearest wad\n   * @param a Wad\n   * @param b Wad\n   * @return The result of a*b, in wad\n   **/\n  function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\n    if (a == 0 || b == 0) {\n      return 0;\n    }\n\n    require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n    return (a * b + halfWAD) / WAD;\n  }\n\n  /**\n   * @dev Divides two wad, rounding half up to the nearest wad\n   * @param a Wad\n   * @param b Wad\n   * @return The result of a/b, in wad\n   **/\n  function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n    require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n    uint256 halfB = b / 2;\n\n    require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n    return (a * WAD + halfB) / b;\n  }\n\n  /**\n   * @dev Multiplies two ray, rounding half up to the nearest ray\n   * @param a Ray\n   * @param b Ray\n   * @return The result of a*b, in ray\n   **/\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {\n    if (a == 0 || b == 0) {\n      return 0;\n    }\n\n    require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n    return (a * b + halfRAY) / RAY;\n  }\n\n  /**\n   * @dev Divides two ray, rounding half up to the nearest ray\n   * @param a Ray\n   * @param b Ray\n   * @return The result of a/b, in ray\n   **/\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n    require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n    uint256 halfB = b / 2;\n\n    require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n    return (a * RAY + halfB) / b;\n  }\n\n  /**\n   * @dev Casts ray down to wad\n   * @param a Ray\n   * @return a casted to wad, rounded half up to the nearest wad\n   **/\n  function rayToWad(uint256 a) internal pure returns (uint256) {\n    uint256 halfRatio = WAD_RAY_RATIO / 2;\n    uint256 result = halfRatio + a;\n    require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);\n\n    return result / WAD_RAY_RATIO;\n  }\n\n  /**\n   * @dev Converts wad up to ray\n   * @param a Wad\n   * @return a converted in ray\n   **/\n  function wadToRay(uint256 a) internal pure returns (uint256) {\n    uint256 result = a * WAD_RAY_RATIO;\n    require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);\n    return result;\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/math/PercentageMath.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title PercentageMath library\n * @author Aave\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded half up\n **/\n\nlibrary PercentageMath {\n  uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n  uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;\n\n  /**\n   * @dev Executes a percentage multiplication\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return The percentage of value\n   **/\n  function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {\n    if (value == 0 || percentage == 0) {\n      return 0;\n    }\n\n    require(\n      value <= (type(uint256).max - HALF_PERCENT) / percentage,\n      Errors.MATH_MULTIPLICATION_OVERFLOW\n    );\n\n    return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;\n  }\n\n  /**\n   * @dev Executes a percentage division\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return The value divided the percentage\n   **/\n  function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {\n    require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);\n    uint256 halfPercentage = percentage / 2;\n\n    require(\n      value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,\n      Errors.MATH_MULTIPLICATION_OVERFLOW\n    );\n\n    return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/logic/ReserveLogic.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n  using SafeMath for uint256;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeERC20 for IERC20;\n\n  /**\n   * @dev Emitted when the state of a reserve is updated\n   * @param asset The address of the underlying asset of the reserve\n   * @param liquidityRate The new liquidity rate\n   * @param stableBorrowRate The new stable borrow rate\n   * @param variableBorrowRate The new variable borrow rate\n   * @param liquidityIndex The new liquidity index\n   * @param variableBorrowIndex The new variable borrow index\n   **/\n  event ReserveDataUpdated(\n    address indexed asset,\n    uint256 liquidityRate,\n    uint256 stableBorrowRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  /**\n   * @dev Returns the ongoing normalized income for the reserve\n   * A value of 1e27 means there is no income. As time passes, the income is accrued\n   * A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n   * @param reserve The reserve object\n   * @return the normalized income. expressed in ray\n   **/\n  function getNormalizedIncome(DataTypes.ReserveData storage reserve)\n    internal\n    view\n    returns (uint256)\n  {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == uint40(block.timestamp)) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.liquidityIndex;\n    }\n\n    uint256 cumulated =\n      MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n        reserve.liquidityIndex\n      );\n\n    return cumulated;\n  }\n\n  /**\n   * @dev Returns the ongoing normalized variable debt for the reserve\n   * A value of 1e27 means there is no debt. As time passes, the income is accrued\n   * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n   * @param reserve The reserve object\n   * @return The normalized variable debt. expressed in ray\n   **/\n  function getNormalizedDebt(DataTypes.ReserveData storage reserve)\n    internal\n    view\n    returns (uint256)\n  {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == uint40(block.timestamp)) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.variableBorrowIndex;\n    }\n\n    uint256 cumulated =\n      MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n        reserve.variableBorrowIndex\n      );\n\n    return cumulated;\n  }\n\n  /**\n   * @dev Updates the liquidity cumulative index and the variable borrow index.\n   * @param reserve the reserve object\n   **/\n  function updateState(DataTypes.ReserveData storage reserve) internal {\n    uint256 scaledVariableDebt =\n      IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();\n    uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;\n    uint256 previousLiquidityIndex = reserve.liquidityIndex;\n    uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;\n\n    (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =\n      _updateIndexes(\n        reserve,\n        scaledVariableDebt,\n        previousLiquidityIndex,\n        previousVariableBorrowIndex,\n        lastUpdatedTimestamp\n      );\n\n    _mintToTreasury(\n      reserve,\n      scaledVariableDebt,\n      previousVariableBorrowIndex,\n      newLiquidityIndex,\n      newVariableBorrowIndex,\n      lastUpdatedTimestamp\n    );\n  }\n\n  /**\n   * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate\n   * the flashloan fee to the reserve, and spread it between all the depositors\n   * @param reserve The reserve object\n   * @param totalLiquidity The total liquidity available in the reserve\n   * @param amount The amount to accomulate\n   **/\n  function cumulateToLiquidityIndex(\n    DataTypes.ReserveData storage reserve,\n    uint256 totalLiquidity,\n    uint256 amount\n  ) internal {\n    uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());\n\n    uint256 result = amountToLiquidityRatio.add(WadRayMath.ray());\n\n    result = result.rayMul(reserve.liquidityIndex);\n    require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n    reserve.liquidityIndex = uint128(result);\n  }\n\n  /**\n   * @dev Initializes a reserve\n   * @param reserve The reserve object\n   * @param aTokenAddress The address of the overlying atoken contract\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   **/\n  function init(\n    DataTypes.ReserveData storage reserve,\n    address aTokenAddress,\n    address stableDebtTokenAddress,\n    address variableDebtTokenAddress,\n    address interestRateStrategyAddress\n  ) external {\n    require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);\n\n    reserve.liquidityIndex = uint128(WadRayMath.ray());\n    reserve.variableBorrowIndex = uint128(WadRayMath.ray());\n    reserve.aTokenAddress = aTokenAddress;\n    reserve.stableDebtTokenAddress = stableDebtTokenAddress;\n    reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n    reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n  }\n\n  struct UpdateInterestRatesLocalVars {\n    address stableDebtTokenAddress;\n    uint256 availableLiquidity;\n    uint256 totalStableDebt;\n    uint256 newLiquidityRate;\n    uint256 newStableRate;\n    uint256 newVariableRate;\n    uint256 avgStableRate;\n    uint256 totalVariableDebt;\n  }\n\n  /**\n   * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate\n   * @param reserve The address of the reserve to be updated\n   * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action\n   * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n   **/\n  function updateInterestRates(\n    DataTypes.ReserveData storage reserve,\n    address reserveAddress,\n    address aTokenAddress,\n    uint256 liquidityAdded,\n    uint256 liquidityTaken\n  ) internal {\n    UpdateInterestRatesLocalVars memory vars;\n\n    vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;\n\n    (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)\n      .getTotalSupplyAndAvgRate();\n\n    //calculates the total variable debt locally using the scaled total supply instead\n    //of totalSupply(), as it's noticeably cheaper. Also, the index has been\n    //updated by the previous updateState() call\n    vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)\n      .scaledTotalSupply()\n      .rayMul(reserve.variableBorrowIndex);\n\n    vars.availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress);\n\n    (\n      vars.newLiquidityRate,\n      vars.newStableRate,\n      vars.newVariableRate\n    ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(\n      reserveAddress,\n      vars.availableLiquidity.add(liquidityAdded).sub(liquidityTaken),\n      vars.totalStableDebt,\n      vars.totalVariableDebt,\n      vars.avgStableRate,\n      reserve.configuration.getReserveFactor()\n    );\n    require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);\n    require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);\n    require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);\n\n    reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);\n    reserve.currentStableBorrowRate = uint128(vars.newStableRate);\n    reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);\n\n    emit ReserveDataUpdated(\n      reserveAddress,\n      vars.newLiquidityRate,\n      vars.newStableRate,\n      vars.newVariableRate,\n      reserve.liquidityIndex,\n      reserve.variableBorrowIndex\n    );\n  }\n\n  struct MintToTreasuryLocalVars {\n    uint256 currentStableDebt;\n    uint256 principalStableDebt;\n    uint256 previousStableDebt;\n    uint256 currentVariableDebt;\n    uint256 previousVariableDebt;\n    uint256 avgStableRate;\n    uint256 cumulatedStableInterest;\n    uint256 totalDebtAccrued;\n    uint256 amountToMint;\n    uint256 reserveFactor;\n    uint40 stableSupplyUpdatedTimestamp;\n  }\n\n  /**\n   * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the\n   * specific asset.\n   * @param reserve The reserve reserve to be updated\n   * @param scaledVariableDebt The current scaled total variable debt\n   * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest\n   * @param newLiquidityIndex The new liquidity index\n   * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest\n   **/\n  function _mintToTreasury(\n    DataTypes.ReserveData storage reserve,\n    uint256 scaledVariableDebt,\n    uint256 previousVariableBorrowIndex,\n    uint256 newLiquidityIndex,\n    uint256 newVariableBorrowIndex,\n    uint40 timestamp\n  ) internal {\n    MintToTreasuryLocalVars memory vars;\n\n    vars.reserveFactor = reserve.configuration.getReserveFactor();\n\n    if (vars.reserveFactor == 0) {\n      return;\n    }\n\n    //fetching the principal, total stable debt and the avg stable rate\n    (\n      vars.principalStableDebt,\n      vars.currentStableDebt,\n      vars.avgStableRate,\n      vars.stableSupplyUpdatedTimestamp\n    ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();\n\n    //calculate the last principal variable debt\n    vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);\n\n    //calculate the new total supply after accumulation of the index\n    vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);\n\n    //calculate the stable debt until the last timestamp update\n    vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(\n      vars.avgStableRate,\n      vars.stableSupplyUpdatedTimestamp,\n      timestamp\n    );\n\n    vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest);\n\n    //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n    vars.totalDebtAccrued = vars\n      .currentVariableDebt\n      .add(vars.currentStableDebt)\n      .sub(vars.previousVariableDebt)\n      .sub(vars.previousStableDebt);\n\n    vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);\n\n    if (vars.amountToMint != 0) {\n      IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);\n    }\n  }\n\n  /**\n   * @dev Updates the reserve indexes and the timestamp of the update\n   * @param reserve The reserve reserve to be updated\n   * @param scaledVariableDebt The scaled variable debt\n   * @param liquidityIndex The last stored liquidity index\n   * @param variableBorrowIndex The last stored variable borrow index\n   **/\n  function _updateIndexes(\n    DataTypes.ReserveData storage reserve,\n    uint256 scaledVariableDebt,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex,\n    uint40 timestamp\n  ) internal returns (uint256, uint256) {\n    uint256 currentLiquidityRate = reserve.currentLiquidityRate;\n\n    uint256 newLiquidityIndex = liquidityIndex;\n    uint256 newVariableBorrowIndex = variableBorrowIndex;\n\n    //only cumulating if there is any income being produced\n    if (currentLiquidityRate > 0) {\n      uint256 cumulatedLiquidityInterest =\n        MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);\n      newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);\n      require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n      reserve.liquidityIndex = uint128(newLiquidityIndex);\n\n      //as the liquidity rate might come only from stable rate loans, we need to ensure\n      //that there is actual variable debt before accumulating\n      if (scaledVariableDebt != 0) {\n        uint256 cumulatedVariableBorrowInterest =\n          MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);\n        newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);\n        require(\n          newVariableBorrowIndex <= type(uint128).max,\n          Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW\n        );\n        reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);\n      }\n    }\n\n    //solium-disable-next-line\n    reserve.lastUpdateTimestamp = uint40(block.timestamp);\n    return (newLiquidityIndex, newVariableBorrowIndex);\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/logic/GenericLogic.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title GenericLogic library\n * @author Aave\n * @title Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using SafeMath for uint256;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;\n\n  struct balanceDecreaseAllowedLocalVars {\n    uint256 decimals;\n    uint256 liquidationThreshold;\n    uint256 totalCollateralInETH;\n    uint256 totalDebtInETH;\n    uint256 avgLiquidationThreshold;\n    uint256 amountToDecreaseInETH;\n    uint256 collateralBalanceAfterDecrease;\n    uint256 liquidationThresholdAfterDecrease;\n    uint256 healthFactorAfterDecrease;\n    bool reserveUsageAsCollateralEnabled;\n  }\n\n  /**\n   * @dev Checks if a specific balance decrease is allowed\n   * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)\n   * @param asset The address of the underlying asset of the reserve\n   * @param user The address of the user\n   * @param amount The amount to decrease\n   * @param reservesData The data of all the reserves\n   * @param userConfig The user configuration\n   * @param reserves The list of all the active reserves\n   * @param oracle The address of the oracle contract\n   * @return true if the decrease of the balance is allowed\n   **/\n  function balanceDecreaseAllowed(\n    address asset,\n    address user,\n    uint256 amount,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap calldata userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  ) external view returns (bool) {\n    if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {\n      return true;\n    }\n    \n    balanceDecreaseAllowedLocalVars memory vars;\n\n    (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset]\n      .configuration\n      .getParams();\n\n    if (vars.liquidationThreshold == 0) {\n      return true; \n    }\n\n    (\n      vars.totalCollateralInETH,\n      vars.totalDebtInETH,\n      ,\n      vars.avgLiquidationThreshold,\n\n    ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle);\n\n    if (vars.totalDebtInETH == 0) {\n      return true;\n    }\n\n    vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div(\n      10**vars.decimals\n    );\n\n    vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH);\n\n    //if there is a borrow, there can't be 0 collateral\n    if (vars.collateralBalanceAfterDecrease == 0) {\n      return false;\n    }\n\n    vars.liquidationThresholdAfterDecrease = vars\n      .totalCollateralInETH\n      .mul(vars.avgLiquidationThreshold)\n      .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold))\n      .div(vars.collateralBalanceAfterDecrease);\n\n    uint256 healthFactorAfterDecrease =\n      calculateHealthFactorFromBalances(\n        vars.collateralBalanceAfterDecrease,\n        vars.totalDebtInETH,\n        vars.liquidationThresholdAfterDecrease\n      );\n\n    return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\n  }\n\n  struct CalculateUserAccountDataVars {\n    uint256 reserveUnitPrice;\n    uint256 tokenUnit;\n    uint256 compoundedLiquidityBalance;\n    uint256 compoundedBorrowBalance;\n    uint256 decimals;\n    uint256 ltv;\n    uint256 liquidationThreshold;\n    uint256 i;\n    uint256 healthFactor;\n    uint256 totalCollateralInETH;\n    uint256 totalDebtInETH;\n    uint256 avgLtv;\n    uint256 avgLiquidationThreshold;\n    uint256 reservesLength;\n    bool healthFactorBelowThreshold;\n    address currentReserveAddress;\n    bool usageAsCollateralEnabled;\n    bool userUsesReserveAsCollateral;\n  }\n\n  /**\n   * @dev Calculates the user data across the reserves.\n   * this includes the total liquidity/collateral/borrow balances in ETH,\n   * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n   * @param user The address of the user\n   * @param reservesData Data of all the reserves\n   * @param userConfig The configuration of the user\n   * @param reserves The list of the available reserves\n   * @param oracle The price oracle address\n   * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF\n   **/\n  function calculateUserAccountData(\n    address user,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap memory userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  )\n    internal\n    view\n    returns (\n      uint256,\n      uint256,\n      uint256,\n      uint256,\n      uint256\n    )\n  {\n    CalculateUserAccountDataVars memory vars;\n\n    if (userConfig.isEmpty()) {\n      return (0, 0, 0, 0, uint256(-1));\n    }\n    for (vars.i = 0; vars.i < reservesCount; vars.i++) {\n      if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n        continue;\n      }\n\n      vars.currentReserveAddress = reserves[vars.i];\n      DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];\n\n      (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve\n        .configuration\n        .getParams();\n\n      vars.tokenUnit = 10**vars.decimals;\n      vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);\n\n      if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) {\n        vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user);\n\n        uint256 liquidityBalanceETH =\n          vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit);\n\n        vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH);\n\n        vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv));\n        vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add(\n          liquidityBalanceETH.mul(vars.liquidationThreshold)\n        );\n      }\n\n      if (userConfig.isBorrowing(vars.i)) {\n        vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf(\n          user\n        );\n        vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add(\n          IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user)\n        );\n\n        vars.totalDebtInETH = vars.totalDebtInETH.add(\n          vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit)\n        );\n      }\n    }\n\n    vars.avgLtv = vars.totalCollateralInETH > 0\n      ? vars.avgLtv.div(vars.totalCollateralInETH)\n      : 0;\n    vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0\n      ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH)\n      : 0;\n\n    vars.healthFactor = calculateHealthFactorFromBalances(\n      vars.totalCollateralInETH,\n      vars.totalDebtInETH,\n      vars.avgLiquidationThreshold\n    );\n    return (\n      vars.totalCollateralInETH,\n      vars.totalDebtInETH,\n      vars.avgLtv,\n      vars.avgLiquidationThreshold,\n      vars.healthFactor\n    );\n  }\n\n  /**\n   * @dev Calculates the health factor from the corresponding balances\n   * @param totalCollateralInETH The total collateral in ETH\n   * @param totalDebtInETH The total debt in ETH\n   * @param liquidationThreshold The avg liquidation threshold\n   * @return The health factor calculated from the balances provided\n   **/\n  function calculateHealthFactorFromBalances(\n    uint256 totalCollateralInETH,\n    uint256 totalDebtInETH,\n    uint256 liquidationThreshold\n  ) internal pure returns (uint256) {\n    if (totalDebtInETH == 0) return uint256(-1);\n\n    return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH);\n  }\n\n  /**\n   * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the\n   * average Loan To Value\n   * @param totalCollateralInETH The total collateral in ETH\n   * @param totalDebtInETH The total borrow balance\n   * @param ltv The average loan to value\n   * @return the amount available to borrow in ETH for the user\n   **/\n\n  function calculateAvailableBorrowsETH(\n    uint256 totalCollateralInETH,\n    uint256 totalDebtInETH,\n    uint256 ltv\n  ) internal pure returns (uint256) {\n    \n    uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); \n\n    if (availableBorrowsETH < totalDebtInETH) {\n      return 0;\n    }\n\n    availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH);\n    return availableBorrowsETH;\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/logic/ValidationLogic.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {Helpers} from '../helpers/Helpers.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using SafeMath for uint256;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;\n  uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%\n\n  /**\n   * @dev Validates a deposit action\n   * @param reserve The reserve object on which the user is depositing\n   * @param amount The amount to be deposited\n   */\n  function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {\n    (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();\n\n    require(amount != 0, Errors.VL_INVALID_AMOUNT);\n    require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n    require(!isFrozen, Errors.VL_RESERVE_FROZEN);\n  }\n\n  /**\n   * @dev Validates a withdraw action\n   * @param reserveAddress The address of the reserve\n   * @param amount The amount to be withdrawn\n   * @param userBalance The balance of the user\n   * @param reservesData The reserves state\n   * @param userConfig The user configuration\n   * @param reserves The addresses of the reserves\n   * @param reservesCount The number of reserves\n   * @param oracle The price oracle\n   */\n  function validateWithdraw(\n    address reserveAddress,\n    uint256 amount,\n    uint256 userBalance,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  ) external view {\n    require(amount != 0, Errors.VL_INVALID_AMOUNT);\n    require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n    (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags();\n    require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n\n    require(\n      GenericLogic.balanceDecreaseAllowed(\n        reserveAddress,\n        msg.sender,\n        amount,\n        reservesData,\n        userConfig,\n        reserves,\n        reservesCount,\n        oracle\n      ),\n      Errors.VL_TRANSFER_NOT_ALLOWED\n    );\n  }\n\n  struct ValidateBorrowLocalVars {\n    uint256 currentLtv;\n    uint256 currentLiquidationThreshold;\n    uint256 amountOfCollateralNeededETH;\n    uint256 userCollateralBalanceETH;\n    uint256 userBorrowBalanceETH;\n    uint256 availableLiquidity;\n    uint256 healthFactor;\n    bool isActive;\n    bool isFrozen;\n    bool borrowingEnabled;\n    bool stableRateBorrowingEnabled;\n  }\n\n  /**\n   * @dev Validates a borrow action\n   * @param asset The address of the asset to borrow\n   * @param reserve The reserve state from which the user is borrowing\n   * @param userAddress The address of the user\n   * @param amount The amount to be borrowed\n   * @param amountInETH The amount to be borrowed, in ETH\n   * @param interestRateMode The interest rate mode at which the user is borrowing\n   * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage\n   * @param reservesData The state of all the reserves\n   * @param userConfig The state of the user for the specific reserve\n   * @param reserves The addresses of all the active reserves\n   * @param oracle The price oracle\n   */\n\n  function validateBorrow(\n    address asset,\n    DataTypes.ReserveData storage reserve,\n    address userAddress,\n    uint256 amount,\n    uint256 amountInETH,\n    uint256 interestRateMode,\n    uint256 maxStableLoanPercent,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  ) external view {\n    ValidateBorrowLocalVars memory vars;\n\n    (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve\n      .configuration\n      .getFlags();\n\n    require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);\n    require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);\n    require(amount != 0, Errors.VL_INVALID_AMOUNT);\n\n    require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);\n\n    //validate interest rate mode\n    require(\n      uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode ||\n        uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode,\n      Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED\n    );\n\n    (\n      vars.userCollateralBalanceETH,\n      vars.userBorrowBalanceETH,\n      vars.currentLtv,\n      vars.currentLiquidationThreshold,\n      vars.healthFactor\n    ) = GenericLogic.calculateUserAccountData(\n      userAddress,\n      reservesData,\n      userConfig,\n      reserves,\n      reservesCount,\n      oracle\n    );\n\n    require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);\n\n    require(\n      vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n    vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv(\n      vars.currentLtv\n    ); //LTV is calculated in percentage\n\n    require(\n      vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,\n      Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW\n    );\n\n    /**\n     * Following conditions need to be met if the user is borrowing at a stable rate:\n     * 1. Reserve must be enabled for stable rate borrowing\n     * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency\n     *    they are borrowing, to prevent abuses.\n     * 3. Users will be able to borrow only a portion of the total available liquidity\n     **/\n\n    if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) {\n      //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve\n\n      require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);\n\n      require(\n        !userConfig.isUsingAsCollateral(reserve.id) ||\n          reserve.configuration.getLtv() == 0 ||\n          amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress),\n        Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY\n      );\n\n      vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress);\n\n      //calculate the max available loan size in stable rate mode as a percentage of the\n      //available liquidity\n      uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);\n\n      require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);\n    }\n  }\n\n  /**\n   * @dev Validates a repay action\n   * @param reserve The reserve state from which the user is repaying\n   * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n   * @param onBehalfOf The address of the user msg.sender is repaying for\n   * @param stableDebt The borrow balance of the user\n   * @param variableDebt The borrow balance of the user\n   */\n  function validateRepay(\n    DataTypes.ReserveData storage reserve,\n    uint256 amountSent,\n    DataTypes.InterestRateMode rateMode,\n    address onBehalfOf,\n    uint256 stableDebt,\n    uint256 variableDebt\n  ) external view {\n    bool isActive = reserve.configuration.getActive();\n\n    require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n\n    require(amountSent > 0, Errors.VL_INVALID_AMOUNT);\n\n    require(\n      (stableDebt > 0 &&\n        DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) ||\n        (variableDebt > 0 &&\n          DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE),\n      Errors.VL_NO_DEBT_OF_SELECTED_TYPE\n    );\n\n    require(\n      amountSent != uint256(-1) || msg.sender == onBehalfOf,\n      Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n    );\n  }\n\n  /**\n   * @dev Validates a swap of borrow rate mode.\n   * @param reserve The reserve state on which the user is swapping the rate\n   * @param userConfig The user reserves configuration\n   * @param stableDebt The stable debt of the user\n   * @param currentRateMode The rate mode of the borrow\n   */\n  function validateSwapRateMode(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.UserConfigurationMap storage userConfig,\n    uint256 stableDebt,\n    DataTypes.InterestRateMode currentRateMode\n  ) external view {\n    (bool isActive, , , ) = reserve.configuration.getFlags();\n\n    require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n    require(currentRateMode == DataTypes.InterestRateMode.STABLE, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED);\n    require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE);\n  }\n\n  /**\n   * @dev Validates a stable borrow rate rebalance action\n   * @param reserve The reserve state on which the user is getting rebalanced\n   * @param reserveAddress The address of the reserve\n   * @param stableDebtToken The stable debt token instance\n   * @param variableDebtToken The variable debt token instance\n   * @param aTokenAddress The address of the aToken contract\n   */\n  function validateRebalanceStableBorrowRate(\n    DataTypes.ReserveData storage reserve,\n    address reserveAddress,\n    IERC20 stableDebtToken,\n    IERC20 variableDebtToken,\n    address aTokenAddress\n  ) external view {\n    (bool isActive, , , ) = reserve.configuration.getFlags();\n\n    require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n\n    //if the usage ratio is below 95%, no rebalances are needed\n    uint256 totalDebt =\n      stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay();\n    uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay();\n    uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt));\n\n    //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage,\n    //then we allow rebalancing of the stable rate positions.\n\n    uint256 currentLiquidityRate = reserve.currentLiquidityRate;\n    uint256 maxVariableBorrowRate =\n      IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate();\n\n    require(\n      usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD &&\n        currentLiquidityRate <=\n        maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),\n      Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET\n    );\n  }\n\n  /**\n   * @dev Validates the action of setting an asset as collateral\n   * @param reserve The state of the reserve that the user is enabling or disabling as collateral\n   * @param reserveAddress The address of the reserve\n   * @param reservesData The data of all the reserves\n   * @param userConfig The state of the user for the specific reserve\n   * @param reserves The addresses of all the active reserves\n   * @param oracle The price oracle\n   */\n  function validateSetUseReserveAsCollateral(\n    DataTypes.ReserveData storage reserve,\n    address reserveAddress,\n    bool useAsCollateral,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  ) external view {\n    uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender);\n\n    require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0);\n\n    require(\n      useAsCollateral ||\n        GenericLogic.balanceDecreaseAllowed(\n          reserveAddress,\n          msg.sender,\n          underlyingBalance,\n          reservesData,\n          userConfig,\n          reserves,\n          reservesCount,\n          oracle\n        ),\n      Errors.VL_DEPOSIT_ALREADY_IN_USE\n    );\n  }\n\n  /**\n   * @dev Validates a flashloan action\n   * @param assets The assets being flashborrowed\n   * @param amounts The amounts for each asset being borrowed\n   **/\n  function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure {\n    require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS);\n  }\n\n  /**\n   * @dev Validates the liquidation action\n   * @param collateralReserve The reserve data of the collateral\n   * @param principalReserve The reserve data of the principal\n   * @param userConfig The user configuration\n   * @param userHealthFactor The user's health factor\n   * @param userStableDebt Total stable debt balance of the user\n   * @param userVariableDebt Total variable debt balance of the user\n   **/\n  function validateLiquidationCall(\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ReserveData storage principalReserve,\n    DataTypes.UserConfigurationMap storage userConfig,\n    uint256 userHealthFactor,\n    uint256 userStableDebt,\n    uint256 userVariableDebt\n  ) internal view returns (uint256, string memory) {\n    if (\n      !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive()\n    ) {\n      return (\n        uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE),\n        Errors.VL_NO_ACTIVE_RESERVE\n      );\n    }\n\n    if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {\n      return (\n        uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD),\n        Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n      );\n    }\n\n    bool isCollateralEnabled =\n      collateralReserve.configuration.getLiquidationThreshold() > 0 &&\n        userConfig.isUsingAsCollateral(collateralReserve.id);\n\n    //if collateral isn't enabled as collateral by user, it cannot be liquidated\n    if (!isCollateralEnabled) {\n      return (\n        uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED),\n        Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED\n      );\n    }\n\n    if (userStableDebt == 0 && userVariableDebt == 0) {\n      return (\n        uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED),\n        Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER\n      );\n    }\n\n    return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);\n  }\n\n  /**\n   * @dev Validates an aToken transfer\n   * @param from The user from which the aTokens are being transferred\n   * @param reservesData The state of all the reserves\n   * @param userConfig The state of the user for the specific reserve\n   * @param reserves The addresses of all the active reserves\n   * @param oracle The price oracle\n   */\n  function validateTransfer(\n    address from,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    mapping(uint256 => address) storage reserves,\n    uint256 reservesCount,\n    address oracle\n  ) internal view {\n    (, , , , uint256 healthFactor) =\n      GenericLogic.calculateUserAccountData(\n        from,\n        reservesData,\n        userConfig,\n        reserves,\n        reservesCount,\n        oracle\n      );\n\n    require(\n      healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.VL_TRANSFER_NOT_ALLOWED\n    );\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/configuration/ReserveConfiguration.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the reserve configuration\n */\nlibrary ReserveConfiguration {\n  uint256 constant LTV_MASK =                   0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n  uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n  uint256 constant LIQUIDATION_BONUS_MASK =     0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n  uint256 constant DECIMALS_MASK =              0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n  uint256 constant ACTIVE_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 constant FROZEN_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 constant BORROWING_MASK =             0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 constant STABLE_BORROWING_MASK =      0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n  uint256 constant RESERVE_FACTOR_MASK =        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n\n  /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n  uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n  uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n  uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n  uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;\n  uint256 constant IS_FROZEN_START_BIT_POSITION = 57;\n  uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n  uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n  uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n\n  uint256 constant MAX_VALID_LTV = 65535;\n  uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n  uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n  uint256 constant MAX_VALID_DECIMALS = 255;\n  uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;\n\n  /**\n   * @dev Sets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @param ltv the new ltv\n   **/\n  function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {\n    require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);\n\n    self.data = (self.data & LTV_MASK) | ltv;\n  }\n\n  /**\n   * @dev Gets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @return The loan to value\n   **/\n  function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n    return self.data & ~LTV_MASK;\n  }\n\n  /**\n   * @dev Sets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @param threshold The new liquidation threshold\n   **/\n  function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold)\n    internal\n    pure\n  {\n    require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);\n\n    self.data =\n      (self.data & LIQUIDATION_THRESHOLD_MASK) |\n      (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation threshold\n   **/\n  function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self)\n    internal\n    view\n    returns (uint256)\n  {\n    return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n  }\n\n  /**\n   * @dev Sets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @param bonus The new liquidation bonus\n   **/\n  function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {\n    require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);\n\n    self.data =\n      (self.data & LIQUIDATION_BONUS_MASK) |\n      (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation bonus\n   **/\n  function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self)\n    internal\n    view\n    returns (uint256)\n  {\n    return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n  }\n\n  /**\n   * @dev Sets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @param decimals The decimals\n   **/\n  function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {\n    require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);\n\n    self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @return The decimals of the asset\n   **/\n  function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n    return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n  }\n\n  /**\n   * @dev Sets the active state of the reserve\n   * @param self The reserve configuration\n   * @param active The active state\n   **/\n  function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n    self.data =\n      (self.data & ACTIVE_MASK) |\n      (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the active state of the reserve\n   * @param self The reserve configuration\n   * @return The active state\n   **/\n  function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n    return (self.data & ~ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @dev Sets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @param frozen The frozen state\n   **/\n  function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n    self.data =\n      (self.data & FROZEN_MASK) |\n      (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @return The frozen state\n   **/\n  function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n    return (self.data & ~FROZEN_MASK) != 0;\n  }\n\n  /**\n   * @dev Enables or disables borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the borrowing needs to be enabled, false otherwise\n   **/\n  function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {\n    self.data =\n      (self.data & BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The borrowing state\n   **/\n  function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n    return (self.data & ~BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @dev Enables or disables stable rate borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise\n   **/\n  function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled)\n    internal\n    pure\n  {\n    self.data =\n      (self.data & STABLE_BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the stable rate borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The stable rate borrowing state\n   **/\n  function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)\n    internal\n    view\n    returns (bool)\n  {\n    return (self.data & ~STABLE_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @dev Sets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @param reserveFactor The reserve factor\n   **/\n  function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor)\n    internal\n    pure\n  {\n    require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);\n\n    self.data =\n      (self.data & RESERVE_FACTOR_MASK) |\n      (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @return The reserve factor\n   **/\n  function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n    return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n  }\n\n  /**\n   * @dev Gets the configuration flags of the reserve\n   * @param self The reserve configuration\n   * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n   **/\n  function getFlags(DataTypes.ReserveConfigurationMap storage self)\n    internal\n    view\n    returns (\n      bool,\n      bool,\n      bool,\n      bool\n    )\n  {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & ~ACTIVE_MASK) != 0,\n      (dataLocal & ~FROZEN_MASK) != 0,\n      (dataLocal & ~BORROWING_MASK) != 0,\n      (dataLocal & ~STABLE_BORROWING_MASK) != 0\n    );\n  }\n\n  /**\n   * @dev Gets the configuration paramters of the reserve\n   * @param self The reserve configuration\n   * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n   **/\n  function getParams(DataTypes.ReserveConfigurationMap storage self)\n    internal\n    view\n    returns (\n      uint256,\n      uint256,\n      uint256,\n      uint256,\n      uint256\n    )\n  {\n    uint256 dataLocal = self.data;\n\n    return (\n      dataLocal & ~LTV_MASK,\n      (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n      (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n      (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n      (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n    );\n  }\n\n  /**\n   * @dev Gets the configuration paramters of the reserve from a memory object\n   * @param self The reserve configuration\n   * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n   **/\n  function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)\n    internal\n    pure\n    returns (\n      uint256,\n      uint256,\n      uint256,\n      uint256,\n      uint256\n    )\n  {\n    return (\n      self.data & ~LTV_MASK,\n      (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n      (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n      (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n      (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n    );\n  }\n\n  /**\n   * @dev Gets the configuration flags of the reserve from a memory object\n   * @param self The reserve configuration\n   * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n   **/\n  function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)\n    internal\n    pure\n    returns (\n      bool,\n      bool,\n      bool,\n      bool\n    )\n  {\n    return (\n      (self.data & ~ACTIVE_MASK) != 0,\n      (self.data & ~FROZEN_MASK) != 0,\n      (self.data & ~BORROWING_MASK) != 0,\n      (self.data & ~STABLE_BORROWING_MASK) != 0\n    );\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/configuration/UserConfiguration.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title UserConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the user configuration\n */\nlibrary UserConfiguration {\n  uint256 internal constant BORROWING_MASK =\n    0x5555555555555555555555555555555555555555555555555555555555555555;\n\n  /**\n   * @dev Sets if the user is borrowing the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param borrowing True if the user is borrowing the reserve, false otherwise\n   **/\n  function setBorrowing(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool borrowing\n  ) internal {\n    require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n    self.data =\n      (self.data & ~(1 << (reserveIndex * 2))) |\n      (uint256(borrowing ? 1 : 0) << (reserveIndex * 2));\n  }\n\n  /**\n   * @dev Sets if the user is using as collateral the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise\n   **/\n  function setUsingAsCollateral(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool usingAsCollateral\n  ) internal {\n    require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n    self.data =\n      (self.data & ~(1 << (reserveIndex * 2 + 1))) |\n      (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1));\n  }\n\n  /**\n   * @dev Used to validate if a user has been using the reserve for borrowing or as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise\n   **/\n  function isUsingAsCollateralOrBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)\n    internal\n    pure\n    returns (bool)\n  {\n    require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n    return (self.data >> (reserveIndex * 2)) & 3 != 0;\n  }\n\n  /**\n   * @dev Used to validate if a user has been using the reserve for borrowing\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing, false otherwise\n   **/\n  function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)\n    internal\n    pure\n    returns (bool)\n  {\n    require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n    return (self.data >> (reserveIndex * 2)) & 1 != 0;\n  }\n\n  /**\n   * @dev Used to validate if a user has been using the reserve as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve as collateral, false otherwise\n   **/\n  function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)\n    internal\n    pure\n    returns (bool)\n  {\n    require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n    return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0;\n  }\n\n  /**\n   * @dev Used to validate if a user has been borrowing from any reserve\n   * @param self The configuration object\n   * @return True if the user has been borrowing any reserve, false otherwise\n   **/\n  function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data & BORROWING_MASK != 0;\n  }\n\n  /**\n   * @dev Used to validate if a user has not been using any reserve\n   * @param self The configuration object\n   * @return True if the user has been borrowing any reserve, false otherwise\n   **/\n  function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data == 0;\n  }\n}\n"
      },
      "src/contracts/protocol/libraries/types/DataTypes.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nlibrary DataTypes {\n  // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.\n  struct ReserveData {\n    //stores the reserve configuration\n    ReserveConfigurationMap configuration;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    //the current stable borrow rate. Expressed in ray\n    uint128 currentStableBorrowRate;\n    uint40 lastUpdateTimestamp;\n    //tokens addresses\n    address aTokenAddress;\n    address stableDebtTokenAddress;\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the id of the reserve. Represents the position in the list of the active reserves\n    uint8 id;\n  }\n\n  struct ReserveConfigurationMap {\n    //bit 0-15: LTV\n    //bit 16-31: Liq. threshold\n    //bit 32-47: Liq. bonus\n    //bit 48-55: Decimals\n    //bit 56: Reserve is active\n    //bit 57: reserve is frozen\n    //bit 58: borrowing is enabled\n    //bit 59: stable rate borrowing enabled\n    //bit 60-63: reserved\n    //bit 64-79: reserve factor\n    uint256 data;\n  }\n\n  struct UserConfigurationMap {\n    uint256 data;\n  }\n\n  enum InterestRateMode {NONE, STABLE, VARIABLE}\n}\n"
      },
      "src/contracts/protocol/lendingpool/LendingPoolStorage.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\n\ncontract LendingPoolStorage {\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  ILendingPoolAddressesProvider internal _addressesProvider;\n\n  mapping(address => DataTypes.ReserveData) internal _reserves;\n  mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;\n\n  // the list of the available reserves, structured as a mapping for gas savings reasons\n  mapping(uint256 => address) internal _reservesList;\n\n  uint256 internal _reservesCount;\n\n  bool internal _paused;\n}\n"
      },
      "src/contracts/interfaces/IScaledBalanceToken.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\ninterface IScaledBalanceToken {\n  /**\n   * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the\n   * updated stored balance divided by the reserve's liquidity index at the moment of the update\n   * @param user The user whose balance is calculated\n   * @return The scaled balance of the user\n   **/\n  function scaledBalanceOf(address user) external view returns (uint256);\n\n  /**\n   * @dev Returns the scaled balance of the user and the scaled total supply.\n   * @param user The address of the user\n   * @return The scaled balance of the user\n   * @return The scaled balance and the scaled total supply\n   **/\n  function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n\n  /**\n   * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)\n   * @return The scaled total supply\n   **/\n  function scaledTotalSupply() external view returns (uint256);\n}\n"
      },
      "src/interfaces/IRescue.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0;\n\ninterface IRescue {\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   **/\n  function rescueTokens(address token, address to, uint256 amount) external;\n\n  /**\n   * @dev Emitted during the token rescue\n   * @param tokenRescued The token which is being rescued\n   * @param receiver The recipient which will receive the rescued token\n   * @param amountRescued The amount being rescued\n   **/\n  event TokensRescued(\n    address indexed tokenRescued,\n    address indexed receiver,\n    uint256 amountRescued\n  );\n}\n"
      },
      "src/contracts/interfaces/IReserveInterestRateStrategy.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @title IReserveInterestRateStrategyInterface interface\n * @dev Interface for the calculation of the interest rates\n * @author Aave\n */\ninterface IReserveInterestRateStrategy {\n  function baseVariableBorrowRate() external view returns (uint256);\n\n  function getMaxVariableBorrowRate() external view returns (uint256);\n\n  function calculateInterestRates(\n    address reserve,\n    uint256 utilizationRate,\n    uint256 totalStableDebt,\n    uint256 totalVariableDebt,\n    uint256 averageStableBorrowRate,\n    uint256 reserveFactor\n  )\n    external\n    view\n    returns (\n      uint256 liquidityRate,\n      uint256 stableBorrowRate,\n      uint256 variableBorrowRate\n    );\n}\n"
      },
      "src/contracts/protocol/libraries/math/MathUtils.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {WadRayMath} from './WadRayMath.sol';\n\nlibrary MathUtils {\n  using SafeMath for uint256;\n  using WadRayMath for uint256;\n\n  /// @dev Ignoring leap years\n  uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate linearly accumulated during the timeDelta, in ray\n   **/\n\n  function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)\n    internal\n    view\n    returns (uint256)\n  {\n    //solium-disable-next-line\n    uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));\n\n    return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray());\n  }\n\n  /**\n   * @dev Function to calculate the interest using a compounded interest rate formula\n   * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n   *\n   *  (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n   *\n   * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions\n   * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods\n   *\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate compounded during the timeDelta, in ray\n   **/\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp,\n    uint256 currentTimestamp\n  ) internal pure returns (uint256) {\n    //solium-disable-next-line\n    uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));\n\n    if (exp == 0) {\n      return WadRayMath.ray();\n    }\n\n    uint256 expMinusOne = exp - 1;\n\n    uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n    uint256 ratePerSecond = rate / SECONDS_PER_YEAR;\n\n    uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);\n    uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);\n\n    uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;\n    uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;\n\n    return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);\n  }\n\n  /**\n   * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n   * @param rate The interest rate (in ray)\n   * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n   **/\n  function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)\n    internal\n    view\n    returns (uint256)\n  {\n    return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n  }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@aave/core-v3/=lib/aave-helpers/lib/aave-address-book/lib/aave-v3-core/",
        "@aave/periphery-v3/=lib/aave-helpers/lib/aave-address-book/lib/aave-v3-periphery/",
        "aave-address-book/=lib/aave-helpers/lib/aave-address-book/src/",
        "aave-helpers/=lib/aave-helpers/src/",
        "aave-v3-core/=lib/aave-helpers/lib/aave-address-book/lib/aave-v3-core/",
        "aave-v3-periphery/=lib/aave-helpers/lib/aave-address-book/lib/aave-v3-periphery/",
        "ds-test/=lib/aave-helpers/lib/forge-std/lib/ds-test/src/",
        "forge-std/=lib/aave-helpers/lib/forge-std/src/",
        "governance-crosschain-bridges/=lib/aave-helpers/lib/governance-crosschain-bridges/",
        "solidity-utils/=lib/aave-helpers/lib/solidity-utils/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "none"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "istanbul",
      "libraries": {
        "src/contracts/protocol/libraries/logic/ReserveLogic.sol": {
          "ReserveLogic": "0xe58575ba47a348e3c2f9b7ec3eccfbb189ccc6ec"
        },
        "src/contracts/protocol/libraries/logic/ValidationLogic.sol": {
          "ValidationLogic": "0x2fba77a9dD1CcA8c3B54Ce20191057EAa08402D6"
        }
      }
    }
  }}