{"sources":{"lib/aave-v3-origin-private/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 {IReserveInterestRateStrategy} from '../interfaces/IReserveInterestRateStrategy.sol';\nimport {Errors} from '../protocol/libraries/helpers/Errors.sol';\n\n/**\n * @title Aave Pool Instance\n * @author BGD Labs\n * @notice Instance of the Pool for the Aave protocol\n */\ncontract PoolInstance is Pool {\n  uint256 public constant POOL_REVISION = 11;\n\n  constructor(\n    IPoolAddressesProvider provider,\n    IReserveInterestRateStrategy interestRateStrategy_\n  ) Pool(provider, interestRateStrategy_) {}\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.InvalidAddressesProvider());\n  }\n\n  function getRevision() internal pure virtual override returns (uint256) {\n    return POOL_REVISION;\n  }\n}\n"},"lib/aave-v3-origin-private/src/contracts/protocol/pool/Pool.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {Multicall} from 'openzeppelin-contracts/contracts/utils/Multicall.sol';\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 {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 {IERC20WithPermit} from '../../interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol';\nimport {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.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, Multicall {\n  using ReserveLogic for DataTypes.ReserveData;\n\n  IPoolAddressesProvider public immutable ADDRESSES_PROVIDER;\n\n  address public immutable RESERVE_INTEREST_RATE_STRATEGY;\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 an approved position manager can call functions marked by this modifier.\n   */\n  modifier onlyPositionManager(address onBehalfOf) {\n    _onlyPositionManager(onBehalfOf);\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) == _msgSender(), Errors.CallerNotUmbrella());\n    _;\n  }\n\n  function _onlyPoolConfigurator() internal view virtual {\n    require(\n      ADDRESSES_PROVIDER.getPoolConfigurator() == _msgSender(),\n      Errors.CallerNotPoolConfigurator()\n    );\n  }\n\n  function _onlyPoolAdmin() internal view virtual {\n    require(\n      IACLManager(ADDRESSES_PROVIDER.getACLManager()).isPoolAdmin(_msgSender()),\n      Errors.CallerNotPoolAdmin()\n    );\n  }\n\n  function _onlyPositionManager(address onBehalfOf) internal view virtual {\n    require(_positionManager[onBehalfOf][_msgSender()], Errors.CallerNotPositionManager());\n  }\n\n  /**\n   * @dev Constructor.\n   * @param provider The address of the PoolAddressesProvider contract\n   */\n  constructor(IPoolAddressesProvider provider, IReserveInterestRateStrategy interestRateStrategy) {\n    ADDRESSES_PROVIDER = provider;\n    require(address(interestRateStrategy) != address(0), Errors.ZeroAddressNotValid());\n    RESERVE_INTEREST_RATE_STRATEGY = address(interestRateStrategy);\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 supply(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) public virtual override {\n    SupplyLogic.executeSupply(\n      _reserves,\n      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        user: _msgSender(),\n        asset: asset,\n        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode,\n        supplierEModeCategory: _usersEModeCategory[onBehalfOf]\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        _msgSender(),\n        address(this),\n        amount,\n        deadline,\n        permitV,\n        permitR,\n        permitS\n      )\n    {} catch {}\n    SupplyLogic.executeSupply(\n      _reserves,\n      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        user: _msgSender(),\n        asset: asset,\n        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode,\n        supplierEModeCategory: _usersEModeCategory[onBehalfOf]\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[_msgSender()],\n        DataTypes.ExecuteWithdrawParams({\n          user: _msgSender(),\n          asset: asset,\n          interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n          amount: amount,\n          to: to,\n          oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n          userEModeCategory: _usersEModeCategory[_msgSender()]\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        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n        user: _msgSender(),\n        onBehalfOf: onBehalfOf,\n        amount: amount,\n        interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n        referralCode: referralCode,\n        releaseUnderlying: true,\n        oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        userEModeCategory: _usersEModeCategory[onBehalfOf]\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        _eModeCategories,\n        _usersConfig[onBehalfOf],\n        DataTypes.ExecuteRepayParams({\n          asset: asset,\n          user: _msgSender(),\n          interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n          amount: amount,\n          interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n          onBehalfOf: onBehalfOf,\n          useATokens: false,\n          oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n          userEModeCategory: _usersEModeCategory[onBehalfOf]\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        _msgSender(),\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        user: _msgSender(),\n        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n        amount: amount,\n        interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n        onBehalfOf: onBehalfOf,\n        useATokens: false,\n        oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        userEModeCategory: _usersEModeCategory[onBehalfOf]\n      });\n      return\n        BorrowLogic.executeRepay(\n          _reserves,\n          _reservesList,\n          _eModeCategories,\n          _usersConfig[onBehalfOf],\n          params\n        );\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        _eModeCategories,\n        _usersConfig[_msgSender()],\n        DataTypes.ExecuteRepayParams({\n          asset: asset,\n          user: _msgSender(),\n          interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n          amount: amount,\n          interestRateMode: DataTypes.InterestRateMode(interestRateMode),\n          onBehalfOf: _msgSender(),\n          useATokens: true,\n          oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n          userEModeCategory: _usersEModeCategory[_msgSender()]\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[_msgSender()],\n      _msgSender(),\n      asset,\n      useAsCollateral,\n      ADDRESSES_PROVIDER.getPriceOracle(),\n      _usersEModeCategory[_msgSender()]\n    );\n  }\n\n  /// @inheritdoc IPool\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address borrower,\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        liquidator: _msgSender(),\n        debtToCover: debtToCover,\n        collateralAsset: collateralAsset,\n        debtAsset: debtAsset,\n        borrower: borrower,\n        receiveAToken: receiveAToken,\n        priceOracle: ADDRESSES_PROVIDER.getPriceOracle(),\n        borrowerEModeCategory: _usersEModeCategory[borrower],\n        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY\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      user: _msgSender(),\n      receiverAddress: receiverAddress,\n      assets: assets,\n      amounts: amounts,\n      interestRateModes: interestRateModes,\n      interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n      onBehalfOf: onBehalfOf,\n      params: params,\n      referralCode: referralCode,\n      flashLoanPremium: _flashLoanPremium,\n      addressesProvider: address(ADDRESSES_PROVIDER),\n      pool: address(this),\n      isAuthorizedFlashBorrower: IACLManager(ADDRESSES_PROVIDER.getACLManager()).isFlashBorrower(\n        _msgSender()\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      user: _msgSender(),\n      receiverAddress: receiverAddress,\n      asset: asset,\n      interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n      amount: amount,\n      params: params,\n      referralCode: referralCode,\n      flashLoanPremium: _flashLoanPremium\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 res) {\n    DataTypes.ReserveData storage reserve = _reserves[asset];\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_INTEREST_RATE_STRATEGY;\n    res.accruedToTreasury = reserve.accruedToTreasury;\n    res.unbacked = 0;\n    res.isolationModeTotalDebt = 0;\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    // forge-lint: disable-next-line(unsafe-typecast)\n    res.stableDebtTokenAddress = ADDRESSES_PROVIDER.getAddress(bytes32('MOCK_STABLE_DEBT'));\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          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      // @dev legacy check from when dropReserve could leave gaps; see docs/3.7/drop-reserve-removal.md\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 FLASHLOAN_PREMIUM_TOTAL() public view virtual override returns (uint128) {\n    return _flashLoanPremium;\n  }\n\n  /// @inheritdoc IPool\n  function FLASHLOAN_PREMIUM_TO_PROTOCOL() public view virtual override returns (uint128) {\n    return 100_00;\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 scaledAmount,\n    uint256 scaledBalanceFromBefore\n  ) external virtual override {\n    require(_msgSender() == _reserves[asset].aTokenAddress, Errors.CallerNotAToken());\n    SupplyLogic.executeFinalizeTransfer(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig,\n      DataTypes.FinalizeTransferParams({\n        asset: asset,\n        from: from,\n        to: to,\n        scaledAmount: scaledAmount,\n        scaledBalanceFromBefore: scaledBalanceFromBefore,\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  ) 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          reservesCount: _reservesCount,\n          maxNumberReserves: MAX_NUMBER_RESERVES()\n        })\n      )\n    ) {\n      _reservesCount++;\n    }\n  }\n\n  /// @inheritdoc IPool\n  function syncIndexesState(address asset) external virtual override onlyPoolConfigurator {\n    PoolLogic.executeSyncIndexesState(_reserves[asset]);\n  }\n\n  /// @inheritdoc IPool\n  function syncRatesState(address asset) external virtual override onlyPoolConfigurator {\n    PoolLogic.executeSyncRatesState(_reserves[asset], asset, RESERVE_INTEREST_RATE_STRATEGY);\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.ZeroAddressNotValid());\n    require(_reserves[asset].id != 0 || _reservesList[0] == asset, Errors.AssetNotListed());\n    _reserves[asset].configuration = configuration;\n  }\n\n  /// @inheritdoc IPool\n  function updateFlashloanPremium(\n    uint128 flashLoanPremium\n  ) external virtual override onlyPoolConfigurator {\n    _flashLoanPremium = flashLoanPremium;\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.EModeCategoryReserved());\n    _eModeCategories[id].ltv = category.ltv;\n    _eModeCategories[id].liquidationThreshold = category.liquidationThreshold;\n    _eModeCategories[id].liquidationBonus = category.liquidationBonus;\n    _eModeCategories[id].isolated = category.isolated;\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.EModeCategoryReserved());\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.EModeCategoryReserved());\n    _eModeCategories[id].borrowableBitmap = borrowableBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function configureEModeCategoryLtvzeroBitmap(\n    uint8 id,\n    uint128 ltvzeroBitmap\n  ) external virtual override onlyPoolConfigurator {\n    // category 0 is reserved for volatile heterogeneous assets and it's always disabled\n    require(id != 0, Errors.EModeCategoryReserved());\n    _eModeCategories[id].ltvzeroBitmap = ltvzeroBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function configureEModeCategoryIsolated(\n    uint8 id,\n    bool isolated\n  ) external virtual override onlyPoolConfigurator {\n    require(id != 0, Errors.EModeCategoryReserved());\n    _eModeCategories[id].isolated = isolated;\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 res) {\n    res.ltv = _eModeCategories[id].ltv;\n    res.liquidationThreshold = _eModeCategories[id].liquidationThreshold;\n    res.liquidationBonus = _eModeCategories[id].liquidationBonus;\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 getEModeCategoryLtvzeroBitmap(uint8 id) external view returns (uint128) {\n    return _eModeCategories[id].ltvzeroBitmap;\n  }\n\n  /// @inheritdoc IPool\n  function getIsEModeCategoryIsolated(uint8 id) external view returns (bool) {\n    return _eModeCategories[id].isolated;\n  }\n\n  /// @inheritdoc IPool\n  function setUserEMode(uint8 categoryId) external virtual override {\n    SupplyLogic.executeSetUserEMode(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersEModeCategory,\n      _usersConfig[_msgSender()],\n      _msgSender(),\n      ADDRESSES_PROVIDER.getPriceOracle(),\n      categoryId\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 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.AssetNotListed());\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      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      DataTypes.ExecuteSupplyParams({\n        user: _msgSender(),\n        asset: asset,\n        interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY,\n        amount: amount,\n        onBehalfOf: onBehalfOf,\n        referralCode: referralCode,\n        supplierEModeCategory: _usersEModeCategory[onBehalfOf]\n      })\n    );\n  }\n\n  /// @inheritdoc IPool\n  function eliminateReserveDeficit(\n    address asset,\n    uint256 amount\n  ) external override onlyUmbrella returns (uint256) {\n    return\n      LiquidationLogic.executeEliminateDeficit(\n        _reserves,\n        _usersConfig[_msgSender()],\n        DataTypes.ExecuteEliminateDeficitParams({\n          user: _msgSender(),\n          asset: asset,\n          amount: amount,\n          interestRateStrategyAddress: RESERVE_INTEREST_RATE_STRATEGY\n        })\n      );\n  }\n\n  /// @inheritdoc IPool\n  function approvePositionManager(address positionManager, bool approve) external override {\n    if (_positionManager[_msgSender()][positionManager] == approve) return;\n    _positionManager[_msgSender()][positionManager] = approve;\n\n    if (approve) {\n      emit PositionManagerApproved({user: _msgSender(), positionManager: positionManager});\n    } else {\n      emit PositionManagerRevoked({user: _msgSender(), positionManager: positionManager});\n    }\n  }\n\n  /// @inheritdoc IPool\n  function renouncePositionManagerRole(address user) external override {\n    if (_positionManager[user][_msgSender()] == false) return;\n    _positionManager[user][_msgSender()] = false;\n    emit PositionManagerRevoked({user: user, positionManager: _msgSender()});\n  }\n\n  /// @inheritdoc IPool\n  function setUserUseReserveAsCollateralOnBehalfOf(\n    address asset,\n    bool useAsCollateral,\n    address onBehalfOf\n  ) external override onlyPositionManager(onBehalfOf) {\n    SupplyLogic.executeUseReserveAsCollateral(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersConfig[onBehalfOf],\n      onBehalfOf,\n      asset,\n      useAsCollateral,\n      ADDRESSES_PROVIDER.getPriceOracle(),\n      _usersEModeCategory[onBehalfOf]\n    );\n  }\n\n  /// @inheritdoc IPool\n  function setUserEModeOnBehalfOf(\n    uint8 categoryId,\n    address onBehalfOf\n  ) external override onlyPositionManager(onBehalfOf) {\n    SupplyLogic.executeSetUserEMode(\n      _reserves,\n      _reservesList,\n      _eModeCategories,\n      _usersEModeCategory,\n      _usersConfig[onBehalfOf],\n      onBehalfOf,\n      ADDRESSES_PROVIDER.getPriceOracle(),\n      categoryId\n    );\n  }\n\n  /// @inheritdoc IPool\n  function isApprovedPositionManager(\n    address user,\n    address positionManager\n  ) external view override returns (bool) {\n    return _positionManager[user][positionManager];\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 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"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/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  error CallerNotPoolAdmin(); // 'The caller of the function is not a pool admin'\n  error CallerNotPoolOrEmergencyAdmin(); // 'The caller of the function is not a pool or emergency admin'\n  error CallerNotRiskOrPoolAdmin(); // 'The caller of the function is not a risk or pool admin'\n  error CallerNotAssetListingOrPoolAdmin(); // 'The caller of the function is not an asset listing or pool admin'\n  error AddressesProviderNotRegistered(); // 'Pool addresses provider is not registered'\n  error InvalidAddressesProviderId(); // 'Invalid id for the pool addresses provider'\n  error NotContract(); // 'Address is not a contract'\n  error CallerNotPoolConfigurator(); // 'The caller of the function is not the pool configurator'\n  error CallerNotAToken(); // 'The caller of the function is not an AToken'\n  error InvalidAddressesProvider(); // 'The address of the pool addresses provider is invalid'\n  error InvalidFlashloanExecutorReturn(); // 'Invalid return value of the flashloan executor function'\n  error ReserveAlreadyAdded(); // 'Reserve has already been added to reserve list'\n  error NoMoreReservesAllowed(); // 'Maximum amount of reserves in the pool reached'\n  error EModeCategoryReserved(); // 'Zero eMode category is reserved for volatile heterogeneous assets'\n  error ReserveLiquidityNotZero(); // 'The liquidity of the reserve needs to be 0'\n  error FlashloanPremiumInvalid(); // 'Invalid flashloan premium'\n  error InvalidReserveParams(); // 'Invalid risk parameters for the reserve'\n  error InvalidEmodeCategoryParams(); // 'Invalid risk parameters for the eMode category'\n  error CallerMustBePool(); // 'The caller of this function must be a pool'\n  error InvalidMintAmount(); // 'Invalid amount to mint'\n  error InvalidBurnAmount(); // 'Invalid amount to burn'\n  error InvalidAmount(); // 'Amount must be greater than 0'\n  error ReserveInactive(); // 'Action requires an active reserve'\n  error ReserveFrozen(); // 'Action cannot be performed because the reserve is frozen'\n  error ReservePaused(); // 'Action cannot be performed because the reserve is paused'\n  error BorrowingNotEnabled(); // 'Borrowing is not enabled'\n  error NotEnoughAvailableUserBalance(); // 'User cannot withdraw more than the available balance'\n  error InvalidInterestRateModeSelected(); // 'Invalid interest rate mode selected'\n  error HealthFactorLowerThanLiquidationThreshold(); // 'Health factor is below the liquidation threshold'\n  error CollateralCannotCoverNewBorrow(); // 'There is not enough collateral to cover a new borrow'\n  error NoDebtOfSelectedType(); // 'For repayment of a specific type of debt, the user needs to have debt that type'\n  error NoExplicitAmountToRepayOnBehalf(); // 'To repay on behalf of a user an explicit amount to repay is needed'\n  error UnderlyingBalanceZero(); // 'The underlying balance needs to be greater than 0'\n  error HealthFactorNotBelowThreshold(); // 'Health factor is not below the threshold'\n  error CollateralCannotBeLiquidated(); // 'The collateral chosen cannot be liquidated'\n  error SpecifiedCurrencyNotBorrowedByUser(); // 'User did not borrow the specified currency'\n  error InconsistentFlashloanParams(); // 'Inconsistent flashloan parameters'\n  error BorrowCapExceeded(); // 'Borrow cap is exceeded'\n  error SupplyCapExceeded(); // 'Supply cap is exceeded'\n  error LtvValidationFailed(); // 'Ltv validation failed'\n  error InconsistentEModeCategory(); // 'Inconsistent eMode category'\n  error ReserveAlreadyInitialized(); // 'Reserve has already been initialized'\n  error UserHasAssetWithZeroLtv(); // 'User has asset with ltv being zero'\n  error InvalidLtv(); // 'Invalid ltv parameter for the reserve'\n  error InvalidLiquidationThreshold(); // 'Invalid liquidity threshold parameter for the reserve'\n  error InvalidLiquidationBonus(); // 'Invalid liquidity bonus parameter for the reserve'\n  error InvalidDecimals(); // 'Invalid decimals parameter of the underlying asset of the reserve'\n  error InvalidReserveFactor(); // 'Invalid reserve factor parameter for the reserve'\n  error InvalidBorrowCap(); // 'Invalid borrow cap for the reserve'\n  error InvalidSupplyCap(); // 'Invalid supply cap for the reserve'\n  error InvalidLiquidationProtocolFee(); // 'Invalid liquidation protocol fee for the reserve'\n  error InvalidReserveIndex(); // 'Invalid reserve index'\n  error AclAdminCannotBeZero(); // 'ACL admin cannot be set to the zero address'\n  error InconsistentParamsLength(); // 'Array parameters that should be equal length are not'\n  error ZeroAddressNotValid(); // 'Zero address not valid'\n  error InvalidExpiration(); // 'Invalid expiration'\n  error InvalidSignature(); // 'Invalid signature'\n  error OperationNotSupported(); // 'Operation not supported'\n  error AssetNotListed(); // 'Asset is not listed'\n  error InvalidOptimalUsageRatio(); // 'Invalid optimal usage ratio'\n  error UnderlyingCannotBeRescued(); // 'The underlying asset cannot be rescued'\n  error AddressesProviderAlreadyAdded(); // 'Reserve has already been added to reserve list'\n  error PoolAddressesDoNotMatch(); // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n\n  error ReserveDebtNotZero(); // the total debt of the reserve needs to be 0\n  error FlashloanDisabled(); // FlashLoaning for this asset is disabled\n  error InvalidMaxRate(); // The expect maximum borrow rate is invalid\n  error WithdrawToAToken(); // Withdrawing to the aToken is not allowed\n  error SupplyToAToken(); // Supplying to the aToken is not allowed\n  error Slope2MustBeGteSlope1(); // Variable interest rate slope 2 can not be lower than slope 1\n  error CallerNotRiskOrPoolOrEmergencyAdmin(); // 'The caller of the function is not a risk, pool or emergency admin'\n  error LiquidationGraceSentinelCheckFailed(); // 'Liquidation grace sentinel validation failed'\n  error InvalidGracePeriod(); // Grace period above a valid range\n  error InvalidFreezeState(); // Reserve is already in the passed freeze state\n  error InvalidLtvzeroState(); // Reserve is already in the passed ltvzero state\n  error NotBorrowableInEMode(); // Asset not borrowable in eMode\n  error CallerNotUmbrella(); // The caller of the function is not the umbrella contract\n  error ReserveNotInDeficit(); // The reserve is not in deficit\n  error MustNotLeaveDust(); // Below a certain threshold liquidators need to take the full position\n  error UserCannotHaveDebt(); // Thrown when a user tries to interact with a method that requires a position without debt\n  error SelfLiquidation(); // Thrown when a user tries to liquidate themselves\n  error CallerNotPositionManager(); // Thrown when the caller has not been enabled as a position manager of the on-behalf-of user\n  error InvalidCollateralInEmode(address reserve, uint256 categoryId); /// Thrown when trying to enter an eMode with an invalid collateral asset\n  error InvalidDebtInEmode(address reserve, uint256 categoryId); /// Thrown when trying to enter an eMode with an invalid debt asset\n  error MustBeEmodeCollateral(address reserve, uint256 categoryId); /// Thrown when trying to configure an asset as eMode-ltvzero that is not an eMode collateral\n}\n"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Multicall.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)\n\npragma solidity ^0.8.20;\n\nimport {Address} from \"./Address.sol\";\nimport {Context} from \"./Context.sol\";\n\n/**\n * @dev Provides a function to batch together multiple calls in a single external call.\n *\n * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially\n * careful about sending transactions invoking {multicall}. For example, a relay address that filters function\n * selectors won't filter calls nested within a {multicall} operation.\n *\n * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).\n * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`\n * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of\n * {_msgSender} are not propagated to subcalls.\n */\nabstract contract Multicall is Context {\n    /**\n     * @dev Receives and executes a batch of function calls on this contract.\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {\n        bytes memory context = msg.sender == _msgSender()\n            ? new bytes(0)\n            : msg.data[msg.data.length - _contextSuffixLength():];\n\n        results = new bytes[](data.length);\n        for (uint256 i = 0; i < data.length; i++) {\n            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));\n        }\n        return results;\n    }\n}\n"},"lib/aave-v3-origin-private/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 Initializes the implementation contract at the current revision.\n   * In practice this breaks further initialization of the implementation.\n   */\n  constructor() {\n    // break the initialize\n    lastInitializedRevision = getRevision();\n  }\n\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"},"lib/aave-v3-origin-private/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  // @notice there is an unoccupied hole of 2 bit at position 61-62 from pre 3.7 borrowableInIsolation and siloedBorrowing\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 175 left from pre 3.2 eModeCategory\n  //@notice there is an unoccupied hole of 34 bits from 176 to 211 left from pre 3.4 unbackedMintCap\n  //@notice there is an unoccupied hole of 40 bits from 212 to 251 left from pre 3.7 debtCeiling\n  //@notice DEPRECATED: in v3.4 all reserves have virtual accounting enabled\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  //@notice there is an unoccupied hole of 1 bits at 61 left from pre 3.7 borrowableInIsolation\n  //@notice there is an unoccupied hole of 1 bits at 62 left from pre 3.7 siloedBorrowing\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 175 left from pre 3.2 eModeCategory\n  //@notice there is an unoccupied hole of 34 bits from 176 to 211 left from pre 3.4 unbackedMintCap\n  //@notice there is an unoccupied hole of 40 bits from 212 to 251 left from pre 3.7 debtCeiling\n  //@notice DEPRECATED: in v3.4 all reserves have virtual accounting enabled\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\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.InvalidLtv());\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.InvalidLiquidationThreshold());\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.InvalidLiquidationBonus());\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.InvalidDecimals());\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 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.InvalidReserveFactor());\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.InvalidBorrowCap());\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.InvalidSupplyCap());\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 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.InvalidLiquidationProtocolFee()\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 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 Forcefully set the virtual account active state of the reserve to `true`\n   * @dev DEPRECATED: in v3.4 all reserves have virtual accounting enabled.\n   * The flag is carried along for backward compatibility with integrations directly querying the configuration.\n   * @param self The reserve configuration\n   */\n  function setVirtualAccActive(DataTypes.ReserveConfigurationMap memory self) internal pure {\n    self.data =\n      (self.data & ~VIRTUAL_ACC_ACTIVE_MASK) |\n      (uint256(1) << VIRTUAL_ACC_START_BIT_POSITION);\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"},"lib/aave-v3-origin-private/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 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {TokenMath} from '../helpers/TokenMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.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 TokenMath for uint256;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\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.NotContract());\n    reservesData[params.asset].init(params.aTokenAddress, params.variableDebtAddress);\n\n    bool reserveAlreadyAdded = reservesData[params.asset].id != 0 ||\n      reservesList[0] == params.asset;\n    require(!reserveAlreadyAdded, Errors.ReserveAlreadyAdded());\n\n    for (uint16 i = 0; i < params.reservesCount; i++) {\n      // @dev legacy check from when dropReserve could leave gaps; see docs/3.7/drop-reserve-removal.md\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.NoMoreReservesAllowed());\n    reservesData[params.asset].id = params.reservesCount;\n    reservesList[params.reservesCount] = params.asset;\n    return true;\n  }\n\n  /**\n   * @notice Accumulates interest to all indexes of the reserve\n   * @param reserve The state of the reserve\n   */\n  function executeSyncIndexesState(DataTypes.ReserveData storage reserve) external {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n  }\n\n  /**\n   * @notice Updates interest rates on the reserve data\n   * @param reserve The state of the reserve\n   * @param asset The address of the asset\n   * @param interestRateStrategyAddress The address of the interest rate\n   */\n  function executeSyncRatesState(\n    DataTypes.ReserveData storage reserve,\n    address asset,\n    address interestRateStrategyAddress\n  ) external {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      asset,\n      0,\n      0,\n      interestRateStrategyAddress\n    );\n  }\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   */\n  function 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.getATokenBalance(normalizedIncome);\n        IAToken(reserve.aTokenAddress).mintToTreasury(accruedToTreasury, normalizedIncome);\n\n        emit IPool.MintedToTreasury(assetAddress, amountToMint);\n      }\n    }\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 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"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/logic/ReserveLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {IPool} from '../../../interfaces/IPool.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 {TokenMath} from '../helpers/TokenMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {SafeCast} from 'openzeppelin-contracts/contracts/utils/math/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 TokenMath 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  /**\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, the variable borrow index and the timestamp of the update.\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 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   */\n  function init(\n    DataTypes.ReserveData storage reserve,\n    address aTokenAddress,\n    address variableDebtTokenAddress\n  ) internal {\n    require(reserve.aTokenAddress == address(0), Errors.ReserveAlreadyInitialized());\n\n    reserve.liquidityIndex = uint128(WadRayMath.RAY);\n    reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n    reserve.aTokenAddress = aTokenAddress;\n    reserve.variableDebtTokenAddress = variableDebtTokenAddress;\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    address interestRateStrategyAddress\n  ) internal {\n    uint256 totalVariableDebt = reserveCache.nextScaledVariableDebt.getVTokenBalance(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    (uint256 nextLiquidityRate, uint256 nextVariableRate) = IReserveInterestRateStrategy(\n      interestRateStrategyAddress\n    ).calculateInterestRates(\n        DataTypes.CalculateInterestRatesParams({\n          unbacked: reserve.deficit,\n          liquidityAdded: liquidityAdded,\n          liquidityTaken: liquidityTaken,\n          totalDebt: totalVariableDebt,\n          reserveFactor: reserveCache.reserveFactor,\n          reserve: reserveAddress,\n          usingVirtualBalance: true,\n          virtualUnderlyingBalance: reserve.virtualUnderlyingBalance\n        })\n      );\n\n    reserve.currentLiquidityRate = nextLiquidityRate.toUint128();\n    reserve.currentVariableBorrowRate = nextVariableRate.toUint128();\n\n    if (liquidityAdded > 0) {\n      reserve.virtualUnderlyingBalance += liquidityAdded.toUint128();\n    }\n    if (liquidityTaken > 0) {\n      reserve.virtualUnderlyingBalance -= liquidityTaken.toUint128();\n    }\n\n    emit IPool.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    // debt accrued is the sum of the current debt minus the sum of the debt at the last update\n    // Rounding down to undermint to the treasury and keep the invariant healthy.\n    uint256 totalDebtAccrued = reserveCache.currScaledVariableDebt.rayMulFloor(\n      reserveCache.nextVariableBorrowIndex - reserveCache.currVariableBorrowIndex\n    );\n\n    uint256 amountToMint = totalDebtAccrued.percentMul(reserveCache.reserveFactor);\n\n    if (amountToMint != 0) {\n      reserve.accruedToTreasury += amountToMint\n        .getATokenMintScaledAmount(reserveCache.nextLiquidityIndex)\n        .toUint128();\n    }\n  }\n\n  /**\n   * @notice Updates the reserve indexes.\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"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/logic/SupplyLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {TokenMath} from '../helpers/TokenMath.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 TokenMath for uint256;\n  using PercentageMath for uint256;\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 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(uint8 => DataTypes.EModeCategory) storage eModeCategories,\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    uint256 scaledAmount = params.amount.getATokenMintScaledAmount(reserveCache.nextLiquidityIndex);\n\n    ValidationLogic.validateSupply(reserveCache, reserve, scaledAmount, params.onBehalfOf);\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      params.amount,\n      0,\n      params.interestRateStrategyAddress\n    );\n\n    IERC20(params.asset).safeTransferFrom(params.user, reserveCache.aTokenAddress, params.amount);\n\n    // As aToken.mint rounds down the minted shares, we ensure an equivalent of <= params.amount shares is minted.\n    bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(\n      params.user,\n      params.onBehalfOf,\n      scaledAmount,\n      reserveCache.nextLiquidityIndex\n    );\n\n    if (isFirstSupply) {\n      if (\n        ValidationLogic.validateUseAsCollateral(\n          reservesData,\n          eModeCategories,\n          params.asset,\n          params.supplierEModeCategory\n        )\n      ) {\n        userConfig.setUsingAsCollateral(reserve.id, params.asset, params.onBehalfOf, true);\n      }\n    }\n\n    emit IPool.Supply(\n      params.asset,\n      params.user,\n      params.onBehalfOf,\n      params.amount,\n      params.referralCode\n    );\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.WithdrawToAToken());\n\n    reserve.updateState(reserveCache);\n\n    uint256 scaledUserBalance = IAToken(reserveCache.aTokenAddress).scaledBalanceOf(params.user);\n\n    uint256 amountToWithdraw;\n    uint256 scaledAmountToWithdraw;\n    if (params.amount == type(uint256).max) {\n      scaledAmountToWithdraw = scaledUserBalance;\n\n      amountToWithdraw = scaledUserBalance.getATokenBalance(reserveCache.nextLiquidityIndex);\n    } else {\n      scaledAmountToWithdraw = params.amount.getATokenBurnScaledAmount(\n        reserveCache.nextLiquidityIndex\n      );\n\n      amountToWithdraw = params.amount;\n    }\n\n    ValidationLogic.validateWithdraw(reserveCache, scaledAmountToWithdraw, scaledUserBalance);\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      0,\n      amountToWithdraw,\n      params.interestRateStrategyAddress\n    );\n\n    // As aToken.burn rounds up the burned shares, we ensure at least an equivalent of >= amountToWithdraw is burned.\n    bool zeroBalanceAfterBurn = IAToken(reserveCache.aTokenAddress).burn({\n      from: params.user,\n      receiverOfUnderlying: params.to,\n      amount: amountToWithdraw,\n      scaledAmount: scaledAmountToWithdraw,\n      index: reserveCache.nextLiquidityIndex\n    });\n\n    if (userConfig.isUsingAsCollateral(reserve.id)) {\n      if (zeroBalanceAfterBurn) {\n        userConfig.setUsingAsCollateral(reserve.id, params.asset, params.user, false);\n      }\n      if (userConfig.isBorrowingAny()) {\n        ValidationLogic.validateHFAndLtvzero(\n          reservesData,\n          reservesList,\n          eModeCategories,\n          userConfig,\n          params.asset,\n          params.user,\n          params.oracle,\n          params.userEModeCategory\n        );\n      }\n    }\n\n    emit IPool.Withdraw(params.asset, params.user, 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 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\n    if (params.from != params.to && params.scaledAmount != 0) {\n      DataTypes.UserConfigurationMap storage fromConfig = usersConfig[params.from];\n\n      if (fromConfig.isUsingAsCollateral(reserveId)) {\n        if (params.scaledBalanceFromBefore == params.scaledAmount) {\n          fromConfig.setUsingAsCollateral(reserveId, params.asset, params.from, false);\n        }\n        if (fromConfig.isBorrowingAny()) {\n          ValidationLogic.validateHFAndLtvzero(\n            reservesData,\n            reservesList,\n            eModeCategories,\n            usersConfig[params.from],\n            params.asset,\n            params.from,\n            params.oracle,\n            params.fromEModeCategory\n          );\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 user The user calling the method\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 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 user,\n    address asset,\n    bool useAsCollateral,\n    address priceOracle,\n    uint8 userEModeCategory\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[asset];\n    DataTypes.ReserveConfigurationMap memory reserveConfigCached = reserve.configuration;\n\n    ValidationLogic.validateSetUseReserveAsCollateral(reserveConfigCached);\n\n    if (useAsCollateral == userConfig.isUsingAsCollateral(reserve.id)) return;\n\n    if (useAsCollateral) {\n      // When enabling a reserve as collateral, we want to ensure the user has at least some collateral\n      require(\n        IAToken(reserve.aTokenAddress).scaledBalanceOf(user) != 0,\n        Errors.UnderlyingBalanceZero()\n      );\n\n      require(\n        ValidationLogic.validateUseAsCollateral(\n          reservesData,\n          eModeCategories,\n          asset,\n          userEModeCategory\n        ),\n        Errors.UserHasAssetWithZeroLtv()\n      );\n\n      userConfig.setUsingAsCollateral(reserve.id, asset, user, true);\n    } else {\n      userConfig.setUsingAsCollateral(reserve.id, asset, user, false);\n      ValidationLogic.validateHFAndLtvzero(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        userConfig,\n        asset,\n        user,\n        priceOracle,\n        userEModeCategory\n      );\n    }\n  }\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 user The selected user\n   * @param oracle The address of the oracle\n   * @param categoryId The selected eMode categoryId\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    address user,\n    address oracle,\n    uint8 categoryId\n  ) external {\n    if (usersEModeCategory[user] == categoryId) return;\n\n    ValidationLogic.validateSetUserEMode(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      categoryId\n    );\n\n    usersEModeCategory[user] = categoryId;\n\n    ValidationLogic.validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      user,\n      categoryId,\n      oracle\n    );\n    emit IPool.UserEModeSet(user, categoryId);\n  }\n}\n"},"lib/aave-v3-origin-private/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 'openzeppelin-contracts/contracts/utils/math/SafeCast.sol';\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/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 {TokenMath} from '../helpers/TokenMath.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 TokenMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\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 flashloanPremium;\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.flashloanPremium = params.isAuthorizedFlashBorrower ? 0 : params.flashLoanPremium;\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.percentMulCeil(vars.flashloanPremium)\n        : 0;\n\n      reservesData[params.assets[i]].virtualUnderlyingBalance -= vars.currentAmount.toUint128();\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        params.user,\n        params.params\n      ),\n      Errors.InvalidFlashloanExecutorReturn()\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            user: params.user,\n            asset: vars.currentAsset,\n            interestRateStrategyAddress: params.interestRateStrategyAddress,\n            receiverAddress: params.receiverAddress,\n            amount: vars.currentAmount,\n            totalPremium: vars.totalPremiums[i],\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            interestRateStrategyAddress: params.interestRateStrategyAddress,\n            user: params.user,\n            onBehalfOf: params.onBehalfOf,\n            amount: vars.currentAmount,\n            interestRateMode: DataTypes.InterestRateMode(params.interestRateModes[i]),\n            referralCode: params.referralCode,\n            releaseUnderlying: false,\n            oracle: IPoolAddressesProvider(params.addressesProvider).getPriceOracle(),\n            userEModeCategory: IPool(params.pool).getUserEMode(params.onBehalfOf).toUint8()\n          })\n        );\n        // no premium is paid when taking on the flashloan as debt\n        emit IPool.FlashLoan(\n          params.receiverAddress,\n          params.user,\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.percentMulCeil(params.flashLoanPremium);\n\n    reserve.virtualUnderlyingBalance -= params.amount.toUint128();\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        params.user,\n        params.params\n      ),\n      Errors.InvalidFlashloanExecutorReturn()\n    );\n\n    _handleFlashLoanRepayment(\n      reserve,\n      DataTypes.FlashLoanRepaymentParams({\n        user: params.user,\n        asset: params.asset,\n        interestRateStrategyAddress: params.interestRateStrategyAddress,\n        receiverAddress: params.receiverAddress,\n        amount: params.amount,\n        totalPremium: totalPremium,\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 amountPlusPremium = params.amount + params.totalPremium;\n\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n\n    reserve.accruedToTreasury += params\n      .totalPremium\n      .getATokenMintScaledAmount(reserveCache.nextLiquidityIndex)\n      .toUint128();\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      amountPlusPremium,\n      0,\n      params.interestRateStrategyAddress\n    );\n\n    IERC20(params.asset).safeTransferFrom(\n      params.receiverAddress,\n      reserveCache.aTokenAddress,\n      amountPlusPremium\n    );\n\n    emit IPool.FlashLoan(\n      params.receiverAddress,\n      params.user,\n      params.asset,\n      params.amount,\n      DataTypes.InterestRateMode.NONE,\n      params.totalPremium,\n      params.referralCode\n    );\n  }\n}\n"},"lib/aave-v3-origin-private/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 'openzeppelin-contracts/contracts/utils/math/SafeCast.sol';\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {TokenMath} from '../../libraries/helpers/TokenMath.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';\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 TokenMath for uint256;\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  /**\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.\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    uint256 amountScaled = params.amount.getVTokenMintScaledAmount(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    ValidationLogic.validateBorrow(\n      reservesData,\n      eModeCategories,\n      DataTypes.ValidateBorrowParams({\n        reserveCache: reserveCache,\n        asset: params.asset,\n        amountScaled: amountScaled,\n        interestRateMode: params.interestRateMode,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    reserveCache.nextScaledVariableDebt = IVariableDebtToken(reserveCache.variableDebtTokenAddress)\n      .mint(\n        params.user,\n        params.onBehalfOf,\n        params.amount,\n        amountScaled,\n        reserveCache.nextVariableBorrowIndex\n      );\n\n    uint16 cachedReserveId = reserve.id;\n    if (!userConfig.isBorrowing(cachedReserveId)) {\n      userConfig.setBorrowing(cachedReserveId, true);\n    }\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      0,\n      params.releaseUnderlying ? params.amount : 0,\n      params.interestRateStrategyAddress\n    );\n\n    if (params.releaseUnderlying) {\n      IAToken(reserveCache.aTokenAddress).transferUnderlyingTo(params.user, params.amount);\n    }\n\n    ValidationLogic.validateHFAndLtv(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      params.onBehalfOf,\n      params.userEModeCategory,\n      params.oracle\n    );\n\n    emit IPool.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.\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 onBehalfOfConfig 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    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage onBehalfOfConfig,\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 userDebtScaled = IVariableDebtToken(reserveCache.variableDebtTokenAddress)\n      .scaledBalanceOf(params.onBehalfOf);\n    uint256 userDebt = userDebtScaled.getVTokenBalance(reserveCache.nextVariableBorrowIndex);\n\n    ValidationLogic.validateRepay(\n      params.user,\n      reserveCache,\n      params.amount,\n      params.interestRateMode,\n      params.onBehalfOf,\n      userDebtScaled\n    );\n\n    uint256 paybackAmount = params.amount;\n    if (params.useATokens && params.amount == type(uint256).max) {\n      // Allows a user to repay with aTokens without leaving dust from interest.\n      paybackAmount = IAToken(reserveCache.aTokenAddress)\n        .scaledBalanceOf(params.user)\n        .getATokenBalance(reserveCache.nextLiquidityIndex);\n    }\n\n    if (paybackAmount > userDebt) {\n      paybackAmount = userDebt;\n    }\n\n    bool noMoreDebt;\n    (noMoreDebt, reserveCache.nextScaledVariableDebt) = IVariableDebtToken(\n      reserveCache.variableDebtTokenAddress\n    ).burn({\n        from: params.onBehalfOf,\n        scaledAmount: paybackAmount.getVTokenBurnScaledAmount(reserveCache.nextVariableBorrowIndex),\n        index: reserveCache.nextVariableBorrowIndex\n      });\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      params.useATokens ? 0 : paybackAmount,\n      0,\n      params.interestRateStrategyAddress\n    );\n\n    if (noMoreDebt) {\n      onBehalfOfConfig.setBorrowing(reserve.id, false);\n    }\n\n    // in case of aToken repayment the sender must always repay on behalf of itself\n    if (params.useATokens) {\n      // As aToken.burn rounds up the burned shares, we ensure at least an equivalent of >= paybackAmount is burned.\n      bool zeroBalanceAfterBurn = IAToken(reserveCache.aTokenAddress).burn({\n        from: params.user,\n        receiverOfUnderlying: reserveCache.aTokenAddress,\n        amount: paybackAmount,\n        scaledAmount: paybackAmount.getATokenBurnScaledAmount(reserveCache.nextLiquidityIndex),\n        index: reserveCache.nextLiquidityIndex\n      });\n      if (onBehalfOfConfig.isUsingAsCollateral(reserve.id)) {\n        if (zeroBalanceAfterBurn) {\n          onBehalfOfConfig.setUsingAsCollateral(reserve.id, params.asset, params.user, false);\n        }\n\n        if (onBehalfOfConfig.isBorrowingAny()) {\n          ValidationLogic.validateHealthFactor(\n            reservesData,\n            reservesList,\n            eModeCategories,\n            onBehalfOfConfig,\n            params.user,\n            params.userEModeCategory,\n            params.oracle\n          );\n        }\n      }\n    } else {\n      IERC20(params.asset).safeTransferFrom(params.user, reserveCache.aTokenAddress, paybackAmount);\n    }\n\n    emit IPool.Repay(\n      params.asset,\n      params.onBehalfOf,\n      params.user,\n      paybackAmount,\n      params.useATokens\n    );\n\n    return paybackAmount;\n  }\n}\n"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/logic/LiquidationLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {PercentageMath} from '../../libraries/math/PercentageMath.sol';\nimport {MathUtils} from '../../libraries/math/MathUtils.sol';\nimport {TokenMath} from '../../libraries/helpers/TokenMath.sol';\nimport {DataTypes} from '../../libraries/types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {GenericLogic} from './GenericLogic.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 {IPool} from '../../../interfaces/IPool.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {SafeCast} from 'openzeppelin-contracts/contracts/utils/math/SafeCast.sol';\nimport {Errors} from '../helpers/Errors.sol';\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 TokenMath 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  /**\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 the equivalent aToken `amount`\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   * @return The amount of deficit covered\n   */\n  function executeEliminateDeficit(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteEliminateDeficitParams memory params\n  ) external returns (uint256) {\n    require(params.amount != 0, Errors.InvalidAmount());\n\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    uint256 currentDeficit = reserve.deficit;\n\n    require(currentDeficit != 0, Errors.ReserveNotInDeficit());\n    require(!userConfig.isBorrowingAny(), Errors.UserCannotHaveDebt());\n\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n    bool isActive = reserveCache.reserveConfiguration.getActive();\n    require(isActive, Errors.ReserveInactive());\n\n    uint256 balanceWriteOff = params.amount;\n\n    if (params.amount > currentDeficit) {\n      balanceWriteOff = currentDeficit;\n    }\n\n    uint256 userScaledBalance = IAToken(reserveCache.aTokenAddress).scaledBalanceOf(params.user);\n    uint256 scaledBalanceWriteOff = balanceWriteOff.getATokenBurnScaledAmount(\n      reserveCache.nextLiquidityIndex\n    );\n    require(scaledBalanceWriteOff <= userScaledBalance, Errors.NotEnoughAvailableUserBalance());\n\n    bool isCollateral = userConfig.isUsingAsCollateral(reserve.id);\n    if (isCollateral && scaledBalanceWriteOff == userScaledBalance) {\n      userConfig.setUsingAsCollateral(reserve.id, params.asset, params.user, false);\n    }\n\n    IAToken(reserveCache.aTokenAddress).burn({\n      from: params.user,\n      receiverOfUnderlying: reserveCache.aTokenAddress,\n      amount: balanceWriteOff,\n      scaledAmount: scaledBalanceWriteOff,\n      index: reserveCache.nextLiquidityIndex\n    });\n\n    reserve.deficit -= balanceWriteOff.toUint128();\n\n    reserve.updateInterestRatesAndVirtualBalance(\n      reserveCache,\n      params.asset,\n      0,\n      0,\n      params.interestRateStrategyAddress\n    );\n\n    emit IPool.DeficitCovered(params.asset, params.user, balanceWriteOff);\n\n    return balanceWriteOff;\n  }\n\n  struct LiquidationCallLocalVars {\n    uint256 borrowerCollateralBalance;\n    uint256 borrowerReserveDebt;\n    uint256 actualDebtToLiquidate;\n    uint256 actualCollateralToLiquidate;\n    uint256 liquidationBonus;\n    uint256 healthFactor;\n    uint256 liquidationProtocolFeeAmount;\n    uint256 totalCollateralInBaseCurrency;\n    uint256 totalDebtInBaseCurrency;\n    uint256 borrowerReserveDebtInBaseCurrency;\n    uint256 borrowerReserveCollateralInBaseCurrency;\n    uint256 borrowerScaledCollateralBalance;\n    uint256 collateralAssetPrice;\n    uint256 debtAssetPrice;\n    uint256 collateralAssetUnit;\n    uint256 debtAssetUnit;\n    DataTypes.ReserveCache debtReserveCache;\n    DataTypes.ReserveCache collateralReserveCache;\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 borrowerConfig = usersConfig[params.borrower];\n    vars.debtReserveCache = debtReserve.cache();\n    debtReserve.updateState(vars.debtReserveCache);\n    // caching of the collateral happens after debtReserveCache is updated\n    // this ensures a non stale cache is used\n    vars.collateralReserveCache = collateralReserve.cache();\n    collateralReserve.updateState(vars.collateralReserveCache);\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: borrowerConfig,\n        user: params.borrower,\n        oracle: params.priceOracle,\n        userEModeCategory: params.borrowerEModeCategory\n      })\n    );\n\n    vars.borrowerScaledCollateralBalance = IAToken(vars.collateralReserveCache.aTokenAddress)\n      .scaledBalanceOf(params.borrower);\n    vars.borrowerCollateralBalance = vars.borrowerScaledCollateralBalance.getATokenBalance(\n      vars.collateralReserveCache.nextLiquidityIndex\n    );\n    vars.borrowerReserveDebt = IVariableDebtToken(vars.debtReserveCache.variableDebtTokenAddress)\n      .scaledBalanceOf(params.borrower)\n      .getVTokenBalance(vars.debtReserveCache.nextVariableBorrowIndex);\n\n    ValidationLogic.validateLiquidationCall(\n      borrowerConfig,\n      collateralReserve,\n      debtReserve,\n      DataTypes.ValidateLiquidationCallParams({\n        debtReserveCache: vars.debtReserveCache,\n        totalDebt: vars.borrowerReserveDebt,\n        healthFactor: vars.healthFactor,\n        borrower: params.borrower,\n        liquidator: params.liquidator\n      })\n    );\n\n    if (\n      params.borrowerEModeCategory != 0 &&\n      EModeConfiguration.isReserveEnabledOnBitmap(\n        eModeCategories[params.borrowerEModeCategory].collateralBitmap,\n        collateralReserve.id\n      )\n    ) {\n      vars.liquidationBonus = eModeCategories[params.borrowerEModeCategory].liquidationBonus;\n    } else {\n      vars.liquidationBonus = vars\n        .collateralReserveCache\n        .reserveConfiguration\n        .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 ** vars.collateralReserveCache.reserveConfiguration.getDecimals();\n    vars.debtAssetUnit = 10 ** vars.debtReserveCache.reserveConfiguration.getDecimals();\n\n    vars.borrowerReserveDebtInBaseCurrency = MathUtils.mulDivCeil(\n      vars.borrowerReserveDebt,\n      vars.debtAssetPrice,\n      vars.debtAssetUnit\n    );\n\n    // @note floor rounding\n    vars.borrowerReserveCollateralInBaseCurrency =\n      (vars.borrowerCollateralBalance * vars.collateralAssetPrice) /\n      vars.collateralAssetUnit;\n\n    // by default whole debt in the reserve could be liquidated\n    uint256 maxLiquidatableDebt = vars.borrowerReserveDebt;\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.borrowerReserveCollateralInBaseCurrency >= MIN_BASE_MAX_CLOSE_FACTOR_THRESHOLD &&\n      vars.borrowerReserveDebtInBaseCurrency >= 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.borrowerReserveDebtInBaseCurrency > 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    ) = _calculateAvailableCollateralToLiquidate(\n      vars.collateralReserveCache.reserveConfiguration,\n      vars.collateralAssetPrice,\n      vars.collateralAssetUnit,\n      vars.debtAssetPrice,\n      vars.debtAssetUnit,\n      vars.actualDebtToLiquidate,\n      vars.borrowerCollateralBalance,\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.borrowerReserveDebt &&\n      vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount <\n      vars.borrowerCollateralBalance\n    ) {\n      bool isDebtMoreThanLeftoverThreshold = MathUtils.mulDivCeil(\n        vars.borrowerReserveDebt - vars.actualDebtToLiquidate,\n        vars.debtAssetPrice,\n        vars.debtAssetUnit\n      ) >= MIN_LEFTOVER_BASE;\n\n      // @note floor rounding\n      bool isCollateralMoreThanLeftoverThreshold = ((vars.borrowerCollateralBalance -\n        vars.actualCollateralToLiquidate -\n        vars.liquidationProtocolFeeAmount) * vars.collateralAssetPrice) /\n        vars.collateralAssetUnit >=\n        MIN_LEFTOVER_BASE;\n\n      require(\n        isDebtMoreThanLeftoverThreshold && isCollateralMoreThanLeftoverThreshold,\n        Errors.MustNotLeaveDust()\n      );\n    }\n\n    // Determine whether the user's collateral is fully depleted after this liquidation.\n    //\n    // The actual token operations use rayDivCeil independently for the liquidator transfer and\n    // the protocol fee transfer. The sum of these ceil-rounded scaled amounts can meet or exceed\n    // the scaled balance even when the unscaled arithmetic predicts a small leftover. When this\n    // happens (reserveFullyConsumed), we use the full reserve value as consumed$ to correctly\n    // detect that no collateral remains.\n    //\n    // For high-decimal tokens (e.g., 18-decimal WETH), a genuine leftover of a few wei may\n    // round to $0 in base currency. In this case consumed$ also equals totalCollateral$ because\n    // the worthless dust vanishes in the floor division — so hasNoCollateralLeft is set correctly.\n    //\n    // Both getATokenBurnScaledAmount and getATokenTransferScaledAmount use rayDivCeil,\n    // so the scaled consumption is correct for both the receiveAToken and the burn path.\n    bool hasNoCollateralLeft;\n    {\n      uint256 scaledCollateralConsumed = vars.actualCollateralToLiquidate.getATokenBurnScaledAmount(\n          vars.collateralReserveCache.nextLiquidityIndex\n        ) +\n        vars.liquidationProtocolFeeAmount.getATokenTransferScaledAmount(\n          vars.collateralReserveCache.nextLiquidityIndex\n        );\n\n      // Cap to the actual scaled balance (the fee transfer is capped on-chain too, see L430)\n      if (scaledCollateralConsumed > vars.borrowerScaledCollateralBalance) {\n        scaledCollateralConsumed = vars.borrowerScaledCollateralBalance;\n      }\n\n      bool reserveFullyConsumed = scaledCollateralConsumed == vars.borrowerScaledCollateralBalance;\n\n      // Compute consumed$ from the capped scaled consumption.\n      // When reserveFullyConsumed, this equals the reserve's full base value.\n      // When not, a few-wei leftover that rounds to $0 makes consumed$ == totalCollateral$ too.\n      uint256 consumedInBaseCurrency = (scaledCollateralConsumed.getATokenBalance(\n          vars.collateralReserveCache.nextLiquidityIndex\n        ) * vars.collateralAssetPrice) / vars.collateralAssetUnit;\n\n      hasNoCollateralLeft = consumedInBaseCurrency == vars.totalCollateralInBaseCurrency;\n\n      // Clear the collateral flag when:\n      // - the reserve's scaled balance will be zero post-transfer, or\n      // - all user collateral is consumed (deficit will be created)\n      if (reserveFullyConsumed || hasNoCollateralLeft) {\n        borrowerConfig.setUsingAsCollateral(\n          collateralReserve.id,\n          params.collateralAsset,\n          params.borrower,\n          false\n        );\n      }\n    }\n    _burnDebtTokens(\n      vars.debtReserveCache,\n      debtReserve,\n      borrowerConfig,\n      params.borrower,\n      params.debtAsset,\n      vars.borrowerReserveDebt,\n      vars.actualDebtToLiquidate,\n      hasNoCollateralLeft,\n      params.interestRateStrategyAddress\n    );\n\n    if (params.receiveAToken) {\n      IAToken(vars.collateralReserveCache.aTokenAddress).transferOnLiquidation(\n        params.borrower,\n        params.liquidator,\n        vars.actualCollateralToLiquidate,\n        vars.actualCollateralToLiquidate.getATokenTransferScaledAmount(\n          vars.collateralReserveCache.nextLiquidityIndex\n        ),\n        vars.collateralReserveCache.nextLiquidityIndex\n      );\n    } else {\n      // @note Manually updating the cache in case the debt and collateral are the same asset.\n      // This ensures the rates are updated correctly, considering the burning of debt\n      // in the `_burnDebtTokens` function.\n      if (params.collateralAsset == params.debtAsset) {\n        vars.collateralReserveCache.nextScaledVariableDebt = vars\n          .debtReserveCache\n          .nextScaledVariableDebt;\n      }\n\n      _burnCollateralATokens(collateralReserve, params, vars);\n    }\n\n    // Transfer fee to treasury if it is non-zero\n    if (vars.liquidationProtocolFeeAmount != 0) {\n      // getATokenTransferScaledAmount has been used because under the hood, transferOnLiquidation is calling AToken.transfer\n      uint256 scaledDownLiquidationProtocolFee = vars\n        .liquidationProtocolFeeAmount\n        .getATokenTransferScaledAmount(vars.collateralReserveCache.nextLiquidityIndex);\n      uint256 scaledDownBorrowerBalance = IAToken(vars.collateralReserveCache.aTokenAddress)\n        .scaledBalanceOf(params.borrower);\n      // To avoid trying to send more aTokens than available on balance, due to 1 wei imprecision\n      if (scaledDownLiquidationProtocolFee > scaledDownBorrowerBalance) {\n        scaledDownLiquidationProtocolFee = scaledDownBorrowerBalance;\n        vars.liquidationProtocolFeeAmount = scaledDownBorrowerBalance.getATokenBalance(\n          vars.collateralReserveCache.nextLiquidityIndex\n        );\n      }\n      IAToken(vars.collateralReserveCache.aTokenAddress).transferOnLiquidation({\n        from: params.borrower,\n        to: IAToken(vars.collateralReserveCache.aTokenAddress).RESERVE_TREASURY_ADDRESS(),\n        amount: vars.liquidationProtocolFeeAmount,\n        scaledAmount: scaledDownLiquidationProtocolFee,\n        index: vars.collateralReserveCache.nextLiquidityIndex\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 && borrowerConfig.isBorrowingAny()) {\n      _burnBadDebt(reservesData, reservesList, borrowerConfig, params);\n    }\n\n    // Transfers the debt asset being repaid to the aToken, where the liquidity is kept\n    IERC20(params.debtAsset).safeTransferFrom(\n      params.liquidator,\n      vars.debtReserveCache.aTokenAddress,\n      vars.actualDebtToLiquidate\n    );\n\n    emit IPool.LiquidationCall(\n      params.collateralAsset,\n      params.debtAsset,\n      params.borrower,\n      vars.actualDebtToLiquidate,\n      vars.actualCollateralToLiquidate,\n      params.liquidator,\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    collateralReserve.updateInterestRatesAndVirtualBalance(\n      vars.collateralReserveCache,\n      params.collateralAsset,\n      0,\n      vars.actualCollateralToLiquidate,\n      params.interestRateStrategyAddress\n    );\n\n    // Burn the equivalent amount of aToken, sending the underlying to the liquidator\n    IAToken(vars.collateralReserveCache.aTokenAddress).burn({\n      from: params.borrower,\n      receiverOfUnderlying: params.liquidator,\n      amount: vars.actualCollateralToLiquidate,\n      scaledAmount: vars.actualCollateralToLiquidate.getATokenBurnScaledAmount(\n        vars.collateralReserveCache.nextLiquidityIndex\n      ),\n      index: vars.collateralReserveCache.nextLiquidityIndex\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 borrowerConfig The pointer of the user configuration\n   * @param borrower 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 borrowerConfig,\n    address borrower,\n    address debtAsset,\n    uint256 borrowerReserveDebt,\n    uint256 actualDebtToLiquidate,\n    bool hasNoCollateralLeft,\n    address interestRateStrategyAddress\n  ) internal {\n    bool noMoreDebt = true;\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 (borrowerReserveDebt != 0) {\n      uint256 burnAmount = hasNoCollateralLeft ? borrowerReserveDebt : actualDebtToLiquidate;\n\n      // As vDebt.burn rounds down, we ensure an equivalent of <= amount debt is burned.\n      (noMoreDebt, debtReserveCache.nextScaledVariableDebt) = IVariableDebtToken(\n        debtReserveCache.variableDebtTokenAddress\n      ).burn({\n          from: borrower,\n          scaledAmount: burnAmount.getVTokenBurnScaledAmount(\n            debtReserveCache.nextVariableBorrowIndex\n          ),\n          index: debtReserveCache.nextVariableBorrowIndex\n        });\n    }\n\n    uint256 outstandingDebt = borrowerReserveDebt - actualDebtToLiquidate;\n    if (hasNoCollateralLeft && outstandingDebt != 0) {\n      debtReserve.deficit += outstandingDebt.toUint128();\n      emit IPool.DeficitCreated(borrower, debtAsset, outstandingDebt);\n    }\n\n    if (noMoreDebt) {\n      borrowerConfig.setBorrowing(debtReserve.id, false);\n    }\n\n    debtReserve.updateInterestRatesAndVirtualBalance(\n      debtReserveCache,\n      debtAsset,\n      actualDebtToLiquidate,\n      0,\n      interestRateStrategyAddress\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 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 borrowerCollateralBalance 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   */\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 borrowerCollateralBalance,\n    uint256 liquidationBonus\n  ) internal pure returns (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.percentMulFloor(liquidationBonus);\n\n    if (vars.maxCollateralToLiquidate > borrowerCollateralBalance) {\n      vars.collateralAmount = borrowerCollateralBalance;\n      vars.debtAmountNeeded = ((vars.collateralAssetPrice * vars.collateralAmount * debtAssetUnit) /\n        (debtAssetPrice * collateralAssetUnit)).percentDivCeil(liquidationBonus);\n    } else {\n      vars.collateralAmount = vars.maxCollateralToLiquidate;\n      vars.debtAmountNeeded = debtToCover;\n    }\n\n    if (vars.liquidationProtocolFeePercentage != 0) {\n      vars.bonusCollateral =\n        vars.collateralAmount -\n        vars.collateralAmount.percentDivFloor(liquidationBonus);\n\n      vars.liquidationProtocolFee = vars.bonusCollateral.percentMulCeil(\n        vars.liquidationProtocolFeePercentage\n      );\n      vars.collateralAmount -= vars.liquidationProtocolFee;\n    }\n    return (vars.collateralAmount, vars.debtAmountNeeded, vars.liquidationProtocolFee);\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 borrowerConfig The user configuration\n   * @param params The txn params\n   */\n  function _burnBadDebt(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage borrowerConfig,\n    DataTypes.ExecuteLiquidationCallParams memory params\n  ) internal {\n    // the cache is muted inside the iteration and should not be used for other operations\n    uint256 unsafe_cachedBorrowerConfig = borrowerConfig.data;\n    uint256 i = 0;\n    bool isBorrowed = false;\n    while (unsafe_cachedBorrowerConfig != 0) {\n      (unsafe_cachedBorrowerConfig, isBorrowed, ) = UserConfiguration.getNextFlags(\n        unsafe_cachedBorrowerConfig\n      );\n      if (isBorrowed) {\n        address reserveAddress = reservesList[i];\n        // @dev legacy check from when dropReserve could leave gaps; see docs/3.7/drop-reserve-removal.md\n        if (reserveAddress != address(0)) {\n          DataTypes.ReserveCache memory reserveCache = reservesData[reserveAddress].cache();\n          if (reserveCache.reserveConfiguration.getActive()) {\n            reservesData[reserveAddress].updateState(reserveCache);\n\n            _burnDebtTokens(\n              reserveCache,\n              reservesData[reserveAddress],\n              borrowerConfig,\n              params.borrower,\n              reserveAddress,\n              IVariableDebtToken(reserveCache.variableDebtTokenAddress)\n                .scaledBalanceOf(params.borrower)\n                .getVTokenBalance(reserveCache.nextVariableBorrowIndex),\n              0,\n              true,\n              params.interestRateStrategyAddress\n            );\n          }\n        }\n      }\n      unchecked {\n        ++i;\n      }\n    }\n  }\n}\n"},"lib/aave-v3-origin-private/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    // DEPRECATED on v3.4.0, should use the `RESERVE_INTEREST_RATE_STRATEGY` variable from the Pool contract\n    address interestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    // DEPRECATED on v3.4.0\n    uint128 unbacked;\n    // DEPRECATED on v3.7.0\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    // DEPRECATED on v3.4.0, should use the `RESERVE_INTEREST_RATE_STRATEGY` variable from the Pool contract\n    address __deprecatedInterestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    // In aave 3.3.0 this storage slot contained the `unbacked`\n    uint128 virtualUnderlyingBalance;\n    //the outstanding debt borrowed against this asset in isolation mode\n    uint128 __deprecatedIsolationModeTotalDebt;\n    //the amount of underlying accounted for by the protocol\n    // DEPRECATED on v3.4.0. Moved into the same slot as accruedToTreasury for optimized storage access.\n    uint128 __deprecatedVirtualUnderlyingBalance;\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: DEPRECATED: borrowing in isolation mode is enabled\n    //bit 62: DEPRECATED: 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: DEPRECATED: unbacked mint cap\n    //bit 212-251: DEPRECATED: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n    //bit 252: DEPRECATED: 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    bool isolated;\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    bool isolated; // if true, only assets in collateralBitmap can be used as collateral, and all others will have ltv0 rules applying\n    string label;\n    uint128 borrowableBitmap;\n    uint128 ltvzeroBitmap; // if true, the asset will be treated as ltv0 and ltv0 rules apply\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    address liquidator;\n    uint256 debtToCover;\n    address collateralAsset;\n    address debtAsset;\n    address borrower;\n    bool receiveAToken;\n    address priceOracle;\n    uint8 borrowerEModeCategory;\n    address interestRateStrategyAddress;\n  }\n\n  struct ExecuteSupplyParams {\n    address user;\n    address asset;\n    address interestRateStrategyAddress;\n    uint256 amount;\n    address onBehalfOf;\n    uint16 referralCode;\n    uint8 supplierEModeCategory;\n  }\n\n  struct ExecuteBorrowParams {\n    address asset;\n    address user;\n    address onBehalfOf;\n    address interestRateStrategyAddress;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint16 referralCode;\n    bool releaseUnderlying;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteRepayParams {\n    address asset;\n    address user;\n    address interestRateStrategyAddress;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    address onBehalfOf;\n    bool useATokens;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteWithdrawParams {\n    address user;\n    address asset;\n    address interestRateStrategyAddress;\n    uint256 amount;\n    address to;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteEliminateDeficitParams {\n    address user;\n    address asset;\n    address interestRateStrategyAddress;\n    uint256 amount;\n  }\n\n  struct FinalizeTransferParams {\n    address asset;\n    address from;\n    address to;\n    uint256 scaledAmount;\n    uint256 scaledBalanceFromBefore;\n    address oracle;\n    uint8 fromEModeCategory;\n  }\n\n  struct FlashloanParams {\n    address user;\n    address receiverAddress;\n    address[] assets;\n    uint256[] amounts;\n    uint256[] interestRateModes;\n    address interestRateStrategyAddress;\n    address onBehalfOf;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremium;\n    address addressesProvider;\n    address pool;\n    bool isAuthorizedFlashBorrower;\n  }\n\n  struct FlashloanSimpleParams {\n    address user;\n    address receiverAddress;\n    address asset;\n    address interestRateStrategyAddress;\n    uint256 amount;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremium;\n  }\n\n  struct FlashLoanRepaymentParams {\n    address user;\n    uint256 amount;\n    uint256 totalPremium;\n    address asset;\n    address interestRateStrategyAddress;\n    address receiverAddress;\n    uint16 referralCode;\n  }\n\n  struct CalculateUserAccountDataParams {\n    UserConfigurationMap userConfig;\n    address user;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ValidateBorrowParams {\n    ReserveCache reserveCache;\n    address asset;\n    uint256 amountScaled;\n    InterestRateMode interestRateMode;\n    uint8 userEModeCategory;\n  }\n\n  struct ValidateLiquidationCallParams {\n    ReserveCache debtReserveCache;\n    uint256 totalDebt;\n    uint256 healthFactor;\n    address borrower;\n    address liquidator;\n  }\n\n  struct CalculateInterestRatesParams {\n    uint256 unbacked;\n    uint256 liquidityAdded;\n    uint256 liquidityTaken;\n    uint256 totalDebt;\n    uint256 reserveFactor;\n    address reserve;\n    // @notice DEPRECATED in 3.4, but kept for backwards compatibility\n    bool usingVirtualBalance;\n    uint256 virtualUnderlyingBalance;\n  }\n\n  struct InitReserveParams {\n    address asset;\n    address aTokenAddress;\n    address variableDebtAddress;\n    uint16 reservesCount;\n    uint16 maxNumberReserves;\n  }\n}\n"},"lib/aave-v3-origin-private/src/contracts/interfaces/IERC20WithPermit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/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"},"lib/aave-v3-origin-private/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 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 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   * @dev Emitted when a position manager is approved by the user.\n   * @param user The user address\n   * @param positionManager The address of the position manager\n   */\n  event PositionManagerApproved(address indexed user, address indexed positionManager);\n\n  /**\n   * @dev Emitted when a position manager is revoked by the user.\n   * @param user The user address\n   * @param positionManager The address of the position manager\n   */\n  event PositionManagerRevoked(address indexed user, address indexed positionManager);\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 borrower 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 borrower,\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\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   */\n  function initReserve(address asset, address aTokenAddress, address variableDebtAddress) 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 scaledAmount The scaled amount being transferred/withdrawn\n   * @param scaledBalanceFromBefore The aToken scaled balance of the `from` user before the transfer\n   */\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 scaledAmount,\n    uint256 scaledBalanceFromBefore\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 Returns the ReserveInterestRateStrategy connected to all the reserves\n   * @return The address of the ReserveInterestRateStrategy contract\n   */\n  function RESERVE_INTEREST_RATE_STRATEGY() external view returns (address);\n\n  /**\n   * @notice Updates flash loan premium. All this premium is collected by the protocol treasury.\n   * @dev The premium is calculated on the total borrowed amount\n   * @dev Only callable by the PoolConfigurator contract\n   * @param flashLoanPremium The flash loan premium, expressed in bps\n   */\n  function updateFlashloanPremium(uint128 flashLoanPremium) 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 Replaces the current eMode ltvzeroBitmap.\n   * @param id The id of the category\n   * @param ltvzeroBitmap The ltvzeroBitmap of the category\n   */\n  function configureEModeCategoryLtvzeroBitmap(uint8 id, uint128 ltvzeroBitmap) external;\n\n  /**\n   * @notice Sets the isolated flag of an eMode category.\n   * @param id The id of the category\n   * @param isolated True if the eMode should be isolated\n   */\n  function configureEModeCategoryIsolated(uint8 id, bool isolated) 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   * @dev This function is deprecated and will be removed in a future version.\n   * @custom:deprecated\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 Returns the ltvzero of an eMode category\n   * @param id The id of the category\n   * @return The ltvzeroBitmap of the category\n   */\n  function getEModeCategoryLtvzeroBitmap(uint8 id) external view returns (uint128);\n\n  /**\n   * @notice Returns the isolated flag of an eMode category\n   * @param id The id of the category\n   * @return True if the eMode category is isolated\n   */\n  function getIsEModeCategoryIsolated(uint8 id) external view returns (bool);\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 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   * @dev From v3.4 all flashloan fees will be send to the treasury.\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 flashloan fees sent to protocol\n   * @dev From v3.4 all flashloan fees will be send to the treasury and this value\n   *      is always 100_00.\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 the equivalent aToken `amount` for assets\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\n   * @return The amount of tokens burned\n   */\n  function eliminateReserveDeficit(address asset, uint256 amount) external returns (uint256);\n\n  /**\n   * @notice Approves or disapproves a position manager. This position manager will be able\n   * to call the `setUserUseReserveAsCollateralOnBehalfOf` and the\n   * `setUserEModeOnBehalfOf` function on behalf of the user.\n   * @param positionManager The address of the position manager\n   * @param approve True if the position manager should be approved, false otherwise\n   */\n  function approvePositionManager(address positionManager, bool approve) external;\n\n  /**\n   * @notice Renounces a position manager role for a given user.\n   * @param user The address of the user\n   */\n  function renouncePositionManagerRole(address user) external;\n\n  /**\n   * @notice Sets the use as collateral flag for the user on the specific reserve on behalf of the user.\n   * @param asset The address of the underlying asset of the reserve\n   * @param useAsCollateral True if the user wants to use the reserve as collateral, false otherwise\n   * @param onBehalfOf The address of the user\n   */\n  function setUserUseReserveAsCollateralOnBehalfOf(\n    address asset,\n    bool useAsCollateral,\n    address onBehalfOf\n  ) external;\n\n  /**\n   * @notice Sets the eMode category for the user on the specific reserve on behalf of the user.\n   * @param categoryId The id of the category\n   * @param onBehalfOf The address of the user\n   */\n  function setUserEModeOnBehalfOf(uint8 categoryId, address onBehalfOf) external;\n\n  /**\n   * @notice Returns true if the `positionManager` address is approved to use the position manager role on behalf of the user.\n   * @param user The address of the user\n   * @param positionManager The address of the position manager\n   * @return True if the user is approved to use the position manager, false otherwise\n   */\n  function isApprovedPositionManager(\n    address user,\n    address positionManager\n  ) external view returns (bool);\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 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"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/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 __DEPRECATED_bridgeProtocolFee;\n\n  // FlashLoan Premium, expressed in bps.\n  // From v3.4 all flashloan premium is paid to treasury.\n  uint128 internal _flashLoanPremium;\n\n  // FlashLoan premium paid to protocol treasury, expressed in bps.\n  // From v3.4 all flashloan premium is paid to treasury.\n  uint128 internal __DEPRECATED_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  // Allowlisted permissionManagers can enable collaterals & switch eModes on behalf of a user\n  mapping(address user => mapping(address permittedPositionManager => bool))\n    internal _positionManager;\n}\n"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert Errors.FailedCall();\n        }\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 or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\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    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\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    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\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            assembly (\"memory-safe\") {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\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 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) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"lib/aave-v3-origin-private/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/contracts/token/ERC20/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"},"lib/aave-v3-origin-private/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"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\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    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n     * 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 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` 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 from, address to, uint256 value) external returns (bool);\n}\n"},"lib/aave-v3-origin-private/src/contracts/interfaces/IAToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/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 scaledAmount The scaled 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 scaledAmount,\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 Passing both the unscaled and scaled amounts enhances precision. The `scaledAmount` is used for precise balance updates,\n   * while the `amount` is used for the underlying asset transfer, preventing cumulative rounding errors.\n   * @dev In some instances, a mint event may be emitted from a burn transaction 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 of underlying to be burned (non scaled)\n   * @param scaledAmount The scaled amount of aTokens to be burned (scaled)\n   * @param index The next liquidity index of the reserve\n   * @return `true` if the the new balance of the user is 0\n   */\n  function burn(\n    address from,\n    address receiverOfUnderlying,\n    uint256 amount,\n    uint256 scaledAmount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @notice Mints aTokens to the reserve treasury\n   * @param scaledAmount The scaled amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   */\n  function mintToTreasury(uint256 scaledAmount, uint256 index) external;\n\n  /**\n   * @notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidator reclaims the aToken.\n   * @dev Passing both the unscaled and scaled amounts enhances precision. The `scaledAmount` is used for precise balance updates,\n   * while the `amount` is used for logging and consistency, preventing cumulative rounding errors.\n   * @param from The address getting liquidated, current owner of the aTokens\n   * @param to The recipient\n   * @param amount The amount of tokens getting transferred (non-scaled)\n   * @param scaledAmount The scaled amount of tokens getting transferred (scaled)\n   * @param index The next liquidity index of the reserve\n   */\n  function transferOnLiquidation(\n    address from,\n    address to,\n    uint256 amount,\n    uint256 scaledAmount,\n    uint256 index\n  ) 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 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"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/helpers/TokenMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\n\n/**\n * @title TokenMath\n * @author BGD Labs\n * @notice Provides utility functions for calculating scaled amounts and balances for aTokens and vTokens,\n *         applying specific rounding rules (floor/ceil) as per Aave v3.5's rounding improvements.\n *         The rounding behavior of the operations is in line with the ERC-4626 token standard.\n *         In practice, this means rounding in favor of the protocol.\n */\nlibrary TokenMath {\n  using WadRayMath for uint256;\n\n  /**\n   * @notice Calculates the scaled amount of aTokens to mint when supplying underlying assets.\n   *         The amount is rounded down to ensure the minted aTokens are less than or equal to the supplied amount.\n   * @param amount The amount of underlying asset supplied.\n   * @param liquidityIndex The current aToken liquidityIndex.\n   * @return The scaled amount of aTokens to mint.\n   */\n  function getATokenMintScaledAmount(\n    uint256 amount,\n    uint256 liquidityIndex\n  ) internal pure returns (uint256) {\n    return amount.rayDivFloor(liquidityIndex);\n  }\n\n  /**\n   * @notice Calculates the scaled amount of aTokens to burn when withdrawing underlying assets.\n   *         The scaled amount is rounded up to ensure the user's aToken balance is sufficiently reduced.\n   * @param amount The amount of underlying asset to withdraw.\n   * @param liquidityIndex The current aToken liquidityIndex.\n   * @return The scaled amount of aTokens to burn.\n   */\n  function getATokenBurnScaledAmount(\n    uint256 amount,\n    uint256 liquidityIndex\n  ) internal pure returns (uint256) {\n    return amount.rayDivCeil(liquidityIndex);\n  }\n\n  /**\n   * @notice Calculates the scaled amount of aTokens to transfer.\n   *         The scaled amount is rounded up to ensure the recipient receives at least the requested amount.\n   * @param amount The amount of aTokens to transfer.\n   * @param liquidityIndex The current aToken liquidityIndex.\n   * @return The scaled amount of aTokens for transfer.\n   */\n  function getATokenTransferScaledAmount(\n    uint256 amount,\n    uint256 liquidityIndex\n  ) internal pure returns (uint256) {\n    return amount.rayDivCeil(liquidityIndex);\n  }\n\n  /**\n   * @notice Calculates the actual aToken balance from a scaled balance and the current liquidityIndex.\n   *         The balance is rounded down to prevent overaccounting.\n   * @param scaledAmount The scaled aToken balance.\n   * @param liquidityIndex The current aToken liquidityIndex.\n   * @return The actual aToken balance.\n   */\n  function getATokenBalance(\n    uint256 scaledAmount,\n    uint256 liquidityIndex\n  ) internal pure returns (uint256) {\n    return scaledAmount.rayMulFloor(liquidityIndex);\n  }\n\n  /**\n   * @notice Calculates the scaled amount of vTokens to mint when borrowing.\n   *         The amount is rounded up to ensure the protocol never underaccounts the user's debt.\n   * @param amount The amount of underlying asset borrowed.\n   * @param variableBorrowIndex The current vToken variableBorrowIndex.\n   * @return The scaled amount of vTokens to mint.\n   */\n  function getVTokenMintScaledAmount(\n    uint256 amount,\n    uint256 variableBorrowIndex\n  ) internal pure returns (uint256) {\n    return amount.rayDivCeil(variableBorrowIndex);\n  }\n\n  /**\n   * @notice Calculates the scaled amount of vTokens to burn.\n   *         The scaled amount is rounded down to prevent over-burning of vTokens.\n   * @param amount The amount of underlying asset corresponding to the vTokens to burn.\n   * @param variableBorrowIndex The current vToken variableBorrowIndex.\n   * @return The scaled amount of vTokens to burn.\n   */\n  function getVTokenBurnScaledAmount(\n    uint256 amount,\n    uint256 variableBorrowIndex\n  ) internal pure returns (uint256) {\n    return amount.rayDivFloor(variableBorrowIndex);\n  }\n\n  /**\n   * @notice Calculates the actual vToken balance (debt) from a scaled balance and the current variableBorrowIndex.\n   *         The balance is rounded up to prevent underaccounting the user's debt.\n   * @param scaledAmount The scaled vToken balance.\n   * @param variableBorrowIndex The current vToken variableBorrowIndex.\n   * @return The actual vToken balance (debt).\n   */\n  function getVTokenBalance(\n    uint256 scaledAmount,\n    uint256 variableBorrowIndex\n  ) internal pure returns (uint256) {\n    return scaledAmount.rayMulCeil(variableBorrowIndex);\n  }\n}\n"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/logic/GenericLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\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 {TokenMath} from '../helpers/TokenMath.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ValidationLogic} from './ValidationLogic.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 TokenMath for uint256;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  struct CalculateUserAccountDataVars {\n    uint256 assetPrice;\n    uint256 assetUnit;\n    uint256 userBalanceInBaseCurrency;\n    uint256 unsafe_cachedUserConfig;\n    DataTypes.ReserveConfigurationMap configurationCache;\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 eModeLiqThreshold;\n    uint128 eModeCollateralBitmap;\n    address currentReserveAddress;\n    bool hasZeroLtvCollateral;\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.eModeLiqThreshold = eModeCategories[params.userEModeCategory].liquidationThreshold;\n      vars.eModeCollateralBitmap = eModeCategories[params.userEModeCategory].collateralBitmap;\n    }\n\n    vars.unsafe_cachedUserConfig = params.userConfig.data;\n    bool isBorrowed = false;\n    bool isEnabledAsCollateral = false;\n\n    while (vars.unsafe_cachedUserConfig != 0) {\n      (vars.unsafe_cachedUserConfig, isBorrowed, isEnabledAsCollateral) = UserConfiguration\n        .getNextFlags(vars.unsafe_cachedUserConfig);\n      if (isEnabledAsCollateral || isBorrowed) {\n        vars.currentReserveAddress = reservesList[vars.i];\n\n        // @dev legacy check from when dropReserve could leave gaps; see docs/3.7/drop-reserve-removal.md\n        if (vars.currentReserveAddress != address(0)) {\n          DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];\n          vars.configurationCache = currentReserve.configuration;\n\n          unchecked {\n            vars.assetUnit = 10 ** vars.configurationCache.getDecimals();\n          }\n\n          vars.assetPrice = IPriceOracleGetter(params.oracle).getAssetPrice(\n            vars.currentReserveAddress\n          );\n\n          if (isEnabledAsCollateral) {\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.ltv = ValidationLogic.getUserReserveLtv(\n              currentReserve,\n              eModeCategories[params.userEModeCategory],\n              params.userEModeCategory\n            );\n            if (vars.ltv == 0) {\n              vars.hasZeroLtvCollateral = true;\n            } else {\n              vars.avgLtv += vars.userBalanceInBaseCurrency * vars.ltv;\n            }\n\n            if (\n              params.userEModeCategory != 0 &&\n              EModeConfiguration.isReserveEnabledOnBitmap(vars.eModeCollateralBitmap, vars.i)\n            ) {\n              vars.liquidationThreshold = vars.eModeLiqThreshold;\n            } else {\n              vars.liquidationThreshold = vars.configurationCache.getLiquidationThreshold();\n            }\n\n            vars.avgLiquidationThreshold +=\n              vars.userBalanceInBaseCurrency *\n              vars.liquidationThreshold;\n          }\n\n          if (isBorrowed) {\n            vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(\n              params.user,\n              currentReserve,\n              vars.assetPrice,\n              vars.assetUnit\n            );\n          }\n        }\n      }\n\n      unchecked {\n        ++vars.i;\n      }\n    }\n\n    // @note At this point, `avgLiquidationThreshold` represents\n    // `SUM(collateral_base_value_i * liquidation_threshold_i)` for all collateral assets.\n    // It has 8 decimals (base currency) + 2 decimals (percentage) = 10 decimals.\n    // healthFactor has 18 decimals\n    // healthFactor = (avgLiquidationThreshold * WAD / totalDebtInBaseCurrency) / 100_00\n    // 18 decimals = (10 decimals * 18 decimals / 8 decimals) / 2 decimals = 18 decimals\n    vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)\n      ? type(uint256).max\n      : vars.avgLiquidationThreshold.wadDiv(vars.totalDebtInBaseCurrency) / 100_00;\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    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.percentMulFloor(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    uint256 userTotalDebt = IScaledBalanceToken(reserve.variableDebtTokenAddress)\n      .scaledBalanceOf(user)\n      .getVTokenBalance(reserve.getNormalizedDebt());\n\n    return MathUtils.mulDivCeil(userTotalDebt, assetPrice, assetUnit);\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 balance = (\n      IScaledBalanceToken(reserve.aTokenAddress).scaledBalanceOf(user).getATokenBalance(\n        reserve.getNormalizedIncome()\n      )\n    ) * assetPrice;\n\n    unchecked {\n      return balance / assetUnit;\n    }\n  }\n}\n"},"lib/aave-v3-origin-private/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   * @dev Passing both the unscaled and scaled amounts enhances precision. The `scaledAmount` is used for precise balance updates,\n   * while the `amount` is used for allowance checks, preventing cumulative rounding errors.\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 unscaled amount of debt to be accounted for allowance\n   * @param scaledAmount The scaled amount of debt tokens to mint\n   * @param index The variable debt index of the reserve\n   * @return The scaled total debt of the reserve\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 scaledAmount,\n    uint256 index\n  ) external returns (uint256);\n\n  /**\n   * @notice Burns user variable debt.\n   * @dev Passing the scaled amount allows for more precise calculations and avoids cumulative errors from repeated conversions.\n   * @dev In some instances, a burn transaction will emit a mint event 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 scaledAmount The scaled amount of debt getting burned\n   * @param index The variable debt index of the reserve\n   * @return True if the new balance is zero\n   * @return The scaled total debt of the reserve\n   */\n  function burn(address from, uint256 scaledAmount, uint256 index) external returns (bool, 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"},"lib/aave-v3-origin-private/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    // calculations compound interest using the ideal formula - e^(rate per year * number of years)\n    // 100_000% per year = 1_000 * 100, passed 10_000 years:\n    // e^(1_000 * 10_000) = 6.5922325346184394895608861310659088446667722661221381641234330770... × 10^4342944\n\n    // The current formula in the contract returns:\n    // 1.66666716666676666667 × 10^20\n    // This happens because the contract uses a polynomial approximation of the ideal formula\n    // and on big numbers the ideal formula with exponential function has much more speed.\n    // Used approximation in contracts is not precise enough on such big numbers.\n    //\n    // But we can be sure that the current formula in contracts can't overflow on such big numbers\n    // and we can use unchecked arithmetics to save gas.\n    //\n    // Also, if we take into an account the fact that all timestamps are stored in uint32/40 types\n    // we can only have 100 years left until we will have overflows in timestamps.\n    // Because of that realistically we can't overflow in this formula.\n\n    unchecked {\n      // this can't overflow because rate is always fits in 128 bits and exp always fits in 40 bits\n      uint256 x = (rate * exp) / SECONDS_PER_YEAR;\n\n      return WadRayMath.RAY + x + x.rayMul(x / 2 + x.rayMul(x / 6));\n    }\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  function mulDivCeil(uint256 a, uint256 b, uint256 c) internal pure returns (uint256 d) {\n    assembly {\n      // Revert if c == 0 to avoid division by zero\n      if iszero(c) {\n        revert(0, 0)\n      }\n\n      // Overflow check: Ensure a * b does not exceed uint256 max\n      if iszero(or(iszero(b), iszero(gt(a, div(not(0), b))))) {\n        revert(0, 0)\n      }\n\n      let product := mul(a, b)\n      d := add(div(product, c), iszero(iszero(mod(product, c))))\n    }\n  }\n}\n"},"lib/aave-v3-origin-private/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 Default operations round half up (if a value is >= .5, it will be rounded up, otherwise rounded down).\n * @dev For specific rounding behaviors, functions with `Floor` and `Ceil` suffixes or a `Rounding` parameter are available.\n */\nlibrary WadRayMath {\n  enum Rounding {\n    Floor,\n    Ceil\n  }\n\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  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        revert(0, 0)\n      }\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  function rayMulFloor(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // Overflow check: Ensure a * b does not exceed uint256 max\n      if iszero(or(iszero(b), iszero(gt(a, div(not(0), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(mul(a, b), RAY)\n    }\n  }\n\n  function rayMulCeil(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // Overflow check: Ensure a * b does not exceed uint256 max\n      if iszero(or(iszero(b), iszero(gt(a, div(not(0), b))))) {\n        revert(0, 0)\n      }\n\n      let product := mul(a, b)\n      c := add(div(product, RAY), iszero(iszero(mod(product, 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    assembly {\n      // to avoid overflow, a <= (type(uint256).max - b / 2) / RAY\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) {\n        revert(0, 0)\n      }\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  function rayDivCeil(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // Overflow check: Ensure a * RAY does not exceed uint256 max\n      if or(iszero(b), iszero(iszero(gt(a, div(not(0), RAY))))) {\n        revert(0, 0)\n      }\n      let scaled := mul(a, RAY)\n      c := add(div(scaled, b), iszero(iszero(mod(scaled, b))))\n    }\n  }\n\n  function rayDivFloor(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // Overflow check: Ensure a * RAY does not exceed uint256 max\n      if or(iszero(b), iszero(iszero(gt(a, div(not(0), RAY))))) {\n        revert(0, 0)\n      }\n      c := div(mul(a, RAY), 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"},"lib/aave-v3-origin-private/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  function percentMulCeil(\n    uint256 value,\n    uint256 percentage\n  ) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= type(uint256).max / percentage\n    assembly {\n      if iszero(or(iszero(percentage), iszero(gt(value, div(not(0), percentage))))) {\n        revert(0, 0)\n      }\n\n      let product := mul(value, percentage)\n      result := add(\n        div(product, PERCENTAGE_FACTOR),\n        iszero(iszero(mod(product, PERCENTAGE_FACTOR)))\n      )\n    }\n  }\n\n  function percentMulFloor(\n    uint256 value,\n    uint256 percentage\n  ) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= type(uint256).max / percentage\n    assembly {\n      if iszero(or(iszero(percentage), iszero(gt(value, div(not(0), percentage))))) {\n        revert(0, 0)\n      }\n\n      result := div(mul(value, percentage), 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  function percentDivFloor(\n    uint256 value,\n    uint256 percentage\n  ) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= type(uint256).max / PERCENTAGE_FACTOR\n    assembly {\n      if or(iszero(percentage), iszero(iszero(gt(value, div(not(0), PERCENTAGE_FACTOR))))) {\n        revert(0, 0)\n      }\n      result := div(mul(value, PERCENTAGE_FACTOR), percentage)\n    }\n  }\n\n  function percentDivCeil(\n    uint256 value,\n    uint256 percentage\n  ) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= type(uint256).max / PERCENTAGE_FACTOR\n    assembly {\n      if or(iszero(percentage), iszero(iszero(gt(value, div(not(0), PERCENTAGE_FACTOR))))) {\n        revert(0, 0)\n      }\n      let val := mul(value, PERCENTAGE_FACTOR)\n      result := add(div(val, percentage), iszero(iszero(mod(val, percentage))))\n    }\n  }\n}\n"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool 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 */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\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        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(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        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(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        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(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        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(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        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(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        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\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        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\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        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\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    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\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    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\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    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\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    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\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    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\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        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/configuration/UserConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPool} from '../../../interfaces/IPool.sol';\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.InvalidReserveIndex());\n      // forge-lint: disable-next-line(incorrect-shift)\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 asset The address of the reserve\n   * @param user The address of the user\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    address asset,\n    address user,\n    bool usingAsCollateral\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.InvalidReserveIndex());\n      // forge-lint: disable-next-line(incorrect-shift)\n      uint256 bit = 1 << ((reserveIndex << 1) + 1);\n      if (usingAsCollateral) {\n        self.data |= bit;\n        emit IPool.ReserveUsedAsCollateralEnabled(asset, user);\n      } else {\n        self.data &= ~bit;\n        emit IPool.ReserveUsedAsCollateralDisabled(asset, user);\n      }\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.InvalidReserveIndex());\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.InvalidReserveIndex());\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 as collateral\n   * @param self The configuration object\n   * @return True if the user has not been borrowing, or using as collateral 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 borrowed and collateral flags for the first asset on the bitmap and the bitmap shifted by two.\n   * @dev This function mutates the input and the 2 bit slots in the bitmap will no longer correspond to the reserve index.\n   * This is useful in situations where we want to iterate the bitmap as it allows for early exit once the bitmap turns zero.\n   * @param data The configuration uint256\n   * @return The bitmap shifted by 2 bits, so that the first asset points to the *next* asset.\n   * @return True if the first asset in the bitmap is borrowed.\n   * @return True if the first asset in the bitmap is a collateral.\n   */\n  function getNextFlags(uint256 data) internal pure returns (uint256, bool, bool) {\n    bool isBorrowed = data & 1 == 1;\n    bool isEnabledAsCollateral = data & 2 == 2;\n    return (data >> 2, isBorrowed, isEnabledAsCollateral);\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"},"lib/aave-v3-origin-private/src/contracts/protocol/libraries/logic/ValidationLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';\nimport {IAToken} from '../../../interfaces/IAToken.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 {TokenMath} from '../helpers/TokenMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {GenericLogic} from './GenericLogic.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 TokenMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\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   * @notice Validates a supply action.\n   * @param reserveCache The cached data of the reserve\n   * @param scaledAmount The scaledAmount to be supplied\n   */\n  function validateSupply(\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.ReserveData storage reserve,\n    uint256 scaledAmount,\n    address onBehalfOf\n  ) internal view {\n    require(scaledAmount != 0, Errors.InvalidAmount());\n\n    (bool isActive, bool isFrozen, , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.ReserveInactive());\n    require(!isPaused, Errors.ReservePaused());\n    require(!isFrozen, Errors.ReserveFrozen());\n    require(onBehalfOf != reserveCache.aTokenAddress, Errors.SupplyToAToken());\n\n    uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();\n    require(\n      supplyCap == 0 ||\n        (\n          (IAToken(reserveCache.aTokenAddress).scaledTotalSupply() +\n            scaledAmount +\n            uint256(reserve.accruedToTreasury)).getATokenBalance(reserveCache.nextLiquidityIndex)\n        ) <=\n        supplyCap * (10 ** reserveCache.reserveConfiguration.getDecimals()),\n      Errors.SupplyCapExceeded()\n    );\n  }\n\n  /**\n   * @notice Validates a withdraw action.\n   * @param reserveCache The cached data of the reserve\n   * @param scaledAmount The scaled amount to be withdrawn\n   * @param scaledUserBalance The scaled balance of the user\n   */\n  function validateWithdraw(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 scaledAmount,\n    uint256 scaledUserBalance\n  ) internal pure {\n    require(scaledAmount != 0, Errors.InvalidAmount());\n    require(scaledAmount <= scaledUserBalance, Errors.NotEnoughAvailableUserBalance());\n\n    (bool isActive, , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.ReserveInactive());\n    require(!isPaused, Errors.ReservePaused());\n  }\n\n  struct ValidateBorrowLocalVars {\n    uint256 amount;\n    uint256 totalDebt;\n    uint256 reserveDecimals;\n    uint256 borrowCap;\n    uint256 assetUnit;\n    bool isActive;\n    bool isFrozen;\n    bool isPaused;\n    bool borrowingEnabled;\n  }\n\n  /**\n   * @notice Validates a borrow action.\n   * @param reservesData The state of all the 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(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ValidateBorrowParams memory params\n  ) internal view {\n    require(params.amountScaled != 0, Errors.InvalidAmount());\n\n    ValidateBorrowLocalVars memory vars;\n    vars.amount = params.amountScaled.getVTokenBalance(params.reserveCache.nextVariableBorrowIndex);\n\n    (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.isPaused) = params\n      .reserveCache\n      .reserveConfiguration\n      .getFlags();\n\n    require(vars.isActive, Errors.ReserveInactive());\n    require(!vars.isPaused, Errors.ReservePaused());\n    require(!vars.isFrozen, Errors.ReserveFrozen());\n    if (params.userEModeCategory != 0) {\n      require(\n        EModeConfiguration.isReserveEnabledOnBitmap(\n          eModeCategories[params.userEModeCategory].borrowableBitmap,\n          reservesData[params.asset].id\n        ),\n        Errors.NotBorrowableInEMode()\n      );\n    } else {\n      require(vars.borrowingEnabled, Errors.BorrowingNotEnabled());\n    }\n    require(\n      IERC20(params.reserveCache.aTokenAddress).totalSupply() >= vars.amount,\n      Errors.InvalidAmount()\n    );\n\n    //validate interest rate mode\n    require(\n      params.interestRateMode == DataTypes.InterestRateMode.VARIABLE,\n      Errors.InvalidInterestRateModeSelected()\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.totalDebt = (params.reserveCache.currScaledVariableDebt + params.amountScaled)\n        .getVTokenBalance(params.reserveCache.nextVariableBorrowIndex);\n\n      unchecked {\n        require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BorrowCapExceeded());\n      }\n    }\n  }\n\n  /**\n   * @notice Validates a repay action.\n   * @param user The user initiating the repayment\n   * @param reserveCache The cached data of the reserve\n   * @param amountSent The amount sent for the repayment. Can be an actual value or type(uint256).max\n   * @param onBehalfOf The address of the user sender is repaying for\n   * @param debtScaled The borrow scaled balance of the user\n   */\n  function validateRepay(\n    address user,\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amountSent,\n    DataTypes.InterestRateMode interestRateMode,\n    address onBehalfOf,\n    uint256 debtScaled\n  ) internal pure {\n    require(amountSent != 0, Errors.InvalidAmount());\n    require(\n      interestRateMode == DataTypes.InterestRateMode.VARIABLE,\n      Errors.InvalidInterestRateModeSelected()\n    );\n    require(\n      amountSent != type(uint256).max || user == onBehalfOf,\n      Errors.NoExplicitAmountToRepayOnBehalf()\n    );\n\n    (bool isActive, , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.ReserveInactive());\n    require(!isPaused, Errors.ReservePaused());\n\n    require(debtScaled != 0, Errors.NoDebtOfSelectedType());\n  }\n\n  /**\n   * @notice Validates the action of setting an asset as collateral.\n   * @param reserveConfig The config of the reserve\n   */\n  function validateSetUseReserveAsCollateral(\n    DataTypes.ReserveConfigurationMap memory reserveConfig\n  ) internal pure {\n    (bool isActive, , , bool isPaused) = reserveConfig.getFlags();\n    require(isActive, Errors.ReserveInactive());\n    require(!isPaused, Errors.ReservePaused());\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.InconsistentFlashloanParams());\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.InconsistentFlashloanParams());\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.ReservePaused());\n    require(configuration.getActive(), Errors.ReserveInactive());\n    require(configuration.getFlashLoanEnabled(), Errors.FlashloanDisabled());\n    require(IERC20(reserve.aTokenAddress).totalSupply() >= amount, Errors.InvalidAmount());\n  }\n\n  struct ValidateLiquidationCallLocalVars {\n    bool collateralReserveActive;\n    bool collateralReservePaused;\n    bool principalReserveActive;\n    bool principalReservePaused;\n  }\n\n  /**\n   * @notice Validates the liquidation action.\n   * @param borrowerConfig 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 borrowerConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ReserveData storage debtReserve,\n    DataTypes.ValidateLiquidationCallParams memory params\n  ) internal view {\n    ValidateLiquidationCallLocalVars memory vars;\n\n    require(params.borrower != params.liquidator, Errors.SelfLiquidation());\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.ReserveInactive());\n    require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.ReservePaused());\n\n    require(\n      collateralReserve.liquidationGracePeriodUntil < uint40(block.timestamp) &&\n        debtReserve.liquidationGracePeriodUntil < uint40(block.timestamp),\n      Errors.LiquidationGraceSentinelCheckFailed()\n    );\n\n    require(\n      params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HealthFactorNotBelowThreshold()\n    );\n\n    //if collateral isn't enabled as collateral by user, it cannot be liquidated\n    require(\n      borrowerConfig.isUsingAsCollateral(collateralReserve.id),\n      Errors.CollateralCannotBeLiquidated()\n    );\n    require(params.totalDebt != 0, Errors.SpecifiedCurrencyNotBorrowedByUser());\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 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    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          user: user,\n          oracle: oracle,\n          userEModeCategory: userEModeCategory\n        })\n      );\n\n    require(\n      healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HealthFactorLowerThanLiquidationThreshold()\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 borrowed.\n   *         The ltv validation is a measure to prevent accidental borrowing close to liquidations.\n   *         Sophisticated users can work around this validation in various ways.\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 from which the aTokens are being transferred\n   * @param userEModeCategory The users active efficiency mode category\n   * @param oracle The price oracle\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 user,\n    uint8 userEModeCategory,\n    address oracle\n  ) internal view {\n    (\n      uint256 userCollateralInBaseCurrency,\n      uint256 userDebtInBaseCurrency,\n      uint256 currentLtv,\n      ,\n      uint256 healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        DataTypes.CalculateUserAccountDataParams({\n          userConfig: userConfig,\n          user: user,\n          oracle: oracle,\n          userEModeCategory: userEModeCategory\n        })\n      );\n\n    require(currentLtv != 0, Errors.LtvValidationFailed());\n\n    require(\n      healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HealthFactorLowerThanLiquidationThreshold()\n    );\n\n    require(\n      userCollateralInBaseCurrency >= userDebtInBaseCurrency.percentDivCeil(currentLtv),\n      Errors.CollateralCannotCoverNewBorrow()\n    );\n  }\n\n  /**\n   * @notice Validates the health factor of a user and the ltvzero configuration for the asset being withdrawn/transferred or disabled as collateral.\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 oracle The price oracle\n   * @param userEModeCategory The users active efficiency mode category\n   */\n  function validateHFAndLtvzero(\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    address oracle,\n    uint8 userEModeCategory\n  ) internal view {\n    (, bool hasZeroLtvCollateral) = validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      from,\n      userEModeCategory,\n      oracle\n    );\n\n    // If the user has an ltvzero asset, the selected asset must be the ltv0 asset.\n    // This mechanism ensures that a multi-collateral position needs to withdraw/transfer the ltv0 asset first.\n    if (hasZeroLtvCollateral) {\n      require(\n        getUserReserveLtv(\n          reservesData[asset],\n          eModeCategories[userEModeCategory],\n          userEModeCategory\n        ) == 0,\n        Errors.LtvValidationFailed()\n      );\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.ReservePaused());\n  }\n\n  /**\n   * @notice Validates the action of setting efficiency mode.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories a mapping storing configurations for all efficiency mode categories\n   * @param userConfig the user configuration\n   * @param categoryId The id of the users eMode category\n   */\n  function validateSetUserEMode(\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    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.InconsistentEModeCategory()\n    );\n\n    // eMode can always be enabled if the user hasn't supplied anything\n    if (userConfig.isEmpty()) {\n      return;\n    }\n\n    uint256 i = 0;\n    bool isBorrowed = false;\n    bool isEnabledAsCollateral = false;\n    // the cache is muted inside the iteration and should not be used for other operations\n    uint256 unsafe_cachedUserConfig = userConfig.data;\n\n    // ensure that in the target eMode (even if it's eMode 0), the assets can still be borrowed and be used as collateral\n    unchecked {\n      while (unsafe_cachedUserConfig != 0) {\n        (unsafe_cachedUserConfig, isBorrowed, isEnabledAsCollateral) = UserConfiguration\n          .getNextFlags(unsafe_cachedUserConfig);\n\n        // ensure a user can only enter or exit an eMode if all his borrowed assets can be borrowed in the target state\n        if (isBorrowed) {\n          require(\n            categoryId != 0\n              ? EModeConfiguration.isReserveEnabledOnBitmap(eModeCategory.borrowableBitmap, i)\n              : reservesData[reservesList[i]].configuration.getBorrowingEnabled(),\n            Errors.InvalidDebtInEmode(reservesList[i], categoryId)\n          );\n        }\n        // the asset must either be collateral inside or outside of eMode\n        if (isEnabledAsCollateral) {\n          require(\n            getUserReserveLtv(reservesData[reservesList[i]], eModeCategory, categoryId) != 0,\n            Errors.InvalidCollateralInEmode(reservesList[i], categoryId)\n          );\n        }\n        ++i;\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\n   * @param reservesData The state of all the reserves\n   * @param eModeCategories a mapping storing configurations for all efficiency mode categories\n   * @param asset Address of the reserve to be enabled as collateral\n   * @param categoryId The id of the users eMode category\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(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    address asset,\n    uint8 categoryId\n  ) internal view returns (bool) {\n    return getUserReserveLtv(reservesData[asset], eModeCategories[categoryId], categoryId) != 0;\n  }\n\n  /**\n   * @notice Returns the ltv of the user in the particular reserve\n   * @param reserveData The reserve configuration\n   * @param eModeCategoryData The users eMode category configuration\n   * @param categoryId The id of the users eMode category\n   **/\n  function getUserReserveLtv(\n    DataTypes.ReserveData storage reserveData,\n    DataTypes.EModeCategory storage eModeCategoryData,\n    uint8 categoryId\n  ) internal view returns (uint256) {\n    if (\n      categoryId != 0 &&\n      EModeConfiguration.isReserveEnabledOnBitmap(\n        eModeCategoryData.collateralBitmap,\n        reserveData.id\n      )\n    ) {\n      if (\n        EModeConfiguration.isReserveEnabledOnBitmap(eModeCategoryData.ltvzeroBitmap, reserveData.id)\n      ) {\n        return 0;\n      } else {\n        return eModeCategoryData.ltv;\n      }\n    }\n    // If eMode is isolated and asset is NOT in collateralBitmap, return 0\n    if (categoryId != 0 && eModeCategoryData.isolated) {\n      return 0;\n    }\n    return reserveData.configuration.getLtv();\n  }\n}\n"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/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.InvalidReserveIndex());\n      // forge-lint: disable-next-line(incorrect-shift, unsafe-typecast)\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.InvalidReserveIndex());\n      return (bitmap >> reserveIndex) & 1 != 0;\n    }\n  }\n}\n"},"lib/aave-v3-origin-private/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"},"lib/aave-helpers/lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Errors.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"},"lib/aave-v3-origin-private/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"},"lib/aave-v3-origin-private/src/contracts/interfaces/IInitializableAToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\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 underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\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 underlyingAsset,\n    uint8 aTokenDecimals,\n    string calldata aTokenName,\n    string calldata aTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"},"lib/aave-v3-origin-private/src/contracts/interfaces/IInitializableDebtToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\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 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    uint8 debtTokenDecimals,\n    string memory debtTokenName,\n    string memory debtTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"}},"abi":[{"type":"constructor","inputs":[{"name":"provider","type":"address","internalType":"contract IPoolAddressesProvider"},{"name":"interestRateStrategy_","type":"address","internalType":"contract IReserveInterestRateStrategy"}],"stateMutability":"nonpayable"},{"name":"AddressEmptyCode","type":"error","inputs":[{"name":"target","type":"address","internalType":"address"}]},{"name":"AssetNotListed","type":"error","inputs":[]},{"name":"CallerNotAToken","type":"error","inputs":[]},{"name":"CallerNotPoolAdmin","type":"error","inputs":[]},{"name":"CallerNotPoolConfigurator","type":"error","inputs":[]},{"name":"CallerNotPositionManager","type":"error","inputs":[]},{"name":"CallerNotUmbrella","type":"error","inputs":[]},{"name":"EModeCategoryReserved","type":"error","inputs":[]},{"name":"FailedCall","type":"error","inputs":[]},{"name":"InvalidAddressesProvider","type":"error","inputs":[]},{"name":"ZeroAddressNotValid","type":"error","inputs":[]},{"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":"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":"MintedToTreasury","type":"event","inputs":[{"name":"reserve","type":"address","indexed":true,"internalType":"address"},{"name":"amountMinted","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"PositionManagerApproved","type":"event","inputs":[{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"positionManager","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"name":"PositionManagerRevoked","type":"event","inputs":[{"name":"user","type":"address","indexed":true,"internalType":"address"},{"name":"positionManager","type":"address","indexed":true,"internalType":"address"}],"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":"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":"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":"RESERVE_INTEREST_RATE_STRATEGY","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"UMBRELLA","type":"function","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"name":"approvePositionManager","type":"function","inputs":[{"name":"positionManager","type":"address","internalType":"address"},{"name":"approve","type":"bool","internalType":"bool"}],"outputs":[],"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":"isolated","type":"bool","internalType":"bool"},{"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":"configureEModeCategoryIsolated","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"},{"name":"isolated","type":"bool","internalType":"bool"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"configureEModeCategoryLtvzeroBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"},{"name":"ltvzeroBitmap","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":"eliminateReserveDeficit","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"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":"scaledAmount","type":"uint256","internalType":"uint256"},{"name":"scaledBalanceFromBefore","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":"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":"res","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":"getEModeCategoryLtvzeroBitmap","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"uint128","internalType":"uint128"}],"stateMutability":"view"},{"name":"getFlashLoanLogic","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"pure"},{"name":"getIsEModeCategoryIsolated","type":"function","inputs":[{"name":"id","type":"uint8","internalType":"uint8"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"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":"res","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"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"initialize","type":"function","inputs":[{"name":"provider","type":"address","internalType":"contract IPoolAddressesProvider"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"isApprovedPositionManager","type":"function","inputs":[{"name":"user","type":"address","internalType":"address"},{"name":"positionManager","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"name":"liquidationCall","type":"function","inputs":[{"name":"collateralAsset","type":"address","internalType":"address"},{"name":"debtAsset","type":"address","internalType":"address"},{"name":"borrower","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":"multicall","type":"function","inputs":[{"name":"data","type":"bytes[]","internalType":"bytes[]"}],"outputs":[{"name":"results","type":"bytes[]","internalType":"bytes[]"}],"stateMutability":"nonpayable"},{"name":"renouncePositionManagerRole","type":"function","inputs":[{"name":"user","type":"address","internalType":"address"}],"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":"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":"setUserEMode","type":"function","inputs":[{"name":"categoryId","type":"uint8","internalType":"uint8"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setUserEModeOnBehalfOf","type":"function","inputs":[{"name":"categoryId","type":"uint8","internalType":"uint8"},{"name":"onBehalfOf","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setUserUseReserveAsCollateral","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"useAsCollateral","type":"bool","internalType":"bool"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"setUserUseReserveAsCollateralOnBehalfOf","type":"function","inputs":[{"name":"asset","type":"address","internalType":"address"},{"name":"useAsCollateral","type":"bool","internalType":"bool"},{"name":"onBehalfOf","type":"address","internalType":"address"}],"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":"updateFlashloanPremium","type":"function","inputs":[{"name":"flashLoanPremium","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":"30150693","creationMatch":"match","runtimeMatch":"match","verifiedAt":"2026-05-29T21:37:44Z","match":"match","chainId":"1","address":"0x78680A9AC74B093571e7a5b76636248F031D9bC2"}