zellic-audit
Initial commit
f998fcd
raw
history blame
205 kB
{
"language": "Solidity",
"sources": {
"contracts/protocol/lendingpool/LendingPool.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\npragma abicoder v2;\n\nimport {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IERC721} from '../../dependencies/openzeppelin/contracts/IERC721.sol';\nimport {SafeERC721} from '../libraries/helpers/SafeERC721.sol';\nimport {Address} from '../../dependencies/openzeppelin/contracts/Address.sol';\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {IVToken} from '../../interfaces/IVToken.sol';\nimport {INToken} from '../../interfaces/INToken.sol';\nimport {IERC721WithStat} from '../../interfaces/IERC721WithStat.sol';\nimport {INFTFlashLoanReceiver} from '../../flashloan/interfaces/INFTFlashLoanReceiver.sol';\nimport {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';\nimport {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';\nimport {INFTXEligibility} from '../../interfaces/INFTXEligibility.sol';\n//import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';\nimport {ILendingPool} from '../../interfaces/ILendingPool.sol';\nimport {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';\nimport {Helpers} from '../libraries/helpers/Helpers.sol';\nimport {Errors} from '../libraries/helpers/Errors.sol';\nimport {WadRayMath} from '../libraries/math/WadRayMath.sol';\nimport {PercentageMath} from '../libraries/math/PercentageMath.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {NFTVaultLogic} from '../libraries/logic/NFTVaultLogic.sol';\nimport {GenericLogic} from '../libraries/logic/GenericLogic.sol';\nimport {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {NFTVaultConfiguration} from '../libraries/configuration/NFTVaultConfiguration.sol';\nimport {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\nimport {LendingPoolStorage} from './LendingPoolStorage.sol';\n\n/**\n * @title LendingPool contract\n * @dev Main point of interaction with a Vinci protocol's market\n * - Users can:\n * # Deposit\n * # Withdraw\n * # Deposit NFT\n * # Withdraw NFT\n * # Borrow\n * # Repay\n * # Enable/disable their NFTs as collateral\n * # Liquidate positions\n * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market\n * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the\n * LendingPoolAddressesProvider\n * @author Aave\n * @author Vinci\n **/\ncontract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage {\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using GPv2SafeERC20 for IERC20;\n using SafeERC721 for IERC721;\n using ReserveLogic for DataTypes.ReserveData;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NFTVaultLogic for DataTypes.NFTVaultData;\n using NFTVaultConfiguration for DataTypes.NFTVaultConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n uint256 public constant LENDINGPOOL_REVISION = 0x3;\n\n modifier whenNotPaused() {\n _whenNotPaused();\n _;\n }\n\n modifier onlyLendingPoolConfigurator() {\n _onlyLendingPoolConfigurator();\n _;\n }\n\n function _whenNotPaused() internal view {\n require(!_paused, Errors.LP_IS_PAUSED);\n }\n\n function _onlyLendingPoolConfigurator() internal view {\n require(\n _addressesProvider.getLendingPoolConfigurator() == msg.sender,\n Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR\n );\n }\n\n function getRevision() internal pure override returns (uint256) {\n return LENDINGPOOL_REVISION;\n }\n\n /**\n * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the\n * LendingPoolAddressesProvider of the market.\n * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption\n * on subsequent operations\n * @param provider The address of the LendingPoolAddressesProvider\n **/\n function initialize(ILendingPoolAddressesProvider provider) public initializer {\n _addressesProvider = provider;\n _maxStableRateBorrowSizePercent = 2500;\n _flashLoanPremiumTotal = 0;\n _maxNumberOfReserves = 128;\n _maxNumberOfNFTVaults = 256;\n }\n\n /**\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying vTokens.\n * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to deposit\n * @param amount The amount to be deposited\n * @param onBehalfOf The address that will receive the vTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of vTokens\n * is a different wallet\n **/\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external override whenNotPaused {\n DataTypes.ReserveData storage reserve = _reserves.data[asset];\n\n ValidationLogic.validateDeposit(reserve, amount);\n\n address vToken = reserve.vTokenAddress;\n\n reserve.updateState();\n reserve.updateInterestRates(asset, vToken, amount, 0);\n\n IERC20(asset).safeTransferFrom(msg.sender, vToken, amount);\n\n IVToken(vToken).mint(onBehalfOf, amount, reserve.liquidityIndex);\n\n emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);\n }\n\n /**\n * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 vUSDC, calls withdraw() and receives 100 USDC, burning the 100 vUSDC\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 vToken balance\n * @param to Address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdraw(\n address asset,\n uint256 amount,\n address to\n ) external override whenNotPaused returns (uint256) {\n DataTypes.ReserveData storage reserve = _reserves.data[asset];\n\n address vToken = reserve.vTokenAddress;\n\n uint256 userBalance = IVToken(vToken).balanceOf(msg.sender);\n\n uint256 amountToWithdraw = amount;\n\n if (amount == type(uint256).max) {\n amountToWithdraw = userBalance;\n }\n\n ValidationLogic.validateWithdraw(\n asset,\n amountToWithdraw,\n userBalance,\n _reserves,\n _usersConfig[msg.sender],\n _addressesProvider.getPriceOracle()\n );\n\n reserve.updateState();\n\n reserve.updateInterestRates(asset, vToken, 0, amountToWithdraw);\n\n IVToken(vToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex);\n\n emit Withdraw(asset, msg.sender, to, amountToWithdraw);\n\n return amountToWithdraw;\n }\n\n /**\n * @dev Deposits NFTs with given `tokenIds` and `amounts` into the vault, receiving in return overlying nTokens.\n * E.g. User deposits an MAYC with tokenid 1234 and gets in return 1 vnMAYC with tokenid 1234\n * @param nft The address of the underlying asset to deposit\n * @param tokenIds The array of token ids to deposit\n * @param amounts The array of amounts to deposit. \n * - Must be the same length with `tokenIds`. \n * - All elements must be 1 for ERC721 NFT.\n * @param onBehalfOf The address that will receive the vnTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of vnTokens\n * is a different wallet\n **/\n function depositNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address onBehalfOf,\n uint16 referralCode\n ) external override whenNotPaused {\n require(tokenIds.length == amounts.length, Errors.LP_TOKEN_AND_AMOUNT_LENGTH_NOT_MATCH);\n DataTypes.NFTVaultData storage vault = _nftVaults.data[nft];\n\n ValidationLogic.validateDepositNFT(\n vault,\n tokenIds,\n amounts\n );\n\n address nToken = vault.nTokenAddress;\n for(uint256 i = 0; i < tokenIds.length; ++i){\n IERC721(nft).safeTransferFrom(msg.sender, nToken, tokenIds[i]);\n bool isFirstDeposit = INToken(nToken).mint(onBehalfOf, tokenIds[i], 1);\n if (isFirstDeposit) {\n _usersConfig[onBehalfOf].setUsingNFTVaultAsCollateral(vault.id, true);\n emit NFTVaultUsedAsCollateralEnabled(nft, onBehalfOf);\n }\n }\n\n emit DepositNFT(nft, msg.sender, onBehalfOf, tokenIds, amounts, referralCode);\n\n }\n\n function depositAndLockNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address onBehalfOf,\n uint16 lockType,\n uint16 referralCode\n ) external override whenNotPaused {\n require(tokenIds.length == amounts.length, Errors.LP_TOKEN_AND_AMOUNT_LENGTH_NOT_MATCH);\n DataTypes.NFTVaultData storage vault = _nftVaults.data[nft];\n\n ValidationLogic.validateDepositNFT(\n vault,\n tokenIds,\n amounts\n );\n\n ValidationLogic.validateLockNFT(\n vault,\n uint40(block.timestamp)\n ); \n\n address nToken = vault.nTokenAddress;\n for(uint256 i = 0; i < tokenIds.length; ++i){\n IERC721(nft).safeTransferFrom(msg.sender, nToken, tokenIds[i]);\n bool isFirstDeposit = INToken(nToken).mint(onBehalfOf, tokenIds[i], 1);\n if(lockType != 0) {\n INToken(nToken).lock(tokenIds[i], lockType);\n }\n if (isFirstDeposit) {\n _usersConfig[onBehalfOf].setUsingNFTVaultAsCollateral(vault.id, true);\n emit NFTVaultUsedAsCollateralEnabled(nft, onBehalfOf);\n }\n }\n\n emit DepositNFT(nft, msg.sender, onBehalfOf, tokenIds, amounts, referralCode);\n\n }\n\n /**\n * @dev Withdraws underlying NFTs with given `tokenIds` and `amounts` from the vault, burning the equivalent nTokens owned\n * E.g. User has vnMAYC with token id 1234, calls withdraw() and receives the MAYC with token id 1234, burning the vUSDC with token id 1234.\n * @param nft The address of the underlying NFT to withdraw\n * @param tokenIds The array of token ids to withdraw\n * @param amounts The array of amounts to withdraw. \n * - Must be the same length with `tokenIds`. \n * - All elements must be 1 for ERC721 NFT.\n * @param to Address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdrawNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address to\n ) external override whenNotPaused returns (uint256[] memory) {\n require(tokenIds.length == amounts.length, Errors.LP_TOKEN_AND_AMOUNT_LENGTH_NOT_MATCH);\n DataTypes.NFTVaultData storage vault = _nftVaults.data[nft];\n\n address nToken = vault.nTokenAddress;\n\n uint256[] memory userBalances = INToken(nToken).unlockedBalanceOfBatch(msg.sender, tokenIds);\n\n uint256[] memory amountsToWithdraw = amounts;\n\n uint256 amountToWithdraw = 0;\n\n for(uint256 i = 0; i < tokenIds.length; ++i){\n if (amounts[i] == type(uint256).max) {\n amountsToWithdraw[i] = userBalances[i];\n }\n amountToWithdraw = amountToWithdraw + amountsToWithdraw[i];\n }\n\n ValidationLogic.validateWithdrawNFT(\n nft,\n tokenIds,\n amountsToWithdraw,\n userBalances,\n _reserves,\n _nftVaults,\n _usersConfig[msg.sender],\n _addressesProvider.getPriceOracle()\n );\n\n if (amountToWithdraw == IERC721(nToken).balanceOf(msg.sender)) {\n _usersConfig[msg.sender].setUsingNFTVaultAsCollateral(vault.id, false);\n emit NFTVaultUsedAsCollateralDisabled(nft, msg.sender);\n }\n\n INToken(nToken).burnBatch(msg.sender, to, tokenIds, amountsToWithdraw);\n \n INFTXEligibility(vault.nftEligibility).afterRedeemHook(tokenIds);\n emit WithdrawNFT(nft, msg.sender, to, tokenIds, amountsToWithdraw);\n\n return amountsToWithdraw;\n }\n\n /**\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already deposited enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 variable debt tokens.\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow. Unused currently, must be > 0\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n **/\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external override whenNotPaused {\n DataTypes.ReserveData storage reserve = _reserves.data[asset];\n\n _executeBorrow(\n ExecuteBorrowParams(\n asset,\n msg.sender,\n onBehalfOf,\n amount,\n interestRateMode,\n reserve.vTokenAddress,\n referralCode,\n true\n )\n );\n }\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param rateMode The interest rate mode at of the debt the user wants to repay. Unused Currently, must be > 0\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n **/\n function repay(\n address asset,\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) external override whenNotPaused returns (uint256) {\n DataTypes.ReserveData storage reserve = _reserves.data[asset];\n\n (, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);\n\n DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);\n\n ValidationLogic.validateRepay(\n reserve,\n amount,\n interestRateMode,\n onBehalfOf,\n 0,\n variableDebt\n );\n\n uint256 paybackAmount = variableDebt;\n\n if (amount < paybackAmount) {\n paybackAmount = amount;\n }\n\n reserve.updateState();\n\n /*if (interestRateMode == DataTypes.InterestRateMode.STABLE) {\n IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);\n } else {*/\n IVariableDebtToken(reserve.variableDebtTokenAddress).burn(\n onBehalfOf,\n paybackAmount,\n reserve.variableBorrowIndex\n );\n //}\n\n address vToken = reserve.vTokenAddress;\n reserve.updateInterestRates(asset, vToken, paybackAmount, 0);\n\n if (variableDebt - paybackAmount == 0) {\n _usersConfig[onBehalfOf].setBorrowing(reserve.id, false);\n }\n\n IERC20(asset).safeTransferFrom(msg.sender, vToken, paybackAmount);\n\n IVToken(vToken).handleRepayment(msg.sender, paybackAmount);\n\n emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);\n\n return paybackAmount;\n }\n\n struct NFTLiquidationCallParameters {\n address collateralAsset;\n address debtAsset;\n address user;\n uint256[] tokenIds;\n uint256[] amounts;\n bool receiveNToken;\n }\n\n /**\n * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) chooses `tokenIds` and `amounts` of the `collateralAsset` NFTs of the \n * user getting liquidated, and pays the corrensponding discounted `debtAsset` price\n * to cover the debt of the user getting liquidated. \n * - If there is any `debtAsset` left after repayment of the debt, it will be converted to vToken\n * and transferred to the user getting liquidated.\n * @param collateralAsset The address of the underlying NFT 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 tokenIds The array of token ids of the NFTs that the liquidator wants to receive\n * - Starting from the front, only the portion that covers 50% of the debt of the user get liquidating will be liquidated\n * @param amounts The array of ammounts of the NFTs that the liquidator wants to receive\n * - Must be the same length with `tokenIds`\n * @param receiveNToken `true` if the liquidators wants to receive the collateral nTokens, `false` if he wants\n * to receive the underlying collateral NFT directly\n **/\n function nftLiquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n bool receiveNToken\n ) external override whenNotPaused {\n address collateralManager = _addressesProvider.getLendingPoolCollateralManager();\n NFTLiquidationCallParameters memory params;\n params.collateralAsset = collateralAsset;\n params.debtAsset = debtAsset;\n params.user = user;\n params.tokenIds = tokenIds;\n params.amounts = amounts;\n params.receiveNToken = receiveNToken;\n //solium-disable-next-line\n (bool success, bytes memory result) =\n collateralManager.delegatecall(\n abi.encodeWithSignature(\n 'nftLiquidationCall((address,address,address,uint256[],uint256[],bool))',\n params\n )\n );\n\n require(success, Errors.LP_LIQUIDATION_CALL_FAILED);\n\n (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));\n\n require(returnCode == 0, string(abi.encodePacked(returnMessage)));\n }\n\n struct NFTFlashLoanLocalVars {\n INFTFlashLoanReceiver receiver;\n uint256 i;\n address asset;\n address nTokenAddress;\n uint256 currentAmount;\n uint256 currentPremium;\n uint256 currentAmountPlusPremium;\n }\n\n /**\n * @dev Allows smartcontracts to access the nft vault of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\n * For further details please visit https://developers.aave.com\n * @param receiverAddress The address of the contract receiving the funds, implementing the INFTFlashLoanReceiver interface\n * @param asset The addresses of the assets being flash-borrowed\n * @param tokenIds The tokenIds of the NFTs being flash-borrowed\n * @param amounts For ERC1155 only: The amounts of NFTs being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n **/\n function nftFlashLoan(\n address receiverAddress,\n address asset,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n bytes calldata params,\n uint16 referralCode\n ) external override whenNotPaused \n {\n NFTFlashLoanLocalVars memory vars;\n\n vars.nTokenAddress = _nftVaults.data[asset].nTokenAddress;\n // uint256 premium = tokenIds.length * _flashLoadPremiumTotal / 10000;\n uint256 premium = 0;\n\n uint256[] memory userBalances = IERC721WithStat(vars.nTokenAddress).balanceOfBatch(msg.sender, tokenIds);\n ValidationLogic.validateNFTFlashloan(asset, tokenIds, amounts, userBalances);\n\n vars.receiver = INFTFlashLoanReceiver(receiverAddress);\n for (vars.i = 0; vars.i < tokenIds.length; vars.i++) {\n INToken(vars.nTokenAddress).transferUnderlyingTo(receiverAddress, tokenIds[vars.i], amounts[vars.i]);\n }\n require(\n vars.receiver.executeOperation(asset, tokenIds, amounts, premium, msg.sender, params),\n Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN\n );\n\n for (vars.i = 0; vars.i < tokenIds.length; vars.i++) {\n IERC721(asset).safeTransferFrom(receiverAddress, vars.nTokenAddress, tokenIds[vars.i]);\n }\n emit NFTFlashLoan(\n receiverAddress,\n msg.sender,\n asset,\n tokenIds,\n amounts,\n 0,\n referralCode\n );\n }\n\n /**\n * @dev Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state of the reserve\n **/\n function getReserveData(address asset)\n external\n view\n override\n returns (DataTypes.ReserveData memory)\n {\n return _reserves.data[asset];\n }\n\n /**\n * @dev Returns the state and configuration of the vault\n * @param asset The address of the underlying NFT of the vault\n * @return The state of the vault\n **/\n function getNFTVaultData(address asset) \n external \n view \n override\n returns (DataTypes.NFTVaultData memory)\n {\n return _nftVaults.data[asset];\n }\n\n /**\n * @dev Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralETH the total collateral in ETH of the user\n * @return totalDebtETH the total debt in ETH of the user\n * @return availableBorrowsETH the borrowing power left of the user\n * @return currentLiquidationThreshold the liquidation threshold of the user\n * @return ltv the loan to value of the user\n * @return healthFactor the current health factor of the user\n **/\n function getUserAccountData(address user)\n external\n view\n override\n returns (\n uint256 totalCollateralETH,\n uint256 totalDebtETH,\n uint256 availableBorrowsETH,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n )\n {\n (\n totalCollateralETH,\n totalDebtETH,\n ltv,\n currentLiquidationThreshold,\n healthFactor\n ) = GenericLogic.calculateUserAccountData(\n user,\n _reserves,\n _nftVaults,\n _usersConfig[user],\n _addressesProvider.getPriceOracle()\n );\n\n availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(\n totalCollateralETH,\n totalDebtETH,\n ltv\n );\n }\n\n /**\n * @dev Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getConfiguration(address asset)\n external\n view\n override\n returns (DataTypes.ReserveConfigurationMap memory)\n {\n return _reserves.data[asset].configuration;\n }\n\n /**\n * @dev Returns the configuration of the vault\n * @param asset The address of the underlying nft of the vault\n * @return The configuration of the vault\n **/\n function getNFTVaultConfiguration(address asset)\n external\n view\n override\n returns (DataTypes.NFTVaultConfigurationMap memory)\n {\n return _nftVaults.data[asset].configuration;\n }\n\n /**\n * @dev Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n **/\n function getUserConfiguration(address user)\n external\n view\n override\n returns (DataTypes.UserConfigurationMap memory)\n {\n return _usersConfig[user];\n }\n\n /**\n * @dev Returns the normalized income per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n virtual\n override\n returns (uint256)\n {\n return _reserves.data[asset].getNormalizedIncome();\n }\n\n /**\n * @dev Returns the normalized variable debt per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n override\n returns (uint256)\n {\n return _reserves.data[asset].getNormalizedDebt();\n }\n\n /**\n * @dev Returns if the LendingPool is paused\n */\n function paused() external view override returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Returns the list of the initialized reserves\n **/\n function getReservesList() external view override returns (address[] memory) {\n address[] memory _activeReserves = new address[](_reserves.count);\n\n for (uint256 i = 0; i < _reserves.count; i++) {\n _activeReserves[i] = _reserves.list[i];\n }\n return _activeReserves;\n }\n\n /**\n * @dev Returns the list of the initialized vaults\n **/\n function getNFTVaultsList() external view override returns (address[] memory) {\n address[] memory _activeVaults = new address[](_nftVaults.count);\n\n for (uint256 i = 0; i < _nftVaults.count; i++) {\n _activeVaults[i] = _nftVaults.list[i];\n }\n return _activeVaults;\n }\n\n /**\n * @dev Returns the cached LendingPoolAddressesProvider connected to this contract\n **/\n function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) {\n return _addressesProvider;\n }\n\n /**\n * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) {\n return _maxStableRateBorrowSizePercent;\n }\n\n /**\n * @dev Returns the fee on flash loans \n */\n function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) {\n return _flashLoanPremiumTotal;\n }\n\n /**\n * @dev Returns the maximum number of reserves supported to be listed in this LendingPool\n */\n function MAX_NUMBER_RESERVES() public view returns (uint256) {\n return _maxNumberOfReserves;\n }\n\n /**\n * @dev Validates and finalizes a vToken transfer\n * - Only callable by the overlying vToken of the `asset`\n * @param asset The address of the underlying asset of the vToken\n * @param from The user from which the vTokens are transferred\n * @param to The user receiving the vTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The vToken balance of the `from` user before the transfer\n * @param balanceToBefore The vToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external override whenNotPaused {\n require(msg.sender == _reserves.data[asset].vTokenAddress, Errors.LP_CALLER_MUST_BE_AN_VTOKEN);\n\n ValidationLogic.validateTransfer(\n from,\n _reserves,\n _nftVaults,\n _usersConfig[from],\n _addressesProvider.getPriceOracle()\n );\n }\n\n /**\n * @dev Validates and finalizes a nToken transfer\n * - Only callable by the overlying nToken of the `asset`\n * @param asset The address of the underlying NFT of the nToken\n * @param from The user from which the nTokens are transferred\n * @param to The user receiving the nTokens\n * @param tokenId The token id of the NFT being transferred/withdrawn\n * @param amount The amount of the NFT with `tokenId` being transferred/withdrawn\n * @param balanceFromBefore The vToken balance of the `from` user before the transfer\n * @param balanceToBefore The vToken balance of the `to` user before the transfer\n */\n function finalizeNFTSingleTransfer(\n address asset,\n address from,\n address to,\n uint256 tokenId,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external override whenNotPaused {\n require(msg.sender == _nftVaults.data[asset].nTokenAddress, Errors.LP_CALLER_MUST_BE_AN_VTOKEN);\n\n ValidationLogic.validateTransfer(\n from,\n _reserves,\n _nftVaults,\n _usersConfig[from],\n _addressesProvider.getPriceOracle()\n );\n\n uint256 vaultId = _nftVaults.data[asset].id;\n\n if (from != to) {\n if (balanceFromBefore -amount == 0) {\n DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];\n fromConfig.setUsingNFTVaultAsCollateral(vaultId, false);\n emit NFTVaultUsedAsCollateralDisabled(asset, from);\n }\n\n if (balanceToBefore == 0 && amount != 0) {\n DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];\n toConfig.setUsingNFTVaultAsCollateral(vaultId, true);\n emit NFTVaultUsedAsCollateralEnabled(asset, to);\n }\n }\n\n }\n\n /**\n * @dev Validates and finalizes a batch nToken transfer\n * - Only callable by the overlying nToken of the `asset`\n * @param asset The address of the underlying NFT of the nTokens\n * @param from The user from which the nTokens are transferred\n * @param to The user receiving the vTokens\n * @param tokenIds The array of token ids of the NFTs being transferred/withdrawn\n * @param amounts The array of amounts of the NFTs being transferred/withdrawn\n * - Must be the same length with `tokenIds`\n * @param balanceFromBefore The vToken balance of the `from` user before the transfer\n * @param balanceToBefore The vToken balance of the `to` user before the transfer\n */\n function finalizeNFTBatchTransfer(\n address asset,\n address from,\n address to,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external override whenNotPaused {\n require(msg.sender == _nftVaults.data[asset].nTokenAddress, Errors.LP_CALLER_MUST_BE_AN_VTOKEN);\n\n ValidationLogic.validateTransfer(\n from,\n _reserves,\n _nftVaults,\n _usersConfig[from],\n _addressesProvider.getPriceOracle()\n );\n\n uint256 vaultId = _nftVaults.data[asset].id;\n uint256 amount = 0;\n for(uint256 i = 0; i < amounts.length; ++i){\n amount = amount + amounts[i];\n }\n\n if (from != to) {\n if (balanceFromBefore - amount == 0) {\n DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];\n fromConfig.setUsingNFTVaultAsCollateral(vaultId, false);\n emit NFTVaultUsedAsCollateralDisabled(asset, from);\n }\n\n if (balanceToBefore == 0 && amount != 0) {\n DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];\n toConfig.setUsingNFTVaultAsCollateral(vaultId, true);\n emit NFTVaultUsedAsCollateralEnabled(asset, to);\n }\n }\n\n }\n\n /**\n * @dev Initializes a reserve, activating it, assigning a vToken and debt tokens and an\n * interest rate strategy\n * - Only callable by the LendingPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param vTokenAddress The address of the vToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param vTokenAddress 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 vTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external override onlyLendingPoolConfigurator {\n require(Address.isContract(asset), Errors.LP_NOT_CONTRACT);\n _reserves.data[asset].init(\n vTokenAddress,\n stableDebtAddress,\n variableDebtAddress,\n interestRateStrategyAddress\n );\n _addReserveToList(asset);\n }\n\n /**\n * @dev Initializes a vault, activating it, assigning a nToken and an eligibility checker\n * - Only callable by the LendingPoolConfigurator contract\n * @param nft The address of the underlying NFT of the vault\n * @param nTokenAddress The address of the nToken that will be assigned to the vault\n * @param nftEligibility The address of the NFTXEligibility contract that will be used for checking NFT eligibility\n **/\n function initNFTVault(\n address nft,\n address nTokenAddress,\n address nftEligibility\n ) external override onlyLendingPoolConfigurator {\n require(Address.isContract(nft), Errors.LP_NOT_CONTRACT);\n _nftVaults.data[nft].init(\n nTokenAddress,\n nftEligibility\n );\n _addNFTVaultToList(nft);\n }\n\n /**\n * @dev Updates the address of the interest rate strategy contract\n * - Only callable by the LendingPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n **/\n function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)\n external\n override\n onlyLendingPoolConfigurator\n {\n _reserves.data[asset].interestRateStrategyAddress = rateStrategyAddress;\n }\n\n /**\n * @dev Sets the configuration bitmap of the reserve as a whole\n * - Only callable by the LendingPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n **/\n function setConfiguration(address asset, uint256 configuration)\n external\n override\n onlyLendingPoolConfigurator\n {\n _reserves.data[asset].configuration.data = configuration;\n }\n\n /**\n * @dev Sets the configuration bitmap of the vault as a whole\n * - Only callable by the LendingPoolConfigurator contract\n * @param vault The address of the underlying NFT of the vault\n * @param configuration The new configuration bitmap\n **/\n function setNFTVaultConfiguration(address vault, uint256 configuration)\n external\n override\n onlyLendingPoolConfigurator\n {\n _nftVaults.data[vault].configuration.data = configuration;\n }\n\n function setNFTVaultActionExpiration(address vault, uint40 expiration)\n external\n override\n onlyLendingPoolConfigurator\n {\n _nftVaults.data[vault].expiration = expiration;\n }\n\n function setNFTVaultEligibility(address vault, address eligibility)\n external\n override\n onlyLendingPoolConfigurator\n {\n _nftVaults.data[vault].nftEligibility = eligibility;\n }\n\n /**\n * @dev Set the _pause state of a reserve\n * - Only callable by the LendingPoolConfigurator contract\n * @param val `true` to pause the reserve, `false` to un-pause it\n */\n function setPause(bool val) external override onlyLendingPoolConfigurator {\n _paused = val;\n if (_paused) {\n emit Paused();\n } else {\n emit Unpaused();\n }\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n uint256 interestRateMode;\n address vTokenAddress;\n uint16 referralCode;\n bool releaseUnderlying;\n }\n\n function _executeBorrow(ExecuteBorrowParams memory vars) internal {\n DataTypes.ReserveData storage reserve = _reserves.data[vars.asset];\n DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf];\n\n address oracle = _addressesProvider.getPriceOracle();\n\n uint256 amountInETH =\n IPriceOracleGetter(oracle).getAssetPrice(vars.asset) * vars.amount\n / (10**reserve.configuration.getDecimals());\n\n ValidationLogic.validateBorrow(\n vars.asset,\n reserve,\n vars.onBehalfOf,\n vars.amount,\n amountInETH,\n vars.interestRateMode,\n 0, //_maxStableRateBorrowSizePercent,\n _reserves,\n _nftVaults,\n userConfig,\n oracle\n );\n\n reserve.updateState();\n\n //uint256 currentStableRate = 0;\n\n bool isFirstBorrowing = false;\n /*if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) {\n currentStableRate = reserve.currentStableBorrowRate;\n\n isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint(\n vars.user,\n vars.onBehalfOf,\n vars.amount,\n currentStableRate\n );\n } else {*/\n isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint(\n vars.user,\n vars.onBehalfOf,\n vars.amount,\n reserve.variableBorrowIndex\n );\n //}\n\n if (isFirstBorrowing) {\n userConfig.setBorrowing(reserve.id, true);\n }\n\n reserve.updateInterestRates(\n vars.asset,\n vars.vTokenAddress,\n 0,\n vars.releaseUnderlying ? vars.amount : 0\n );\n\n if (vars.releaseUnderlying) {\n IVToken(vars.vTokenAddress).transferUnderlyingTo(vars.user, vars.amount);\n }\n\n emit Borrow(\n vars.asset,\n vars.user,\n vars.onBehalfOf,\n vars.amount,\n vars.interestRateMode,\n //DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE\n // ? currentStableRate\n reserve.currentVariableBorrowRate,\n vars.referralCode\n );\n }\n\n function _addReserveToList(address asset) internal {\n uint256 reservesCount = _reserves.count;\n\n require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED);\n\n bool reserveAlreadyAdded = _reserves.data[asset].id != 0 || _reserves.list[0] == asset;\n\n if (!reserveAlreadyAdded) {\n _reserves.data[asset].id = uint8(reservesCount);\n _reserves.list[reservesCount] = asset;\n\n _reserves.count = reservesCount + 1;\n }\n }\n\n function _addNFTVaultToList(address nft) internal {\n uint256 nftVaultsCount = _nftVaults.count;\n\n require(nftVaultsCount < _maxNumberOfNFTVaults, Errors.LP_NO_MORE_NFT_VAULTS_ALLOWED);\n\n bool vaultAlreadyAdded = _nftVaults.data[nft].id != 0 || _nftVaults.list[0] == nft;\n\n if (!vaultAlreadyAdded) {\n _nftVaults.data[nft].id = uint8(nftVaultsCount);\n _nftVaults.list[nftVaultsCount] = nft;\n\n _nftVaults.count = nftVaultsCount + 1;\n }\n }\n}\n"
},
"contracts/dependencies/openzeppelin/contracts/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)\n\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(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-or-later\npragma solidity 0.8.11;\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(\n IERC20 token,\n address to,\n uint256 value\n ) 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(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) 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"
},
"contracts/dependencies/openzeppelin/contracts/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/protocol/libraries/helpers/SafeERC721.sol": {
"content": "pragma solidity ^0.8.0;\n\nimport \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport \"../../../dependencies/openzeppelin/contracts/Address.sol\";\n\nlibrary SafeERC721 {\n using Address for address;\n\n function safeApprove(\n IERC721 token,\n address spender,\n uint256 tokenId\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, tokenId));\n }\n\n function safeSetApprovalForAll(\n IERC721 token,\n address operator,\n bool approved\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.setApprovalForAll.selector, operator, approved));\n\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC721 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC721: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC721: ERC721 operation did not succeed\");\n }\n }\n}"
},
"contracts/dependencies/openzeppelin/contracts/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (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(address target, bytes memory data) 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"
},
"contracts/interfaces/ILendingPoolAddressesProvider.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\n/**\n * @title LendingPoolAddressesProvider contract\n * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles\n * - Acting also as factory of proxies and admin of those, so with right to change its implementations\n * - Owned by the Aave Governance\n * @author Aave\n **/\ninterface ILendingPoolAddressesProvider {\n event MarketIdSet(string newMarketId);\n event LendingPoolUpdated(address indexed newAddress);\n event ConfigurationAdminUpdated(address indexed newAddress);\n event EmergencyAdminUpdated(address indexed newAddress);\n event LendingPoolConfiguratorUpdated(address indexed newAddress);\n event LendingPoolCollateralManagerUpdated(address indexed newAddress);\n event PriceOracleUpdated(address indexed newAddress);\n event LendingRateOracleUpdated(address indexed newAddress);\n event ProxyCreated(bytes32 id, address indexed newAddress);\n event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);\n\n function getMarketId() external view returns (string memory);\n\n function setMarketId(string calldata marketId) external;\n\n function setAddress(bytes32 id, address newAddress) external;\n\n function setAddressAsProxy(bytes32 id, address impl) external;\n\n function getAddress(bytes32 id) external view returns (address);\n\n function getLendingPool() external view returns (address);\n\n function setLendingPoolImpl(address pool) external;\n\n function getLendingPoolConfigurator() external view returns (address);\n\n function setLendingPoolConfiguratorImpl(address configurator) external;\n\n function getLendingPoolCollateralManager() external view returns (address);\n\n function setLendingPoolCollateralManager(address manager) external;\n\n function getPoolAdmin() external view returns (address);\n\n function setPoolAdmin(address admin) external;\n\n function getEmergencyAdmin() external view returns (address);\n\n function setEmergencyAdmin(address admin) external;\n\n function getPriceOracle() external view returns (address);\n\n function setPriceOracle(address priceOracle) external;\n\n function getLendingRateOracle() external view returns (address);\n\n function setLendingRateOracle(address lendingRateOracle) external;\n}\n"
},
"contracts/interfaces/IVToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableVToken} from './IInitializableVToken.sol';\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\n\ninterface IVToken is IERC20, IScaledBalanceToken, IInitializableVToken {\n /**\n * @dev Emitted after the mint action\n * @param from The address performing the mint\n * @param value The amount being\n * @param index The new liquidity index of the reserve\n **/\n event Mint(address indexed from, uint256 value, uint256 index);\n\n /**\n * @dev Mints `amount` vTokens to `user`\n * @param user The address receiving the minted tokens\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n * @return `true` if the the previous balance of the user was 0\n */\n function mint(\n address user,\n uint256 amount,\n uint256 index\n ) external returns (bool);\n\n /**\n * @dev Emitted after vTokens are burned\n * @param from The owner of the vTokens, getting them burned\n * @param target The address that will receive the underlying\n * @param value The amount being burned\n * @param index The new liquidity index of the reserve\n **/\n event Burn(address indexed from, address indexed target, uint256 value, uint256 index);\n\n /**\n * @dev Emitted during the transfer action\n * @param from The user whose tokens are being transferred\n * @param to The recipient\n * @param value The amount being transferred\n * @param index The new liquidity index of the reserve\n **/\n event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n /**\n * @dev Burns vTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * @param user The owner of the vTokens, getting them burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param amount The amount being burned\n * @param index The new liquidity index of the reserve\n **/\n function burn(\n address user,\n address receiverOfUnderlying,\n uint256 amount,\n uint256 index\n ) external;\n\n /**\n * @dev Mints vTokens to the reserve treasury\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n */\n function mintToTreasury(uint256 amount, uint256 index) external;\n\n /**\n * @dev Transfers vTokens in the event of a borrow being liquidated, in case the liquidators reclaims the vToken\n * @param from The address getting liquidated, current owner of the vTokens\n * @param to The recipient\n * @param value The amount of tokens getting transferred\n **/\n function transferOnLiquidation(\n address from,\n address to,\n uint256 value\n ) external;\n\n /**\n * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer\n * assets in borrow(), withdraw() and flashLoan()\n * @param user The recipient of the underlying\n * @param amount The amount getting transferred\n * @return The amount transferred\n **/\n function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);\n\n /**\n * @dev Invoked to execute actions on the vToken side after a repayment.\n * @param user The user executing the repayment\n * @param amount The amount getting repaid\n **/\n function handleRepayment(address user, uint256 amount) external;\n\n /**\n * @dev Returns the address of the incentives controller contract\n **/\n function getIncentivesController() external view returns (IAaveIncentivesController);\n\n /**\n * @dev Returns the address of the underlying asset of this vToken (E.g. WETH for aWETH)\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
},
"contracts/interfaces/INToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {ITimeLockableERC721} from './ITimeLockableERC721.sol';\nimport {IInitializableNToken} from './IInitializableNToken.sol';\n\ninterface INToken is ITimeLockableERC721, IInitializableNToken {\n /**\n * @dev Emitted after the mint action\n * @param from The address performing the mint\n * @param tokenId The token id being\n * @param value The amount being\n **/\n event Mint(address indexed from, uint256 tokenId, uint256 value);\n\n /**\n * @dev Mints `amount` NTokens with `tokenId` to `user`\n * @param user The address receiving the minted tokens\n * @param tokenId The NFT's id\n * @param amount The amount of tokens getting minted\n * @return `true` if the the previous balance of the user was 0\n */\n function mint(\n address user,\n uint256 tokenId,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted after nTokens are burned\n * @param from The owner of the nTokens, getting them burned\n * @param target The address that will receive the underlying\n * @param tokenId The token id being burned\n * @param value The amount being burned\n **/\n event Burn(address indexed from, address indexed target, uint256 tokenId, uint256 value);\n\n /**\n * @dev Emitted during the transfer action\n * @param from The user whose tokens are being transferred\n * @param to The recipient\n * @param tokenId The NFT token id being transfered\n * @param amount The amount being transferred\n **/\n event BalanceTransfer(address indexed from, address indexed to, uint256 tokenId, uint256 amount);\n\n /**\n * @dev Emitted during the transfer action\n * @param from The user whose tokens are being transferred\n * @param to The recipient\n * @param tokenIds The ids of NFT tokens being transferred\n * @param amounts The amounts being transferred\n **/\n event BalanceBatchTransfer(address indexed from, address indexed to, uint256[] tokenIds, uint256[] amounts);\n\n /**\n * @dev Burns nTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * @param user The owner of the vTokens, getting them burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param tokenId The token id being burned\n * @param amount The amount being burned\n **/\n function burn(\n address user,\n address receiverOfUnderlying,\n uint256 tokenId,\n uint256 amount\n ) external;\n\n function burnBatch(\n address user,\n address receiverOfUnderlying,\n uint256[] memory tokenIds,\n uint256[] memory amounts\n ) external;\n\n /**\n * @dev Transfers nTokens in the event of a borrow being liquidated, in case the liquidators reclaims the nToken\n * @param from The address getting liquidated, current owner of the vTokens\n * @param to The recipient\n * @param tokenIds The token id of tokens getting transffered\n * @param values The amount of tokens getting transferred\n **/\n function transferOnLiquidation(\n address from,\n address to,\n uint256[] memory tokenIds,\n uint256[] memory values\n ) external;\n\n /**\n * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer\n * assets in withdrawNFT()\n * @param user The recipient of the underlying\n * @param tokenId The token id getting transferred\n * @param amount The amount getting transferred\n * @return The amount transferred\n **/\n function transferUnderlyingTo(address user, uint256 tokenId, uint256 amount) external returns (uint256);\n\n function getLiquidationAmounts(address user, uint256 maxTotal, uint256[] memory tokenIds, uint256[] memory amounts) external view returns(uint256, uint256[] memory);\n\n /**\n * @dev Returns the address of the underlying asset of this nToken\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
},
"contracts/interfaces/IERC721WithStat.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport {IERC721Enumerable} from '../dependencies/openzeppelin/contracts/IERC721Enumerable.sol';\n\n\ninterface IERC721WithStat is IERC721Enumerable{\n function balanceOfBatch(address user, uint256[] calldata ids) external view returns (uint256[] memory);\n function tokensByAccount(address account) external view returns (uint256[] memory);\n /**\n * @dev Returns the scaled balance of the user and the scaled total supply.\n * @param user The address of the user\n * @return The scaled balance of the user\n * @return The scaled balance and the scaled total supply\n **/\n function getUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n}\n"
},
"contracts/flashloan/interfaces/INFTFlashLoanReceiver.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {ILendingPool} from '../../interfaces/ILendingPool.sol';\n\n/**\n * @title INFTFlashLoanReceiver interface\n * @notice Interface for the Vinci fee INFTFlashLoanReceiver.\n * @author Aave\n * @author Vinci\n * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n **/\ninterface INFTFlashLoanReceiver {\n function executeOperation(\n address assets,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n uint256 premiums,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);\n\n function LENDING_POOL() external view returns (ILendingPool);\n}\n"
},
"contracts/interfaces/IVariableDebtToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableDebtToken} from './IInitializableDebtToken.sol';\nimport {IAaveIncentivesController} from './IAaveIncentivesController.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 * @dev Emitted after the mint action\n * @param from The address performing the mint\n * @param onBehalfOf The address of the user on which behalf minting has been performed\n * @param value The amount to be minted\n * @param index The last index of the reserve\n **/\n event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);\n\n /**\n * @dev Mints debt token to the `onBehalfOf` address\n * @param user The address receiving the borrowed underlying, being the delegatee in case\n * of credit delegate, or same as `onBehalfOf` otherwise\n * @param onBehalfOf The address receiving the debt tokens\n * @param amount The amount of debt being minted\n * @param index The variable debt index of the reserve\n * @return `true` if the the previous balance of the user is 0\n **/\n function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external returns (bool);\n\n /**\n * @dev Emitted when variable debt is burnt\n * @param user The user which debt has been burned\n * @param amount The amount of debt being burned\n * @param index The index of the user\n **/\n event Burn(address indexed user, uint256 amount, uint256 index);\n\n /**\n * @dev Burns user variable debt\n * @param user The user which debt is burnt\n * @param index The variable debt index of the reserve\n **/\n function burn(\n address user,\n uint256 amount,\n uint256 index\n ) external;\n\n /**\n * @dev Returns the address of the incentives controller contract\n **/\n function getIncentivesController() external view returns (IAaveIncentivesController);\n}\n"
},
"contracts/interfaces/IPriceOracleGetter.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\n/**\n * @title IPriceOracleGetter interface\n * @notice Interface for the Aave price oracle.\n **/\n\ninterface IPriceOracleGetter {\n /**\n * @dev returns the asset price in ETH\n * @param asset the address of the asset\n * @return the ETH price of the asset\n **/\n function getAssetPrice(address asset) external view returns (uint256);\n}\n"
},
"contracts/interfaces/INFTXEligibility.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface INFTXEligibility {\n // Read functions.\n function name() external pure returns (string memory);\n function finalized() external view returns (bool);\n function targetAsset() external pure returns (address);\n function checkAllEligible(uint256[] calldata tokenIds)\n external\n view\n returns (bool);\n function checkEligible(uint256[] calldata tokenIds)\n external\n view\n returns (bool[] memory);\n function checkAllIneligible(uint256[] calldata tokenIds)\n external\n view\n returns (bool);\n function checkIsEligible(uint256 tokenId) external view returns (bool);\n\n // Write functions.\n function __NFTXEligibility_init_bytes(bytes calldata configData) external;\n function beforeMintHook(uint256[] calldata tokenIds) external;\n function afterMintHook(uint256[] calldata tokenIds) external;\n function beforeRedeemHook(uint256[] calldata tokenIds) external;\n function afterRedeemHook(uint256[] calldata tokenIds) external;\n function afterLiquidationHook(uint256[] calldata tokenIds, uint256[] calldata amounts) external;\n}\n"
},
"contracts/interfaces/ILendingPool.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\npragma abicoder v2;\n\nimport {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\ninterface ILendingPool {\n /**\n * @dev Emitted on deposit()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the deposit\n * @param onBehalfOf The beneficiary of the deposit, receiving the vTokens\n * @param amount The amount deposited\n **/\n event Deposit(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referral\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlyng asset being withdrawn\n * @param user The address initiating the withdrawal, owner of vTokens\n * @param to Address that will receive the underlying\n * @param amount The amount to be withdrawn\n **/\n event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n\n event DepositNFT(\n address indexed vault, \n address user,\n address indexed onBehalfOf, \n uint256[] tokenIds, \n uint256[] amounts,\n uint16 indexed referral\n );\n\n event WithdrawNFT(\n address indexed vault, \n address indexed user, \n address indexed to, \n uint256[] tokenIds,\n uint256[] amounts\n );\n\n /**\n * @dev Emitted on nftFlashLoan()\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 tokenIds The token IDs for each NFT being flash borrowed\n * @param amounts The amounts for each NFT being flash borrowed\n * @param premium The fee flash borrowed\n **/\n event NFTFlashLoan(\n address indexed target,\n address indexed initiator,\n address indexed asset,\n uint256[] tokenIds,\n uint256[] amounts,\n uint256 premium,\n uint16 referralCode\n );\n\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 amount The amount borrowed out\n * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed\n **/\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint256 borrowRateMode,\n uint256 borrowRate,\n uint16 indexed referral\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param amount The amount repaid\n **/\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount\n );\n\n /**\n * @dev Emitted when a reserve is disabled as collateral for an user\n * @param reserve The address of the reserve\n * @param user The address of the user\n **/\n event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n /**\n * @dev Emitted when a reserve is enabled as collateral for an user\n * @param reserve The address of the reserve\n * @param user The address of the user\n **/\n event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n\n /**\n * @dev Emitted on setUserUseNFTVaultAsCollateral()\n * @param nftVault The address of the underlying asset of the vault\n * @param user The address of the user enabling the usage as collateral\n **/\n event NFTVaultUsedAsCollateralEnabled(address indexed nftVault, address indexed user);\n\n /**\n * @dev Emitted on setUserUseNFTVaultAsCollateral()\n * @param nftVault The address of the underlying asset of the vault\n * @param user The address of the user enabling the usage as collateral\n **/\n event NFTVaultUsedAsCollateralDisabled(address indexed nftVault, address indexed user);\n\n /**\n * @dev Emitted when the pause is triggered.\n */\n event Paused();\n\n /**\n * @dev Emitted when the pause is lifted.\n */\n event Unpaused();\n\n /**\n * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared\n * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,\n * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it\n * gets added to the LendingPool ABI\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The new liquidity rate\n * @param stableBorrowRate The new stable borrow rate\n * @param variableBorrowRate The new variable borrow rate\n * @param liquidityIndex The new liquidity index\n * @param variableBorrowIndex The new variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying vTokens.\n * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\n * @param amount The amount to be deposited\n * @param onBehalfOf The address that will receive the vTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of vTokens\n * is a different wallet\n **/\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent vTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole vToken balance\n * @param to Address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdraw(\n address asset,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @dev Deposits an `amounts[i]` of underlying `tokenIds[i]` into the NFT reserve, receiving in return overlying nTokens.\n * @param tokenIds The tokenIds of the NFTs to be deposited\n * @param amounts For ERC1155 only: The amounts of NFTs to be deposited\n * @param onBehalfOf The address that will receive the nTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of nTokens\n * is a different wallet\n **/\n function depositNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Deposits an `amounts[i]` of underlying `tokenIds[i]` into the NFT reserve, receiving in return overlying nTokens.\n * @param tokenIds The tokenIds of the NFTs to be deposited\n * @param amounts For ERC1155 only: The amounts of NFTs to be deposited\n * @param onBehalfOf The address that will receive the nTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of nTokens\n * is a different wallet\n **/\n function depositAndLockNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address onBehalfOf,\n uint16 lockType,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Withdraws an `amounts[i]` of nTokens with `tokenIds[i]` from the reserve, burning the equivalent nTokens owned\n * @param tokenIds The tokenIds of the NFTs to be withdraw\n * @param amounts For ERC1155 only: The amounts of NFTs to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole ERC1155 tokenId balance\n * @param to Address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn. \n - the `returnedValue[i]` equals the amount of `tokenIds[i]` that has been withdrawn.\n **/\n function withdrawNFT(\n address nft,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n address to\n ) external returns (uint256[] memory);\n\n /**\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already deposited enough collateral.\n * @param amount The amount to be borrowed\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 * @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 * @return The final amount repaid\n **/\n function repay(\n address asset,\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n function nftLiquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256[] memory tokenIds,\n uint256[] memory amounts,\n bool receiveNToken\n ) external;\n\n /**\n * @dev Allows smartcontracts to access the nft vault of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\n * For further details please visit https://developers.aave.com\n * @param receiverAddress The address of the contract receiving the funds, implementing the INFTFlashLoanReceiver interface\n * @param asset The addresses of the assets being flash-borrowed\n * @param tokenIds The tokenIds of the NFTs being flash-borrowed\n * @param amounts For ERC1155 only: The amounts of NFTs being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n **/\n function nftFlashLoan(\n address receiverAddress,\n address asset,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralETH the total collateral in ETH of the user\n * @return totalDebtETH the total debt in ETH of the user\n * @return availableBorrowsETH the borrowing power left of the user\n * @return currentLiquidationThreshold the liquidation threshold of the user\n * @return ltv the loan to value of the user\n * @return healthFactor the current health factor of the user\n **/\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralETH,\n uint256 totalDebtETH,\n uint256 availableBorrowsETH,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n function initReserve(\n address reserve,\n address vTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n function initNFTVault(\n address vault,\n address nTokenAddress,\n address nftEligibility\n ) external;\n\n function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)\n external;\n\n function setConfiguration(address reserve, uint256 configuration) external;\n function setNFTVaultConfiguration(address reserve, uint256 configuration) external;\n function setNFTVaultActionExpiration(address nftValue, uint40 expiration) external;\n function setNFTVaultEligibility(address nftValue, address eligibility) external;\n\n /**\n * @dev Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @dev Returns the configuration of the NFT reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getNFTVaultConfiguration(address asset)\n external\n view\n returns (DataTypes.NFTVaultConfigurationMap memory);\n\n /**\n * @dev Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n **/\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @dev Returns the normalized income normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n /**\n * @dev Returns the normalized variable debt per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\n\n /**\n * @dev Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state of the reserve\n **/\n function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\n\n /**\n * @dev Returns the state and configuration of the NFT reserve\n * @param asset The address of the underlying NFT of the reserve\n * @return The state of the reserve\n **/\n function getNFTVaultData(address asset) external view returns (DataTypes.NFTVaultData memory);\n\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromAfter,\n uint256 balanceToBefore\n ) external;\n\n function finalizeNFTSingleTransfer(\n address asset,\n address from,\n address to,\n uint256 tokenId,\n uint256 amount,\n uint256 balanceFromAfter,\n uint256 balanceToBefore\n ) external;\n\n function finalizeNFTBatchTransfer(\n address asset,\n address from,\n address to,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n uint256 balanceFromAfter,\n uint256 balanceToBefore\n ) external;\n\n function getReservesList() external view returns (address[] memory);\n function getNFTVaultsList() external view returns (address[] memory);\n\n\n function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);\n\n function setPause(bool val) external;\n\n function paused() external view returns (bool);\n}\n"
},
"contracts/protocol/libraries/aave-upgradeability/VersionedInitializable.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\n/**\n * @title VersionedInitializable\n *\n * @dev Helper contract to implement initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n *\n * @author Aave, inspired by the OpenZeppelin Initializable contract\n */\nabstract contract VersionedInitializable {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint256 private lastInitializedRevision = 0;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private initializing;\n\n /**\n * @dev Modifier to use in the initializer function of a contract.\n */\n modifier initializer() {\n uint256 revision = getRevision();\n require(\n initializing || isConstructor() || revision > lastInitializedRevision,\n 'Contract instance has already been initialized'\n );\n\n bool isTopLevelCall = !initializing;\n if (isTopLevelCall) {\n initializing = true;\n lastInitializedRevision = revision;\n }\n\n _;\n\n if (isTopLevelCall) {\n initializing = false;\n }\n }\n\n /**\n * @dev returns the revision number of the contract\n * Needs to be defined in the inherited class as a constant.\n **/\n function getRevision() internal pure virtual returns (uint256);\n\n /**\n * @dev Returns true if and only if the function is running in the constructor\n **/\n function isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n uint256 cs;\n //solium-disable-next-line\n assembly {\n cs := extcodesize(address())\n }\n return cs == 0;\n }\n\n // Reserved storage space to allow for layout changes in the future.\n uint256[50] private ______gap;\n}\n"
},
"contracts/protocol/libraries/helpers/Helpers.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title Helpers library\n * @author Aave\n */\nlibrary Helpers {\n /**\n * @dev Fetches the user current stable and variable debt balances\n * @param user The user address\n * @param reserve The reserve data object\n * @return The stable and variable debt balance\n **/\n function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve)\n internal\n view\n returns (uint256, uint256)\n {\n return (\n 0, //IERC20(reserve.stableDebtTokenAddress).balanceOf(user),\n IERC20(reserve.variableDebtTokenAddress).balanceOf(user)\n );\n }\n\n function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve)\n internal\n view\n returns (uint256, uint256)\n {\n return (\n 0, //IERC20(reserve.stableDebtTokenAddress).balanceOf(user),\n IERC20(reserve.variableDebtTokenAddress).balanceOf(user)\n );\n }\n}\n"
},
"contracts/protocol/libraries/helpers/Errors.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\n/**\n * @title Errors library\n * @author Aave\n * @notice Defines the error messages emitted by the different contracts of the Aave protocol\n * @dev Error messages prefix glossary:\n * - VL = ValidationLogic\n * - MATH = Math libraries\n * - CT = Common errors between tokens (VToken, VariableDebtToken and StableDebtToken)\n * - AT = VToken\n * - SDT = StableDebtToken\n * - VDT = VariableDebtToken\n * - LP = LendingPool\n * - LPAPR = LendingPoolAddressesProviderRegistry\n * - LPC = LendingPoolConfiguration\n * - RL = ReserveLogic\n * - NL = NFTVaultLogic\n * - LPCM = LendingPoolCollateralManager\n * - P = Pausable\n */\nlibrary Errors {\n //common errors\n string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'\n string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small\n\n //contract specific errors\n string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0'\n string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve'\n string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen'\n string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough'\n string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance'\n string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.'\n string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled'\n string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected'\n string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0'\n string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold'\n string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow'\n string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled\n string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed\n string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode\n string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'\n string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed'\n string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve'\n string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve'\n string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0'\n string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral'\n string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve'\n string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met'\n string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed'\n string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow'\n string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.'\n string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent'\n string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator'\n string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28';\n string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool'\n string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself'\n string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero'\n string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized'\n string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_VTOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve'\n string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin'\n string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered'\n string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold'\n string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated'\n string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency'\n string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // \"There isn't enough liquidity available to liquidate\"\n string public constant LPCM_NO_ERRORS = '46'; // 'No errors'\n string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected\n string public constant MATH_MULTIPLICATION_OVERFLOW = '48';\n string public constant MATH_ADDITION_OVERFLOW = '49';\n string public constant MATH_DIVISION_BY_ZERO = '50';\n string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128\n string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128\n string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128\n string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128\n string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128\n string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint\n string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57';\n string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn\n string public constant LP_FAILED_COLLATERAL_SWAP = '60';\n string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61';\n string public constant LP_REENTRANCY_NOT_ALLOWED = '62';\n string public constant LP_CALLER_MUST_BE_AN_VTOKEN = '63';\n string public constant LP_IS_PAUSED = '64'; // 'Pool is paused'\n string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';\n string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';\n string public constant RC_INVALID_LTV = '67';\n string public constant RC_INVALID_LIQ_THRESHOLD = '68';\n string public constant RC_INVALID_LIQ_BONUS = '69';\n string public constant RC_INVALID_DECIMALS = '70';\n string public constant RC_INVALID_RESERVE_FACTOR = '71';\n string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';\n string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';\n string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74';\n string public constant UL_INVALID_INDEX = '77';\n string public constant LP_NOT_CONTRACT = '78';\n string public constant SDT_STABLE_DEBT_OVERFLOW = '79';\n string public constant SDT_BURN_EXCEEDS_BALANCE = '80';\n string public constant CT_CALLER_MUST_BE_CLAIM_ADMIN = '81';\n string public constant CT_TOKEN_CAN_NOT_BE_UNDERLYING = '82';\n string public constant CT_TOKEN_CAN_NOT_BE_SELF = '83';\n string public constant VL_NFT_LOCK_ACTION_IS_EXPIRED = '84';\n string public constant LP_NO_MORE_NFT_VAULTS_ALLOWED = '85';\n string public constant LCPM_NO_COLLATERAL_AVAILABLE = '86';\n string public constant NL_VAULT_ALREADY_INITIALIZED = '100'; // 'NFT vault has already been initialized'\n string public constant VL_NFT_INELIGIBLE_TOKEN_ID = '130';\n string public constant LP_TOKEN_AND_AMOUNT_LENGTH_NOT_MATCH = \"148\";\n\n\n enum CollateralManagerErrors {\n NO_ERROR,\n NO_COLLATERAL_AVAILABLE,\n COLLATERAL_CANNOT_BE_LIQUIDATED,\n CURRRENCY_NOT_BORROWED,\n HEALTH_FACTOR_ABOVE_THRESHOLD,\n NOT_ENOUGH_LIQUIDITY,\n NO_ACTIVE_RESERVE,\n HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,\n INVALID_EQUAL_ASSETS_TO_SWAP,\n FROZEN_RESERVE\n }\n}\n"
},
"contracts/protocol/libraries/math/WadRayMath.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title WadRayMath library\n * @author Aave\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)\n **/\n\nlibrary WadRayMath {\n uint256 internal constant WAD = 1e18;\n uint256 internal constant halfWAD = WAD / 2;\n\n uint256 internal constant RAY = 1e27;\n uint256 internal constant halfRAY = RAY / 2;\n\n uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n /**\n * @return One ray, 1e27\n **/\n function ray() internal pure returns (uint256) {\n return RAY;\n }\n\n /**\n * @return One wad, 1e18\n **/\n\n function wad() internal pure returns (uint256) {\n return WAD;\n }\n\n /**\n * @return Half ray, 1e27/2\n **/\n function halfRay() internal pure returns (uint256) {\n return halfRAY;\n }\n\n /**\n * @return Half ray, 1e18/2\n **/\n function halfWad() internal pure returns (uint256) {\n return halfWAD;\n }\n\n /**\n * @dev Multiplies two wad, rounding half up to the nearest wad\n * @param a Wad\n * @param b Wad\n * @return The result of a*b, in wad\n **/\n function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n\n require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * b + halfWAD) / WAD;\n }\n\n /**\n * @dev Divides two wad, rounding half up to the nearest wad\n * @param a Wad\n * @param b Wad\n * @return The result of a/b, in wad\n **/\n function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfB = b / 2;\n\n require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * WAD + halfB) / b;\n }\n\n /**\n * @dev Multiplies two ray, rounding half up to the nearest ray\n * @param a Ray\n * @param b Ray\n * @return The result of a*b, in ray\n **/\n function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n\n require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * b + halfRAY) / RAY;\n }\n\n /**\n * @dev Divides two ray, rounding half up to the nearest ray\n * @param a Ray\n * @param b Ray\n * @return The result of a/b, in ray\n **/\n function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfB = b / 2;\n\n require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * RAY + halfB) / b;\n }\n\n /**\n * @dev Casts ray down to wad\n * @param a Ray\n * @return a casted to wad, rounded half up to the nearest wad\n **/\n function rayToWad(uint256 a) internal pure returns (uint256) {\n uint256 halfRatio = WAD_RAY_RATIO / 2;\n uint256 result = halfRatio + a;\n require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);\n\n return result / WAD_RAY_RATIO;\n }\n\n /**\n * @dev Converts wad up to ray\n * @param a Wad\n * @return a converted in ray\n **/\n function wadToRay(uint256 a) internal pure returns (uint256) {\n uint256 result = a * WAD_RAY_RATIO;\n require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);\n return result;\n }\n}\n"
},
"contracts/protocol/libraries/math/PercentageMath.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title PercentageMath library\n * @author Aave\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded half up\n **/\n\nlibrary PercentageMath {\n uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;\n\n /**\n * @dev Executes a percentage multiplication\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return The percentage of value\n **/\n function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {\n if (value == 0 || percentage == 0) {\n return 0;\n }\n\n require(\n value <= (type(uint256).max - HALF_PERCENT) / percentage,\n Errors.MATH_MULTIPLICATION_OVERFLOW\n );\n\n return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;\n }\n\n /**\n * @dev Executes a percentage division\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return The value divided the percentage\n **/\n function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {\n require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfPercentage = percentage / 2;\n\n require(\n value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,\n Errors.MATH_MULTIPLICATION_OVERFLOW\n );\n\n return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;\n }\n}\n"
},
"contracts/protocol/libraries/logic/ReserveLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IVToken} from '../../../interfaces/IVToken.sol';\n//import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using GPv2SafeERC20 for IERC20;\n\n /**\n * @dev Emitted when the state of a reserve is updated\n * @param asset The address of the underlying asset of the reserve\n * @param liquidityRate The new liquidity rate\n * @param stableBorrowRate The new stable borrow rate\n * @param variableBorrowRate The new variable borrow rate\n * @param liquidityIndex The new liquidity index\n * @param variableBorrowIndex The new variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed asset,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n using ReserveLogic for DataTypes.ReserveData;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n /**\n * @dev Returns the ongoing normalized income for the reserve\n * A value of 1e27 means there is no income. As time passes, the income is accrued\n * A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n * @param reserve The reserve object\n * @return the normalized income. expressed in ray\n **/\n function getNormalizedIncome(DataTypes.ReserveData storage reserve)\n internal\n view\n returns (uint256)\n {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == uint40(block.timestamp)) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.liquidityIndex;\n }\n\n uint256 cumulated =\n MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n reserve.liquidityIndex\n );\n\n return cumulated;\n }\n\n /**\n * @dev Returns the ongoing normalized variable debt for the reserve\n * A value of 1e27 means there is no debt. As time passes, the income is accrued\n * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n * @param reserve The reserve object\n * @return The normalized variable debt. expressed in ray\n **/\n function getNormalizedDebt(DataTypes.ReserveData storage reserve)\n internal\n view\n returns (uint256)\n {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == uint40(block.timestamp)) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.variableBorrowIndex;\n }\n\n uint256 cumulated =\n MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n reserve.variableBorrowIndex\n );\n\n return cumulated;\n }\n\n /**\n * @dev Updates the liquidity cumulative index and the variable borrow index.\n * @param reserve the reserve object\n **/\n function updateState(DataTypes.ReserveData storage reserve) internal {\n uint256 scaledVariableDebt =\n IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();\n uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;\n uint256 previousLiquidityIndex = reserve.liquidityIndex;\n uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;\n\n (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =\n _updateIndexes(\n reserve,\n scaledVariableDebt,\n previousLiquidityIndex,\n previousVariableBorrowIndex,\n lastUpdatedTimestamp\n );\n\n _mintToTreasury(\n reserve,\n scaledVariableDebt,\n previousVariableBorrowIndex,\n newLiquidityIndex,\n newVariableBorrowIndex,\n lastUpdatedTimestamp\n );\n }\n\n /**\n * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate\n * the flashloan fee to the reserve, and spread it between all the depositors\n * @param reserve The reserve object\n * @param totalLiquidity The total liquidity available in the reserve\n * @param amount The amount to accomulate\n **/\n function cumulateToLiquidityIndex(\n DataTypes.ReserveData storage reserve,\n uint256 totalLiquidity,\n uint256 amount\n ) internal {\n uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());\n\n uint256 result = amountToLiquidityRatio + WadRayMath.ray();\n\n result = result.rayMul(reserve.liquidityIndex);\n require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n reserve.liquidityIndex = uint128(result);\n }\n\n /**\n * @dev Initializes a reserve\n * @param reserve The reserve object\n * @param vTokenAddress The address of the overlying vtoken contract\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n **/\n function init(\n DataTypes.ReserveData storage reserve,\n address vTokenAddress,\n address stableDebtTokenAddress,\n address variableDebtTokenAddress,\n address interestRateStrategyAddress\n ) external {\n require(reserve.vTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);\n\n reserve.liquidityIndex = uint128(WadRayMath.ray());\n reserve.variableBorrowIndex = uint128(WadRayMath.ray());\n reserve.vTokenAddress = vTokenAddress;\n reserve.stableDebtTokenAddress = stableDebtTokenAddress;\n reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n }\n\n struct UpdateInterestRatesLocalVars {\n //address stableDebtTokenAddress;\n uint256 availableLiquidity;\n //uint256 totalStableDebt;\n uint256 newLiquidityRate;\n //uint256 newStableRate;\n uint256 newVariableRate;\n //uint256 avgStableRate;\n uint256 totalVariableDebt;\n }\n\n /**\n * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate\n * @param reserve The address of the reserve to be updated\n * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action\n * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n **/\n function updateInterestRates(\n DataTypes.ReserveData storage reserve,\n address reserveAddress,\n address vTokenAddress,\n uint256 liquidityAdded,\n uint256 liquidityTaken\n ) internal {\n UpdateInterestRatesLocalVars memory vars;\n\n //vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;\n\n //(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)\n // .getTotalSupplyAndAvgRate();\n\n //calculates the total variable debt locally using the scaled total supply instead\n //of totalSupply(), as it's noticeably cheaper. Also, the index has been\n //updated by the previous updateState() call\n vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)\n .scaledTotalSupply()\n .rayMul(reserve.variableBorrowIndex);\n\n (\n vars.newLiquidityRate,\n ,\n vars.newVariableRate\n ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(\n reserveAddress,\n vTokenAddress,\n liquidityAdded,\n liquidityTaken,\n 0,//vars.totalStableDebt,\n vars.totalVariableDebt,\n 0,//vars.avgStableRate,\n reserve.configuration.getReserveFactor()\n );\n require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);\n //require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);\n require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);\n\n reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);\n //reserve.currentStableBorrowRate = uint128(vars.newStableRate);\n reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);\n\n emit ReserveDataUpdated(\n reserveAddress,\n vars.newLiquidityRate,\n 0, //vars.newStableRate,\n vars.newVariableRate,\n reserve.liquidityIndex,\n reserve.variableBorrowIndex\n );\n }\n\n struct MintToTreasuryLocalVars {\n //uint256 currentStableDebt;\n //uint256 principalStableDebt;\n //uint256 previousStableDebt;\n uint256 currentVariableDebt;\n uint256 previousVariableDebt;\n //uint256 avgStableRate;\n //uint256 cumulatedStableInterest;\n uint256 totalDebtAccrued;\n uint256 amountToMint;\n uint256 reserveFactor;\n //uint40 stableSupplyUpdatedTimestamp;\n }\n\n /**\n * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the\n * specific asset.\n * @param reserve The reserve reserve to be updated\n * @param scaledVariableDebt The current scaled total variable debt\n * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest\n * @param newLiquidityIndex The new liquidity index\n * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest\n **/\n function _mintToTreasury(\n DataTypes.ReserveData storage reserve,\n uint256 scaledVariableDebt,\n uint256 previousVariableBorrowIndex,\n uint256 newLiquidityIndex,\n uint256 newVariableBorrowIndex,\n uint40 timestamp\n ) internal {\n MintToTreasuryLocalVars memory vars;\n\n vars.reserveFactor = reserve.configuration.getReserveFactor();\n\n if (vars.reserveFactor == 0) {\n return;\n }\n\n //fetching the principal, total stable debt and the avg stable rate\n /*(\n vars.principalStableDebt,\n vars.currentStableDebt,\n vars.avgStableRate,\n vars.stableSupplyUpdatedTimestamp\n ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();*/\n\n //calculate the last principal variable debt\n vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);\n\n //calculate the new total supply after accumulation of the index\n vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);\n\n //calculate the stable debt until the last timestamp update\n /*vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(\n vars.avgStableRate,\n vars.stableSupplyUpdatedTimestamp,\n timestamp\n );*/\n\n //vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest);\n\n //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n vars.totalDebtAccrued = vars.currentVariableDebt - vars.previousVariableDebt;\n\n vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);\n\n if (vars.amountToMint != 0) {\n IVToken(reserve.vTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);\n }\n }\n\n /**\n * @dev Updates the reserve indexes and the timestamp of the update\n * @param reserve The reserve reserve to be updated\n * @param scaledVariableDebt The scaled variable debt\n * @param liquidityIndex The last stored liquidity index\n * @param variableBorrowIndex The last stored variable borrow index\n **/\n function _updateIndexes(\n DataTypes.ReserveData storage reserve,\n uint256 scaledVariableDebt,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex,\n uint40 timestamp\n ) internal returns (uint256, uint256) {\n uint256 currentLiquidityRate = reserve.currentLiquidityRate;\n\n uint256 newLiquidityIndex = liquidityIndex;\n uint256 newVariableBorrowIndex = variableBorrowIndex;\n\n //only cumulating if there is any income being produced\n if (currentLiquidityRate > 0) {\n uint256 cumulatedLiquidityInterest =\n MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);\n newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);\n require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n reserve.liquidityIndex = uint128(newLiquidityIndex);\n\n //as the liquidity rate might come only from stable rate loans, we need to ensure\n //that there is actual variable debt before accumulating\n if (scaledVariableDebt != 0) {\n uint256 cumulatedVariableBorrowInterest =\n MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);\n newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);\n require(\n newVariableBorrowIndex <= type(uint128).max,\n Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW\n );\n reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);\n }\n }\n\n //solium-disable-next-line\n reserve.lastUpdateTimestamp = uint40(block.timestamp);\n return (newLiquidityIndex, newVariableBorrowIndex);\n }\n}\n"
},
"contracts/protocol/libraries/logic/NFTVaultLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {NFTVaultConfiguration} from '../configuration/NFTVaultConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title NFTVaultLogic library\n * @author Vinci\n * @notice Implements the logic to update the vault state\n */\nlibrary NFTVaultLogic {\n using NFTVaultLogic for DataTypes.NFTVaultData;\n using NFTVaultConfiguration for DataTypes.NFTVaultConfigurationMap;\n\n /**\n * @dev Initializes a reserve\n * @param reserve The reserve object\n * @param nTokenAddress The address of the overlying vtoken contract\n **/\n function init(\n DataTypes.NFTVaultData storage reserve,\n address nTokenAddress,\n address nftEligibility\n ) external {\n require(reserve.nTokenAddress == address(0), Errors.NL_VAULT_ALREADY_INITIALIZED);\n reserve.nTokenAddress = nTokenAddress;\n reserve.nftEligibility = nftEligibility;\n }\n\n}\n"
},
"contracts/protocol/libraries/logic/GenericLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\npragma abicoder v2;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC721WithStat} from '../../../interfaces/IERC721WithStat.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {NFTVaultLogic} from './NFTVaultLogic.sol';\nimport {NFTVaultConfiguration} from '../configuration/NFTVaultConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title GenericLogic library\n * @author Aave\n * @title Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using NFTVaultLogic for DataTypes.NFTVaultData;\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NFTVaultConfiguration for DataTypes.NFTVaultConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;\n\n struct balanceDecreaseAllowedLocalVars {\n uint256 liquidationThreshold;\n uint256 totalCollateralInETH;\n uint256 totalDebtInETH;\n uint256 avgLiquidationThreshold;\n uint256 amountToDecreaseInETH;\n uint256 collateralBalanceAfterDecrease;\n uint256 liquidationThresholdAfterDecrease;\n uint256 healthFactorAfterDecrease;\n bool reserveUsageAsCollateralEnabled;\n }\n\n /**\n * @dev Checks if a specific balance decrease is allowed\n * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)\n * @param asset The address of the underlying asset of the reserve\n * @param user The address of the user\n * @param amount The amount to decrease\n * @param reserves The data of all the reserves\n * @param nftVaults The data of all the vaults\n * @param userConfig The user configuration\n * @param oracle The address of the oracle contract\n * @return true if the decrease of the balance is allowed\n **/\n function balanceDecreaseAllowed(\n address asset,\n address user,\n uint256 amount,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.PoolNFTVaultsData storage nftVaults,\n DataTypes.UserConfigurationMap calldata userConfig,\n address oracle\n ) external view returns (bool) {\n if (!userConfig.isBorrowingAny()) {\n return true;\n }\n\n balanceDecreaseAllowedLocalVars memory vars;\n\n (, vars.liquidationThreshold, ) = nftVaults.data[asset]\n .configuration\n .getParams();\n\n if (vars.liquidationThreshold == 0) {\n return true;\n }\n\n (\n vars.totalCollateralInETH,\n vars.totalDebtInETH,\n ,\n vars.avgLiquidationThreshold,\n\n ) = calculateUserAccountData(user, reserves, nftVaults, userConfig, oracle);\n\n if (vars.totalDebtInETH == 0) {\n return true;\n }\n\n vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset) * amount;\n\n vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH - vars.amountToDecreaseInETH;\n\n //if there is a borrow, there can't be 0 collateral\n if (vars.collateralBalanceAfterDecrease == 0) {\n return false;\n }\n\n vars.liquidationThresholdAfterDecrease = (vars.totalCollateralInETH * vars.avgLiquidationThreshold\n - vars.amountToDecreaseInETH * vars.liquidationThreshold)\n / vars.collateralBalanceAfterDecrease;\n\n uint256 healthFactorAfterDecrease =\n calculateHealthFactorFromBalances(\n vars.collateralBalanceAfterDecrease,\n vars.totalDebtInETH,\n vars.liquidationThresholdAfterDecrease\n );\n\n return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\n }\n\n struct CalculateUserAccountDataVars {\n uint256 reserveUnitPrice;\n uint256 tokenUnit;\n uint256 compoundedLiquidityBalance;\n uint256 compoundedBorrowBalance;\n uint256 decimals;\n uint256 ltv;\n uint256 liquidationThreshold;\n uint256 i;\n uint256 healthFactor;\n uint256 totalCollateralInETH;\n uint256 totalDebtInETH;\n uint256 avgLtv;\n uint256 avgLiquidationThreshold;\n uint256 reservesLength;\n bool healthFactorBelowThreshold;\n address currentReserveAddress;\n bool usageAsCollateralEnabled;\n bool userUsesReserveAsCollateral;\n }\n\n /**\n * @dev Calculates the user data across the reserves.\n * this includes the total liquidity/collateral/borrow balances in ETH,\n * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n * @param user The address of the user\n * @param reserves data of all the reserves\n * @param userConfig The configuration of the user\n * @param reserves The list of the available reserves\n * @param oracle The price oracle address\n * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF\n **/\n function calculateUserAccountData(\n address user,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.PoolNFTVaultsData storage nftVaults,\n DataTypes.UserConfigurationMap memory userConfig,\n address oracle\n )\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n CalculateUserAccountDataVars memory vars;\n\n if (userConfig.isEmpty()) {\n return (0, 0, 0, 0, type(uint256).max);\n }\n for (vars.i = 0; vars.i < reserves.count; vars.i++) {\n if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n continue;\n }\n\n vars.currentReserveAddress = reserves.list[vars.i];\n DataTypes.ReserveData storage currentReserve = reserves.data[vars.currentReserveAddress];\n\n (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve\n .configuration\n .getParams();\n\n vars.tokenUnit = 10**vars.decimals;\n vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);\n\n if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) {\n vars.compoundedLiquidityBalance = IERC20(currentReserve.vTokenAddress).balanceOf(user);\n\n uint256 liquidityBalanceETH =\n vars.reserveUnitPrice * vars.compoundedLiquidityBalance / vars.tokenUnit;\n\n vars.totalCollateralInETH = vars.totalCollateralInETH + liquidityBalanceETH;\n\n vars.avgLtv = vars.avgLtv + liquidityBalanceETH * vars.ltv;\n vars.avgLiquidationThreshold = vars.avgLiquidationThreshold\n + liquidityBalanceETH * vars.liquidationThreshold;\n }\n\n if (userConfig.isBorrowing(vars.i)) {\n vars.compoundedBorrowBalance = IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user);\n\n vars.totalDebtInETH = vars.totalDebtInETH\n + vars.reserveUnitPrice * vars.compoundedBorrowBalance / vars.tokenUnit;\n }\n }\n\n for (vars.i = 0; vars.i < nftVaults.count; vars.i++) {\n if (!userConfig.isUsingNFTVaultAsCollateral(vars.i)) {\n continue;\n }\n\n vars.currentReserveAddress = nftVaults.list[vars.i];\n DataTypes.NFTVaultData storage currentVault = nftVaults.data[vars.currentReserveAddress];\n\n (vars.ltv, vars.liquidationThreshold, ) = currentVault\n .configuration\n .getParams();\n\n vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);\n\n if (vars.liquidationThreshold != 0 && userConfig.isUsingNFTVaultAsCollateral(vars.i)) {\n vars.compoundedLiquidityBalance = IERC721WithStat(currentVault.nTokenAddress).balanceOf(user);\n\n uint256 liquidityBalanceETH =\n vars.reserveUnitPrice * vars.compoundedLiquidityBalance;\n\n vars.totalCollateralInETH = vars.totalCollateralInETH + liquidityBalanceETH;\n\n vars.avgLtv = vars.avgLtv + liquidityBalanceETH * vars.ltv;\n vars.avgLiquidationThreshold = vars.avgLiquidationThreshold\n + liquidityBalanceETH * vars.liquidationThreshold;\n }\n }\n\n vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv / vars.totalCollateralInETH : 0;\n vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0\n ? vars.avgLiquidationThreshold / vars.totalCollateralInETH\n : 0;\n\n vars.healthFactor = calculateHealthFactorFromBalances(\n vars.totalCollateralInETH,\n vars.totalDebtInETH,\n vars.avgLiquidationThreshold\n );\n return (\n vars.totalCollateralInETH,\n vars.totalDebtInETH,\n vars.avgLtv,\n vars.avgLiquidationThreshold,\n vars.healthFactor\n );\n }\n\n /**\n * @dev Calculates the health factor from the corresponding balances\n * @param totalCollateralInETH The total collateral in ETH\n * @param totalDebtInETH The total debt in ETH\n * @param liquidationThreshold The avg liquidation threshold\n * @return The health factor calculated from the balances provided\n **/\n function calculateHealthFactorFromBalances(\n uint256 totalCollateralInETH,\n uint256 totalDebtInETH,\n uint256 liquidationThreshold\n ) internal pure returns (uint256) {\n if (totalDebtInETH == 0) return type(uint256).max;\n\n return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH);\n }\n\n /**\n * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the\n * average Loan To Value\n * @param totalCollateralInETH The total collateral in ETH\n * @param totalDebtInETH The total borrow balance\n * @param ltv The average loan to value\n * @return the amount available to borrow in ETH for the user\n **/\n\n function calculateAvailableBorrowsETH(\n uint256 totalCollateralInETH,\n uint256 totalDebtInETH,\n uint256 ltv\n ) internal pure returns (uint256) {\n uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv);\n\n if (availableBorrowsETH < totalDebtInETH) {\n return 0;\n }\n\n availableBorrowsETH = availableBorrowsETH - totalDebtInETH;\n return availableBorrowsETH;\n }\n}\n"
},
"contracts/protocol/libraries/logic/ValidationLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\npragma abicoder v2;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {NFTVaultLogic} from './NFTVaultLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {NFTVaultConfiguration} from '../configuration/NFTVaultConfiguration.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {Helpers} from '../helpers/Helpers.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {INFTXEligibility} from '../../../interfaces/INFTXEligibility.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using NFTVaultLogic for DataTypes.NFTVaultData;\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using GPv2SafeERC20 for IERC20;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NFTVaultConfiguration for DataTypes.NFTVaultConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;\n uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%\n\n /**\n * @dev Validates a deposit action\n * @param reserve The reserve object on which the user is depositing\n * @param amount The amount to be deposited\n */\n function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {\n (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();\n\n require(amount != 0, Errors.VL_INVALID_AMOUNT);\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n require(!isFrozen, Errors.VL_RESERVE_FROZEN);\n }\n\n function validateDepositNFT(DataTypes.NFTVaultData storage vault, uint256[] memory ids, uint256[] memory amounts) external view {\n (bool isActive, bool isFrozen) = vault.configuration.getFlags();\n\n require(ids.length != 0, Errors.VL_INVALID_AMOUNT);\n for(uint256 i = 0; i < ids.length; ++i) {\n require(amounts[i] != 0, Errors.VL_INVALID_AMOUNT);\n }\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n require(!isFrozen, Errors.VL_RESERVE_FROZEN);\n INFTXEligibility eligibility = INFTXEligibility(vault.nftEligibility);\n require(eligibility.checkAllEligible(ids), Errors.VL_NFT_INELIGIBLE_TOKEN_ID);\n }\n\n function validateLockNFT(DataTypes.NFTVaultData storage vault, uint40 now) external view {\n require(vault.expiration >= now, Errors.VL_NFT_LOCK_ACTION_IS_EXPIRED);\n }\n\n /**\n * @dev Validates a withdraw action\n * @param reserveAddress The address of the reserve\n * @param amount The amount to be withdrawn\n * @param userBalance The balance of the user\n * @param reserves The reserves state\n * @param userConfig The user configuration\n * @param oracle The price oracle\n */\n function validateWithdraw(\n address reserveAddress,\n uint256 amount,\n uint256 userBalance,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.UserConfigurationMap storage userConfig,\n address oracle\n ) external view {\n require(amount != 0, Errors.VL_INVALID_AMOUNT);\n require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n (bool isActive, , , ) = reserves.data[reserveAddress].configuration.getFlags();\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n }\n\n /**\n * @dev Validates a withdraw action\n * @param vaultAddress The address of the vault\n * @param tokenIds The array of token ids of the NFTs to be withdrawn\n * @param amounts The array of amounts of the NFTs to be withdrawn\n * @param userBalances The array of balances of every NFT in `tokenIds` of the user\n * @param reserves The reserves state\n * @param nftVaults The vaults state\n * @param userConfig The user configuration\n * @param oracle The price oracle\n */\n function validateWithdrawNFT(\n address vaultAddress,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts,\n uint256[] calldata userBalances,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.PoolNFTVaultsData storage nftVaults,\n DataTypes.UserConfigurationMap storage userConfig,\n address oracle\n ) external view {\n require(tokenIds.length == amounts.length, Errors.VL_INVALID_AMOUNT);\n uint256 amount;\n for(uint256 i = 0; i < tokenIds.length; ++i) {\n require(amounts[i] != 0, Errors.VL_INVALID_AMOUNT);\n require(amounts[i] <= userBalances[i], Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n amount = amount + amounts[i];\n }\n\n (bool isActive, ) = nftVaults.data[vaultAddress].configuration.getFlags();\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n\n require(\n GenericLogic.balanceDecreaseAllowed(\n vaultAddress,\n msg.sender,\n amount,\n reserves,\n nftVaults,\n userConfig,\n oracle\n ),\n Errors.VL_TRANSFER_NOT_ALLOWED\n );\n }\n\n\n struct ValidateBorrowLocalVars {\n uint256 currentLtv;\n uint256 currentLiquidationThreshold;\n uint256 amountOfCollateralNeededETH;\n uint256 userCollateralBalanceETH;\n uint256 userBorrowBalanceETH;\n uint256 availableLiquidity;\n uint256 healthFactor;\n bool isActive;\n bool isFrozen;\n bool borrowingEnabled;\n //bool stableRateBorrowingEnabled;\n }\n\n /**\n * @dev Validates a borrow action\n * @param asset The address of the asset to borrow\n * @param reserve The reserve state from which the user is borrowing\n * @param userAddress The address of the user\n * @param amount The amount to be borrowed\n * @param amountInETH The amount to be borrowed, in ETH\n * @param interestRateMode The interest rate mode at which the user is borrowing\n * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage\n * @param reserves The reserves state\n * @param nftVaults The vaults state\n * @param userConfig The user configuration\n * @param oracle The price oracle\n */\n function validateBorrow(\n address asset,\n DataTypes.ReserveData storage reserve,\n address userAddress,\n uint256 amount,\n uint256 amountInETH,\n uint256 interestRateMode,\n uint256 maxStableLoanPercent,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.PoolNFTVaultsData storage nftVaults,\n DataTypes.UserConfigurationMap storage userConfig,\n address oracle\n ) external view {\n ValidateBorrowLocalVars memory vars;\n\n (vars.isActive, vars.isFrozen, vars.borrowingEnabled, ) = reserve\n .configuration\n .getFlags();\n\n require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);\n require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);\n require(amount != 0, Errors.VL_INVALID_AMOUNT);\n\n require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);\n\n //validate interest rate mode\n require(\n uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode,\n Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED\n );\n\n (\n vars.userCollateralBalanceETH,\n vars.userBorrowBalanceETH,\n vars.currentLtv,\n vars.currentLiquidationThreshold,\n vars.healthFactor\n ) = GenericLogic.calculateUserAccountData(\n userAddress,\n reserves,\n nftVaults,\n userConfig,\n oracle\n );\n\n require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);\n\n require(\n vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n );\n\n //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n vars.amountOfCollateralNeededETH = (vars.userBorrowBalanceETH + amountInETH).percentDiv(\n vars.currentLtv\n ); //LTV is calculated in percentage\n\n require(\n vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,\n Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW\n );\n\n }\n\n /**\n * @dev Validates a repay action\n * @param reserve The reserve state from which the user is repaying\n * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n * @param onBehalfOf The address of the user msg.sender is repaying for\n * @param stableDebt The borrow balance of the user\n * @param variableDebt The borrow balance of the user\n */\n function validateRepay(\n DataTypes.ReserveData storage reserve,\n uint256 amountSent,\n DataTypes.InterestRateMode rateMode,\n address onBehalfOf,\n uint256 stableDebt,\n uint256 variableDebt\n ) external view {\n bool isActive = reserve.configuration.getActive();\n\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n\n require(amountSent > 0, Errors.VL_INVALID_AMOUNT);\n\n require(\n (variableDebt > 0 &&\n DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE),\n Errors.VL_NO_DEBT_OF_SELECTED_TYPE\n );\n\n require(\n amountSent != type(uint256).max || msg.sender == onBehalfOf,\n Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n );\n }\n\n /**\n * @dev Validates a nft-flashloan action\n * @param asset The asset being flashborrowed\n * @param tokenIds The tokenIds for each NFT being borrowed\n * @param amounts The amounts for each NFT being borrowed\n * @param userBalances The amounts for each NFT in the vault\n **/\n function validateNFTFlashloan(address asset, uint256[] memory tokenIds, uint256[] memory amounts, uint256[] memory userBalances) internal pure {\n require(tokenIds.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS);\n for(uint256 i = 0; i < tokenIds.length; ++i) {\n require(amounts[i] != 0, Errors.VL_INVALID_AMOUNT);\n require(amounts[i] <= userBalances[i], Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n }\n }\n\n /**\n * @dev Validates the liquidation action\n * @param collateralVault The vault data of the collateral\n * @param principalReserve The reserve data of the principal\n * @param userConfig The user configuration\n * @param userHealthFactor The user's health factor\n * @param userStableDebt Total stable debt balance of the user\n * @param userVariableDebt Total variable debt balance of the user\n **/\n function validateNFTLiquidationCall(\n DataTypes.NFTVaultData storage collateralVault,\n DataTypes.ReserveData storage principalReserve,\n DataTypes.UserConfigurationMap storage userConfig,\n uint256 userHealthFactor,\n uint256 userStableDebt,\n uint256 userVariableDebt\n ) internal view returns (uint256, string memory) {\n if (\n !collateralVault.configuration.getActive() || !principalReserve.configuration.getActive()\n ) {\n return (\n uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE),\n Errors.VL_NO_ACTIVE_RESERVE\n );\n }\n\n if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {\n return (\n uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD),\n Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n );\n }\n\n bool isCollateralEnabled =\n collateralVault.configuration.getLiquidationThreshold() > 0 &&\n userConfig.isUsingNFTVaultAsCollateral(collateralVault.id);\n\n //if collateral isn't enabled as collateral by user, it cannot be liquidated\n if (!isCollateralEnabled) {\n return (\n uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED),\n Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED\n );\n }\n\n if (userVariableDebt == 0) {\n return (\n uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED),\n Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER\n );\n }\n\n return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);\n }\n\n /**\n * @dev Validates a vToken transfer or an nToken transfer\n * @param from The user from which the vTokens/nTokens are being transferred\n * @param reserves The state of all the reserves\n * @param nftVaults The state of all the NFT vaults\n * @param userConfig The state of the user for the specific reserve\n * @param oracle The price oracle\n */\n function validateTransfer(\n address from,\n DataTypes.PoolReservesData storage reserves,\n DataTypes.PoolNFTVaultsData storage nftVaults,\n DataTypes.UserConfigurationMap storage userConfig,\n address oracle\n ) internal view {\n (, , , , uint256 healthFactor) =\n GenericLogic.calculateUserAccountData(\n from,\n reserves,\n nftVaults,\n userConfig,\n oracle\n );\n\n require(\n healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.VL_TRANSFER_NOT_ALLOWED\n );\n }\n}\n"
},
"contracts/protocol/libraries/configuration/ReserveConfiguration.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the reserve configuration\n */\nlibrary ReserveConfiguration {\n uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n\n /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;\n uint256 constant IS_FROZEN_START_BIT_POSITION = 57;\n uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n\n uint256 constant MAX_VALID_LTV = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n uint256 constant MAX_VALID_DECIMALS = 255;\n uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;\n\n /**\n * @dev Sets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @param ltv the new ltv\n **/\n function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {\n require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);\n\n self.data = (self.data & LTV_MASK) | ltv;\n }\n\n /**\n * @dev Gets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @return The loan to value\n **/\n function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return self.data & ~LTV_MASK;\n }\n\n /**\n * @dev Sets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @param threshold The new liquidation threshold\n **/\n function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold)\n internal\n pure\n {\n require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);\n\n self.data =\n (self.data & LIQUIDATION_THRESHOLD_MASK) |\n (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @return The liquidation threshold\n **/\n function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @param bonus The new liquidation bonus\n **/\n function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus)\n internal\n pure\n {\n require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);\n\n self.data =\n (self.data & LIQUIDATION_BONUS_MASK) |\n (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @return The liquidation bonus\n **/\n function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @param decimals The decimals\n **/\n function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals)\n internal\n pure\n {\n require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);\n\n self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @return The decimals of the asset\n **/\n function getDecimals(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the active state of the reserve\n * @param self The reserve configuration\n * @param active The active state\n **/\n function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n self.data =\n (self.data & ACTIVE_MASK) |\n (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the active state of the reserve\n * @param self The reserve configuration\n * @return The active state\n **/\n function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~ACTIVE_MASK) != 0;\n }\n\n /**\n * @dev Sets the frozen state of the reserve\n * @param self The reserve configuration\n * @param frozen The frozen state\n **/\n function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n self.data =\n (self.data & FROZEN_MASK) |\n (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the frozen state of the reserve\n * @param self The reserve configuration\n * @return The frozen state\n **/\n function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~FROZEN_MASK) != 0;\n }\n\n /**\n * @dev Enables or disables borrowing on the reserve\n * @param self The reserve configuration\n * @param enabled True if the borrowing needs to be enabled, false otherwise\n **/\n function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled)\n internal\n pure\n {\n self.data =\n (self.data & BORROWING_MASK) |\n (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the borrowing state of the reserve\n * @param self The reserve configuration\n * @return The borrowing state\n **/\n function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (bool)\n {\n return (self.data & ~BORROWING_MASK) != 0;\n }\n\n /**\n * @dev Enables or disables stable rate borrowing on the reserve\n * @param self The reserve configuration\n * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise\n **/\n function setStableRateBorrowingEnabled(\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 * @dev Gets the stable rate borrowing state of the reserve\n * @param self The reserve configuration\n * @return The stable rate borrowing state\n **/\n function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (bool)\n {\n return (self.data & ~STABLE_BORROWING_MASK) != 0;\n }\n\n /**\n * @dev Sets the reserve factor of the reserve\n * @param self The reserve configuration\n * @param reserveFactor The reserve factor\n **/\n function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor)\n internal\n pure\n {\n require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);\n\n self.data =\n (self.data & RESERVE_FACTOR_MASK) |\n (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the reserve factor of the reserve\n * @param self The reserve configuration\n * @return The reserve factor\n **/\n function getReserveFactor(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n }\n\n /**\n * @dev Gets the configuration flags of the reserve\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlags(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n bool,\n bool,\n bool,\n bool\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~ACTIVE_MASK) != 0,\n (dataLocal & ~FROZEN_MASK) != 0,\n (dataLocal & ~BORROWING_MASK) != 0,\n (dataLocal & ~STABLE_BORROWING_MASK) != 0\n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParams(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n return (\n self.data & ~LTV_MASK,\n (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the configuration flags of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n bool,\n bool,\n bool,\n bool\n )\n {\n return (\n (self.data & ~ACTIVE_MASK) != 0,\n (self.data & ~FROZEN_MASK) != 0,\n (self.data & ~BORROWING_MASK) != 0,\n (self.data & ~STABLE_BORROWING_MASK) != 0\n );\n }\n}\n"
},
"contracts/protocol/libraries/configuration/NFTVaultConfiguration.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title NFTVaultConfiguration library\n * @author Vinci\n * @notice Implements the bitmap logic to handle the NFT vault configuration\n */\nlibrary NFTVaultConfiguration {\n uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n // uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n // uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n // uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n // uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n\n /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n // uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;\n uint256 constant IS_FROZEN_START_BIT_POSITION = 57;\n // uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n // uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n // uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n\n uint256 constant MAX_VALID_LTV = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n // uint256 constant MAX_VALID_DECIMALS = 255;\n // uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;\n\n /**\n * @dev Sets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @param ltv the new ltv\n **/\n function setLtv(DataTypes.NFTVaultConfigurationMap memory self, uint256 ltv) internal pure {\n require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);\n\n self.data = (self.data & LTV_MASK) | ltv;\n }\n\n /**\n * @dev Gets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @return The loan to value\n **/\n function getLtv(DataTypes.NFTVaultConfigurationMap storage self) internal view returns (uint256) {\n return self.data & ~LTV_MASK;\n }\n\n /**\n * @dev Sets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @param threshold The new liquidation threshold\n **/\n function setLiquidationThreshold(DataTypes.NFTVaultConfigurationMap memory self, uint256 threshold)\n internal\n pure\n {\n require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);\n\n self.data =\n (self.data & LIQUIDATION_THRESHOLD_MASK) |\n (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @return The liquidation threshold\n **/\n function getLiquidationThreshold(DataTypes.NFTVaultConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @param bonus The new liquidation bonus\n **/\n function setLiquidationBonus(DataTypes.NFTVaultConfigurationMap memory self, uint256 bonus)\n internal\n pure\n {\n require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);\n\n self.data =\n (self.data & LIQUIDATION_BONUS_MASK) |\n (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @return The liquidation bonus\n **/\n function getLiquidationBonus(DataTypes.NFTVaultConfigurationMap storage self)\n internal\n view\n returns (uint256)\n {\n return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the active state of the reserve\n * @param self The reserve configuration\n * @param active The active state\n **/\n function setActive(DataTypes.NFTVaultConfigurationMap memory self, bool active) internal pure {\n self.data =\n (self.data & ACTIVE_MASK) |\n (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the active state of the reserve\n * @param self The reserve configuration\n * @return The active state\n **/\n function getActive(DataTypes.NFTVaultConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~ACTIVE_MASK) != 0;\n }\n\n /**\n * @dev Sets the frozen state of the reserve\n * @param self The reserve configuration\n * @param frozen The frozen state\n **/\n function setFrozen(DataTypes.NFTVaultConfigurationMap memory self, bool frozen) internal pure {\n self.data =\n (self.data & FROZEN_MASK) |\n (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the frozen state of the reserve\n * @param self The reserve configuration\n * @return The frozen state\n **/\n function getFrozen(DataTypes.NFTVaultConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~FROZEN_MASK) != 0;\n }\n\n /**\n * @dev Gets the configuration flags of the reserve\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlags(DataTypes.NFTVaultConfigurationMap storage self)\n internal\n view\n returns (\n bool,\n bool\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~ACTIVE_MASK) != 0,\n (dataLocal & ~FROZEN_MASK) != 0\n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParams(DataTypes.NFTVaultConfigurationMap storage self)\n internal\n view\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION \n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParamsMemory(DataTypes.NFTVaultConfigurationMap memory self)\n internal\n pure\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n return (\n self.data & ~LTV_MASK,\n (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the configuration flags of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlagsMemory(DataTypes.NFTVaultConfigurationMap memory self)\n internal\n pure\n returns (\n bool,\n bool\n )\n {\n return (\n (self.data & ~ACTIVE_MASK) != 0,\n (self.data & ~FROZEN_MASK) != 0\n );\n }\n}"
},
"contracts/protocol/libraries/configuration/UserConfiguration.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title UserConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the user configuration\n */\nlibrary UserConfiguration {\n uint256 internal constant BORROWING_MASK =\n 0x5555555555555555555555555555555555555555555555555555555555555555;\n\n /**\n * @dev Sets if the user is borrowing the reserve identified by reserveIndex\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @param borrowing True if the user is borrowing the reserve, false otherwise\n **/\n function setBorrowing(\n DataTypes.UserConfigurationMap storage self,\n uint256 reserveIndex,\n bool borrowing\n ) internal {\n require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n self.data =\n (self.data & ~(1 << (reserveIndex * 2))) |\n (uint256(borrowing ? 1 : 0) << (reserveIndex * 2));\n }\n\n /**\n * @dev Sets if the user is using as collateral the reserve identified by reserveIndex\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise\n **/\n function setUsingAsCollateral(\n DataTypes.UserConfigurationMap storage self,\n uint256 reserveIndex,\n bool usingAsCollateral\n ) internal {\n require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n self.data =\n (self.data & ~(1 << (reserveIndex * 2 + 1))) |\n (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1));\n }\n\n /**\n * @dev Sets if the user is using as collateral the nft vault identified by vaultIndex\n * @param self The configuration object\n * @param vaultIndex The index of the nft vault in the bitmap\n * @param usingAsCollateral True if the user is usin the nft vault as collateral, false otherwise\n **/\n function setUsingNFTVaultAsCollateral(\n DataTypes.UserConfigurationMap storage self,\n uint256 vaultIndex,\n bool usingAsCollateral\n ) internal {\n require(vaultIndex < 256, Errors.UL_INVALID_INDEX);\n self.nData =\n (self.nData & ~(1 << vaultIndex)) |\n (uint256(usingAsCollateral ? 1 : 0) << vaultIndex);\n }\n\n /**\n * @dev Used to validate if a user has been using the reserve for borrowing or as collateral\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise\n **/\n function isUsingAsCollateralOrBorrowing(\n DataTypes.UserConfigurationMap memory self,\n uint256 reserveIndex\n ) internal pure returns (bool) {\n require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n return (self.data >> (reserveIndex * 2)) & 3 != 0;\n }\n\n /**\n * @dev Used to validate if a user has been using the reserve for borrowing\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve for borrowing, false otherwise\n **/\n function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)\n internal\n pure\n returns (bool)\n {\n require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n return (self.data >> (reserveIndex * 2)) & 1 != 0;\n }\n\n /**\n * @dev Used to validate if a user has been using the reserve as collateral\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve as collateral, false otherwise\n **/\n function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)\n internal\n pure\n returns (bool)\n {\n require(reserveIndex < 128, Errors.UL_INVALID_INDEX);\n return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0;\n }\n\n /**\n * @dev Used to validate if a user has been using the nft vault as collateral\n * @param self The configuration object\n * @param vaultIndex The index of the nft vault in the bitmap\n * @return True if the user has been using a nft vault as collateral, false otherwise\n **/\n function isUsingNFTVaultAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 vaultIndex)\n internal\n pure\n returns (bool)\n {\n require(vaultIndex < 256, Errors.UL_INVALID_INDEX);\n return (self.nData >> vaultIndex) & 1 != 0;\n }\n\n /**\n * @dev Used to validate if a user has been borrowing from any reserve\n * @param self The configuration object\n * @return True if the user has been borrowing any reserve, false otherwise\n **/\n function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n return self.data & BORROWING_MASK != 0;\n }\n\n /**\n * @dev Used to validate if a user has not been using any reserve\n * @param self The configuration object\n * @return True if the user has been borrowing any reserve, false otherwise\n **/\n function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n return self.data == 0 && self.nData == 0;\n }\n}\n"
},
"contracts/protocol/libraries/types/DataTypes.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nlibrary DataTypes {\n // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n uint40 lastUpdateTimestamp;\n //tokens addresses\n address vTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint8 id;\n }\n\n struct NFTVaultData {\n NFTVaultConfigurationMap configuration;\n address nTokenAddress;\n address nftEligibility;\n uint32 id;\n uint40 expiration;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: Reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60-63: reserved\n //bit 64-79: reserve factor\n uint256 data;\n }\n\n struct NFTVaultConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. thresold\n //bit 32-47: Liq. bonus\n //bit 48-55: reserved\n //bit 56: Vault is active\n //bit 57: Vault is frozen\n uint256 data;\n }\n\n struct UserConfigurationMap {\n uint256 data;\n uint256 nData;\n }\n\n struct PoolReservesData {\n uint256 count;\n mapping(address => ReserveData) data;\n mapping(uint256 => address) list;\n }\n\n struct PoolNFTVaultsData {\n uint256 count;\n mapping(address => NFTVaultData) data;\n mapping(uint256 => address) list;\n }\n\n struct TimeLock {\n uint40 expiration;\n uint16 lockType;\n }\n\n enum InterestRateMode {NONE, STABLE, VARIABLE}\n}\n"
},
"contracts/protocol/lendingpool/LendingPoolStorage.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {NFTVaultConfiguration} from '../libraries/configuration/NFTVaultConfiguration.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {NFTVaultLogic} from '../libraries/logic/NFTVaultLogic.sol';\nimport {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';\nimport {INFTXEligibility} from '../../interfaces/INFTXEligibility.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\n\ncontract LendingPoolStorage {\n using ReserveLogic for DataTypes.ReserveData;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NFTVaultLogic for DataTypes.NFTVaultData;\n using NFTVaultConfiguration for DataTypes.NFTVaultConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n ILendingPoolAddressesProvider internal _addressesProvider;\n INFTXEligibility internal _nftEligibility;\n\n DataTypes.PoolReservesData internal _reserves;\n DataTypes.PoolNFTVaultsData internal _nftVaults;\n\n mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;\n\n bool internal _paused;\n\n uint256 internal _maxStableRateBorrowSizePercent;\n\n uint256 internal _flashLoanPremiumTotal;\n\n uint256 internal _maxNumberOfReserves;\n uint256 internal _maxNumberOfNFTVaults;\n}\n"
},
"contracts/dependencies/openzeppelin/contracts/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IScaledBalanceToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\ninterface IScaledBalanceToken {\n /**\n * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the\n * updated stored balance divided by the reserve's liquidity index at the moment of the update\n * @param user The user whose balance is calculated\n * @return The scaled balance of the user\n **/\n function scaledBalanceOf(address user) external view returns (uint256);\n\n /**\n * @dev Returns the scaled balance of the user and the scaled total supply.\n * @param user The address of the user\n * @return The scaled balance of the user\n * @return The scaled balance and the scaled total supply\n **/\n function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n\n /**\n * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)\n * @return The scaled total supply\n **/\n function scaledTotalSupply() external view returns (uint256);\n}\n"
},
"contracts/interfaces/IInitializableVToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {ILendingPool} from './ILendingPool.sol';\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\n\n/**\n * @title IInitializableVToken\n * @notice Interface for the initialize function on VToken\n * @author Aave\n **/\ninterface IInitializableVToken {\n /**\n * @dev Emitted when an vToken is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated lending pool\n * @param treasury The address of the treasury\n * @param incentivesController The address of the incentives controller for this vToken\n * @param vTokenDecimals the decimals of the underlying\n * @param vTokenName the name of the vToken\n * @param vTokenSymbol the symbol of the vToken\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 vTokenDecimals,\n string vTokenName,\n string vTokenSymbol,\n bytes params\n );\n\n /**\n * @dev Initializes the vToken\n * @param pool The address of the lending pool where this vToken will be used\n * @param treasury The address of the Aave treasury, receiving the fees on this vToken\n * @param underlyingAsset The address of the underlying asset of this vToken (E.g. WETH for aWETH)\n * @param incentivesController The smart contract managing potential incentives distribution\n * @param vTokenDecimals The decimals of the vToken, same as the underlying asset's\n * @param vTokenName The name of the vToken\n * @param vTokenSymbol The symbol of the vToken\n */\n function initialize(\n ILendingPool pool,\n address treasury,\n address underlyingAsset,\n IAaveIncentivesController incentivesController,\n uint8 vTokenDecimals,\n string calldata vTokenName,\n string calldata vTokenSymbol,\n bytes calldata params\n ) external;\n}\n"
},
"contracts/interfaces/IAaveIncentivesController.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\npragma experimental ABIEncoderV2;\n\ninterface IAaveIncentivesController {\n event RewardsAccrued(address indexed user, uint256 amount);\n\n event RewardsClaimed(address indexed user, address indexed to, uint256 amount);\n\n event RewardsClaimed(\n address indexed user,\n address indexed to,\n address indexed claimer,\n uint256 amount\n );\n\n event ClaimerSet(address indexed user, address indexed claimer);\n\n /*\n * @dev Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index, the emission per second and the last updated timestamp\n **/\n function getAssetData(address asset)\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n /*\n * LEGACY **************************\n * @dev Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index, the emission per second and the last updated timestamp\n **/\n function assets(address asset)\n external\n view\n returns (\n uint128,\n uint128,\n uint256\n );\n\n /**\n * @dev Whitelists an address to claim the rewards on behalf of another address\n * @param user The address of the user\n * @param claimer The address of the claimer\n */\n function setClaimer(address user, address claimer) external;\n\n /**\n * @dev Returns the whitelisted claimer for a certain address (0x0 if not set)\n * @param user The address of the user\n * @return The claimer address\n */\n function getClaimer(address user) external view returns (address);\n\n /**\n * @dev Configure assets for a certain rewards emission\n * @param assetsToConfig The assets to incentivize\n * @param emissionsPerSecond The emission for each asset\n */\n function configureAssets(address[] calldata assetsToConfig, uint256[] calldata emissionsPerSecond)\n external;\n\n /**\n * @dev Called by the corresponding asset on any update that affects the rewards distribution\n * @param asset The address of the user\n * @param userBalance The balance of the user of the asset in the lending pool\n * @param totalSupply The total supply of the asset in the lending pool\n **/\n function handleAction(\n address asset,\n uint256 userBalance,\n uint256 totalSupply\n ) external;\n\n /**\n * @dev Returns the total of rewards of an user, already accrued + not yet accrued\n * @param user The address of the user\n * @return The rewards\n **/\n function getRewardsBalance(address[] calldata assetsToCheck, address user)\n external\n view\n returns (uint256);\n\n /**\n * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards\n * @param amount Amount of rewards to claim\n * @param to Address that will be receiving the rewards\n * @return Rewards claimed\n **/\n function claimRewards(\n address[] calldata assetsToClaim,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must\n * be whitelisted via \"allowClaimOnBehalf\" function by the RewardsAdmin role manager\n * @param amount Amount of rewards to claim\n * @param user Address to check and claim rewards\n * @param to Address that will be receiving the rewards\n * @return Rewards claimed\n **/\n function claimRewardsOnBehalf(\n address[] calldata assetsToClaim,\n uint256 amount,\n address user,\n address to\n ) external returns (uint256);\n\n /**\n * @dev returns the unclaimed rewards of the user\n * @param user the address of the user\n * @return the unclaimed user rewards\n */\n function getUserUnclaimedRewards(address user) external view returns (uint256);\n\n /**\n * @dev returns the unclaimed rewards of the user\n * @param user the address of the user\n * @param asset The asset to incentivize\n * @return the user index for the asset\n */\n function getUserAssetData(address user, address asset) external view returns (uint256);\n\n /**\n * @dev for backward compatibility with previous implementation of the Incentives controller\n */\n function REWARD_TOKEN() external view returns (address);\n\n /**\n * @dev for backward compatibility with previous implementation of the Incentives controller\n */\n function PRECISION() external view returns (uint8);\n\n /**\n * @dev Gets the distribution end timestamp of the emissions\n */\n function DISTRIBUTION_END() external view returns (uint256);\n}\n"
},
"contracts/interfaces/ITimeLockableERC721.sol": {
"content": "pragma solidity 0.8.11;\n\nimport {IERC721} from '../dependencies/openzeppelin/contracts/IERC721.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\ninterface ITimeLockableERC721 is IERC721 {\n event TimeLocked(\n uint256 indexed tokenid,\n uint256 indexed lockType,\n uint40 indexed expirationTime\n );\n\n function lock(uint256 tokenid, uint16 lockType) external;\n\n function getUnlockTime(uint256 tokenId) external view returns(uint40 unlockTime);\n\n function getLockData(uint256 tokenId) external view returns(DataTypes.TimeLock memory lock);\n\n function unlockedBalanceOfBatch(address user, uint256[] memory tokenIds) external view returns(uint256[] memory amounts);\n\n function tokensAndLocksByAccount(address user) external view returns(uint256[] memory tokenIds, DataTypes.TimeLock[] memory locks);\n}"
},
"contracts/interfaces/IInitializableNToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {ILendingPool} from './ILendingPool.sol';\n\n/**\n * @title IInitializableVToken\n * @notice Interface for the initialize function on NToken\n * @author Aave\n **/\ninterface IInitializableNToken {\n /**\n * @dev Emitted when an vToken is initialized\n * @param underlyingAsset The address of the underlying NFT asset\n * @param pool The address of the associated lending pool\n * @param nTokenName the name of the NToken\n * @param nTokenSymbol the symbol of the NToken\n * @param params A set of encoded parameters for additional initialization\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n string nTokenName,\n string nTokenSymbol,\n string baseURI,\n bytes params\n );\n\n /**\n * @dev Initializes the nToken\n * @param pool The address of the lending pool where this nToken will be used\n * @param underlyingAsset The address of the underlying asset of this nToken\n * @param nTokenName The name of the nToken\n * @param nTokenSymbol The symbol of the nToken\n */\n function initialize(\n ILendingPool pool,\n address underlyingAsset,\n string calldata nTokenName,\n string calldata nTokenSymbol,\n string calldata baseURI,\n bytes calldata params\n ) external;\n}\n"
},
"contracts/dependencies/openzeppelin/contracts/IERC721Enumerable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"
},
"contracts/interfaces/IInitializableDebtToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {ILendingPool} from './ILendingPool.sol';\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\n\n/**\n * @title IInitializableDebtToken\n * @notice Interface for the initialize function common between debt tokens\n * @author Aave\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 lending pool\n * @param incentivesController The address of the incentives controller for this vToken\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 * @dev Initializes the debt token.\n * @param pool The address of the lending pool where this vToken will be used\n * @param underlyingAsset The address of the underlying asset of this vToken (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 */\n function initialize(\n ILendingPool 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"
},
"contracts/interfaces/IReserveInterestRateStrategy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\n/**\n * @title IReserveInterestRateStrategyInterface interface\n * @dev Interface for the calculation of the interest rates\n * @author Aave\n */\ninterface IReserveInterestRateStrategy {\n function baseVariableBorrowRate() external view returns (uint256);\n\n function getMaxVariableBorrowRate() external view returns (uint256);\n\n function calculateInterestRates(\n address reserve,\n uint256 availableLiquidity,\n uint256 totalStableDebt,\n uint256 totalVariableDebt,\n uint256 averageStableBorrowRate,\n uint256 reserveFactor\n )\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n function calculateInterestRates(\n address reserve,\n address vToken,\n uint256 liquidityAdded,\n uint256 liquidityTaken,\n uint256 totalStableDebt,\n uint256 totalVariableDebt,\n uint256 averageStableBorrowRate,\n uint256 reserveFactor\n )\n external\n view\n returns (\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate\n );\n}\n"
},
"contracts/protocol/libraries/math/MathUtils.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.11;\n\nimport {WadRayMath} from './WadRayMath.sol';\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\n function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)\n internal\n view\n returns (uint256)\n {\n //solium-disable-next-line\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\n\n return (rate * timeDifference / SECONDS_PER_YEAR + WadRayMath.ray());\n }\n\n /**\n * @dev Function to calculate the interest using a compounded interest rate formula\n * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n *\n * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n *\n * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions\n * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods\n *\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate compounded during the timeDelta, in ray\n **/\n function calculateCompoundedInterest(\n uint256 rate,\n uint40 lastUpdateTimestamp,\n uint256 currentTimestamp\n ) internal pure returns (uint256) {\n //solium-disable-next-line\n uint256 exp = currentTimestamp - uint256(lastUpdateTimestamp);\n\n if (exp == 0) {\n return WadRayMath.ray();\n }\n\n uint256 expMinusOne = exp - 1;\n\n uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n uint256 ratePerSecond = rate / SECONDS_PER_YEAR;\n\n uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);\n uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);\n\n uint256 secondTerm = exp * expMinusOne * basePowerTwo/ 2;\n uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree / 6;\n\n return WadRayMath.ray() + ratePerSecond * exp + 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 **/\n function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)\n internal\n view\n returns (uint256)\n {\n return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {
"contracts/protocol/libraries/logic/NFTVaultLogic.sol": {
"NFTVaultLogic": "0x37206a476adc1a3a820a35be414d6bf39fc474d3"
},
"contracts/protocol/libraries/logic/ReserveLogic.sol": {
"ReserveLogic": "0x8ba0b857ddc9602020ac95ad359717d94598e9de"
},
"contracts/protocol/libraries/logic/ValidationLogic.sol": {
"ValidationLogic": "0xb7e6fa926d1d027d36dd212981a98edfb66a34b8"
}
}
}
}