diff --git a/buidler.config.ts b/buidler.config.ts index ef5cf6f0..95ed92bd 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -16,17 +16,13 @@ usePlugin('@nomiclabs/buidler-etherscan'); usePlugin('buidler-gas-reporter'); const SKIP_LOAD = process.env.SKIP_LOAD === 'true'; -const DEFAULT_BLOCK_GAS_LIMIT = 12000000; +const DEFAULT_BLOCK_GAS_LIMIT = 12450000; const DEFAULT_GAS_PRICE = 10; const HARDFORK = 'istanbul'; const INFURA_KEY = process.env.INFURA_KEY || ''; const ETHERSCAN_KEY = process.env.ETHERSCAN_KEY || ''; const MNEMONIC_PATH = "m/44'/60'/0'/0"; -const MNEMONICS: {[network: string]: string} = { - [eEthereumNetwork.kovan]: process.env.MNEMONIC || '', - [eEthereumNetwork.ropsten]: process.env.MNEMONIC || '', - [eEthereumNetwork.main]: process.env.MNEMONIC || '', -}; +const MNEMONIC = process.env.MNEMONIC || ''; // Prevent to load scripts before compilation and typechain if (!SKIP_LOAD) { @@ -46,7 +42,7 @@ const getCommonNetworkConfig = (networkName: eEthereumNetwork, networkId: number gasMultiplier: DEFAULT_GAS_PRICE, chainId: networkId, accounts: { - mnemonic: MNEMONICS[networkName], + mnemonic: MNEMONIC, path: MNEMONIC_PATH, initialIndex: 0, count: 20, diff --git a/contracts/configuration/LendingPoolAddressesProvider.sol b/contracts/configuration/LendingPoolAddressesProvider.sol index 15b37635..38aa1280 100644 --- a/contracts/configuration/LendingPoolAddressesProvider.sol +++ b/contracts/configuration/LendingPoolAddressesProvider.sol @@ -19,16 +19,11 @@ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; - bytes32 private constant LENDING_POOL_CORE = 'LENDING_POOL_CORE'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant AAVE_ADMIN = 'AAVE_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; - bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = 'FLASHLOAN_PROVIDER'; - bytes32 private constant DATA_PROVIDER = 'DATA_PROVIDER'; - bytes32 private constant ETHEREUM_ADDRESS = 'ETHEREUM_ADDRESS'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; - bytes32 private constant WALLET_BALANCE_PROVIDER = 'WALLET_BALANCE_PROVIDER'; /** * @dev Sets an address for an id, allowing to cover it or not with a proxy diff --git a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol index bf15ef3d..4be6e034 100644 --- a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol +++ b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol @@ -56,7 +56,7 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP * @param provider the pool address to be registered **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { - require(id != 0, Errors.INVALID_ADDRESSES_PROVIDER_ID); + require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); @@ -68,7 +68,7 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP * @param provider the pool address to be unregistered **/ function unregisterAddressesProvider(address provider) external override onlyOwner { - require(_addressesProviders[provider] > 0, Errors.PROVIDER_NOT_REGISTERED); + require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } diff --git a/contracts/deployments/ATokensAndRatesHelper.sol b/contracts/deployments/ATokensAndRatesHelper.sol index 769b98fc..f39cdaa2 100644 --- a/contracts/deployments/ATokensAndRatesHelper.sol +++ b/contracts/deployments/ATokensAndRatesHelper.sol @@ -97,7 +97,7 @@ contract ATokensAndRatesHelper is Ownable { require(liquidationBonuses.length == tokens.length); for (uint256 i = 0; i < tokens.length; i++) { - LendingPoolConfigurator(poolConfigurator).enableReserveAsCollateral( + LendingPoolConfigurator(poolConfigurator).configureReserveAsCollateral( tokens[i], baseLTVs[i], liquidationThresholds[i], diff --git a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol index 784d0fa3..af9e384f 100644 --- a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol +++ b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol @@ -12,6 +12,7 @@ interface IFlashLoanReceiver { address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, + address initiator, bytes calldata params ) external returns (bool); } diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 450def2d..c6da3c32 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -27,16 +27,17 @@ interface ILendingPool { * @dev emitted during a withdraw action. * @param reserve the address of the reserve * @param user the address of the user + * @param to address that will receive the underlying * @param amount the amount to be withdrawn **/ - event Withdraw(address indexed reserve, address indexed user, uint256 amount); + event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); event BorrowAllowanceDelegated( - address indexed asset, address indexed fromUser, address indexed toUser, - uint256 interestRateMode, - uint256 amount + address[] assets, + uint256[] interestRateModes, + uint256[] amounts ); /** * @dev emitted on borrow @@ -74,7 +75,7 @@ interface ILendingPool { * @param reserve the address of the reserve * @param user the address of the user executing the swap **/ - event Swap(address indexed reserve, address indexed user); + event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev emitted when a user enables a reserve as collateral @@ -99,20 +100,18 @@ interface ILendingPool { /** * @dev emitted when a flashloan is executed * @param target the address of the flashLoanReceiver - * @param mode Type of the debt to open if the flash loan is not returned. 0 -> Don't open any debt, just revert, 1 -> stable, 2 -> variable - * @param onBehalfOf the address incurring the debt, if borrow mode is not 0 - * @param assets the address of the assets being flashborrowed - * @param amounts the amount requested - * @param premiums the total fee on the amount + * @param initiator the address initiating the flash loan + * @param asset the address of the asset being flashborrowed + * @param amount the amount requested + * @param premium the total fee on the amount * @param referralCode the referral code of the caller **/ event FlashLoan( address indexed target, - uint256 mode, - address indexed onBehalfOf, - address[] assets, - uint256[] amounts, - uint256[] premiums, + address indexed initiator, + address indexed asset, + uint256 amount, + uint256 premium, uint16 referralCode ); @@ -188,21 +187,26 @@ interface ILendingPool { * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed + * @param to address that will receive the underlying **/ - function withdraw(address reserve, uint256 amount) external; + function withdraw( + address reserve, + uint256 amount, + address to + ) external; /** - * @dev Sets allowance to borrow on a certain type of debt asset for a certain user address - * @param asset The underlying asset of the debt token + * @dev Sets allowance to borrow on a certain type of debt assets for a certain user address + * @param assets The underlying asset of each debt token * @param user The user to give allowance to - * @param interestRateMode Type of debt: 1 for stable, 2 for variable - * @param amount Allowance amount to borrow + * @param interestRateModes Types of debt: 1 for stable, 2 for variable + * @param amounts Allowance amounts to borrow **/ function delegateBorrowAllowance( - address asset, + address[] calldata assets, address user, - uint256 interestRateMode, - uint256 amount + uint256[] calldata interestRateModes, + uint256[] calldata amounts ) external; function getBorrowAllowance( @@ -289,7 +293,7 @@ interface ILendingPool { * @param receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param assets the address of the principal reserve * @param amounts the amount requested for this flashloan - * @param mode the flashloan mode + * @param modes the flashloan borrow modes * @param params a bytes array to be sent to the flashloan executor * @param referralCode the referral code of the caller **/ @@ -297,7 +301,7 @@ interface ILendingPool { address receiver, address[] calldata assets, uint256[] calldata amounts, - uint256 mode, + uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode diff --git a/contracts/interfaces/ISwapAdapter.sol b/contracts/interfaces/ISwapAdapter.sol deleted file mode 100644 index ed91f95f..00000000 --- a/contracts/interfaces/ISwapAdapter.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity ^0.6.8; - -interface ISwapAdapter { - /** - * @dev Swaps an `amountToSwap` of an asset to another, approving a `fundsDestination` to pull the funds - * @param assetToSwapFrom Origin asset - * @param assetToSwapTo Destination asset - * @param amountToSwap How much `assetToSwapFrom` needs to be swapped - * @param fundsDestination Address that will be pulling the swapped funds - * @param params Additional variadic field to include extra params - */ - function executeOperation( - address assetToSwapFrom, - address assetToSwapTo, - uint256 amountToSwap, - address fundsDestination, - bytes calldata params - ) external; -} diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 539b6ac6..23bf3e94 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -20,7 +20,6 @@ import {IStableDebtToken} from '../tokenization/interfaces/IStableDebtToken.sol' import {IVariableDebtToken} from '../tokenization/interfaces/IVariableDebtToken.sol'; import {DebtTokenBase} from '../tokenization/base/DebtTokenBase.sol'; import {IFlashLoanReceiver} from '../flashloan/interfaces/IFlashLoanReceiver.sol'; -import {ISwapAdapter} from '../interfaces/ISwapAdapter.sol'; import {LendingPoolCollateralManager} from './LendingPoolCollateralManager.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; @@ -53,7 +52,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, - Errors.CALLER_NOT_LENDING_POOL_CONFIGURATOR + Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } @@ -65,7 +64,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * - The contract must not be paused. */ function _whenNotPaused() internal view { - require(!_paused, Errors.IS_PAUSED); + require(!_paused, Errors.LP_IS_PAUSED); } function getRevision() internal override pure returns (uint256) { @@ -120,8 +119,13 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @dev withdraws the _reserves of user. * @param asset the address of the reserve * @param amount the underlying amount to be redeemed + * @param to address that will receive the underlying **/ - function withdraw(address asset, uint256 amount) external override { + function withdraw( + address asset, + uint256 amount, + address to + ) external override { _whenNotPaused(); ReserveLogic.ReserveData storage reserve = _reserves[asset]; @@ -155,9 +159,9 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); } - IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw, reserve.liquidityIndex); + IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); - emit Withdraw(asset, msg.sender, amountToWithdraw); + emit Withdraw(asset, msg.sender, to, amountToWithdraw); } /** @@ -179,23 +183,32 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage } /** - * @dev Sets allowance to borrow on a certain type of debt asset for a certain user address - * @param asset The underlying asset of the debt token + * @dev Sets allowance to borrow on a certain type of debt assets for a certain user address + * @param assets The underlying asset of each debt token * @param user The user to give allowance to - * @param interestRateMode Type of debt: 1 for stable, 2 for variable - * @param amount Allowance amount to borrow + * @param interestRateModes Types of debt: 1 for stable, 2 for variable + * @param amounts Allowance amounts to borrow **/ function delegateBorrowAllowance( - address asset, + address[] calldata assets, address user, - uint256 interestRateMode, - uint256 amount + uint256[] calldata interestRateModes, + uint256[] calldata amounts ) external override { _whenNotPaused(); - address debtToken = _reserves[asset].getDebtTokenAddress(interestRateMode); - _borrowAllowance[debtToken][msg.sender][user] = amount; - emit BorrowAllowanceDelegated(asset, msg.sender, user, interestRateMode, amount); + uint256 countAssets = assets.length; + require( + countAssets == interestRateModes.length && countAssets == amounts.length, + Errors.LP_INCONSISTENT_PARAMS_LENGTH + ); + + for (uint256 i = 0; i < countAssets; i++) { + address debtToken = _reserves[assets[i]].getDebtTokenAddress(interestRateModes[i]); + _borrowAllowance[debtToken][msg.sender][user] = amounts[i]; + } + + emit BorrowAllowanceDelegated(msg.sender, user, assets, interestRateModes, amounts); } /** @@ -223,7 +236,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage _borrowAllowance[debtToken][onBehalfOf][msg .sender] = _borrowAllowance[debtToken][onBehalfOf][msg.sender].sub( amount, - Errors.BORROW_ALLOWANCE_ARE_NOT_ENOUGH + Errors.LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH ); } _executeBorrow( @@ -352,7 +365,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - emit Swap(asset, msg.sender); + emit Swap(asset, msg.sender, rateMode); } /** @@ -398,7 +411,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), - Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET + Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); reserve.updateState(); @@ -473,7 +486,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage receiveAToken ) ); - require(success, Errors.LIQUIDATION_CALL_FAILED); + require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); @@ -486,13 +499,13 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; - ReserveLogic.InterestRateMode debtMode; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; + address debtToken; } /** @@ -502,7 +515,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param assets The addresss of the assets being flashborrowed * @param amounts The amounts requested for this flashloan for each asset - * @param mode Type of the debt to open if the flash loan is not returned. 0 -> Don't open any debt, just revert, 1 -> stable, 2 -> variable + * @param modes Types of the debt to open if the flash loan is not returned. 0 -> Don't open any debt, just revert, 1 -> stable, 2 -> variable * @param onBehalfOf If mode is not 0, then the address to take the debt onBehalfOf. The onBehalfOf address must already have approved `msg.sender` to incur the debt on their behalf. * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Referral code of the flash loan @@ -511,7 +524,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage address receiverAddress, address[] calldata assets, uint256[] calldata amounts, - uint256 mode, + uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode @@ -520,13 +533,12 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage FlashLoanLocalVars memory vars; - ValidationLogic.validateFlashloan(assets, amounts, mode); + ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); - vars.debtMode = ReserveLogic.InterestRateMode(mode); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; @@ -539,8 +551,8 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage //execute action of the receiver require( - vars.receiver.executeOperation(assets, amounts, premiums, params), - Errors.INVALID_FLASH_LOAN_EXECUTOR_RETURN + vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), + Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { @@ -548,10 +560,9 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; - vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); - if (vars.debtMode == ReserveLogic.InterestRateMode.NONE) { + if (ReserveLogic.InterestRateMode(modes[vars.i]) == ReserveLogic.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), @@ -571,13 +582,11 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ); } else { if (msg.sender != onBehalfOf) { - address debtToken = _reserves[vars.currentAsset].getDebtTokenAddress(mode); + vars.debtToken = _reserves[vars.currentAsset].getDebtTokenAddress(modes[vars.i]); - _borrowAllowance[debtToken][onBehalfOf][msg - .sender] = _borrowAllowance[debtToken][onBehalfOf][msg.sender].sub( - vars.currentAmount, - Errors.BORROW_ALLOWANCE_ARE_NOT_ENOUGH - ); + _borrowAllowance[vars.debtToken][onBehalfOf][msg.sender] = _borrowAllowance[vars + .debtToken][onBehalfOf][msg.sender] + .sub(vars.currentAmount, Errors.LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH); } //if the user didn't choose to return the funds, the system checks if there @@ -588,14 +597,21 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage msg.sender, onBehalfOf, vars.currentAmount, - mode, + modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } - emit FlashLoan(receiverAddress, mode, onBehalfOf, assets, amounts, premiums, referralCode); + emit FlashLoan( + receiverAddress, + msg.sender, + vars.currentAsset, + vars.currentAmount, + vars.currentPremium, + referralCode + ); } } @@ -691,7 +707,13 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @param asset the address of the reserve * @return the reserve normalized income */ - function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + function getReserveNormalizedIncome(address asset) + external + virtual + override + view + returns (uint256) + { return _reserves[asset].getNormalizedIncome(); } @@ -754,7 +776,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ) external override { _whenNotPaused(); - require(msg.sender == _reserves[asset].aTokenAddress, Errors.CALLER_MUST_BE_AN_ATOKEN); + require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, @@ -875,6 +897,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ); ValidationLogic.validateBorrow( + vars.asset, reserve, vars.onBehalfOf, vars.amount, @@ -888,34 +911,34 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage oracle ); - uint256 reserveId = reserve.id; - if (!userConfig.isBorrowing(reserveId)) { - userConfig.setBorrowing(reserveId, true); - } - reserve.updateState(); //caching the current stable borrow rate uint256 currentStableRate = 0; + bool isFirstBorrowing = false; if ( ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE ) { currentStableRate = reserve.currentStableBorrowRate; - IStableDebtToken(reserve.stableDebtTokenAddress).mint( + isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.onBehalfOf, vars.amount, currentStableRate ); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint( + isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } + if (isFirstBorrowing) { + userConfig.setBorrowing(reserve.id, true); + } + reserve.updateInterestRates( vars.asset, vars.aTokenAddress, @@ -946,7 +969,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; - require(reservesCount < MAX_NUMBER_RESERVES, Errors.NO_MORE_RESERVES_ALLOWED); + require(reservesCount < MAX_NUMBER_RESERVES, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; diff --git a/contracts/lendingpool/LendingPoolCollateralManager.sol b/contracts/lendingpool/LendingPoolCollateralManager.sol index 16abdd10..993f7fe5 100644 --- a/contracts/lendingpool/LendingPoolCollateralManager.sol +++ b/contracts/lendingpool/LendingPoolCollateralManager.sol @@ -15,7 +15,6 @@ import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; -import {ISwapAdapter} from '../interfaces/ISwapAdapter.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; @@ -186,7 +185,7 @@ contract LendingPoolCollateralManager is VersionedInitializable, LendingPoolStor if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), - Errors.NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE + Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } @@ -264,7 +263,7 @@ contract LendingPoolCollateralManager is VersionedInitializable, LendingPoolStor receiveAToken ); - return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.NO_ERRORS); + return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index c3da634c..8f9c28dd 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -13,6 +13,7 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {ITokenConfiguration} from '../tokenization/interfaces/ITokenConfiguration.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; +import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; /** @@ -47,7 +48,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param asset the address of the reserve * @param stableRateEnabled true if stable rate borrowing is enabled, false otherwise **/ - event BorrowingEnabledOnReserve(address asset, bool stableRateEnabled); + event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev emitted when borrowing is disabled on a reserve @@ -56,25 +57,19 @@ contract LendingPoolConfigurator is VersionedInitializable { event BorrowingDisabledOnReserve(address indexed asset); /** - * @dev emitted when a reserve is enabled as collateral. + * @dev emitted when a a reserve collateralization risk parameters are updated. * @param asset the address of the reserve * @param ltv the loan to value of the asset when used as collateral * @param liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus the bonus liquidators receive to liquidate this asset **/ - event ReserveEnabledAsCollateral( + event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); - /** - * @dev emitted when a reserve is disabled as collateral - * @param asset the address of the reserve - **/ - event ReserveDisabledAsCollateral(address indexed asset); - /** * @dev emitted when stable rate borrowing is enabled on a reserve * @param asset the address of the reserve @@ -100,58 +95,58 @@ contract LendingPoolConfigurator is VersionedInitializable { event ReserveDeactivated(address indexed asset); /** - * @dev emitted when a reserve is freezed + * @dev emitted when a reserve is frozen * @param asset the address of the reserve **/ - event ReserveFreezed(address indexed asset); + event ReserveFrozen(address indexed asset); /** - * @dev emitted when a reserve is unfreezed + * @dev emitted when a reserve is unfrozen * @param asset the address of the reserve **/ - event ReserveUnfreezed(address indexed asset); + event ReserveUnfrozen(address indexed asset); /** * @dev emitted when a reserve loan to value is updated * @param asset the address of the reserve * @param ltv the new value for the loan to value **/ - event ReserveBaseLtvChanged(address asset, uint256 ltv); + event ReserveBaseLtvChanged(address indexed asset, uint256 ltv); /** * @dev emitted when a reserve factor is updated * @param asset the address of the reserve * @param factor the new reserve factor **/ - event ReserveFactorChanged(address asset, uint256 factor); + event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev emitted when a reserve liquidation threshold is updated * @param asset the address of the reserve * @param threshold the new value for the liquidation threshold **/ - event ReserveLiquidationThresholdChanged(address asset, uint256 threshold); + event ReserveLiquidationThresholdChanged(address indexed asset, uint256 threshold); /** * @dev emitted when a reserve liquidation bonus is updated * @param asset the address of the reserve * @param bonus the new value for the liquidation bonus **/ - event ReserveLiquidationBonusChanged(address asset, uint256 bonus); + event ReserveLiquidationBonusChanged(address indexed asset, uint256 bonus); /** * @dev emitted when the reserve decimals are updated * @param asset the address of the reserve * @param decimals the new decimals **/ - event ReserveDecimalsChanged(address asset, uint256 decimals); + event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev emitted when a reserve interest strategy contract is updated * @param asset the address of the reserve * @param strategy the new address of the interest strategy contract **/ - event ReserveInterestRateStrategyChanged(address asset, address strategy); + event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev emitted when an aToken implementation is upgraded @@ -159,7 +154,11 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the aToken proxy address * @param implementation the new aToken implementation **/ - event ATokenUpgraded(address asset, address proxy, address implementation); + event ATokenUpgraded( + address indexed asset, + address indexed proxy, + address indexed implementation + ); /** * @dev emitted when the implementation of a stable debt token is upgraded @@ -167,7 +166,11 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the stable debt token proxy address * @param implementation the new aToken implementation **/ - event StableDebtTokenUpgraded(address asset, address proxy, address implementation); + event StableDebtTokenUpgraded( + address indexed asset, + address indexed proxy, + address indexed implementation + ); /** * @dev emitted when the implementation of a variable debt token is upgraded @@ -175,7 +178,11 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the variable debt token proxy address * @param implementation the new aToken implementation **/ - event VariableDebtTokenUpgraded(address asset, address proxy, address implementation); + event VariableDebtTokenUpgraded( + address indexed asset, + address indexed proxy, + address indexed implementation + ); ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; @@ -184,7 +191,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @dev only the lending pool manager can call functions affected by this modifier **/ modifier onlyAaveAdmin { - require(addressesProvider.getAaveAdmin() == msg.sender, Errors.CALLER_NOT_AAVE_ADMIN); + require(addressesProvider.getAaveAdmin() == msg.sender, Errors.LPC_CALLER_NOT_AAVE_ADMIN); _; } @@ -218,23 +225,23 @@ contract LendingPoolConfigurator is VersionedInitializable { require( address(pool) == ITokenConfiguration(aTokenImpl).POOL(), - Errors.INVALID_ATOKEN_POOL_ADDRESS + Errors.LPC_INVALID_ATOKEN_POOL_ADDRESS ); require( address(pool) == ITokenConfiguration(stableDebtTokenImpl).POOL(), - Errors.INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS + Errors.LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS ); require( address(pool) == ITokenConfiguration(variableDebtTokenImpl).POOL(), - Errors.INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS + Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS ); require( asset == ITokenConfiguration(stableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(), - Errors.INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS + Errors.LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS ); require( asset == ITokenConfiguration(variableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(), - Errors.INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS + Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS ); address aTokenProxyAddress = _initTokenWithProxy(aTokenImpl, underlyingAssetDecimals); @@ -347,13 +354,13 @@ contract LendingPoolConfigurator is VersionedInitializable { } /** - * @dev enables a reserve to be used as collateral + * @dev configures the reserve collateralization parameters * @param asset the address of the reserve * @param ltv the loan to value of the asset when used as collateral * @param liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus the bonus liquidators receive to liquidate this asset **/ - function enableReserveAsCollateral( + function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, @@ -361,27 +368,33 @@ contract LendingPoolConfigurator is VersionedInitializable { ) external onlyAaveAdmin { ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); + //validation of the parameters: the LTV can + //only be lower or equal than the liquidation threshold + //(otherwise a loan against the asset would cause instantaneous liquidation) + require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); + + if (liquidationThreshold != 0) { + //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less + //collateral than needed to cover the debt + require( + liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, + Errors.LPC_INVALID_CONFIGURATION + ); + } else { + require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); + //if the liquidation threshold is being set to 0, + // the reserve is being disabled as collateral. To do so, + //we need to ensure no liquidity is deposited + _checkNoLiquidity(asset); + } + currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); - emit ReserveEnabledAsCollateral(asset, ltv, liquidationThreshold, liquidationBonus); - } - - /** - * @dev disables a reserve as collateral - * @param asset the address of the reserve - **/ - function disableReserveAsCollateral(address asset) external onlyAaveAdmin { - ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); - - currentConfig.setLtv(0); - - pool.setConfiguration(asset, currentConfig.data); - - emit ReserveDisabledAsCollateral(asset); + emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** @@ -431,14 +444,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param asset the address of the reserve **/ function deactivateReserve(address asset) external onlyAaveAdmin { - ReserveLogic.ReserveData memory reserveData = pool.getReserveData(asset); - - uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); - - require( - availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, - Errors.RESERVE_LIQUIDITY_NOT_0 - ); + _checkNoLiquidity(asset); ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); @@ -450,7 +456,7 @@ contract LendingPoolConfigurator is VersionedInitializable { } /** - * @dev freezes a reserve. A freezed reserve doesn't accept any new deposit, borrow or rate swap, but can accept repayments, liquidations, rate rebalances and redeems + * @dev freezes a reserve. A frozen reserve doesn't accept any new deposit, borrow or rate swap, but can accept repayments, liquidations, rate rebalances and redeems * @param asset the address of the reserve **/ function freezeReserve(address asset) external onlyAaveAdmin { @@ -460,7 +466,7 @@ contract LendingPoolConfigurator is VersionedInitializable { pool.setConfiguration(asset, currentConfig.data); - emit ReserveFreezed(asset); + emit ReserveFrozen(asset); } /** @@ -474,7 +480,7 @@ contract LendingPoolConfigurator is VersionedInitializable { pool.setConfiguration(asset, currentConfig.data); - emit ReserveUnfreezed(asset); + emit ReserveUnfrozen(asset); } /** @@ -617,4 +623,15 @@ contract LendingPoolConfigurator is VersionedInitializable { function setPoolPause(bool val) external onlyAaveAdmin { pool.setPause(val); } + + function _checkNoLiquidity(address asset) internal view { + ReserveLogic.ReserveData memory reserveData = pool.getReserveData(asset); + + uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); + + require( + availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, + Errors.LPC_RESERVE_LIQUIDITY_NOT_0 + ); + } } diff --git a/contracts/lendingpool/LendingPoolStorage.sol b/contracts/lendingpool/LendingPoolStorage.sol index 1def3b12..ceeadd39 100644 --- a/contracts/lendingpool/LendingPoolStorage.sol +++ b/contracts/lendingpool/LendingPoolStorage.sol @@ -23,6 +23,5 @@ contract LendingPoolStorage { uint256 internal _reservesCount; - bool internal _flashLiquidationLocked; bool internal _paused; } diff --git a/contracts/libraries/configuration/ReserveConfiguration.sol b/contracts/libraries/configuration/ReserveConfiguration.sol index ce4f722a..7951d91a 100644 --- a/contracts/libraries/configuration/ReserveConfiguration.sol +++ b/contracts/libraries/configuration/ReserveConfiguration.sol @@ -55,7 +55,7 @@ library ReserveConfiguration { * @param ltv the new ltv **/ function setLtv(ReserveConfiguration.Map memory self, uint256 ltv) internal pure { - require(ltv <= MAX_VALID_LTV, Errors.INVALID_LTV); + require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } @@ -78,7 +78,7 @@ library ReserveConfiguration { internal pure { - require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD); + require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | @@ -104,7 +104,7 @@ library ReserveConfiguration { * @param bonus the new liquidation bonus **/ function setLiquidationBonus(ReserveConfiguration.Map memory self, uint256 bonus) internal pure { - require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS); + require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | @@ -130,7 +130,7 @@ library ReserveConfiguration { * @param decimals the decimals **/ function setDecimals(ReserveConfiguration.Map memory self, uint256 decimals) internal pure { - require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS); + require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } @@ -240,7 +240,7 @@ library ReserveConfiguration { internal pure { - require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.INVALID_RESERVE_FACTOR); + require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | @@ -259,7 +259,7 @@ library ReserveConfiguration { /** * @dev gets the configuration flags of the reserve * @param self the reserve configuration - * @return the state flags representing active, freezed, borrowing enabled, stableRateBorrowing enabled + * @return the state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(ReserveConfiguration.Map storage self) internal @@ -336,7 +336,7 @@ library ReserveConfiguration { /** * @dev gets the configuration flags of the reserve from a memory object * @param self the reserve configuration - * @return the state flags representing active, freezed, borrowing enabled, stableRateBorrowing enabled + * @return the state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(ReserveConfiguration.Map memory self) internal diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 2c5a36db..3b37e91a 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -5,98 +5,93 @@ pragma solidity ^0.6.8; * @title Errors library * @author Aave * @notice Implements error messages. + * @dev Error messages prefix glossary: + * - VL = ValidationLogic + * - MATH = Math libraries + * - AT = aToken or DebtTokens + * - LP = LendingPool + * - LPAPR = LendingPoolAddressesProviderRegistry + * - LPC = LendingPoolConfiguration + * - RL = ReserveLogic + * - LPCM = LendingPoolCollateralManager + * - P = Pausable */ library Errors { - // require error messages - ValidationLogic - string public constant AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' - string public constant NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' - string public constant NO_UNFREEZED_RESERVE = '3'; // 'Action requires an unfreezed reserve' - string public constant CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' - string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' - string public constant TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' - string public constant BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' - string public constant INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' - string public constant COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' - string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' - string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' - string public constant STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled - string public constant CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed - string public constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode - string public constant 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' - string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' - string public constant NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' - string public constant NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' - string public constant UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' - string public constant DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' - - // require error messages - LendingPool - string public constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' - string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' - string public constant LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' - string public constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' - string public constant REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' - string public constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' - string public constant CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The actual balance of the protocol is inconsistent' - string public constant INVALID_FLASHLOAN_MODE = '43'; //Invalid flashloan mode selected - string public constant BORROW_ALLOWANCE_ARE_NOT_ENOUGH = '54'; // User borrows on behalf, but allowance are too small - string public constant REENTRANCY_NOT_ALLOWED = '57'; - string public constant FAILED_REPAY_WITH_COLLATERAL = '53'; - string public constant FAILED_COLLATERAL_SWAP = '55'; - string public constant INVALID_EQUAL_ASSETS_TO_SWAP = '56'; - string public constant NO_MORE_RESERVES_ALLOWED = '59'; - string public constant INVALID_FLASH_LOAN_EXECUTOR_RETURN = '60'; - string public constant INCONSISTENT_FLASHLOAN_PARAMS = '69'; - string public constant CALLER_MUST_BE_AN_ATOKEN = '76'; - - // require error messages - aToken - DebtTokens - string public constant CALLER_MUST_BE_LENDING_POOL = '28'; // 'The caller of this function must be a lending pool' - string public constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' - string public constant TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' - string public constant INVALID_MINT_AMOUNT = '61'; //invalid amount to mint - string public constant INVALID_BURN_AMOUNT = '62'; //invalid amount to burn - - // require error messages - ReserveLogic - string public constant RESERVE_ALREADY_INITIALIZED = '34'; // 'Reserve has already been initialized' - string public constant LIQUIDITY_INDEX_OVERFLOW = '47'; // Liquidity index overflows uint128 - string public constant VARIABLE_BORROW_INDEX_OVERFLOW = '48'; // Variable borrow index overflows uint128 - string public constant LIQUIDITY_RATE_OVERFLOW = '49'; // Liquidity rate overflows uint128 - string public constant VARIABLE_BORROW_RATE_OVERFLOW = '50'; // Variable borrow rate overflows uint128 - string public constant STABLE_BORROW_RATE_OVERFLOW = '51'; // Stable borrow rate overflows uint128 - - //require error messages - LendingPoolConfiguration - string public constant CALLER_NOT_AAVE_ADMIN = '35'; // 'The caller must be the aave admin' - string public constant RESERVE_LIQUIDITY_NOT_0 = '36'; // 'The liquidity of the reserve needs to be 0' - string public constant INVALID_ATOKEN_POOL_ADDRESS = '63'; // the lending pool in the aToken implementation is not configured correctly - string public constant INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '64'; // the lending pool in the stable debt token implementation is not configured correctly - string public constant INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '65'; // the lending pool in the variable debt token implementation is not configured correctly - string public constant INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '66'; // the underlying asset in the stable debt token implementation is not configured correctly - string public constant INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '67'; // the underlying asset in the variable debt token implementation is not configured correctly - - //require error messages - LendingPoolAddressesProviderRegistry - string public constant PROVIDER_NOT_REGISTERED = '37'; // 'Provider is not registered' - string public constant INVALID_ADDRESSES_PROVIDER_ID = '68'; // the addresses provider id needs to be greater than 0 - - //return error messages - LendingPoolCollateralManager - string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '38'; // 'Health factor is not below the threshold' - string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '39'; // 'The collateral chosen cannot be liquidated' - string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '40'; // 'User did not borrow the specified currency' - string public constant NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '41'; // "There isn't enough liquidity available to liquidate" - string public constant NO_ERRORS = '42'; // 'No errors' - - //require error messages - Math libraries - string public constant MULTIPLICATION_OVERFLOW = '44'; - string public constant ADDITION_OVERFLOW = '45'; - string public constant DIVISION_BY_ZERO = '46'; - - // pausable error message - string public constant IS_PAUSED = '58'; // 'Pool is paused' - - // Reserve configuration - string public constant INVALID_LTV = '70'; - string public constant INVALID_LIQ_THRESHOLD = '71'; - string public constant INVALID_LIQ_BONUS = '72'; - string public constant INVALID_DECIMALS = '73'; - string public constant INVALID_RESERVE_FACTOR = '74'; + string public constant VL_AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' + string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' + string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' + string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' + string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' + string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' + string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' + string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' + string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' + string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' + string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' + string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled + string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed + 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 + 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' + 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' + string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' + string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' + string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' + string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' + string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' + string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' + string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' + string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' + string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' + string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' + string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The actual balance of the protocol is inconsistent' + string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; + string public constant AT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' + string public constant AT_CANNOT_GIVE_ALLVWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' + string public constant AT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' + string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' + string public constant LPC_CALLER_NOT_AAVE_ADMIN = '33'; // 'The caller must be the aave admin' + string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' + string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' + string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' + string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' + string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' + string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' + string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" + string public constant LPCM_NO_ERRORS = '46'; // 'No errors' + string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected + string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; + string public constant MATH_ADDITION_OVERFLOW = '49'; + string public constant MATH_DIVISION_BY_ZERO = '50'; + string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 + string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 + string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 + string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 + string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 + string public constant AT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint + string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; + string public constant AT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn + string public constant LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small + string public constant LP_FAILED_COLLATERAL_SWAP = '60'; + string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; + string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; + string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; + string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' + string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; + string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; + string public constant RC_INVALID_LTV = '67'; + string public constant RC_INVALID_LIQ_THRESHOLD = '68'; + string public constant RC_INVALID_LIQ_BONUS = '69'; + string public constant RC_INVALID_DECIMALS = '70'; + string public constant RC_INVALID_RESERVE_FACTOR = '71'; + string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; + string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; + string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; enum CollateralManagerErrors { NO_ERROR, @@ -108,6 +103,6 @@ library Errors { NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, - NO_UNFREEZED_RESERVE + FROZEN_RESERVE } } diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 1e4cba4c..f3d13628 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -133,7 +133,7 @@ library ReserveLogic { require( ReserveLogic.InterestRateMode.STABLE == ReserveLogic.InterestRateMode(interestRateMode) || ReserveLogic.InterestRateMode.VARIABLE == ReserveLogic.InterestRateMode(interestRateMode), - Errors.INVALID_INTEREST_RATE_MODE_SELECTED + Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); return ReserveLogic.InterestRateMode.STABLE == ReserveLogic.InterestRateMode(interestRateMode) @@ -188,7 +188,7 @@ library ReserveLogic { uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); - require(result < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); + require(result < (1 << 128), Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } @@ -206,7 +206,7 @@ library ReserveLogic { address variableDebtTokenAddress, address interestRateStrategyAddress ) external { - require(reserve.aTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED); + require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); if (reserve.liquidityIndex == 0) { //if the reserve has not been initialized yet reserve.liquidityIndex = uint128(WadRayMath.ray()); @@ -395,7 +395,7 @@ library ReserveLogic { timestamp ); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); - require(newLiquidityIndex < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); + require(newLiquidityIndex < (1 << 128), Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); @@ -407,7 +407,7 @@ library ReserveLogic { timestamp ); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); - require(newVariableBorrowIndex < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); + require(newVariableBorrowIndex < (1 << 128), Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 78f74154..47bf3fd8 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -33,12 +33,12 @@ library ValidationLogic { * @param reserve the reserve state on which the user is depositing * @param amount the amount to be deposited */ - function validateDeposit(ReserveLogic.ReserveData storage reserve, uint256 amount) internal view { - (bool isActive, bool isFreezed, , ) = reserve.configuration.getFlags(); + function validateDeposit(ReserveLogic.ReserveData storage reserve, uint256 amount) external view { + (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); - require(amount > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); - require(isActive, Errors.NO_ACTIVE_RESERVE); - require(!isFreezed, Errors.NO_UNFREEZED_RESERVE); + require(amount > 0, Errors.VL_AMOUNT_NOT_GREATER_THAN_0); + require(isActive, Errors.VL_NO_ACTIVE_RESERVE); + require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** @@ -61,10 +61,10 @@ library ValidationLogic { mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle - ) internal view { - require(amount > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); + ) external view { + require(amount > 0, Errors.VL_AMOUNT_NOT_GREATER_THAN_0); - require(amount <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE); + require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); require( GenericLogic.balanceDecreaseAllowed( @@ -77,7 +77,7 @@ library ValidationLogic { reservesCount, oracle ), - Errors.TRANSFER_NOT_ALLOWED + Errors.VL_TRANSFER_NOT_ALLOWED ); } @@ -97,13 +97,14 @@ library ValidationLogic { ReserveLogic.InterestRateMode rateMode; bool healthFactorBelowThreshold; bool isActive; - bool isFreezed; + bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev validates a borrow. + * @param asset the address of the asset to borrow * @param reserve the reserve state from which the user is borrowing * @param userAddress the address of the user * @param amount the amount to be borrowed @@ -117,6 +118,7 @@ library ValidationLogic { */ function validateBorrow( + address asset, ReserveLogic.ReserveData storage reserve, address userAddress, uint256 amount, @@ -131,23 +133,20 @@ library ValidationLogic { ) external view { ValidateBorrowLocalVars memory vars; - ( - vars.isActive, - vars.isFreezed, - vars.borrowingEnabled, - vars.stableRateBorrowingEnabled - ) = reserve.configuration.getFlags(); + (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve + .configuration + .getFlags(); - require(vars.isActive, Errors.NO_ACTIVE_RESERVE); - require(!vars.isFreezed, Errors.NO_UNFREEZED_RESERVE); + require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); + require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); - require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); + require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(ReserveLogic.InterestRateMode.VARIABLE) == interestRateMode || uint256(ReserveLogic.InterestRateMode.STABLE) == interestRateMode, - Errors.INVALID_INTEREST_RATE_MODE_SELECTED + Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( @@ -165,11 +164,11 @@ library ValidationLogic { oracle ); - require(vars.userCollateralBalanceETH > 0, Errors.COLLATERAL_BALANCE_IS_0); + require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, - Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD + Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. @@ -179,7 +178,7 @@ library ValidationLogic { require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, - Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW + Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** @@ -194,20 +193,22 @@ library ValidationLogic { if (vars.rateMode == ReserveLogic.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve - require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); + require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), - Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY + Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); + vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); + //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); - require(amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); + require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } @@ -229,21 +230,21 @@ library ValidationLogic { ) external view { bool isActive = reserve.configuration.getActive(); - require(isActive, Errors.NO_ACTIVE_RESERVE); + require(isActive, Errors.VL_NO_ACTIVE_RESERVE); - require(amountSent > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); + require(amountSent > 0, Errors.VL_AMOUNT_NOT_GREATER_THAN_0); require( (stableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.STABLE) || (variableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.VARIABLE), - Errors.NO_DEBT_OF_SELECTED_TYPE + Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, - Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF + Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } @@ -251,26 +252,26 @@ library ValidationLogic { * @dev validates a swap of borrow rate mode. * @param reserve the reserve state on which the user is swapping the rate * @param userConfig the user reserves configuration - * @param stableBorrowBalance the stable borrow balance of the user - * @param variableBorrowBalance the stable borrow balance of the user + * @param stableDebt the stable debt of the user + * @param variableDebt the variable debt of the user * @param currentRateMode the rate mode of the borrow */ function validateSwapRateMode( ReserveLogic.ReserveData storage reserve, UserConfiguration.Map storage userConfig, - uint256 stableBorrowBalance, - uint256 variableBorrowBalance, + uint256 stableDebt, + uint256 variableDebt, ReserveLogic.InterestRateMode currentRateMode ) external view { - (bool isActive, bool isFreezed, , bool stableRateEnabled) = reserve.configuration.getFlags(); + (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); - require(isActive, Errors.NO_ACTIVE_RESERVE); - require(!isFreezed, Errors.NO_UNFREEZED_RESERVE); + require(isActive, Errors.VL_NO_ACTIVE_RESERVE); + require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == ReserveLogic.InterestRateMode.STABLE) { - require(stableBorrowBalance > 0, Errors.NO_STABLE_RATE_LOAN_IN_RESERVE); + require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) { - require(variableBorrowBalance > 0, Errors.NO_VARIABLE_RATE_LOAN_IN_RESERVE); + require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve @@ -278,17 +279,16 @@ library ValidationLogic { * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ - require(stableRateEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); + require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || - stableBorrowBalance.add(variableBorrowBalance) > - IERC20(reserve.aTokenAddress).balanceOf(msg.sender), - Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY + stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), + Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { - revert(Errors.INVALID_INTEREST_RATE_MODE_SELECTED); + revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } @@ -312,7 +312,7 @@ library ValidationLogic { ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); - require(underlyingBalance > 0, Errors.UNDERLYING_BALANCE_NOT_GREATER_THAN_0); + require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( GenericLogic.balanceDecreaseAllowed( @@ -325,23 +325,17 @@ library ValidationLogic { reservesCount, oracle ), - Errors.DEPOSIT_ALREADY_IN_USE + Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev validates a flashloan action - * @param mode the flashloan mode (0 = classic flashloan, 1 = open a stable rate loan, 2 = open a variable rate loan) * @param assets the assets being flashborrowed * @param amounts the amounts for each asset being borrowed **/ - function validateFlashloan( - address[] memory assets, - uint256[] memory amounts, - uint256 mode - ) internal pure { - require(mode <= uint256(ReserveLogic.InterestRateMode.VARIABLE), Errors.INVALID_FLASHLOAN_MODE); - require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS); + function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { + require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** @@ -364,13 +358,16 @@ library ValidationLogic { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { - return (uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.NO_ACTIVE_RESERVE); + return ( + uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), + Errors.VL_NO_ACTIVE_RESERVE + ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), - Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD + Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } @@ -381,18 +378,18 @@ library ValidationLogic { if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), - Errors.COLLATERAL_CANNOT_BE_LIQUIDATED + Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), - Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER + Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } - return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.NO_ERRORS); + return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** @@ -422,7 +419,7 @@ library ValidationLogic { require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, - Errors.TRANSFER_NOT_ALLOWED + Errors.VL_TRANSFER_NOT_ALLOWED ); } } diff --git a/contracts/libraries/math/PercentageMath.sol b/contracts/libraries/math/PercentageMath.sol index dda119f9..c0556011 100644 --- a/contracts/libraries/math/PercentageMath.sol +++ b/contracts/libraries/math/PercentageMath.sol @@ -28,7 +28,7 @@ library PercentageMath { require( value <= (type(uint256).max - HALF_PERCENT) / percentage, - Errors.MULTIPLICATION_OVERFLOW + Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; @@ -41,12 +41,12 @@ library PercentageMath { * @return the value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { - require(percentage != 0, Errors.DIVISION_BY_ZERO); + require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, - Errors.MULTIPLICATION_OVERFLOW + Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; diff --git a/contracts/libraries/math/WadRayMath.sol b/contracts/libraries/math/WadRayMath.sol index 2b4f989a..64d2e511 100644 --- a/contracts/libraries/math/WadRayMath.sol +++ b/contracts/libraries/math/WadRayMath.sol @@ -58,7 +58,7 @@ library WadRayMath { return 0; } - require(a <= (type(uint256).max - halfWAD) / b, Errors.MULTIPLICATION_OVERFLOW); + require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } @@ -70,10 +70,10 @@ library WadRayMath { * @return the result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { - require(b != 0, Errors.DIVISION_BY_ZERO); + require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; - require(a <= (type(uint256).max - halfB) / WAD, Errors.MULTIPLICATION_OVERFLOW); + require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } @@ -89,7 +89,7 @@ library WadRayMath { return 0; } - require(a <= (type(uint256).max - halfRAY) / b, Errors.MULTIPLICATION_OVERFLOW); + require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } @@ -101,10 +101,10 @@ library WadRayMath { * @return the result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { - require(b != 0, Errors.DIVISION_BY_ZERO); + require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; - require(a <= (type(uint256).max - halfB) / RAY, Errors.MULTIPLICATION_OVERFLOW); + require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } @@ -117,7 +117,7 @@ library WadRayMath { function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; - require(result >= halfRatio, Errors.ADDITION_OVERFLOW); + require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } @@ -129,7 +129,7 @@ library WadRayMath { **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; - require(result / WAD_RAY_RATIO == a, Errors.MULTIPLICATION_OVERFLOW); + require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } diff --git a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol index 7b72c2cb..215746ae 100644 --- a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol +++ b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol @@ -47,9 +47,11 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, + address initiator, bytes memory params ) public override returns (bool) { params; + initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index adc1771b..0a664548 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -13,7 +13,7 @@ import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /** * @title Aave ERC20 AToken * - * @dev Implementation of the interest bearing token for the DLP protocol. + * @dev Implementation of the interest bearing token for the Aave protocol. * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { @@ -40,7 +40,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { bytes32 public DOMAIN_SEPARATOR; modifier onlyLendingPool { - require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_LENDING_POOL); + require(_msgSender() == address(POOL), Errors.AT_CALLER_MUST_BE_LENDING_POOL); _; } @@ -100,7 +100,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); - require(amountScaled != 0, Errors.INVALID_BURN_AMOUNT); + require(amountScaled != 0, Errors.AT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); //transfers the underlying to the target @@ -108,7 +108,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { //transfer event to track balances emit Transfer(user, address(0), amount); - emit Burn(_msgSender(), receiverOfUnderlying, amount, index); + emit Burn(user, receiverOfUnderlying, amount, index); } /** @@ -127,7 +127,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); - require(amountScaled != 0, Errors.INVALID_MINT_AMOUNT); + require(amountScaled != 0, Errors.AT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); //transfer event to track balances diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 346d9719..e6105dbb 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -97,7 +97,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { address user, uint256 amount, uint256 rate - ) external override onlyLendingPool { + ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; //cumulates the user debt @@ -142,12 +142,14 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { emit Mint( user, amount, - previousBalance, currentBalance, balanceIncrease, vars.newStableRate, - vars.currentAvgStableRate + vars.currentAvgStableRate, + vars.nextSupply ); + + return currentBalance == 0; } /** @@ -164,16 +166,17 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 previousSupply = totalSupply(); uint256 newStableRate = 0; + uint256 nextSupply = 0; //since the total supply and each single user debt accrue separately, //there might be accumulation errors so that the last borrower repaying //might actually try to repay more than the available debt supply. //in this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { - newStableRate = _avgStableRate = 0; + _avgStableRate = 0; _totalSupply = 0; } else { - uint256 nextSupply = _totalSupply = previousSupply.sub(amount); + nextSupply = _totalSupply = previousSupply.sub(amount); newStableRate = _avgStableRate = _avgStableRate .rayMul(previousSupply.wadToRay()) .sub(_usersData[user].rayMul(amount.wadToRay())) @@ -199,7 +202,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { // transfer event to track balances emit Transfer(user, address(0), amount); - emit Burn(user, amount, previousBalance, currentBalance, balanceIncrease, newStableRate); + emit Burn(user, amount, currentBalance, balanceIncrease, newStableRate, nextSupply); } /** @@ -286,7 +289,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { * @param avgRate the average rate at which calculate the total supply * @return The debt balance of the user since the last burn/mint action **/ - function _calcTotalSupply(uint256 avgRate) internal view returns (uint256) { + function _calcTotalSupply(uint256 avgRate) internal virtual view returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 2a5d903c..6f16082b 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -60,7 +60,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); - require(amountScaled != 0, Errors.INVALID_MINT_AMOUNT); + require(amountScaled != 0, Errors.AT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); @@ -81,7 +81,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); - require(amountScaled != 0, Errors.INVALID_BURN_AMOUNT); + require(amountScaled != 0, Errors.AT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); diff --git a/contracts/tokenization/base/DebtTokenBase.sol b/contracts/tokenization/base/DebtTokenBase.sol index 0dddb431..723bb5d2 100644 --- a/contracts/tokenization/base/DebtTokenBase.sol +++ b/contracts/tokenization/base/DebtTokenBase.sol @@ -23,7 +23,7 @@ abstract contract DebtTokenBase is IncentivizedERC20, VersionedInitializable { * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { - require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_LENDING_POOL); + require(_msgSender() == address(POOL), Errors.AT_CALLER_MUST_BE_LENDING_POOL); _; } diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 4c0d5940..81c1b586 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -17,38 +17,38 @@ interface IStableDebtToken { * @dev emitted when new stable debt is minted * @param user the address of the user * @param amount the amount minted - * @param previousBalance the previous balance of the user * @param currentBalance the current balance of the user - * @param balanceIncrease the debt increase since the last update + * @param balanceIncrease the the increase in balance since the last action of the user * @param newRate the rate of the debt after the minting * @param avgStableRate the new average stable rate after the minting + * @param newTotalSupply the new total supply of the stable debt token after the action **/ event Mint( address indexed user, uint256 amount, - uint256 previousBalance, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, - uint256 avgStableRate + uint256 avgStableRate, + uint256 newTotalSupply ); /** * @dev emitted when new stable debt is burned * @param user the address of the user * @param amount the amount minted - * @param previousBalance the previous balance of the user * @param currentBalance the current balance of the user - * @param balanceIncrease the debt increase since the last update + * @param balanceIncrease the the increase in balance since the last action of the user * @param avgStableRate the new average stable rate after the minting + * @param newTotalSupply the new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, - uint256 previousBalance, uint256 currentBalance, uint256 balanceIncrease, - uint256 avgStableRate + uint256 avgStableRate, + uint256 newTotalSupply ); /** @@ -62,7 +62,7 @@ interface IStableDebtToken { address user, uint256 amount, uint256 rate - ) external; + ) external returns (bool); /** * @dev burns debt of the target user. diff --git a/deployed-contracts.json b/deployed-contracts.json index 642cd6a5..a2173231 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -163,25 +163,26 @@ }, "ReserveLogic": { "buidlerevm": { - "address": "0xFAe0fd738dAbc8a0426F47437322b6d026A9FD95", + "address": "0x78Ee8Fb9fE5abD5e347Fc94c2fb85596d1f60e3c", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "GenericLogic": { "buidlerevm": { - "address": "0x6082731fdAba4761277Fb31299ebC782AD3bCf24", + "address": "0x920d847fE49E54C19047ba8bc236C45A8068Bca7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "ValidationLogic": { "buidlerevm": { - "address": "0x8456161947DFc1fC159A0B26c025cD2b4bba0c3e", + "address": "0xA4765Ff72A9F3CfE73089bb2c3a41B838DF71574", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPool": { "buidlerevm": { - "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" + "address": "0x35c1419Da7cf0Ff885B8Ef8EA9242FEF6800c99b", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPoolConfigurator": { @@ -197,7 +198,7 @@ }, "ATokensAndRatesHelper": { "buidlerevm": { - "address": "0x06bA8d8af0dF898D0712DffFb0f862cC51AF45c2", + "address": "0x920d847fE49E54C19047ba8bc236C45A8068Bca7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, diff --git a/helpers/contracts-deployments.ts b/helpers/contracts-deployments.ts index 82ac2d97..90561b28 100644 --- a/helpers/contracts-deployments.ts +++ b/helpers/contracts-deployments.ts @@ -33,7 +33,10 @@ import { LendingRateOracleFactory, MintableErc20Factory, MockAggregatorFactory, + MockATokenFactory, MockFlashLoanReceiverFactory, + MockStableDebtTokenFactory, + MockVariableDebtTokenFactory, PriceOracleFactory, ReserveLogicFactory, StableDebtTokenFactory, @@ -42,6 +45,8 @@ import { } from '../types'; import {withSaveAndVerify, registerContractInJsonDb, linkBytecode} from './contracts-helpers'; import {StableAndVariableTokensHelperFactory} from '../types/StableAndVariableTokensHelperFactory'; +import {MockStableDebtToken} from '../types/MockStableDebtToken'; +import {MockVariableDebtToken} from '../types/MockVariableDebtToken'; export const deployLendingPoolAddressesProvider = async (verify?: boolean) => withSaveAndVerify( @@ -140,7 +145,6 @@ export const deployAaveLibraries = async ( return { ['__$5201a97c05ba6aa659e2f36a933dd51801$__']: validationLogic.address, ['__$d3b4366daeb9cadc7528af6145b50b2183$__']: reserveLogic.address, - ['__$4c26be947d349222af871a3168b3fe584b$__']: genericLogic.address, }; }; @@ -374,3 +378,36 @@ export const deployATokensAndRatesHelper = async ( args, verify ); + +export const deployMockStableDebtToken = async ( + args: [tEthereumAddress, tEthereumAddress, string, string, tEthereumAddress], + verify?: boolean +) => + withSaveAndVerify( + await new MockStableDebtTokenFactory(await getFirstSigner()).deploy(...args), + eContractid.ATokensAndRatesHelper, + args, + verify + ); + +export const deployMockVariableDebtToken = async ( + args: [tEthereumAddress, tEthereumAddress, string, string, tEthereumAddress], + verify?: boolean +) => + withSaveAndVerify( + await new MockVariableDebtTokenFactory(await getFirstSigner()).deploy(...args), + eContractid.ATokensAndRatesHelper, + args, + verify + ); + +export const deployMockAToken = async ( + args: [tEthereumAddress, tEthereumAddress, tEthereumAddress, string, string, tEthereumAddress], + verify?: boolean +) => + withSaveAndVerify( + await new MockATokenFactory(await getFirstSigner()).deploy(...args), + eContractid.ATokensAndRatesHelper, + args, + verify + ); diff --git a/helpers/contracts-getters.ts b/helpers/contracts-getters.ts index 0b03cb63..7fa9fdee 100644 --- a/helpers/contracts-getters.ts +++ b/helpers/contracts-getters.ts @@ -10,7 +10,10 @@ import { LendingPoolFactory, LendingRateOracleFactory, MintableErc20Factory, + MockATokenFactory, MockFlashLoanReceiverFactory, + MockStableDebtTokenFactory, + MockVariableDebtTokenFactory, PriceOracleFactory, ReserveLogicFactory, StableAndVariableTokensHelperFactory, @@ -222,3 +225,23 @@ export const getATokensAndRatesHelper = async (address?: tEthereumAddress) => .address, await getFirstSigner() ); + +export const getMockAToken = async (address?: tEthereumAddress) => + await MockATokenFactory.connect( + address || (await getDb().get(`${eContractid.MockAToken}.${BRE.network.name}`).value()).address, + await getFirstSigner() + ); + +export const getMockVariableDebtToken = async (address?: tEthereumAddress) => + await MockVariableDebtTokenFactory.connect( + address || + (await getDb().get(`${eContractid.MockVariableDebtToken}.${BRE.network.name}`).value()) + .address, + await getFirstSigner() + ); +export const getMockStableDebtToken = async (address?: tEthereumAddress) => + await MockStableDebtTokenFactory.connect( + address || + (await getDb().get(`${eContractid.MockStableDebtToken}.${BRE.network.name}`).value()).address, + await getFirstSigner() + ); diff --git a/helpers/types.ts b/helpers/types.ts index 51269f16..dab5c704 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -61,72 +61,91 @@ export enum eContractid { UiPoolDataProvider = 'UiPoolDataProvider', } +/* + * Error messages prefix glossary: + * - VL = ValidationLogic + * - MATH = Math libraries + * - AT = aToken or DebtTokens + * - LP = LendingPool + * - LPAPR = LendingPoolAddressesProviderRegistry + * - LPC = LendingPoolConfiguration + * - RL = ReserveLogic + * - LPCM = LendingPoolCollateralManager + * - P = Pausable + */ export enum ProtocolErrors { - // require error messages - ValidationLogic - AMOUNT_NOT_GREATER_THAN_0 = '1', // 'Amount must be greater than 0' - NO_ACTIVE_RESERVE = '2', // 'Action requires an active reserve' - NO_UNFREEZED_RESERVE = '3', // 'Action requires an unfreezed reserve' - CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4', // 'The current liquidity is not enough' - NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5', // 'User cannot withdraw more than the available balance' - TRANSFER_NOT_ALLOWED = '6', // 'Transfer cannot be allowed.' - BORROWING_NOT_ENABLED = '7', // 'Borrowing is not enabled' - INVALID_INTEREST_RATE_MODE_SELECTED = '8', // 'Invalid interest rate mode selected' - COLLATERAL_BALANCE_IS_0 = '9', // 'The collateral balance is 0' - HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10', // 'Health factor is lesser than the liquidation threshold' - COLLATERAL_CANNOT_COVER_NEW_BORROW = '11', // 'There is not enough collateral to cover a new borrow' - STABLE_BORROWING_NOT_ENABLED = '12', // stable borrowing not enabled - CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13', // collateral is (mostly) the same currency that is being borrowed - AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14', // 'The requested amount is greater than the max loan size in stable rate mode - 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' - NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16', // 'To repay on behalf of an user an explicit amount to repay is needed' - NO_STABLE_RATE_LOAN_IN_RESERVE = '17', // 'User does not have a stable rate loan in progress on this reserve' - NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18', // 'User does not have a variable rate loan in progress on this reserve' - UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19', // 'The underlying balance needs to be greater than 0' - DEPOSIT_ALREADY_IN_USE = '20', // 'User deposit is already being used as collateral' - INVALID_EQUAL_ASSETS_TO_SWAP = '56', // User can't use same reserve as destination of liquidity swap - - // require error messages - LendingPool - NOT_ENOUGH_STABLE_BORROW_BALANCE = '21', // 'User does not have any stable rate loan for this reserve' - INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22', // 'Interest rate rebalance conditions were not met' - LIQUIDATION_CALL_FAILED = '23', // 'Liquidation call failed' - NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24', // 'There is not enough liquidity available to borrow' - REQUESTED_AMOUNT_TOO_SMALL = '25', // 'The requested amount is too small for a FlashLoan.' - INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26', // 'The actual balance of the protocol is inconsistent' - CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27', // 'The actual balance of the protocol is inconsistent' - BORROW_ALLOWANCE_ARE_NOT_ENOUGH = '54', // User borrows on behalf, but allowance are too small - INVALID_FLASH_LOAN_EXECUTOR_RETURN = '60', // The flash loan received returned 0 (EOA) - - // require error messages - aToken - CALLER_MUST_BE_LENDING_POOL = '28', // 'The caller of this function must be a lending pool' - CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30', // 'User cannot give allowance to himself' - TRANSFER_AMOUNT_NOT_GT_0 = '31', // 'Transferred amount needs to be greater than zero' - - // require error messages - ReserveLogic - RESERVE_ALREADY_INITIALIZED = '34', // 'Reserve has already been initialized' - - //require error messages - LendingPoolConfiguration - CALLER_NOT_AAVE_ADMIN = '35', // 'The caller must be the aave admin' - RESERVE_LIQUIDITY_NOT_0 = '36', // 'The liquidity of the reserve needs to be 0' - - //require error messages - LendingPoolAddressesProviderRegistry - PROVIDER_NOT_REGISTERED = '37', // 'Provider is not registered' - INVALID_ADDRESSES_PROVIDER_ID = '68', - - //return error messages - LendingPoolCollateralManager - HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '38', // 'Health factor is not below the threshold' - COLLATERAL_CANNOT_BE_LIQUIDATED = '39', // 'The collateral chosen cannot be liquidated' - SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '40', // 'User did not borrow the specified currency' - NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '41', // "There isn't enough liquidity available to liquidate" - NO_ERRORS = '42', // 'No errors' - INVALID_FLASHLOAN_MODE = '43', //Invalid flashloan mode - - IS_PAUSED = '58', // Pool is paused - - INVALID_LTV = '70', - INVALID_LIQ_THRESHOLD = '71', - INVALID_LIQ_BONUS = '72', - INVALID_DECIMALS = '73', - INVALID_RESERVE_FACTOR = '74', + VL_AMOUNT_NOT_GREATER_THAN_0 = '1', // 'Amount must be greater than 0' + VL_NO_ACTIVE_RESERVE = '2', // 'Action requires an active reserve' + VL_RESERVE_FROZEN = '3', // 'Action requires an unfrozen reserve' + VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4', // 'The current liquidity is not enough' + VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5', // 'User cannot withdraw more than the available balance' + VL_TRANSFER_NOT_ALLOWED = '6', // 'Transfer cannot be allowed.' + VL_BORROWING_NOT_ENABLED = '7', // 'Borrowing is not enabled' + VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8', // 'Invalid interest rate mode selected' + VL_COLLATERAL_BALANCE_IS_0 = '9', // 'The collateral balance is 0' + VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10', // 'Health factor is lesser than the liquidation threshold' + VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11', // 'There is not enough collateral to cover a new borrow' + VL_STABLE_BORROWING_NOT_ENABLED = '12', // stable borrowing not enabled + VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13', // collateral is (mostly) the same currency that is being borrowed + VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14', // 'The requested amount is greater than the max loan size in stable rate mode + 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' + VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16', // 'To repay on behalf of an user an explicit amount to repay is needed' + VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17', // 'User does not have a stable rate loan in progress on this reserve' + VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18', // 'User does not have a variable rate loan in progress on this reserve' + VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19', // 'The underlying balance needs to be greater than 0' + VL_DEPOSIT_ALREADY_IN_USE = '20', // 'User deposit is already being used as collateral' + LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21', // 'User does not have any stable rate loan for this reserve' + LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22', // 'Interest rate rebalance conditions were not met' + LP_LIQUIDATION_CALL_FAILED = '23', // 'Liquidation call failed' + LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24', // 'There is not enough liquidity available to borrow' + LP_REQUESTED_AMOUNT_TOO_SMALL = '25', // 'The requested amount is too small for a FlashLoan.' + LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26', // 'The actual balance of the protocol is inconsistent' + LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27', // 'The actual balance of the protocol is inconsistent' + LP_INCONSISTENT_FLASHLOAN_PARAMS = '28', + AT_CALLER_MUST_BE_LENDING_POOL = '29', // 'The caller of this function must be a lending pool' + AT_CANNOT_GIVE_ALLVWANCE_TO_HIMSELF = '30', // 'User cannot give allowance to himself' + AT_TRANSFER_AMOUNT_NOT_GT_0 = '31', // 'Transferred amount needs to be greater than zero' + RL_RESERVE_ALREADY_INITIALIZED = '32', // 'Reserve has already been initialized' + LPC_CALLER_NOT_AAVE_ADMIN = '33', // 'The caller must be the aave admin' + LPC_RESERVE_LIQUIDITY_NOT_0 = '34', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_ATOKEN_POOL_ADDRESS = '35', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39', // 'The liquidity of the reserve needs to be 0' + LPC_INVALID_ADDRESSES_PROVIDER_ID = '40', // 'The liquidity of the reserve needs to be 0' + LPAPR_PROVIDER_NOT_REGISTERED = '41', // 'Provider is not registered' + LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42', // 'Health factor is not below the threshold' + LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43', // 'The collateral chosen cannot be liquidated' + LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44', // 'User did not borrow the specified currency' + LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45', // "There isn't enough liquidity available to liquidate" + LPCM_NO_ERRORS = '46', // 'No errors' + LP_INVALID_FLASHLOAN_MODE = '47', //Invalid flashloan mode selected + MATH_MULTIPLICATION_OVERFLOW = '48', + MATH_ADDITION_OVERFLOW = '49', + MATH_DIVISION_BY_ZERO = '50', + RL_LIQUIDITY_INDEX_OVERFLOW = '51', // Liquidity index overflows uint128 + RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52', // Variable borrow index overflows uint128 + RL_LIQUIDITY_RATE_OVERFLOW = '53', // Liquidity rate overflows uint128 + RL_VARIABLE_BORROW_RATE_OVERFLOW = '54', // Variable borrow rate overflows uint128 + RL_STABLE_BORROW_RATE_OVERFLOW = '55', // Stable borrow rate overflows uint128 + AT_INVALID_MINT_AMOUNT = '56', //invalid amount to mint + LP_FAILED_REPAY_WITH_COLLATERAL = '57', + AT_INVALID_BURN_AMOUNT = '58', //invalid amount to burn + LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH = '59', // User borrows on behalf, but allowance are too small + LP_FAILED_COLLATERAL_SWAP = '60', + LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61', + LP_REENTRANCY_NOT_ALLOWED = '62', + LP_CALLER_MUST_BE_AN_ATOKEN = '63', + LP_IS_PAUSED = '64', // 'Pool is paused' + LP_NO_MORE_RESERVES_ALLOWED = '65', + LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66', + RC_INVALID_LTV = '67', + RC_INVALID_LIQ_THRESHOLD = '68', + RC_INVALID_LIQ_BONUS = '69', + RC_INVALID_DECIMALS = '70', + RC_INVALID_RESERVE_FACTOR = '71', + LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72', // old diff --git a/package-lock.json b/package-lock.json index a05b7b34..b1ac6412 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5274,13 +5274,13 @@ "dependencies": { "ansi-regex": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "resolved": false, "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", "dev": true }, "ansi-styles": { "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "resolved": false, "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "requires": { @@ -5289,7 +5289,7 @@ }, "bindings": { "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "resolved": false, "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", "dev": true, "requires": { @@ -5298,7 +5298,7 @@ }, "bip66": { "version": "1.1.5", - "resolved": "https://registry.npmjs.org/bip66/-/bip66-1.1.5.tgz", + "resolved": false, "integrity": "sha1-AfqHSHhcpwlV1QESF9GzE5lpyiI=", "dev": true, "requires": { @@ -5307,19 +5307,19 @@ }, "bn.js": { "version": "4.11.8", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "resolved": false, "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", "dev": true }, "brorand": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "resolved": false, "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", "dev": true }, "browserify-aes": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "resolved": false, "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "dev": true, "requires": { @@ -5333,25 +5333,25 @@ }, "buffer-from": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "resolved": false, "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", "dev": true }, "buffer-xor": { "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "resolved": false, "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", "dev": true }, "camelcase": { "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "resolved": false, "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, "cipher-base": { "version": "1.0.4", - "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "resolved": false, "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", "dev": true, "requires": { @@ -5361,7 +5361,7 @@ }, "cliui": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "resolved": false, "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", "dev": true, "requires": { @@ -5372,7 +5372,7 @@ }, "color-convert": { "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "resolved": false, "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "requires": { @@ -5381,13 +5381,13 @@ }, "color-name": { "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "resolved": false, "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, "create-hash": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "resolved": false, "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "dev": true, "requires": { @@ -5400,7 +5400,7 @@ }, "create-hmac": { "version": "1.1.7", - "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "resolved": false, "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "dev": true, "requires": { @@ -5414,7 +5414,7 @@ }, "cross-spawn": { "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "resolved": false, "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", "dev": true, "requires": { @@ -5427,13 +5427,13 @@ }, "decamelize": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "resolved": false, "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "drbg.js": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/drbg.js/-/drbg.js-1.0.1.tgz", + "resolved": false, "integrity": "sha1-Pja2xCs3BDgjzbwzLVjzHiRFSAs=", "dev": true, "requires": { @@ -5444,7 +5444,7 @@ }, "elliptic": { "version": "6.5.0", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.0.tgz", + "resolved": false, "integrity": "sha512-eFOJTMyCYb7xtE/caJ6JJu+bhi67WCYNbkGSknu20pmM8Ke/bqOfdnZWxyoGN26JgfxTbXrsCkEw4KheCT/KGg==", "dev": true, "requires": { @@ -5459,13 +5459,13 @@ }, "emoji-regex": { "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "resolved": false, "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, "end-of-stream": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "resolved": false, "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", "dev": true, "requires": { @@ -5474,7 +5474,7 @@ }, "ethereumjs-util": { "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-6.1.0.tgz", + "resolved": false, "integrity": "sha512-URESKMFbDeJxnAxPppnk2fN6Y3BIatn9fwn76Lm8bQlt+s52TpG8dN9M66MLPuRAiAOIqL3dfwqWJf0sd0fL0Q==", "dev": true, "requires": { @@ -5489,7 +5489,7 @@ }, "ethjs-util": { "version": "0.1.6", - "resolved": "https://registry.npmjs.org/ethjs-util/-/ethjs-util-0.1.6.tgz", + "resolved": false, "integrity": "sha512-CUnVOQq7gSpDHZVVrQW8ExxUETWrnrvXYvYz55wOU8Uj4VCgw56XC2B/fVqQN+f7gmrnRHSLVnFAwsCuNwji8w==", "dev": true, "requires": { @@ -5499,7 +5499,7 @@ }, "evp_bytestokey": { "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "resolved": false, "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", "dev": true, "requires": { @@ -5509,7 +5509,7 @@ }, "execa": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "resolved": false, "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", "dev": true, "requires": { @@ -5524,13 +5524,13 @@ }, "file-uri-to-path": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "resolved": false, "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", "dev": true }, "find-up": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "resolved": false, "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "dev": true, "requires": { @@ -5539,13 +5539,13 @@ }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "resolved": false, "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "get-stream": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "resolved": false, "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", "dev": true, "requires": { @@ -5554,7 +5554,7 @@ }, "hash-base": { "version": "3.0.4", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "resolved": false, "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", "dev": true, "requires": { @@ -5564,7 +5564,7 @@ }, "hash.js": { "version": "1.1.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "resolved": false, "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", "dev": true, "requires": { @@ -5574,7 +5574,7 @@ }, "hmac-drbg": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "resolved": false, "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", "dev": true, "requires": { @@ -5585,43 +5585,43 @@ }, "inherits": { "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "resolved": false, "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, "invert-kv": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", + "resolved": false, "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "resolved": false, "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "is-hex-prefixed": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-hex-prefixed/-/is-hex-prefixed-1.0.0.tgz", + "resolved": false, "integrity": "sha1-fY035q135dEnFIkTxXPggtd39VQ=", "dev": true }, "is-stream": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "resolved": false, "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", "dev": true }, "isexe": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "resolved": false, "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, "keccak": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/keccak/-/keccak-1.4.0.tgz", + "resolved": false, "integrity": "sha512-eZVaCpblK5formjPjeTBik7TAg+pqnDrMHIffSvi9Lh7PQgM1+hSzakUeZFCk9DVVG0dacZJuaz2ntwlzZUIBw==", "dev": true, "requires": { @@ -5633,7 +5633,7 @@ }, "lcid": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", + "resolved": false, "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", "dev": true, "requires": { @@ -5642,7 +5642,7 @@ }, "locate-path": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "resolved": false, "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "dev": true, "requires": { @@ -5652,7 +5652,7 @@ }, "map-age-cleaner": { "version": "0.1.3", - "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", + "resolved": false, "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", "dev": true, "requires": { @@ -5661,7 +5661,7 @@ }, "md5.js": { "version": "1.3.5", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "resolved": false, "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", "dev": true, "requires": { @@ -5672,7 +5672,7 @@ }, "mem": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-4.3.0.tgz", + "resolved": false, "integrity": "sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==", "dev": true, "requires": { @@ -5683,37 +5683,37 @@ }, "mimic-fn": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "resolved": false, "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "dev": true }, "minimalistic-assert": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "resolved": false, "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", "dev": true }, "minimalistic-crypto-utils": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "resolved": false, "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", "dev": true }, "nan": { "version": "2.14.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", + "resolved": false, "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", "dev": true }, "nice-try": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "resolved": false, "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", "dev": true }, "npm-run-path": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "resolved": false, "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "dev": true, "requires": { @@ -5722,7 +5722,7 @@ }, "once": { "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "resolved": false, "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { @@ -5731,7 +5731,7 @@ }, "os-locale": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", + "resolved": false, "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", "dev": true, "requires": { @@ -5742,25 +5742,25 @@ }, "p-defer": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "resolved": false, "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", "dev": true }, "p-finally": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "resolved": false, "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", "dev": true }, "p-is-promise": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", + "resolved": false, "integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==", "dev": true }, "p-limit": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", + "resolved": false, "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", "dev": true, "requires": { @@ -5769,7 +5769,7 @@ }, "p-locate": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "resolved": false, "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "dev": true, "requires": { @@ -5778,25 +5778,25 @@ }, "p-try": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "resolved": false, "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, "path-exists": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "resolved": false, "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", "dev": true }, "path-key": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "resolved": false, "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "pump": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "resolved": false, "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dev": true, "requires": { @@ -5806,19 +5806,19 @@ }, "require-directory": { "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "resolved": false, "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "resolved": false, "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "ripemd160": { "version": "2.0.2", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "resolved": false, "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", "dev": true, "requires": { @@ -5828,7 +5828,7 @@ }, "rlp": { "version": "2.2.3", - "resolved": "https://registry.npmjs.org/rlp/-/rlp-2.2.3.tgz", + "resolved": false, "integrity": "sha512-l6YVrI7+d2vpW6D6rS05x2Xrmq8oW7v3pieZOJKBEdjuTF4Kz/iwk55Zyh1Zaz+KOB2kC8+2jZlp2u9L4tTzCQ==", "dev": true, "requires": { @@ -5838,13 +5838,13 @@ }, "safe-buffer": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "resolved": false, "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", "dev": true }, "secp256k1": { "version": "3.7.1", - "resolved": "https://registry.npmjs.org/secp256k1/-/secp256k1-3.7.1.tgz", + "resolved": false, "integrity": "sha512-1cf8sbnRreXrQFdH6qsg2H71Xw91fCCS9Yp021GnUNJzWJS/py96fS4lHbnTnouLp08Xj6jBoBB6V78Tdbdu5g==", "dev": true, "requires": { @@ -5860,19 +5860,19 @@ }, "semver": { "version": "5.7.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "resolved": false, "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", "dev": true }, "set-blocking": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "resolved": false, "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, "sha.js": { "version": "2.4.11", - "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "resolved": false, "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "dev": true, "requires": { @@ -5882,7 +5882,7 @@ }, "shebang-command": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "resolved": false, "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { @@ -5891,25 +5891,25 @@ }, "shebang-regex": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "resolved": false, "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "signal-exit": { "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "resolved": false, "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "resolved": false, "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, "source-map-support": { "version": "0.5.12", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz", + "resolved": false, "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==", "dev": true, "requires": { @@ -5919,7 +5919,7 @@ }, "string-width": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "resolved": false, "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "dev": true, "requires": { @@ -5930,7 +5930,7 @@ }, "strip-ansi": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "resolved": false, "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "dev": true, "requires": { @@ -5939,13 +5939,13 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "resolved": false, "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", "dev": true }, "strip-hex-prefix": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz", + "resolved": false, "integrity": "sha1-DF8VX+8RUTczd96du1iNoFUA428=", "dev": true, "requires": { @@ -5954,7 +5954,7 @@ }, "which": { "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "resolved": false, "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", "dev": true, "requires": { @@ -5963,13 +5963,13 @@ }, "which-module": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "resolved": false, "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wrap-ansi": { "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "resolved": false, "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", "dev": true, "requires": { @@ -5980,19 +5980,19 @@ }, "wrappy": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "resolved": false, "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, "y18n": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "resolved": false, "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", "dev": true }, "yargs": { "version": "13.2.4", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.4.tgz", + "resolved": false, "integrity": "sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg==", "dev": true, "requires": { @@ -6011,7 +6011,7 @@ }, "yargs-parser": { "version": "13.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", + "resolved": false, "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", "dev": true, "requires": { diff --git a/runStableTokenCLI.sh b/runStableTokenCLI.sh new file mode 100644 index 00000000..8903f2f9 --- /dev/null +++ b/runStableTokenCLI.sh @@ -0,0 +1 @@ +certoraRun specs/harness/StableDebtTokenHarness.sol:StableDebtTokenHarness --solc solc6.8 --verify StableDebtTokenHarness:specs/StableDebtToken.spec --settings -assumeUnwindCond --cache StableDebtToken --staging master \ No newline at end of file diff --git a/runUserConfigCLI.sh b/runUserConfigCLI.sh new file mode 100644 index 00000000..f3ddbacc --- /dev/null +++ b/runUserConfigCLI.sh @@ -0,0 +1 @@ +certoraRun specs/harness/UserConfigurationHarness.sol --solc solc6.8 --verify UserConfigurationHarness:specs/UserConfiguration.spec --settings -useBitVectorTheory --staging master diff --git a/runVariableTokenCLI.sh b/runVariableTokenCLI.sh new file mode 100644 index 00000000..483e152e --- /dev/null +++ b/runVariableTokenCLI.sh @@ -0,0 +1 @@ +certoraRun contracts/tokenization/VariableDebtToken.sol:VariableDebtToken specs/harness/LendingPoolHarnessForVariableDebtToken.sol --solc solc6.8 --link VariableDebtToken:POOL=LendingPoolHarnessForVariableDebtToken --verify VariableDebtToken:specs/VariableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache VariableDebtToken --staging \ No newline at end of file diff --git a/specs/StableDebtToken.spec b/specs/StableDebtToken.spec new file mode 100644 index 00000000..0d6e0c5d --- /dev/null +++ b/specs/StableDebtToken.spec @@ -0,0 +1,155 @@ +methods { + getUserLastUpdated(address) returns uint40 envfree +} + +rule integrityTimeStamp(address user, method f) { + env e; + require sinvoke getIncentivesController(e) == 0; + require getUserLastUpdated(user) <= e.block.timestamp; + calldataarg arg; + sinvoke f(e,arg); + assert getUserLastUpdated(user) <= e.block.timestamp; +} + +/** +TotalSupply is the sum of all users’ balances + +totalSupply(t) = Σaddress u. balanceOf(u,t) + +Check that each possible opertaion changes the balance of at most one user +*/ +rule balanceOfChange(address a, address b, method f ) +{ + env e; + require a!=b; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 balanceBBefore = sinvoke balanceOf(e,b); + + calldataarg arg; + sinvoke f(e, arg); + + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 balanceBAfter = sinvoke balanceOf(e,b); + + assert ( balanceABefore == balanceAAfter || balanceBBefore == balanceBAfter ); +} + +/** +Check that the change to total supply is coherent with the changes to balance +*/ +rule integirtyBalanceOfTotalSupply(address a, method f ) +{ + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 totalSupplyBefore = sinvoke totalSupply(e); + + calldataarg arg; + sinvoke f(e, arg); + require (f.selector != burn(address,uint256).selector ); + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 totalSupplyAfter = sinvoke totalSupply(e); + + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/* Burn behaves differently and due to accumulation errors might have less total supply than the balance +*/ +rule integirtyBalanceOfTotalSupplyOnBurn(address a, method f) +{ + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 totalSupplyBefore = sinvoke totalSupply(e); + + uint256 x; + sinvoke burn(e, a, x); + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 totalSupplyAfter = sinvoke totalSupply(e); + if (totalSupplyBefore > x) + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); + else + assert (totalSupplyAfter == 0 ); +} + +/** +Mint inceases the balanceOf user a as expected +*/ +rule integrityMint(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke mint(e,a,x,index); + + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balanceAfter == balancebefore+x; +} + +/** +Mint is additive, can performed either all at once or gradually +mint(u,x); mint(u,y) ~ mint(u,x+y) at the same timestamp + +Note: We assume that the stable rate of the user is 0. +The case where the rate is non-zero takes much more time to prove, +and therefore it is currently excluded from the CI. +*/ +rule additiveMint(address a, uint256 x, uint256 y) { + env e; + require sinvoke getIncentivesController(e) == 0; + require getUserStableRate(e,a) == 0; + uint256 index; + storage initialStorage = lastStorage; + sinvoke mint(e,a,x,index); + sinvoke mint(e,a,y,index); + uint256 balanceScenario1 = sinvoke balanceOf(e,a); + + uint256 t = x + y; + sinvoke mint(e,a, t ,index) at initialStorage; + + uint256 balanceScenario2 = sinvoke balanceOf(e,a); + assert balanceScenario1 == balanceScenario2, "mint is not additive"; +} + +rule integrityBurn(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke burn(e,a,x); + + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balanceAfter == balancebefore - x; +} + +rule additiveBurn(address a, uint256 x, uint256 y) { + env e; + require sinvoke getIncentivesController(e) == 0; + storage initialStorage = lastStorage; + sinvoke burn(e, a, x); + sinvoke burn(e, a, y); + uint256 balanceScenario1 = balanceOf(e, a); + uint256 t = x + y; + sinvoke burn(e, a, t) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "burn is not additive"; +} + + +/** +mint and burn are inverse operations +Thus, totalSupply is back to initial state +BalanceOf user is back to initial state */ +rule inverseMintBurn(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke mint(e,a,x,index); + sinvoke burn(e,a,x); + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balancebefore == balanceAfter, "burn is not inverse of mint"; +} + diff --git a/specs/UserConfiguration.spec b/specs/UserConfiguration.spec new file mode 100644 index 00000000..14fce3a6 --- /dev/null +++ b/specs/UserConfiguration.spec @@ -0,0 +1,66 @@ +methods { + setBorrowing(address, uint256, bool) envfree + setUsingAsCollateral(address, uint256, bool) envfree + isUsingAsCollateralOrBorrowing(address, uint256) returns bool envfree + isBorrowing(address, uint256) returns bool envfree + isUsingAsCollateral(address, uint256) returns bool envfree + isBorrowingAny(address ) returns bool envfree + isEmpty(address ) returns bool envfree +} + +invariant empty(address user, uint256 reserveIndex ) + isEmpty(user) => !isBorrowingAny(user) && !isUsingAsCollateralOrBorrowing(user, reserveIndex) + +invariant notEmpty(address user, uint256 reserveIndex ) + ( isBorrowingAny(user) || isUsingAsCollateral(user, reserveIndex)) => !isEmpty(user) + + +invariant borrowing(address user, uint256 reserveIndex ) + isBorrowing(user, reserveIndex) => isBorrowingAny(user) + +invariant collateralOrBorrowing(address user, uint256 reserveIndex ) + ( isUsingAsCollateral(user, reserveIndex) || isBorrowing(user, reserveIndex) ) <=> isUsingAsCollateralOrBorrowing(user, reserveIndex) + + + +rule setBorrowing(address user, uint256 reserveIndex, bool borrowing) +{ + require reserveIndex < 128; + + setBorrowing(user, reserveIndex, borrowing); + assert isBorrowing(user, reserveIndex) == borrowing, "unexpected result"; +} + +rule setBorrowingNoChangeToOther(address user, uint256 reserveIndex, uint256 reserveIndexOther, bool borrowing) +{ + require reserveIndexOther != reserveIndex; + require reserveIndexOther < 128 && reserveIndex < 128; + bool otherReserveBorrowing = isBorrowing(user, reserveIndexOther); + bool otherReserveCollateral = isUsingAsCollateral(user,reserveIndexOther); + + setBorrowing(user, reserveIndex, borrowing); + assert otherReserveBorrowing == isBorrowing(user, reserveIndexOther) && + otherReserveCollateral == isUsingAsCollateral(user,reserveIndexOther), "changed to other reserve"; +} + + +rule setUsingAsCollateral(address user, uint256 reserveIndex, bool usingAsCollateral) +{ + require reserveIndex < 128; + + setUsingAsCollateral(user, reserveIndex, usingAsCollateral); + assert isUsingAsCollateral(user, reserveIndex) == usingAsCollateral, "unexpected result"; +} + + +rule setUsingAsCollateralNoChangeToOther(address user, uint256 reserveIndex, uint256 reserveIndexOther, bool usingAsCollateral) +{ + require reserveIndexOther != reserveIndex; + require reserveIndexOther < 128 && reserveIndex < 128; + bool otherReserveBorrowing = isBorrowing(user, reserveIndexOther); + bool otherReserveCollateral = isUsingAsCollateral(user,reserveIndexOther); + + setUsingAsCollateral(user, reserveIndex, usingAsCollateral); + assert otherReserveBorrowing == isBorrowing(user, reserveIndexOther) && + otherReserveCollateral == isUsingAsCollateral(user,reserveIndexOther), "changed to other reserve"; +} diff --git a/specs/VariableDebtToken.spec b/specs/VariableDebtToken.spec new file mode 100644 index 00000000..73e7e39c --- /dev/null +++ b/specs/VariableDebtToken.spec @@ -0,0 +1,173 @@ +using LendingPoolHarnessForVariableDebtToken as POOL +/** +TotalSupply is the sum of all users’ balances + +totalSupply(t) = Σaddress u. balanceOf(u,t) + +Check that each possible opertaion changes the balance of at most one user +*/ +rule balanceOfChange(address a, address b, method f) +{ + env e; + require a!=b ; + uint256 balanceABefore = sinvoke balanceOf(e, a); + uint256 balanceBBefore = sinvoke balanceOf(e, b); + + calldataarg arg; + sinvoke f(e, arg); + + uint256 balanceAAfter = sinvoke balanceOf(e, a); + uint256 balanceBAfter = sinvoke balanceOf(e, b); + + assert ( balanceABefore == balanceAAfter || balanceBBefore == balanceBAfter ); +} + +/* +Check that the changed to total supply is coherent with the changes to balance +*/ + +rule integirtyBalanceOfTotalSupply(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + calldataarg arg; + sinvoke f(e, arg); + require (f.selector != burn(address, uint256, uint256).selector && + f.selector != mint(address, uint256, uint256).selector ) ; + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/* Burn behaves deferently and due to accumulation errors might hace less total supply then the balance +*/ + +rule integirtyBalanceOfTotalSupplyOnBurn(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + uint256 x; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + sinvoke burn(e, a, x, index); + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +rule integirtyBalanceOfTotalSupplyOnMint(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + uint256 x; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + sinvoke mint(e, a, x, index); + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/** +Minting an amount of x tokens for user u increases their balance by x, up to rounding errors. +{ b= balanceOf(u,t) } +mint(u,x,index) +{ balanceOf(u,t) = b + x } + +*/ +rule integrityMint(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e,asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke mint(e, a, x, index); + + uint256 balanceAfter = balanceOf(e, a); + assert balanceAfter == balancebefore+x; +} + +/** +Mint is additive, can performed either all at once or gradually +mint(u,x); mint(u,y) ~ mint(u,x+y) at the same timestamp +*/ +rule additiveMint(address a, uint256 x, uint256 y) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + storage initialStorage = lastStorage; + sinvoke mint(e, a, x, index); + sinvoke mint(e, a, y, index); + uint256 balanceScenario1 = balanceOf(e, a); + uint t = x + y; + sinvoke mint(e, a, t ,index) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "mint is not additive"; +} + +/** +Transfer of x amount of tokens from user u where receiver is user u’ +{bu = balanceOf(u) } + burn(u, u’, x) +{balanceOf(u) = bu - x } +*/ +rule integrityBurn(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke burn(e, a, x, index); + + uint256 balanceAfter = balanceOf(e, a); + assert balanceAfter == balancebefore - x; +} +/** +Minting is additive, i.e., it can be performed either all at once or in steps. + +burn(u, u’, x); burn(u, u’, y) ~ burn(u, u’, x+y) +*/ +rule additiveBurn(address a, uint256 x, uint256 y) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + storage initialStorage = lastStorage; + sinvoke burn(e, a, x, index); + sinvoke burn(e, a, y, index); + uint256 balanceScenario1 = balanceOf(e, a); + uint t = x + y; + sinvoke burn(e, a, t ,index) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "burn is not additive"; +} + +/** +Minting and burning are inverse operations. + +{bu = balanceOf(u) } +mint(u,x); burn(u, u, x) + {balanceOf(u) = bu } +*/ +rule inverseMintBurn(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke mint(e, a, x, index); + sinvoke burn(e, a, x, index); + uint256 balanceAfter = balanceOf(e, a); + assert balancebefore == balanceAfter, "burn is not inverse of mint"; +} + + + diff --git a/specs/harness/LendingPoolHarnessForVariableDebtToken.sol b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol new file mode 100644 index 00000000..a6ffb6f2 --- /dev/null +++ b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol @@ -0,0 +1,214 @@ +pragma solidity ^0.6.8; +pragma experimental ABIEncoderV2; + +import { + ReserveConfiguration +} from '../../contracts/libraries/configuration/ReserveConfiguration.sol'; +import {UserConfiguration} from '../../contracts/libraries/configuration/UserConfiguration.sol'; +import {ReserveLogic} from '../../contracts/libraries/logic/ReserveLogic.sol'; +import {ILendingPool} from '../../contracts/interfaces/ILendingPool.sol'; +import {LendingPool} from '../../contracts/lendingpool/LendingPool.sol'; + +/* +Certora: Harness that delegates calls to the original LendingPool. +Used for the verification of the VariableDebtToken contract. +*/ +contract LendingPoolHarnessForVariableDebtToken is ILendingPool { + LendingPool private originalPool; + + function deposit( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external override { + originalPool.deposit(asset, amount, onBehalfOf, referralCode); + } + + function withdraw(address asset, uint256 amount) external override { + originalPool.withdraw(asset, amount); + } + + function getBorrowAllowance( + address fromUser, + address toUser, + address asset, + uint256 interestRateMode + ) external override view returns (uint256) { + return originalPool.getBorrowAllowance(fromUser, toUser, asset, interestRateMode); + } + + function delegateBorrowAllowance( + address asset, + address user, + uint256 interestRateMode, + uint256 amount + ) external override { + originalPool.delegateBorrowAllowance(asset, user, interestRateMode, amount); + } + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external override { + originalPool.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf); + } + + function repay( + address asset, + uint256 amount, + uint256 rateMode, + address onBehalfOf + ) external override { + originalPool.repay(asset, amount, rateMode, onBehalfOf); + } + + function swapBorrowRateMode(address asset, uint256 rateMode) external override { + originalPool.swapBorrowRateMode(asset, rateMode); + } + + function rebalanceStableBorrowRate(address asset, address user) external override { + originalPool.rebalanceStableBorrowRate(asset, user); + } + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override { + originalPool.setUserUseReserveAsCollateral(asset, useAsCollateral); + } + + function liquidationCall( + address collateral, + address asset, + address user, + uint256 purchaseAmount, + bool receiveAToken + ) external override { + originalPool.liquidationCall(collateral, asset, user, purchaseAmount, receiveAToken); + } + + function getReservesList() external override view returns (address[] memory) { + return originalPool.getReservesList(); + } + + function getReserveData(address asset) + external + override + view + returns (ReserveLogic.ReserveData memory) + { + return originalPool.getReserveData(asset); + } + + function getUserConfiguration(address user) + external + override + view + returns (UserConfiguration.Map memory) + { + return originalPool.getUserConfiguration(user); + } + + function getUserAccountData(address user) + external + override + view + returns ( + uint256 totalCollateralETH, + uint256 totalBorrowsETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ) + { + return originalPool.getUserAccountData(user); + } + + function initReserve( + address asset, + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress + ) external override { + originalPool.initReserve( + asset, + aTokenAddress, + stableDebtAddress, + variableDebtAddress, + interestRateStrategyAddress + ); + } + + function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) + external + override + { + originalPool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); + } + + function setConfiguration(address asset, uint256 configuration) external override { + originalPool.setConfiguration(asset, configuration); + } + + function getConfiguration(address asset) + external + override + view + returns (ReserveConfiguration.Map memory) + { + return originalPool.getConfiguration(asset); + } + + mapping(uint256 => uint256) private reserveNormalizedIncome; + + function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + require(reserveNormalizedIncome[block.timestamp] == 1e27); + return reserveNormalizedIncome[block.timestamp]; + } + + mapping(uint256 => uint256) private reserveNormalizedVariableDebt; + + function getReserveNormalizedVariableDebt(address asset) + external + override + view + returns (uint256) + { + require(reserveNormalizedVariableDebt[block.timestamp] == 1e27); + return reserveNormalizedVariableDebt[block.timestamp]; + } + + function setPause(bool val) external override { + originalPool.setPause(val); + } + + function paused() external override view returns (bool) { + return originalPool.paused(); + } + + function flashLoan( + address receiver, + address[] calldata assets, + uint256[] calldata amounts, + uint256 mode, + address onBehalfOf, + bytes calldata params, + uint16 referralCode + ) external override { + originalPool.flashLoan(receiver, assets, amounts, mode, onBehalfOf, params, referralCode); + } + + function finalizeTransfer( + address asset, + address from, + address to, + uint256 amount, + uint256 balanceFromAfter, + uint256 balanceToBefore + ) external override { + originalPool.finalizeTransfer(asset, from, to, amount, balanceFromAfter, balanceToBefore); + } +} diff --git a/specs/harness/StableDebtTokenHarness.sol b/specs/harness/StableDebtTokenHarness.sol new file mode 100644 index 00000000..3daf2261 --- /dev/null +++ b/specs/harness/StableDebtTokenHarness.sol @@ -0,0 +1,26 @@ +pragma solidity ^0.6.8; + +import {StableDebtToken} from '../../contracts/tokenization/StableDebtToken.sol'; +import {IncentivizedERC20} from '../../contracts/tokenization/IncentivizedERC20.sol'; + +contract StableDebtTokenHarness is StableDebtToken { + constructor( + address pool, + address underlyingAsset, + string memory name, + string memory symbol, + address incentivesController + ) public StableDebtToken(pool, underlyingAsset, name, symbol, incentivesController) {} + + function balanceOf(address account) public override view returns (uint256) { + return IncentivizedERC20.balanceOf(account); + } + + function _calcTotalSupply(uint256 avgRate) internal override view returns (uint256) { + return IncentivizedERC20.totalSupply(); + } + + function getIncentivesController() public view returns (address) { + return address(_incentivesController); + } +} diff --git a/specs/harness/UserConfigurationHarness.sol b/specs/harness/UserConfigurationHarness.sol new file mode 100644 index 00000000..0ab1c495 --- /dev/null +++ b/specs/harness/UserConfigurationHarness.sol @@ -0,0 +1,56 @@ +pragma solidity ^0.6.8; +pragma experimental ABIEncoderV2; + +import {UserConfiguration} from '../../contracts/libraries/configuration/UserConfiguration.sol'; + +/* +A wrapper contract for calling functions from the library UserConfiguration. +*/ +contract UserConfigurationHarness { + UserConfiguration.Map internal usersConfig; + + function setBorrowing( + address user, + uint256 reserveIndex, + bool borrowing + ) public { + UserConfiguration.setBorrowing(usersConfig, reserveIndex, borrowing); + } + + function setUsingAsCollateral( + address user, + uint256 reserveIndex, + bool _usingAsCollateral + ) public { + UserConfiguration.setUsingAsCollateral(usersConfig, reserveIndex, _usingAsCollateral); + } + + function isUsingAsCollateralOrBorrowing(address user, uint256 reserveIndex) + public + view + returns (bool) + { + return UserConfiguration.isUsingAsCollateralOrBorrowing(usersConfig, reserveIndex); + } + + function isBorrowing(address user, uint256 reserveIndex) public view returns (bool) { + return UserConfiguration.isBorrowing(usersConfig, reserveIndex); + } + + function isUsingAsCollateral(address user, uint256 reserveIndex) public view returns (bool) { + return UserConfiguration.isUsingAsCollateral(usersConfig, reserveIndex); + } + + function isBorrowingAny(address user) public view returns (bool) { + return UserConfiguration.isBorrowingAny(usersConfig); + } + + function isEmpty(address user) public view returns (bool) { + return UserConfiguration.isEmpty(usersConfig); + } + + /* + Mimics the original constructor of the contract. + */ + function init_state() public {} +} diff --git a/test/addresses-provider-registry.spec.ts b/test/addresses-provider-registry.spec.ts index d7b148e7..caa135e2 100644 --- a/test/addresses-provider-registry.spec.ts +++ b/test/addresses-provider-registry.spec.ts @@ -19,10 +19,10 @@ makeSuite('AddressesProviderRegistry', (testEnv: TestEnv) => { it('tries to register an addresses provider with id 0', async () => { const {users, registry} = testEnv; - const {INVALID_ADDRESSES_PROVIDER_ID} = ProtocolErrors; + const {LPAPR_INVALID_ADDRESSES_PROVIDER_ID} = ProtocolErrors; await expect(registry.registerAddressesProvider(users[2].address, '0')).to.be.revertedWith( - INVALID_ADDRESSES_PROVIDER_ID + LPAPR_INVALID_ADDRESSES_PROVIDER_ID ); }); @@ -62,22 +62,22 @@ makeSuite('AddressesProviderRegistry', (testEnv: TestEnv) => { }); it('Tries to remove a unregistered addressesProvider', async () => { - const {PROVIDER_NOT_REGISTERED} = ProtocolErrors; + const {LPAPR_PROVIDER_NOT_REGISTERED} = ProtocolErrors; const {users, registry} = testEnv; await expect(registry.unregisterAddressesProvider(users[2].address)).to.be.revertedWith( - PROVIDER_NOT_REGISTERED + LPAPR_PROVIDER_NOT_REGISTERED ); }); it('Tries to remove a unregistered addressesProvider', async () => { - const {PROVIDER_NOT_REGISTERED} = ProtocolErrors; + const {LPAPR_PROVIDER_NOT_REGISTERED} = ProtocolErrors; const {users, registry} = testEnv; await expect(registry.unregisterAddressesProvider(users[2].address)).to.be.revertedWith( - PROVIDER_NOT_REGISTERED + LPAPR_PROVIDER_NOT_REGISTERED ); }); diff --git a/test/atoken-modifiers.spec.ts b/test/atoken-modifiers.spec.ts index 98495dec..e1b00203 100644 --- a/test/atoken-modifiers.spec.ts +++ b/test/atoken-modifiers.spec.ts @@ -3,19 +3,19 @@ import {makeSuite, TestEnv} from './helpers/make-suite'; import {ProtocolErrors} from '../helpers/types'; makeSuite('AToken: Modifiers', (testEnv: TestEnv) => { - const {CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; + const {AT_CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; it('Tries to invoke mint not being the LendingPool', async () => { const {deployer, aDai} = testEnv; await expect(aDai.mint(deployer.address, '1', '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); it('Tries to invoke burn not being the LendingPool', async () => { const {deployer, aDai} = testEnv; await expect(aDai.burn(deployer.address, deployer.address, '1', '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); @@ -23,13 +23,13 @@ makeSuite('AToken: Modifiers', (testEnv: TestEnv) => { const {deployer, users, aDai} = testEnv; await expect( aDai.transferOnLiquidation(deployer.address, users[0].address, '1') - ).to.be.revertedWith(CALLER_MUST_BE_LENDING_POOL); + ).to.be.revertedWith(AT_CALLER_MUST_BE_LENDING_POOL); }); it('Tries to invoke transferUnderlyingTo not being the LendingPool', async () => { const {deployer, users, aDai} = testEnv; await expect(aDai.transferUnderlyingTo(deployer.address, '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); }); diff --git a/test/atoken-transfer.spec.ts b/test/atoken-transfer.spec.ts index eb3cef4b..778c9d60 100644 --- a/test/atoken-transfer.spec.ts +++ b/test/atoken-transfer.spec.ts @@ -14,10 +14,7 @@ makeSuite('AToken: Transfer', (testEnv: TestEnv) => { const { INVALID_FROM_BALANCE_AFTER_TRANSFER, INVALID_TO_BALANCE_AFTER_TRANSFER, - // ZERO_COLLATERAL, - COLLATERAL_BALANCE_IS_0, - TRANSFER_NOT_ALLOWED, - IS_PAUSED, + VL_TRANSFER_NOT_ALLOWED, } = ProtocolErrors; it('User 0 deposits 1000 DAI, transfers to user 1', async () => { @@ -86,8 +83,8 @@ makeSuite('AToken: Transfer', (testEnv: TestEnv) => { await expect( aDai.connect(users[1].signer).transfer(users[0].address, aDAItoTransfer), - TRANSFER_NOT_ALLOWED - ).to.be.revertedWith(TRANSFER_NOT_ALLOWED); + VL_TRANSFER_NOT_ALLOWED + ).to.be.revertedWith(VL_TRANSFER_NOT_ALLOWED); }); it('User 1 tries to transfer a small amount of DAI used as collateral back to user 0', async () => { diff --git a/test/configurator.spec.ts b/test/configurator.spec.ts index 788add5c..315dc26e 100644 --- a/test/configurator.spec.ts +++ b/test/configurator.spec.ts @@ -11,13 +11,13 @@ const {expect} = require('chai'); makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const { - CALLER_NOT_AAVE_ADMIN, - RESERVE_LIQUIDITY_NOT_0, - INVALID_LTV, - INVALID_LIQ_THRESHOLD, - INVALID_LIQ_BONUS, - INVALID_DECIMALS, - INVALID_RESERVE_FACTOR, + LPC_CALLER_NOT_AAVE_ADMIN, + LPC_RESERVE_LIQUIDITY_NOT_0, + RC_INVALID_LTV, + RC_INVALID_LIQ_THRESHOLD, + RC_INVALID_LIQ_BONUS, + RC_INVALID_DECIMALS, + RC_INVALID_RESERVE_FACTOR, } = ProtocolErrors; it('Reverts trying to set an invalid LTV', async () => { @@ -25,7 +25,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const invalidLtv = 65536; - await expect(configurator.setLtv(weth.address, invalidLtv)).to.be.revertedWith(INVALID_LTV); + await expect(configurator.setLtv(weth.address, invalidLtv)).to.be.revertedWith(RC_INVALID_LTV); }); it('Reverts trying to set an invalid liquidation threshold', async () => { @@ -35,7 +35,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { await expect( configurator.setLiquidationThreshold(weth.address, invalidLiqThreshold) - ).to.be.revertedWith(INVALID_LIQ_THRESHOLD); + ).to.be.revertedWith(RC_INVALID_LIQ_THRESHOLD); }); it('Reverts trying to set an invalid liquidation bonus', async () => { @@ -45,7 +45,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { await expect( configurator.setLiquidationBonus(weth.address, invalidLiqBonus) - ).to.be.revertedWith(INVALID_LIQ_BONUS); + ).to.be.revertedWith(RC_INVALID_LIQ_BONUS); }); it('Reverts trying to set an invalid reserve decimals', async () => { @@ -54,7 +54,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const invalidDecimals = 256; await expect(configurator.setReserveDecimals(weth.address, invalidDecimals)).to.be.revertedWith( - INVALID_DECIMALS + RC_INVALID_DECIMALS ); }); @@ -65,7 +65,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { await expect( configurator.setReserveFactor(weth.address, invalidReserveFactor) - ).to.be.revertedWith(INVALID_RESERVE_FACTOR); + ).to.be.revertedWith(RC_INVALID_RESERVE_FACTOR); }); it('Deactivates the ETH reserve', async () => { @@ -87,16 +87,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).deactivateReserve(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on activateReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).activateReserve(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Freezes the ETH reserve', async () => { @@ -156,16 +156,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).freezeReserve(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on unfreezeReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).unfreezeReserve(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Deactivates the ETH reserve for borrowing', async () => { @@ -228,21 +228,22 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).disableBorrowingOnReserve(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on enableBorrowingOnReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).enableBorrowingOnReserve(weth.address, true), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Deactivates the ETH reserve as collateral', async () => { const {configurator, helpersContract, weth} = testEnv; - await configurator.disableReserveAsCollateral(weth.address); + await configurator.configureReserveAsCollateral(weth.address, 0, 0, 0); + const { decimals, ltv, @@ -260,15 +261,15 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { expect(isFrozen).to.be.equal(false); expect(decimals).to.be.equal(18); expect(ltv).to.be.equal(0); - expect(liquidationThreshold).to.be.equal(8000); - expect(liquidationBonus).to.be.equal(10500); + expect(liquidationThreshold).to.be.equal(0); + expect(liquidationBonus).to.be.equal(0); expect(stableBorrowRateEnabled).to.be.equal(true); expect(reserveFactor).to.be.equal(0); }); it('Activates the ETH reserve as collateral', async () => { const {configurator, helpersContract, weth} = testEnv; - await configurator.enableReserveAsCollateral(weth.address, '7500', '8000', '10500'); + await configurator.configureReserveAsCollateral(weth.address, '7500', '8000', '10500'); const { decimals, @@ -293,22 +294,14 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { expect(reserveFactor).to.be.equal(0); }); - it('Check the onlyAaveAdmin on disableReserveAsCollateral ', async () => { - const {configurator, users, weth} = testEnv; - await expect( - configurator.connect(users[2].signer).disableReserveAsCollateral(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); - }); - - it('Check the onlyAaveAdmin on enableReserveAsCollateral ', async () => { + it('Check the onlyAaveAdmin on configureReserveAsCollateral ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator .connect(users[2].signer) - .enableReserveAsCollateral(weth.address, '75', '80', '105'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + .configureReserveAsCollateral(weth.address, '7500', '8000', '10500'), + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Disable stable borrow rate on the ETH reserve', async () => { @@ -367,16 +360,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).disableReserveStableRate(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on enableReserveStableRate', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).enableReserveStableRate(weth.address), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Changes LTV of the reserve', async () => { @@ -409,8 +402,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLtv(weth.address, '75'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Changes the reserve factor of the reserve', async () => { @@ -443,8 +436,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setReserveFactor(weth.address, '2000'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Changes liquidation threshold of the reserve', async () => { @@ -477,8 +470,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationThreshold(weth.address, '80'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Changes liquidation bonus of the reserve', async () => { @@ -511,24 +504,24 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationBonus(weth.address, '80'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on setReserveDecimals', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setReserveDecimals(weth.address, '80'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Check the onlyAaveAdmin on setLiquidationBonus', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationBonus(weth.address, '80'), - CALLER_NOT_AAVE_ADMIN - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + LPC_CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Reverts when trying to disable the DAI reserve with liquidity on it', async () => { @@ -545,7 +538,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { await expect( configurator.deactivateReserve(dai.address), - RESERVE_LIQUIDITY_NOT_0 - ).to.be.revertedWith(RESERVE_LIQUIDITY_NOT_0); + LPC_RESERVE_LIQUIDITY_NOT_0 + ).to.be.revertedWith(LPC_RESERVE_LIQUIDITY_NOT_0); }); }); diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 8a8ab4e3..387a091a 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -8,21 +8,23 @@ import {MockFlashLoanReceiver} from '../types/MockFlashLoanReceiver'; import {ProtocolErrors, eContractid} from '../helpers/types'; import {VariableDebtToken} from '../types/VariableDebtToken'; import {StableDebtToken} from '../types/StableDebtToken'; -import {getMockFlashLoanReceiver} from '../helpers/contracts-getters'; +import { + getMockFlashLoanReceiver, + getStableDebtToken, + getVariableDebtToken, +} from '../helpers/contracts-getters'; const {expect} = require('chai'); makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { - COLLATERAL_BALANCE_IS_0, - REQUESTED_AMOUNT_TOO_SMALL, + VL_COLLATERAL_BALANCE_IS_0, TRANSFER_AMOUNT_EXCEEDS_BALANCE, - INVALID_FLASHLOAN_MODE, + LP_INVALID_FLASHLOAN_MODE, SAFEERC20_LOWLEVEL_CALL, - IS_PAUSED, - INVALID_FLASH_LOAN_EXECUTOR_RETURN, - BORROW_ALLOWANCE_ARE_NOT_ENOUGH, + LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN, + LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH, } = ProtocolErrors; before(async () => { @@ -48,7 +50,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], _mockFlashLoanReceiver.address, '0x10', '0' @@ -78,7 +80,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], ['1000720000000000000'], - 0, + [0], _mockFlashLoanReceiver.address, '0x10', '0' @@ -110,7 +112,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], caller.address, '0x10', '0' @@ -131,12 +133,12 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], caller.address, '0x10', '0' ) - ).to.be.revertedWith(INVALID_FLASH_LOAN_EXECUTOR_RETURN); + ).to.be.revertedWith(LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN); }); it('Takes a WETH flashloan with an invalid mode. (revert expected)', async () => { @@ -152,12 +154,12 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 4, + [4], caller.address, '0x10', '0' ) - ).to.be.revertedWith(INVALID_FLASHLOAN_MODE); + ).to.be.reverted; }); it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan with mode = 2, does not return the funds. A variable loan for caller is created', async () => { @@ -181,7 +183,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 2, + [2], caller.address, '0x10', '0' @@ -190,10 +192,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { weth.address ); - const wethDebtToken = await getContract<VariableDebtToken>( - eContractid.VariableDebtToken, - variableDebtTokenAddress - ); + const wethDebtToken = await getVariableDebtToken(variableDebtTokenAddress); const callerDebt = await wethDebtToken.balanceOf(caller.address); @@ -209,7 +208,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], ['1004415000000000000'], //slightly higher than the available liquidity - 2, + [2], caller.address, '0x10', '0' @@ -227,7 +226,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { deployer.address, [weth.address], ['1000000000000000000'], - 2, + [2], caller.address, '0x10', '0' @@ -259,7 +258,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], - 0, + [0], _mockFlashLoanReceiver.address, '0x10', '0' @@ -302,12 +301,12 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], - 2, + [2], caller.address, '0x10', '0' ) - ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); + ).to.be.revertedWith(VL_COLLATERAL_BALANCE_IS_0); }); it('Caller deposits 5 WETH as collateral, Takes a USDC flashloan with mode = 2, does not return the funds. A loan for caller is created', async () => { @@ -333,7 +332,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], - 2, + [2], caller.address, '0x10', '0' @@ -342,10 +341,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { usdc.address ); - const usdcDebtToken = await getContract<VariableDebtToken>( - eContractid.VariableDebtToken, - variableDebtTokenAddress - ); + const usdcDebtToken = await getVariableDebtToken(variableDebtTokenAddress); const callerDebt = await usdcDebtToken.balanceOf(caller.address); @@ -376,7 +372,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [flashAmount], - 0, + [0], caller.address, '0x10', '0' @@ -399,7 +395,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [flashAmount], - 1, + [1], caller.address, '0x10', '0' @@ -407,10 +403,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const {stableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses(weth.address); - const wethDebtToken = await getContract<StableDebtToken>( - eContractid.VariableDebtToken, - stableDebtTokenAddress - ); + const wethDebtToken = await getStableDebtToken(stableDebtTokenAddress); const callerDebt = await wethDebtToken.balanceOf(caller.address); @@ -445,12 +438,12 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [flashAmount], - 1, + [1], onBehalfOf.address, '0x10', '0' ) - ).to.be.revertedWith(BORROW_ALLOWANCE_ARE_NOT_ENOUGH); + ).to.be.revertedWith(LP_BORROW_ALLOWANCE_ARE_NOT_ENOUGH); }); it('Caller takes a WETH flashloan with mode = 1 onBehalfOf user with allowance. A loan for onBehalfOf is creatd.', async () => { @@ -464,7 +457,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { // Deposited for onBehalfOf user already, delegate borrow allowance await pool .connect(onBehalfOf.signer) - .delegateBorrowAllowance(weth.address, caller.address, 1, flashAmount); + .delegateBorrowAllowance([weth.address], caller.address, [1], [flashAmount]); await _mockFlashLoanReceiver.setFailExecutionTransfer(true); @@ -474,7 +467,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [flashAmount], - 1, + [1], onBehalfOf.address, '0x10', '0' @@ -482,10 +475,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const {stableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses(weth.address); - const wethDebtToken = await getContract<StableDebtToken>( - eContractid.VariableDebtToken, - stableDebtTokenAddress - ); + const wethDebtToken = await getStableDebtToken(stableDebtTokenAddress); const onBehalfOfDebt = await wethDebtToken.balanceOf(onBehalfOf.address); diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 422b0455..d998962b 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -231,7 +231,7 @@ export const withdraw = async ( if (expectedResult === 'success') { const txResult = await waitForTx( - await pool.connect(user.signer).withdraw(reserve, amountToWithdraw) + await pool.connect(user.signer).withdraw(reserve, amountToWithdraw, user.address) ); const { @@ -269,15 +269,17 @@ export const withdraw = async ( // ); // }); } else if (expectedResult === 'revert') { - await expect(pool.connect(user.signer).withdraw(reserve, amountToWithdraw), revertMessage).to.be - .reverted; + await expect( + pool.connect(user.signer).withdraw(reserve, amountToWithdraw, user.address), + revertMessage + ).to.be.reverted; } }; export const delegateBorrowAllowance = async ( - reserveSymbol: string, - amount: string, - interestRateMode: string, + reserveSymbols: string[], + amounts: string[], + interestRateModes: string[], user: SignerWithAddress, receiver: tEthereumAddress, expectedResult: string, @@ -286,20 +288,32 @@ export const delegateBorrowAllowance = async ( ) => { const {pool} = testEnv; - const reserve = await getReserveAddressFromSymbol(reserveSymbol); - const amountToDelegate = await convertToCurrencyDecimals(reserve, amount); + const reserves: tEthereumAddress[] = []; + const amountsToDelegate: tEthereumAddress[] = []; + for (const reserveSymbol of reserveSymbols) { + const newLength = reserves.push(await getReserveAddressFromSymbol(reserveSymbol)); + amountsToDelegate.push( + await ( + await convertToCurrencyDecimals(reserves[newLength - 1], amounts[newLength - 1]) + ).toString() + ); + } const delegateAllowancePromise = pool .connect(user.signer) - .delegateBorrowAllowance(reserve, receiver, interestRateMode, amountToDelegate.toString()); + .delegateBorrowAllowance(reserves, receiver, interestRateModes, amountsToDelegate); if (expectedResult === 'revert') { await expect(delegateAllowancePromise, revertMessage).to.be.reverted; return; } else { await delegateAllowancePromise; - expect( - (await pool.getBorrowAllowance(user.address, receiver, reserve, interestRateMode)).toString() - ).to.be.equal(amountToDelegate.toString(), 'borrowAllowance are set incorrectly'); + for (const [i, reserve] of reserves.entries()) { + expect( + ( + await pool.getBorrowAllowance(user.address, receiver, reserve, interestRateModes[i]) + ).toString() + ).to.be.equal(amountsToDelegate[i], 'borrowAllowance are set incorrectly'); + } } }; diff --git a/test/helpers/scenario-engine.ts b/test/helpers/scenario-engine.ts index bb4f82f8..fe2e302a 100644 --- a/test/helpers/scenario-engine.ts +++ b/test/helpers/scenario-engine.ts @@ -121,9 +121,9 @@ const executeAction = async (action: Action, users: SignerWithAddress[], testEnv } await delegateBorrowAllowance( - reserve, - amount, - rateMode, + [reserve], + [amount], + [rateMode], user, toUser, expected, diff --git a/test/liquidation-atoken.spec.ts b/test/liquidation-atoken.spec.ts index 5b2fd527..8d4ba803 100644 --- a/test/liquidation-atoken.spec.ts +++ b/test/liquidation-atoken.spec.ts @@ -17,11 +17,11 @@ const {expect} = chai; makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => { const { - HEALTH_FACTOR_NOT_BELOW_THRESHOLD, + LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD, INVALID_HF, - SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER, - COLLATERAL_CANNOT_BE_LIQUIDATED, - IS_PAUSED, + LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER, + LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED, + LP_IS_PAUSED, } = ProtocolErrors; it('LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1', async () => { @@ -80,7 +80,7 @@ makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => //someone tries to liquidate user 2 await expect( pool.liquidationCall(weth.address, dai.address, borrower.address, 1, true) - ).to.be.revertedWith(HEALTH_FACTOR_NOT_BELOW_THRESHOLD); + ).to.be.revertedWith(LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD); }); it('LIQUIDATION - Drop the health factor below 1', async () => { @@ -105,7 +105,7 @@ makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => //user 2 tries to borrow await expect( pool.liquidationCall(weth.address, weth.address, borrower.address, oneEther.toString(), true) - ).revertedWith(SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); + ).revertedWith(LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); }); it('LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral', async () => { @@ -114,7 +114,7 @@ makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => await expect( pool.liquidationCall(dai.address, dai.address, borrower.address, oneEther.toString(), true) - ).revertedWith(COLLATERAL_CANNOT_BE_LIQUIDATED); + ).revertedWith(LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED); }); it('LIQUIDATION - Liquidates the borrow', async () => { diff --git a/test/pausable-functions.spec.ts b/test/pausable-functions.spec.ts index 7220cb61..9c7f6473 100644 --- a/test/pausable-functions.spec.ts +++ b/test/pausable-functions.spec.ts @@ -13,8 +13,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { - IS_PAUSED, - TRANSFER_NOT_ALLOWED, + LP_IS_PAUSED, INVALID_FROM_BALANCE_AFTER_TRANSFER, INVALID_TO_BALANCE_AFTER_TRANSFER, } = ProtocolErrors; @@ -45,7 +44,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // User 0 tries the transfer to User 1 await expect( aDai.connect(users[0].signer).transfer(users[1].address, amountDAItoDeposit) - ).to.revertedWith(IS_PAUSED); + ).to.revertedWith(LP_IS_PAUSED); const pausedFromBalance = await aDai.balanceOf(users[0].address); const pausedToBalance = await aDai.balanceOf(users[1].address); @@ -92,7 +91,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { await configurator.setPoolPause(true); await expect( pool.connect(users[0].signer).deposit(dai.address, amountDAItoDeposit, users[0].address, '0') - ).to.revertedWith(IS_PAUSED); + ).to.revertedWith(LP_IS_PAUSED); // Configurator unpauses the pool await configurator.setPoolPause(false); @@ -116,8 +115,8 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // user tries to burn await expect( - pool.connect(users[0].signer).withdraw(dai.address, amountDAItoDeposit) - ).to.revertedWith(IS_PAUSED); + pool.connect(users[0].signer).withdraw(dai.address, amountDAItoDeposit, users[0].address) + ).to.revertedWith(LP_IS_PAUSED); // Configurator unpauses the pool await configurator.setPoolPause(false); @@ -133,8 +132,8 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Try to execute liquidation await expect( - pool.connect(user.signer).delegateBorrowAllowance(dai.address, toUser.address, '1', '1') - ).revertedWith(IS_PAUSED); + pool.connect(user.signer).delegateBorrowAllowance([dai.address], toUser.address, ['1'], ['1']) + ).revertedWith(LP_IS_PAUSED); // Unpause the pool await configurator.setPoolPause(false); @@ -150,7 +149,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Try to execute liquidation await expect( pool.connect(user.signer).borrow(dai.address, '1', '1', '0', user.address) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause the pool await configurator.setPoolPause(false); @@ -165,7 +164,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Try to execute liquidation await expect(pool.connect(user.signer).repay(dai.address, '1', '1', user.address)).revertedWith( - IS_PAUSED + LP_IS_PAUSED ); // Unpause the pool @@ -191,12 +190,12 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [flashAmount], - 1, + [1], caller.address, '0x10', '0' ) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause pool await configurator.setPoolPause(false); @@ -277,7 +276,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Do liquidation expect( pool.liquidationCall(weth.address, usdc.address, borrower.address, amountToLiquidate, true) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause pool await configurator.setPoolPause(false); @@ -306,7 +305,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Try to repay await expect( pool.connect(user.signer).swapBorrowRateMode(usdc.address, RateMode.Stable) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause pool await configurator.setPoolPause(false); @@ -320,7 +319,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { await expect( pool.connect(user.signer).rebalanceStableBorrowRate(dai.address, user.address) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause pool await configurator.setPoolPause(false); @@ -340,7 +339,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { await expect( pool.connect(user.signer).setUserUseReserveAsCollateral(weth.address, false) - ).revertedWith(IS_PAUSED); + ).revertedWith(LP_IS_PAUSED); // Unpause pool await configurator.setPoolPause(false); diff --git a/test/stable-token.spec.ts b/test/stable-token.spec.ts index fea265c6..02348d8b 100644 --- a/test/stable-token.spec.ts +++ b/test/stable-token.spec.ts @@ -3,9 +3,10 @@ import {makeSuite, TestEnv} from './helpers/make-suite'; import {ProtocolErrors, eContractid} from '../helpers/types'; import {getContract} from '../helpers/contracts-helpers'; import {StableDebtToken} from '../types/StableDebtToken'; +import {getStableDebtToken} from '../helpers/contracts-getters'; makeSuite('Stable debt token tests', (testEnv: TestEnv) => { - const {CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; + const {AT_CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; it('Tries to invoke mint not being the LendingPool', async () => { const {deployer, pool, dai, helpersContract} = testEnv; @@ -13,13 +14,10 @@ makeSuite('Stable debt token tests', (testEnv: TestEnv) => { const daiStableDebtTokenAddress = (await helpersContract.getReserveTokensAddresses(dai.address)) .stableDebtTokenAddress; - const stableDebtContract = await getContract<StableDebtToken>( - eContractid.StableDebtToken, - daiStableDebtTokenAddress - ); + const stableDebtContract = await getStableDebtToken(daiStableDebtTokenAddress); await expect(stableDebtContract.mint(deployer.address, '1', '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); @@ -29,16 +27,13 @@ makeSuite('Stable debt token tests', (testEnv: TestEnv) => { const daiStableDebtTokenAddress = (await helpersContract.getReserveTokensAddresses(dai.address)) .stableDebtTokenAddress; - const stableDebtContract = await getContract<StableDebtToken>( - eContractid.StableDebtToken, - daiStableDebtTokenAddress - ); + const stableDebtContract = await getStableDebtToken(daiStableDebtTokenAddress); const name = await stableDebtContract.name(); expect(name).to.be.equal('Aave stable debt bearing DAI'); await expect(stableDebtContract.burn(deployer.address, '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); }); diff --git a/test/upgradeability.spec.ts b/test/upgradeability.spec.ts index 72d818d7..93fb1ddd 100644 --- a/test/upgradeability.spec.ts +++ b/test/upgradeability.spec.ts @@ -6,17 +6,27 @@ import {MockAToken} from '../types/MockAToken'; import {MockStableDebtToken} from '../types/MockStableDebtToken'; import {MockVariableDebtToken} from '../types/MockVariableDebtToken'; import {ZERO_ADDRESS} from '../helpers/constants'; -import {getAToken} from '../helpers/contracts-getters'; +import { + getAToken, + getMockStableDebtToken, + getMockVariableDebtToken, + getVariableDebtToken, +} from '../helpers/contracts-getters'; +import { + deployMockAToken, + deployMockStableDebtToken, + deployMockVariableDebtToken, +} from '../helpers/contracts-deployments'; makeSuite('Upgradeability', (testEnv: TestEnv) => { - const {CALLER_NOT_AAVE_ADMIN} = ProtocolErrors; + const {LPC_CALLER_NOT_AAVE_ADMIN} = ProtocolErrors; let newATokenAddress: string; let newStableTokenAddress: string; let newVariableTokenAddress: string; before('deploying instances', async () => { const {dai, pool} = testEnv; - const aTokenInstance = await deployContract<MockAToken>(eContractid.MockAToken, [ + const aTokenInstance = await deployMockAToken([ pool.address, dai.address, ZERO_ADDRESS, @@ -25,27 +35,21 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { ZERO_ADDRESS, ]); - const stableDebtTokenInstance = await deployContract<MockStableDebtToken>( - eContractid.MockStableDebtToken, - [ - pool.address, - dai.address, - 'Aave stable debt bearing DAI updated', - 'stableDebtDAI', - ZERO_ADDRESS, - ] - ); + const stableDebtTokenInstance = await deployMockStableDebtToken([ + pool.address, + dai.address, + 'Aave stable debt bearing DAI updated', + 'stableDebtDAI', + ZERO_ADDRESS, + ]); - const variableDebtTokenInstance = await deployContract<MockVariableDebtToken>( - eContractid.MockVariableDebtToken, - [ - pool.address, - dai.address, - 'Aave variable debt bearing DAI updated', - 'variableDebtDAI', - ZERO_ADDRESS, - ] - ); + const variableDebtTokenInstance = await deployMockVariableDebtToken([ + pool.address, + dai.address, + 'Aave variable debt bearing DAI updated', + 'variableDebtDAI', + ZERO_ADDRESS, + ]); newATokenAddress = aTokenInstance.address; newVariableTokenAddress = variableDebtTokenInstance.address; @@ -57,7 +61,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { await expect( configurator.connect(users[1].signer).updateAToken(dai.address, newATokenAddress) - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Upgrades the DAI Atoken implementation ', async () => { @@ -79,7 +83,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { configurator .connect(users[1].signer) .updateStableDebtToken(dai.address, newStableTokenAddress) - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Upgrades the DAI stable debt token implementation ', async () => { @@ -91,10 +95,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {stableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses(dai.address); - const debtToken = await getContract<MockStableDebtToken>( - eContractid.MockStableDebtToken, - stableDebtTokenAddress - ); + const debtToken = await getMockStableDebtToken(stableDebtTokenAddress); const tokenName = await debtToken.name(); @@ -108,7 +109,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { configurator .connect(users[1].signer) .updateVariableDebtToken(dai.address, newVariableTokenAddress) - ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); + ).to.be.revertedWith(LPC_CALLER_NOT_AAVE_ADMIN); }); it('Upgrades the DAI variable debt token implementation ', async () => { @@ -120,10 +121,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {variableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses(dai.address); - const debtToken = await getContract<MockStableDebtToken>( - eContractid.MockStableDebtToken, - variableDebtTokenAddress - ); + const debtToken = await getMockVariableDebtToken(variableDebtTokenAddress); const tokenName = await debtToken.name(); diff --git a/test/variable-debt-token.spec.ts b/test/variable-debt-token.spec.ts index e92c6d12..5e21f939 100644 --- a/test/variable-debt-token.spec.ts +++ b/test/variable-debt-token.spec.ts @@ -1,11 +1,10 @@ import {expect} from 'chai'; import {makeSuite, TestEnv} from './helpers/make-suite'; import {ProtocolErrors, TokenContractId, eContractid} from '../helpers/types'; -import {getContract} from '../helpers/contracts-helpers'; -import {VariableDebtToken} from '../types/VariableDebtToken'; +import {getVariableDebtToken} from '../helpers/contracts-getters'; makeSuite('Variable debt token tests', (testEnv: TestEnv) => { - const {CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; + const {AT_CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; it('Tries to invoke mint not being the LendingPool', async () => { const {deployer, pool, dai, helpersContract} = testEnv; @@ -14,13 +13,10 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { await helpersContract.getReserveTokensAddresses(dai.address) ).variableDebtTokenAddress; - const variableDebtContract = await getContract<VariableDebtToken>( - eContractid.VariableDebtToken, - daiVariableDebtTokenAddress - ); + const variableDebtContract = await getVariableDebtToken(daiVariableDebtTokenAddress); await expect(variableDebtContract.mint(deployer.address, '1', '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); @@ -31,13 +27,10 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { await helpersContract.getReserveTokensAddresses(dai.address) ).variableDebtTokenAddress; - const variableDebtContract = await getContract<VariableDebtToken>( - eContractid.VariableDebtToken, - daiVariableDebtTokenAddress - ); + const variableDebtContract = await getVariableDebtToken(daiVariableDebtTokenAddress); await expect(variableDebtContract.burn(deployer.address, '1', '1')).to.be.revertedWith( - CALLER_MUST_BE_LENDING_POOL + AT_CALLER_MUST_BE_LENDING_POOL ); }); });