creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/LiquidationLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts//IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {PercentageMath} from '../../libraries/math/PercentageMath.sol';\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\nimport {Helpers} from '../../libraries/helpers/Helpers.sol';\nimport {DataTypes} from '../../libraries/types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {IsolationModeLogic} from './IsolationModeLogic.sol';\nimport {EModeLogic} from './EModeLogic.sol';\nimport {UserConfiguration} from '../../libraries/configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../../libraries/configuration/ReserveConfiguration.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.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 WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using GPv2SafeERC20 for IERC20;\n\n  // See `IPool` for descriptions\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n  event LiquidationCall(\n    address indexed collateralAsset,\n    address indexed debtAsset,\n    address indexed user,\n    uint256 debtToCover,\n    uint256 liquidatedCollateralAmount,\n    address liquidator,\n    bool receiveAToken\n  );\n\n  /**\n   * @dev Default percentage of borrower's debt to be repaid in a liquidation.\n   * @dev Percentage applied when the users health factor is above `CLOSE_FACTOR_HF_THRESHOLD`\n   * Expressed in bps, a value of 0.5e4 results in 50.00%\n   */\n  uint256 internal constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 0.5e4;\n\n  /**\n   * @dev Maximum percentage of borrower's debt to be repaid in a liquidation\n   * @dev Percentage applied when the users health factor is below `CLOSE_FACTOR_HF_THRESHOLD`\n   * Expressed in bps, a value of 1e4 results in 100.00%\n   */\n  uint256 public constant MAX_LIQUIDATION_CLOSE_FACTOR = 1e4;\n\n  /**\n   * @dev This constant represents below which health factor value it is possible to liquidate\n   * an amount of debt corresponding to `MAX_LIQUIDATION_CLOSE_FACTOR`.\n   * A value of 0.95e18 results in 0.95\n   */\n  uint256 public constant CLOSE_FACTOR_HF_THRESHOLD = 0.95e18;\n\n  struct LiquidationCallLocalVars {\n    uint256 userCollateralBalance;\n    uint256 userVariableDebt;\n    uint256 userTotalDebt;\n    uint256 actualDebtToLiquidate;\n    uint256 actualCollateralToLiquidate;\n    uint256 liquidationBonus;\n    uint256 healthFactor;\n    uint256 liquidationProtocolFeeAmount;\n    address collateralPriceSource;\n    address debtPriceSource;\n    IAToken collateralAToken;\n    DataTypes.ReserveCache debtReserveCache;\n  }\n\n  /**\n   * @notice Function to liquidate a position if its Health Factor drops below 1. The caller (liquidator)\n   * covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   * a proportional amount of the `collateralAsset` plus a bonus to cover market risk\n   * @dev Emits the `LiquidationCall()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params The additional parameters needed to execute the liquidation function\n   */\n  function executeLiquidationCall(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ExecuteLiquidationCallParams memory params\n  ) external {\n    LiquidationCallLocalVars memory vars;\n\n    DataTypes.ReserveData storage collateralReserve = reservesData[params.collateralAsset];\n    DataTypes.ReserveData storage debtReserve = reservesData[params.debtAsset];\n    DataTypes.UserConfigurationMap storage userConfig = usersConfig[params.user];\n    vars.debtReserveCache = debtReserve.cache();\n    debtReserve.updateState(vars.debtReserveCache);\n\n    (, , , , vars.healthFactor, ) = GenericLogic.calculateUserAccountData(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.CalculateUserAccountDataParams({\n        userConfig: userConfig,\n        reservesCount: params.reservesCount,\n        user: params.user,\n        oracle: params.priceOracle,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    (vars.userVariableDebt, vars.userTotalDebt, vars.actualDebtToLiquidate) = _calculateDebt(\n      vars.debtReserveCache,\n      params,\n      vars.healthFactor\n    );\n\n    ValidationLogic.validateLiquidationCall(\n      userConfig,\n      collateralReserve,\n      DataTypes.ValidateLiquidationCallParams({\n        debtReserveCache: vars.debtReserveCache,\n        totalDebt: vars.userTotalDebt,\n        healthFactor: vars.healthFactor,\n        priceOracleSentinel: params.priceOracleSentinel\n      })\n    );\n\n    (\n      vars.collateralAToken,\n      vars.collateralPriceSource,\n      vars.debtPriceSource,\n      vars.liquidationBonus\n    ) = _getConfigurationData(eModeCategories, collateralReserve, params);\n\n    vars.userCollateralBalance = vars.collateralAToken.balanceOf(params.user);\n\n    (\n      vars.actualCollateralToLiquidate,\n      vars.actualDebtToLiquidate,\n      vars.liquidationProtocolFeeAmount\n    ) = _calculateAvailableCollateralToLiquidate(\n      collateralReserve,\n      vars.debtReserveCache,\n      vars.collateralPriceSource,\n      vars.debtPriceSource,\n      vars.actualDebtToLiquidate,\n      vars.userCollateralBalance,\n      vars.liquidationBonus,\n      IPriceOracleGetter(params.priceOracle)\n    );\n\n    if (vars.userTotalDebt == vars.actualDebtToLiquidate) {\n      userConfig.setBorrowing(debtReserve.id, false);\n    }\n\n    // If the collateral being liquidated is equal to the user balance,\n    // we set the currency as not being used as collateral anymore\n    if (\n      vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount ==\n      vars.userCollateralBalance\n    ) {\n      userConfig.setUsingAsCollateral(collateralReserve.id, false);\n      emit ReserveUsedAsCollateralDisabled(params.collateralAsset, params.user);\n    }\n\n    _burnDebtTokens(params, vars);\n\n    debtReserve.updateInterestRates(\n      vars.debtReserveCache,\n      params.debtAsset,\n      vars.actualDebtToLiquidate,\n      0\n    );\n\n    IsolationModeLogic.updateIsolatedDebtIfIsolated(\n      reservesData,\n      reservesList,\n      userConfig,\n      vars.debtReserveCache,\n      vars.actualDebtToLiquidate\n    );\n\n    if (params.receiveAToken) {\n      _liquidateATokens(reservesData, reservesList, usersConfig, collateralReserve, params, vars);\n    } else {\n      _burnCollateralATokens(collateralReserve, params, vars);\n    }\n\n    // Transfer fee to treasury if it is non-zero\n    if (vars.liquidationProtocolFeeAmount != 0) {\n      uint256 liquidityIndex = collateralReserve.getNormalizedIncome();\n      uint256 scaledDownLiquidationProtocolFee = vars.liquidationProtocolFeeAmount.rayDiv(\n        liquidityIndex\n      );\n      uint256 scaledDownUserBalance = vars.collateralAToken.scaledBalanceOf(params.user);\n      // To avoid trying to send more aTokens than available on balance, due to 1 wei imprecision\n      if (scaledDownLiquidationProtocolFee > scaledDownUserBalance) {\n        vars.liquidationProtocolFeeAmount = scaledDownUserBalance.rayMul(liquidityIndex);\n      }\n      vars.collateralAToken.transferOnLiquidation(\n        params.user,\n        vars.collateralAToken.RESERVE_TREASURY_ADDRESS(),\n        vars.liquidationProtocolFeeAmount\n      );\n    }\n\n    // Transfers the debt asset being repaid to the aToken, where the liquidity is kept\n    IERC20(params.debtAsset).safeTransferFrom(\n      msg.sender,\n      vars.debtReserveCache.aTokenAddress,\n      vars.actualDebtToLiquidate\n    );\n\n    IAToken(vars.debtReserveCache.aTokenAddress).handleRepayment(\n      msg.sender,\n      params.user,\n      vars.actualDebtToLiquidate\n    );\n\n    emit LiquidationCall(\n      params.collateralAsset,\n      params.debtAsset,\n      params.user,\n      vars.actualDebtToLiquidate,\n      vars.actualCollateralToLiquidate,\n      msg.sender,\n      params.receiveAToken\n    );\n  }\n\n  /**\n   * @notice Burns the collateral aTokens and transfers the underlying to the liquidator.\n   * @dev   The function also updates the state and the interest rate of the collateral reserve.\n   * @param collateralReserve The data of the collateral reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param vars The executeLiquidationCall() function local vars\n   */\n  function _burnCollateralATokens(\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    LiquidationCallLocalVars memory vars\n  ) internal {\n    DataTypes.ReserveCache memory collateralReserveCache = collateralReserve.cache();\n    collateralReserve.updateState(collateralReserveCache);\n    collateralReserve.updateInterestRates(\n      collateralReserveCache,\n      params.collateralAsset,\n      0,\n      vars.actualCollateralToLiquidate\n    );\n\n    // Burn the equivalent amount of aToken, sending the underlying to the liquidator\n    vars.collateralAToken.burn(\n      params.user,\n      msg.sender,\n      vars.actualCollateralToLiquidate,\n      collateralReserveCache.nextLiquidityIndex\n    );\n  }\n\n  /**\n   * @notice Liquidates the user aTokens by transferring them to the liquidator.\n   * @dev   The function also checks the state of the liquidator and activates the aToken as collateral\n   *        as in standard transfers if the isolation mode constraints are respected.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n   * @param collateralReserve The data of the collateral reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param vars The executeLiquidationCall() function local vars\n   */\n  function _liquidateATokens(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    LiquidationCallLocalVars memory vars\n  ) internal {\n    uint256 liquidatorPreviousATokenBalance = IERC20(vars.collateralAToken).balanceOf(msg.sender);\n    vars.collateralAToken.transferOnLiquidation(\n      params.user,\n      msg.sender,\n      vars.actualCollateralToLiquidate\n    );\n\n    if (liquidatorPreviousATokenBalance == 0) {\n      DataTypes.UserConfigurationMap storage liquidatorConfig = usersConfig[msg.sender];\n      if (\n        ValidationLogic.validateAutomaticUseAsCollateral(\n          reservesData,\n          reservesList,\n          liquidatorConfig,\n          collateralReserve.configuration,\n          collateralReserve.aTokenAddress\n        )\n      ) {\n        liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true);\n        emit ReserveUsedAsCollateralEnabled(params.collateralAsset, msg.sender);\n      }\n    }\n  }\n\n  /**\n   * @notice Burns the debt tokens of the user up to the amount being repaid by the liquidator.\n   * @dev The function alters the `debtReserveCache` state in `vars` to update the debt related data.\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param vars the executeLiquidationCall() function local vars\n   */\n  function _burnDebtTokens(\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    LiquidationCallLocalVars memory vars\n  ) internal {\n    if (vars.userVariableDebt >= vars.actualDebtToLiquidate) {\n      vars.debtReserveCache.nextScaledVariableDebt = IVariableDebtToken(\n        vars.debtReserveCache.variableDebtTokenAddress\n      ).burn(\n          params.user,\n          vars.actualDebtToLiquidate,\n          vars.debtReserveCache.nextVariableBorrowIndex\n        );\n    } else {\n      // If the user doesn't have variable debt, no need to try to burn variable debt tokens\n      if (vars.userVariableDebt != 0) {\n        vars.debtReserveCache.nextScaledVariableDebt = IVariableDebtToken(\n          vars.debtReserveCache.variableDebtTokenAddress\n        ).burn(params.user, vars.userVariableDebt, vars.debtReserveCache.nextVariableBorrowIndex);\n      }\n      (\n        vars.debtReserveCache.nextTotalStableDebt,\n        vars.debtReserveCache.nextAvgStableBorrowRate\n      ) = IStableDebtToken(vars.debtReserveCache.stableDebtTokenAddress).burn(\n        params.user,\n        vars.actualDebtToLiquidate - vars.userVariableDebt\n      );\n    }\n  }\n\n  /**\n   * @notice Calculates the total debt of the user and the actual amount to liquidate depending on the health factor\n   * and corresponding close factor.\n   * @dev If the Health Factor is below CLOSE_FACTOR_HF_THRESHOLD, the close factor is increased to MAX_LIQUIDATION_CLOSE_FACTOR\n   * @param debtReserveCache The reserve cache data object of the debt reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @param healthFactor The health factor of the position\n   * @return The variable debt of the user\n   * @return The total debt of the user\n   * @return The actual debt to liquidate as a function of the closeFactor\n   */\n  function _calculateDebt(\n    DataTypes.ReserveCache memory debtReserveCache,\n    DataTypes.ExecuteLiquidationCallParams memory params,\n    uint256 healthFactor\n  ) internal view returns (uint256, uint256, uint256) {\n    (uint256 userStableDebt, uint256 userVariableDebt) = Helpers.getUserCurrentDebt(\n      params.user,\n      debtReserveCache\n    );\n\n    uint256 userTotalDebt = userStableDebt + userVariableDebt;\n\n    uint256 closeFactor = healthFactor > CLOSE_FACTOR_HF_THRESHOLD\n      ? DEFAULT_LIQUIDATION_CLOSE_FACTOR\n      : MAX_LIQUIDATION_CLOSE_FACTOR;\n\n    uint256 maxLiquidatableDebt = userTotalDebt.percentMul(closeFactor);\n\n    uint256 actualDebtToLiquidate = params.debtToCover > maxLiquidatableDebt\n      ? maxLiquidatableDebt\n      : params.debtToCover;\n\n    return (userVariableDebt, userTotalDebt, actualDebtToLiquidate);\n  }\n\n  /**\n   * @notice Returns the configuration data for the debt and the collateral reserves.\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param collateralReserve The data of the collateral reserve\n   * @param params The additional parameters needed to execute the liquidation function\n   * @return The collateral aToken\n   * @return The address to use as price source for the collateral\n   * @return The address to use as price source for the debt\n   * @return The liquidation bonus to apply to the collateral\n   */\n  function _getConfigurationData(\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ExecuteLiquidationCallParams memory params\n  ) internal view returns (IAToken, address, address, uint256) {\n    IAToken collateralAToken = IAToken(collateralReserve.aTokenAddress);\n    uint256 liquidationBonus = collateralReserve.configuration.getLiquidationBonus();\n\n    address collateralPriceSource = params.collateralAsset;\n    address debtPriceSource = params.debtAsset;\n\n    if (params.userEModeCategory != 0) {\n      address eModePriceSource = eModeCategories[params.userEModeCategory].priceSource;\n\n      if (\n        EModeLogic.isInEModeCategory(\n          params.userEModeCategory,\n          collateralReserve.configuration.getEModeCategory()\n        )\n      ) {\n        liquidationBonus = eModeCategories[params.userEModeCategory].liquidationBonus;\n\n        if (eModePriceSource != address(0)) {\n          collateralPriceSource = eModePriceSource;\n        }\n      }\n\n      // when in eMode, debt will always be in the same eMode category, can skip matching category check\n      if (eModePriceSource != address(0)) {\n        debtPriceSource = eModePriceSource;\n      }\n    }\n\n    return (collateralAToken, collateralPriceSource, debtPriceSource, liquidationBonus);\n  }\n\n  struct AvailableCollateralToLiquidateLocalVars {\n    uint256 collateralPrice;\n    uint256 debtAssetPrice;\n    uint256 maxCollateralToLiquidate;\n    uint256 baseCollateral;\n    uint256 bonusCollateral;\n    uint256 debtAssetDecimals;\n    uint256 collateralDecimals;\n    uint256 collateralAssetUnit;\n    uint256 debtAssetUnit;\n    uint256 collateralAmount;\n    uint256 debtAmountNeeded;\n    uint256 liquidationProtocolFeePercentage;\n    uint256 liquidationProtocolFee;\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 collateralReserve The data of the collateral reserve\n   * @param debtReserveCache The cached data of the debt reserve\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 debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated\n   * @param liquidationBonus The collateral bonus percentage to receive as result of the liquidation\n   * @return The maximum amount that is possible to liquidate given all the liquidation constraints (user balance, close factor)\n   * @return The amount to repay with the liquidation\n   * @return The fee taken from the liquidation bonus amount to be paid to the protocol\n   */\n  function _calculateAvailableCollateralToLiquidate(\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ReserveCache memory debtReserveCache,\n    address collateralAsset,\n    address debtAsset,\n    uint256 debtToCover,\n    uint256 userCollateralBalance,\n    uint256 liquidationBonus,\n    IPriceOracleGetter oracle\n  ) internal view returns (uint256, uint256, uint256) {\n    AvailableCollateralToLiquidateLocalVars memory vars;\n\n    vars.collateralPrice = oracle.getAssetPrice(collateralAsset);\n    vars.debtAssetPrice = oracle.getAssetPrice(debtAsset);\n\n    vars.collateralDecimals = collateralReserve.configuration.getDecimals();\n    vars.debtAssetDecimals = debtReserveCache.reserveConfiguration.getDecimals();\n\n    unchecked {\n      vars.collateralAssetUnit = 10 ** vars.collateralDecimals;\n      vars.debtAssetUnit = 10 ** vars.debtAssetDecimals;\n    }\n\n    vars.liquidationProtocolFeePercentage = collateralReserve\n      .configuration\n      .getLiquidationProtocolFee();\n\n    // This is the base collateral to liquidate based on the given debt to cover\n    vars.baseCollateral =\n      ((vars.debtAssetPrice * debtToCover * vars.collateralAssetUnit)) /\n      (vars.collateralPrice * vars.debtAssetUnit);\n\n    vars.maxCollateralToLiquidate = vars.baseCollateral.percentMul(liquidationBonus);\n\n    if (vars.maxCollateralToLiquidate > userCollateralBalance) {\n      vars.collateralAmount = userCollateralBalance;\n      vars.debtAmountNeeded = ((vars.collateralPrice * vars.collateralAmount * vars.debtAssetUnit) /\n        (vars.debtAssetPrice * vars.collateralAssetUnit)).percentDiv(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.percentDiv(liquidationBonus);\n\n      vars.liquidationProtocolFee = vars.bonusCollateral.percentMul(\n        vars.liquidationProtocolFeePercentage\n      );\n\n      return (\n        vars.collateralAmount - vars.liquidationProtocolFee,\n        vars.debtAmountNeeded,\n        vars.liquidationProtocolFee\n      );\n    } else {\n      return (vars.collateralAmount, vars.debtAmountNeeded, 0);\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n  /**\n   * @dev Returns the amount of tokens in existence.\n   */\n  function totalSupply() external view returns (uint256);\n\n  /**\n   * @dev Returns the amount of tokens owned by `account`.\n   */\n  function balanceOf(address account) external view returns (uint256);\n\n  /**\n   * @dev Moves `amount` tokens from the caller's account to `recipient`.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transfer(address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Returns the remaining number of tokens that `spender` will be\n   * allowed to spend on behalf of `owner` through {transferFrom}. This is\n   * zero by default.\n   *\n   * This value changes when {approve} or {transferFrom} are called.\n   */\n  function allowance(address owner, address spender) external view returns (uint256);\n\n  /**\n   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * IMPORTANT: Beware that changing an allowance with this method brings the risk\n   * that someone may use both the old and the new allowance by unfortunate\n   * transaction ordering. One possible solution to mitigate this race\n   * condition is to first reduce the spender's allowance to 0 and set the\n   * desired value afterwards:\n   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n   *\n   * Emits an {Approval} event.\n   */\n  function approve(address spender, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Moves `amount` tokens from `sender` to `recipient` using the\n   * allowance mechanism. `amount` is then deducted from the caller's\n   * allowance.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Emitted when `value` tokens are moved from one account (`from`) to\n   * another (`to`).\n   *\n   * Note that `value` may be zero.\n   */\n  event Transfer(address indexed from, address indexed to, uint256 value);\n\n  /**\n   * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n   * a call to {approve}. `value` is the new allowance.\n   */\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-or-later\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../../openzeppelin/contracts/IERC20.sol';\n\n/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library\n/// @author Gnosis Developers\n/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract.\nlibrary GPv2SafeERC20 {\n  /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts\n  /// also when the token returns `false`.\n  function safeTransfer(IERC20 token, address to, uint256 value) internal {\n    bytes4 selector_ = token.transfer.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transfer');\n  }\n\n  /// @dev Wrapper around a call to the ERC20 function `transferFrom` that\n  /// reverts also when the token returns `false`.\n  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n    bytes4 selector_ = token.transferFrom.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 68), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transferFrom');\n  }\n\n  /// @dev Verifies that the last return was a successful `transfer*` call.\n  /// This is done by checking that the return data is either empty, or\n  /// is a valid ABI encoded boolean.\n  function getLastTransferResult(IERC20 token) private view returns (bool success) {\n    // NOTE: Inspecting previous return data requires assembly. Note that\n    // we write the return data to memory 0 in the case where the return\n    // data size is 32, this is OK since the first 64 bytes of memory are\n    // reserved by Solidy as a scratch space that can be used within\n    // assembly blocks.\n    // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html>\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      /// @dev Revert with an ABI encoded Solidity error with a message\n      /// that fits into 32-bytes.\n      ///\n      /// An ABI encoded Solidity error has the following memory layout:\n      ///\n      /// ------------+----------------------------------\n      ///  byte range | value\n      /// ------------+----------------------------------\n      ///  0x00..0x04 |        selector(\"Error(string)\")\n      ///  0x04..0x24 |      string offset (always 0x20)\n      ///  0x24..0x44 |                    string length\n      ///  0x44..0x64 | string value, padded to 32-bytes\n      function revertWithMessage(length, message) {\n        mstore(0x00, '\\x08\\xc3\\x79\\xa0')\n        mstore(0x04, 0x20)\n        mstore(0x24, length)\n        mstore(0x44, message)\n        revert(0x00, 0x64)\n      }\n\n      switch returndatasize()\n      // Non-standard ERC20 transfer without return.\n      case 0 {\n        // NOTE: When the return data size is 0, verify that there\n        // is code at the address. This is done in order to maintain\n        // compatibility with Solidity calling conventions.\n        // <https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls>\n        if iszero(extcodesize(token)) {\n          revertWithMessage(20, 'GPv2: not a contract')\n        }\n\n        success := 1\n      }\n      // Standard ERC20 transfer returning boolean success value.\n      case 32 {\n        returndatacopy(0, 0, returndatasize())\n\n        // NOTE: For ABI encoding v1, any non-zero value is accepted\n        // as `true` for a boolean. In order to stay compatible with\n        // OpenZeppelin's `SafeERC20` library which is known to work\n        // with the existing ERC20 implementation we care about,\n        // make sure we return success for any non-zero return value\n        // from the `transfer*` call.\n        success := iszero(iszero(mload(0)))\n      }\n      default {\n        revertWithMessage(31, 'GPv2: malformed transfer result')\n      }\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/math/PercentageMath.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n/**\n * @title PercentageMath library\n * @author Aave\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary PercentageMath {\n  // Maximum percentage factor (100.00%)\n  uint256 internal constant PERCENTAGE_FACTOR = 1e4;\n\n  // Half percentage factor (50.00%)\n  uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4;\n\n  /**\n   * @notice Executes a percentage multiplication\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentmul percentage\n   */\n  function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage\n    assembly {\n      if iszero(\n        or(\n          iszero(percentage),\n          iszero(gt(value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage)))\n        )\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)\n    }\n  }\n\n  /**\n   * @notice Executes a percentage division\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentdiv percentage\n   */\n  function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR\n    assembly {\n      if or(\n        iszero(percentage),\n        iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR))))\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage)\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/math/WadRayMath.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n/**\n * @title WadRayMath library\n * @author Aave\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary WadRayMath {\n  // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n  uint256 internal constant WAD = 1e18;\n  uint256 internal constant HALF_WAD = 0.5e18;\n\n  uint256 internal constant RAY = 1e27;\n  uint256 internal constant HALF_RAY = 0.5e27;\n\n  uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n  /**\n   * @dev Multiplies two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a*b, in wad\n   */\n  function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_WAD), WAD)\n    }\n  }\n\n  /**\n   * @dev Divides two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a/b, in wad\n   */\n  function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / WAD\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, WAD), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @notice Multiplies two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raymul b\n   */\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  /**\n   * @notice Divides two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raydiv b\n   */\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Casts ray down to wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @return b = a converted to wad, rounded half up to the nearest wad\n   */\n  function rayToWad(uint256 a) internal pure returns (uint256 b) {\n    assembly {\n      b := div(a, WAD_RAY_RATIO)\n      let remainder := mod(a, WAD_RAY_RATIO)\n      if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n        b := add(b, 1)\n      }\n    }\n  }\n\n  /**\n   * @dev Converts wad up to ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @return b = a converted in ray\n   */\n  function wadToRay(uint256 a) internal pure returns (uint256 b) {\n    // to avoid overflow, b/WAD_RAY_RATIO == a\n    assembly {\n      b := mul(a, WAD_RAY_RATIO)\n\n      if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n        revert(0, 0)\n      }\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/helpers/Helpers.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title Helpers library\n * @author Aave\n */\nlibrary Helpers {\n  /**\n   * @notice Fetches the user current stable and variable debt balances\n   * @param user The user address\n   * @param reserveCache The reserve cache data object\n   * @return The stable debt balance\n   * @return The variable debt balance\n   */\n  function getUserCurrentDebt(\n    address user,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal view returns (uint256, uint256) {\n    return (\n      IERC20(reserveCache.stableDebtTokenAddress).balanceOf(user),\n      IERC20(reserveCache.variableDebtTokenAddress).balanceOf(user)\n    );\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/types/DataTypes.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\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    //the current stable borrow rate. Expressed in ray\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    //stableDebtToken address\n    address stableDebtTokenAddress;\n    //variableDebtToken address\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    //the outstanding unbacked aTokens minted through the bridging feature\n    uint128 unbacked;\n    //the outstanding debt borrowed against this asset in isolation mode\n    uint128 isolationModeTotalDebt;\n  }\n\n  struct ReserveConfigurationMap {\n    //bit 0-15: LTV\n    //bit 16-31: Liq. threshold\n    //bit 32-47: Liq. bonus\n    //bit 48-55: Decimals\n    //bit 56: reserve is active\n    //bit 57: reserve is frozen\n    //bit 58: borrowing is enabled\n    //bit 59: stable rate borrowing enabled\n    //bit 60: asset is paused\n    //bit 61: borrowing in isolation mode is enabled\n    //bit 62: siloed borrowing enabled\n    //bit 63: flashloaning enabled\n    //bit 64-79: reserve factor\n    //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n    //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n    //bit 152-167 liquidation protocol fee\n    //bit 168-175 eMode category\n    //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n    //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n    //bit 252-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  struct EModeCategory {\n    // each eMode category has a custom ltv and liquidation threshold\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n    // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n    address priceSource;\n    string label;\n  }\n\n  enum InterestRateMode {NONE, STABLE, VARIABLE}\n\n  struct ReserveCache {\n    uint256 currScaledVariableDebt;\n    uint256 nextScaledVariableDebt;\n    uint256 currPrincipalStableDebt;\n    uint256 currAvgStableBorrowRate;\n    uint256 currTotalStableDebt;\n    uint256 nextAvgStableBorrowRate;\n    uint256 nextTotalStableDebt;\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 stableDebtTokenAddress;\n    address variableDebtTokenAddress;\n    uint40 reserveLastUpdateTimestamp;\n    uint40 stableDebtLastUpdateTimestamp;\n  }\n\n  struct ExecuteLiquidationCallParams {\n    uint256 reservesCount;\n    uint256 debtToCover;\n    address collateralAsset;\n    address debtAsset;\n    address user;\n    bool receiveAToken;\n    address priceOracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteSupplyParams {\n    address asset;\n    uint256 amount;\n    address onBehalfOf;\n    uint16 referralCode;\n  }\n\n  struct ExecuteBorrowParams {\n    address asset;\n    address user;\n    address onBehalfOf;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint16 referralCode;\n    bool releaseUnderlying;\n    uint256 maxStableRateBorrowSizePercent;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteRepayParams {\n    address asset;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    address onBehalfOf;\n    bool useATokens;\n  }\n\n  struct ExecuteWithdrawParams {\n    address asset;\n    uint256 amount;\n    address to;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteSetUserEModeParams {\n    uint256 reservesCount;\n    address oracle;\n    uint8 categoryId;\n  }\n\n  struct FinalizeTransferParams {\n    address asset;\n    address from;\n    address to;\n    uint256 amount;\n    uint256 balanceFromBefore;\n    uint256 balanceToBefore;\n    uint256 reservesCount;\n    address oracle;\n    uint8 fromEModeCategory;\n  }\n\n  struct FlashloanParams {\n    address receiverAddress;\n    address[] assets;\n    uint256[] amounts;\n    uint256[] interestRateModes;\n    address onBehalfOf;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n    uint256 maxStableRateBorrowSizePercent;\n    uint256 reservesCount;\n    address addressesProvider;\n    address pool;\n    uint8 userEModeCategory;\n    bool isAuthorizedFlashBorrower;\n  }\n\n  struct FlashloanSimpleParams {\n    address receiverAddress;\n    address asset;\n    uint256 amount;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n  }\n\n  struct FlashLoanRepaymentParams {\n    uint256 amount;\n    uint256 totalPremium;\n    uint256 flashLoanPremiumToProtocol;\n    address asset;\n    address receiverAddress;\n    uint16 referralCode;\n  }\n\n  struct CalculateUserAccountDataParams {\n    UserConfigurationMap userConfig;\n    uint256 reservesCount;\n    address user;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ValidateBorrowParams {\n    ReserveCache reserveCache;\n    UserConfigurationMap userConfig;\n    address asset;\n    address userAddress;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint256 maxStableLoanPercent;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n    bool isolationModeActive;\n    address isolationModeCollateralAddress;\n    uint256 isolationModeDebtCeiling;\n  }\n\n  struct ValidateLiquidationCallParams {\n    ReserveCache debtReserveCache;\n    uint256 totalDebt;\n    uint256 healthFactor;\n    address priceOracleSentinel;\n  }\n\n  struct CalculateInterestRatesParams {\n    uint256 unbacked;\n    uint256 liquidityAdded;\n    uint256 liquidityTaken;\n    uint256 totalStableDebt;\n    uint256 totalVariableDebt;\n    uint256 averageStableBorrowRate;\n    uint256 reserveFactor;\n    address reserve;\n    address aToken;\n  }\n\n  struct InitReserveParams {\n    address asset;\n    address aTokenAddress;\n    address stableDebtAddress;\n    address variableDebtAddress;\n    address interestRateStrategyAddress;\n    uint16 reservesCount;\n    uint16 maxNumberReserves;\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/ReserveLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPool` for descriptions\n  event ReserveDataUpdated(\n    address indexed reserve,\n    uint256 liquidityRate,\n    uint256 stableBorrowRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  /**\n   * @notice Returns the ongoing normalized income for the reserve.\n   * @dev A value of 1e27 means there is no income. As time passes, the income is accrued\n   * @dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n   * @param reserve The reserve object\n   * @return The normalized income, expressed in ray\n   */\n  function getNormalizedIncome(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.liquidityIndex;\n    } else {\n      return\n        MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n          reserve.liquidityIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Returns the ongoing normalized variable debt for the reserve.\n   * @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued\n   * @dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n   * @param reserve The reserve object\n   * @return The normalized variable debt, expressed in ray\n   */\n  function getNormalizedDebt(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.variableBorrowIndex;\n    } else {\n      return\n        MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n          reserve.variableBorrowIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Updates the liquidity cumulative index and the variable borrow index.\n   * @param reserve The reserve object\n   * @param reserveCache The caching layer for the reserve data\n   */\n  function updateState(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // If time didn't pass since last stored timestamp, skip state update\n    //solium-disable-next-line\n    if (reserve.lastUpdateTimestamp == 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  }\n\n  /**\n   * @notice Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example\n   * to accumulate the flashloan fee to the reserve, and spread it between all the suppliers.\n   * @param reserve The reserve object\n   * @param totalLiquidity The total liquidity available in the reserve\n   * @param amount The amount to accumulate\n   * @return The next liquidity index of the reserve\n   */\n  function cumulateToLiquidityIndex(\n    DataTypes.ReserveData storage reserve,\n    uint256 totalLiquidity,\n    uint256 amount\n  ) internal returns (uint256) {\n    //next liquidity index is calculated this way: `((amount / totalLiquidity) + 1) * liquidityIndex`\n    //division `amount / totalLiquidity` done in ray for precision\n    uint256 result = (amount.wadToRay().rayDiv(totalLiquidity.wadToRay()) + WadRayMath.RAY).rayMul(\n      reserve.liquidityIndex\n    );\n    reserve.liquidityIndex = result.toUint128();\n    return result;\n  }\n\n  /**\n   * @notice Initializes a reserve.\n   * @param reserve The reserve object\n   * @param aTokenAddress The address of the overlying atoken contract\n   * @param stableDebtTokenAddress The address of the overlying stable debt token contract\n   * @param variableDebtTokenAddress The address of the overlying variable debt token contract\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   */\n  function init(\n    DataTypes.ReserveData storage reserve,\n    address aTokenAddress,\n    address stableDebtTokenAddress,\n    address variableDebtTokenAddress,\n    address interestRateStrategyAddress\n  ) internal {\n    require(reserve.aTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED);\n\n    reserve.liquidityIndex = uint128(WadRayMath.RAY);\n    reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n    reserve.aTokenAddress = aTokenAddress;\n    reserve.stableDebtTokenAddress = stableDebtTokenAddress;\n    reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n    reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n  }\n\n  struct UpdateInterestRatesLocalVars {\n    uint256 nextLiquidityRate;\n    uint256 nextStableRate;\n    uint256 nextVariableRate;\n    uint256 totalVariableDebt;\n  }\n\n  /**\n   * @notice Updates the reserve current stable borrow rate, the 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 updateInterestRates(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    address reserveAddress,\n    uint256 liquidityAdded,\n    uint256 liquidityTaken\n  ) internal {\n    UpdateInterestRatesLocalVars memory vars;\n\n    vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    (\n      vars.nextLiquidityRate,\n      vars.nextStableRate,\n      vars.nextVariableRate\n    ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(\n      DataTypes.CalculateInterestRatesParams({\n        unbacked: reserve.unbacked,\n        liquidityAdded: liquidityAdded,\n        liquidityTaken: liquidityTaken,\n        totalStableDebt: reserveCache.nextTotalStableDebt,\n        totalVariableDebt: vars.totalVariableDebt,\n        averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,\n        reserveFactor: reserveCache.reserveFactor,\n        reserve: reserveAddress,\n        aToken: reserveCache.aTokenAddress\n      })\n    );\n\n    reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();\n    reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();\n    reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();\n\n    emit ReserveDataUpdated(\n      reserveAddress,\n      vars.nextLiquidityRate,\n      vars.nextStableRate,\n      vars.nextVariableRate,\n      reserveCache.nextLiquidityIndex,\n      reserveCache.nextVariableBorrowIndex\n    );\n  }\n\n  struct AccrueToTreasuryLocalVars {\n    uint256 prevTotalStableDebt;\n    uint256 prevTotalVariableDebt;\n    uint256 currTotalVariableDebt;\n    uint256 cumulatedStableInterest;\n    uint256 totalDebtAccrued;\n    uint256 amountToMint;\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    AccrueToTreasuryLocalVars memory vars;\n\n    if (reserveCache.reserveFactor == 0) {\n      return;\n    }\n\n    //calculate the total variable debt at moment of the last interaction\n    vars.prevTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.currVariableBorrowIndex\n    );\n\n    //calculate the new total variable debt after accumulation of the interest on the index\n    vars.currTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    //calculate the stable debt until the last timestamp update\n    vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(\n      reserveCache.currAvgStableBorrowRate,\n      reserveCache.stableDebtLastUpdateTimestamp,\n      reserveCache.reserveLastUpdateTimestamp\n    );\n\n    vars.prevTotalStableDebt = reserveCache.currPrincipalStableDebt.rayMul(\n      vars.cumulatedStableInterest\n    );\n\n    //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n    vars.totalDebtAccrued =\n      vars.currTotalVariableDebt +\n      reserveCache.currTotalStableDebt -\n      vars.prevTotalVariableDebt -\n      vars.prevTotalStableDebt;\n\n    vars.amountToMint = vars.totalDebtAccrued.percentMul(reserveCache.reserveFactor);\n\n    if (vars.amountToMint != 0) {\n      reserve.accruedToTreasury += vars\n        .amountToMint\n        .rayDiv(reserveCache.nextLiquidityIndex)\n        .toUint128();\n    }\n  }\n\n  /**\n   * @notice Updates the reserve indexes and the timestamp of the update.\n   * @param reserve The reserve reserve to be updated\n   * @param reserveCache The cache layer holding the cached protocol data\n   */\n  function _updateIndexes(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // Only cumulating on the supply side if there is any income being produced\n    // The case of Reserve Factor 100% is not a problem (currentLiquidityRate == 0),\n    // as liquidity index should not be updated\n    if (reserveCache.currLiquidityRate != 0) {\n      uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(\n        reserveCache.currLiquidityRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextLiquidityIndex = cumulatedLiquidityInterest.rayMul(\n        reserveCache.currLiquidityIndex\n      );\n      reserve.liquidityIndex = reserveCache.nextLiquidityIndex.toUint128();\n    }\n\n    // Variable borrow index only gets updated if there is any variable debt.\n    // reserveCache.currVariableBorrowRate != 0 is not a correct validation,\n    // because a positive base variable rate can be stored on\n    // reserveCache.currVariableBorrowRate, but the index should not increase\n    if (reserveCache.currScaledVariableDebt != 0) {\n      uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(\n        reserveCache.currVariableBorrowRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(\n        reserveCache.currVariableBorrowIndex\n      );\n      reserve.variableBorrowIndex = reserveCache.nextVariableBorrowIndex.toUint128();\n    }\n  }\n\n  /**\n   * @notice Creates a cache object to avoid repeated storage reads and external contract calls when updating state and\n   * interest rates.\n   * @param reserve The reserve object for which the cache will be filled\n   * @return The cache object\n   */\n  function cache(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (DataTypes.ReserveCache memory) {\n    DataTypes.ReserveCache memory reserveCache;\n\n    reserveCache.reserveConfiguration = reserve.configuration;\n    reserveCache.reserveFactor = reserveCache.reserveConfiguration.getReserveFactor();\n    reserveCache.currLiquidityIndex = reserveCache.nextLiquidityIndex = reserve.liquidityIndex;\n    reserveCache.currVariableBorrowIndex = reserveCache.nextVariableBorrowIndex = reserve\n      .variableBorrowIndex;\n    reserveCache.currLiquidityRate = reserve.currentLiquidityRate;\n    reserveCache.currVariableBorrowRate = reserve.currentVariableBorrowRate;\n\n    reserveCache.aTokenAddress = reserve.aTokenAddress;\n    reserveCache.stableDebtTokenAddress = reserve.stableDebtTokenAddress;\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    (\n      reserveCache.currPrincipalStableDebt,\n      reserveCache.currTotalStableDebt,\n      reserveCache.currAvgStableBorrowRate,\n      reserveCache.stableDebtLastUpdateTimestamp\n    ) = IStableDebtToken(reserveCache.stableDebtTokenAddress).getSupplyData();\n\n    // by default the actions are considered as not affecting the debt balances.\n    // if the action involves mint/burn of debt, the cache needs to be updated\n    reserveCache.nextTotalStableDebt = reserveCache.currTotalStableDebt;\n    reserveCache.nextAvgStableBorrowRate = reserveCache.currAvgStableBorrowRate;\n\n    return reserveCache;\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/ValidationLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using Address for address;\n\n  // Factor to apply to \"only-variable-debt\" liquidity rate to get threshold for rebalancing, expressed in bps\n  // A value of 0.9e4 results in 90%\n  uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4;\n\n  // Minimum health factor allowed under any circumstance\n  // A value of 0.95e18 results in 0.95\n  uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18;\n\n  /**\n   * @dev Minimum health factor to consider a user position healthy\n   * A value of 1e18 results in 1\n   */\n  uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n  /**\n   * @dev Role identifier for the role allowed to supply isolated reserves as collateral\n   */\n  bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE =\n    keccak256('ISOLATED_COLLATERAL_SUPPLIER');\n\n  /**\n   * @notice Validates a supply action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be supplied\n   */\n  function validateSupply(\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.ReserveData storage reserve,\n    uint256 amount\n  ) internal view {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n\n    (bool isActive, bool isFrozen, , , bool isPaused) = reserveCache\n      .reserveConfiguration\n      .getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n    require(!isFrozen, Errors.RESERVE_FROZEN);\n\n    uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();\n    require(\n      supplyCap == 0 ||\n        ((IAToken(reserveCache.aTokenAddress).scaledTotalSupply() +\n          uint256(reserve.accruedToTreasury)).rayMul(reserveCache.nextLiquidityIndex) + amount) <=\n        supplyCap * (10 ** reserveCache.reserveConfiguration.getDecimals()),\n      Errors.SUPPLY_CAP_EXCEEDED\n    );\n  }\n\n  /**\n   * @notice Validates a withdraw action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be withdrawn\n   * @param userBalance The balance of the user\n   */\n  function validateWithdraw(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amount,\n    uint256 userBalance\n  ) internal pure {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n    require(amount <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  struct ValidateBorrowLocalVars {\n    uint256 currentLtv;\n    uint256 collateralNeededInBaseCurrency;\n    uint256 userCollateralInBaseCurrency;\n    uint256 userDebtInBaseCurrency;\n    uint256 availableLiquidity;\n    uint256 healthFactor;\n    uint256 totalDebt;\n    uint256 totalSupplyVariableDebt;\n    uint256 reserveDecimals;\n    uint256 borrowCap;\n    uint256 amountInBaseCurrency;\n    uint256 assetUnit;\n    address eModePriceSource;\n    address siloedBorrowingAddress;\n    bool isActive;\n    bool isFrozen;\n    bool isPaused;\n    bool borrowingEnabled;\n    bool stableRateBorrowingEnabled;\n    bool siloedBorrowingEnabled;\n  }\n\n  /**\n   * @notice Validates a borrow action.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional params needed for the validation\n   */\n  function validateBorrow(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ValidateBorrowParams memory params\n  ) internal view {\n    require(params.amount != 0, Errors.INVALID_AMOUNT);\n\n    ValidateBorrowLocalVars memory vars;\n\n    (\n      vars.isActive,\n      vars.isFrozen,\n      vars.borrowingEnabled,\n      vars.stableRateBorrowingEnabled,\n      vars.isPaused\n    ) = params.reserveCache.reserveConfiguration.getFlags();\n\n    require(vars.isActive, Errors.RESERVE_INACTIVE);\n    require(!vars.isPaused, Errors.RESERVE_PAUSED);\n    require(!vars.isFrozen, Errors.RESERVE_FROZEN);\n    require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED);\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    //validate interest rate mode\n    require(\n      params.interestRateMode == DataTypes.InterestRateMode.VARIABLE ||\n        params.interestRateMode == DataTypes.InterestRateMode.STABLE,\n      Errors.INVALID_INTEREST_RATE_MODE_SELECTED\n    );\n\n    vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals();\n    vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap();\n    unchecked {\n      vars.assetUnit = 10 ** vars.reserveDecimals;\n    }\n\n    if (vars.borrowCap != 0) {\n      vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul(\n        params.reserveCache.nextVariableBorrowIndex\n      );\n\n      vars.totalDebt =\n        params.reserveCache.currTotalStableDebt +\n        vars.totalSupplyVariableDebt +\n        params.amount;\n\n      unchecked {\n        require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED);\n      }\n    }\n\n    if (params.isolationModeActive) {\n      // check that the asset being borrowed is borrowable in isolation mode AND\n      // the total exposure is no bigger than the collateral debt ceiling\n      require(\n        params.reserveCache.reserveConfiguration.getBorrowableInIsolation(),\n        Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION\n      );\n\n      require(\n        reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt +\n          (params.amount /\n            10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS))\n            .toUint128() <=\n          params.isolationModeDebtCeiling,\n        Errors.DEBT_CEILING_EXCEEDED\n      );\n    }\n\n    if (params.userEModeCategory != 0) {\n      require(\n        params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory,\n        Errors.INCONSISTENT_EMODE_CATEGORY\n      );\n      vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource;\n    }\n\n    (\n      vars.userCollateralInBaseCurrency,\n      vars.userDebtInBaseCurrency,\n      vars.currentLtv,\n      ,\n      vars.healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.CalculateUserAccountDataParams({\n        userConfig: params.userConfig,\n        reservesCount: params.reservesCount,\n        user: params.userAddress,\n        oracle: params.oracle,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO);\n    require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED);\n\n    require(\n      vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    vars.amountInBaseCurrency =\n      IPriceOracleGetter(params.oracle).getAssetPrice(\n        vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset\n      ) *\n      params.amount;\n    unchecked {\n      vars.amountInBaseCurrency /= vars.assetUnit;\n    }\n\n    //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n    vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency)\n      .percentDiv(vars.currentLtv); //LTV is calculated in percentage\n\n    require(\n      vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency,\n      Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW\n    );\n\n    /**\n     * Following conditions need to be met if the user is borrowing at a stable rate:\n     * 1. Reserve must be enabled for stable rate borrowing\n     * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency\n     *    they are borrowing, to prevent abuses.\n     * 3. Users will be able to borrow only a portion of the total available liquidity\n     */\n\n    if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve\n\n      require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED);\n\n      require(\n        !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) ||\n          params.reserveCache.reserveConfiguration.getLtv() == 0 ||\n          params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress),\n        Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY\n      );\n\n      vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress);\n\n      //calculate the max available loan size in stable rate mode as a percentage of the\n      //available liquidity\n      uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent);\n\n      require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);\n    }\n\n    if (params.userConfig.isBorrowingAny()) {\n      (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params\n        .userConfig\n        .getSiloedBorrowingState(reservesData, reservesList);\n\n      if (vars.siloedBorrowingEnabled) {\n        require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION);\n      } else {\n        require(\n          !params.reserveCache.reserveConfiguration.getSiloedBorrowing(),\n          Errors.SILOED_BORROWING_VIOLATION\n        );\n      }\n    }\n  }\n\n  /**\n   * @notice Validates a repay action.\n   * @param reserveCache The cached data of the reserve\n   * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n   * @param interestRateMode The interest rate mode of the debt being repaid\n   * @param onBehalfOf The address of the user msg.sender is repaying for\n   * @param stableDebt The borrow balance of the user\n   * @param variableDebt The borrow balance of the user\n   */\n  function validateRepay(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amountSent,\n    DataTypes.InterestRateMode interestRateMode,\n    address onBehalfOf,\n    uint256 stableDebt,\n    uint256 variableDebt\n  ) internal view {\n    require(amountSent != 0, Errors.INVALID_AMOUNT);\n    require(\n      amountSent != type(uint256).max || msg.sender == onBehalfOf,\n      Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n    );\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n\n    require(\n      (stableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.STABLE) ||\n        (variableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.VARIABLE),\n      Errors.NO_DEBT_OF_SELECTED_TYPE\n    );\n  }\n\n  /**\n   * @notice Validates a swap of borrow rate mode.\n   * @param reserve The reserve state on which the user is swapping the rate\n   * @param reserveCache The cached data of the reserve\n   * @param userConfig The user reserves configuration\n   * @param stableDebt The stable debt of the user\n   * @param variableDebt The variable debt of the user\n   * @param currentRateMode The rate mode of the debt being swapped\n   */\n  function validateSwapRateMode(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.UserConfigurationMap storage userConfig,\n    uint256 stableDebt,\n    uint256 variableDebt,\n    DataTypes.InterestRateMode currentRateMode\n  ) internal view {\n    (bool isActive, bool isFrozen, , bool stableRateEnabled, bool isPaused) = reserveCache\n      .reserveConfiguration\n      .getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n    require(!isFrozen, Errors.RESERVE_FROZEN);\n\n    if (currentRateMode == DataTypes.InterestRateMode.STABLE) {\n      require(stableDebt != 0, Errors.NO_OUTSTANDING_STABLE_DEBT);\n    } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) {\n      require(variableDebt != 0, Errors.NO_OUTSTANDING_VARIABLE_DEBT);\n      /**\n       * user wants to swap to stable, before swapping we need to ensure that\n       * 1. stable borrow rate is enabled on the reserve\n       * 2. user is not trying to abuse the reserve by supplying\n       * more collateral than he is borrowing, artificially lowering\n       * the interest rate, borrowing at variable, and switching to stable\n       */\n      require(stableRateEnabled, Errors.STABLE_BORROWING_NOT_ENABLED);\n\n      require(\n        !userConfig.isUsingAsCollateral(reserve.id) ||\n          reserveCache.reserveConfiguration.getLtv() == 0 ||\n          stableDebt + variableDebt > IERC20(reserveCache.aTokenAddress).balanceOf(msg.sender),\n        Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY\n      );\n    } else {\n      revert(Errors.INVALID_INTEREST_RATE_MODE_SELECTED);\n    }\n  }\n\n  /**\n   * @notice Validates a stable borrow rate rebalance action.\n   * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only)\n   * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate.\n   * @param reserve The reserve state on which the user is getting rebalanced\n   * @param reserveCache The cached state of the reserve\n   * @param reserveAddress The address of the reserve\n   */\n  function validateRebalanceStableBorrowRate(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    address reserveAddress\n  ) internal view {\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n\n    uint256 totalDebt = IERC20(reserveCache.stableDebtTokenAddress).totalSupply() +\n      IERC20(reserveCache.variableDebtTokenAddress).totalSupply();\n\n    (uint256 liquidityRateVariableDebtOnly, , ) = IReserveInterestRateStrategy(\n      reserve.interestRateStrategyAddress\n    ).calculateInterestRates(\n        DataTypes.CalculateInterestRatesParams({\n          unbacked: reserve.unbacked,\n          liquidityAdded: 0,\n          liquidityTaken: 0,\n          totalStableDebt: 0,\n          totalVariableDebt: totalDebt,\n          averageStableBorrowRate: 0,\n          reserveFactor: reserveCache.reserveFactor,\n          reserve: reserveAddress,\n          aToken: reserveCache.aTokenAddress\n        })\n      );\n\n    require(\n      reserveCache.currLiquidityRate <=\n        liquidityRateVariableDebtOnly.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),\n      Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET\n    );\n  }\n\n  /**\n   * @notice Validates the action of setting an asset as collateral.\n   * @param reserveCache The cached data of the reserve\n   * @param userBalance The balance of the user\n   */\n  function validateSetUseReserveAsCollateral(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 userBalance\n  ) internal pure {\n    require(userBalance != 0, Errors.UNDERLYING_BALANCE_ZERO);\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reservesData The state of all the reserves\n   * @param assets The assets being flash-borrowed\n   * @param amounts The amounts for each asset being borrowed\n   */\n  function validateFlashloan(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address[] memory assets,\n    uint256[] memory amounts\n  ) internal view {\n    require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS);\n    for (uint256 i = 0; i < assets.length; i++) {\n      validateFlashloanSimple(reservesData[assets[i]]);\n    }\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reserve The state of the reserve\n   */\n  function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view {\n    DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration;\n    require(!configuration.getPaused(), Errors.RESERVE_PAUSED);\n    require(configuration.getActive(), Errors.RESERVE_INACTIVE);\n    require(configuration.getFlashLoanEnabled(), Errors.FLASHLOAN_DISABLED);\n  }\n\n  struct ValidateLiquidationCallLocalVars {\n    bool collateralReserveActive;\n    bool collateralReservePaused;\n    bool principalReserveActive;\n    bool principalReservePaused;\n    bool isCollateralEnabled;\n  }\n\n  /**\n   * @notice Validates the liquidation action.\n   * @param userConfig The user configuration mapping\n   * @param collateralReserve The reserve data of the collateral\n   * @param params Additional parameters needed for the validation\n   */\n  function validateLiquidationCall(\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ValidateLiquidationCallParams memory params\n  ) internal view {\n    ValidateLiquidationCallLocalVars memory vars;\n\n    (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve\n      .configuration\n      .getFlags();\n\n    (vars.principalReserveActive, , , , vars.principalReservePaused) = params\n      .debtReserveCache\n      .reserveConfiguration\n      .getFlags();\n\n    require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE);\n    require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED);\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    require(\n      params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n    );\n\n    vars.isCollateralEnabled =\n      collateralReserve.configuration.getLiquidationThreshold() != 0 &&\n      userConfig.isUsingAsCollateral(collateralReserve.id);\n\n    //if collateral isn't enabled as collateral by user, it cannot be liquidated\n    require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED);\n    require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER);\n  }\n\n  /**\n   * @notice Validates the health factor of a user.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param user The user to validate health factor of\n   * @param userEModeCategory The users active efficiency mode category\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   */\n  function validateHealthFactor(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address user,\n    uint8 userEModeCategory,\n    uint256 reservesCount,\n    address oracle\n  ) internal view returns (uint256, bool) {\n    (, , , , uint256 healthFactor, bool hasZeroLtvCollateral) = GenericLogic\n      .calculateUserAccountData(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        DataTypes.CalculateUserAccountDataParams({\n          userConfig: userConfig,\n          reservesCount: reservesCount,\n          user: user,\n          oracle: oracle,\n          userEModeCategory: userEModeCategory\n        })\n      );\n\n    require(\n      healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    return (healthFactor, hasZeroLtvCollateral);\n  }\n\n  /**\n   * @notice Validates the health factor of a user and the ltv of the asset being withdrawn.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param asset The asset for which the ltv will be validated\n   * @param from The user from which the aTokens are being transferred\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   * @param userEModeCategory The users active efficiency mode category\n   */\n  function validateHFAndLtv(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address asset,\n    address from,\n    uint256 reservesCount,\n    address oracle,\n    uint8 userEModeCategory\n  ) internal view {\n    DataTypes.ReserveData memory reserve = reservesData[asset];\n\n    (, bool hasZeroLtvCollateral) = validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      from,\n      userEModeCategory,\n      reservesCount,\n      oracle\n    );\n\n    require(\n      !hasZeroLtvCollateral || reserve.configuration.getLtv() == 0,\n      Errors.LTV_VALIDATION_FAILED\n    );\n  }\n\n  /**\n   * @notice Validates a transfer action.\n   * @param reserve The reserve object\n   */\n  function validateTransfer(DataTypes.ReserveData storage reserve) internal view {\n    require(!reserve.configuration.getPaused(), Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a drop reserve action.\n   * @param reservesList The addresses of all the active reserves\n   * @param reserve The reserve object\n   * @param asset The address of the reserve's underlying asset\n   */\n  function validateDropReserve(\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.ReserveData storage reserve,\n    address asset\n  ) internal view {\n    require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n    require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n    require(IERC20(reserve.stableDebtTokenAddress).totalSupply() == 0, Errors.STABLE_DEBT_NOT_ZERO);\n    require(\n      IERC20(reserve.variableDebtTokenAddress).totalSupply() == 0,\n      Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO\n    );\n    require(\n      IERC20(reserve.aTokenAddress).totalSupply() == 0 && reserve.accruedToTreasury == 0,\n      Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO\n    );\n  }\n\n  /**\n   * @notice Validates the action of setting efficiency mode.\n   * @param 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 reservesCount The total number of valid reserves\n   * @param categoryId The id of the 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    uint256 reservesCount,\n    uint8 categoryId\n  ) internal view {\n    // category is invalid if the liq threshold is not set\n    require(\n      categoryId == 0 || eModeCategories[categoryId].liquidationThreshold != 0,\n      Errors.INCONSISTENT_EMODE_CATEGORY\n    );\n\n    // eMode can always be enabled if the user hasn't supplied anything\n    if (userConfig.isEmpty()) {\n      return;\n    }\n\n    // if user is trying to set another category than default we require that\n    // either the user is not borrowing, or it's borrowing assets of categoryId\n    if (categoryId != 0) {\n      unchecked {\n        for (uint256 i = 0; i < reservesCount; i++) {\n          if (userConfig.isBorrowing(i)) {\n            DataTypes.ReserveConfigurationMap memory configuration = reservesData[reservesList[i]]\n              .configuration;\n            require(\n              configuration.getEModeCategory() == categoryId,\n              Errors.INCONSISTENT_EMODE_CATEGORY\n            );\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * @notice Validates the action of activating the asset as collateral.\n   * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig\n  ) internal view returns (bool) {\n    if (reserveConfig.getLtv() == 0) {\n      return false;\n    }\n    if (!userConfig.isUsingAsCollateralAny()) {\n      return true;\n    }\n    (bool isolationModeActive, , ) = userConfig.getIsolationModeState(reservesData, reservesList);\n\n    return (!isolationModeActive && reserveConfig.getDebtCeiling() == 0);\n  }\n\n  /**\n   * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply,\n   * transfer, mint unbacked, and liquidate\n   * @dev This is used to ensure that isolated assets are not enabled as collateral automatically\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateAutomaticUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig,\n    address aTokenAddress\n  ) internal view returns (bool) {\n    if (reserveConfig.getDebtCeiling() != 0) {\n      // ensures only the ISOLATED_COLLATERAL_SUPPLIER_ROLE can enable collateral as side-effect of an action\n      IPoolAddressesProvider addressesProvider = IncentivizedERC20(aTokenAddress)\n        .POOL()\n        .ADDRESSES_PROVIDER();\n      if (\n        !IAccessControl(addressesProvider.getACLManager()).hasRole(\n          ISOLATED_COLLATERAL_SUPPLIER_ROLE,\n          msg.sender\n        )\n      ) return false;\n    }\n    return validateUseAsCollateral(reservesData, reservesList, userConfig, reserveConfig);\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/GenericLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {EModeLogic} from './EModeLogic.sol';\n\n/**\n * @title GenericLogic library\n * @author Aave\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  struct CalculateUserAccountDataVars {\n    uint256 assetPrice;\n    uint256 assetUnit;\n    uint256 userBalanceInBaseCurrency;\n    uint256 decimals;\n    uint256 ltv;\n    uint256 liquidationThreshold;\n    uint256 i;\n    uint256 healthFactor;\n    uint256 totalCollateralInBaseCurrency;\n    uint256 totalDebtInBaseCurrency;\n    uint256 avgLtv;\n    uint256 avgLiquidationThreshold;\n    uint256 eModeAssetPrice;\n    uint256 eModeLtv;\n    uint256 eModeLiqThreshold;\n    uint256 eModeAssetCategory;\n    address currentReserveAddress;\n    bool hasZeroLtvCollateral;\n    bool isInEModeCategory;\n  }\n\n  /**\n   * @notice Calculates the user data across the reserves.\n   * @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,\n   * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional parameters needed for the calculation\n   * @return The total collateral of the user in the base currency used by the price feed\n   * @return The total debt of the user in the base currency used by the price feed\n   * @return The average ltv of the user\n   * @return The average liquidation threshold of the user\n   * @return The health factor of the user\n   * @return True if the ltv is zero, false otherwise\n   */\n  function calculateUserAccountData(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.CalculateUserAccountDataParams memory params\n  ) internal view returns (uint256, uint256, uint256, uint256, uint256, bool) {\n    if (params.userConfig.isEmpty()) {\n      return (0, 0, 0, 0, type(uint256).max, false);\n    }\n\n    CalculateUserAccountDataVars memory vars;\n\n    if (params.userEModeCategory != 0) {\n      (vars.eModeLtv, vars.eModeLiqThreshold, vars.eModeAssetPrice) = EModeLogic\n        .getEModeConfiguration(\n          eModeCategories[params.userEModeCategory],\n          IPriceOracleGetter(params.oracle)\n        );\n    }\n\n    while (vars.i < params.reservesCount) {\n      if (!params.userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      vars.currentReserveAddress = reservesList[vars.i];\n\n      if (vars.currentReserveAddress == address(0)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];\n\n      (\n        vars.ltv,\n        vars.liquidationThreshold,\n        ,\n        vars.decimals,\n        ,\n        vars.eModeAssetCategory\n      ) = currentReserve.configuration.getParams();\n\n      unchecked {\n        vars.assetUnit = 10 ** vars.decimals;\n      }\n\n      vars.assetPrice = vars.eModeAssetPrice != 0 &&\n        params.userEModeCategory == vars.eModeAssetCategory\n        ? vars.eModeAssetPrice\n        : IPriceOracleGetter(params.oracle).getAssetPrice(vars.currentReserveAddress);\n\n      if (vars.liquidationThreshold != 0 && params.userConfig.isUsingAsCollateral(vars.i)) {\n        vars.userBalanceInBaseCurrency = _getUserBalanceInBaseCurrency(\n          params.user,\n          currentReserve,\n          vars.assetPrice,\n          vars.assetUnit\n        );\n\n        vars.totalCollateralInBaseCurrency += vars.userBalanceInBaseCurrency;\n\n        vars.isInEModeCategory = EModeLogic.isInEModeCategory(\n          params.userEModeCategory,\n          vars.eModeAssetCategory\n        );\n\n        if (vars.ltv != 0) {\n          vars.avgLtv +=\n            vars.userBalanceInBaseCurrency *\n            (vars.isInEModeCategory ? vars.eModeLtv : vars.ltv);\n        } else {\n          vars.hasZeroLtvCollateral = true;\n        }\n\n        vars.avgLiquidationThreshold +=\n          vars.userBalanceInBaseCurrency *\n          (vars.isInEModeCategory ? vars.eModeLiqThreshold : vars.liquidationThreshold);\n      }\n\n      if (params.userConfig.isBorrowing(vars.i)) {\n        vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(\n          params.user,\n          currentReserve,\n          vars.assetPrice,\n          vars.assetUnit\n        );\n      }\n\n      unchecked {\n        ++vars.i;\n      }\n    }\n\n    unchecked {\n      vars.avgLtv = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLtv / vars.totalCollateralInBaseCurrency\n        : 0;\n      vars.avgLiquidationThreshold = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLiquidationThreshold / vars.totalCollateralInBaseCurrency\n        : 0;\n    }\n\n    vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)\n      ? type(uint256).max\n      : (vars.totalCollateralInBaseCurrency.percentMul(vars.avgLiquidationThreshold)).wadDiv(\n        vars.totalDebtInBaseCurrency\n      );\n    return (\n      vars.totalCollateralInBaseCurrency,\n      vars.totalDebtInBaseCurrency,\n      vars.avgLtv,\n      vars.avgLiquidationThreshold,\n      vars.healthFactor,\n      vars.hasZeroLtvCollateral\n    );\n  }\n\n  /**\n   * @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt\n   * and the average Loan To Value\n   * @param totalCollateralInBaseCurrency The total collateral in the base currency used by the price feed\n   * @param totalDebtInBaseCurrency The total borrow balance in the base currency used by the price feed\n   * @param ltv The average loan to value\n   * @return The amount available to borrow in the base currency of the used by the price feed\n   */\n  function calculateAvailableBorrows(\n    uint256 totalCollateralInBaseCurrency,\n    uint256 totalDebtInBaseCurrency,\n    uint256 ltv\n  ) internal pure returns (uint256) {\n    uint256 availableBorrowsInBaseCurrency = totalCollateralInBaseCurrency.percentMul(ltv);\n\n    if (availableBorrowsInBaseCurrency < totalDebtInBaseCurrency) {\n      return 0;\n    }\n\n    availableBorrowsInBaseCurrency = availableBorrowsInBaseCurrency - totalDebtInBaseCurrency;\n    return availableBorrowsInBaseCurrency;\n  }\n\n  /**\n   * @notice Calculates total debt of the user in the based currency used to normalize the values of the assets\n   * @dev This fetches the `balanceOf` of the stable and variable debt tokens for the user. For gas reasons, the\n   * variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than\n   * fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total debt of the user is being calculated\n   * @param assetPrice The price of the asset for which the total debt of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total debt of the user normalized to the base currency\n   */\n  function _getUserDebtInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    // fetching variable debt\n    uint256 userTotalDebt = IScaledBalanceToken(reserve.variableDebtTokenAddress).scaledBalanceOf(\n      user\n    );\n    if (userTotalDebt != 0) {\n      userTotalDebt = userTotalDebt.rayMul(reserve.getNormalizedDebt());\n    }\n\n    userTotalDebt = userTotalDebt + IERC20(reserve.stableDebtTokenAddress).balanceOf(user);\n\n    userTotalDebt = assetPrice * userTotalDebt;\n\n    unchecked {\n      return userTotalDebt / assetUnit;\n    }\n  }\n\n  /**\n   * @notice Calculates total aToken balance of the user in the based currency used by the price oracle\n   * @dev For gas reasons, the aToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which\n   * is cheaper than fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total aToken balance of the user is being calculated\n   * @param assetPrice The price of the asset for which the total aToken balance of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total aToken balance of the user normalized to the base currency of the price oracle\n   */\n  function _getUserBalanceInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    uint256 normalizedIncome = reserve.getNormalizedIncome();\n    uint256 balance = (\n      IScaledBalanceToken(reserve.aTokenAddress).scaledBalanceOf(user).rayMul(normalizedIncome)\n    ) * assetPrice;\n\n    unchecked {\n      return balance / assetUnit;\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/IsolationModeLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\n\n/**\n * @title IsolationModeLogic library\n * @author Aave\n * @notice Implements the base logic for handling repayments for assets borrowed in isolation mode\n */\nlibrary IsolationModeLogic {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @notice updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping\n   * @param reserveCache The cached data of the reserve\n   * @param repayAmount The amount being repaid\n   */\n  function updateIsolatedDebtIfIsolated(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 repayAmount\n  ) internal {\n    (bool isolationModeActive, address isolationModeCollateralAddress, ) = userConfig\n      .getIsolationModeState(reservesData, reservesList);\n\n    if (isolationModeActive) {\n      uint128 isolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n        .isolationModeTotalDebt;\n\n      uint128 isolatedDebtRepaid = (repayAmount /\n        10 **\n          (reserveCache.reserveConfiguration.getDecimals() -\n            ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128();\n\n      // since the debt ceiling does not take into account the interest accrued, it might happen that amount\n      // repaid > debt in isolation mode\n      if (isolationModeTotalDebt <= isolatedDebtRepaid) {\n        reservesData[isolationModeCollateralAddress].isolationModeTotalDebt = 0;\n        emit IsolationModeTotalDebtUpdated(isolationModeCollateralAddress, 0);\n      } else {\n        uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n          .isolationModeTotalDebt = isolationModeTotalDebt - isolatedDebtRepaid;\n        emit IsolationModeTotalDebtUpdated(\n          isolationModeCollateralAddress,\n          nextIsolationModeTotalDebt\n        );\n      }\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/logic/EModeLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\n/**\n * @title EModeLogic library\n * @author Aave\n * @notice Implements the base logic for all the actions related to the eMode\n */\nlibrary EModeLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n\n  // See `IPool` for descriptions\n  event UserEModeSet(address indexed user, uint8 categoryId);\n\n  /**\n   * @notice Updates the user efficiency mode category\n   * @dev Will revert if user is borrowing non-compatible asset or change will drop HF < HEALTH_FACTOR_LIQUIDATION_THRESHOLD\n   * @dev Emits the `UserEModeSet` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param usersEModeCategory The state of all users efficiency mode category\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the setUserEMode function\n   */\n  function executeSetUserEMode(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    mapping(address => uint8) storage usersEModeCategory,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteSetUserEModeParams memory params\n  ) external {\n    ValidationLogic.validateSetUserEMode(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      params.reservesCount,\n      params.categoryId\n    );\n\n    uint8 prevCategoryId = usersEModeCategory[msg.sender];\n    usersEModeCategory[msg.sender] = params.categoryId;\n\n    if (prevCategoryId != 0) {\n      ValidationLogic.validateHealthFactor(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        userConfig,\n        msg.sender,\n        params.categoryId,\n        params.reservesCount,\n        params.oracle\n      );\n    }\n    emit UserEModeSet(msg.sender, params.categoryId);\n  }\n\n  /**\n   * @notice Gets the eMode configuration and calculates the eMode asset price if a custom oracle is configured\n   * @dev The eMode asset price returned is 0 if no oracle is specified\n   * @param category The user eMode category\n   * @param oracle The price oracle\n   * @return The eMode ltv\n   * @return The eMode liquidation threshold\n   * @return The eMode asset price\n   */\n  function getEModeConfiguration(\n    DataTypes.EModeCategory storage category,\n    IPriceOracleGetter oracle\n  ) internal view returns (uint256, uint256, uint256) {\n    uint256 eModeAssetPrice = 0;\n    address eModePriceSource = category.priceSource;\n\n    if (eModePriceSource != address(0)) {\n      eModeAssetPrice = oracle.getAssetPrice(eModePriceSource);\n    }\n\n    return (category.ltv, category.liquidationThreshold, eModeAssetPrice);\n  }\n\n  /**\n   * @notice Checks if eMode is active for a user and if yes, if the asset belongs to the eMode category chosen\n   * @param eModeUserCategory The user eMode category\n   * @param eModeAssetCategory The asset eMode category\n   * @return True if eMode is active and the asset belongs to the eMode category chosen by the user, false otherwise\n   */\n  function isInEModeCategory(\n    uint256 eModeUserCategory,\n    uint256 eModeAssetCategory\n  ) internal pure returns (bool) {\n    return (eModeUserCategory != 0 && eModeAssetCategory == eModeUserCategory);\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/configuration/UserConfiguration.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from './ReserveConfiguration.sol';\n\n/**\n * @title UserConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the user configuration\n */\nlibrary UserConfiguration {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  uint256 internal constant BORROWING_MASK =\n    0x5555555555555555555555555555555555555555555555555555555555555555;\n  uint256 internal constant COLLATERAL_MASK =\n    0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;\n\n  /**\n   * @notice Sets if the user is borrowing the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param borrowing True if the user is borrowing the reserve, false otherwise\n   */\n  function setBorrowing(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool borrowing\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << (reserveIndex << 1);\n      if (borrowing) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Sets if the user is using as collateral the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param usingAsCollateral True if the user is using the reserve as collateral, false otherwise\n   */\n  function setUsingAsCollateral(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool usingAsCollateral\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << ((reserveIndex << 1) + 1);\n      if (usingAsCollateral) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Returns if a user has been using the reserve for borrowing or as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise\n   */\n  function isUsingAsCollateralOrBorrowing(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 3 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate a user has been using the reserve for borrowing\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing, false otherwise\n   */\n  function isBorrowing(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate a user has been using the reserve as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve as collateral, false otherwise\n   */\n  function isUsingAsCollateral(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Checks if a user has been supplying only one reserve as collateral\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isUsingAsCollateralOne(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    uint256 collateralData = self.data & COLLATERAL_MASK;\n    return collateralData != 0 && (collateralData & (collateralData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks if a user has been supplying any reserve as collateral\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral any reserve, false otherwise\n   */\n  function isUsingAsCollateralAny(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return self.data & COLLATERAL_MASK != 0;\n  }\n\n  /**\n   * @notice Checks if a user has been borrowing only one asset\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isBorrowingOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    uint256 borrowingData = self.data & BORROWING_MASK;\n    return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks if a user has been borrowing from any reserve\n   * @param self The configuration object\n   * @return True if the user has been borrowing any reserve, false otherwise\n   */\n  function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data & BORROWING_MASK != 0;\n  }\n\n  /**\n   * @notice Checks if a user has not been using any reserve for borrowing or supply\n   * @param self The configuration object\n   * @return True if the user has not been borrowing or supplying any reserve, false otherwise\n   */\n  function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data == 0;\n  }\n\n  /**\n   * @notice Returns the Isolation Mode state of the user\n   * @param self The configuration object\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @return True if the user is in isolation mode, false otherwise\n   * @return The address of the only asset used as collateral\n   * @return The debt ceiling of the reserve\n   */\n  function getIsolationModeState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address, uint256) {\n    if (isUsingAsCollateralOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, COLLATERAL_MASK);\n\n      address assetAddress = reservesList[assetId];\n      uint256 ceiling = reservesData[assetAddress].configuration.getDebtCeiling();\n      if (ceiling != 0) {\n        return (true, assetAddress, ceiling);\n      }\n    }\n    return (false, address(0), 0);\n  }\n\n  /**\n   * @notice Returns the siloed borrowing state for the user\n   * @param self The configuration object\n   * @param reservesData The data of all the reserves\n   * @param reservesList The reserve list\n   * @return True if the user has borrowed a siloed asset, false otherwise\n   * @return The address of the only borrowed asset\n   */\n  function getSiloedBorrowingState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address) {\n    if (isBorrowingOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK);\n      address assetAddress = reservesList[assetId];\n      if (reservesData[assetAddress].configuration.getSiloedBorrowing()) {\n        return (true, assetAddress);\n      }\n    }\n\n    return (false, address(0));\n  }\n\n  /**\n   * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask\n   * @param self The configuration object\n   * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied\n   */\n  function _getFirstAssetIdByMask(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 mask\n  ) internal pure returns (uint256) {\n    unchecked {\n      uint256 bitmapData = self.data & mask;\n      uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1);\n      uint256 id;\n\n      while ((firstAssetPosition >>= 2) != 0) {\n        id += 1;\n      }\n      return id;\n    }\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/configuration/ReserveConfiguration.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\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 =                       0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n  uint256 internal constant LIQUIDATION_THRESHOLD_MASK =     0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n  uint256 internal constant LIQUIDATION_BONUS_MASK =         0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n  uint256 internal constant DECIMALS_MASK =                  0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant ACTIVE_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant FROZEN_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROWING_MASK =                 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant STABLE_BORROWING_MASK =          0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant PAUSED_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROWABLE_IN_ISOLATION_MASK =   0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant SILOED_BORROWING_MASK =          0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant FLASHLOAN_ENABLED_MASK =         0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant RESERVE_FACTOR_MASK =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROW_CAP_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant SUPPLY_CAP_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK =  0xFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant EMODE_CATEGORY_MASK =            0xFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant UNBACKED_MINT_CAP_MASK =         0xFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant DEBT_CEILING_MASK =              0xF0000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // 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 STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n  uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60;\n  uint256 internal constant BORROWABLE_IN_ISOLATION_START_BIT_POSITION = 61;\n  uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62;\n  uint256 internal constant FLASHLOAN_ENABLED_START_BIT_POSITION = 63;\n  uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n  uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80;\n  uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116;\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152;\n  uint256 internal constant EMODE_CATEGORY_START_BIT_POSITION = 168;\n  uint256 internal constant UNBACKED_MINT_CAP_START_BIT_POSITION = 176;\n  uint256 internal constant DEBT_CEILING_START_BIT_POSITION = 212;\n\n  uint256 internal constant MAX_VALID_LTV = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n  uint256 internal constant MAX_VALID_DECIMALS = 255;\n  uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65535;\n  uint256 internal constant MAX_VALID_BORROW_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_SUPPLY_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65535;\n  uint256 internal constant MAX_VALID_EMODE_CATEGORY = 255;\n  uint256 internal constant MAX_VALID_UNBACKED_MINT_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_DEBT_CEILING = 1099511627775;\n\n  uint256 public constant DEBT_CEILING_DECIMALS = 2;\n  uint16 public constant MAX_RESERVES_COUNT = 128;\n\n  /**\n   * @notice Sets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @param ltv The new ltv\n   */\n  function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {\n    require(ltv <= MAX_VALID_LTV, Errors.INVALID_LTV);\n\n    self.data = (self.data & LTV_MASK) | ltv;\n  }\n\n  /**\n   * @notice Gets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @return The loan to value\n   */\n  function getLtv(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {\n    return self.data & ~LTV_MASK;\n  }\n\n  /**\n   * @notice Sets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @param threshold The new liquidation threshold\n   */\n  function setLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 threshold\n  ) internal pure {\n    require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD);\n\n    self.data =\n      (self.data & LIQUIDATION_THRESHOLD_MASK) |\n      (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation threshold\n   */\n  function getLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @param bonus The new liquidation bonus\n   */\n  function setLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 bonus\n  ) internal pure {\n    require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS);\n\n    self.data =\n      (self.data & LIQUIDATION_BONUS_MASK) |\n      (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation bonus\n   */\n  function getLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @param decimals The decimals\n   */\n  function setDecimals(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 decimals\n  ) internal pure {\n    require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS);\n\n    self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @return The decimals of the asset\n   */\n  function getDecimals(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the active state of the reserve\n   * @param self The reserve configuration\n   * @param active The active state\n   */\n  function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n    self.data =\n      (self.data & ACTIVE_MASK) |\n      (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the active state of the reserve\n   * @param self The reserve configuration\n   * @return The active state\n   */\n  function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @param frozen The frozen state\n   */\n  function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n    self.data =\n      (self.data & FROZEN_MASK) |\n      (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @return The frozen state\n   */\n  function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~FROZEN_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the paused state of the reserve\n   * @param self The reserve configuration\n   * @param paused The paused state\n   */\n  function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure {\n    self.data =\n      (self.data & PAUSED_MASK) |\n      (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the paused state of the reserve\n   * @param self The reserve configuration\n   * @return The paused state\n   */\n  function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~PAUSED_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the borrowable in isolation flag for the reserve.\n   * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed\n   * amount will be accumulated in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @param borrowable True if the asset is borrowable\n   */\n  function setBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool borrowable\n  ) internal pure {\n    self.data =\n      (self.data & BORROWABLE_IN_ISOLATION_MASK) |\n      (uint256(borrowable ? 1 : 0) << BORROWABLE_IN_ISOLATION_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowable in isolation flag for the reserve.\n   * @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with\n   * isolated collateral is accounted for in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @return The borrowable in isolation flag\n   */\n  function getBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~BORROWABLE_IN_ISOLATION_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @param siloed True if the asset is siloed\n   */\n  function setSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool siloed\n  ) internal pure {\n    self.data =\n      (self.data & SILOED_BORROWING_MASK) |\n      (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @return The siloed borrowing flag\n   */\n  function getSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~SILOED_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Enables or disables borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the borrowing needs to be enabled, false otherwise\n   */\n  function setBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool enabled\n  ) internal pure {\n    self.data =\n      (self.data & BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The borrowing state\n   */\n  function getBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Enables or disables stable rate borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise\n   */\n  function setStableRateBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool enabled\n  ) internal pure {\n    self.data =\n      (self.data & STABLE_BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the stable rate borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The stable rate borrowing state\n   */\n  function getStableRateBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~STABLE_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @param reserveFactor The reserve factor\n   */\n  function setReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 reserveFactor\n  ) internal pure {\n    require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.INVALID_RESERVE_FACTOR);\n\n    self.data =\n      (self.data & RESERVE_FACTOR_MASK) |\n      (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @return The reserve factor\n   */\n  function getReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @param borrowCap The borrow cap\n   */\n  function setBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 borrowCap\n  ) internal pure {\n    require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.INVALID_BORROW_CAP);\n\n    self.data = (self.data & BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @return The borrow cap\n   */\n  function getBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @param supplyCap The supply cap\n   */\n  function setSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 supplyCap\n  ) internal pure {\n    require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.INVALID_SUPPLY_CAP);\n\n    self.data = (self.data & SUPPLY_CAP_MASK) | (supplyCap << SUPPLY_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @return The supply cap\n   */\n  function getSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the debt ceiling in isolation mode for the asset\n   * @param self The reserve configuration\n   * @param ceiling The maximum debt ceiling for the asset\n   */\n  function setDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 ceiling\n  ) internal pure {\n    require(ceiling <= MAX_VALID_DEBT_CEILING, Errors.INVALID_DEBT_CEILING);\n\n    self.data = (self.data & DEBT_CEILING_MASK) | (ceiling << DEBT_CEILING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the debt ceiling for the asset if the asset is in isolation mode\n   * @param self The reserve configuration\n   * @return The debt ceiling (0 = isolation mode disabled)\n   */\n  function getDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DEBT_CEILING_MASK) >> DEBT_CEILING_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation protocol fee of the reserve\n   * @param self The reserve configuration\n   * @param liquidationProtocolFee The liquidation protocol fee\n   */\n  function setLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 liquidationProtocolFee\n  ) internal pure {\n    require(\n      liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE,\n      Errors.INVALID_LIQUIDATION_PROTOCOL_FEE\n    );\n\n    self.data =\n      (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) |\n      (liquidationProtocolFee << LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the liquidation protocol fee\n   * @param self The reserve configuration\n   * @return The liquidation protocol fee\n   */\n  function getLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return\n      (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK) >> LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @param unbackedMintCap The unbacked mint cap\n   */\n  function setUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 unbackedMintCap\n  ) internal pure {\n    require(unbackedMintCap <= MAX_VALID_UNBACKED_MINT_CAP, Errors.INVALID_UNBACKED_MINT_CAP);\n\n    self.data =\n      (self.data & UNBACKED_MINT_CAP_MASK) |\n      (unbackedMintCap << UNBACKED_MINT_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @return The unbacked mint cap\n   */\n  function getUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~UNBACKED_MINT_CAP_MASK) >> UNBACKED_MINT_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the eMode asset category\n   * @param self The reserve configuration\n   * @param category The asset category when the user selects the eMode\n   */\n  function setEModeCategory(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 category\n  ) internal pure {\n    require(category <= MAX_VALID_EMODE_CATEGORY, Errors.INVALID_EMODE_CATEGORY);\n\n    self.data = (self.data & EMODE_CATEGORY_MASK) | (category << EMODE_CATEGORY_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the eMode asset category\n   * @param self The reserve configuration\n   * @return The eMode category for the asset\n   */\n  function getEModeCategory(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~EMODE_CATEGORY_MASK) >> EMODE_CATEGORY_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 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 stableRateBorrowing 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, 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 & ~STABLE_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   * @return The state param representing eMode category\n   */\n  function getParams(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, 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      (dataLocal & ~EMODE_CATEGORY_MASK) >> EMODE_CATEGORY_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/sparklend-v1-core/contracts/interfaces/IAToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableAToken} from './IInitializableAToken.sol';\n\n/**\n * @title IAToken\n * @author Aave\n * @notice Defines the basic interface for an AToken.\n */\ninterface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {\n  /**\n   * @dev Emitted during the transfer action\n   * @param from The user whose tokens are being transferred\n   * @param to The recipient\n   * @param value The scaled amount being transferred\n   * @param index The next liquidity index of the reserve\n   */\n  event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n  /**\n   * @notice Mints `amount` aTokens to `user`\n   * @param caller The address performing the mint\n   * @param onBehalfOf The address of the user that will receive the minted aTokens\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   * @return `true` if the the previous balance of the user was 0\n   */\n  function mint(\n    address caller,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @notice Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n   * @dev In some instances, the mint event could be emitted from a burn transaction\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the aTokens will be burned\n   * @param receiverOfUnderlying The address that will receive the underlying\n   * @param amount The amount being burned\n   * @param index The next liquidity index of the reserve\n   */\n  function burn(address from, address receiverOfUnderlying, uint256 amount, uint256 index) external;\n\n  /**\n   * @notice Mints aTokens to the reserve treasury\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   */\n  function mintToTreasury(uint256 amount, uint256 index) external;\n\n  /**\n   * @notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken\n   * @param from The address getting liquidated, current owner of the aTokens\n   * @param to The recipient\n   * @param value The amount of tokens getting transferred\n   */\n  function transferOnLiquidation(address from, address to, uint256 value) external;\n\n  /**\n   * @notice Transfers the underlying asset to `target`.\n   * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan()\n   * @param target The recipient of the underlying\n   * @param amount The amount getting transferred\n   */\n  function transferUnderlyingTo(address target, uint256 amount) external;\n\n  /**\n   * @notice Handles the underlying received by the aToken after the transfer has been completed.\n   * @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the\n   * transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying\n   * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset.\n   * @param user The user executing the repayment\n   * @param onBehalfOf The address of the user who will get his debt reduced/removed\n   * @param amount The amount getting repaid\n   */\n  function handleRepayment(address user, address onBehalfOf, uint256 amount) external;\n\n  /**\n   * @notice Allow passing a signed message to approve spending\n   * @dev implements the permit function as for\n   * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n   * @param owner The owner of the funds\n   * @param spender The spender\n   * @param value The amount\n   * @param deadline The deadline timestamp, type(uint256).max for max deadline\n   * @param v Signature param\n   * @param s Signature param\n   * @param r Signature param\n   */\n  function permit(\n    address owner,\n    address spender,\n    uint256 value,\n    uint256 deadline,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external;\n\n  /**\n   * @notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Returns the address of the Aave treasury, receiving the fees on this aToken.\n   * @return Address of the Aave treasury\n   */\n  function RESERVE_TREASURY_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Get the domain separator for the token\n   * @dev Return cached value if chainId matches cache, otherwise recomputes separator\n   * @return The domain separator of the token at current chain\n   */\n  function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n  /**\n   * @notice Returns the nonce for owner.\n   * @param owner The address of the owner\n   * @return The nonce of the owner\n   */\n  function nonces(address owner) external view returns (uint256);\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   */\n  function rescueTokens(address token, address to, uint256 amount) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IStableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IInitializableDebtToken} from './IInitializableDebtToken.sol';\n\n/**\n * @title IStableDebtToken\n * @author Aave\n * @notice Defines the interface for the stable debt token\n * @dev It does not inherit from IERC20 to save in code size\n */\ninterface IStableDebtToken is IInitializableDebtToken {\n  /**\n   * @dev Emitted when new stable debt is minted\n   * @param user The address of the user who triggered the minting\n   * @param onBehalfOf The recipient of stable debt tokens\n   * @param amount The amount minted (user entered amount + balance increase from interest)\n   * @param currentBalance The balance of the user based on the previous balance and balance increase from interest\n   * @param balanceIncrease The increase in balance since the last action of the user 'onBehalfOf'\n   * @param newRate The rate of the debt after the minting\n   * @param avgStableRate The next average stable rate after the minting\n   * @param newTotalSupply The next total supply of the stable debt token after the action\n   */\n  event Mint(\n    address indexed user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 newRate,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @dev Emitted when new stable debt is burned\n   * @param from The address from which the debt will be burned\n   * @param amount The amount being burned (user entered amount - balance increase from interest)\n   * @param currentBalance The balance of the user based on the previous balance and balance increase from interest\n   * @param balanceIncrease The increase in balance since the last action of 'from'\n   * @param avgStableRate The next average stable rate after the burning\n   * @param newTotalSupply The next total supply of the stable debt token after the action\n   */\n  event Burn(\n    address indexed from,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @notice Mints debt token to the `onBehalfOf` address.\n   * @dev The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt tokens to mint\n   * @param rate The rate of the debt being minted\n   * @return True if it is the first borrow, false otherwise\n   * @return The total stable debt\n   * @return The average stable borrow rate\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 rate\n  ) external returns (bool, uint256, uint256);\n\n  /**\n   * @notice Burns debt of `user`\n   * @dev The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @dev In some instances, a burn transaction will emit a mint event\n   * if the amount to burn is less than the interest the user earned\n   * @param from The address from which the debt will be burned\n   * @param amount The amount of debt tokens getting burned\n   * @return The total stable debt\n   * @return The average stable borrow rate\n   */\n  function burn(address from, uint256 amount) external returns (uint256, uint256);\n\n  /**\n   * @notice Returns the average rate of all the stable rate loans.\n   * @return The average stable rate\n   */\n  function getAverageStableRate() external view returns (uint256);\n\n  /**\n   * @notice Returns the stable rate of the user debt\n   * @param user The address of the user\n   * @return The stable rate of the user\n   */\n  function getUserStableRate(address user) external view returns (uint256);\n\n  /**\n   * @notice Returns the timestamp of the last update of the user\n   * @param user The address of the user\n   * @return The timestamp\n   */\n  function getUserLastUpdated(address user) external view returns (uint40);\n\n  /**\n   * @notice Returns the principal, the total supply, the average stable rate and the timestamp for the last update\n   * @return The principal\n   * @return The total supply\n   * @return The average stable rate\n   * @return The timestamp of the last update\n   */\n  function getSupplyData() external view returns (uint256, uint256, uint256, uint40);\n\n  /**\n   * @notice Returns the timestamp of the last update of the total supply\n   * @return The timestamp\n   */\n  function getTotalSupplyLastUpdated() external view returns (uint40);\n\n  /**\n   * @notice Returns the total supply and the average stable rate\n   * @return The total supply\n   * @return The average rate\n   */\n  function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);\n\n  /**\n   * @notice Returns the principal debt balance of the user\n   * @return The debt balance of the user since the last burn/mint action\n   */\n  function principalBalanceOf(address user) external view returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of this stableDebtToken (E.g. WETH for stableDebtWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IVariableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableDebtToken} from './IInitializableDebtToken.sol';\n\n/**\n * @title IVariableDebtToken\n * @author Aave\n * @notice Defines the basic interface for a variable debt token.\n */\ninterface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {\n  /**\n   * @notice Mints debt token to the `onBehalfOf` address\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt being minted\n   * @param index The variable debt index of the reserve\n   * @return True if the previous balance of the user is 0, false otherwise\n   * @return The scaled total debt of the reserve\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool, uint256);\n\n  /**\n   * @notice Burns user variable debt\n   * @dev In some instances, a burn transaction will emit a mint event\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the debt will be burned\n   * @param amount The amount getting burned\n   * @param index The variable debt index of the reserve\n   * @return The scaled total debt of the reserve\n   */\n  function burn(address from, uint256 amount, uint256 index) external returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IPriceOracleGetter.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\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/sparklend-v1-core/contracts/interfaces/IReserveInterestRateStrategy.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IReserveInterestRateStrategy\n * @author Aave\n * @notice Interface for the calculation of the interest rates\n */\ninterface IReserveInterestRateStrategy {\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 rays\n   * @return stableBorrowRate The stable borrow rate expressed in rays\n   * @return variableBorrowRate The variable borrow rate expressed in rays\n   */\n  function calculateInterestRates(\n    DataTypes.CalculateInterestRatesParams memory params\n  ) external view returns (uint256, uint256, uint256);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/math/MathUtils.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {WadRayMath} from './WadRayMath.sol';\n\n/**\n * @title MathUtils library\n * @author Aave\n * @notice Provides functions to perform linear and compounded interest calculations\n */\nlibrary MathUtils {\n  using WadRayMath for uint256;\n\n  /// @dev Ignoring leap years\n  uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate linearly accumulated during the timeDelta, in ray\n   */\n  function calculateLinearInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    //solium-disable-next-line\n    uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp));\n    unchecked {\n      result = result / SECONDS_PER_YEAR;\n    }\n\n    return WadRayMath.RAY + result;\n  }\n\n  /**\n   * @dev Function to calculate the interest using a compounded interest rate formula\n   * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n   *\n   *  (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n   *\n   * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great\n   * gas cost reductions. The whitepaper contains reference to the approximation and a table showing the margin of\n   * error per different time periods\n   *\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate compounded during the timeDelta, in ray\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp,\n    uint256 currentTimestamp\n  ) internal pure returns (uint256) {\n    //solium-disable-next-line\n    uint256 exp = currentTimestamp - uint256(lastUpdateTimestamp);\n\n    if (exp == 0) {\n      return WadRayMath.RAY;\n    }\n\n    uint256 expMinusOne;\n    uint256 expMinusTwo;\n    uint256 basePowerTwo;\n    uint256 basePowerThree;\n    unchecked {\n      expMinusOne = exp - 1;\n\n      expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n      basePowerTwo = rate.rayMul(rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR);\n      basePowerThree = basePowerTwo.rayMul(rate) / SECONDS_PER_YEAR;\n    }\n\n    uint256 secondTerm = exp * expMinusOne * basePowerTwo;\n    unchecked {\n      secondTerm /= 2;\n    }\n    uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree;\n    unchecked {\n      thirdTerm /= 6;\n    }\n\n    return WadRayMath.RAY + (rate * exp) / SECONDS_PER_YEAR + secondTerm + thirdTerm;\n  }\n\n  /**\n   * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n   * @param rate The interest rate (in ray)\n   * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n   * @return The interest rate compounded between lastUpdateTimestamp and current block timestamp, in ray\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/libraries/helpers/Errors.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n/**\n * @title Errors library\n * @author Aave\n * @notice Defines the error messages emitted by the different contracts of the Aave protocol\n */\nlibrary Errors {\n  string public constant CALLER_NOT_POOL_ADMIN = '1'; // 'The caller of the function is not a pool admin'\n  string public constant CALLER_NOT_EMERGENCY_ADMIN = '2'; // 'The caller of the function is not an emergency admin'\n  string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = '3'; // 'The caller of the function is not a pool or emergency admin'\n  string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = '4'; // 'The caller of the function is not a risk or pool admin'\n  string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = '5'; // 'The caller of the function is not an asset listing or pool admin'\n  string public constant CALLER_NOT_BRIDGE = '6'; // 'The caller of the function is not a bridge'\n  string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = '7'; // 'Pool addresses provider is not registered'\n  string public constant INVALID_ADDRESSES_PROVIDER_ID = '8'; // 'Invalid id for the pool addresses provider'\n  string public constant NOT_CONTRACT = '9'; // 'Address is not a contract'\n  string public constant CALLER_NOT_POOL_CONFIGURATOR = '10'; // 'The caller of the function is not the pool configurator'\n  string public constant CALLER_NOT_ATOKEN = '11'; // 'The caller of the function is not an AToken'\n  string public constant INVALID_ADDRESSES_PROVIDER = '12'; // 'The address of the pool addresses provider is invalid'\n  string public constant INVALID_FLASHLOAN_EXECUTOR_RETURN = '13'; // 'Invalid return value of the flashloan executor function'\n  string public constant RESERVE_ALREADY_ADDED = '14'; // 'Reserve has already been added to reserve list'\n  string public constant NO_MORE_RESERVES_ALLOWED = '15'; // 'Maximum amount of reserves in the pool reached'\n  string public constant EMODE_CATEGORY_RESERVED = '16'; // 'Zero eMode category is reserved for volatile heterogeneous assets'\n  string public constant INVALID_EMODE_CATEGORY_ASSIGNMENT = '17'; // 'Invalid eMode category assignment to asset'\n  string public constant RESERVE_LIQUIDITY_NOT_ZERO = '18'; // 'The liquidity of the reserve needs to be 0'\n  string public constant FLASHLOAN_PREMIUM_INVALID = '19'; // 'Invalid flashloan premium'\n  string public constant INVALID_RESERVE_PARAMS = '20'; // 'Invalid risk parameters for the reserve'\n  string public constant INVALID_EMODE_CATEGORY_PARAMS = '21'; // 'Invalid risk parameters for the eMode category'\n  string public constant BRIDGE_PROTOCOL_FEE_INVALID = '22'; // 'Invalid bridge protocol fee'\n  string public constant CALLER_MUST_BE_POOL = '23'; // 'The caller of this function must be a pool'\n  string public constant INVALID_MINT_AMOUNT = '24'; // 'Invalid amount to mint'\n  string public constant INVALID_BURN_AMOUNT = '25'; // 'Invalid amount to burn'\n  string public constant INVALID_AMOUNT = '26'; // 'Amount must be greater than 0'\n  string public constant RESERVE_INACTIVE = '27'; // 'Action requires an active reserve'\n  string public constant RESERVE_FROZEN = '28'; // 'Action cannot be performed because the reserve is frozen'\n  string public constant RESERVE_PAUSED = '29'; // 'Action cannot be performed because the reserve is paused'\n  string public constant BORROWING_NOT_ENABLED = '30'; // 'Borrowing is not enabled'\n  string public constant STABLE_BORROWING_NOT_ENABLED = '31'; // 'Stable borrowing is not enabled'\n  string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '32'; // 'User cannot withdraw more than the available balance'\n  string public constant INVALID_INTEREST_RATE_MODE_SELECTED = '33'; // 'Invalid interest rate mode selected'\n  string public constant COLLATERAL_BALANCE_IS_ZERO = '34'; // 'The collateral balance is 0'\n  string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '35'; // 'Health factor is lesser than the liquidation threshold'\n  string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '36'; // 'There is not enough collateral to cover a new borrow'\n  string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = '37'; // 'Collateral is (mostly) the same currency that is being borrowed'\n  string public constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '38'; // 'The requested amount is greater than the max loan size in stable rate mode'\n  string public constant NO_DEBT_OF_SELECTED_TYPE = '39'; // 'For repayment of a specific type of debt, the user needs to have debt that type'\n  string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '40'; // 'To repay on behalf of a user an explicit amount to repay is needed'\n  string public constant NO_OUTSTANDING_STABLE_DEBT = '41'; // 'User does not have outstanding stable rate debt on this reserve'\n  string public constant NO_OUTSTANDING_VARIABLE_DEBT = '42'; // 'User does not have outstanding variable rate debt on this reserve'\n  string public constant UNDERLYING_BALANCE_ZERO = '43'; // 'The underlying balance needs to be greater than 0'\n  string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '44'; // 'Interest rate rebalance conditions were not met'\n  string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '45'; // 'Health factor is not below the threshold'\n  string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '46'; // 'The collateral chosen cannot be liquidated'\n  string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '47'; // 'User did not borrow the specified currency'\n  string public constant INCONSISTENT_FLASHLOAN_PARAMS = '49'; // 'Inconsistent flashloan parameters'\n  string public constant BORROW_CAP_EXCEEDED = '50'; // 'Borrow cap is exceeded'\n  string public constant SUPPLY_CAP_EXCEEDED = '51'; // 'Supply cap is exceeded'\n  string public constant UNBACKED_MINT_CAP_EXCEEDED = '52'; // 'Unbacked mint cap is exceeded'\n  string public constant DEBT_CEILING_EXCEEDED = '53'; // 'Debt ceiling is exceeded'\n  string public constant UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO = '54'; // 'Claimable rights over underlying not zero (aToken supply or accruedToTreasury)'\n  string public constant STABLE_DEBT_NOT_ZERO = '55'; // 'Stable debt supply is not zero'\n  string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = '56'; // 'Variable debt supply is not zero'\n  string public constant LTV_VALIDATION_FAILED = '57'; // 'Ltv validation failed'\n  string public constant INCONSISTENT_EMODE_CATEGORY = '58'; // 'Inconsistent eMode category'\n  string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = '59'; // 'Price oracle sentinel validation failed'\n  string public constant ASSET_NOT_BORROWABLE_IN_ISOLATION = '60'; // 'Asset is not borrowable in isolation mode'\n  string public constant RESERVE_ALREADY_INITIALIZED = '61'; // 'Reserve has already been initialized'\n  string public constant USER_IN_ISOLATION_MODE_OR_LTV_ZERO = '62'; // 'User is in isolation mode or ltv is zero'\n  string public constant INVALID_LTV = '63'; // 'Invalid ltv parameter for the reserve'\n  string public constant INVALID_LIQ_THRESHOLD = '64'; // 'Invalid liquidity threshold parameter for the reserve'\n  string public constant INVALID_LIQ_BONUS = '65'; // 'Invalid liquidity bonus parameter for the reserve'\n  string public constant INVALID_DECIMALS = '66'; // 'Invalid decimals parameter of the underlying asset of the reserve'\n  string public constant INVALID_RESERVE_FACTOR = '67'; // 'Invalid reserve factor parameter for the reserve'\n  string public constant INVALID_BORROW_CAP = '68'; // 'Invalid borrow cap for the reserve'\n  string public constant INVALID_SUPPLY_CAP = '69'; // 'Invalid supply cap for the reserve'\n  string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = '70'; // 'Invalid liquidation protocol fee for the reserve'\n  string public constant INVALID_EMODE_CATEGORY = '71'; // 'Invalid eMode category for the reserve'\n  string public constant INVALID_UNBACKED_MINT_CAP = '72'; // 'Invalid unbacked mint cap for the reserve'\n  string public constant INVALID_DEBT_CEILING = '73'; // 'Invalid debt ceiling for the reserve\n  string public constant INVALID_RESERVE_INDEX = '74'; // 'Invalid reserve index'\n  string public constant ACL_ADMIN_CANNOT_BE_ZERO = '75'; // 'ACL admin cannot be set to the zero address'\n  string public constant INCONSISTENT_PARAMS_LENGTH = '76'; // 'Array parameters that should be equal length are not'\n  string public constant ZERO_ADDRESS_NOT_VALID = '77'; // 'Zero address not valid'\n  string public constant INVALID_EXPIRATION = '78'; // 'Invalid expiration'\n  string public constant INVALID_SIGNATURE = '79'; // 'Invalid signature'\n  string public constant OPERATION_NOT_SUPPORTED = '80'; // 'Operation not supported'\n  string public constant DEBT_CEILING_NOT_ZERO = '81'; // 'Debt ceiling is not zero'\n  string public constant ASSET_NOT_LISTED = '82'; // 'Asset is not listed'\n  string public constant INVALID_OPTIMAL_USAGE_RATIO = '83'; // 'Invalid optimal usage ratio'\n  string public constant INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO = '84'; // 'Invalid optimal stable to total debt ratio'\n  string public constant UNDERLYING_CANNOT_BE_RESCUED = '85'; // 'The underlying asset cannot be rescued'\n  string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = '86'; // 'Reserve has already been added to reserve list'\n  string public constant POOL_ADDRESSES_DO_NOT_MATCH = '87'; // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n  string public constant STABLE_BORROWING_ENABLED = '88'; // 'Stable borrowing is enabled'\n  string public constant SILOED_BORROWING_VIOLATION = '89'; // 'User is trying to borrow multiple assets including a siloed one'\n  string public constant RESERVE_DEBT_NOT_ZERO = '90'; // the total debt of the reserve needs to be 0\n  string public constant FLASHLOAN_DISABLED = '91'; // FlashLoaning for this asset is disabled\n}\n"
      },
      "lib/sparklend-v1-core/contracts/dependencies/openzeppelin/contracts/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n  /**\n   * @dev Returns the downcasted uint224 from uint256, reverting on\n   * overflow (when the input is greater than largest uint224).\n   *\n   * Counterpart to Solidity's `uint224` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 224 bits\n   */\n  function toUint224(uint256 value) internal pure returns (uint224) {\n    require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n    return uint224(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint128 from uint256, reverting on\n   * overflow (when the input is greater than largest uint128).\n   *\n   * Counterpart to Solidity's `uint128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   */\n  function toUint128(uint256 value) internal pure returns (uint128) {\n    require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n    return uint128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint96 from uint256, reverting on\n   * overflow (when the input is greater than largest uint96).\n   *\n   * Counterpart to Solidity's `uint96` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 96 bits\n   */\n  function toUint96(uint256 value) internal pure returns (uint96) {\n    require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n    return uint96(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint64 from uint256, reverting on\n   * overflow (when the input is greater than largest uint64).\n   *\n   * Counterpart to Solidity's `uint64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   */\n  function toUint64(uint256 value) internal pure returns (uint64) {\n    require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n    return uint64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint32 from uint256, reverting on\n   * overflow (when the input is greater than largest uint32).\n   *\n   * Counterpart to Solidity's `uint32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   */\n  function toUint32(uint256 value) internal pure returns (uint32) {\n    require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n    return uint32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint16 from uint256, reverting on\n   * overflow (when the input is greater than largest uint16).\n   *\n   * Counterpart to Solidity's `uint16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   */\n  function toUint16(uint256 value) internal pure returns (uint16) {\n    require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n    return uint16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint8 from uint256, reverting on\n   * overflow (when the input is greater than largest uint8).\n   *\n   * Counterpart to Solidity's `uint8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   */\n  function toUint8(uint256 value) internal pure returns (uint8) {\n    require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n    return uint8(value);\n  }\n\n  /**\n   * @dev Converts a signed int256 into an unsigned uint256.\n   *\n   * Requirements:\n   *\n   * - input must be greater than or equal to 0.\n   */\n  function toUint256(int256 value) internal pure returns (uint256) {\n    require(value >= 0, 'SafeCast: value must be positive');\n    return uint256(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int128 from int256, reverting on\n   * overflow (when the input is less than smallest int128 or\n   * greater than largest int128).\n   *\n   * Counterpart to Solidity's `int128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt128(int256 value) internal pure returns (int128) {\n    require(\n      value >= type(int128).min && value <= type(int128).max,\n      \"SafeCast: value doesn't fit in 128 bits\"\n    );\n    return int128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int64 from int256, reverting on\n   * overflow (when the input is less than smallest int64 or\n   * greater than largest int64).\n   *\n   * Counterpart to Solidity's `int64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt64(int256 value) internal pure returns (int64) {\n    require(\n      value >= type(int64).min && value <= type(int64).max,\n      \"SafeCast: value doesn't fit in 64 bits\"\n    );\n    return int64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int32 from int256, reverting on\n   * overflow (when the input is less than smallest int32 or\n   * greater than largest int32).\n   *\n   * Counterpart to Solidity's `int32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt32(int256 value) internal pure returns (int32) {\n    require(\n      value >= type(int32).min && value <= type(int32).max,\n      \"SafeCast: value doesn't fit in 32 bits\"\n    );\n    return int32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int16 from int256, reverting on\n   * overflow (when the input is less than smallest int16 or\n   * greater than largest int16).\n   *\n   * Counterpart to Solidity's `int16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt16(int256 value) internal pure returns (int16) {\n    require(\n      value >= type(int16).min && value <= type(int16).max,\n      \"SafeCast: value doesn't fit in 16 bits\"\n    );\n    return int16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int8 from int256, reverting on\n   * overflow (when the input is less than smallest int8 or\n   * greater than largest int8).\n   *\n   * Counterpart to Solidity's `int8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   *\n   * _Available since v3.1._\n   */\n  function toInt8(int256 value) internal pure returns (int8) {\n    require(\n      value >= type(int8).min && value <= type(int8).max,\n      \"SafeCast: value doesn't fit in 8 bits\"\n    );\n    return int8(value);\n  }\n\n  /**\n   * @dev Converts an unsigned uint256 into a signed int256.\n   *\n   * Requirements:\n   *\n   * - input must be less than or equal to maxInt256.\n   */\n  function toInt256(uint256 value) internal pure returns (int256) {\n    // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n    require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n    return int256(value);\n  }\n}\n"
      },
      "lib/sparklend-v1-core/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/sparklend-v1-core/contracts/interfaces/IScaledBalanceToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\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/sparklend-v1-core/contracts/interfaces/IPriceOracleSentinel.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IPriceOracleSentinel\n * @author Aave\n * @notice Defines the basic interface for the PriceOracleSentinel\n */\ninterface IPriceOracleSentinel {\n  /**\n   * @dev Emitted after the sequencer oracle is updated\n   * @param newSequencerOracle The new sequencer oracle\n   */\n  event SequencerOracleUpdated(address newSequencerOracle);\n\n  /**\n   * @dev Emitted after the grace period is updated\n   * @param newGracePeriod The new grace period value\n   */\n  event GracePeriodUpdated(uint256 newGracePeriod);\n\n  /**\n   * @notice Returns the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns true if the `borrow` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `borrow` operation is allowed, false otherwise.\n   */\n  function isBorrowAllowed() external view returns (bool);\n\n  /**\n   * @notice Returns true if the `liquidation` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `liquidation` operation is allowed, false otherwise.\n   */\n  function isLiquidationAllowed() external view returns (bool);\n\n  /**\n   * @notice Updates the address of the sequencer oracle\n   * @param newSequencerOracle The address of the new Sequencer Oracle to use\n   */\n  function setSequencerOracle(address newSequencerOracle) external;\n\n  /**\n   * @notice Updates the duration of the grace period\n   * @param newGracePeriod The value of the new grace period duration\n   */\n  function setGracePeriod(uint256 newGracePeriod) external;\n\n  /**\n   * @notice Returns the SequencerOracle\n   * @return The address of the sequencer oracle contract\n   */\n  function getSequencerOracle() external view returns (address);\n\n  /**\n   * @notice Returns the grace period\n   * @return The duration of the grace period\n   */\n  function getGracePeriod() external view returns (uint256);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IPoolAddressesProvider.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\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/sparklend-v1-core/contracts/dependencies/openzeppelin/contracts/IAccessControl.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n  /**\n   * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n   *\n   * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n   * {RoleAdminChanged} not being emitted signaling this.\n   *\n   * _Available since v3.1._\n   */\n  event RoleAdminChanged(\n    bytes32 indexed role,\n    bytes32 indexed previousAdminRole,\n    bytes32 indexed newAdminRole\n  );\n\n  /**\n   * @dev Emitted when `account` is granted `role`.\n   *\n   * `sender` is the account that originated the contract call, an admin role\n   * bearer except when using {AccessControl-_setupRole}.\n   */\n  event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Emitted when `account` is revoked `role`.\n   *\n   * `sender` is the account that originated the contract call:\n   *   - if using `revokeRole`, it is the admin role bearer\n   *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n   */\n  event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Returns `true` if `account` has been granted `role`.\n   */\n  function hasRole(bytes32 role, address account) external view returns (bool);\n\n  /**\n   * @dev Returns the admin role that controls `role`. See {grantRole} and\n   * {revokeRole}.\n   *\n   * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n   */\n  function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n  /**\n   * @dev Grants `role` to `account`.\n   *\n   * If `account` had not been already granted `role`, emits a {RoleGranted}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function grantRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from `account`.\n   *\n   * If `account` had been granted `role`, emits a {RoleRevoked} event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function revokeRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from the calling account.\n   *\n   * Roles are often managed via {grantRole} and {revokeRole}: this function's\n   * purpose is to provide a mechanism for accounts to lose their privileges\n   * if they are compromised (such as when a trusted device is misplaced).\n   *\n   * If the calling account had been granted `role`, emits a {RoleRevoked}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must be `account`.\n   */\n  function renounceRole(bytes32 role, address account) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/protocol/tokenization/base/IncentivizedERC20.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.10;\n\nimport {Context} from '../../../dependencies/openzeppelin/contracts/Context.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC20Detailed} from '../../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\nimport {Errors} from '../../libraries/helpers/Errors.sol';\nimport {IAaveIncentivesController} from '../../../interfaces/IAaveIncentivesController.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {IACLManager} from '../../../interfaces/IACLManager.sol';\n\n/**\n * @title IncentivizedERC20\n * @author Aave, inspired by the Openzeppelin ERC20 implementation\n * @notice Basic ERC20 implementation\n */\nabstract contract IncentivizedERC20 is Context, IERC20Detailed {\n  using WadRayMath for uint256;\n  using SafeCast for uint256;\n\n  /**\n   * @dev Only pool admin can call functions marked by this modifier.\n   */\n  modifier onlyPoolAdmin() {\n    IACLManager aclManager = IACLManager(_addressesProvider.getACLManager());\n    require(aclManager.isPoolAdmin(msg.sender), Errors.CALLER_NOT_POOL_ADMIN);\n    _;\n  }\n\n  /**\n   * @dev Only pool can call functions marked by this modifier.\n   */\n  modifier onlyPool() {\n    require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL);\n    _;\n  }\n\n  /**\n   * @dev UserState - additionalData is a flexible field.\n   * ATokens and VariableDebtTokens use this field store the index of the\n   * user's last supply/withdrawal/borrow/repayment. StableDebtTokens use\n   * this field to store the user's stable rate.\n   */\n  struct UserState {\n    uint128 balance;\n    uint128 additionalData;\n  }\n  // Map of users address and their state data (userAddress => userStateData)\n  mapping(address => UserState) internal _userState;\n\n  // Map of allowances (delegator => delegatee => allowanceAmount)\n  mapping(address => mapping(address => uint256)) private _allowances;\n\n  uint256 internal _totalSupply;\n  string private _name;\n  string private _symbol;\n  uint8 private _decimals;\n  IAaveIncentivesController internal _incentivesController;\n  IPoolAddressesProvider internal immutable _addressesProvider;\n  IPool public immutable POOL;\n\n  /**\n   * @dev Constructor.\n   * @param pool The reference to the main Pool contract\n   * @param name The name of the token\n   * @param symbol The symbol of the token\n   * @param decimals The number of decimals of the token\n   */\n  constructor(IPool pool, string memory name, string memory symbol, uint8 decimals) {\n    _addressesProvider = pool.ADDRESSES_PROVIDER();\n    _name = name;\n    _symbol = symbol;\n    _decimals = decimals;\n    POOL = pool;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function name() public view override returns (string memory) {\n    return _name;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function symbol() external view override returns (string memory) {\n    return _symbol;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function decimals() external view override returns (uint8) {\n    return _decimals;\n  }\n\n  /// @inheritdoc IERC20\n  function totalSupply() public view virtual override returns (uint256) {\n    return _totalSupply;\n  }\n\n  /// @inheritdoc IERC20\n  function balanceOf(address account) public view virtual override returns (uint256) {\n    return _userState[account].balance;\n  }\n\n  /**\n   * @notice Returns the address of the Incentives Controller contract\n   * @return The address of the Incentives Controller\n   */\n  function getIncentivesController() external view virtual returns (IAaveIncentivesController) {\n    return _incentivesController;\n  }\n\n  /**\n   * @notice Sets a new Incentives Controller\n   * @param controller the new Incentives controller\n   */\n  function setIncentivesController(IAaveIncentivesController controller) external onlyPoolAdmin {\n    _incentivesController = controller;\n  }\n\n  /// @inheritdoc IERC20\n  function transfer(address recipient, uint256 amount) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _transfer(_msgSender(), recipient, castAmount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function allowance(\n    address owner,\n    address spender\n  ) external view virtual override returns (uint256) {\n    return _allowances[owner][spender];\n  }\n\n  /// @inheritdoc IERC20\n  function approve(address spender, uint256 amount) external virtual override returns (bool) {\n    _approve(_msgSender(), spender, amount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function transferFrom(\n    address sender,\n    address recipient,\n    uint256 amount\n  ) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - castAmount);\n    _transfer(sender, recipient, castAmount);\n    return true;\n  }\n\n  /**\n   * @notice Increases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param addedValue The amount being added to the allowance\n   * @return `true`\n   */\n  function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);\n    return true;\n  }\n\n  /**\n   * @notice Decreases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param subtractedValue The amount being subtracted to the allowance\n   * @return `true`\n   */\n  function decreaseAllowance(\n    address spender,\n    uint256 subtractedValue\n  ) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);\n    return true;\n  }\n\n  /**\n   * @notice Transfers tokens between two users and apply incentives if defined.\n   * @param sender The source address\n   * @param recipient The destination address\n   * @param amount The amount getting transferred\n   */\n  function _transfer(address sender, address recipient, uint128 amount) internal virtual {\n    uint128 oldSenderBalance = _userState[sender].balance;\n    _userState[sender].balance = oldSenderBalance - amount;\n    uint128 oldRecipientBalance = _userState[recipient].balance;\n    _userState[recipient].balance = oldRecipientBalance + amount;\n\n    IAaveIncentivesController incentivesControllerLocal = _incentivesController;\n    if (address(incentivesControllerLocal) != address(0)) {\n      uint256 currentTotalSupply = _totalSupply;\n      incentivesControllerLocal.handleAction(sender, currentTotalSupply, oldSenderBalance);\n      if (sender != recipient) {\n        incentivesControllerLocal.handleAction(recipient, currentTotalSupply, oldRecipientBalance);\n      }\n    }\n  }\n\n  /**\n   * @notice Approve `spender` to use `amount` of `owner`s balance\n   * @param owner The address owning the tokens\n   * @param spender The address approved for spending\n   * @param amount The amount of tokens to approve spending of\n   */\n  function _approve(address owner, address spender, uint256 amount) internal virtual {\n    _allowances[owner][spender] = amount;\n    emit Approval(owner, spender, amount);\n  }\n\n  /**\n   * @notice Update the name of the token\n   * @param newName The new name for the token\n   */\n  function _setName(string memory newName) internal {\n    _name = newName;\n  }\n\n  /**\n   * @notice Update the symbol for the token\n   * @param newSymbol The new symbol for the token\n   */\n  function _setSymbol(string memory newSymbol) internal {\n    _symbol = newSymbol;\n  }\n\n  /**\n   * @notice Update the number of decimals for the token\n   * @param newDecimals The new number of decimals for the token\n   */\n  function _setDecimals(uint8 newDecimals) internal {\n    _decimals = newDecimals;\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IInitializableAToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableAToken\n * @author Aave\n * @notice Interface for the initialize function on AToken\n */\ninterface IInitializableAToken {\n  /**\n   * @dev Emitted when an aToken is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param treasury The address of the treasury\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param aTokenDecimals The decimals of the underlying\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address treasury,\n    address incentivesController,\n    uint8 aTokenDecimals,\n    string aTokenName,\n    string aTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the aToken\n   * @param pool The pool contract that is initializing this contract\n   * @param treasury The address of the Aave treasury, receiving the fees on this aToken\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address treasury,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 aTokenDecimals,\n    string calldata aTokenName,\n    string calldata aTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IInitializableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableDebtToken\n * @author Aave\n * @notice Interface for the initialize function common between debt tokens\n */\ninterface IInitializableDebtToken {\n  /**\n   * @dev Emitted when a debt token is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param debtTokenDecimals The decimals of the debt token\n   * @param debtTokenName The name of the debt token\n   * @param debtTokenSymbol The symbol of the debt token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address incentivesController,\n    uint8 debtTokenDecimals,\n    string debtTokenName,\n    string debtTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the debt token.\n   * @param pool The pool contract that is initializing this contract\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's\n   * @param debtTokenName The name of the token\n   * @param debtTokenSymbol The symbol of the token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 debtTokenDecimals,\n    string memory debtTokenName,\n    string memory debtTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/dependencies/openzeppelin/contracts/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n  function _msgSender() internal view virtual returns (address payable) {\n    return payable(msg.sender);\n  }\n\n  function _msgData() internal view virtual returns (bytes memory) {\n    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n    return msg.data;\n  }\n}\n"
      },
      "lib/sparklend-v1-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IERC20} from './IERC20.sol';\n\ninterface IERC20Detailed is IERC20 {\n  function name() external view returns (string memory);\n\n  function symbol() external view returns (string memory);\n\n  function decimals() external view returns (uint8);\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IAaveIncentivesController.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAaveIncentivesController\n * @author Aave\n * @notice Defines the basic interface for an Aave Incentives Controller.\n * @dev It only contains one single function, needed as a hook on aToken and debtToken transfers.\n */\ninterface IAaveIncentivesController {\n  /**\n   * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution.\n   * @dev The units of `totalSupply` and `userBalance` should be the same.\n   * @param user The address of the user whose asset balance has changed\n   * @param totalSupply The total supply of the asset prior to user balance change\n   * @param userBalance The previous user balance prior to balance change\n   */\n  function handleAction(address user, uint256 totalSupply, uint256 userBalance) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IPool.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n  /**\n   * @dev Emitted on mintUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n   * @param amount The amount of supplied assets\n   * @param referralCode The referral code used\n   */\n  event MintUnbacked(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on backUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param backer The address paying for the backing\n   * @param amount The amount added as backing\n   * @param fee The amount paid in fees\n   */\n  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n  /**\n   * @dev Emitted on supply()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n   * @param amount The amount supplied\n   * @param referralCode The referral code used\n   */\n  event Supply(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on withdraw()\n   * @param reserve The address of the underlying asset being withdrawn\n   * @param user The address initiating the withdrawal, owner of aTokens\n   * @param to The address that will receive the underlying\n   * @param amount The amount to be withdrawn\n   */\n  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n\n  /**\n   * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n   * @param reserve The address of the underlying asset being borrowed\n   * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n   * initiator of the transaction on flashLoan()\n   * @param onBehalfOf The address that will be getting the debt\n   * @param amount The amount borrowed out\n   * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n   * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n   * @param referralCode The referral code used\n   */\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 borrowRate,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on repay()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The beneficiary of the repayment, getting his debt reduced\n   * @param repayer The address of the user initiating the repay(), providing the funds\n   * @param amount The amount repaid\n   * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n   */\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount,\n    bool useATokens\n  );\n\n  /**\n   * @dev Emitted on swapBorrowRateMode()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user swapping his rate mode\n   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n   */\n  event SwapBorrowRateMode(\n    address indexed reserve,\n    address indexed user,\n    DataTypes.InterestRateMode interestRateMode\n  );\n\n  /**\n   * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n   * @param asset The address of the underlying asset of the reserve\n   * @param totalDebt The total isolation mode debt for the reserve\n   */\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @dev Emitted when the user selects a certain asset category for eMode\n   * @param user The address of the user\n   * @param categoryId The category id\n   */\n  event UserEModeSet(address indexed user, uint8 categoryId);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   */\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   */\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on rebalanceStableBorrowRate()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user for which the rebalance has been executed\n   */\n  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on flashLoan()\n   * @param target The address of the flash loan receiver contract\n   * @param initiator The address initiating the flash loan\n   * @param asset The address of the asset being flash borrowed\n   * @param amount The amount flash borrowed\n   * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\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\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 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   * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n   * @param asset The address of the underlying asset to mint\n   * @param amount The amount to mint\n   * @param onBehalfOf The address that will receive the aTokens\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function mintUnbacked(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n   * @param asset The address of the underlying asset to back\n   * @param amount The amount to back\n   * @param fee The amount paid in fees\n   * @return The backed amount\n   */\n  function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256);\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n\n  /**\n   * @notice Supply with transfer approval of asset to be supplied done via permit function\n   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param deadline The deadline timestamp that the permit is valid\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   */\n  function supplyWithPermit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external;\n\n  /**\n   * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance\n   * @param to The address that will receive the underlying, same as msg.sender if the user\n   *   wants to receive it on his own wallet, or a different address if the beneficiary is a\n   *   different wallet\n   * @return The final amount withdrawn\n   */\n  function withdraw(address asset, uint256 amount, address to) external returns (uint256);\n\n  /**\n   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n   * corresponding debt token (StableDebtToken or VariableDebtToken)\n   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n   * @param referralCode 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/stable debt tokens of the `onBehalfOf` address\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\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 The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n   * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n   * other borrower whose debt should be removed\n   * @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/stable 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 The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\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 a borrower to swap his debt between stable and variable mode, or vice versa\n   * @param asset The address of the underlying asset borrowed\n   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n   */\n  function swapBorrowRateMode(address asset, uint256 interestRateMode) external;\n\n  /**\n   * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n   * - Users can be rebalanced if the following conditions are satisfied:\n   *     1. Usage ratio is above 95%\n   *     2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n   *        much has been borrowed at a stable rate and suppliers are not earning enough\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be rebalanced\n   */\n  function rebalanceStableBorrowRate(address asset, address user) external;\n\n  /**\n   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n   * @param asset The address of the underlying asset supplied\n   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n   */\n  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n  /**\n   * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   */\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) external;\n\n  /**\n   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n   * @param assets The addresses of the assets being flash-borrowed\n   * @param amounts The amounts of the assets being flash-borrowed\n   * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function flashLoan(\n    address receiverAddress,\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata interestRateModes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n   * @param asset The address of the asset being flash-borrowed\n   * @param amount The amount of the asset being flash-borrowed\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function flashLoanSimple(\n    address receiverAddress,\n    address asset,\n    uint256 amount,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Returns the user account data across all the reserves\n   * @param user The address of the user\n   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n   * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n   * @return currentLiquidationThreshold The liquidation threshold of the user\n   * @return ltv The loan to value of The user\n   * @return healthFactor The current health factor of the user\n   */\n  function getUserAccountData(\n    address user\n  )\n    external\n    view\n    returns (\n      uint256 totalCollateralBase,\n      uint256 totalDebtBase,\n      uint256 availableBorrowsBase,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    );\n\n  /**\n   * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n   * interest rate strategy\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n   * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n   * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   */\n  function initReserve(\n    address asset,\n    address aTokenAddress,\n    address stableDebtAddress,\n    address variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Drop a reserve\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function dropReserve(address asset) external;\n\n  /**\n   * @notice Updates the address of the interest rate strategy contract\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param rateStrategyAddress The address of the interest rate strategy contract\n   */\n  function setReserveInterestRateStrategyAddress(\n    address asset,\n    address rateStrategyAddress\n  ) external;\n\n  /**\n   * @notice 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.ReserveData memory);\n\n  /**\n   * @notice Validates and finalizes an aToken transfer\n   * @dev Only callable by the overlying aToken of the `asset`\n   * @param asset The address of the underlying asset of the aToken\n   * @param from The user from which the aTokens are transferred\n   * @param to The user receiving the aTokens\n   * @param amount The amount being transferred/withdrawn\n   * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n   * @param balanceToBefore The aToken balance of the `to` user before the transfer\n   */\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 amount,\n    uint256 balanceFromBefore,\n    uint256 balanceToBefore\n  ) external;\n\n  /**\n   * @notice Returns the list of the underlying assets of all the initialized reserves\n   * @dev It does not include dropped reserves\n   * @return The addresses of the underlying assets of the initialized reserves\n   */\n  function getReservesList() external view returns (address[] memory);\n\n  /**\n   * @notice Returns the number of initialized reserves\n   * @dev It includes dropped reserves\n   * @return The count\n   */\n  function getReservesCount() external view returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n   * @return The address of the reserve associated with id\n   */\n  function getReserveAddressById(uint16 id) external view returns (address);\n\n  /**\n   * @notice Returns the PoolAddressesProvider connected to this contract\n   * @return The address of the PoolAddressesProvider\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Updates the protocol fee on the bridging\n   * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n   */\n  function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n  /**\n   * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n   * - A part is sent to aToken holders as extra, one time accumulated interest\n   * - A part is collected by the protocol treasury\n   * @dev The total premium is calculated on the total borrowed amount\n   * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n   * @dev Only callable by the PoolConfigurator contract\n   * @param flashLoanPremiumTotal The total premium, expressed in bps\n   * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n   */\n  function updateFlashloanPremiums(\n    uint128 flashLoanPremiumTotal,\n    uint128 flashLoanPremiumToProtocol\n  ) external;\n\n  /**\n   * @notice Configures a new category for the 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(uint8 id, DataTypes.EModeCategory memory config) external;\n\n  /**\n   * @notice Returns the data of an eMode category\n   * @param id The id of the category\n   * @return The configuration data of the category\n   */\n  function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);\n\n  /**\n   * @notice Allows a user to use the protocol in eMode\n   * @param categoryId The id of the category\n   */\n  function setUserEMode(uint8 categoryId) external;\n\n  /**\n   * @notice Returns the eMode the user is using\n   * @param user The address of the user\n   * @return The eMode id\n   */\n  function getUserEMode(address user) external view returns (uint256);\n\n  /**\n   * @notice Resets the isolation mode total debt of the given asset to zero\n   * @dev It requires the given asset has zero debt ceiling\n   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n   */\n  function resetIsolationModeTotalDebt(address asset) external;\n\n  /**\n   * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n   * @return The percentage of available liquidity to borrow, expressed in bps\n   */\n  function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);\n\n  /**\n   * @notice Returns the total fee on flash loans\n   * @return The total fee on flashloans\n   */\n  function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n  /**\n   * @notice Returns the part of the bridge fees sent to protocol\n   * @return The bridge fee sent to the protocol treasury\n   */\n  function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n  /**\n   * @notice Returns the part of the flashloan fees sent to protocol\n   * @return The flashloan fee sent to the protocol treasury\n   */\n  function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n  /**\n   * @notice Returns the maximum number of reserves supported to be listed in this Pool\n   * @return The maximum number of reserves supported\n   */\n  function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n  /**\n   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n   * @param assets The list of reserves for which the minting needs to be executed\n   */\n  function mintToTreasury(address[] calldata assets) external;\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   */\n  function rescueTokens(address token, address to, uint256 amount) external;\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @dev Deprecated: Use the `supply` function instead\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n}\n"
      },
      "lib/sparklend-v1-core/contracts/interfaces/IACLManager.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\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"
      }
    },
    "settings": {
      "remappings": [
        "@aave/core-v3/=lib/sparklend-v1-core/",
        "aave-helpers/=lib/aave-helpers/src/",
        "@uniswap/v3-core/=lib/v3-core/",
        "solidity-utils/=lib/V2-V3-migration-helpers/lib/solidity-utils/src/",
        "@aave/periphery-v3/=lib/aave-address-book/lib/aave-v3-periphery/",
        "V2-V3-migration-helpers/=lib/V2-V3-migration-helpers/",
        "aave-address-book/=lib/aave-address-book/src/",
        "aave-v3-core/=lib/aave-address-book/lib/aave-v3-core/",
        "aave-v3-periphery/=lib/aave-v3-periphery/contracts/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "dss-interfaces/=lib/dss-test/lib/dss-interfaces/src/",
        "dss-test/=lib/dss-test/src/",
        "forge-std/=lib/forge-std/src/",
        "governance-crosschain-bridges/=lib/aave-helpers/lib/governance-crosschain-bridges/",
        "sparklend-v1-core/=lib/sparklend-v1-core/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 100000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "london",
      "viaIR": false,
      "libraries": {
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/BorrowLogic.sol": {
          "BorrowLogic": "0x68fB4530e156ED17cB849D19102892B7AF8cbeef"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/BridgeLogic.sol": {
          "BridgeLogic": "0x813C6C11ac19e7E8aA4148d5C6EDF31a4a160867"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/EModeLogic.sol": {
          "EModeLogic": "0xC814B56BAaeE8574C169Cc0226C97466dab68c95"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/FlashLoanLogic.sol": {
          "FlashLoanLogic": "0xCC3037F5aef5831730A9AcB1739D0562117314C0"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/LiquidationLogic.sol": {
          "LiquidationLogic": "0xC0816EFC31779C697B18B3B68f1DfBeDe313e1fA"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/PoolLogic.sol": {
          "PoolLogic": "0xD072fF8184E873a938cb15B20f2Ad5Cc1a02D8bf"
        },
        "lib/sparklend-v1-core/contracts/protocol/libraries/logic/SupplyLogic.sol": {
          "SupplyLogic": "0x4c83d30CE4D0f92A867C2006B33d9b102D29F707"
        }
      }
    }
  }}