{"sources":{"src/contracts/instances/PoolInstance.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {Pool} from '../protocol/pool/Pool.sol';\nimport {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol';\nimport {Errors} from '../protocol/libraries/helpers/Errors.sol';\n\ncontract PoolInstance is Pool {\n  uint256 public constant POOL_REVISION = 7;\n\n  constructor(IPoolAddressesProvider provider) Pool(provider) {}\n\n  /**\n   * @notice Initializes the Pool.\n   * @dev Function is invoked by the proxy contract when the Pool contract is added to the\n   * PoolAddressesProvider of the market.\n   * @dev The passed PoolAddressesProvider is validated against the POOL.ADDRESSES_PROVIDER, to ensure the upgrade is done with correct intention.\n   * @param provider The address of the PoolAddressesProvider\n   */\n  function initialize(IPoolAddressesProvider provider) external virtual override initializer {\n    require(provider == ADDRESSES_PROVIDER, Errors.INVALID_ADDRESSES_PROVIDER);\n  }\n\n  function getRevision() internal pure virtual override returns (uint256) {\n    return POOL_REVISION;\n  }\n}\n"},"src/contracts/protocol/pool/Pool.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {VersionedInitializable} from '../../misc/aave-upgradeability/VersionedInitializable.sol';\nimport {Errors} from '../libraries/helpers/Errors.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {PoolLogic} from '../libraries/logic/PoolLogic.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {EModeLogic} from '../libraries/logic/EModeLogic.sol';\nimport {SupplyLogic} from '../libraries/logic/SupplyLogic.sol';\nimport {FlashLoanLogic} from '../libraries/logic/FlashLoanLogic.sol';\nimport {BorrowLogic} from '../libraries/logic/BorrowLogic.sol';\nimport {LiquidationLogic} from '../libraries/logic/LiquidationLogic.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\nimport {BridgeLogic} from '../libraries/logic/BridgeLogic.sol';\nimport {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../interfaces/IPool.sol';\nimport {IACLManager} from '../../interfaces/IACLManager.sol';\nimport {PoolStorage} from './PoolStorage.sol';\n\n/**\n * @title Pool contract\n * @author Aave\n * @notice Main point of interaction with an Aave protocol's market\n * - Users can:\n *   # Supply\n *   # Withdraw\n *   # Borrow\n *   # Repay\n *   # Enable/disable their supplied assets as collateral\n *   # Liquidate positions\n *   # Execute Flash Loans\n * @dev To be covered by a proxy contract, owned by the PoolAddressesProvider of the specific market\n * @dev All admin functions are callable by the PoolConfigurator contract defined also in the\n *   PoolAddressesProvider\n */\nabstract contract Pool is VersionedInitializable, PoolStorage, IPool {\n  using ReserveLogic for DataTypes.ReserveData;\n\n  IPoolAddressesProvider public immutable ADDRESSES_PROVIDER;\n\n  // @notice The name used to fetch the UMBRELLA contract\n  bytes32 public constant UMBRELLA = 'UMBRELLA';\n\n  /**\n   * @dev Only pool configurator can call functions marked by this modifier.\n   */\n  modifier onlyPoolConfigurator() {\n    _onlyPoolConfigurator();\n    _;\n  }\n\n  /**\n   * @dev Only pool admin can call functions marked by this modifier.\n   */\n  modifier onlyPoolAdmin() {\n    _onlyPoolAdmin();\n    _;\n  }\n\n  /**\n   * @dev Only bridge can call functions marked by this modifier.\n   */\n  modifier onlyBridge() {\n    _onlyBridge();\n    _;\n  }\n\n  /**\n   * @dev Only the umbrella contract can call functions marked by this modifier.\n   */\n  modifier onlyUmbrella() {\n    require(ADDRESSES_PROVIDER.getAddress(UMBRELLA) == msg.sender, Errors.CALLER_NOT_UMBRELLA);\n    _;\n  }\n\n  function _onlyPoolConfigurator() internal view virtual {\n    require(\n      ADDRESSES_PROVIDER.getPoolConfigurator() == msg.sender,\n      Errors.CALLER_NOT_POOL_CONFIGURATOR\n    );\n  }\n\n  function _onlyPoolAdmin() internal view virtual {\n    require(\n      IACLManager(ADDRESSES_PROVIDER.getACLManager()).isPoolAdmin(msg.sender),\n      Errors.CALLER_NOT_POOL_ADMIN\n    );\n  }\n\n  function _onlyBridge() internal view virtual {\n    require(\n      IACLManager(ADDRESSES_PROVIDER.getACLManager()).isBridge(msg.sender),\n      Errors.CALLER_NOT_BRIDGE\n    );\n  }\n\n  /**\n   * @dev Constructor.\n   * @param provider The address of the PoolAddressesProvider contract\n   */\n  constructor(IPoolAddressesProvider provider) {\n    ADDRESSES_PROVIDER = provider;\n  }\n\n  /**\n   * @notice Initializes the Pool.\n   * @dev Function is invoked by the proxy contract when the Pool contract is added to the\n   * PoolAddressesProvider of the market.\n   * @dev Caching the address of the PoolAddressesProvider in order to reduce gas consumption on subsequent operations\n   * @param provider The address of the PoolAddressesProvider\n   */\n  function initialize(IPoolAddressesProvider provider) external virtual;\n\n  /// @inheritdoc IPool\n  function mintUnbacked(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external virtual override onlyBridge {\n    BridgeLogic.executeMintUnbacked(\n      _reserves,\n      _reservesList,\n      _usersConfig[onBehalfOf],\n      asset,\n      amount,\n      onBehalfOf,\n      referralCode\n    );\n  }\n\n  /// @inheritdoc IPool\n  function backUnbacked(\n    address asset,\n    uint256 amount,\n    uint256 fee\n  ) external virtual override onlyBridge returns (uint256) {\n    return\n      BridgeLogic.executeBackUnbacked(_reserves[asset], asset, amount, fee, _bridgeProtocolFee);\n  }\n\n  /// @inheritdoc IPool\n  function supply(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) public virtual override {\n    SupplyLogic.executeSupply(\n      _reserves,\n      _reservesList,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        asset: asset,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function supplyWithPermit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) public virtual override {\n    try\n      IERC20WithPermit(asset).permit(\n        msg.sender,\n        address(this),\n        amount,\n        deadline,\n        permitV,\n        permitR,\n        permitS\n      )\n    {} catch {}\n    SupplyLogic.executeSupply(\n      _reserves,\n      _reservesList,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        asset: asset,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function withdraw(\n    address asset,\n    uint256 amount,\n    address to\n  ) public virtual override returns (uint256) {\n    return\n      SupplyLogic.executeWithdraw(\n        _reserves,\n        _reservesList,\n        _eModeCategories,\n        _usersConfig[msg.sender],\n        DataTypes.ExecuteWithdrawParams({\n          asset: asset,\n          amount: amount,\n          to: to,\n          reservesCount: _reservesCount,\n          oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n          userEModeCategory: _usersEModeCategory[msg.sender]\n        })\n      );\n  }\n\n  /// @inheritdoc IPool\n  function borrow(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode,\n    address onBehalfOf\n  ) public virtual override {\n    BorrowLogic.executeBorrow(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteBorrowParams({\n        asset: asset,\n        user: msg.sender,\n        onBehalfOf: onBehalfOf,\n        amount: amount,\n        interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n        referralCode: referralCode,\n        releaseUnderlying: true,\n        reservesCount: _reservesCount,\n        oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        userEModeCategory: _usersEModeCategory[onBehalfOf],\n        priceOracleSentinel: ADDRESSES_PROVIDER.getPriceOracleSentinel()\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function repay(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    address onBehalfOf\n  ) public virtual override returns (uint256) {\n    return\n      BorrowLogic.executeRepay(\n        _reserves,\n        _reservesList,\n        _usersConfig[onBehalfOf],\n        DataTypes.ExecuteRepayParams({\n          asset: asset,\n          amount: amount,\n          interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n          onBehalfOf: onBehalfOf,\n          useATokens: false\n        })\n      );\n  }\n\n  /// @inheritdoc IPool\n  function repayWithPermit(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    address onBehalfOf,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) public virtual override returns (uint256) {\n    try\n      IERC20WithPermit(asset).permit(\n        msg.sender,\n        address(this),\n        amount,\n        deadline,\n        permitV,\n        permitR,\n        permitS\n      )\n    {} catch {}\n\n    {\n      DataTypes.ExecuteRepayParams memory params = DataTypes.ExecuteRepayParams({\n        asset: asset,\n        amount: amount,\n        interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n        onBehalfOf: onBehalfOf,\n        useATokens: false\n      });\n      return BorrowLogic.executeRepay(_reserves, _reservesList, _usersConfig[onBehalfOf], params);\n    }\n  }\n\n  /// @inheritdoc IPool\n  function repayWithATokens(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode\n  ) public virtual override returns (uint256) {\n    return\n      BorrowLogic.executeRepay(\n        _reserves,\n        _reservesList,\n        _usersConfig[msg.sender],\n        DataTypes.ExecuteRepayParams({\n          asset: asset,\n          amount: amount,\n          interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n          onBehalfOf: msg.sender,\n          useATokens: true\n        })\n      );\n  }\n\n  /// @inheritdoc IPool\n  function setUserUseReserveAsCollateral(\n    address asset,\n    bool useAsCollateral\n  ) public virtual override {\n    SupplyLogic.executeUseReserveAsCollateral(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig[msg.sender],\n      asset,\n      useAsCollateral,\n      _reservesCount,\n      ADDRESSES_PROVIDER.getPriceOracle(),\n      _usersEModeCategory[msg.sender]\n    );\n  }\n\n  /// @inheritdoc IPool\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) public virtual override {\n    LiquidationLogic.executeLiquidationCall(\n      _reserves,\n      _reservesList,\n      _usersConfig,\n      _eModeCategories,\n      DataTypes.ExecuteLiquidationCallParams({\n        reservesCount: _reservesCount,\n        debtToCover: debtToCover,\n        collateralAsset: collateralAsset,\n        debtAsset: debtAsset,\n        user: user,\n        receiveAToken: receiveAToken,\n        priceOracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        userEModeCategory: _usersEModeCategory[user],\n        priceOracleSentinel: ADDRESSES_PROVIDER.getPriceOracleSentinel()\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function flashLoan(\n    address receiverAddress,\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata interestRateModes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) public virtual override {\n    DataTypes.FlashloanParams memory flashParams = DataTypes.FlashloanParams({\n      receiverAddress: receiverAddress,\n      assets: assets,\n      amounts: amounts,\n      interestRateModes: interestRateModes,\n      onBehalfOf: onBehalfOf,\n      params: params,\n      referralCode: referralCode,\n      flashLoanPremiumToProtocol: _flashLoanPremiumToProtocol,\n      flashLoanPremiumTotal: _flashLoanPremiumTotal,\n      reservesCount: _reservesCount,\n      addressesProvider: address(ADDRESSES_PROVIDER),\n      pool: address(this),\n      userEModeCategory: _usersEModeCategory[onBehalfOf],\n      isAuthorizedFlashBorrower: IACLManager(ADDRESSES_PROVIDER.getACLManager()).isFlashBorrower(\n        msg.sender\n      )\n    });\n\n    FlashLoanLogic.executeFlashLoan(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      flashParams\n    );\n  }\n\n  /// @inheritdoc IPool\n  function flashLoanSimple(\n    address receiverAddress,\n    address asset,\n    uint256 amount,\n    bytes calldata params,\n    uint16 referralCode\n  ) public virtual override {\n    DataTypes.FlashloanSimpleParams memory flashParams = DataTypes.FlashloanSimpleParams({\n      receiverAddress: receiverAddress,\n      asset: asset,\n      amount: amount,\n      params: params,\n      referralCode: referralCode,\n      flashLoanPremiumToProtocol: _flashLoanPremiumToProtocol,\n      flashLoanPremiumTotal: _flashLoanPremiumTotal\n    });\n    FlashLoanLogic.executeFlashLoanSimple(_reserves[asset], flashParams);\n  }\n\n  /// @inheritdoc IPool\n  function mintToTreasury(address[] calldata assets) external virtual override {\n    PoolLogic.executeMintToTreasury(_reserves, assets);\n  }\n\n  /// @inheritdoc IPool\n  function getReserveData(\n    address asset\n  ) external view virtual override returns (DataTypes.ReserveDataLegacy memory) {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n    DataTypes.ReserveDataLegacy memory res;\n\n    res.configuration = reserve.configuration;\n    res.liquidityIndex = reserve.liquidityIndex;\n    res.currentLiquidityRate = reserve.currentLiquidityRate;\n    res.variableBorrowIndex = reserve.variableBorrowIndex;\n    res.currentVariableBorrowRate = reserve.currentVariableBorrowRate;\n    res.lastUpdateTimestamp = reserve.lastUpdateTimestamp;\n    res.id = reserve.id;\n    res.aTokenAddress = reserve.aTokenAddress;\n    res.variableDebtTokenAddress = reserve.variableDebtTokenAddress;\n    res.interestRateStrategyAddress = reserve.interestRateStrategyAddress;\n    res.accruedToTreasury = reserve.accruedToTreasury;\n    res.unbacked = reserve.unbacked;\n    res.isolationModeTotalDebt = reserve.isolationModeTotalDebt;\n    // This is a temporary workaround for integrations that are broken by Aave 3.2\n    // While the new pool data provider is backward compatible, some integrations hard-code an old implementation\n    // To allow them to not have any infrastructural blocker, a mock must be configured in the Aave Pool Addresses Provider, returning zero on all required view methods, instead of reverting\n    res.stableDebtTokenAddress = ADDRESSES_PROVIDER.getAddress(bytes32('MOCK_STABLE_DEBT'));\n    return res;\n  }\n\n  /// @inheritdoc IPool\n  function getVirtualUnderlyingBalance(\n    address asset\n  ) external view virtual override returns (uint128) {\n    return _reserves[asset].virtualUnderlyingBalance;\n  }\n\n  /// @inheritdoc IPool\n  function getUserAccountData(\n    address user\n  )\n    external\n    view\n    virtual\n    override\n    returns (\n      uint256 totalCollateralBase,\n      uint256 totalDebtBase,\n      uint256 availableBorrowsBase,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    )\n  {\n    return\n      PoolLogic.executeGetUserAccountData(\n        _reserves,\n        _reservesList,\n        _eModeCategories,\n        DataTypes.CalculateUserAccountDataParams({\n          userConfig: _usersConfig[user],\n          reservesCount: _reservesCount,\n          user: user,\n          oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n          userEModeCategory: _usersEModeCategory[user]\n        })\n      );\n  }\n\n  /// @inheritdoc IPool\n  function getConfiguration(\n    address asset\n  ) external view virtual override returns (DataTypes.ReserveConfigurationMap memory) {\n    return _reserves[asset].configuration;\n  }\n\n  /// @inheritdoc IPool\n  function getUserConfiguration(\n    address user\n  ) external view virtual override returns (DataTypes.UserConfigurationMap memory) {\n    return _usersConfig[user];\n  }\n\n  /// @inheritdoc IPool\n  function getReserveNormalizedIncome(\n    address asset\n  ) external view virtual override returns (uint256) {\n    return _reserves[asset].getNormalizedIncome();\n  }\n\n  /// @inheritdoc IPool\n  function getReserveNormalizedVariableDebt(\n    address asset\n  ) external view virtual override returns (uint256) {\n    return _reserves[asset].getNormalizedDebt();\n  }\n\n  /// @inheritdoc IPool\n  function getReservesList() external view virtual override returns (address[] memory) {\n    uint256 reservesListCount = _reservesCount;\n    uint256 droppedReservesCount = 0;\n    address[] memory reservesList = new address[](reservesListCount);\n\n    for (uint256 i = 0; i < reservesListCount; i++) {\n      if (_reservesList[i] != address(0)) {\n        reservesList[i - droppedReservesCount] = _reservesList[i];\n      } else {\n        droppedReservesCount++;\n      }\n    }\n\n    // Reduces the length of the reserves array by `droppedReservesCount`\n    assembly {\n      mstore(reservesList, sub(reservesListCount, droppedReservesCount))\n    }\n    return reservesList;\n  }\n\n  /// @inheritdoc IPool\n  function getReservesCount() external view virtual override returns (uint256) {\n    return _reservesCount;\n  }\n\n  /// @inheritdoc IPool\n  function getReserveAddressById(uint16 id) external view returns (address) {\n    return _reservesList[id];\n  }\n\n  /// @inheritdoc IPool\n  function BRIDGE_PROTOCOL_FEE() public view virtual override returns (uint256) {\n    return _bridgeProtocolFee;\n  }\n\n  /// @inheritdoc IPool\n  function FLASHLOAN_PREMIUM_TOTAL() public view virtual override returns (uint128) {\n    return _flashLoanPremiumTotal;\n  }\n\n  /// @inheritdoc IPool\n  function FLASHLOAN_PREMIUM_TO_PROTOCOL() public view virtual override returns (uint128) {\n    return _flashLoanPremiumToProtocol;\n  }\n\n  /// @inheritdoc IPool\n  function MAX_NUMBER_RESERVES() public view virtual override returns (uint16) {\n    return ReserveConfiguration.MAX_RESERVES_COUNT;\n  }\n\n  /// @inheritdoc IPool\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 amount,\n    uint256 balanceFromBefore,\n    uint256 balanceToBefore\n  ) external virtual override {\n    require(msg.sender == _reserves[asset].aTokenAddress, Errors.CALLER_NOT_ATOKEN);\n    SupplyLogic.executeFinalizeTransfer(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig,\n      DataTypes.FinalizeTransferParams({\n        asset: asset,\n        from: from,\n        to: to,\n        amount: amount,\n        balanceFromBefore: balanceFromBefore,\n        balanceToBefore: balanceToBefore,\n        reservesCount: _reservesCount,\n        oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        fromEModeCategory: _usersEModeCategory[from]\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function initReserve(\n    address asset,\n    address aTokenAddress,\n    address variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external virtual override onlyPoolConfigurator {\n    if (\n      PoolLogic.executeInitReserve(\n        _reserves,\n        _reservesList,\n        DataTypes.InitReserveParams({\n          asset: asset,\n          aTokenAddress: aTokenAddress,\n          variableDebtAddress: variableDebtAddress,\n          interestRateStrategyAddress: interestRateStrategyAddress,\n          reservesCount: _reservesCount,\n          maxNumberReserves: MAX_NUMBER_RESERVES()\n        })\n      )\n    ) {\n      _reservesCount++;\n    }\n  }\n\n  /// @inheritdoc IPool\n  function dropReserve(address asset) external virtual override onlyPoolConfigurator {\n    PoolLogic.executeDropReserve(_reserves, _reservesList, asset);\n  }\n\n  /// @inheritdoc IPool\n  function setReserveInterestRateStrategyAddress(\n    address asset,\n    address rateStrategyAddress\n  ) external virtual override onlyPoolConfigurator {\n    require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n    require(_reserves[asset].id != 0 || _reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n\n    _reserves[asset].interestRateStrategyAddress = rateStrategyAddress;\n  }\n\n  /// @inheritdoc IPool\n  function syncIndexesState(address asset) external virtual override onlyPoolConfigurator {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n  }\n\n  /// @inheritdoc IPool\n  function syncRatesState(address asset) external virtual override onlyPoolConfigurator {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    ReserveLogic.updateInterestRatesAndVirtualBalance(reserve, reserveCache, asset, 0, 0);\n  }\n\n  /// @inheritdoc IPool\n  function setConfiguration(\n    address asset,\n    DataTypes.ReserveConfigurationMap calldata configuration\n  ) external virtual override onlyPoolConfigurator {\n    require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n    require(_reserves[asset].id != 0 || _reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n    _reserves[asset].configuration = configuration;\n  }\n\n  /// @inheritdoc IPool\n  function updateBridgeProtocolFee(\n    uint256 protocolFee\n  ) external virtual override onlyPoolConfigurator {\n    _bridgeProtocolFee = protocolFee;\n  }\n\n  /// @inheritdoc IPool\n  function updateFlashloanPremiums(\n    uint128 flashLoanPremiumTotal,\n    uint128 flashLoanPremiumToProtocol\n  ) external virtual override onlyPoolConfigurator {\n    _flashLoanPremiumTotal = flashLoanPremiumTotal;\n    _flashLoanPremiumToProtocol = flashLoanPremiumToProtocol;\n  }\n\n  /// @inheritdoc IPool\n  function configureEModeCategory(\n    uint8 id,\n    DataTypes.EModeCategoryBaseConfiguration calldata category\n  ) external virtual override onlyPoolConfigurator {\n    // category 0 is reserved for volatile heterogeneous assets and it's always disabled\n    require(id != 0, Errors.EMODE_CATEGORY_RESERVED);\n    _eModeCategories[id].ltv = category.ltv;\n    _eModeCategories[id].liquidationThreshold = category.liquidationThreshold;\n    _eModeCategories[id].liquidationBonus = category.liquidationBonus;\n    _eModeCategories[id].label = category.label;\n  }\n\n  /// @inheritdoc IPool\n  function configureEModeCategoryCollateralBitmap(\n    uint8 id,\n    uint128 collateralBitmap\n  ) external virtual override onlyPoolConfigurator {\n    // category 0 is reserved for volatile heterogeneous assets and it's always disabled\n    require(id != 0, Errors.EMODE_CATEGORY_RESERVED);\n    _eModeCategories[id].collateralBitmap = collateralBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function configureEModeCategoryBorrowableBitmap(\n    uint8 id,\n    uint128 borrowableBitmap\n  ) external virtual override onlyPoolConfigurator {\n    // category 0 is reserved for volatile heterogeneous assets and it's always disabled\n    require(id != 0, Errors.EMODE_CATEGORY_RESERVED);\n    _eModeCategories[id].borrowableBitmap = borrowableBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function getEModeCategoryData(\n    uint8 id\n  ) external view virtual override returns (DataTypes.EModeCategoryLegacy memory) {\n    DataTypes.EModeCategory storage category = _eModeCategories[id];\n    return\n      DataTypes.EModeCategoryLegacy({\n        ltv: category.ltv,\n        liquidationThreshold: category.liquidationThreshold,\n        liquidationBonus: category.liquidationBonus,\n        priceSource: address(0),\n        label: category.label\n      });\n  }\n\n  /// @inheritdoc IPool\n  function getEModeCategoryCollateralConfig(\n    uint8 id\n  ) external view returns (DataTypes.CollateralConfig memory) {\n    return\n      DataTypes.CollateralConfig({\n        ltv: _eModeCategories[id].ltv,\n        liquidationThreshold: _eModeCategories[id].liquidationThreshold,\n        liquidationBonus: _eModeCategories[id].liquidationBonus\n      });\n  }\n\n  /// @inheritdoc IPool\n  function getEModeCategoryLabel(uint8 id) external view returns (string memory) {\n    return _eModeCategories[id].label;\n  }\n\n  /// @inheritdoc IPool\n  function getEModeCategoryCollateralBitmap(uint8 id) external view returns (uint128) {\n    return _eModeCategories[id].collateralBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function getEModeCategoryBorrowableBitmap(uint8 id) external view returns (uint128) {\n    return _eModeCategories[id].borrowableBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function setUserEMode(uint8 categoryId) external virtual override {\n    EModeLogic.executeSetUserEMode(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersEModeCategory,\n      _usersConfig[msg.sender],\n      DataTypes.ExecuteSetUserEModeParams({\n        reservesCount: _reservesCount,\n        oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        categoryId: categoryId\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function getUserEMode(address user) external view virtual override returns (uint256) {\n    return _usersEModeCategory[user];\n  }\n\n  /// @inheritdoc IPool\n  function resetIsolationModeTotalDebt(\n    address asset\n  ) external virtual override onlyPoolConfigurator {\n    PoolLogic.executeResetIsolationModeTotalDebt(_reserves, asset);\n  }\n\n  /// @inheritdoc IPool\n  function getLiquidationGracePeriod(\n    address asset\n  ) external view virtual override returns (uint40) {\n    return _reserves[asset].liquidationGracePeriodUntil;\n  }\n\n  /// @inheritdoc IPool\n  function setLiquidationGracePeriod(\n    address asset,\n    uint40 until\n  ) external virtual override onlyPoolConfigurator {\n    require(_reserves[asset].id != 0 || _reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n    PoolLogic.executeSetLiquidationGracePeriod(_reserves, asset, until);\n  }\n\n  /// @inheritdoc IPool\n  function rescueTokens(\n    address token,\n    address to,\n    uint256 amount\n  ) external virtual override onlyPoolAdmin {\n    PoolLogic.executeRescueTokens(token, to, amount);\n  }\n\n  /// @inheritdoc IPool\n  /// @dev Deprecated: maintained for compatibility purposes\n  function deposit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external virtual override {\n    SupplyLogic.executeSupply(\n      _reserves,\n      _reservesList,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        asset: asset,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function eliminateReserveDeficit(address asset, uint256 amount) external override onlyUmbrella {\n    LiquidationLogic.executeEliminateDeficit(\n      _reserves,\n      _usersConfig[msg.sender],\n      DataTypes.ExecuteEliminateDeficitParams({asset: asset, amount: amount})\n    );\n  }\n\n  /// @inheritdoc IPool\n  function getReserveDeficit(address asset) external view virtual returns (uint256) {\n    return _reserves[asset].deficit;\n  }\n\n  /// @inheritdoc IPool\n  function getReserveAToken(address asset) external view virtual returns (address) {\n    return _reserves[asset].aTokenAddress;\n  }\n\n  /// @inheritdoc IPool\n  function getReserveVariableDebtToken(address asset) external view virtual returns (address) {\n    return _reserves[asset].variableDebtTokenAddress;\n  }\n\n  /// @inheritdoc IPool\n  function getFlashLoanLogic() external pure returns (address) {\n    return address(FlashLoanLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getBorrowLogic() external pure returns (address) {\n    return address(BorrowLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getBridgeLogic() external pure returns (address) {\n    return address(BridgeLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getEModeLogic() external pure returns (address) {\n    return address(EModeLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getLiquidationLogic() external pure returns (address) {\n    return address(LiquidationLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getPoolLogic() external pure returns (address) {\n    return address(PoolLogic);\n  }\n\n  /// @inheritdoc IPool\n  function getSupplyLogic() external pure returns (address) {\n    return address(SupplyLogic);\n  }\n}\n"},"src/contracts/interfaces/IPoolAddressesProvider.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n  /**\n   * @dev Emitted when the market identifier is updated.\n   * @param oldMarketId The old id of the market\n   * @param newMarketId The new id of the market\n   */\n  event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n  /**\n   * @dev Emitted when the pool is updated.\n   * @param oldAddress The old address of the Pool\n   * @param newAddress The new address of the Pool\n   */\n  event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the pool configurator is updated.\n   * @param oldAddress The old address of the PoolConfigurator\n   * @param newAddress The new address of the PoolConfigurator\n   */\n  event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the price oracle is updated.\n   * @param oldAddress The old address of the PriceOracle\n   * @param newAddress The new address of the PriceOracle\n   */\n  event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the ACL manager is updated.\n   * @param oldAddress The old address of the ACLManager\n   * @param newAddress The new address of the ACLManager\n   */\n  event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the ACL admin is updated.\n   * @param oldAddress The old address of the ACLAdmin\n   * @param newAddress The new address of the ACLAdmin\n   */\n  event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the price oracle sentinel is updated.\n   * @param oldAddress The old address of the PriceOracleSentinel\n   * @param newAddress The new address of the PriceOracleSentinel\n   */\n  event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the pool data provider is updated.\n   * @param oldAddress The old address of the PoolDataProvider\n   * @param newAddress The new address of the PoolDataProvider\n   */\n  event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when a new proxy is created.\n   * @param id The identifier of the proxy\n   * @param proxyAddress The address of the created proxy contract\n   * @param implementationAddress The address of the implementation contract\n   */\n  event ProxyCreated(\n    bytes32 indexed id,\n    address indexed proxyAddress,\n    address indexed implementationAddress\n  );\n\n  /**\n   * @dev Emitted when a new non-proxied contract address is registered.\n   * @param id The identifier of the contract\n   * @param oldAddress The address of the old contract\n   * @param newAddress The address of the new contract\n   */\n  event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the implementation of the proxy registered with id is updated\n   * @param id The identifier of the contract\n   * @param proxyAddress The address of the proxy contract\n   * @param oldImplementationAddress The address of the old implementation contract\n   * @param newImplementationAddress The address of the new implementation contract\n   */\n  event AddressSetAsProxy(\n    bytes32 indexed id,\n    address indexed proxyAddress,\n    address oldImplementationAddress,\n    address indexed newImplementationAddress\n  );\n\n  /**\n   * @notice Returns the id of the Aave market to which this contract points to.\n   * @return The market id\n   */\n  function getMarketId() external view returns (string memory);\n\n  /**\n   * @notice Associates an id with a specific PoolAddressesProvider.\n   * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n   * identify and validate multiple Aave markets.\n   * @param newMarketId The market id\n   */\n  function setMarketId(string calldata newMarketId) external;\n\n  /**\n   * @notice Returns an address by its identifier.\n   * @dev The returned address might be an EOA or a contract, potentially proxied\n   * @dev It returns ZERO if there is no registered address with the given id\n   * @param id The id\n   * @return The address of the registered for the specified id\n   */\n  function getAddress(bytes32 id) external view returns (address);\n\n  /**\n   * @notice General function to update the implementation of a proxy registered with\n   * certain `id`. If there is no proxy registered, it will instantiate one and\n   * set as implementation the `newImplementationAddress`.\n   * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n   * setter function, in order to avoid unexpected consequences\n   * @param id The id\n   * @param newImplementationAddress The address of the new implementation\n   */\n  function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;\n\n  /**\n   * @notice Sets an address for an id replacing the address saved in the addresses map.\n   * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n   * @param id The id\n   * @param newAddress The address to set\n   */\n  function setAddress(bytes32 id, address newAddress) external;\n\n  /**\n   * @notice Returns the address of the Pool proxy.\n   * @return The Pool proxy address\n   */\n  function getPool() external view returns (address);\n\n  /**\n   * @notice Updates the implementation of the Pool, or creates a proxy\n   * setting the new `pool` implementation when the function is called for the first time.\n   * @param newPoolImpl The new Pool implementation\n   */\n  function setPoolImpl(address newPoolImpl) external;\n\n  /**\n   * @notice Returns the address of the PoolConfigurator proxy.\n   * @return The PoolConfigurator proxy address\n   */\n  function getPoolConfigurator() external view returns (address);\n\n  /**\n   * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n   * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n   * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n   */\n  function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n  /**\n   * @notice Returns the address of the price oracle.\n   * @return The address of the PriceOracle\n   */\n  function getPriceOracle() external view returns (address);\n\n  /**\n   * @notice Updates the address of the price oracle.\n   * @param newPriceOracle The address of the new PriceOracle\n   */\n  function setPriceOracle(address newPriceOracle) external;\n\n  /**\n   * @notice Returns the address of the ACL manager.\n   * @return The address of the ACLManager\n   */\n  function getACLManager() external view returns (address);\n\n  /**\n   * @notice Updates the address of the ACL manager.\n   * @param newAclManager The address of the new ACLManager\n   */\n  function setACLManager(address newAclManager) external;\n\n  /**\n   * @notice Returns the address of the ACL admin.\n   * @return The address of the ACL admin\n   */\n  function getACLAdmin() external view returns (address);\n\n  /**\n   * @notice Updates the address of the ACL admin.\n   * @param newAclAdmin The address of the new ACL admin\n   */\n  function setACLAdmin(address newAclAdmin) external;\n\n  /**\n   * @notice Returns the address of the price oracle sentinel.\n   * @return The address of the PriceOracleSentinel\n   */\n  function getPriceOracleSentinel() external view returns (address);\n\n  /**\n   * @notice Updates the address of the price oracle sentinel.\n   * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n   */\n  function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n  /**\n   * @notice Returns the address of the data provider.\n   * @return The address of the DataProvider\n   */\n  function getPoolDataProvider() external view returns (address);\n\n  /**\n   * @notice Updates the address of the data provider.\n   * @param newDataProvider The address of the new DataProvider\n   */\n  function setPoolDataProvider(address newDataProvider) external;\n}\n"},"src/contracts/protocol/libraries/helpers/Errors.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\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 */\nlibrary Errors {\n  string public constant CALLER_NOT_POOL_ADMIN = '1'; // 'The caller of the function is not a pool admin'\n  string public constant CALLER_NOT_EMERGENCY_ADMIN = '2'; // 'The caller of the function is not an emergency admin'\n  string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = '3'; // 'The caller of the function is not a pool or emergency admin'\n  string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = '4'; // 'The caller of the function is not a risk or pool admin'\n  string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = '5'; // 'The caller of the function is not an asset listing or pool admin'\n  string public constant CALLER_NOT_BRIDGE = '6'; // 'The caller of the function is not a bridge'\n  string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = '7'; // 'Pool addresses provider is not registered'\n  string public constant INVALID_ADDRESSES_PROVIDER_ID = '8'; // 'Invalid id for the pool addresses provider'\n  string public constant NOT_CONTRACT = '9'; // 'Address is not a contract'\n  string public constant CALLER_NOT_POOL_CONFIGURATOR = '10'; // 'The caller of the function is not the pool configurator'\n  string public constant CALLER_NOT_ATOKEN = '11'; // 'The caller of the function is not an AToken'\n  string public constant INVALID_ADDRESSES_PROVIDER = '12'; // 'The address of the pool addresses provider is invalid'\n  string public constant INVALID_FLASHLOAN_EXECUTOR_RETURN = '13'; // 'Invalid return value of the flashloan executor function'\n  string public constant RESERVE_ALREADY_ADDED = '14'; // 'Reserve has already been added to reserve list'\n  string public constant NO_MORE_RESERVES_ALLOWED = '15'; // 'Maximum amount of reserves in the pool reached'\n  string public constant EMODE_CATEGORY_RESERVED = '16'; // 'Zero eMode category is reserved for volatile heterogeneous assets'\n  string public constant INVALID_EMODE_CATEGORY_ASSIGNMENT = '17'; // 'Invalid eMode category assignment to asset'\n  string public constant RESERVE_LIQUIDITY_NOT_ZERO = '18'; // 'The liquidity of the reserve needs to be 0'\n  string public constant FLASHLOAN_PREMIUM_INVALID = '19'; // 'Invalid flashloan premium'\n  string public constant INVALID_RESERVE_PARAMS = '20'; // 'Invalid risk parameters for the reserve'\n  string public constant INVALID_EMODE_CATEGORY_PARAMS = '21'; // 'Invalid risk parameters for the eMode category'\n  string public constant BRIDGE_PROTOCOL_FEE_INVALID = '22'; // 'Invalid bridge protocol fee'\n  string public constant CALLER_MUST_BE_POOL = '23'; // 'The caller of this function must be a pool'\n  string public constant INVALID_MINT_AMOUNT = '24'; // 'Invalid amount to mint'\n  string public constant INVALID_BURN_AMOUNT = '25'; // 'Invalid amount to burn'\n  string public constant INVALID_AMOUNT = '26'; // 'Amount must be greater than 0'\n  string public constant RESERVE_INACTIVE = '27'; // 'Action requires an active reserve'\n  string public constant RESERVE_FROZEN = '28'; // 'Action cannot be performed because the reserve is frozen'\n  string public constant RESERVE_PAUSED = '29'; // 'Action cannot be performed because the reserve is paused'\n  string public constant BORROWING_NOT_ENABLED = '30'; // 'Borrowing is not enabled'\n  string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '32'; // 'User cannot withdraw more than the available balance'\n  string public constant INVALID_INTEREST_RATE_MODE_SELECTED = '33'; // 'Invalid interest rate mode selected'\n  string public constant COLLATERAL_BALANCE_IS_ZERO = '34'; // 'The collateral balance is 0'\n  string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '35'; // 'Health factor is lesser than the liquidation threshold'\n  string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '36'; // 'There is not enough collateral to cover a new borrow'\n  string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = '37'; // 'Collateral is (mostly) the same currency that is being borrowed'\n  string public constant NO_DEBT_OF_SELECTED_TYPE = '39'; // 'For repayment of a specific type of debt, the user needs to have debt that type'\n  string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '40'; // 'To repay on behalf of a user an explicit amount to repay is needed'\n  string public constant NO_OUTSTANDING_VARIABLE_DEBT = '42'; // 'User does not have outstanding variable rate debt on this reserve'\n  string public constant UNDERLYING_BALANCE_ZERO = '43'; // 'The underlying balance needs to be greater than 0'\n  string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '44'; // 'Interest rate rebalance conditions were not met'\n  string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '45'; // 'Health factor is not below the threshold'\n  string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '46'; // 'The collateral chosen cannot be liquidated'\n  string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '47'; // 'User did not borrow the specified currency'\n  string public constant INCONSISTENT_FLASHLOAN_PARAMS = '49'; // 'Inconsistent flashloan parameters'\n  string public constant BORROW_CAP_EXCEEDED = '50'; // 'Borrow cap is exceeded'\n  string public constant SUPPLY_CAP_EXCEEDED = '51'; // 'Supply cap is exceeded'\n  string public constant UNBACKED_MINT_CAP_EXCEEDED = '52'; // 'Unbacked mint cap is exceeded'\n  string public constant DEBT_CEILING_EXCEEDED = '53'; // 'Debt ceiling is exceeded'\n  string public constant UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO = '54'; // 'Claimable rights over underlying not zero (aToken supply or accruedToTreasury)'\n  string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = '56'; // 'Variable debt supply is not zero'\n  string public constant LTV_VALIDATION_FAILED = '57'; // 'Ltv validation failed'\n  string public constant INCONSISTENT_EMODE_CATEGORY = '58'; // 'Inconsistent eMode category'\n  string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = '59'; // 'Price oracle sentinel validation failed'\n  string public constant ASSET_NOT_BORROWABLE_IN_ISOLATION = '60'; // 'Asset is not borrowable in isolation mode'\n  string public constant RESERVE_ALREADY_INITIALIZED = '61'; // 'Reserve has already been initialized'\n  string public constant USER_IN_ISOLATION_MODE_OR_LTV_ZERO = '62'; // 'User is in isolation mode or ltv is zero'\n  string public constant INVALID_LTV = '63'; // 'Invalid ltv parameter for the reserve'\n  string public constant INVALID_LIQ_THRESHOLD = '64'; // 'Invalid liquidity threshold parameter for the reserve'\n  string public constant INVALID_LIQ_BONUS = '65'; // 'Invalid liquidity bonus parameter for the reserve'\n  string public constant INVALID_DECIMALS = '66'; // 'Invalid decimals parameter of the underlying asset of the reserve'\n  string public constant INVALID_RESERVE_FACTOR = '67'; // 'Invalid reserve factor parameter for the reserve'\n  string public constant INVALID_BORROW_CAP = '68'; // 'Invalid borrow cap for the reserve'\n  string public constant INVALID_SUPPLY_CAP = '69'; // 'Invalid supply cap for the reserve'\n  string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = '70'; // 'Invalid liquidation protocol fee for the reserve'\n  string public constant INVALID_EMODE_CATEGORY = '71'; // 'Invalid eMode category for the reserve'\n  string public constant INVALID_UNBACKED_MINT_CAP = '72'; // 'Invalid unbacked mint cap for the reserve'\n  string public constant INVALID_DEBT_CEILING = '73'; // 'Invalid debt ceiling for the reserve\n  string public constant INVALID_RESERVE_INDEX = '74'; // 'Invalid reserve index'\n  string public constant ACL_ADMIN_CANNOT_BE_ZERO = '75'; // 'ACL admin cannot be set to the zero address'\n  string public constant INCONSISTENT_PARAMS_LENGTH = '76'; // 'Array parameters that should be equal length are not'\n  string public constant ZERO_ADDRESS_NOT_VALID = '77'; // 'Zero address not valid'\n  string public constant INVALID_EXPIRATION = '78'; // 'Invalid expiration'\n  string public constant INVALID_SIGNATURE = '79'; // 'Invalid signature'\n  string public constant OPERATION_NOT_SUPPORTED = '80'; // 'Operation not supported'\n  string public constant DEBT_CEILING_NOT_ZERO = '81'; // 'Debt ceiling is not zero'\n  string public constant ASSET_NOT_LISTED = '82'; // 'Asset is not listed'\n  string public constant INVALID_OPTIMAL_USAGE_RATIO = '83'; // 'Invalid optimal usage ratio'\n  string public constant UNDERLYING_CANNOT_BE_RESCUED = '85'; // 'The underlying asset cannot be rescued'\n  string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = '86'; // 'Reserve has already been added to reserve list'\n  string public constant POOL_ADDRESSES_DO_NOT_MATCH = '87'; // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n  string public constant SILOED_BORROWING_VIOLATION = '89'; // 'User is trying to borrow multiple assets including a siloed one'\n  string public constant RESERVE_DEBT_NOT_ZERO = '90'; // the total debt of the reserve needs to be 0\n  string public constant FLASHLOAN_DISABLED = '91'; // FlashLoaning for this asset is disabled\n  string public constant INVALID_MAX_RATE = '92'; // The expect maximum borrow rate is invalid\n  string public constant WITHDRAW_TO_ATOKEN = '93'; // Withdrawing to the aToken is not allowed\n  string public constant SUPPLY_TO_ATOKEN = '94'; // Supplying to the aToken is not allowed\n  string public constant SLOPE_2_MUST_BE_GTE_SLOPE_1 = '95'; // Variable interest rate slope 2 can not be lower than slope 1\n  string public constant CALLER_NOT_RISK_OR_POOL_OR_EMERGENCY_ADMIN = '96'; // 'The caller of the function is not a risk, pool or emergency admin'\n  string public constant LIQUIDATION_GRACE_SENTINEL_CHECK_FAILED = '97'; // 'Liquidation grace sentinel validation failed'\n  string public constant INVALID_GRACE_PERIOD = '98'; // Grace period above a valid range\n  string public constant INVALID_FREEZE_STATE = '99'; // Reserve is already in the passed freeze state\n  string public constant NOT_BORROWABLE_IN_EMODE = '100'; // Asset not borrowable in eMode\n  string public constant CALLER_NOT_UMBRELLA = '101'; // The caller of the function is not the umbrella contract\n  string public constant RESERVE_NOT_IN_DEFICIT = '102'; // The reserve is not in deficit\n  string public constant MUST_NOT_LEAVE_DUST = '103'; // Below a certain threshold liquidators need to take the full position\n  string public constant USER_CANNOT_HAVE_DEBT = '104'; // Thrown when a user tries to interact with a method that requires a position without debt\n  string public constant CALLER_NOT_ATOKEN_TRANSFER_ADMIN = '1000'; // The caller of the function is not the RWA authorized transfer admin\n  string public constant SUPPLY_ON_BEHALF_OF_NOT_SUPPORTED = '1001'; // Supply on behalf of is not supported\n}\n"},"src/contracts/misc/aave-upgradeability/VersionedInitializable.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/**\n * @title VersionedInitializable\n * @author Aave, inspired by the OpenZeppelin Initializable contract\n * @notice Helper contract to implement initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * @dev 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 */\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   * @notice Returns the revision number of the contract\n   * @dev Needs to be defined in the inherited class as a constant.\n   * @return The revision number\n   */\n  function getRevision() internal pure virtual returns (uint256);\n\n  /**\n   * @notice Returns true if and only if the function is running in the constructor\n   * @return True 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/configuration/ReserveConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\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 internal constant LTV_MASK =                       0x000000000000000000000000000000000000000000000000000000000000FFFF; // prettier-ignore\n  uint256 internal constant LIQUIDATION_THRESHOLD_MASK =     0x00000000000000000000000000000000000000000000000000000000FFFF0000; // prettier-ignore\n  uint256 internal constant LIQUIDATION_BONUS_MASK =         0x0000000000000000000000000000000000000000000000000000FFFF00000000; // prettier-ignore\n  uint256 internal constant DECIMALS_MASK =                  0x00000000000000000000000000000000000000000000000000FF000000000000; // prettier-ignore\n  uint256 internal constant ACTIVE_MASK =                    0x0000000000000000000000000000000000000000000000000100000000000000; // prettier-ignore\n  uint256 internal constant FROZEN_MASK =                    0x0000000000000000000000000000000000000000000000000200000000000000; // prettier-ignore\n  uint256 internal constant BORROWING_MASK =                 0x0000000000000000000000000000000000000000000000000400000000000000; // prettier-ignore\n  // @notice there is an unoccupied hole of 1 bit at position 59 from pre 3.2 stableBorrowRateEnabled\n  uint256 internal constant PAUSED_MASK =                    0x0000000000000000000000000000000000000000000000001000000000000000; // prettier-ignore\n  uint256 internal constant BORROWABLE_IN_ISOLATION_MASK =   0x0000000000000000000000000000000000000000000000002000000000000000; // prettier-ignore\n  uint256 internal constant SILOED_BORROWING_MASK =          0x0000000000000000000000000000000000000000000000004000000000000000; // prettier-ignore\n  uint256 internal constant FLASHLOAN_ENABLED_MASK =         0x0000000000000000000000000000000000000000000000008000000000000000; // prettier-ignore\n  uint256 internal constant RESERVE_FACTOR_MASK =            0x00000000000000000000000000000000000000000000FFFF0000000000000000; // prettier-ignore\n  uint256 internal constant BORROW_CAP_MASK =                0x00000000000000000000000000000000000FFFFFFFFF00000000000000000000; // prettier-ignore\n  uint256 internal constant SUPPLY_CAP_MASK =                0x00000000000000000000000000FFFFFFFFF00000000000000000000000000000; // prettier-ignore\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK =  0x0000000000000000000000FFFF00000000000000000000000000000000000000; // prettier-ignore\n  //@notice there is an unoccupied hole of 8 bits from 168 to 176 left from pre 3.2 eModeCategory\n  uint256 internal constant UNBACKED_MINT_CAP_MASK =         0x00000000000FFFFFFFFF00000000000000000000000000000000000000000000; // prettier-ignore\n  uint256 internal constant DEBT_CEILING_MASK =              0x0FFFFFFFFFF00000000000000000000000000000000000000000000000000000; // prettier-ignore\n  uint256 internal constant VIRTUAL_ACC_ACTIVE_MASK =        0x1000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore\n\n  /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n  uint256 internal constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n  uint256 internal constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n  uint256 internal constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n  uint256 internal constant IS_ACTIVE_START_BIT_POSITION = 56;\n  uint256 internal constant IS_FROZEN_START_BIT_POSITION = 57;\n  uint256 internal constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n  uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60;\n  uint256 internal constant BORROWABLE_IN_ISOLATION_START_BIT_POSITION = 61;\n  uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62;\n  uint256 internal constant FLASHLOAN_ENABLED_START_BIT_POSITION = 63;\n  uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n  uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80;\n  uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116;\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152;\n  //@notice there is an unoccupied hole of 8 bits from 168 to 176 left from pre 3.2 eModeCategory\n  uint256 internal constant UNBACKED_MINT_CAP_START_BIT_POSITION = 176;\n  uint256 internal constant DEBT_CEILING_START_BIT_POSITION = 212;\n  uint256 internal constant VIRTUAL_ACC_START_BIT_POSITION = 252;\n\n  uint256 internal constant MAX_VALID_LTV = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n  uint256 internal constant MAX_VALID_DECIMALS = 255;\n  uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65535;\n  uint256 internal constant MAX_VALID_BORROW_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_SUPPLY_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65535;\n  uint256 internal constant MAX_VALID_UNBACKED_MINT_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_DEBT_CEILING = 1099511627775;\n\n  uint256 public constant DEBT_CEILING_DECIMALS = 2;\n  uint16 public constant MAX_RESERVES_COUNT = 128;\n\n  /**\n   * @notice 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.INVALID_LTV);\n\n    self.data = (self.data & ~LTV_MASK) | ltv;\n  }\n\n  /**\n   * @notice 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 memory self) internal pure returns (uint256) {\n    return self.data & LTV_MASK;\n  }\n\n  /**\n   * @notice Sets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @param threshold The new liquidation threshold\n   */\n  function setLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 threshold\n  ) internal pure {\n    require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD);\n\n    self.data =\n      (self.data & ~LIQUIDATION_THRESHOLD_MASK) |\n      (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation threshold\n   */\n  function getLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @param bonus The new liquidation bonus\n   */\n  function setLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 bonus\n  ) internal pure {\n    require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS);\n\n    self.data =\n      (self.data & ~LIQUIDATION_BONUS_MASK) |\n      (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation bonus\n   */\n  function getLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice 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(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 decimals\n  ) internal pure {\n    require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS);\n\n    self.data = (self.data & ~DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice 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(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice 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   * @notice Gets the active state of the reserve\n   * @param self The reserve configuration\n   * @return The active state\n   */\n  function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @notice 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   * @notice Gets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @return The frozen state\n   */\n  function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & FROZEN_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the paused state of the reserve\n   * @param self The reserve configuration\n   * @param paused The paused state\n   */\n  function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure {\n    self.data =\n      (self.data & ~PAUSED_MASK) |\n      (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the paused state of the reserve\n   * @param self The reserve configuration\n   * @return The paused state\n   */\n  function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & PAUSED_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the borrowable in isolation flag for the reserve.\n   * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed\n   * amount will be accumulated in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @param borrowable True if the asset is borrowable\n   */\n  function setBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool borrowable\n  ) internal pure {\n    self.data =\n      (self.data & ~BORROWABLE_IN_ISOLATION_MASK) |\n      (uint256(borrowable ? 1 : 0) << BORROWABLE_IN_ISOLATION_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowable in isolation flag for the reserve.\n   * @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with\n   * isolated collateral is accounted for in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @return The borrowable in isolation flag\n   */\n  function getBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & BORROWABLE_IN_ISOLATION_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @param siloed True if the asset is siloed\n   */\n  function setSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool siloed\n  ) internal pure {\n    self.data =\n      (self.data & ~SILOED_BORROWING_MASK) |\n      (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @return The siloed borrowing flag\n   */\n  function getSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & SILOED_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice 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(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool enabled\n  ) internal pure {\n    self.data =\n      (self.data & ~BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The borrowing state\n   */\n  function getBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @param reserveFactor The reserve factor\n   */\n  function setReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 reserveFactor\n  ) internal pure {\n    require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.INVALID_RESERVE_FACTOR);\n\n    self.data =\n      (self.data & ~RESERVE_FACTOR_MASK) |\n      (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @return The reserve factor\n   */\n  function getReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @param borrowCap The borrow cap\n   */\n  function setBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 borrowCap\n  ) internal pure {\n    require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.INVALID_BORROW_CAP);\n\n    self.data = (self.data & ~BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @return The borrow cap\n   */\n  function getBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @param supplyCap The supply cap\n   */\n  function setSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 supplyCap\n  ) internal pure {\n    require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.INVALID_SUPPLY_CAP);\n\n    self.data = (self.data & ~SUPPLY_CAP_MASK) | (supplyCap << SUPPLY_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @return The supply cap\n   */\n  function getSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the debt ceiling in isolation mode for the asset\n   * @param self The reserve configuration\n   * @param ceiling The maximum debt ceiling for the asset\n   */\n  function setDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 ceiling\n  ) internal pure {\n    require(ceiling <= MAX_VALID_DEBT_CEILING, Errors.INVALID_DEBT_CEILING);\n\n    self.data = (self.data & ~DEBT_CEILING_MASK) | (ceiling << DEBT_CEILING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the debt ceiling for the asset if the asset is in isolation mode\n   * @param self The reserve configuration\n   * @return The debt ceiling (0 = isolation mode disabled)\n   */\n  function getDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & DEBT_CEILING_MASK) >> DEBT_CEILING_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation protocol fee of the reserve\n   * @param self The reserve configuration\n   * @param liquidationProtocolFee The liquidation protocol fee\n   */\n  function setLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 liquidationProtocolFee\n  ) internal pure {\n    require(\n      liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE,\n      Errors.INVALID_LIQUIDATION_PROTOCOL_FEE\n    );\n\n    self.data =\n      (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK) |\n      (liquidationProtocolFee << LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the liquidation protocol fee\n   * @param self The reserve configuration\n   * @return The liquidation protocol fee\n   */\n  function getLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return\n      (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) >> LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @param unbackedMintCap The unbacked mint cap\n   */\n  function setUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 unbackedMintCap\n  ) internal pure {\n    require(unbackedMintCap <= MAX_VALID_UNBACKED_MINT_CAP, Errors.INVALID_UNBACKED_MINT_CAP);\n\n    self.data =\n      (self.data & ~UNBACKED_MINT_CAP_MASK) |\n      (unbackedMintCap << UNBACKED_MINT_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @return The unbacked mint cap\n   */\n  function getUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & UNBACKED_MINT_CAP_MASK) >> UNBACKED_MINT_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the flashloanable flag for the reserve\n   * @param self The reserve configuration\n   * @param flashLoanEnabled True if the asset is flashloanable, false otherwise\n   */\n  function setFlashLoanEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool flashLoanEnabled\n  ) internal pure {\n    self.data =\n      (self.data & ~FLASHLOAN_ENABLED_MASK) |\n      (uint256(flashLoanEnabled ? 1 : 0) << FLASHLOAN_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the flashloanable flag for the reserve\n   * @param self The reserve configuration\n   * @return The flashloanable flag\n   */\n  function getFlashLoanEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & FLASHLOAN_ENABLED_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the virtual account active/not state of the reserve\n   * @param self The reserve configuration\n   * @param active The active state\n   */\n  function setVirtualAccActive(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool active\n  ) internal pure {\n    self.data =\n      (self.data & ~VIRTUAL_ACC_ACTIVE_MASK) |\n      (uint256(active ? 1 : 0) << VIRTUAL_ACC_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the virtual account active/not state of the reserve\n   * @dev The state should be true for all normal assets and should be false\n   * Virtual accounting being disabled means that the asset:\n   * - is GHO\n   * - can never be supplied\n   * - the interest rate strategy is not influenced by the virtual balance\n   * @param self The reserve configuration\n   * @return The active state\n   */\n  function getIsVirtualAccActive(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & VIRTUAL_ACC_ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @notice Gets the configuration flags of the reserve\n   * @param self The reserve configuration\n   * @return The state flag representing active\n   * @return The state flag representing frozen\n   * @return The state flag representing borrowing enabled\n   * @return The state flag representing paused\n   */\n  function getFlags(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool, bool, bool, bool) {\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 & PAUSED_MASK) != 0\n    );\n  }\n\n  /**\n   * @notice Gets the configuration parameters of the reserve from storage\n   * @param self The reserve configuration\n   * @return The state param representing ltv\n   * @return The state param representing liquidation threshold\n   * @return The state param representing liquidation bonus\n   * @return The state param representing reserve decimals\n   * @return The state param representing reserve factor\n   */\n  function getParams(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, uint256, uint256, uint256, uint256) {\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   * @notice Gets the caps parameters of the reserve from storage\n   * @param self The reserve configuration\n   * @return The state param representing borrow cap\n   * @return The state param representing supply cap.\n   */\n  function getCaps(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, uint256) {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION,\n      (dataLocal & SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION\n    );\n  }\n}\n"},"src/contracts/protocol/libraries/logic/PoolLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\n\n/**\n * @title PoolLogic library\n * @author Aave\n * @notice Implements the logic for Pool specific functions\n */\nlibrary PoolLogic {\n  using GPv2SafeERC20 for IERC20;\n  using WadRayMath for uint256;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPool` for descriptions\n  event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @notice Initialize an asset reserve and add the reserve to the list of reserves\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param params Additional parameters needed for initiation\n   * @return true if appended, false if inserted at existing empty spot\n   */\n  function executeInitReserve(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.InitReserveParams memory params\n  ) external returns (bool) {\n    require(Address.isContract(params.asset), Errors.NOT_CONTRACT);\n    reservesData[params.asset].init(\n      params.aTokenAddress,\n      params.variableDebtAddress,\n      params.interestRateStrategyAddress\n    );\n\n    bool reserveAlreadyAdded = reservesData[params.asset].id != 0 ||\n      reservesList[0] == params.asset;\n    require(!reserveAlreadyAdded, Errors.RESERVE_ALREADY_ADDED);\n\n    for (uint16 i = 0; i < params.reservesCount; i++) {\n      if (reservesList[i] == address(0)) {\n        reservesData[params.asset].id = i;\n        reservesList[i] = params.asset;\n        return false;\n      }\n    }\n\n    require(params.reservesCount < params.maxNumberReserves, Errors.NO_MORE_RESERVES_ALLOWED);\n    reservesData[params.asset].id = params.reservesCount;\n    reservesList[params.reservesCount] = params.asset;\n    return true;\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 executeRescueTokens(address token, address to, uint256 amount) external {\n    IERC20(token).safeTransfer(to, amount);\n  }\n\n  /**\n   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n   * @param reservesData The state of all the reserves\n   * @param assets The list of reserves for which the minting needs to be executed\n   */\n  function executeMintToTreasury(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address[] calldata assets\n  ) external {\n    for (uint256 i = 0; i < assets.length; i++) {\n      address assetAddress = assets[i];\n\n      DataTypes.ReserveData storage reserve = reservesData[assetAddress];\n\n      // this cover both inactive reserves and invalid reserves since the flag will be 0 for both\n      if (!reserve.configuration.getActive()) {\n        continue;\n      }\n\n      uint256 accruedToTreasury = reserve.accruedToTreasury;\n\n      if (accruedToTreasury != 0) {\n        reserve.accruedToTreasury = 0;\n        uint256 normalizedIncome = reserve.getNormalizedIncome();\n        uint256 amountToMint = accruedToTreasury.rayMul(normalizedIncome);\n        IAToken(reserve.aTokenAddress).mintToTreasury(amountToMint, normalizedIncome);\n\n        emit MintedToTreasury(assetAddress, amountToMint);\n      }\n    }\n  }\n\n  /**\n   * @notice Resets the isolation mode total debt of the given asset to zero\n   * @dev It requires the given asset has zero debt ceiling\n   * @param reservesData The state of all the reserves\n   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n   */\n  function executeResetIsolationModeTotalDebt(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address asset\n  ) external {\n    require(reservesData[asset].configuration.getDebtCeiling() == 0, Errors.DEBT_CEILING_NOT_ZERO);\n    reservesData[asset].isolationModeTotalDebt = 0;\n    emit IsolationModeTotalDebtUpdated(asset, 0);\n  }\n\n  /**\n   * @notice Sets the liquidation grace period of the asset\n   * @param reservesData The state of all the reserves\n   * @param asset The address of the underlying asset to set the liquidationGracePeriod\n   * @param until Timestamp when the liquidation grace period will end\n   */\n  function executeSetLiquidationGracePeriod(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address asset,\n    uint40 until\n  ) external {\n    reservesData[asset].liquidationGracePeriodUntil = until;\n  }\n\n  /**\n   * @notice Drop a reserve\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function executeDropReserve(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    address asset\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[asset];\n    ValidationLogic.validateDropReserve(reservesList, reserve, asset);\n    reservesList[reservesData[asset].id] = address(0);\n    delete reservesData[asset];\n  }\n\n  /**\n   * @notice Returns the user account data across all the reserves\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional params needed for the calculation\n   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n   * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\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 executeGetUserAccountData(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.CalculateUserAccountDataParams memory params\n  )\n    external\n    view\n    returns (\n      uint256 totalCollateralBase,\n      uint256 totalDebtBase,\n      uint256 availableBorrowsBase,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    )\n  {\n    (\n      totalCollateralBase,\n      totalDebtBase,\n      ltv,\n      currentLiquidationThreshold,\n      healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(reservesData, reservesList, eModeCategories, params);\n\n    availableBorrowsBase = GenericLogic.calculateAvailableBorrows(\n      totalCollateralBase,\n      totalDebtBase,\n      ltv\n    );\n  }\n}\n"},"src/contracts/protocol/libraries/logic/ReserveLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.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';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.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 WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPool` for descriptions\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   * @notice Returns the ongoing normalized income for the reserve.\n   * @dev A value of 1e27 means there is no income. As time passes, the income is accrued\n   * @dev 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(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.liquidityIndex;\n    } else {\n      return\n        MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n          reserve.liquidityIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Returns the ongoing normalized variable debt for the reserve.\n   * @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued\n   * @dev 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(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.variableBorrowIndex;\n    } else {\n      return\n        MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n          reserve.variableBorrowIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Updates the liquidity cumulative index and the variable borrow index.\n   * @param reserve The reserve object\n   * @param reserveCache The caching layer for the reserve data\n   */\n  function updateState(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // If time didn't pass since last stored timestamp, skip state update\n    //solium-disable-next-line\n    if (reserveCache.reserveLastUpdateTimestamp == uint40(block.timestamp)) {\n      return;\n    }\n\n    _updateIndexes(reserve, reserveCache);\n    _accrueToTreasury(reserve, reserveCache);\n\n    //solium-disable-next-line\n    reserve.lastUpdateTimestamp = uint40(block.timestamp);\n    reserveCache.reserveLastUpdateTimestamp = uint40(block.timestamp);\n  }\n\n  /**\n   * @notice Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example\n   * to accumulate the flashloan fee to the reserve, and spread it between all the suppliers.\n   * @param reserve The reserve object\n   * @param totalLiquidity The total liquidity available in the reserve\n   * @param amount The amount to accumulate\n   * @return The next liquidity index of the reserve\n   */\n  function cumulateToLiquidityIndex(\n    DataTypes.ReserveData storage reserve,\n    uint256 totalLiquidity,\n    uint256 amount\n  ) internal returns (uint256) {\n    //next liquidity index is calculated this way: `((amount / totalLiquidity) + 1) * liquidityIndex`\n    //division `amount / totalLiquidity` done in ray for precision\n    uint256 result = (amount.wadToRay().rayDiv(totalLiquidity.wadToRay()) + WadRayMath.RAY).rayMul(\n      reserve.liquidityIndex\n    );\n    reserve.liquidityIndex = result.toUint128();\n    return result;\n  }\n\n  /**\n   * @notice Initializes a reserve.\n   * @param reserve The reserve object\n   * @param aTokenAddress The address of the overlying atoken contract\n   * @param variableDebtTokenAddress The address of the overlying variable debt token 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 variableDebtTokenAddress,\n    address interestRateStrategyAddress\n  ) internal {\n    require(reserve.aTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED);\n\n    reserve.liquidityIndex = uint128(WadRayMath.RAY);\n    reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n    reserve.aTokenAddress = aTokenAddress;\n    reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n    reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n  }\n\n  /**\n   * @notice Updates the reserve current variable borrow rate and the current liquidity rate.\n   * @param reserve The reserve reserve to be updated\n   * @param reserveCache The caching layer for the reserve data\n   * @param reserveAddress The address of the reserve to be updated\n   * @param liquidityAdded The amount of liquidity added to the protocol (supply or repay) in the previous action\n   * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n   */\n  function updateInterestRatesAndVirtualBalance(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    address reserveAddress,\n    uint256 liquidityAdded,\n    uint256 liquidityTaken\n  ) internal {\n    uint256 totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    (uint256 nextLiquidityRate, uint256 nextVariableRate) = IReserveInterestRateStrategy(\n      reserve.interestRateStrategyAddress\n    ).calculateInterestRates(\n        DataTypes.CalculateInterestRatesParams({\n          unbacked: reserve.unbacked + reserve.deficit,\n          liquidityAdded: liquidityAdded,\n          liquidityTaken: liquidityTaken,\n          totalDebt: totalVariableDebt,\n          reserveFactor: reserveCache.reserveFactor,\n          reserve: reserveAddress,\n          usingVirtualBalance: reserveCache.reserveConfiguration.getIsVirtualAccActive(),\n          virtualUnderlyingBalance: reserve.virtualUnderlyingBalance\n        })\n      );\n\n    reserve.currentLiquidityRate = nextLiquidityRate.toUint128();\n    reserve.currentVariableBorrowRate = nextVariableRate.toUint128();\n\n    // Only affect virtual balance if the reserve uses it\n    if (reserveCache.reserveConfiguration.getIsVirtualAccActive()) {\n      if (liquidityAdded > 0) {\n        reserve.virtualUnderlyingBalance += liquidityAdded.toUint128();\n      }\n      if (liquidityTaken > 0) {\n        reserve.virtualUnderlyingBalance -= liquidityTaken.toUint128();\n      }\n    }\n\n    emit ReserveDataUpdated(\n      reserveAddress,\n      nextLiquidityRate,\n      0,\n      nextVariableRate,\n      reserveCache.nextLiquidityIndex,\n      reserveCache.nextVariableBorrowIndex\n    );\n  }\n\n  /**\n   * @notice Mints part of the repaid interest to the reserve treasury as a function of the reserve factor for the\n   * specific asset.\n   * @param reserve The reserve to be updated\n   * @param reserveCache The caching layer for the reserve data\n   */\n  function _accrueToTreasury(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    if (reserveCache.reserveFactor == 0) {\n      return;\n    }\n\n    //calculate the total variable debt at moment of the last interaction\n    uint256 prevTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.currVariableBorrowIndex\n    );\n\n    //calculate the new total variable debt after accumulation of the interest on the index\n    uint256 currTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n    uint256 totalDebtAccrued = currTotalVariableDebt - prevTotalVariableDebt;\n\n    uint256 amountToMint = totalDebtAccrued.percentMul(reserveCache.reserveFactor);\n\n    if (amountToMint != 0) {\n      reserve.accruedToTreasury += amountToMint.rayDiv(reserveCache.nextLiquidityIndex).toUint128();\n    }\n  }\n\n  /**\n   * @notice Updates the reserve indexes and the timestamp of the update.\n   * @param reserve The reserve reserve to be updated\n   * @param reserveCache The cache layer holding the cached protocol data\n   */\n  function _updateIndexes(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // Only cumulating on the supply side if there is any income being produced\n    // The case of Reserve Factor 100% is not a problem (currentLiquidityRate == 0),\n    // as liquidity index should not be updated\n    if (reserveCache.currLiquidityRate != 0) {\n      uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(\n        reserveCache.currLiquidityRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextLiquidityIndex = cumulatedLiquidityInterest.rayMul(\n        reserveCache.currLiquidityIndex\n      );\n      reserve.liquidityIndex = reserveCache.nextLiquidityIndex.toUint128();\n    }\n\n    // Variable borrow index only gets updated if there is any variable debt.\n    // reserveCache.currVariableBorrowRate != 0 is not a correct validation,\n    // because a positive base variable rate can be stored on\n    // reserveCache.currVariableBorrowRate, but the index should not increase\n    if (reserveCache.currScaledVariableDebt != 0) {\n      uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(\n        reserveCache.currVariableBorrowRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(\n        reserveCache.currVariableBorrowIndex\n      );\n      reserve.variableBorrowIndex = reserveCache.nextVariableBorrowIndex.toUint128();\n    }\n  }\n\n  /**\n   * @notice Creates a cache object to avoid repeated storage reads and external contract calls when updating state and\n   * interest rates.\n   * @param reserve The reserve object for which the cache will be filled\n   * @return The cache object\n   */\n  function cache(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (DataTypes.ReserveCache memory) {\n    DataTypes.ReserveCache memory reserveCache;\n\n    reserveCache.reserveConfiguration = reserve.configuration;\n    reserveCache.reserveFactor = reserveCache.reserveConfiguration.getReserveFactor();\n    reserveCache.currLiquidityIndex = reserveCache.nextLiquidityIndex = reserve.liquidityIndex;\n    reserveCache.currVariableBorrowIndex = reserveCache.nextVariableBorrowIndex = reserve\n      .variableBorrowIndex;\n    reserveCache.currLiquidityRate = reserve.currentLiquidityRate;\n    reserveCache.currVariableBorrowRate = reserve.currentVariableBorrowRate;\n\n    reserveCache.aTokenAddress = reserve.aTokenAddress;\n    reserveCache.variableDebtTokenAddress = reserve.variableDebtTokenAddress;\n\n    reserveCache.reserveLastUpdateTimestamp = reserve.lastUpdateTimestamp;\n\n    reserveCache.currScaledVariableDebt = reserveCache.nextScaledVariableDebt = IVariableDebtToken(\n      reserveCache.variableDebtTokenAddress\n    ).scaledTotalSupply();\n\n    return reserveCache;\n  }\n}\n"},"src/contracts/protocol/libraries/logic/EModeLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\n/**\n * @title EModeLogic library\n * @author Aave\n * @notice Implements the base logic for all the actions related to the eMode\n */\nlibrary EModeLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n\n  // See `IPool` for descriptions\n  event UserEModeSet(address indexed user, uint8 categoryId);\n\n  /**\n   * @notice Updates the user efficiency mode category\n   * @dev Will revert if user is borrowing non-compatible asset or change will drop HF < HEALTH_FACTOR_LIQUIDATION_THRESHOLD\n   * @dev Emits the `UserEModeSet` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param usersEModeCategory The state of all users efficiency mode category\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the setUserEMode function\n   */\n  function executeSetUserEMode(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    mapping(address => uint8) storage usersEModeCategory,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteSetUserEModeParams memory params\n  ) external {\n    if (usersEModeCategory[msg.sender] == params.categoryId) return;\n\n    ValidationLogic.validateSetUserEMode(\n      eModeCategories,\n      userConfig,\n      params.reservesCount,\n      params.categoryId\n    );\n\n    usersEModeCategory[msg.sender] = params.categoryId;\n\n    ValidationLogic.validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      msg.sender,\n      params.categoryId,\n      params.reservesCount,\n      params.oracle\n    );\n    emit UserEModeSet(msg.sender, params.categoryId);\n  }\n}\n"},"src/contracts/protocol/libraries/logic/SupplyLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\n\n/**\n * @title SupplyLogic library\n * @author Aave\n * @notice Implements the base logic for supply/withdraw\n */\nlibrary SupplyLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n\n  // See `IPool` for descriptions\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n  event Supply(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @notice Implements the supply feature. Through `supply()`, users supply assets to the Aave protocol.\n   * @dev Emits the `Supply()` event.\n   * @dev In the first supply action, `ReserveUsedAsCollateralEnabled()` is emitted, if the asset can be enabled as\n   * collateral.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the supply function\n   */\n  function executeSupply(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteSupplyParams memory params\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    ValidationLogic.validateSupply(reserveCache, reserve, params.amount, params.onBehalfOf);\n\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, params.asset, params.amount, 0);\n\n    IERC20(params.asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, params.amount);\n\n    bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(\n      msg.sender,\n      params.onBehalfOf,\n      params.amount,\n      reserveCache.nextLiquidityIndex\n    );\n\n    if (isFirstSupply) {\n      if (\n        ValidationLogic.validateAutomaticUseAsCollateral(\n          reservesData,\n          reservesList,\n          userConfig,\n          reserveCache.reserveConfiguration,\n          reserveCache.aTokenAddress\n        )\n      ) {\n        userConfig.setUsingAsCollateral(reserve.id, true);\n        emit ReserveUsedAsCollateralEnabled(params.asset, params.onBehalfOf);\n      }\n    }\n\n    emit Supply(params.asset, msg.sender, params.onBehalfOf, params.amount, params.referralCode);\n  }\n\n  /**\n   * @notice Implements the withdraw feature. Through `withdraw()`, users redeem their aTokens for the underlying asset\n   * previously supplied in the Aave protocol.\n   * @dev Emits the `Withdraw()` event.\n   * @dev If the user withdraws everything, `ReserveUsedAsCollateralDisabled()` is emitted.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the withdraw function\n   * @return The actual amount withdrawn\n   */\n  function executeWithdraw(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteWithdrawParams memory params\n  ) external returns (uint256) {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    require(params.to != reserveCache.aTokenAddress, Errors.WITHDRAW_TO_ATOKEN);\n\n    reserve.updateState(reserveCache);\n\n    uint256 userBalance = IAToken(reserveCache.aTokenAddress).scaledBalanceOf(msg.sender).rayMul(\n      reserveCache.nextLiquidityIndex\n    );\n\n    uint256 amountToWithdraw = params.amount;\n\n    if (params.amount == type(uint256).max) {\n      amountToWithdraw = userBalance;\n    }\n\n    ValidationLogic.validateWithdraw(reserveCache, amountToWithdraw, userBalance);\n\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, params.asset, 0, amountToWithdraw);\n\n    bool isCollateral = userConfig.isUsingAsCollateral(reserve.id);\n\n    if (isCollateral && amountToWithdraw == userBalance) {\n      userConfig.setUsingAsCollateral(reserve.id, false);\n      emit ReserveUsedAsCollateralDisabled(params.asset, msg.sender);\n    }\n\n    IAToken(reserveCache.aTokenAddress).burn(\n      msg.sender,\n      params.to,\n      amountToWithdraw,\n      reserveCache.nextLiquidityIndex\n    );\n\n    if (isCollateral && userConfig.isBorrowingAny()) {\n      ValidationLogic.validateHFAndLtv(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        userConfig,\n        params.asset,\n        msg.sender,\n        params.reservesCount,\n        params.oracle,\n        params.userEModeCategory\n      );\n    }\n\n    emit Withdraw(params.asset, msg.sender, params.to, amountToWithdraw);\n\n    return amountToWithdraw;\n  }\n\n  /**\n   * @notice Validates a transfer of aTokens. The sender is subjected to health factor validation to avoid\n   * collateralization constraints violation.\n   * @dev Emits the `ReserveUsedAsCollateralEnabled()` event for the `to` account, if the asset is being activated as\n   * collateral.\n   * @dev In case the `from` user transfers everything, `ReserveUsedAsCollateralDisabled()` is emitted for `from`.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the finalizeTransfer function\n   */\n  function executeFinalizeTransfer(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n    DataTypes.FinalizeTransferParams memory params\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n\n    ValidationLogic.validateTransfer(reserve);\n\n    uint256 reserveId = reserve.id;\n    uint256 scaledAmount = params.amount.rayDiv(reserve.getNormalizedIncome());\n\n    if (params.from != params.to && scaledAmount != 0) {\n      DataTypes.UserConfigurationMap storage fromConfig = usersConfig[params.from];\n\n      if (fromConfig.isUsingAsCollateral(reserveId)) {\n        if (fromConfig.isBorrowingAny()) {\n          ValidationLogic.validateHFAndLtv(\n            reservesData,\n            reservesList,\n            eModeCategories,\n            usersConfig[params.from],\n            params.asset,\n            params.from,\n            params.reservesCount,\n            params.oracle,\n            params.fromEModeCategory\n          );\n        }\n        if (params.balanceFromBefore == params.amount) {\n          fromConfig.setUsingAsCollateral(reserveId, false);\n          emit ReserveUsedAsCollateralDisabled(params.asset, params.from);\n        }\n      }\n\n      if (params.balanceToBefore == 0) {\n        DataTypes.UserConfigurationMap storage toConfig = usersConfig[params.to];\n        if (\n          ValidationLogic.validateAutomaticUseAsCollateral(\n            reservesData,\n            reservesList,\n            toConfig,\n            reserve.configuration,\n            reserve.aTokenAddress\n          )\n        ) {\n          toConfig.setUsingAsCollateral(reserveId, true);\n          emit ReserveUsedAsCollateralEnabled(params.asset, params.to);\n        }\n      }\n    }\n  }\n\n  /**\n   * @notice Executes the 'set as collateral' feature. A user can choose to activate or deactivate an asset as\n   * collateral at any point in time. Deactivating an asset as collateral is subjected to the usual health factor\n   * checks to ensure collateralization.\n   * @dev Emits the `ReserveUsedAsCollateralEnabled()` event if the asset can be activated as collateral.\n   * @dev In case the asset is being deactivated as collateral, `ReserveUsedAsCollateralDisabled()` is emitted.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param asset The address of the asset being configured as collateral\n   * @param useAsCollateral True if the user wants to set the asset as collateral, false otherwise\n   * @param reservesCount The number of initialized reserves\n   * @param priceOracle The address of the price oracle\n   * @param userEModeCategory The eMode category chosen by the user\n   */\n  function executeUseReserveAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage userConfig,\n    address asset,\n    bool useAsCollateral,\n    uint256 reservesCount,\n    address priceOracle,\n    uint8 userEModeCategory\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    uint256 userBalance = IERC20(reserveCache.aTokenAddress).balanceOf(msg.sender);\n\n    ValidationLogic.validateSetUseReserveAsCollateral(reserveCache, userBalance);\n\n    if (useAsCollateral == userConfig.isUsingAsCollateral(reserve.id)) return;\n\n    if (useAsCollateral) {\n      require(\n        ValidationLogic.validateUseAsCollateral(\n          reservesData,\n          reservesList,\n          userConfig,\n          reserveCache.reserveConfiguration\n        ),\n        Errors.USER_IN_ISOLATION_MODE_OR_LTV_ZERO\n      );\n\n      userConfig.setUsingAsCollateral(reserve.id, true);\n      emit ReserveUsedAsCollateralEnabled(asset, msg.sender);\n    } else {\n      userConfig.setUsingAsCollateral(reserve.id, false);\n      ValidationLogic.validateHFAndLtv(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        userConfig,\n        asset,\n        msg.sender,\n        reservesCount,\n        priceOracle,\n        userEModeCategory\n      );\n\n      emit ReserveUsedAsCollateralDisabled(asset, msg.sender);\n    }\n  }\n}\n"},"src/contracts/protocol/libraries/logic/FlashLoanLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {IFlashLoanReceiver} from '../../../misc/flashloan/interfaces/IFlashLoanReceiver.sol';\nimport {IFlashLoanSimpleReceiver} from '../../../misc/flashloan/interfaces/IFlashLoanSimpleReceiver.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {BorrowLogic} from './BorrowLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\n/**\n * @title FlashLoanLogic library\n * @author Aave\n * @notice Implements the logic for the flash loans\n */\nlibrary FlashLoanLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event FlashLoan(\n    address indexed target,\n    address initiator,\n    address indexed asset,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 premium,\n    uint16 indexed referralCode\n  );\n\n  // Helper struct for internal variables used in the `executeFlashLoan` function\n  struct FlashLoanLocalVars {\n    IFlashLoanReceiver receiver;\n    address currentAsset;\n    uint256 currentAmount;\n    uint256[] totalPremiums;\n    uint256 flashloanPremiumTotal;\n    uint256 flashloanPremiumToProtocol;\n  }\n\n  /**\n   * @notice Implements the flashloan feature that allow users to access liquidity of the pool for one transaction\n   * as long as the amount taken plus fee is returned or debt is opened.\n   * @dev For authorized flashborrowers the fee is waived\n   * @dev At the end of the transaction the pool will pull amount borrowed + fee from the receiver,\n   * if the receiver have not approved the pool the transaction will revert.\n   * @dev Emits the `FlashLoan()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the flashloan function\n   */\n  function executeFlashLoan(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.FlashloanParams memory params\n  ) external {\n    // The usual action flow (cache -> updateState -> validation -> changeState -> updateRates)\n    // is altered to (validation -> user payload -> cache -> updateState -> changeState -> updateRates) for flashloans.\n    // This is done to protect against reentrance and rate manipulation within the user specified payload.\n\n    ValidationLogic.validateFlashloan(reservesData, params.assets, params.amounts);\n\n    FlashLoanLocalVars memory vars;\n\n    vars.totalPremiums = new uint256[](params.assets.length);\n\n    vars.receiver = IFlashLoanReceiver(params.receiverAddress);\n    (vars.flashloanPremiumTotal, vars.flashloanPremiumToProtocol) = params.isAuthorizedFlashBorrower\n      ? (0, 0)\n      : (params.flashLoanPremiumTotal, params.flashLoanPremiumToProtocol);\n\n    for (uint256 i = 0; i < params.assets.length; i++) {\n      vars.currentAmount = params.amounts[i];\n      vars.totalPremiums[i] = DataTypes.InterestRateMode(params.interestRateModes[i]) ==\n        DataTypes.InterestRateMode.NONE\n        ? vars.currentAmount.percentMul(vars.flashloanPremiumTotal)\n        : 0;\n\n      if (reservesData[params.assets[i]].configuration.getIsVirtualAccActive()) {\n        reservesData[params.assets[i]].virtualUnderlyingBalance -= vars.currentAmount.toUint128();\n      }\n\n      IAToken(reservesData[params.assets[i]].aTokenAddress).transferUnderlyingTo(\n        params.receiverAddress,\n        vars.currentAmount\n      );\n    }\n\n    require(\n      vars.receiver.executeOperation(\n        params.assets,\n        params.amounts,\n        vars.totalPremiums,\n        msg.sender,\n        params.params\n      ),\n      Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN\n    );\n\n    for (uint256 i = 0; i < params.assets.length; i++) {\n      vars.currentAsset = params.assets[i];\n      vars.currentAmount = params.amounts[i];\n\n      if (\n        DataTypes.InterestRateMode(params.interestRateModes[i]) == DataTypes.InterestRateMode.NONE\n      ) {\n        _handleFlashLoanRepayment(\n          reservesData[vars.currentAsset],\n          DataTypes.FlashLoanRepaymentParams({\n            asset: vars.currentAsset,\n            receiverAddress: params.receiverAddress,\n            amount: vars.currentAmount,\n            totalPremium: vars.totalPremiums[i],\n            flashLoanPremiumToProtocol: vars.flashloanPremiumToProtocol,\n            referralCode: params.referralCode\n          })\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        BorrowLogic.executeBorrow(\n          reservesData,\n          reservesList,\n          eModeCategories,\n          userConfig,\n          DataTypes.ExecuteBorrowParams({\n            asset: vars.currentAsset,\n            user: msg.sender,\n            onBehalfOf: params.onBehalfOf,\n            amount: vars.currentAmount,\n            interestRateMode: DataTypes.InterestRateMode(params.interestRateModes[i]),\n            referralCode: params.referralCode,\n            releaseUnderlying: false,\n            reservesCount: IPool(params.pool).getReservesCount(),\n            oracle: IPoolAddressesProvider(params.addressesProvider).getPriceOracle(),\n            userEModeCategory: IPool(params.pool).getUserEMode(params.onBehalfOf).toUint8(),\n            priceOracleSentinel: IPoolAddressesProvider(params.addressesProvider)\n              .getPriceOracleSentinel()\n          })\n        );\n        // no premium is paid when taking on the flashloan as debt\n        emit FlashLoan(\n          params.receiverAddress,\n          msg.sender,\n          vars.currentAsset,\n          vars.currentAmount,\n          DataTypes.InterestRateMode(params.interestRateModes[i]),\n          0,\n          params.referralCode\n        );\n      }\n    }\n  }\n\n  /**\n   * @notice Implements the simple flashloan feature that allow users to access liquidity of ONE reserve for one\n   * transaction as long as the amount taken plus fee is returned.\n   * @dev Does not waive fee for approved flashborrowers nor allow taking on debt instead of repaying to save gas\n   * @dev At the end of the transaction the pool will pull amount borrowed + fee from the receiver,\n   * if the receiver have not approved the pool the transaction will revert.\n   * @dev Emits the `FlashLoan()` event\n   * @param reserve The state of the flashloaned reserve\n   * @param params The additional parameters needed to execute the simple flashloan function\n   */\n  function executeFlashLoanSimple(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.FlashloanSimpleParams memory params\n  ) external {\n    // The usual action flow (cache -> updateState -> validation -> changeState -> updateRates)\n    // is altered to (validation -> user payload -> cache -> updateState -> changeState -> updateRates) for flashloans.\n    // This is done to protect against reentrance and rate manipulation within the user specified payload.\n\n    ValidationLogic.validateFlashloanSimple(reserve, params.amount);\n\n    IFlashLoanSimpleReceiver receiver = IFlashLoanSimpleReceiver(params.receiverAddress);\n    uint256 totalPremium = params.amount.percentMul(params.flashLoanPremiumTotal);\n\n    if (reserve.configuration.getIsVirtualAccActive()) {\n      reserve.virtualUnderlyingBalance -= params.amount.toUint128();\n    }\n\n    IAToken(reserve.aTokenAddress).transferUnderlyingTo(params.receiverAddress, params.amount);\n\n    require(\n      receiver.executeOperation(\n        params.asset,\n        params.amount,\n        totalPremium,\n        msg.sender,\n        params.params\n      ),\n      Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN\n    );\n\n    _handleFlashLoanRepayment(\n      reserve,\n      DataTypes.FlashLoanRepaymentParams({\n        asset: params.asset,\n        receiverAddress: params.receiverAddress,\n        amount: params.amount,\n        totalPremium: totalPremium,\n        flashLoanPremiumToProtocol: params.flashLoanPremiumToProtocol,\n        referralCode: params.referralCode\n      })\n    );\n  }\n\n  /**\n   * @notice Handles repayment of flashloaned assets + premium\n   * @dev Will pull the amount + premium from the receiver, so must have approved pool\n   * @param reserve The state of the flashloaned reserve\n   * @param params The additional parameters needed to execute the repayment function\n   */\n  function _handleFlashLoanRepayment(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.FlashLoanRepaymentParams memory params\n  ) internal {\n    uint256 premiumToProtocol = params.totalPremium.percentMul(params.flashLoanPremiumToProtocol);\n    uint256 premiumToLP = params.totalPremium - premiumToProtocol;\n    uint256 amountPlusPremium = params.amount + params.totalPremium;\n\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n    reserveCache.nextLiquidityIndex = reserve.cumulateToLiquidityIndex(\n      IERC20(reserveCache.aTokenAddress).totalSupply() +\n        uint256(reserve.accruedToTreasury).rayMul(reserveCache.nextLiquidityIndex),\n      premiumToLP\n    );\n\n    reserve.accruedToTreasury += premiumToProtocol\n      .rayDiv(reserveCache.nextLiquidityIndex)\n      .toUint128();\n\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, params.asset, amountPlusPremium, 0);\n\n    IERC20(params.asset).safeTransferFrom(\n      params.receiverAddress,\n      reserveCache.aTokenAddress,\n      amountPlusPremium\n    );\n\n    IAToken(reserveCache.aTokenAddress).handleRepayment(\n      params.receiverAddress,\n      params.receiverAddress,\n      amountPlusPremium\n    );\n\n    emit FlashLoan(\n      params.receiverAddress,\n      msg.sender,\n      params.asset,\n      params.amount,\n      DataTypes.InterestRateMode.NONE,\n      params.totalPremium,\n      params.referralCode\n    );\n  }\n}\n"},"src/contracts/protocol/libraries/logic/BorrowLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {IsolationModeLogic} from './IsolationModeLogic.sol';\n\n/**\n * @title BorrowLogic library\n * @author Aave\n * @notice Implements the base logic for all the actions related to borrowing\n */\nlibrary BorrowLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 borrowRate,\n    uint16 indexed referralCode\n  );\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount,\n    bool useATokens\n  );\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n  /**\n   * @notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the\n   * Aave protocol proportionally to their collateralization power. For isolated positions, it also increases the\n   * isolated debt.\n   * @dev  Emits the `Borrow()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the borrow function\n   */\n  function executeBorrow(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteBorrowParams memory params\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    (\n      bool isolationModeActive,\n      address isolationModeCollateralAddress,\n      uint256 isolationModeDebtCeiling\n    ) = userConfig.getIsolationModeState(reservesData, reservesList);\n\n    ValidationLogic.validateBorrow(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.ValidateBorrowParams({\n        reserveCache: reserveCache,\n        userConfig: userConfig,\n        asset: params.asset,\n        userAddress: params.onBehalfOf,\n        amount: params.amount,\n        interestRateMode: params.interestRateMode,\n        reservesCount: params.reservesCount,\n        oracle: params.oracle,\n        userEModeCategory: params.userEModeCategory,\n        priceOracleSentinel: params.priceOracleSentinel,\n        isolationModeActive: isolationModeActive,\n        isolationModeCollateralAddress: isolationModeCollateralAddress,\n        isolationModeDebtCeiling: isolationModeDebtCeiling\n      })\n    );\n\n    bool isFirstBorrowing = false;\n\n    (isFirstBorrowing, reserveCache.nextScaledVariableDebt) = IVariableDebtToken(\n      reserveCache.variableDebtTokenAddress\n    ).mint(params.user, params.onBehalfOf, params.amount, reserveCache.nextVariableBorrowIndex);\n\n    if (isFirstBorrowing) {\n      userConfig.setBorrowing(reserve.id, true);\n    }\n\n    if (isolationModeActive) {\n      uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n        .isolationModeTotalDebt += (params.amount /\n        10 **\n          (reserveCache.reserveConfiguration.getDecimals() -\n            ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128();\n      emit IsolationModeTotalDebtUpdated(\n        isolationModeCollateralAddress,\n        nextIsolationModeTotalDebt\n      );\n    }\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      0,\n      params.releaseUnderlying ? params.amount : 0\n    );\n\n    if (params.releaseUnderlying) {\n      IAToken(reserveCache.aTokenAddress).transferUnderlyingTo(params.user, params.amount);\n    }\n\n    emit Borrow(\n      params.asset,\n      params.user,\n      params.onBehalfOf,\n      params.amount,\n      DataTypes.InterestRateMode.VARIABLE,\n      reserve.currentVariableBorrowRate,\n      params.referralCode\n    );\n  }\n\n  /**\n   * @notice Implements the repay feature. Repaying transfers the underlying back to the aToken and clears the\n   * equivalent amount of debt for the user by burning the corresponding debt token. For isolated positions, it also\n   * reduces the isolated debt.\n   * @dev  Emits the `Repay()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the repay function\n   * @return The actual amount being repaid\n   */\n  function executeRepay(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteRepayParams memory params\n  ) external returns (uint256) {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n\n    uint256 variableDebt = IERC20(reserveCache.variableDebtTokenAddress).balanceOf(\n      params.onBehalfOf\n    );\n\n    ValidationLogic.validateRepay(\n      reserveCache,\n      params.amount,\n      params.interestRateMode,\n      params.onBehalfOf,\n      variableDebt\n    );\n\n    uint256 paybackAmount = variableDebt;\n\n    // Allows a user to repay with aTokens without leaving dust from interest.\n    if (params.useATokens && params.amount == type(uint256).max) {\n      params.amount = IAToken(reserveCache.aTokenAddress).balanceOf(msg.sender);\n    }\n\n    if (params.amount < paybackAmount) {\n      paybackAmount = params.amount;\n    }\n\n    reserveCache.nextScaledVariableDebt = IVariableDebtToken(reserveCache.variableDebtTokenAddress)\n      .burn(params.onBehalfOf, paybackAmount, reserveCache.nextVariableBorrowIndex);\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      params.useATokens ? 0 : paybackAmount,\n      0\n    );\n\n    if (variableDebt - paybackAmount == 0) {\n      userConfig.setBorrowing(reserve.id, false);\n    }\n\n    IsolationModeLogic.updateIsolatedDebtIfIsolated(\n      reservesData,\n      reservesList,\n      userConfig,\n      reserveCache,\n      paybackAmount\n    );\n\n    // in case of aToken repayment the msg.sender must always repay on behalf of itself\n    if (params.useATokens) {\n      IAToken(reserveCache.aTokenAddress).burn(\n        msg.sender,\n        reserveCache.aTokenAddress,\n        paybackAmount,\n        reserveCache.nextLiquidityIndex\n      );\n      bool isCollateral = userConfig.isUsingAsCollateral(reserve.id);\n      if (isCollateral && IAToken(reserveCache.aTokenAddress).scaledBalanceOf(msg.sender) == 0) {\n        userConfig.setUsingAsCollateral(reserve.id, false);\n        emit ReserveUsedAsCollateralDisabled(params.asset, msg.sender);\n      }\n    } else {\n      IERC20(params.asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, paybackAmount);\n      IAToken(reserveCache.aTokenAddress).handleRepayment(\n        msg.sender,\n        params.onBehalfOf,\n        paybackAmount\n      );\n    }\n\n    emit Repay(params.asset, params.onBehalfOf, msg.sender, paybackAmount, params.useATokens);\n\n    return paybackAmount;\n  }\n}\n"},"src/contracts/protocol/libraries/logic/LiquidationLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts//IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {PercentageMath} from '../../libraries/math/PercentageMath.sol';\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\nimport {DataTypes} from '../../libraries/types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {IsolationModeLogic} from './IsolationModeLogic.sol';\nimport {UserConfiguration} from '../../libraries/configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../../libraries/configuration/ReserveConfiguration.sol';\nimport {EModeConfiguration} from '../../libraries/configuration/EModeConfiguration.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {Errors} from '../helpers/Errors.sol';\n\ninterface IGhoVariableDebtToken {\n  function getBalanceFromInterest(address user) external view returns (uint256);\n}\n\n/**\n * @title LiquidationLogic library\n * @author Aave\n * @notice Implements actions involving management of collateral in the protocol, the main one being the liquidations\n */\nlibrary LiquidationLogic {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using GPv2SafeERC20 for IERC20;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n  event DeficitCreated(address indexed user, address indexed debtAsset, uint256 amountCreated);\n  event DeficitCovered(address indexed reserve, address caller, uint256 amountCovered);\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 Default percentage of borrower's debt to be repaid in a liquidation.\n   * @dev Percentage applied when the users health factor is above `CLOSE_FACTOR_HF_THRESHOLD`\n   * Expressed in bps, a value of 0.5e4 results in 50.00%\n   */\n  uint256 internal constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 0.5e4;\n\n  /**\n   * @dev This constant represents the upper bound on the health factor, below(inclusive) which the full amount of debt becomes liquidatable.\n   * A value of 0.95e18 results in 0.95\n   */\n  uint256 public constant CLOSE_FACTOR_HF_THRESHOLD = 0.95e18;\n\n  /**\n   * @dev This constant represents a base value threshold.\n   * If the total collateral or debt on a position is below this threshold, the close factor is raised to 100%.\n   * @notice The default value assumes that the basePrice is usd denominated by 8 decimals and needs to be adjusted in a non USD-denominated pool.\n   */\n  uint256 public constant MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD = 2000e8;\n\n  /**\n   * @dev This constant represents the minimum amount of assets in base currency that need to be leftover after a liquidation, if not clearing a position completely.\n   * This parameter is inferred from MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD as the logic is dependent.\n   * Assuming a MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD of `n` a liquidation of `n+1` might result in `n/2` leftover which is assumed to be still economically liquidatable.\n   * This mechanic was introduced to ensure liquidators don't optimize gas by leaving some wei on the liquidation.\n   */\n  uint256 public constant MIN_LEFTOVER_BASE = MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD / 2;\n\n  /**\n   * @notice Reduces a portion or all of the deficit of a specified reserve by burning:\n   * - the equivalent aToken `amount` for assets with virtual accounting enabled\n   * - the equivalent `amount` of underlying for assets with virtual accounting disabled (e.g. GHO)\n   * The caller of this method MUST always be the Umbrella contract and the Umbrella contract is assumed to never have debt.\n   * @dev Emits the `DeficitCovered() event`.\n   * @dev If the coverage admin covers its entire balance, `ReserveUsedAsCollateralDisabled()` is emitted.\n   * @param reservesData The state of all the reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the eliminateDeficit function\n   */\n  function executeEliminateDeficit(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteEliminateDeficitParams memory params\n  ) external {\n    require(params.amount != 0, Errors.INVALID_AMOUNT);\n\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    uint256 currentDeficit = reserve.deficit;\n\n    require(currentDeficit != 0, Errors.RESERVE_NOT_IN_DEFICIT);\n    require(!userConfig.isBorrowingAny(), Errors.USER_CANNOT_HAVE_DEBT);\n\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n    bool isActive = reserveCache.reserveConfiguration.getActive();\n    require(isActive, Errors.RESERVE_INACTIVE);\n\n    uint256 balanceWriteOff = params.amount;\n\n    if (params.amount > currentDeficit) {\n      balanceWriteOff = currentDeficit;\n    }\n\n    uint256 userBalance = reserveCache.reserveConfiguration.getIsVirtualAccActive()\n      ? IAToken(reserveCache.aTokenAddress).scaledBalanceOf(msg.sender).rayMul(\n        reserveCache.nextLiquidityIndex\n      )\n      : IERC20(params.asset).balanceOf(msg.sender);\n    require(balanceWriteOff <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n    if (reserveCache.reserveConfiguration.getIsVirtualAccActive()) {\n      // assets without virtual accounting can never be a collateral\n      bool isCollateral = userConfig.isUsingAsCollateral(reserve.id);\n      if (isCollateral && balanceWriteOff == userBalance) {\n        userConfig.setUsingAsCollateral(reserve.id, false);\n        emit ReserveUsedAsCollateralDisabled(params.asset, msg.sender);\n      }\n\n      IAToken(reserveCache.aTokenAddress).burn(\n        msg.sender,\n        reserveCache.aTokenAddress,\n        balanceWriteOff,\n        reserveCache.nextLiquidityIndex\n      );\n    } else {\n      // This is a special case to allow mintable assets (ex. GHO), which by definition cannot be supplied\n      // and thus do not use virtual underlying balances.\n      // In that case, the procedure is 1) sending the underlying asset to the aToken and\n      // 2) trigger the handleRepayment() for the aToken to dispose of those assets\n      IERC20(params.asset).safeTransferFrom(\n        msg.sender,\n        reserveCache.aTokenAddress,\n        balanceWriteOff\n      );\n      // it is assumed that handleRepayment does not touch the variable debt balance\n      IAToken(reserveCache.aTokenAddress).handleRepayment(\n        msg.sender,\n        // In the context of GHO it's only relevant that the address has no debt.\n        // Passing the pool is fitting as it's handling the repayment on behalf of the protocol.\n        address(this),\n        balanceWriteOff\n      );\n    }\n\n    reserve.deficit -= balanceWriteOff.toUint128();\n\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, params.asset, 0, 0);\n\n    emit DeficitCovered(params.asset, msg.sender, balanceWriteOff);\n  }\n\n  struct LiquidationCallLocalVars {\n    uint256 userCollateralBalance;\n    uint256 userReserveDebt;\n    uint256 actualDebtToLiquidate;\n    uint256 actualCollateralToLiquidate;\n    uint256 liquidationBonus;\n    uint256 healthFactor;\n    uint256 liquidationProtocolFeeAmount;\n    uint256 totalCollateralInBaseCurrency;\n    uint256 totalDebtInBaseCurrency;\n    uint256 collateralToLiquidateInBaseCurrency;\n    uint256 userReserveDebtInBaseCurrency;\n    uint256 userReserveCollateralInBaseCurrency;\n    uint256 collateralAssetPrice;\n    uint256 debtAssetPrice;\n    uint256 collateralAssetUnit;\n    uint256 debtAssetUnit;\n    IAToken collateralAToken;\n    DataTypes.ReserveCache debtReserveCache;\n  }\n\n  /**\n   * @notice Function to liquidate a position if its Health Factor drops below 1. The caller (liquidator)\n   * covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   * a proportional amount of the `collateralAsset` plus a bonus to cover market risk\n   * @dev Emits the `LiquidationCall()` event, and the `DeficitCreated()` event if the liquidation results in bad debt\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params The additional parameters needed to execute the liquidation function\n   */\n  function executeLiquidationCall(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ExecuteLiquidationCallParams memory params\n  ) external {\n    LiquidationCallLocalVars memory vars;\n\n    DataTypes.ReserveData storage collateralReserve = reservesData[params.collateralAsset];\n    DataTypes.ReserveData storage debtReserve = reservesData[params.debtAsset];\n    DataTypes.UserConfigurationMap storage userConfig = usersConfig[params.user];\n    vars.debtReserveCache = debtReserve.cache();\n    debtReserve.updateState(vars.debtReserveCache);\n\n    (\n      vars.totalCollateralInBaseCurrency,\n      vars.totalDebtInBaseCurrency,\n      ,\n      ,\n      vars.healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.CalculateUserAccountDataParams({\n        userConfig: userConfig,\n        reservesCount: params.reservesCount,\n        user: params.user,\n        oracle: params.priceOracle,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    vars.collateralAToken = IAToken(collateralReserve.aTokenAddress);\n    vars.userCollateralBalance = vars.collateralAToken.balanceOf(params.user);\n    vars.userReserveDebt = IERC20(vars.debtReserveCache.variableDebtTokenAddress).balanceOf(\n      params.user\n    );\n\n    ValidationLogic.validateLiquidationCall(\n      userConfig,\n      collateralReserve,\n      debtReserve,\n      DataTypes.ValidateLiquidationCallParams({\n        debtReserveCache: vars.debtReserveCache,\n        totalDebt: vars.userReserveDebt,\n        healthFactor: vars.healthFactor,\n        priceOracleSentinel: params.priceOracleSentinel\n      })\n    );\n\n    if (\n      params.userEModeCategory != 0 &&\n      EModeConfiguration.isReserveEnabledOnBitmap(\n        eModeCategories[params.userEModeCategory].collateralBitmap,\n        collateralReserve.id\n      )\n    ) {\n      vars.liquidationBonus = eModeCategories[params.userEModeCategory].liquidationBonus;\n    } else {\n      vars.liquidationBonus = collateralReserve.configuration.getLiquidationBonus();\n    }\n    vars.collateralAssetPrice = IPriceOracleGetter(params.priceOracle).getAssetPrice(\n      params.collateralAsset\n    );\n    vars.debtAssetPrice = IPriceOracleGetter(params.priceOracle).getAssetPrice(params.debtAsset);\n    vars.collateralAssetUnit = 10 ** collateralReserve.configuration.getDecimals();\n    vars.debtAssetUnit = 10 ** vars.debtReserveCache.reserveConfiguration.getDecimals();\n\n    vars.userReserveDebtInBaseCurrency =\n      (vars.userReserveDebt * vars.debtAssetPrice) /\n      vars.debtAssetUnit;\n\n    vars.userReserveCollateralInBaseCurrency =\n      (vars.userCollateralBalance * vars.collateralAssetPrice) /\n      vars.collateralAssetUnit;\n\n    // by default whole debt in the reserve could be liquidated\n    uint256 maxLiquidatableDebt = vars.userReserveDebt;\n    // but if debt and collateral is above or equal MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD\n    // and health factor is above CLOSE_FACTOR_HF_THRESHOLD this amount may be adjusted\n    if (\n      vars.userReserveCollateralInBaseCurrency >= MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD &&\n      vars.userReserveDebtInBaseCurrency >= MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD &&\n      vars.healthFactor > CLOSE_FACTOR_HF_THRESHOLD\n    ) {\n      uint256 totalDefaultLiquidatableDebtInBaseCurrency = vars.totalDebtInBaseCurrency.percentMul(\n        DEFAULT_LIQUIDATION_CLOSE_FACTOR\n      );\n\n      // if the debt is more then DEFAULT_LIQUIDATION_CLOSE_FACTOR % of the whole,\n      // then we CAN liquidate only up to DEFAULT_LIQUIDATION_CLOSE_FACTOR %\n      if (vars.userReserveDebtInBaseCurrency > totalDefaultLiquidatableDebtInBaseCurrency) {\n        maxLiquidatableDebt =\n          (totalDefaultLiquidatableDebtInBaseCurrency * vars.debtAssetUnit) /\n          vars.debtAssetPrice;\n      }\n    }\n\n    vars.actualDebtToLiquidate = params.debtToCover > maxLiquidatableDebt\n      ? maxLiquidatableDebt\n      : params.debtToCover;\n\n    (\n      vars.actualCollateralToLiquidate,\n      vars.actualDebtToLiquidate,\n      vars.liquidationProtocolFeeAmount,\n      vars.collateralToLiquidateInBaseCurrency\n    ) = _calculateAvailableCollateralToLiquidate(\n      collateralReserve.configuration,\n      vars.collateralAssetPrice,\n      vars.collateralAssetUnit,\n      vars.debtAssetPrice,\n      vars.debtAssetUnit,\n      vars.actualDebtToLiquidate,\n      vars.userCollateralBalance,\n      vars.liquidationBonus\n    );\n\n    // to prevent accumulation of dust on the protocol, it is enforced that you either\n    // 1. liquidate all debt\n    // 2. liquidate all collateral\n    // 3. leave more than MIN_LEFTOVER_BASE of collateral & debt\n    if (\n      vars.actualDebtToLiquidate < vars.userReserveDebt &&\n      vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount <\n      vars.userCollateralBalance\n    ) {\n      bool isDebtMoreThanLeftoverThreshold = ((vars.userReserveDebt - vars.actualDebtToLiquidate) *\n        vars.debtAssetPrice) /\n        vars.debtAssetUnit >=\n        MIN_LEFTOVER_BASE;\n\n      bool isCollateralMoreThanLeftoverThreshold = ((vars.userCollateralBalance -\n        vars.actualCollateralToLiquidate -\n        vars.liquidationProtocolFeeAmount) * vars.collateralAssetPrice) /\n        vars.collateralAssetUnit >=\n        MIN_LEFTOVER_BASE;\n\n      require(\n        isDebtMoreThanLeftoverThreshold && isCollateralMoreThanLeftoverThreshold,\n        Errors.MUST_NOT_LEAVE_DUST\n      );\n    }\n\n    // If the collateral being liquidated is equal to the user balance,\n    // we set the currency as not being used as collateral anymore\n    if (\n      vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount ==\n      vars.userCollateralBalance\n    ) {\n      userConfig.setUsingAsCollateral(collateralReserve.id, false);\n      emit ReserveUsedAsCollateralDisabled(params.collateralAsset, params.user);\n    }\n\n    bool hasNoCollateralLeft = vars.totalCollateralInBaseCurrency ==\n      vars.collateralToLiquidateInBaseCurrency;\n    _burnDebtTokens(\n      vars.debtReserveCache,\n      debtReserve,\n      userConfig,\n      params.user,\n      params.debtAsset,\n      vars.userReserveDebt,\n      vars.actualDebtToLiquidate,\n      hasNoCollateralLeft\n    );\n\n    // An asset can only be ceiled if it has no supply or if it was not a collateral previously.\n    // Therefore we can be sure that no inconsistent state can be reached in which a user has multiple collaterals, with one being ceiled.\n    // This allows for the implicit assumption that: if the asset was a collateral & the asset was ceiled, the user must have been in isolation.\n    if (collateralReserve.configuration.getDebtCeiling() != 0) {\n      // IsolationModeTotalDebt only discounts `actualDebtToLiquidate`, not the fully burned amount in case of deficit creation.\n      // This is by design as otherwise the debt ceiling would render ineffective if a collateral asset faces bad debt events.\n      // The governance can decide the raise the ceiling to discount manifested deficit.\n      IsolationModeLogic.updateIsolatedDebt(\n        reservesData,\n        vars.debtReserveCache,\n        vars.actualDebtToLiquidate,\n        params.collateralAsset\n      );\n    }\n\n    if (params.receiveAToken) {\n      _liquidateATokens(reservesData, reservesList, usersConfig, collateralReserve, params, vars);\n    } else {\n      _burnCollateralATokens(collateralReserve, params, vars);\n    }\n\n    // Transfer fee to treasury if it is non-zero\n    if (vars.liquidationProtocolFeeAmount != 0) {\n      uint256 liquidityIndex = collateralReserve.getNormalizedIncome();\n      uint256 scaledDownLiquidationProtocolFee = vars.liquidationProtocolFeeAmount.rayDiv(\n        liquidityIndex\n      );\n      uint256 scaledDownUserBalance = vars.collateralAToken.scaledBalanceOf(params.user);\n      // To avoid trying to send more aTokens than available on balance, due to 1 wei imprecision\n      if (scaledDownLiquidationProtocolFee > scaledDownUserBalance) {\n        vars.liquidationProtocolFeeAmount = scaledDownUserBalance.rayMul(liquidityIndex);\n      }\n      vars.collateralAToken.transferOnLiquidation(\n        params.user,\n        vars.collateralAToken.RESERVE_TREASURY_ADDRESS(),\n        vars.liquidationProtocolFeeAmount\n      );\n    }\n\n    // burn bad debt if necessary\n    // Each additional debt asset already adds around ~75k gas to the liquidation.\n    // To keep the liquidation gas under control, 0 usd collateral positions are not touched, as there is no immediate benefit in burning or transferring to treasury.\n    if (hasNoCollateralLeft && userConfig.isBorrowingAny()) {\n      _burnBadDebt(reservesData, reservesList, userConfig, params.reservesCount, params.user);\n    }\n\n    // Transfers the debt asset being repaid to the aToken, where the liquidity is kept\n    IERC20(params.debtAsset).safeTransferFrom(\n      msg.sender,\n      vars.debtReserveCache.aTokenAddress,\n      vars.actualDebtToLiquidate\n    );\n\n    IAToken(vars.debtReserveCache.aTokenAddress).handleRepayment(\n      msg.sender,\n      params.user,\n      vars.actualDebtToLiquidate\n    );\n\n    emit LiquidationCall(\n      params.collateralAsset,\n      params.debtAsset,\n      params.user,\n      vars.actualDebtToLiquidate,\n      vars.actualCollateralToLiquidate,\n      msg.sender,\n      params.receiveAToken\n    );\n  }\n\n  /**\n   * @notice Burns the collateral aTokens and transfers the underlying to the liquidator.\n   * @dev   The function also updates the state and the interest rate of the collateral reserve.\n   * @param collateralReserve The data of the collateral reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param vars The executeLiquidationCall() function local vars\n   */\n  function _burnCollateralATokens(\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    LiquidationCallLocalVars memory vars\n  ) internal {\n    DataTypes.ReserveCache memory collateralReserveCache = collateralReserve.cache();\n    collateralReserve.updateState(collateralReserveCache);\n    collateralReserve.updateInterestRatesAndVirtualBalance(\n      collateralReserveCache,\n      params.collateralAsset,\n      0,\n      vars.actualCollateralToLiquidate\n    );\n\n    // Burn the equivalent amount of aToken, sending the underlying to the liquidator\n    vars.collateralAToken.burn(\n      params.user,\n      msg.sender,\n      vars.actualCollateralToLiquidate,\n      collateralReserveCache.nextLiquidityIndex\n    );\n  }\n\n  /**\n   * @notice Liquidates the user aTokens by transferring them to the liquidator.\n   * @dev   The function also checks the state of the liquidator and activates the aToken as collateral\n   *        as in standard transfers if the isolation mode constraints are respected.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param collateralReserve The data of the collateral reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param vars The executeLiquidationCall() function local vars\n   */\n  function _liquidateATokens(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    LiquidationCallLocalVars memory vars\n  ) internal {\n    uint256 liquidatorPreviousATokenBalance = IERC20(vars.collateralAToken).balanceOf(msg.sender);\n    vars.collateralAToken.transferOnLiquidation(\n      params.user,\n      msg.sender,\n      vars.actualCollateralToLiquidate\n    );\n\n    if (\n      liquidatorPreviousATokenBalance == 0 ||\n      // For the special case of msg.sender == params.user (self-liquidation) the liquidatorPreviousATokenBalance\n      // will not yet be 0, but the liquidation will result in collateral being fully liquidated and then resupplied.\n      (msg.sender == params.user &&\n        vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount ==\n        vars.userCollateralBalance)\n    ) {\n      DataTypes.UserConfigurationMap storage liquidatorConfig = usersConfig[msg.sender];\n      if (\n        ValidationLogic.validateAutomaticUseAsCollateral(\n          reservesData,\n          reservesList,\n          liquidatorConfig,\n          collateralReserve.configuration,\n          collateralReserve.aTokenAddress\n        )\n      ) {\n        liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true);\n        emit ReserveUsedAsCollateralEnabled(params.collateralAsset, msg.sender);\n      }\n    }\n  }\n\n  /**\n   * @notice Burns the debt tokens of the user up to the amount being repaid by the liquidator\n   * or the entire debt if the user is in a bad debt scenario.\n   * @dev The function alters the `debtReserveCache` state in `vars` to update the debt related data.\n   * @param debtReserveCache The cached debt reserve parameters\n   * @param debtReserve The storage pointer of the debt reserve parameters\n   * @param userConfig The pointer of the user configuration\n   * @param user The user address\n   * @param debtAsset The debt asset address\n   * @param actualDebtToLiquidate The actual debt to liquidate\n   * @param hasNoCollateralLeft The flag representing, will user will have no collateral left after liquidation\n   */\n  function _burnDebtTokens(\n    DataTypes.ReserveCache memory debtReserveCache,\n    DataTypes.ReserveData storage debtReserve,\n    DataTypes.UserConfigurationMap storage userConfig,\n    address user,\n    address debtAsset,\n    uint256 userReserveDebt,\n    uint256 actualDebtToLiquidate,\n    bool hasNoCollateralLeft\n  ) internal {\n    // Prior v3.1, there were cases where, after liquidation, the `isBorrowing` flag was left on\n    // even after the user debt was fully repaid, so to avoid this function reverting in the `_burnScaled`\n    // (see ScaledBalanceTokenBase contract), we check for any debt remaining.\n    if (userReserveDebt != 0) {\n      debtReserveCache.nextScaledVariableDebt = IVariableDebtToken(\n        debtReserveCache.variableDebtTokenAddress\n      ).burn(\n          user,\n          hasNoCollateralLeft ? userReserveDebt : actualDebtToLiquidate,\n          debtReserveCache.nextVariableBorrowIndex\n        );\n    }\n\n    uint256 outstandingDebt = userReserveDebt - actualDebtToLiquidate;\n    if (hasNoCollateralLeft && outstandingDebt != 0) {\n      /**\n       * Special handling of GHO. Implicitly assuming that virtual acc !active == GHO, which is true.\n       * Scenario 1: The amount of GHO debt being liquidated is greater or equal to the GHO accrued interest.\n       *             In this case, the outer handleRepayment will clear the storage and all additional operations can be skipped.\n       * Scenario 2: The amount of debt being liquidated is lower than the GHO accrued interest.\n       *             In this case handleRepayment will be called with the difference required to clear the storage.\n       *             If we assume a liquidation of n debt, and m accrued interest, the difference is k = m-n.\n       *             Therefore we call handleRepayment(k).\n       *             Additionally, as the dao (GHO issuer) accepts the loss on interest on the bad debt,\n       *             we need to discount k from the deficit (via reducing outstandingDebt).\n       * Note: If a non GHO asset is liquidated and GHO bad debt is created in the process, Scenario 2 applies with n = 0.\n       */\n      if (!debtReserveCache.reserveConfiguration.getIsVirtualAccActive()) {\n        uint256 accruedInterest = IGhoVariableDebtToken(debtReserveCache.variableDebtTokenAddress)\n          .getBalanceFromInterest(user);\n        // handleRepayment() will first discount the protocol fee from an internal `accumulatedDebtInterest` variable\n        // and then burn the excess GHO\n        if (accruedInterest != 0 && accruedInterest > actualDebtToLiquidate) {\n          // in order to clean the `accumulatedDebtInterest` storage the function will need to be called with the accruedInterest\n          // discounted by the actualDebtToLiquidate, as in the main flow `handleRepayment` will be called with actualDebtToLiquidate already\n          uint256 amountToBurn = accruedInterest - actualDebtToLiquidate;\n          // In the case of GHO, all obligations are to the protocol\n          // therefore the protocol assumes the losses on interest and only tracks the pure deficit by discounting the not-collected & burned debt\n          outstandingDebt -= amountToBurn;\n          // IMPORTANT: address(0) is used here to indicate that the accrued fee is discounted and not actually repayed.\n          // The value passed has no relevance as it is unused on the aGHO.handleRepayment, therefore the value is purely esthetical.\n          IAToken(debtReserveCache.aTokenAddress).handleRepayment(address(0), user, amountToBurn);\n        }\n      }\n      debtReserve.deficit += outstandingDebt.toUint128();\n      emit DeficitCreated(user, debtAsset, outstandingDebt);\n\n      outstandingDebt = 0;\n    }\n\n    if (outstandingDebt == 0) {\n      userConfig.setBorrowing(debtReserve.id, false);\n    }\n\n    debtReserve.updateInterestRatesAndVirtualBalance(\n      debtReserveCache,\n      debtAsset,\n      actualDebtToLiquidate,\n      0\n    );\n  }\n\n  struct AvailableCollateralToLiquidateLocalVars {\n    uint256 maxCollateralToLiquidate;\n    uint256 baseCollateral;\n    uint256 bonusCollateral;\n    uint256 collateralAmount;\n    uint256 debtAmountNeeded;\n    uint256 liquidationProtocolFeePercentage;\n    uint256 liquidationProtocolFee;\n    uint256 collateralToLiquidateInBaseCurrency;\n    uint256 collateralAssetPrice;\n  }\n\n  /**\n   * @notice Calculates how much of a specific collateral can be liquidated, given\n   * a certain amount of debt asset.\n   * @dev This function needs to be called after all the checks to validate the liquidation have been performed,\n   *   otherwise it might fail.\n   * @param collateralReserveConfiguration The data of the collateral reserve\n   * @param collateralAssetPrice The price of the underlying asset used as collateral\n   * @param collateralAssetUnit The asset units of the collateral\n   * @param debtAssetPrice The price of the underlying borrowed asset to be repaid with the liquidation\n   * @param debtAssetUnit The asset units of the debt\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated\n   * @param liquidationBonus The collateral bonus percentage to receive as result of the liquidation\n   * @return The maximum amount that is possible to liquidate given all the liquidation constraints (user balance, close factor)\n   * @return The amount to repay with the liquidation\n   * @return The fee taken from the liquidation bonus amount to be paid to the protocol\n   * @return The collateral amount to liquidate in the base currency used by the price feed\n   */\n  function _calculateAvailableCollateralToLiquidate(\n    DataTypes.ReserveConfigurationMap memory collateralReserveConfiguration,\n    uint256 collateralAssetPrice,\n    uint256 collateralAssetUnit,\n    uint256 debtAssetPrice,\n    uint256 debtAssetUnit,\n    uint256 debtToCover,\n    uint256 userCollateralBalance,\n    uint256 liquidationBonus\n  ) internal pure returns (uint256, uint256, uint256, uint256) {\n    AvailableCollateralToLiquidateLocalVars memory vars;\n    vars.collateralAssetPrice = collateralAssetPrice;\n    vars.liquidationProtocolFeePercentage = collateralReserveConfiguration\n      .getLiquidationProtocolFee();\n\n    // This is the base collateral to liquidate based on the given debt to cover\n    vars.baseCollateral =\n      ((debtAssetPrice * debtToCover * collateralAssetUnit)) /\n      (vars.collateralAssetPrice * debtAssetUnit);\n\n    vars.maxCollateralToLiquidate = vars.baseCollateral.percentMul(liquidationBonus);\n\n    if (vars.maxCollateralToLiquidate > userCollateralBalance) {\n      vars.collateralAmount = userCollateralBalance;\n      vars.debtAmountNeeded = ((vars.collateralAssetPrice * vars.collateralAmount * debtAssetUnit) /\n        (debtAssetPrice * collateralAssetUnit)).percentDiv(liquidationBonus);\n    } else {\n      vars.collateralAmount = vars.maxCollateralToLiquidate;\n      vars.debtAmountNeeded = debtToCover;\n    }\n\n    vars.collateralToLiquidateInBaseCurrency =\n      (vars.collateralAmount * vars.collateralAssetPrice) /\n      collateralAssetUnit;\n\n    if (vars.liquidationProtocolFeePercentage != 0) {\n      vars.bonusCollateral =\n        vars.collateralAmount -\n        vars.collateralAmount.percentDiv(liquidationBonus);\n\n      vars.liquidationProtocolFee = vars.bonusCollateral.percentMul(\n        vars.liquidationProtocolFeePercentage\n      );\n      vars.collateralAmount -= vars.liquidationProtocolFee;\n    }\n    return (\n      vars.collateralAmount,\n      vars.debtAmountNeeded,\n      vars.liquidationProtocolFee,\n      vars.collateralToLiquidateInBaseCurrency\n    );\n  }\n\n  /**\n   * @notice Remove a user's bad debt by burning debt tokens.\n   * @dev This function iterates through all active reserves where the user has a debt position,\n   * updates their state, and performs the necessary burn.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration\n   * @param reservesCount The total number of valid reserves\n   * @param user The user from which the debt will be burned.\n   */\n  function _burnBadDebt(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    uint256 reservesCount,\n    address user\n  ) internal {\n    for (uint256 i; i < reservesCount; i++) {\n      if (!userConfig.isBorrowing(i)) {\n        continue;\n      }\n\n      address reserveAddress = reservesList[i];\n      if (reserveAddress == address(0)) {\n        continue;\n      }\n\n      DataTypes.ReserveData storage currentReserve = reservesData[reserveAddress];\n      DataTypes.ReserveCache memory reserveCache = currentReserve.cache();\n      if (!reserveCache.reserveConfiguration.getActive()) continue;\n\n      currentReserve.updateState(reserveCache);\n\n      _burnDebtTokens(\n        reserveCache,\n        currentReserve,\n        userConfig,\n        user,\n        reserveAddress,\n        IERC20(reserveCache.variableDebtTokenAddress).balanceOf(user),\n        0,\n        true\n      );\n    }\n  }\n}\n"},"src/contracts/protocol/libraries/types/DataTypes.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n  /**\n   * This exists specifically to maintain the `getReserveData()` interface, since the new, internal\n   * `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`.\n   */\n  struct ReserveDataLegacy {\n    //stores the reserve configuration\n    ReserveConfigurationMap configuration;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    // DEPRECATED on v3.2.0\n    uint128 currentStableBorrowRate;\n    //timestamp of last update\n    uint40 lastUpdateTimestamp;\n    //the id of the reserve. Represents the position in the list of the active reserves\n    uint16 id;\n    //aToken address\n    address aTokenAddress;\n    // DEPRECATED on v3.2.0\n    address stableDebtTokenAddress;\n    //variableDebtToken address\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    //the outstanding unbacked aTokens minted through the bridging feature\n    uint128 unbacked;\n    //the outstanding debt borrowed against this asset in isolation mode\n    uint128 isolationModeTotalDebt;\n  }\n\n  struct ReserveData {\n    //stores the reserve configuration\n    ReserveConfigurationMap configuration;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    /// @notice reused `__deprecatedStableBorrowRate` storage from pre 3.2\n    // the current accumulate deficit in underlying tokens\n    uint128 deficit;\n    //timestamp of last update\n    uint40 lastUpdateTimestamp;\n    //the id of the reserve. Represents the position in the list of the active reserves\n    uint16 id;\n    //timestamp until when liquidations are not allowed on the reserve, if set to past liquidations will be allowed\n    uint40 liquidationGracePeriodUntil;\n    //aToken address\n    address aTokenAddress;\n    // DEPRECATED on v3.2.0\n    address __deprecatedStableDebtTokenAddress;\n    //variableDebtToken address\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    //the outstanding unbacked aTokens minted through the bridging feature\n    uint128 unbacked;\n    //the outstanding debt borrowed against this asset in isolation mode\n    uint128 isolationModeTotalDebt;\n    //the amount of underlying accounted for by the protocol\n    uint128 virtualUnderlyingBalance;\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: DEPRECATED: stable rate borrowing enabled\n    //bit 60: asset is paused\n    //bit 61: borrowing in isolation mode is enabled\n    //bit 62: siloed borrowing enabled\n    //bit 63: flashloaning enabled\n    //bit 64-79: reserve factor\n    //bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap\n    //bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap\n    //bit 152-167: liquidation protocol fee\n    //bit 168-175: DEPRECATED: eMode category\n    //bit 176-211: unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n    //bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n    //bit 252: virtual accounting is enabled for the reserve\n    //bit 253-255 unused\n\n    uint256 data;\n  }\n\n  struct UserConfigurationMap {\n    /**\n     * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n     * The first bit indicates if an asset is used as collateral by the user, the second whether an\n     * asset is borrowed by the user.\n     */\n    uint256 data;\n  }\n\n  // DEPRECATED: kept for backwards compatibility, might be removed in a future version\n  struct EModeCategoryLegacy {\n    // each eMode category has a custom ltv and liquidation threshold\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n    // DEPRECATED\n    address priceSource;\n    string label;\n  }\n\n  struct CollateralConfig {\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n  }\n\n  struct EModeCategoryBaseConfiguration {\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n    string label;\n  }\n\n  struct EModeCategory {\n    // each eMode category has a custom ltv and liquidation threshold\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n    uint128 collateralBitmap;\n    string label;\n    uint128 borrowableBitmap;\n  }\n\n  enum InterestRateMode {\n    NONE,\n    __DEPRECATED,\n    VARIABLE\n  }\n\n  struct ReserveCache {\n    uint256 currScaledVariableDebt;\n    uint256 nextScaledVariableDebt;\n    uint256 currLiquidityIndex;\n    uint256 nextLiquidityIndex;\n    uint256 currVariableBorrowIndex;\n    uint256 nextVariableBorrowIndex;\n    uint256 currLiquidityRate;\n    uint256 currVariableBorrowRate;\n    uint256 reserveFactor;\n    ReserveConfigurationMap reserveConfiguration;\n    address aTokenAddress;\n    address variableDebtTokenAddress;\n    uint40 reserveLastUpdateTimestamp;\n  }\n\n  struct ExecuteLiquidationCallParams {\n    uint256 reservesCount;\n    uint256 debtToCover;\n    address collateralAsset;\n    address debtAsset;\n    address user;\n    bool receiveAToken;\n    address priceOracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteSupplyParams {\n    address asset;\n    uint256 amount;\n    address onBehalfOf;\n    uint16 referralCode;\n  }\n\n  struct ExecuteBorrowParams {\n    address asset;\n    address user;\n    address onBehalfOf;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint16 referralCode;\n    bool releaseUnderlying;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteRepayParams {\n    address asset;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    address onBehalfOf;\n    bool useATokens;\n  }\n\n  struct ExecuteWithdrawParams {\n    address asset;\n    uint256 amount;\n    address to;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteEliminateDeficitParams {\n    address asset;\n    uint256 amount;\n  }\n\n  struct ExecuteSetUserEModeParams {\n    uint256 reservesCount;\n    address oracle;\n    uint8 categoryId;\n  }\n\n  struct FinalizeTransferParams {\n    address asset;\n    address from;\n    address to;\n    uint256 amount;\n    uint256 balanceFromBefore;\n    uint256 balanceToBefore;\n    uint256 reservesCount;\n    address oracle;\n    uint8 fromEModeCategory;\n  }\n\n  struct FlashloanParams {\n    address receiverAddress;\n    address[] assets;\n    uint256[] amounts;\n    uint256[] interestRateModes;\n    address onBehalfOf;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n    uint256 reservesCount;\n    address addressesProvider;\n    address pool;\n    uint8 userEModeCategory;\n    bool isAuthorizedFlashBorrower;\n  }\n\n  struct FlashloanSimpleParams {\n    address receiverAddress;\n    address asset;\n    uint256 amount;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n  }\n\n  struct FlashLoanRepaymentParams {\n    uint256 amount;\n    uint256 totalPremium;\n    uint256 flashLoanPremiumToProtocol;\n    address asset;\n    address receiverAddress;\n    uint16 referralCode;\n  }\n\n  struct CalculateUserAccountDataParams {\n    UserConfigurationMap userConfig;\n    uint256 reservesCount;\n    address user;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ValidateBorrowParams {\n    ReserveCache reserveCache;\n    UserConfigurationMap userConfig;\n    address asset;\n    address userAddress;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n    bool isolationModeActive;\n    address isolationModeCollateralAddress;\n    uint256 isolationModeDebtCeiling;\n  }\n\n  struct ValidateLiquidationCallParams {\n    ReserveCache debtReserveCache;\n    uint256 totalDebt;\n    uint256 healthFactor;\n    address priceOracleSentinel;\n  }\n\n  struct CalculateInterestRatesParams {\n    uint256 unbacked;\n    uint256 liquidityAdded;\n    uint256 liquidityTaken;\n    uint256 totalDebt;\n    uint256 reserveFactor;\n    address reserve;\n    bool usingVirtualBalance;\n    uint256 virtualUnderlyingBalance;\n  }\n\n  struct InitReserveParams {\n    address asset;\n    address aTokenAddress;\n    address variableDebtAddress;\n    address interestRateStrategyAddress;\n    uint16 reservesCount;\n    uint16 maxNumberReserves;\n  }\n}\n"},"src/contracts/protocol/libraries/logic/BridgeLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\n/**\n * @title BridgeLogic library\n * @author Aave\n * @notice Implements functions to mint unbacked aTokens and back the unbacked tokens.\n */\nlibrary BridgeLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n\n  // See `IPool` for descriptions\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n  event MintUnbacked(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n  /**\n   * @notice Mint unbacked aTokens to a user and updates the unbacked for the reserve.\n   * @dev Essentially a supply without transferring the underlying.\n   * @dev Emits the `MintUnbacked` event\n   * @dev Emits the `ReserveUsedAsCollateralEnabled` if asset is set as collateral\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param asset The address of the underlying asset to mint aTokens of\n   * @param amount The amount to mint\n   * @param onBehalfOf The address that will receive the aTokens\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 executeMintUnbacked(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    ValidationLogic.validateSupply(reserveCache, reserve, amount, onBehalfOf);\n\n    uint256 unbackedMintCap = reserveCache.reserveConfiguration.getUnbackedMintCap();\n    uint256 reserveDecimals = reserveCache.reserveConfiguration.getDecimals();\n\n    uint256 unbacked = reserve.unbacked += amount.toUint128();\n\n    require(\n      unbacked <= unbackedMintCap * (10 ** reserveDecimals),\n      Errors.UNBACKED_MINT_CAP_EXCEEDED\n    );\n\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, asset, 0, 0);\n\n    bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(\n      msg.sender,\n      onBehalfOf,\n      amount,\n      reserveCache.nextLiquidityIndex\n    );\n\n    if (isFirstSupply) {\n      if (\n        ValidationLogic.validateAutomaticUseAsCollateral(\n          reservesData,\n          reservesList,\n          userConfig,\n          reserveCache.reserveConfiguration,\n          reserveCache.aTokenAddress\n        )\n      ) {\n        userConfig.setUsingAsCollateral(reserve.id, true);\n        emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);\n      }\n    }\n\n    emit MintUnbacked(asset, msg.sender, onBehalfOf, amount, referralCode);\n  }\n\n  /**\n   * @notice Back the current unbacked with `amount` and pay `fee`.\n   * @dev It is not possible to back more than the existing unbacked amount of the reserve\n   * @dev Emits the `BackUnbacked` event\n   * @param reserve The reserve to back unbacked for\n   * @param asset The address of the underlying asset to repay\n   * @param amount The amount to back\n   * @param fee The amount paid in fees\n   * @param protocolFeeBps The fraction of fees in basis points paid to the protocol\n   * @return The backed amount\n   */\n  function executeBackUnbacked(\n    DataTypes.ReserveData storage reserve,\n    address asset,\n    uint256 amount,\n    uint256 fee,\n    uint256 protocolFeeBps\n  ) external returns (uint256) {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    uint256 backingAmount = (amount < reserve.unbacked) ? amount : reserve.unbacked;\n\n    uint256 feeToProtocol = fee.percentMul(protocolFeeBps);\n    uint256 feeToLP = fee - feeToProtocol;\n    uint256 added = backingAmount + fee;\n\n    reserveCache.nextLiquidityIndex = reserve.cumulateToLiquidityIndex(\n      IERC20(reserveCache.aTokenAddress).totalSupply() +\n        uint256(reserve.accruedToTreasury).rayMul(reserveCache.nextLiquidityIndex),\n      feeToLP\n    );\n\n    reserve.accruedToTreasury += feeToProtocol.rayDiv(reserveCache.nextLiquidityIndex).toUint128();\n\n    reserve.unbacked -= backingAmount.toUint128();\n    reserve.updateInterestRatesAndVirtualBalance(reserveCache, asset, added, 0);\n\n    IERC20(asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, added);\n\n    emit BackUnbacked(asset, msg.sender, backingAmount, fee);\n\n    return backingAmount;\n  }\n}\n"},"src/contracts/interfaces/IERC20WithPermit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\n\n/**\n * @title IERC20WithPermit\n * @author Aave\n * @notice Interface for the permit function (EIP-2612)\n */\ninterface IERC20WithPermit is IERC20 {\n  /**\n   * @notice Allow passing a signed message to approve spending\n   * @dev implements the permit function as for\n   * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n   * @param owner The owner of the funds\n   * @param spender The spender\n   * @param value The amount\n   * @param deadline The deadline timestamp, type(uint256).max for max deadline\n   * @param v Signature param\n   * @param s Signature param\n   * @param r Signature param\n   */\n  function permit(\n    address owner,\n    address spender,\n    uint256 value,\n    uint256 deadline,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external;\n}\n"},"src/contracts/interfaces/IPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n  /**\n   * @dev Emitted on mintUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n   * @param amount The amount of supplied assets\n   * @param referralCode The referral code used\n   */\n  event MintUnbacked(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on backUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param backer The address paying for the backing\n   * @param amount The amount added as backing\n   * @param fee The amount paid in fees\n   */\n  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n  /**\n   * @dev Emitted on supply()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n   * @param amount The amount supplied\n   * @param referralCode The referral code used\n   */\n  event Supply(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on withdraw()\n   * @param reserve The address of the underlying asset being withdrawn\n   * @param user The address initiating the withdrawal, owner of aTokens\n   * @param to The 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 interestRateMode The rate mode: 2 for Variable, 1 is deprecated (changed on v3.2.0)\n   * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n   * @param referralCode The referral code used\n   */\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 borrowRate,\n    uint16 indexed referralCode\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   * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n   */\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount,\n    bool useATokens\n  );\n\n  /**\n   * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n   * @param asset The address of the underlying asset of the reserve\n   * @param totalDebt The total isolation mode debt for the reserve\n   */\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @dev Emitted when the user selects a certain asset category for eMode\n   * @param user The address of the user\n   * @param categoryId The category id\n   */\n  event UserEModeSet(address indexed user, uint8 categoryId);\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 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 interestRateMode The flashloan mode: 0 for regular flashloan,\n   *        1 for Stable (Deprecated on v3.2.0), 2 for Variable\n   * @param premium The fee flash borrowed\n   * @param referralCode The referral code used\n   */\n  event FlashLoan(\n    address indexed target,\n    address initiator,\n    address indexed asset,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 premium,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted when a borrower is liquidated.\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 liquidator\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.\n   * @param reserve The address of the underlying asset of the reserve\n   * @param liquidityRate The next liquidity rate\n   * @param stableBorrowRate The next stable borrow rate @note deprecated on v3.2.0\n   * @param variableBorrowRate The next variable borrow rate\n   * @param liquidityIndex The next liquidity index\n   * @param variableBorrowIndex The next 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 Emitted when the deficit of a reserve is covered.\n   * @param reserve The address of the underlying asset of the reserve\n   * @param caller The caller that triggered the DeficitCovered event\n   * @param amountCovered The amount of deficit covered\n   */\n  event DeficitCovered(address indexed reserve, address caller, uint256 amountCovered);\n\n  /**\n   * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n   * @param reserve The address of the reserve\n   * @param amountMinted The amount minted to the treasury\n   */\n  event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n  /**\n   * @dev Emitted when deficit is realized on a liquidation.\n   * @param user The user address where the bad debt will be burned\n   * @param debtAsset The address of the underlying borrowed asset to be burned\n   * @param amountCreated The amount of deficit created\n   */\n  event DeficitCreated(address indexed user, address indexed debtAsset, uint256 amountCreated);\n\n  /**\n   * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n   * @param asset The address of the underlying asset to mint\n   * @param amount The amount to mint\n   * @param onBehalfOf The address that will receive the aTokens\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 mintUnbacked(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n   * @param asset The address of the underlying asset to back\n   * @param amount The amount to back\n   * @param fee The amount paid in fees\n   * @return The backed amount\n   */\n  function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256);\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\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 supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n\n  /**\n   * @notice Supply with transfer approval of asset to be supplied done via permit function\n   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\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 deadline The deadline timestamp that the permit is valid\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 permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   */\n  function supplyWithPermit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external;\n\n  /**\n   * @notice 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 The 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(address asset, uint256 amount, address to) external returns (uint256);\n\n  /**\n   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the VariableDebtToken\n   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n   *   and 100 variable debt tokens\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0\n   * @param referralCode The 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 The 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 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 interestRateMode 2 for Variable, 1 is deprecated on v3.2.0\n   * @param onBehalfOf The 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 interestRateMode,\n    address onBehalfOf\n  ) external returns (uint256);\n\n  /**\n   * @notice Repay with transfer approval of asset to be repaid done via permit function\n   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\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 interestRateMode 2 for Variable, 1 is deprecated on v3.2.0\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   * @param deadline The deadline timestamp that the permit is valid\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   * @return The final amount repaid\n   */\n  function repayWithPermit(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    address onBehalfOf,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external returns (uint256);\n\n  /**\n   * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n   * equivalent debt tokens\n   * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens\n   * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n   * balance is not enough to cover the whole debt\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 interestRateMode DEPRECATED in v3.2.0\n   * @return The final amount repaid\n   */\n  function repayWithATokens(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode\n  ) external returns (uint256);\n\n  /**\n   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n   * @param asset The address of the underlying asset supplied\n   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n   */\n  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n  /**\n   * @notice 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   * @notice 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   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n   * @param assets The addresses of the assets being flash-borrowed\n   * @param amounts The amounts of the assets being flash-borrowed\n   * @param interestRateModes 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 -> Deprecated on v3.2.0\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 2 on `modes`\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The 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 interestRateModes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice 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   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n   * @param asset The address of the asset being flash-borrowed\n   * @param amount The amount of the asset being flash-borrowed\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The 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 flashLoanSimple(\n    address receiverAddress,\n    address asset,\n    uint256 amount,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Returns the user account data across all the reserves\n   * @param user The address of the user\n   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n   * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\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(\n    address user\n  )\n    external\n    view\n    returns (\n      uint256 totalCollateralBase,\n      uint256 totalDebtBase,\n      uint256 availableBorrowsBase,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    );\n\n  /**\n   * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n   * interest rate strategy\n   * @dev Only callable by the PoolConfigurator 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 variableDebtAddress 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 variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Drop a reserve\n   * @dev Only callable by the PoolConfigurator contract\n   * @dev Does not reset eMode flags, which must be considered when reusing the same reserve id for a different reserve.\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function dropReserve(address asset) external;\n\n  /**\n   * @notice Updates the address of the interest rate strategy contract\n   * @dev Only callable by the PoolConfigurator 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(\n    address asset,\n    address rateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Accumulates interest to all indexes of the reserve\n   * @dev Only callable by the PoolConfigurator contract\n   * @dev To be used when required by the configurator, for example when updating interest rates strategy data\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function syncIndexesState(address asset) external;\n\n  /**\n   * @notice Updates interest rates on the reserve data\n   * @dev Only callable by the PoolConfigurator contract\n   * @dev To be used when required by the configurator, for example when updating interest rates strategy data\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function syncRatesState(address asset) external;\n\n  /**\n   * @notice Sets the configuration bitmap of the reserve as a whole\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param configuration The new configuration bitmap\n   */\n  function setConfiguration(\n    address asset,\n    DataTypes.ReserveConfigurationMap calldata configuration\n  ) external;\n\n  /**\n   * @notice 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(\n    address asset\n  ) external view returns (DataTypes.ReserveConfigurationMap memory);\n\n  /**\n   * @notice 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(\n    address user\n  ) external view returns (DataTypes.UserConfigurationMap memory);\n\n  /**\n   * @notice Returns the 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   * @notice Returns the normalized variable debt per unit of asset\n   * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n   * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n   * moment (approx. a borrower would get if opening a position). This means that is always used in\n   * combination with variable debt supply/balances.\n   * If using this function externally, consider that is possible to have an increasing normalized\n   * variable debt that is not equivalent to how the variable debt index would be updated in storage\n   * (e.g. only updates with non-zero variable debt supply)\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   * @notice Returns the state and configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The state and configuration data of the reserve\n   */\n  function getReserveData(address asset) external view returns (DataTypes.ReserveDataLegacy memory);\n\n  /**\n   * @notice Returns the virtual underlying balance of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve virtual underlying balance\n   */\n  function getVirtualUnderlyingBalance(address asset) external view returns (uint128);\n\n  /**\n   * @notice Validates and finalizes an aToken transfer\n   * @dev 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;\n\n  /**\n   * @notice Returns the list of the underlying assets of all the initialized reserves\n   * @dev It does not include dropped reserves\n   * @return The addresses of the underlying assets of the initialized reserves\n   */\n  function getReservesList() external view returns (address[] memory);\n\n  /**\n   * @notice Returns the number of initialized reserves\n   * @dev It includes dropped reserves\n   * @return The count\n   */\n  function getReservesCount() external view returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n   * @return The address of the reserve associated with id\n   */\n  function getReserveAddressById(uint16 id) external view returns (address);\n\n  /**\n   * @notice Returns the PoolAddressesProvider connected to this contract\n   * @return The address of the PoolAddressesProvider\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Updates the protocol fee on the bridging\n   * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n   */\n  function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n  /**\n   * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n   * - A part is sent to aToken holders as extra, one time accumulated interest\n   * - A part is collected by the protocol treasury\n   * @dev The total premium is calculated on the total borrowed amount\n   * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n   * @dev Only callable by the PoolConfigurator contract\n   * @param flashLoanPremiumTotal The total premium, expressed in bps\n   * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n   */\n  function updateFlashloanPremiums(\n    uint128 flashLoanPremiumTotal,\n    uint128 flashLoanPremiumToProtocol\n  ) external;\n\n  /**\n   * @notice Configures a new or alters an existing collateral configuration of an eMode.\n   * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n   * The category 0 is reserved as it's the default for volatile assets\n   * @param id The id of the category\n   * @param config The configuration of the category\n   */\n  function configureEModeCategory(\n    uint8 id,\n    DataTypes.EModeCategoryBaseConfiguration memory config\n  ) external;\n\n  /**\n   * @notice Replaces the current eMode collateralBitmap.\n   * @param id The id of the category\n   * @param collateralBitmap The collateralBitmap of the category\n   */\n  function configureEModeCategoryCollateralBitmap(uint8 id, uint128 collateralBitmap) external;\n\n  /**\n   * @notice Replaces the current eMode borrowableBitmap.\n   * @param id The id of the category\n   * @param borrowableBitmap The borrowableBitmap of the category\n   */\n  function configureEModeCategoryBorrowableBitmap(uint8 id, uint128 borrowableBitmap) external;\n\n  /**\n   * @notice Returns the data of an eMode category\n   * @dev DEPRECATED use independent getters instead\n   * @param id The id of the category\n   * @return The configuration data of the category\n   */\n  function getEModeCategoryData(\n    uint8 id\n  ) external view returns (DataTypes.EModeCategoryLegacy memory);\n\n  /**\n   * @notice Returns the label of an eMode category\n   * @param id The id of the category\n   * @return The label of the category\n   */\n  function getEModeCategoryLabel(uint8 id) external view returns (string memory);\n\n  /**\n   * @notice Returns the collateral config of an eMode category\n   * @param id The id of the category\n   * @return The ltv,lt,lb of the category\n   */\n  function getEModeCategoryCollateralConfig(\n    uint8 id\n  ) external view returns (DataTypes.CollateralConfig memory);\n\n  /**\n   * @notice Returns the collateralBitmap of an eMode category\n   * @param id The id of the category\n   * @return The collateralBitmap of the category\n   */\n  function getEModeCategoryCollateralBitmap(uint8 id) external view returns (uint128);\n\n  /**\n   * @notice Returns the borrowableBitmap of an eMode category\n   * @param id The id of the category\n   * @return The borrowableBitmap of the category\n   */\n  function getEModeCategoryBorrowableBitmap(uint8 id) external view returns (uint128);\n\n  /**\n   * @notice Allows a user to use the protocol in eMode\n   * @param categoryId The id of the category\n   */\n  function setUserEMode(uint8 categoryId) external;\n\n  /**\n   * @notice Returns the eMode the user is using\n   * @param user The address of the user\n   * @return The eMode id\n   */\n  function getUserEMode(address user) external view returns (uint256);\n\n  /**\n   * @notice Resets the isolation mode total debt of the given asset to zero\n   * @dev It requires the given asset has zero debt ceiling\n   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n   */\n  function resetIsolationModeTotalDebt(address asset) external;\n\n  /**\n   * @notice Sets the liquidation grace period of the given asset\n   * @dev To enable a liquidation grace period, a timestamp in the future should be set,\n   *      To disable a liquidation grace period, any timestamp in the past works, like 0\n   * @param asset The address of the underlying asset to set the liquidationGracePeriod\n   * @param until Timestamp when the liquidation grace period will end\n   **/\n  function setLiquidationGracePeriod(address asset, uint40 until) external;\n\n  /**\n   * @notice Returns the liquidation grace period of the given asset\n   * @param asset The address of the underlying asset\n   * @return Timestamp when the liquidation grace period will end\n   **/\n  function getLiquidationGracePeriod(address asset) external view returns (uint40);\n\n  /**\n   * @notice Returns the total fee on flash loans\n   * @return The total fee on flashloans\n   */\n  function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n  /**\n   * @notice Returns the part of the bridge fees sent to protocol\n   * @return The bridge fee sent to the protocol treasury\n   */\n  function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n  /**\n   * @notice Returns the part of the flashloan fees sent to protocol\n   * @return The flashloan fee sent to the protocol treasury\n   */\n  function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n  /**\n   * @notice Returns the maximum number of reserves supported to be listed in this Pool\n   * @return The maximum number of reserves supported\n   */\n  function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n  /**\n   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n   * @param assets The list of reserves for which the minting needs to be executed\n   */\n  function mintToTreasury(address[] calldata assets) external;\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;\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @dev Deprecated: Use the `supply` function instead\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\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(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n\n  /**\n   * @notice It covers the deficit of a specified reserve by burning:\n   * - the equivalent aToken `amount` for assets with virtual accounting enabled\n   * - the equivalent `amount` of underlying for assets with virtual accounting disabled (e.g. GHO)\n   * @dev The deficit of a reserve can occur due to situations where borrowed assets are not repaid, leading to bad debt.\n   * @param asset The address of the underlying asset to cover the deficit.\n   * @param amount The amount to be covered, in aToken or underlying on non-virtual accounted assets\n   */\n  function eliminateReserveDeficit(address asset, uint256 amount) external;\n\n  /**\n   * @notice Returns the current deficit of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @return The current deficit of the reserve\n   */\n  function getReserveDeficit(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the aToken address of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @return The address of the aToken\n   */\n  function getReserveAToken(address asset) external view returns (address);\n\n  /**\n   * @notice Returns the variableDebtToken address of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @return The address of the variableDebtToken\n   */\n  function getReserveVariableDebtToken(address asset) external view returns (address);\n\n  /**\n   * @notice Gets the address of the external FlashLoanLogic\n   */\n  function getFlashLoanLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external BorrowLogic\n   */\n  function getBorrowLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external BridgeLogic\n   */\n  function getBridgeLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external EModeLogic\n   */\n  function getEModeLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external LiquidationLogic\n   */\n  function getLiquidationLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external PoolLogic\n   */\n  function getPoolLogic() external view returns (address);\n\n  /**\n   * @notice Gets the address of the external SupplyLogic\n   */\n  function getSupplyLogic() external view returns (address);\n}\n"},"src/contracts/interfaces/IACLManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IACLManager\n * @author Aave\n * @notice Defines the basic interface for the ACL Manager\n */\ninterface IACLManager {\n  /**\n   * @notice Returns the contract address of the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns the identifier of the PoolAdmin role\n   * @return The id of the PoolAdmin role\n   */\n  function POOL_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the EmergencyAdmin role\n   * @return The id of the EmergencyAdmin role\n   */\n  function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the RiskAdmin role\n   * @return The id of the RiskAdmin role\n   */\n  function RISK_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the FlashBorrower role\n   * @return The id of the FlashBorrower role\n   */\n  function FLASH_BORROWER_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the Bridge role\n   * @return The id of the Bridge role\n   */\n  function BRIDGE_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the AssetListingAdmin role\n   * @return The id of the AssetListingAdmin role\n   */\n  function ASSET_LISTING_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Set the role as admin of a specific role.\n   * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`.\n   * @param role The role to be managed by the admin role\n   * @param adminRole The admin role\n   */\n  function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\n\n  /**\n   * @notice Adds a new admin as PoolAdmin\n   * @param admin The address of the new admin\n   */\n  function addPoolAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as PoolAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removePoolAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is PoolAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is PoolAdmin, false otherwise\n   */\n  function isPoolAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as EmergencyAdmin\n   * @param admin The address of the new admin\n   */\n  function addEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as EmergencyAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is EmergencyAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is EmergencyAdmin, false otherwise\n   */\n  function isEmergencyAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as RiskAdmin\n   * @param admin The address of the new admin\n   */\n  function addRiskAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as RiskAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeRiskAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is RiskAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is RiskAdmin, false otherwise\n   */\n  function isRiskAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new address as FlashBorrower\n   * @param borrower The address of the new FlashBorrower\n   */\n  function addFlashBorrower(address borrower) external;\n\n  /**\n   * @notice Removes an address as FlashBorrower\n   * @param borrower The address of the FlashBorrower to remove\n   */\n  function removeFlashBorrower(address borrower) external;\n\n  /**\n   * @notice Returns true if the address is FlashBorrower, false otherwise\n   * @param borrower The address to check\n   * @return True if the given address is FlashBorrower, false otherwise\n   */\n  function isFlashBorrower(address borrower) external view returns (bool);\n\n  /**\n   * @notice Adds a new address as Bridge\n   * @param bridge The address of the new Bridge\n   */\n  function addBridge(address bridge) external;\n\n  /**\n   * @notice Removes an address as Bridge\n   * @param bridge The address of the bridge to remove\n   */\n  function removeBridge(address bridge) external;\n\n  /**\n   * @notice Returns true if the address is Bridge, false otherwise\n   * @param bridge The address to check\n   * @return True if the given address is Bridge, false otherwise\n   */\n  function isBridge(address bridge) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as AssetListingAdmin\n   * @param admin The address of the new admin\n   */\n  function addAssetListingAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as AssetListingAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeAssetListingAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is AssetListingAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is AssetListingAdmin, false otherwise\n   */\n  function isAssetListingAdmin(address admin) external view returns (bool);\n}\n"},"src/contracts/protocol/pool/PoolStorage.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\n\n/**\n * @title PoolStorage\n * @author Aave\n * @notice Contract used as storage of the Pool contract.\n * @dev It defines the storage layout of the Pool contract.\n */\ncontract PoolStorage {\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  // Map of reserves and their data (underlyingAssetOfReserve => reserveData)\n  mapping(address => DataTypes.ReserveData) internal _reserves;\n\n  // Map of users address and their configuration data (userAddress => userConfiguration)\n  mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;\n\n  // List of reserves as a map (reserveId => reserve).\n  // It is structured as a mapping for gas savings reasons, using the reserve id as index\n  mapping(uint256 => address) internal _reservesList;\n\n  // List of eMode categories as a map (eModeCategoryId => eModeCategory).\n  // It is structured as a mapping for gas savings reasons, using the eModeCategoryId as index\n  mapping(uint8 => DataTypes.EModeCategory) internal _eModeCategories;\n\n  // Map of users address and their eMode category (userAddress => eModeCategoryId)\n  mapping(address => uint8) internal _usersEModeCategory;\n\n  // Fee of the protocol bridge, expressed in bps\n  uint256 internal _bridgeProtocolFee;\n\n  // Total FlashLoan Premium, expressed in bps\n  uint128 internal _flashLoanPremiumTotal;\n\n  // FlashLoan premium paid to protocol treasury, expressed in bps\n  uint128 internal _flashLoanPremiumToProtocol;\n\n  // DEPRECATED on v3.2.0\n  uint64 internal __DEPRECATED_maxStableRateBorrowSizePercent;\n\n  // Maximum number of active reserves there have been in the protocol. It is the upper bound of the reserves list\n  uint16 internal _reservesCount;\n}\n"},"src/contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol":{"content":"// SPDX-License-Identifier: LGPL-3.0-or-later\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../openzeppelin/contracts/IERC20.sol';\n\n/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library\n/// @author Gnosis Developers\n/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract.\nlibrary GPv2SafeERC20 {\n  /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts\n  /// also when the token returns `false`.\n  function safeTransfer(IERC20 token, address to, uint256 value) internal {\n    bytes4 selector_ = token.transfer.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transfer');\n  }\n\n  /// @dev Wrapper around a call to the ERC20 function `transferFrom` that\n  /// reverts also when the token returns `false`.\n  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n    bytes4 selector_ = token.transferFrom.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 68), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transferFrom');\n  }\n\n  /// @dev Verifies that the last return was a successful `transfer*` call.\n  /// This is done by checking that the return data is either empty, or\n  /// is a valid ABI encoded boolean.\n  function getLastTransferResult(IERC20 token) private view returns (bool success) {\n    // NOTE: Inspecting previous return data requires assembly. Note that\n    // we write the return data to memory 0 in the case where the return\n    // data size is 32, this is OK since the first 64 bytes of memory are\n    // reserved by Solidy as a scratch space that can be used within\n    // assembly blocks.\n    // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html>\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      /// @dev Revert with an ABI encoded Solidity error with a message\n      /// that fits into 32-bytes.\n      ///\n      /// An ABI encoded Solidity error has the following memory layout:\n      ///\n      /// ------------+----------------------------------\n      ///  byte range | value\n      /// ------------+----------------------------------\n      ///  0x00..0x04 |        selector(\"Error(string)\")\n      ///  0x04..0x24 |      string offset (always 0x20)\n      ///  0x24..0x44 |                    string length\n      ///  0x44..0x64 | string value, padded to 32-bytes\n      function revertWithMessage(length, message) {\n        mstore(0x00, '\\x08\\xc3\\x79\\xa0')\n        mstore(0x04, 0x20)\n        mstore(0x24, length)\n        mstore(0x44, message)\n        revert(0x00, 0x64)\n      }\n\n      switch returndatasize()\n      // Non-standard ERC20 transfer without return.\n      case 0 {\n        // NOTE: When the return data size is 0, verify that there\n        // is code at the address. This is done in order to maintain\n        // compatibility with Solidity calling conventions.\n        // <https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls>\n        if iszero(extcodesize(token)) {\n          revertWithMessage(20, 'GPv2: not a contract')\n        }\n\n        success := 1\n      }\n      // Standard ERC20 transfer returning boolean success value.\n      case 32 {\n        returndatacopy(0, 0, returndatasize())\n\n        // NOTE: For ABI encoding v1, any non-zero value is accepted\n        // as `true` for a boolean. In order to stay compatible with\n        // OpenZeppelin's `SafeERC20` library which is known to work\n        // with the existing ERC20 implementation we care about,\n        // make sure we return success for any non-zero return value\n        // from the `transfer*` call.\n        success := iszero(iszero(mload(0)))\n      }\n      default {\n        revertWithMessage(31, 'GPv2: malformed transfer result')\n      }\n    }\n  }\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\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    // This method relies on extcodesize, which returns 0 for contracts in\n    // construction, since the code is only stored at the end of the\n    // constructor execution.\n\n    uint256 size;\n    assembly {\n      size := extcodesize(account)\n    }\n    return size > 0;\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    (bool success, ) = recipient.call{value: amount}('');\n    require(success, 'Address: unable to send value, recipient may have reverted');\n  }\n\n  /**\n   * @dev Performs a Solidity function call using a low level `call`. A\n   * plain `call` is an unsafe replacement for a function call: use this\n   * function instead.\n   *\n   * If `target` reverts with a revert reason, it is bubbled up by this\n   * function (like regular Solidity function calls).\n   *\n   * Returns the raw returned data. To convert to the expected return value,\n   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n   *\n   * Requirements:\n   *\n   * - `target` must be a contract.\n   * - calling `target` with `data` must not revert.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionCall(target, data, 'Address: low-level call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n   * `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, 0, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but also transferring `value` wei to `target`.\n   *\n   * Requirements:\n   *\n   * - the calling contract must have an ETH balance of at least `value`.\n   * - the called Solidity function must be `payable`.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n   * with `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    require(address(this).balance >= value, 'Address: insufficient balance for call');\n    require(isContract(target), 'Address: call to non-contract');\n\n    (bool success, bytes memory returndata) = target.call{value: value}(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(\n    address target,\n    bytes memory data\n  ) internal view returns (bytes memory) {\n    return functionStaticCall(target, data, 'Address: low-level static call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal view returns (bytes memory) {\n    require(isContract(target), 'Address: static call to non-contract');\n\n    (bool success, bytes memory returndata) = target.staticcall(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionDelegateCall(target, data, 'Address: low-level delegate call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    require(isContract(target), 'Address: delegate call to non-contract');\n\n    (bool success, bytes memory returndata) = target.delegatecall(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n   * revert reason using the provided one.\n   *\n   * _Available since v4.3._\n   */\n  function verifyCallResult(\n    bool success,\n    bytes memory returndata,\n    string memory errorMessage\n  ) internal pure returns (bytes memory) {\n    if (success) {\n      return returndata;\n    } else {\n      // Look for revert reason and bubble it up if present\n      if (returndata.length > 0) {\n        // The easiest way to bubble the revert reason is using memory via assembly\n\n        assembly {\n          let returndata_size := mload(returndata)\n          revert(add(32, returndata), returndata_size)\n        }\n      } else {\n        revert(errorMessage);\n      }\n    }\n  }\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\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(address sender, address recipient, uint256 amount) 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/interfaces/IAToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableAToken} from './IInitializableAToken.sol';\n\n/**\n * @title IAToken\n * @author Aave\n * @notice Defines the basic interface for an AToken.\n */\ninterface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {\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 scaled amount being transferred\n   * @param index The next liquidity index of the reserve\n   */\n  event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n  /**\n   * @notice Mints `amount` aTokens to `user`\n   * @param caller The address performing the mint\n   * @param onBehalfOf The address of the user that will receive the minted aTokens\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   * @return `true` if the the previous balance of the user was 0\n   */\n  function mint(\n    address caller,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @notice Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n   * @dev In some instances, the mint event could be emitted from a burn transaction\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the aTokens will be burned\n   * @param receiverOfUnderlying The address that will receive the underlying\n   * @param amount The amount being burned\n   * @param index The next liquidity index of the reserve\n   */\n  function burn(address from, address receiverOfUnderlying, uint256 amount, uint256 index) external;\n\n  /**\n   * @notice Mints aTokens to the reserve treasury\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   */\n  function mintToTreasury(uint256 amount, uint256 index) external;\n\n  /**\n   * @notice 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(address from, address to, uint256 value) external;\n\n  /**\n   * @notice Transfers the underlying asset to `target`.\n   * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan()\n   * @param target The recipient of the underlying\n   * @param amount The amount getting transferred\n   */\n  function transferUnderlyingTo(address target, uint256 amount) external;\n\n  /**\n   * @notice Handles the underlying received by the aToken after the transfer has been completed.\n   * @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the\n   * transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying\n   * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset.\n   * @param user The user executing the repayment\n   * @param onBehalfOf The address of the user who will get his debt reduced/removed\n   * @param amount The amount getting repaid\n   */\n  function handleRepayment(address user, address onBehalfOf, uint256 amount) external;\n\n  /**\n   * @notice Allow passing a signed message to approve spending\n   * @dev implements the permit function as for\n   * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n   * @param owner The owner of the funds\n   * @param spender The spender\n   * @param value The amount\n   * @param deadline The deadline timestamp, type(uint256).max for max deadline\n   * @param v Signature param\n   * @param s Signature param\n   * @param r Signature param\n   */\n  function permit(\n    address owner,\n    address spender,\n    uint256 value,\n    uint256 deadline,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external;\n\n  /**\n   * @notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Returns the address of the Aave treasury, receiving the fees on this aToken.\n   * @return Address of the Aave treasury\n   */\n  function RESERVE_TREASURY_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Get the domain separator for the token\n   * @dev Return cached value if chainId matches cache, otherwise recomputes separator\n   * @return The domain separator of the token at current chain\n   */\n  function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n  /**\n   * @notice Returns the nonce for owner.\n   * @param owner The address of the owner\n   * @return The nonce of the owner\n   */\n  function nonces(address owner) external view returns (uint256);\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;\n}\n"},"src/contracts/protocol/libraries/math/WadRayMath.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n/**\n * @title WadRayMath library\n * @author Aave\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary WadRayMath {\n  // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n  uint256 internal constant WAD = 1e18;\n  uint256 internal constant HALF_WAD = 0.5e18;\n\n  uint256 internal constant RAY = 1e27;\n  uint256 internal constant HALF_RAY = 0.5e27;\n\n  uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n  /**\n   * @dev Multiplies two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a*b, in wad\n   */\n  function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_WAD), WAD)\n    }\n  }\n\n  /**\n   * @dev Divides two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a/b, in wad\n   */\n  function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / WAD\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, WAD), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @notice Multiplies two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raymul b\n   */\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  /**\n   * @notice Divides two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raydiv b\n   */\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Casts ray down to wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @return b = a converted to wad, rounded half up to the nearest wad\n   */\n  function rayToWad(uint256 a) internal pure returns (uint256 b) {\n    assembly {\n      b := div(a, WAD_RAY_RATIO)\n      let remainder := mod(a, WAD_RAY_RATIO)\n      if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n        b := add(b, 1)\n      }\n    }\n  }\n\n  /**\n   * @dev Converts wad up to ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @return b = a converted in ray\n   */\n  function wadToRay(uint256 a) internal pure returns (uint256 b) {\n    // to avoid overflow, b/WAD_RAY_RATIO == a\n    assembly {\n      b := mul(a, WAD_RAY_RATIO)\n\n      if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n        revert(0, 0)\n      }\n    }\n  }\n}\n"},"src/contracts/protocol/libraries/logic/ValidationLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {EModeConfiguration} from '../configuration/EModeConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol';\n\n/**\n * @title ValidationLogic 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 WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using Address for address;\n\n  // Factor to apply to \"only-variable-debt\" liquidity rate to get threshold for rebalancing, expressed in bps\n  // A value of 0.9e4 results in 90%\n  uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4;\n\n  // Minimum health factor allowed under any circumstance\n  // A value of 0.95e18 results in 0.95\n  uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18;\n\n  /**\n   * @dev Minimum health factor to consider a user position healthy\n   * A value of 1e18 results in 1\n   */\n  uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n  /**\n   * @dev Role identifier for the role allowed to supply isolated reserves as collateral\n   */\n  bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE =\n    keccak256('ISOLATED_COLLATERAL_SUPPLIER');\n\n  /**\n   * @notice Validates a supply action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be supplied\n   */\n  function validateSupply(\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.ReserveData storage reserve,\n    uint256 amount,\n    address onBehalfOf\n  ) internal view {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n\n    (bool isActive, bool isFrozen, , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n    require(!isFrozen, Errors.RESERVE_FROZEN);\n    require(onBehalfOf != reserveCache.aTokenAddress, Errors.SUPPLY_TO_ATOKEN);\n\n    uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();\n    require(\n      supplyCap == 0 ||\n        ((IAToken(reserveCache.aTokenAddress).scaledTotalSupply() +\n          uint256(reserve.accruedToTreasury)).rayMul(reserveCache.nextLiquidityIndex) + amount) <=\n        supplyCap * (10 ** reserveCache.reserveConfiguration.getDecimals()),\n      Errors.SUPPLY_CAP_EXCEEDED\n    );\n  }\n\n  /**\n   * @notice Validates a withdraw action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be withdrawn\n   * @param userBalance The balance of the user\n   */\n  function validateWithdraw(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amount,\n    uint256 userBalance\n  ) internal pure {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n    require(amount <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n    (bool isActive, , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  struct ValidateBorrowLocalVars {\n    uint256 currentLtv;\n    uint256 collateralNeededInBaseCurrency;\n    uint256 userCollateralInBaseCurrency;\n    uint256 userDebtInBaseCurrency;\n    uint256 availableLiquidity;\n    uint256 healthFactor;\n    uint256 totalDebt;\n    uint256 totalSupplyVariableDebt;\n    uint256 reserveDecimals;\n    uint256 borrowCap;\n    uint256 amountInBaseCurrency;\n    uint256 assetUnit;\n    address siloedBorrowingAddress;\n    bool isActive;\n    bool isFrozen;\n    bool isPaused;\n    bool borrowingEnabled;\n    bool siloedBorrowingEnabled;\n  }\n\n  /**\n   * @notice Validates a borrow action.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional params needed for the validation\n   */\n  function validateBorrow(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ValidateBorrowParams memory params\n  ) internal view {\n    require(params.amount != 0, Errors.INVALID_AMOUNT);\n\n    ValidateBorrowLocalVars memory vars;\n\n    (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.isPaused) = params\n      .reserveCache\n      .reserveConfiguration\n      .getFlags();\n\n    require(vars.isActive, Errors.RESERVE_INACTIVE);\n    require(!vars.isPaused, Errors.RESERVE_PAUSED);\n    require(!vars.isFrozen, Errors.RESERVE_FROZEN);\n    require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED);\n    require(\n      !params.reserveCache.reserveConfiguration.getIsVirtualAccActive() ||\n        IERC20(params.reserveCache.aTokenAddress).totalSupply() >= params.amount,\n      Errors.INVALID_AMOUNT\n    );\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    //validate interest rate mode\n    require(\n      params.interestRateMode == DataTypes.InterestRateMode.VARIABLE,\n      Errors.INVALID_INTEREST_RATE_MODE_SELECTED\n    );\n\n    vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals();\n    vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap();\n    unchecked {\n      vars.assetUnit = 10 ** vars.reserveDecimals;\n    }\n\n    if (vars.borrowCap != 0) {\n      vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul(\n        params.reserveCache.nextVariableBorrowIndex\n      );\n\n      vars.totalDebt = vars.totalSupplyVariableDebt + params.amount;\n\n      unchecked {\n        require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED);\n      }\n    }\n\n    if (params.isolationModeActive) {\n      // check that the asset being borrowed is borrowable in isolation mode AND\n      // the total exposure is no bigger than the collateral debt ceiling\n      require(\n        params.reserveCache.reserveConfiguration.getBorrowableInIsolation(),\n        Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION\n      );\n\n      require(\n        reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt +\n          (params.amount /\n            10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS))\n            .toUint128() <=\n          params.isolationModeDebtCeiling,\n        Errors.DEBT_CEILING_EXCEEDED\n      );\n    }\n\n    if (params.userEModeCategory != 0) {\n      require(\n        EModeConfiguration.isReserveEnabledOnBitmap(\n          eModeCategories[params.userEModeCategory].borrowableBitmap,\n          reservesData[params.asset].id\n        ),\n        Errors.NOT_BORROWABLE_IN_EMODE\n      );\n    }\n\n    (\n      vars.userCollateralInBaseCurrency,\n      vars.userDebtInBaseCurrency,\n      vars.currentLtv,\n      ,\n      vars.healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.CalculateUserAccountDataParams({\n        userConfig: params.userConfig,\n        reservesCount: params.reservesCount,\n        user: params.userAddress,\n        oracle: params.oracle,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO);\n    require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED);\n\n    require(\n      vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    vars.amountInBaseCurrency =\n      IPriceOracleGetter(params.oracle).getAssetPrice(params.asset) *\n      params.amount;\n    unchecked {\n      vars.amountInBaseCurrency /= vars.assetUnit;\n    }\n\n    //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n    vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency)\n      .percentDiv(vars.currentLtv); //LTV is calculated in percentage\n\n    require(\n      vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency,\n      Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW\n    );\n\n    if (params.userConfig.isBorrowingAny()) {\n      (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params\n        .userConfig\n        .getSiloedBorrowingState(reservesData, reservesList);\n\n      if (vars.siloedBorrowingEnabled) {\n        require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION);\n      } else {\n        require(\n          !params.reserveCache.reserveConfiguration.getSiloedBorrowing(),\n          Errors.SILOED_BORROWING_VIOLATION\n        );\n      }\n    }\n  }\n\n  /**\n   * @notice Validates a repay action.\n   * @param reserveCache The cached data of the reserve\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 debt The borrow balance of the user\n   */\n  function validateRepay(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amountSent,\n    DataTypes.InterestRateMode interestRateMode,\n    address onBehalfOf,\n    uint256 debt\n  ) internal view {\n    require(amountSent != 0, Errors.INVALID_AMOUNT);\n    require(\n      interestRateMode == DataTypes.InterestRateMode.VARIABLE,\n      Errors.INVALID_INTEREST_RATE_MODE_SELECTED\n    );\n    require(\n      amountSent != type(uint256).max || msg.sender == onBehalfOf,\n      Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n    );\n\n    (bool isActive, , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n\n    require(debt != 0, Errors.NO_DEBT_OF_SELECTED_TYPE);\n  }\n\n  /**\n   * @notice Validates the action of setting an asset as collateral.\n   * @param reserveCache The cached data of the reserve\n   * @param userBalance The balance of the user\n   */\n  function validateSetUseReserveAsCollateral(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 userBalance\n  ) internal pure {\n    require(userBalance != 0, Errors.UNDERLYING_BALANCE_ZERO);\n\n    (bool isActive, , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reservesData The state of all the reserves\n   * @param assets The assets being flash-borrowed\n   * @param amounts The amounts for each asset being borrowed\n   */\n  function validateFlashloan(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address[] memory assets,\n    uint256[] memory amounts\n  ) internal view {\n    require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS);\n    for (uint256 i = 0; i < assets.length; i++) {\n      for (uint256 j = i + 1; j < assets.length; j++) {\n        require(assets[i] != assets[j], Errors.INCONSISTENT_FLASHLOAN_PARAMS);\n      }\n      validateFlashloanSimple(reservesData[assets[i]], amounts[i]);\n    }\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reserve The state of the reserve\n   */\n  function validateFlashloanSimple(\n    DataTypes.ReserveData storage reserve,\n    uint256 amount\n  ) internal view {\n    DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration;\n    require(!configuration.getPaused(), Errors.RESERVE_PAUSED);\n    require(configuration.getActive(), Errors.RESERVE_INACTIVE);\n    require(configuration.getFlashLoanEnabled(), Errors.FLASHLOAN_DISABLED);\n    require(\n      !configuration.getIsVirtualAccActive() ||\n        IERC20(reserve.aTokenAddress).totalSupply() >= amount,\n      Errors.INVALID_AMOUNT\n    );\n  }\n\n  struct ValidateLiquidationCallLocalVars {\n    bool collateralReserveActive;\n    bool collateralReservePaused;\n    bool principalReserveActive;\n    bool principalReservePaused;\n    bool isCollateralEnabled;\n  }\n\n  /**\n   * @notice Validates the liquidation action.\n   * @param userConfig The user configuration mapping\n   * @param collateralReserve The reserve data of the collateral\n   * @param debtReserve The reserve data of the debt\n   * @param params Additional parameters needed for the validation\n   */\n  function validateLiquidationCall(\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ReserveData storage debtReserve,\n    DataTypes.ValidateLiquidationCallParams memory params\n  ) internal view {\n    ValidateLiquidationCallLocalVars memory vars;\n\n    (vars.collateralReserveActive, , , vars.collateralReservePaused) = collateralReserve\n      .configuration\n      .getFlags();\n\n    (vars.principalReserveActive, , , vars.principalReservePaused) = params\n      .debtReserveCache\n      .reserveConfiguration\n      .getFlags();\n\n    require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE);\n    require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED);\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    require(\n      collateralReserve.liquidationGracePeriodUntil < uint40(block.timestamp) &&\n        debtReserve.liquidationGracePeriodUntil < uint40(block.timestamp),\n      Errors.LIQUIDATION_GRACE_SENTINEL_CHECK_FAILED\n    );\n\n    require(\n      params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n    );\n\n    vars.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    require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED);\n    require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER);\n  }\n\n  /**\n   * @notice Validates the health factor of a user.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param user The user to validate health factor of\n   * @param userEModeCategory The users active efficiency mode category\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   */\n  function validateHealthFactor(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address user,\n    uint8 userEModeCategory,\n    uint256 reservesCount,\n    address oracle\n  ) internal view returns (uint256, bool) {\n    (, , , , uint256 healthFactor, bool hasZeroLtvCollateral) = GenericLogic\n      .calculateUserAccountData(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        DataTypes.CalculateUserAccountDataParams({\n          userConfig: userConfig,\n          reservesCount: reservesCount,\n          user: user,\n          oracle: oracle,\n          userEModeCategory: userEModeCategory\n        })\n      );\n\n    require(\n      healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    return (healthFactor, hasZeroLtvCollateral);\n  }\n\n  /**\n   * @notice Validates the health factor of a user and the ltv of the asset being withdrawn.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param asset The asset for which the ltv will be validated\n   * @param from The user from which the aTokens are being transferred\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   * @param userEModeCategory The users active efficiency mode category\n   */\n  function validateHFAndLtv(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address asset,\n    address from,\n    uint256 reservesCount,\n    address oracle,\n    uint8 userEModeCategory\n  ) internal view {\n    DataTypes.ReserveData memory reserve = reservesData[asset];\n\n    (, bool hasZeroLtvCollateral) = validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      from,\n      userEModeCategory,\n      reservesCount,\n      oracle\n    );\n\n    require(\n      !hasZeroLtvCollateral || reserve.configuration.getLtv() == 0,\n      Errors.LTV_VALIDATION_FAILED\n    );\n  }\n\n  /**\n   * @notice Validates a transfer action.\n   * @param reserve The reserve object\n   */\n  function validateTransfer(DataTypes.ReserveData storage reserve) internal view {\n    require(!reserve.configuration.getPaused(), Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a drop reserve action.\n   * @param reservesList The addresses of all the active reserves\n   * @param reserve The reserve object\n   * @param asset The address of the reserve's underlying asset\n   */\n  function validateDropReserve(\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.ReserveData storage reserve,\n    address asset\n  ) internal view {\n    require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n    require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n    require(\n      IERC20(reserve.variableDebtTokenAddress).totalSupply() == 0,\n      Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO\n    );\n    require(\n      IERC20(reserve.aTokenAddress).totalSupply() == 0 && reserve.accruedToTreasury == 0,\n      Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO\n    );\n  }\n\n  /**\n   * @notice Validates the action of setting efficiency mode.\n   * @param eModeCategories a mapping storing configurations for all efficiency mode categories\n   * @param userConfig the user configuration\n   * @param reservesCount The total number of valid reserves\n   * @param categoryId The id of the category\n   */\n  function validateSetUserEMode(\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    uint256 reservesCount,\n    uint8 categoryId\n  ) internal view {\n    DataTypes.EModeCategory storage eModeCategory = eModeCategories[categoryId];\n    // category is invalid if the liq threshold is not set\n    require(\n      categoryId == 0 || eModeCategory.liquidationThreshold != 0,\n      Errors.INCONSISTENT_EMODE_CATEGORY\n    );\n\n    // eMode can always be enabled if the user hasn't supplied anything\n    if (userConfig.isEmpty()) {\n      return;\n    }\n\n    // if user is trying to set another category than default we require that\n    // either the user is not borrowing, or it's borrowing assets of categoryId\n    if (categoryId != 0) {\n      unchecked {\n        for (uint256 i = 0; i < reservesCount; i++) {\n          if (userConfig.isBorrowing(i)) {\n            require(\n              EModeConfiguration.isReserveEnabledOnBitmap(eModeCategory.borrowableBitmap, i),\n              Errors.NOT_BORROWABLE_IN_EMODE\n            );\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * @notice Validates the action of activating the asset as collateral.\n   * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig\n  ) internal view returns (bool) {\n    if (reserveConfig.getLtv() == 0) {\n      return false;\n    }\n    if (!userConfig.isUsingAsCollateralAny()) {\n      return true;\n    }\n    (bool isolationModeActive, , ) = userConfig.getIsolationModeState(reservesData, reservesList);\n\n    return (!isolationModeActive && reserveConfig.getDebtCeiling() == 0);\n  }\n\n  /**\n   * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply,\n   * transfer, mint unbacked, and liquidate\n   * @dev This is used to ensure that isolated assets are not enabled as collateral automatically\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateAutomaticUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig,\n    address aTokenAddress\n  ) internal view returns (bool) {\n    if (reserveConfig.getDebtCeiling() != 0) {\n      // ensures only the ISOLATED_COLLATERAL_SUPPLIER_ROLE can enable collateral as side-effect of an action\n      IPoolAddressesProvider addressesProvider = IncentivizedERC20(aTokenAddress)\n        .POOL()\n        .ADDRESSES_PROVIDER();\n      if (\n        !IAccessControl(addressesProvider.getACLManager()).hasRole(\n          ISOLATED_COLLATERAL_SUPPLIER_ROLE,\n          msg.sender\n        )\n      ) return false;\n    }\n    return validateUseAsCollateral(reservesData, reservesList, userConfig, reserveConfig);\n  }\n}\n"},"src/contracts/protocol/libraries/logic/GenericLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {EModeConfiguration} from '../configuration/EModeConfiguration.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {EModeLogic} from './EModeLogic.sol';\n\n/**\n * @title GenericLogic library\n * @author Aave\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  struct CalculateUserAccountDataVars {\n    uint256 assetPrice;\n    uint256 assetUnit;\n    uint256 userBalanceInBaseCurrency;\n    uint256 decimals;\n    uint256 ltv;\n    uint256 liquidationThreshold;\n    uint256 i;\n    uint256 healthFactor;\n    uint256 totalCollateralInBaseCurrency;\n    uint256 totalDebtInBaseCurrency;\n    uint256 avgLtv;\n    uint256 avgLiquidationThreshold;\n    uint256 eModeLtv;\n    uint256 eModeLiqThreshold;\n    address currentReserveAddress;\n    bool hasZeroLtvCollateral;\n    bool isInEModeCategory;\n  }\n\n  /**\n   * @notice Calculates the user data across the reserves.\n   * @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,\n   * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional parameters needed for the calculation\n   * @return The total collateral of the user in the base currency used by the price feed\n   * @return The total debt of the user in the base currency used by the price feed\n   * @return The average ltv of the user\n   * @return The average liquidation threshold of the user\n   * @return The health factor of the user\n   * @return True if the ltv is zero, false otherwise\n   */\n  function calculateUserAccountData(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.CalculateUserAccountDataParams memory params\n  ) internal view returns (uint256, uint256, uint256, uint256, uint256, bool) {\n    if (params.userConfig.isEmpty()) {\n      return (0, 0, 0, 0, type(uint256).max, false);\n    }\n\n    CalculateUserAccountDataVars memory vars;\n\n    if (params.userEModeCategory != 0) {\n      vars.eModeLtv = eModeCategories[params.userEModeCategory].ltv;\n      vars.eModeLiqThreshold = eModeCategories[params.userEModeCategory].liquidationThreshold;\n    }\n\n    while (vars.i < params.reservesCount) {\n      if (!params.userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      vars.currentReserveAddress = reservesList[vars.i];\n\n      if (vars.currentReserveAddress == address(0)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];\n\n      (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve\n        .configuration\n        .getParams();\n\n      unchecked {\n        vars.assetUnit = 10 ** vars.decimals;\n      }\n\n      vars.assetPrice = IPriceOracleGetter(params.oracle).getAssetPrice(vars.currentReserveAddress);\n\n      if (vars.liquidationThreshold != 0 && params.userConfig.isUsingAsCollateral(vars.i)) {\n        vars.userBalanceInBaseCurrency = _getUserBalanceInBaseCurrency(\n          params.user,\n          currentReserve,\n          vars.assetPrice,\n          vars.assetUnit\n        );\n\n        vars.totalCollateralInBaseCurrency += vars.userBalanceInBaseCurrency;\n\n        vars.isInEModeCategory =\n          params.userEModeCategory != 0 &&\n          EModeConfiguration.isReserveEnabledOnBitmap(\n            eModeCategories[params.userEModeCategory].collateralBitmap,\n            vars.i\n          );\n\n        if (vars.ltv != 0) {\n          vars.avgLtv +=\n            vars.userBalanceInBaseCurrency *\n            (vars.isInEModeCategory ? vars.eModeLtv : vars.ltv);\n        } else {\n          vars.hasZeroLtvCollateral = true;\n        }\n\n        vars.avgLiquidationThreshold +=\n          vars.userBalanceInBaseCurrency *\n          (vars.isInEModeCategory ? vars.eModeLiqThreshold : vars.liquidationThreshold);\n      }\n\n      if (params.userConfig.isBorrowing(vars.i)) {\n        if (currentReserve.configuration.getIsVirtualAccActive()) {\n          vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(\n            params.user,\n            currentReserve,\n            vars.assetPrice,\n            vars.assetUnit\n          );\n        } else {\n          // custom case for GHO, which applies the GHO discount on balanceOf\n          vars.totalDebtInBaseCurrency +=\n            (IERC20(currentReserve.variableDebtTokenAddress).balanceOf(params.user) *\n              vars.assetPrice) /\n            vars.assetUnit;\n        }\n      }\n\n      unchecked {\n        ++vars.i;\n      }\n    }\n\n    unchecked {\n      vars.avgLtv = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLtv / vars.totalCollateralInBaseCurrency\n        : 0;\n      vars.avgLiquidationThreshold = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLiquidationThreshold / vars.totalCollateralInBaseCurrency\n        : 0;\n    }\n\n    vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)\n      ? type(uint256).max\n      : (vars.totalCollateralInBaseCurrency.percentMul(vars.avgLiquidationThreshold)).wadDiv(\n        vars.totalDebtInBaseCurrency\n      );\n    return (\n      vars.totalCollateralInBaseCurrency,\n      vars.totalDebtInBaseCurrency,\n      vars.avgLtv,\n      vars.avgLiquidationThreshold,\n      vars.healthFactor,\n      vars.hasZeroLtvCollateral\n    );\n  }\n\n  /**\n   * @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt\n   * and the average Loan To Value\n   * @param totalCollateralInBaseCurrency The total collateral in the base currency used by the price feed\n   * @param totalDebtInBaseCurrency The total borrow balance in the base currency used by the price feed\n   * @param ltv The average loan to value\n   * @return The amount available to borrow in the base currency of the used by the price feed\n   */\n  function calculateAvailableBorrows(\n    uint256 totalCollateralInBaseCurrency,\n    uint256 totalDebtInBaseCurrency,\n    uint256 ltv\n  ) internal pure returns (uint256) {\n    uint256 availableBorrowsInBaseCurrency = totalCollateralInBaseCurrency.percentMul(ltv);\n\n    if (availableBorrowsInBaseCurrency <= totalDebtInBaseCurrency) {\n      return 0;\n    }\n\n    availableBorrowsInBaseCurrency = availableBorrowsInBaseCurrency - totalDebtInBaseCurrency;\n    return availableBorrowsInBaseCurrency;\n  }\n\n  /**\n   * @notice Calculates total debt of the user in the based currency used to normalize the values of the assets\n   * @dev This fetches the `balanceOf` of the variable debt token for the user. For gas reasons, the\n   * variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than\n   * fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total debt of the user is being calculated\n   * @param assetPrice The price of the asset for which the total debt of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total debt of the user normalized to the base currency\n   */\n  function _getUserDebtInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    // fetching variable debt\n    uint256 userTotalDebt = IScaledBalanceToken(reserve.variableDebtTokenAddress).scaledBalanceOf(\n      user\n    );\n    if (userTotalDebt == 0) {\n      return 0;\n    }\n\n    userTotalDebt = userTotalDebt.rayMul(reserve.getNormalizedDebt()) * assetPrice;\n    unchecked {\n      return userTotalDebt / assetUnit;\n    }\n  }\n\n  /**\n   * @notice Calculates total aToken balance of the user in the based currency used by the price oracle\n   * @dev For gas reasons, the aToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which\n   * is cheaper than fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total aToken balance of the user is being calculated\n   * @param assetPrice The price of the asset for which the total aToken balance of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total aToken balance of the user normalized to the base currency of the price oracle\n   */\n  function _getUserBalanceInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    uint256 normalizedIncome = reserve.getNormalizedIncome();\n    uint256 balance = (\n      IScaledBalanceToken(reserve.aTokenAddress).scaledBalanceOf(user).rayMul(normalizedIncome)\n    ) * assetPrice;\n\n    unchecked {\n      return balance / assetUnit;\n    }\n  }\n}\n"},"src/contracts/interfaces/IVariableDebtToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableDebtToken} from './IInitializableDebtToken.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, IInitializableDebtToken {\n  /**\n   * @notice 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 previous balance of the user is 0, false otherwise\n   * @return The scaled total debt of the reserve\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool, uint256);\n\n  /**\n   * @notice Burns user variable debt\n   * @dev In some instances, a burn transaction will emit a mint event\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the debt will be burned\n   * @param amount The amount getting burned\n   * @param index The variable debt index of the reserve\n   * @return The scaled total debt of the reserve\n   */\n  function burn(address from, uint256 amount, uint256 index) external returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"},"src/contracts/interfaces/IReserveInterestRateStrategy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IReserveInterestRateStrategy\n * @author BGD Labs\n * @notice Basic interface for any rate strategy used by the Aave protocol\n */\ninterface IReserveInterestRateStrategy {\n  /**\n   * @notice Sets interest rate data for an Aave rate strategy\n   * @param reserve The reserve to update\n   * @param rateData The abi encoded reserve interest rate data to apply to the given reserve\n   *   Abstracted this way as rate strategies can be custom\n   */\n  function setInterestRateParams(address reserve, bytes calldata rateData) external;\n\n  /**\n   * @notice Calculates the interest rates depending on the reserve's state and configurations\n   * @param params The parameters needed to calculate interest rates\n   * @return liquidityRate The liquidity rate expressed in ray\n   * @return variableBorrowRate The variable borrow rate expressed in ray\n   */\n  function calculateInterestRates(\n    DataTypes.CalculateInterestRatesParams memory params\n  ) external view returns (uint256, uint256);\n}\n"},"src/contracts/protocol/libraries/math/MathUtils.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {WadRayMath} from './WadRayMath.sol';\n\n/**\n * @title MathUtils library\n * @author Aave\n * @notice Provides functions to perform linear and compounded interest calculations\n */\nlibrary MathUtils {\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  function calculateLinearInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    //solium-disable-next-line\n    uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp));\n    unchecked {\n      result = result / SECONDS_PER_YEAR;\n    }\n\n    return WadRayMath.RAY + result;\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\n   * gas cost reductions. The whitepaper contains reference to the approximation and a table showing the margin of\n   * 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 - uint256(lastUpdateTimestamp);\n\n    if (exp == 0) {\n      return WadRayMath.RAY;\n    }\n\n    uint256 expMinusOne;\n    uint256 expMinusTwo;\n    uint256 basePowerTwo;\n    uint256 basePowerThree;\n    unchecked {\n      expMinusOne = exp - 1;\n\n      expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n      basePowerTwo = rate.rayMul(rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR);\n      basePowerThree = basePowerTwo.rayMul(rate) / SECONDS_PER_YEAR;\n    }\n\n    uint256 secondTerm = exp * expMinusOne * basePowerTwo;\n    unchecked {\n      secondTerm /= 2;\n    }\n    uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree;\n    unchecked {\n      thirdTerm /= 6;\n    }\n\n    return WadRayMath.RAY + (rate * exp) / SECONDS_PER_YEAR + secondTerm + 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   * @return The interest rate compounded between lastUpdateTimestamp and current block timestamp, in ray\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n  }\n}\n"},"src/contracts/protocol/libraries/math/PercentageMath.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\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. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary PercentageMath {\n  // Maximum percentage factor (100.00%)\n  uint256 internal constant PERCENTAGE_FACTOR = 1e4;\n\n  // Half percentage factor (50.00%)\n  uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4;\n\n  /**\n   * @notice Executes a percentage multiplication\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\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 result value percentmul percentage\n   */\n  function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage\n    assembly {\n      if iszero(\n        or(\n          iszero(percentage),\n          iszero(gt(value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage)))\n        )\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)\n    }\n  }\n\n  /**\n   * @notice Executes a percentage division\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\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 result value percentdiv percentage\n   */\n  function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR\n    assembly {\n      if or(\n        iszero(percentage),\n        iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR))))\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage)\n    }\n  }\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\npragma solidity ^0.8.10;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an 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 *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n  /**\n   * @dev Returns the downcasted uint224 from uint256, reverting on\n   * overflow (when the input is greater than largest uint224).\n   *\n   * Counterpart to Solidity's `uint224` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 224 bits\n   */\n  function toUint224(uint256 value) internal pure returns (uint224) {\n    require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n    return uint224(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint128 from uint256, reverting on\n   * overflow (when the input is greater than largest uint128).\n   *\n   * Counterpart to Solidity's `uint128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   */\n  function toUint128(uint256 value) internal pure returns (uint128) {\n    require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n    return uint128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint96 from uint256, reverting on\n   * overflow (when the input is greater than largest uint96).\n   *\n   * Counterpart to Solidity's `uint96` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 96 bits\n   */\n  function toUint96(uint256 value) internal pure returns (uint96) {\n    require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n    return uint96(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint64 from uint256, reverting on\n   * overflow (when the input is greater than largest uint64).\n   *\n   * Counterpart to Solidity's `uint64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   */\n  function toUint64(uint256 value) internal pure returns (uint64) {\n    require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n    return uint64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint32 from uint256, reverting on\n   * overflow (when the input is greater than largest uint32).\n   *\n   * Counterpart to Solidity's `uint32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   */\n  function toUint32(uint256 value) internal pure returns (uint32) {\n    require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n    return uint32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint16 from uint256, reverting on\n   * overflow (when the input is greater than largest uint16).\n   *\n   * Counterpart to Solidity's `uint16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   */\n  function toUint16(uint256 value) internal pure returns (uint16) {\n    require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n    return uint16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint8 from uint256, reverting on\n   * overflow (when the input is greater than largest uint8).\n   *\n   * Counterpart to Solidity's `uint8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   */\n  function toUint8(uint256 value) internal pure returns (uint8) {\n    require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n    return uint8(value);\n  }\n\n  /**\n   * @dev Converts a signed int256 into an unsigned uint256.\n   *\n   * Requirements:\n   *\n   * - input must be greater than or equal to 0.\n   */\n  function toUint256(int256 value) internal pure returns (uint256) {\n    require(value >= 0, 'SafeCast: value must be positive');\n    return uint256(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int128 from int256, reverting on\n   * overflow (when the input is less than smallest int128 or\n   * greater than largest int128).\n   *\n   * Counterpart to Solidity's `int128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt128(int256 value) internal pure returns (int128) {\n    require(\n      value >= type(int128).min && value <= type(int128).max,\n      \"SafeCast: value doesn't fit in 128 bits\"\n    );\n    return int128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int64 from int256, reverting on\n   * overflow (when the input is less than smallest int64 or\n   * greater than largest int64).\n   *\n   * Counterpart to Solidity's `int64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt64(int256 value) internal pure returns (int64) {\n    require(\n      value >= type(int64).min && value <= type(int64).max,\n      \"SafeCast: value doesn't fit in 64 bits\"\n    );\n    return int64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int32 from int256, reverting on\n   * overflow (when the input is less than smallest int32 or\n   * greater than largest int32).\n   *\n   * Counterpart to Solidity's `int32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt32(int256 value) internal pure returns (int32) {\n    require(\n      value >= type(int32).min && value <= type(int32).max,\n      \"SafeCast: value doesn't fit in 32 bits\"\n    );\n    return int32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int16 from int256, reverting on\n   * overflow (when the input is less than smallest int16 or\n   * greater than largest int16).\n   *\n   * Counterpart to Solidity's `int16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt16(int256 value) internal pure returns (int16) {\n    require(\n      value >= type(int16).min && value <= type(int16).max,\n      \"SafeCast: value doesn't fit in 16 bits\"\n    );\n    return int16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int8 from int256, reverting on\n   * overflow (when the input is less than smallest int8 or\n   * greater than largest int8).\n   *\n   * Counterpart to Solidity's `int8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   *\n   * _Available since v3.1._\n   */\n  function toInt8(int256 value) internal pure returns (int8) {\n    require(\n      value >= type(int8).min && value <= type(int8).max,\n      \"SafeCast: value doesn't fit in 8 bits\"\n    );\n    return int8(value);\n  }\n\n  /**\n   * @dev Converts an unsigned uint256 into a signed int256.\n   *\n   * Requirements:\n   *\n   * - input must be less than or equal to maxInt256.\n   */\n  function toInt256(uint256 value) internal pure returns (int256) {\n    // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n    require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n    return int256(value);\n  }\n}\n"},"src/contracts/protocol/libraries/configuration/UserConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from './ReserveConfiguration.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  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  uint256 internal constant BORROWING_MASK =\n    0x5555555555555555555555555555555555555555555555555555555555555555;\n  uint256 internal constant COLLATERAL_MASK =\n    0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;\n\n  /**\n   * @notice 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    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << (reserveIndex << 1);\n      if (borrowing) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice 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 using the reserve as collateral, false otherwise\n   */\n  function setUsingAsCollateral(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool usingAsCollateral\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << ((reserveIndex << 1) + 1);\n      if (usingAsCollateral) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Returns 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(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 3 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate 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(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate 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(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Checks if a user has been supplying only one reserve as collateral\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isUsingAsCollateralOne(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    uint256 collateralData = self.data & COLLATERAL_MASK;\n    return collateralData != 0 && (collateralData & (collateralData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks if a user has been supplying any reserve as collateral\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral any reserve, false otherwise\n   */\n  function isUsingAsCollateralAny(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return self.data & COLLATERAL_MASK != 0;\n  }\n\n  /**\n   * @notice Checks if a user has been borrowing only one asset\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isBorrowingOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    uint256 borrowingData = self.data & BORROWING_MASK;\n    return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks 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   * @notice Checks if a user has not been using any reserve for borrowing or supply\n   * @param self The configuration object\n   * @return True if the user has not been borrowing or supplying any reserve, false otherwise\n   */\n  function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data == 0;\n  }\n\n  /**\n   * @notice Returns the Isolation Mode state of the user\n   * @param self The configuration object\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @return True if the user is in isolation mode, false otherwise\n   * @return The address of the only asset used as collateral\n   * @return The debt ceiling of the reserve\n   */\n  function getIsolationModeState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address, uint256) {\n    if (isUsingAsCollateralOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, COLLATERAL_MASK);\n\n      address assetAddress = reservesList[assetId];\n      uint256 ceiling = reservesData[assetAddress].configuration.getDebtCeiling();\n      if (ceiling != 0) {\n        return (true, assetAddress, ceiling);\n      }\n    }\n    return (false, address(0), 0);\n  }\n\n  /**\n   * @notice Returns the siloed borrowing state for the user\n   * @param self The configuration object\n   * @param reservesData The data of all the reserves\n   * @param reservesList The reserve list\n   * @return True if the user has borrowed a siloed asset, false otherwise\n   * @return The address of the only borrowed asset\n   */\n  function getSiloedBorrowingState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address) {\n    if (isBorrowingOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK);\n      address assetAddress = reservesList[assetId];\n      if (reservesData[assetAddress].configuration.getSiloedBorrowing()) {\n        return (true, assetAddress);\n      }\n    }\n\n    return (false, address(0));\n  }\n\n  /**\n   * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask\n   * @param self The configuration object\n   * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied\n   */\n  function _getFirstAssetIdByMask(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 mask\n  ) internal pure returns (uint256) {\n    unchecked {\n      uint256 bitmapData = self.data & mask;\n      uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1);\n      uint256 id;\n\n      while ((firstAssetPosition >>= 2) != 0) {\n        id += 1;\n      }\n      return id;\n    }\n  }\n}\n"},"src/contracts/misc/flashloan/interfaces/IFlashLoanReceiver.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\n\n/**\n * @title IFlashLoanReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanReceiver {\n  /**\n   * @notice Executes an operation after receiving the flash-borrowed assets\n   * @dev Ensure that the contract can return the debt + premium, e.g., has\n   *      enough funds to repay and has approved the Pool to pull the total amount\n   * @param assets The addresses of the flash-borrowed assets\n   * @param amounts The amounts of the flash-borrowed assets\n   * @param premiums The fee of each flash-borrowed asset\n   * @param initiator The address of the flashloan initiator\n   * @param params The byte-encoded params passed when initiating the flashloan\n   * @return True if the execution of the operation succeeds, false otherwise\n   */\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 (IPoolAddressesProvider);\n\n  function POOL() external view returns (IPool);\n}\n"},"src/contracts/misc/flashloan/interfaces/IFlashLoanSimpleReceiver.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n  /**\n   * @notice Executes an operation after receiving the flash-borrowed asset\n   * @dev Ensure that the contract can return the debt + premium, e.g., has\n   *      enough funds to repay and has approved the Pool to pull the total amount\n   * @param asset The address of the flash-borrowed asset\n   * @param amount The amount of the flash-borrowed asset\n   * @param premium The fee of the flash-borrowed asset\n   * @param initiator The address of the flashloan initiator\n   * @param params The byte-encoded params passed when initiating the flashloan\n   * @return True if the execution of the operation succeeds, false otherwise\n   */\n  function executeOperation(\n    address asset,\n    uint256 amount,\n    uint256 premium,\n    address initiator,\n    bytes calldata params\n  ) external returns (bool);\n\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  function POOL() external view returns (IPool);\n}\n"},"src/contracts/protocol/libraries/logic/IsolationModeLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\n\n/**\n * @title IsolationModeLogic library\n * @author Aave\n * @notice Implements the base logic for handling repayments for assets borrowed in isolation mode\n */\nlibrary IsolationModeLogic {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @notice updated the isolated debt whenever a position collateralized by an isolated asset is repaid\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping\n   * @param reserveCache The cached data of the reserve\n   * @param repayAmount The amount being repaid\n   */\n  function updateIsolatedDebtIfIsolated(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 repayAmount\n  ) internal {\n    (bool isolationModeActive, address isolationModeCollateralAddress, ) = userConfig\n      .getIsolationModeState(reservesData, reservesList);\n\n    if (isolationModeActive) {\n      updateIsolatedDebt(reservesData, reserveCache, repayAmount, isolationModeCollateralAddress);\n    }\n  }\n\n  /**\n   * @notice updated the isolated debt whenever a position collateralized by an isolated asset is liquidated\n   * @param reservesData The state of all the reserves\n   * @param reserveCache The cached data of the reserve\n   * @param repayAmount The amount being repaid\n   * @param isolationModeCollateralAddress The address of the isolated collateral\n   */\n  function updateIsolatedDebt(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 repayAmount,\n    address isolationModeCollateralAddress\n  ) internal {\n    uint128 isolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n      .isolationModeTotalDebt;\n\n    uint128 isolatedDebtRepaid = (repayAmount /\n      10 **\n        (reserveCache.reserveConfiguration.getDecimals() -\n          ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128();\n\n    // since the debt ceiling does not take into account the interest accrued, it might happen that amount\n    // repaid > debt in isolation mode\n    if (isolationModeTotalDebt <= isolatedDebtRepaid) {\n      reservesData[isolationModeCollateralAddress].isolationModeTotalDebt = 0;\n      emit IsolationModeTotalDebtUpdated(isolationModeCollateralAddress, 0);\n    } else {\n      uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n        .isolationModeTotalDebt = isolationModeTotalDebt - isolatedDebtRepaid;\n      emit IsolationModeTotalDebtUpdated(\n        isolationModeCollateralAddress,\n        nextIsolationModeTotalDebt\n      );\n    }\n  }\n}\n"},"src/contracts/protocol/libraries/configuration/EModeConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {ReserveConfiguration} from './ReserveConfiguration.sol';\n\n/**\n * @title EModeConfiguration library\n * @author BGD Labs\n * @notice Implements the bitmap logic to handle the eMode configuration\n */\nlibrary EModeConfiguration {\n  /**\n   * @notice Sets a bit in a given bitmap that represents the reserve index range\n   * @dev The supplied bitmap is supposed to be a uint128 in which each bit represents a reserve\n   * @param bitmap The bitmap\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param enabled True if the reserveIndex should be enabled on the bitmap, false otherwise\n   * @return The altered bitmap\n   */\n  function setReserveBitmapBit(\n    uint128 bitmap,\n    uint256 reserveIndex,\n    bool enabled\n  ) internal pure returns (uint128) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint128 bit = uint128(1 << reserveIndex);\n      if (enabled) {\n        return bitmap | bit;\n      } else {\n        return bitmap & ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Validates if a reserveIndex is flagged as enabled on a given bitmap\n   * @param bitmap The bitmap\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the reserveindex is flagged true\n   */\n  function isReserveEnabledOnBitmap(\n    uint128 bitmap,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (bitmap >> reserveIndex) & 1 != 0;\n    }\n  }\n}\n"},"src/contracts/interfaces/IPriceOracleGetter.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IPriceOracleGetter\n * @author Aave\n * @notice Interface for the Aave price oracle.\n */\ninterface IPriceOracleGetter {\n  /**\n   * @notice Returns the base currency address\n   * @dev Address 0x0 is reserved for USD as base currency.\n   * @return Returns the base currency address.\n   */\n  function BASE_CURRENCY() external view returns (address);\n\n  /**\n   * @notice Returns the base currency unit\n   * @dev 1 ether for ETH, 1e8 for USD.\n   * @return Returns the base currency unit.\n   */\n  function BASE_CURRENCY_UNIT() external view returns (uint256);\n\n  /**\n   * @notice Returns the asset price in the base currency\n   * @param asset The address of the asset\n   * @return The price of the asset\n   */\n  function getAssetPrice(address asset) external view returns (uint256);\n}\n"},"src/contracts/interfaces/IScaledBalanceToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IScaledBalanceToken\n * @author Aave\n * @notice Defines the basic interface for a scaled-balance token.\n */\ninterface IScaledBalanceToken {\n  /**\n   * @dev Emitted after the mint action\n   * @param caller The address performing the mint\n   * @param onBehalfOf The address of the user that will receive the minted tokens\n   * @param value The scaled-up amount being minted (based on user entered amount and balance increase from interest)\n   * @param balanceIncrease The increase in scaled-up balance since the last action of 'onBehalfOf'\n   * @param index The next liquidity index of the reserve\n   */\n  event Mint(\n    address indexed caller,\n    address indexed onBehalfOf,\n    uint256 value,\n    uint256 balanceIncrease,\n    uint256 index\n  );\n\n  /**\n   * @dev Emitted after the burn action\n   * @dev If the burn function does not involve a transfer of the underlying asset, the target defaults to zero address\n   * @param from The address from which the tokens will be burned\n   * @param target The address that will receive the underlying, if any\n   * @param value The scaled-up amount being burned (user entered amount - balance increase from interest)\n   * @param balanceIncrease The increase in scaled-up balance since the last action of 'from'\n   * @param index The next liquidity index of the reserve\n   */\n  event Burn(\n    address indexed from,\n    address indexed target,\n    uint256 value,\n    uint256 balanceIncrease,\n    uint256 index\n  );\n\n  /**\n   * @notice Returns the scaled balance of the user.\n   * @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index\n   * 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   * @notice 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 total supply\n   */\n  function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n\n  /**\n   * @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index)\n   * @return The scaled total supply\n   */\n  function scaledTotalSupply() external view returns (uint256);\n\n  /**\n   * @notice Returns last index interest was accrued to the user's balance\n   * @param user The address of the user\n   * @return The last index interest was accrued to the user's balance, expressed in ray\n   */\n  function getPreviousIndex(address user) external view returns (uint256);\n}\n"},"src/contracts/interfaces/IInitializableAToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableAToken\n * @author Aave\n * @notice Interface for the initialize function on AToken\n */\ninterface IInitializableAToken {\n  /**\n   * @dev Emitted when an aToken is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param treasury The address of the treasury\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param aTokenDecimals The decimals of the underlying\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address treasury,\n    address incentivesController,\n    uint8 aTokenDecimals,\n    string aTokenName,\n    string aTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the aToken\n   * @param pool The pool contract that is initializing this contract\n   * @param treasury The address of the Aave treasury, receiving the fees on this aToken\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address treasury,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 aTokenDecimals,\n    string calldata aTokenName,\n    string calldata aTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"},"src/contracts/interfaces/IPriceOracleSentinel.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IPriceOracleSentinel\n * @author Aave\n * @notice Defines the basic interface for the PriceOracleSentinel\n */\ninterface IPriceOracleSentinel {\n  /**\n   * @dev Emitted after the sequencer oracle is updated\n   * @param newSequencerOracle The new sequencer oracle\n   */\n  event SequencerOracleUpdated(address newSequencerOracle);\n\n  /**\n   * @dev Emitted after the grace period is updated\n   * @param newGracePeriod The new grace period value\n   */\n  event GracePeriodUpdated(uint256 newGracePeriod);\n\n  /**\n   * @notice Returns the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns true if the `borrow` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `borrow` operation is allowed, false otherwise.\n   */\n  function isBorrowAllowed() external view returns (bool);\n\n  /**\n   * @notice Returns true if the `liquidation` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `liquidation` operation is allowed, false otherwise.\n   */\n  function isLiquidationAllowed() external view returns (bool);\n\n  /**\n   * @notice Updates the address of the sequencer oracle\n   * @param newSequencerOracle The address of the new Sequencer Oracle to use\n   */\n  function setSequencerOracle(address newSequencerOracle) external;\n\n  /**\n   * @notice Updates the duration of the grace period\n   * @param newGracePeriod The value of the new grace period duration\n   */\n  function setGracePeriod(uint256 newGracePeriod) external;\n\n  /**\n   * @notice Returns the SequencerOracle\n   * @return The address of the sequencer oracle contract\n   */\n  function getSequencerOracle() external view returns (address);\n\n  /**\n   * @notice Returns the grace period\n   * @return The duration of the grace period\n   */\n  function getGracePeriod() external view returns (uint256);\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/IAccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n  /**\n   * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n   *\n   * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n   * {RoleAdminChanged} not being emitted signaling this.\n   *\n   * _Available since v3.1._\n   */\n  event RoleAdminChanged(\n    bytes32 indexed role,\n    bytes32 indexed previousAdminRole,\n    bytes32 indexed newAdminRole\n  );\n\n  /**\n   * @dev Emitted when `account` is granted `role`.\n   *\n   * `sender` is the account that originated the contract call, an admin role\n   * bearer except when using {AccessControl-_setupRole}.\n   */\n  event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Emitted when `account` is revoked `role`.\n   *\n   * `sender` is the account that originated the contract call:\n   *   - if using `revokeRole`, it is the admin role bearer\n   *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n   */\n  event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Returns `true` if `account` has been granted `role`.\n   */\n  function hasRole(bytes32 role, address account) external view returns (bool);\n\n  /**\n   * @dev Returns the admin role that controls `role`. See {grantRole} and\n   * {revokeRole}.\n   *\n   * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n   */\n  function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n  /**\n   * @dev Grants `role` to `account`.\n   *\n   * If `account` had not been already granted `role`, emits a {RoleGranted}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function grantRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from `account`.\n   *\n   * If `account` had been granted `role`, emits a {RoleRevoked} event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function revokeRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from the calling account.\n   *\n   * Roles are often managed via {grantRole} and {revokeRole}: this function's\n   * purpose is to provide a mechanism for accounts to lose their privileges\n   * if they are compromised (such as when a trusted device is misplaced).\n   *\n   * If the calling account had been granted `role`, emits a {RoleRevoked}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must be `account`.\n   */\n  function renounceRole(bytes32 role, address account) external;\n}\n"},"src/contracts/protocol/tokenization/base/IncentivizedERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {Context} from '../../../dependencies/openzeppelin/contracts/Context.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC20Detailed} from '../../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\nimport {Errors} from '../../libraries/helpers/Errors.sol';\nimport {IAaveIncentivesController} from '../../../interfaces/IAaveIncentivesController.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {IACLManager} from '../../../interfaces/IACLManager.sol';\n\n/**\n * @title IncentivizedERC20\n * @author Aave, inspired by the Openzeppelin ERC20 implementation\n * @notice Basic ERC20 implementation\n */\nabstract contract IncentivizedERC20 is Context, IERC20Detailed {\n  using WadRayMath for uint256;\n  using SafeCast for uint256;\n\n  /**\n   * @dev Only pool admin can call functions marked by this modifier.\n   */\n  modifier onlyPoolAdmin() {\n    IACLManager aclManager = IACLManager(_addressesProvider.getACLManager());\n    require(aclManager.isPoolAdmin(msg.sender), Errors.CALLER_NOT_POOL_ADMIN);\n    _;\n  }\n\n  /**\n   * @dev Only pool can call functions marked by this modifier.\n   */\n  modifier onlyPool() {\n    require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL);\n    _;\n  }\n\n  /**\n   * @dev UserState - additionalData is a flexible field.\n   * ATokens and VariableDebtTokens use this field store the index of the\n   * user's last supply/withdrawal/borrow/repayment.\n   */\n  struct UserState {\n    uint128 balance;\n    uint128 additionalData;\n  }\n  // Map of users address and their state data (userAddress => userStateData)\n  mapping(address => UserState) internal _userState;\n\n  // Map of allowances (delegator => delegatee => allowanceAmount)\n  mapping(address => mapping(address => uint256)) private _allowances;\n\n  uint256 internal _totalSupply;\n  string private _name;\n  string private _symbol;\n  uint8 private _decimals;\n  IAaveIncentivesController internal _incentivesController;\n  IPoolAddressesProvider internal immutable _addressesProvider;\n  IPool public immutable POOL;\n\n  /**\n   * @dev Constructor.\n   * @param pool The reference to the main Pool contract\n   * @param name_ The name of the token\n   * @param symbol_ The symbol of the token\n   * @param decimals_ The number of decimals of the token\n   */\n  constructor(IPool pool, string memory name_, string memory symbol_, uint8 decimals_) {\n    _addressesProvider = pool.ADDRESSES_PROVIDER();\n    _name = name_;\n    _symbol = symbol_;\n    _decimals = decimals_;\n    POOL = pool;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function name() public view override returns (string memory) {\n    return _name;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function symbol() external view override returns (string memory) {\n    return _symbol;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function decimals() external view override returns (uint8) {\n    return _decimals;\n  }\n\n  /// @inheritdoc IERC20\n  function totalSupply() public view virtual override returns (uint256) {\n    return _totalSupply;\n  }\n\n  /// @inheritdoc IERC20\n  function balanceOf(address account) public view virtual override returns (uint256) {\n    return _userState[account].balance;\n  }\n\n  /**\n   * @notice Returns the address of the Incentives Controller contract\n   * @return The address of the Incentives Controller\n   */\n  function getIncentivesController() external view virtual returns (IAaveIncentivesController) {\n    return _incentivesController;\n  }\n\n  /**\n   * @notice Sets a new Incentives Controller\n   * @param controller the new Incentives controller\n   */\n  function setIncentivesController(IAaveIncentivesController controller) external onlyPoolAdmin {\n    _incentivesController = controller;\n  }\n\n  /// @inheritdoc IERC20\n  function transfer(address recipient, uint256 amount) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _transfer(_msgSender(), recipient, castAmount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function allowance(\n    address owner,\n    address spender\n  ) external view virtual override returns (uint256) {\n    return _allowances[owner][spender];\n  }\n\n  /// @inheritdoc IERC20\n  function approve(address spender, uint256 amount) external virtual override returns (bool) {\n    _approve(_msgSender(), spender, amount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function transferFrom(\n    address sender,\n    address recipient,\n    uint256 amount\n  ) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - castAmount);\n    _transfer(sender, recipient, castAmount);\n    return true;\n  }\n\n  /**\n   * @notice Increases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param addedValue The amount being added to the allowance\n   * @return `true`\n   */\n  function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);\n    return true;\n  }\n\n  /**\n   * @notice Decreases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param subtractedValue The amount being subtracted to the allowance\n   * @return `true`\n   */\n  function decreaseAllowance(\n    address spender,\n    uint256 subtractedValue\n  ) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);\n    return true;\n  }\n\n  /**\n   * @notice Transfers tokens between two users and apply incentives if defined.\n   * @param sender The source address\n   * @param recipient The destination address\n   * @param amount The amount getting transferred\n   */\n  function _transfer(address sender, address recipient, uint128 amount) internal virtual {\n    uint128 oldSenderBalance = _userState[sender].balance;\n    _userState[sender].balance = oldSenderBalance - amount;\n    uint128 oldRecipientBalance = _userState[recipient].balance;\n    _userState[recipient].balance = oldRecipientBalance + amount;\n\n    IAaveIncentivesController incentivesControllerLocal = _incentivesController;\n    if (address(incentivesControllerLocal) != address(0)) {\n      uint256 currentTotalSupply = _totalSupply;\n      incentivesControllerLocal.handleAction(sender, currentTotalSupply, oldSenderBalance);\n      if (sender != recipient) {\n        incentivesControllerLocal.handleAction(recipient, currentTotalSupply, oldRecipientBalance);\n      }\n    }\n  }\n\n  /**\n   * @notice Approve `spender` to use `amount` of `owner`s balance\n   * @param owner The address owning the tokens\n   * @param spender The address approved for spending\n   * @param amount The amount of tokens to approve spending of\n   */\n  function _approve(address owner, address spender, uint256 amount) internal virtual {\n    _allowances[owner][spender] = amount;\n    emit Approval(owner, spender, amount);\n  }\n\n  /**\n   * @notice Update the name of the token\n   * @param newName The new name for the token\n   */\n  function _setName(string memory newName) internal {\n    _name = newName;\n  }\n\n  /**\n   * @notice Update the symbol for the token\n   * @param newSymbol The new symbol for the token\n   */\n  function _setSymbol(string memory newSymbol) internal {\n    _symbol = newSymbol;\n  }\n\n  /**\n   * @notice Update the number of decimals for the token\n   * @param newDecimals The new number of decimals for the token\n   */\n  function _setDecimals(uint8 newDecimals) internal {\n    _decimals = newDecimals;\n  }\n}\n"},"src/contracts/interfaces/IInitializableDebtToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableDebtToken\n * @author Aave\n * @notice Interface for the initialize function common between debt tokens\n */\ninterface IInitializableDebtToken {\n  /**\n   * @dev Emitted when a debt token is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param debtTokenDecimals The decimals of the debt token\n   * @param debtTokenName The name of the debt token\n   * @param debtTokenSymbol The symbol of the debt token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address incentivesController,\n    uint8 debtTokenDecimals,\n    string debtTokenName,\n    string debtTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the debt token.\n   * @param pool The pool contract that is initializing this contract\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's\n   * @param debtTokenName The name of the token\n   * @param debtTokenSymbol The symbol of the token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 debtTokenDecimals,\n    string memory debtTokenName,\n    string memory debtTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"},"src/contracts/interfaces/IAaveIncentivesController.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IAaveIncentivesController\n * @author Aave\n * @notice Defines the basic interface for an Aave Incentives Controller.\n * @dev It only contains one single function, needed as a hook on aToken and debtToken transfers.\n */\ninterface IAaveIncentivesController {\n  /**\n   * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution.\n   * @dev The units of `totalSupply` and `userBalance` should be the same.\n   * @param user The address of the user whose asset balance has changed\n   * @param totalSupply The total supply of the asset prior to user balance change\n   * @param userBalance The previous user balance prior to balance change\n   */\n  function handleAction(address user, uint256 totalSupply, uint256 userBalance) external;\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/Context.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n  function _msgSender() internal view virtual returns (address payable) {\n    return payable(msg.sender);\n  }\n\n  function _msgData() internal view virtual returns (bytes memory) {\n    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n    return msg.data;\n  }\n}\n"},"src/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from './IERC20.sol';\n\ninterface IERC20Detailed is IERC20 {\n  function name() external view returns (string memory);\n\n  function symbol() external view returns (string memory);\n\n  function decimals() external view returns (uint8);\n}\n"}},"abi":[{"type":"constructor","inputs":[{"name":"provider","type":"address","internalType":"contract IPoolAddressesProvider"}],"stateMutability":"nonpayable"},{"name":"BackUnbacked","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"backer","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"fee","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"Borrow","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":false,"internalType":"address"},{"name":"onBehalfOf","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"interestRateMode","type":"uint8","indexed":false,"internalType":"enum DataTypes.InterestRateMode"},{"name":"borrowRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"referralCode","type":"uint16","indexed":true,"internalType":"uint16"}],"anonymous":false},{"name":"DeficitCovered","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"caller","type":"address","indexed":false,"internalType":"address"},{"name":"amountCovered","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"DeficitCreated","type":"event","inputs":[{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"debtAsset","type":"address","indexed":true,"internalType":"address"},{"name":"amountCreated","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"FlashLoan","type":"event","inputs":[{"name":"target","type":"address","indexed":true,"internalType":"address"},{"name":"initiator","type":"address","indexed":false,"internalType":"address"},{"name":"asset","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"interestRateMode","type":"uint8","indexed":false,"internalType":"enum DataTypes.InterestRateMode"},{"name":"premium","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"referralCode","type":"uint16","indexed":true,"internalType":"uint16"}],"anonymous":false},{"name":"IsolationModeTotalDebtUpdated","type":"event","inputs":[{"name":"asset","type":"address","indexed":true,"internalType":"address"},{"name":"totalDebt","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"LiquidationCall","type":"event","inputs":[{"name":"collateralAsset","type":"address","indexed":true,"internalType":"address"},{"name":"debtAsset","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"debtToCover","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"liquidatedCollateralAmount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"liquidator","type":"address","indexed":false,"internalType":"address"},{"name":"receiveAToken","type":"bool","indexed":false,"internalType":"bool"}],"anonymous":false},{"name":"MintUnbacked","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":false,"internalType":"address"},{"name":"onBehalfOf","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"referralCode","type":"uint16","indexed":true,"internalType":"uint16"}],"anonymous":false},{"name":"MintedToTreasury","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"amountMinted","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"Repay","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"repayer","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"useATokens","type":"bool","indexed":false,"internalType":"bool"}],"anonymous":false},{"name":"ReserveDataUpdated","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"liquidityRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"stableBorrowRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"variableBorrowRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"liquidityIndex","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"variableBorrowIndex","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"ReserveDataUpdated","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"liquidityRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"stableBorrowRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"variableBorrowRate","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"liquidityIndex","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"variableBorrowIndex","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"ReserveUsedAsCollateralDisabled","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"name":"ReserveUsedAsCollateralEnabled","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"name":"Supply","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":false,"internalType":"address"},{"name":"onBehalfOf","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"referralCode","type":"uint16","indexed":true,"internalType":"uint16"}],"anonymous":false},{"name":"UserEModeSet","type":"event","inputs":[{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"categoryId","type":"uint8","indexed":false,"internalType":"uint8"}],"anonymous":false},{"name":"Withdraw","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"ADDRESSES_PROVIDER","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract IPoolAddressesProvider"}],"stateMutability":"view"},{"name":"BRIDGE_PROTOCOL_FEE","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"FLASHLOAN_PREMIUM_TOTAL","type":"function","inputs":[],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"FLASHLOAN_PREMIUM_TO_PROTOCOL","type":"function","inputs":[],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"MAX_NUMBER_RESERVES","type":"function","inputs":[],"outputs":[{"name":"","type":"uint16","internalType":"uint16"}],"stateMutability":"view"},{"name":"POOL_REVISION","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"UMBRELLA","type":"function","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"name":"backUnbacked","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"fee","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"borrow","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"interestRateMode","type":"uint256","internalType":"uint256"},{"name":"referralCode","type":"uint16","internalType":"uint16"},{"name":"onBehalfOf","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"configureEModeCategory","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"},{"name":"category","type":"tuple","components":[{"name":"ltv","type":"uint16","internalType":"uint16"},{"name":"liquidationThreshold","type":"uint16","internalType":"uint16"},{"name":"liquidationBonus","type":"uint16","internalType":"uint16"},{"name":"label","type":"string","internalType":"string"}],"internalType":"struct DataTypes.EModeCategoryBaseConfiguration"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"configureEModeCategoryBorrowableBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"},{"name":"borrowableBitmap","type":"uint128","internalType":"uint128"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"configureEModeCategoryCollateralBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"},{"name":"collateralBitmap","type":"uint128","internalType":"uint128"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"deposit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"referralCode","type":"uint16","internalType":"uint16"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"dropReserve","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"eliminateReserveDeficit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"finalizeTransfer","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"from","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"balanceFromBefore","type":"uint256","internalType":"uint256"},{"name":"balanceToBefore","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"flashLoan","type":"function","inputs":[{"name":"receiverAddress","type":"address","internalType":"address"},{"name":"assets","type":"address[]","internalType":"address[]"},{"name":"amounts","type":"uint256[]","internalType":"uint256[]"},{"name":"interestRateModes","type":"uint256[]","internalType":"uint256[]"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"params","type":"bytes","internalType":"bytes"},{"name":"referralCode","type":"uint16","internalType":"uint16"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"flashLoanSimple","type":"function","inputs":[{"name":"receiverAddress","type":"address","internalType":"address"},{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"params","type":"bytes","internalType":"bytes"},{"name":"referralCode","type":"uint16","internalType":"uint16"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"getBorrowLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getBridgeLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getConfiguration","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"data","type":"uint256","internalType":"uint256"}],"internalType":"struct DataTypes.ReserveConfigurationMap"}],"stateMutability":"view"},{"name":"getEModeCategoryBorrowableBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"getEModeCategoryCollateralBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"getEModeCategoryCollateralConfig","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"ltv","type":"uint16","internalType":"uint16"},{"name":"liquidationThreshold","type":"uint16","internalType":"uint16"},{"name":"liquidationBonus","type":"uint16","internalType":"uint16"}],"internalType":"struct DataTypes.CollateralConfig"}],"stateMutability":"view"},{"name":"getEModeCategoryData","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"ltv","type":"uint16","internalType":"uint16"},{"name":"liquidationThreshold","type":"uint16","internalType":"uint16"},{"name":"liquidationBonus","type":"uint16","internalType":"uint16"},{"name":"priceSource","type":"address","internalType":"address"},{"name":"label","type":"string","internalType":"string"}],"internalType":"struct DataTypes.EModeCategoryLegacy"}],"stateMutability":"view"},{"name":"getEModeCategoryLabel","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"name":"getEModeLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getFlashLoanLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getLiquidationGracePeriod","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint40","internalType":"uint40"}],"stateMutability":"view"},{"name":"getLiquidationLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getPoolLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getReserveAToken","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"getReserveAddressById","type":"function","inputs":[{"name":"id","type":"uint16","internalType":"uint16"}],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"getReserveData","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"configuration","type":"tuple","components":[{"name":"data","type":"uint256","internalType":"uint256"}],"internalType":"struct DataTypes.ReserveConfigurationMap"},{"name":"liquidityIndex","type":"uint128","internalType":"uint128"},{"name":"currentLiquidityRate","type":"uint128","internalType":"uint128"},{"name":"variableBorrowIndex","type":"uint128","internalType":"uint128"},{"name":"currentVariableBorrowRate","type":"uint128","internalType":"uint128"},{"name":"currentStableBorrowRate","type":"uint128","internalType":"uint128"},{"name":"lastUpdateTimestamp","type":"uint40","internalType":"uint40"},{"name":"id","type":"uint16","internalType":"uint16"},{"name":"aTokenAddress","type":"address","internalType":"address"},{"name":"stableDebtTokenAddress","type":"address","internalType":"address"},{"name":"variableDebtTokenAddress","type":"address","internalType":"address"},{"name":"interestRateStrategyAddress","type":"address","internalType":"address"},{"name":"accruedToTreasury","type":"uint128","internalType":"uint128"},{"name":"unbacked","type":"uint128","internalType":"uint128"},{"name":"isolationModeTotalDebt","type":"uint128","internalType":"uint128"}],"internalType":"struct DataTypes.ReserveDataLegacy"}],"stateMutability":"view"},{"name":"getReserveDeficit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getReserveNormalizedIncome","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getReserveNormalizedVariableDebt","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getReserveVariableDebtToken","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"getReservesCount","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getReservesList","type":"function","inputs":[],"outputs":[{"name":"","type":"address[]","internalType":"address[]"}],"stateMutability":"view"},{"name":"getSupplyLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getUserAccountData","type":"function","inputs":[{"name":"user","type":"address","internalType":"address"}],"outputs":[{"name":"totalCollateralBase","type":"uint256","internalType":"uint256"},{"name":"totalDebtBase","type":"uint256","internalType":"uint256"},{"name":"availableBorrowsBase","type":"uint256","internalType":"uint256"},{"name":"currentLiquidationThreshold","type":"uint256","internalType":"uint256"},{"name":"ltv","type":"uint256","internalType":"uint256"},{"name":"healthFactor","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getUserConfiguration","type":"function","inputs":[{"name":"user","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"data","type":"uint256","internalType":"uint256"}],"internalType":"struct DataTypes.UserConfigurationMap"}],"stateMutability":"view"},{"name":"getUserEMode","type":"function","inputs":[{"name":"user","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"getVirtualUnderlyingBalance","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"initReserve","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"aTokenAddress","type":"address","internalType":"address"},{"name":"variableDebtAddress","type":"address","internalType":"address"},{"name":"interestRateStrategyAddress","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"initialize","type":"function","inputs":[{"name":"provider","type":"address","internalType":"contract IPoolAddressesProvider"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"liquidationCall","type":"function","inputs":[{"name":"collateralAsset","type":"address","internalType":"address"},{"name":"debtAsset","type":"address","internalType":"address"},{"name":"user","type":"address","internalType":"address"},{"name":"debtToCover","type":"uint256","internalType":"uint256"},{"name":"receiveAToken","type":"bool","internalType":"bool"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"mintToTreasury","type":"function","inputs":[{"name":"assets","type":"address[]","internalType":"address[]"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"mintUnbacked","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"referralCode","type":"uint16","internalType":"uint16"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"repay","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"interestRateMode","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"repayWithATokens","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"interestRateMode","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"repayWithPermit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"interestRateMode","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"deadline","type":"uint256","internalType":"uint256"},{"name":"permitV","type":"uint8","internalType":"uint8"},{"name":"permitR","type":"bytes32","internalType":"bytes32"},{"name":"permitS","type":"bytes32","internalType":"bytes32"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"rescueTokens","type":"function","inputs":[{"name":"token","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"resetIsolationModeTotalDebt","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setConfiguration","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"configuration","type":"tuple","components":[{"name":"data","type":"uint256","internalType":"uint256"}],"internalType":"struct DataTypes.ReserveConfigurationMap"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setLiquidationGracePeriod","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"until","type":"uint40","internalType":"uint40"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setReserveInterestRateStrategyAddress","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"rateStrategyAddress","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setUserEMode","type":"function","inputs":[{"name":"categoryId","type":"uint8","internalType":"uint8"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setUserUseReserveAsCollateral","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"useAsCollateral","type":"bool","internalType":"bool"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"supply","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"referralCode","type":"uint16","internalType":"uint16"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"supplyWithPermit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"onBehalfOf","type":"address","internalType":"address"},{"name":"referralCode","type":"uint16","internalType":"uint16"},{"name":"deadline","type":"uint256","internalType":"uint256"},{"name":"permitV","type":"uint8","internalType":"uint8"},{"name":"permitR","type":"bytes32","internalType":"bytes32"},{"name":"permitS","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"syncIndexesState","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"syncRatesState","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"updateBridgeProtocolFee","type":"function","inputs":[{"name":"protocolFee","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"updateFlashloanPremiums","type":"function","inputs":[{"name":"flashLoanPremiumTotal","type":"uint128","internalType":"uint128"},{"name":"flashLoanPremiumToProtocol","type":"uint128","internalType":"uint128"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"withdraw","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"to","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"}],"matchId":"9371920","creationMatch":"match","runtimeMatch":"match","verifiedAt":"2025-09-29T23:21:45Z","match":"match","chainId":"1","address":"0xcD8B9aC3B72E81fD8A0c9a0dBba583597E48A23a"}