From 9ad818996629b151ed835167e5d35cd942d9b6cf Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 23 Aug 2020 16:31:31 +0200 Subject: [PATCH 01/33] Removed reentrancy --- contracts/lendingpool/LendingPool.sol | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index ee429e6f..59c84382 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -87,7 +87,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { address asset, uint256 amount, uint16 referralCode - ) external override nonReentrant { + ) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); @@ -118,7 +118,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @param asset the address of the reserve * @param amount the underlying amount to be redeemed **/ - function withdraw(address asset, uint256 amount) external override nonReentrant { + function withdraw(address asset, uint256 amount) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; IAToken aToken = IAToken(reserve.aTokenAddress); @@ -169,7 +169,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 amount, uint256 interestRateMode, uint16 referralCode - ) external override nonReentrant { + ) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; @@ -236,7 +236,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 amount, uint256 _rateMode, address _onBehalfOf - ) external override nonReentrant { + ) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(_onBehalfOf, reserve); @@ -288,7 +288,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @param asset the address of the reserve on which the user borrowed * @param _rateMode the rate mode that the user wants to swap **/ - function swapBorrowRateMode(address asset, uint256 _rateMode) external override nonReentrant { + function swapBorrowRateMode(address asset, uint256 _rateMode) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); @@ -336,7 +336,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @param asset the address of the reserve * @param _user the address of the user to be rebalanced **/ - function rebalanceStableBorrowRate(address asset, address _user) external override nonReentrant { + function rebalanceStableBorrowRate(address asset, address _user) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); @@ -421,7 +421,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { address _user, uint256 _purchaseAmount, bool _receiveAToken - ) external override nonReentrant { + ) external override { address liquidationManager = addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line @@ -458,7 +458,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { address asset, uint256 amount, bytes calldata params - ) external override nonReentrant { + ) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; address aTokenAddress = reserve.aTokenAddress; From 70eb126b581dbcaf6712daea06f17e26d6732216 Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 23 Aug 2020 16:35:01 +0200 Subject: [PATCH 02/33] Removed ReentrancyGuard from LiquidationManager --- contracts/lendingpool/LendingPool.sol | 4 +--- contracts/lendingpool/LendingPoolLiquidationManager.sol | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 59c84382..6132025e 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -3,7 +3,6 @@ pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; -import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { VersionedInitializable @@ -31,7 +30,7 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; * @author Aave **/ -contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { +contract LendingPool is VersionedInitializable, ILendingPool { using SafeMath for uint256; using WadRayMath for uint256; using ReserveLogic for ReserveLogic.ReserveData; @@ -384,7 +383,6 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { function setUserUseReserveAsCollateral(address asset, bool _useAsCollateral) external override - nonReentrant { ReserveLogic.ReserveData storage reserve = _reserves[asset]; diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 17d08a03..21084154 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -3,8 +3,6 @@ pragma solidity ^0.6.8; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; -import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; -import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../libraries/openzeppelin-upgradeability/VersionedInitializable.sol'; @@ -27,7 +25,7 @@ import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; * @author Aave * @notice Implements the liquidation function. **/ -contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializable { +contract LendingPoolLiquidationManager is VersionedInitializable { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; From 9377a137f1c9c19c8fff7e6157e7e98a9adf94c2 Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 23 Aug 2020 16:49:23 +0200 Subject: [PATCH 03/33] Updated flashloan function --- contracts/lendingpool/LendingPool.sol | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 5f2c8e39..50386d6d 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -459,16 +459,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { address aTokenAddress = reserve.aTokenAddress; - //check that the reserve has enough available liquidity - uint256 availableLiquidityBefore = IERC20(asset).balanceOf(aTokenAddress); - //calculate amount fee uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); - require( - availableLiquidityBefore >= amount, - 'There is not enough liquidity available to borrow' - ); require(amountFee > 0, 'The requested amount is too small for a FlashLoan.'); //get the FlashLoanReceiver instance @@ -480,21 +473,12 @@ contract LendingPool is VersionedInitializable, ILendingPool { //execute action of the receiver receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); - //check that the actual balance of the core contract includes the returned amount - uint256 availableLiquidityAfter = IERC20(asset).balanceOf(aTokenAddress); - - require( - availableLiquidityAfter == availableLiquidityBefore.add(amountFee), - 'The actual balance of the protocol is inconsistent' - ); + //transfer from the receiver the amount plus the fee + IERC20(asset).safeTransferFrom(receiver, aTokenAddress, amount.add(amountFee)); //compounding the cumulated interest reserve.updateCumulativeIndexesAndTimestamp(); - uint256 totalLiquidityBefore = availableLiquidityBefore - .add(IERC20(reserve.variableDebtTokenAddress).totalSupply()) - .add(IERC20(reserve.stableDebtTokenAddress).totalSupply()); - //compounding the received fee into the reserve reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); From d833157cf47250ef0771940b8115c1f292e91e1d Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 23 Aug 2020 18:38:34 +0200 Subject: [PATCH 04/33] Updated flashloans to transferFrom the receiver instead of checking that the funds where sent back --- buidler.config.ts | 2 +- .../flashloan/base/FlashLoanReceiverBase.sol | 19 +- .../interfaces/IFlashLoanReceiver.sol | 1 - contracts/lendingpool/LendingPool.sol | 6 +- .../mocks/flashloan/MockFlashLoanReceiver.sol | 26 +- deployed-contracts.json | 86 +- helpers/types.ts | 2 +- test/flashloan.spec.ts | 13 +- tests.log | 2750 +++++++++++++++++ 9 files changed, 2819 insertions(+), 86 deletions(-) create mode 100644 tests.log diff --git a/buidler.config.ts b/buidler.config.ts index d21f5293..d0657ab0 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -8,7 +8,7 @@ usePlugin('buidler-typechain'); usePlugin('solidity-coverage'); usePlugin('@nomiclabs/buidler-waffle'); usePlugin('@nomiclabs/buidler-etherscan'); -//usePlugin('buidler-gas-reporter'); +usePlugin('buidler-gas-reporter'); const DEFAULT_BLOCK_GAS_LIMIT = 10000000; const DEFAULT_GAS_PRICE = 10; diff --git a/contracts/flashloan/base/FlashLoanReceiverBase.sol b/contracts/flashloan/base/FlashLoanReceiverBase.sol index c4aaecd6..f96609d2 100644 --- a/contracts/flashloan/base/FlashLoanReceiverBase.sol +++ b/contracts/flashloan/base/FlashLoanReceiverBase.sol @@ -12,27 +12,12 @@ abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; - ILendingPoolAddressesProvider public addressesProvider; + ILendingPoolAddressesProvider internal _addressesProvider; constructor(ILendingPoolAddressesProvider provider) public { - addressesProvider = provider; + _addressesProvider = provider; } receive() external payable {} - function _transferFundsBack( - address reserve, - address destination, - uint256 amount - ) internal { - transferInternal(destination, reserve, amount); - } - - function transferInternal( - address destination, - address reserve, - uint256 amount - ) internal { - IERC20(reserve).safeTransfer(destination, amount); - } } diff --git a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol index 95fe6f3d..e3c2636c 100644 --- a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol +++ b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol @@ -10,7 +10,6 @@ pragma solidity ^0.6.8; interface IFlashLoanReceiver { function executeOperation( address reserve, - address destination, uint256 amount, uint256 fee, bytes calldata params diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 50386d6d..77f04893 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -471,16 +471,16 @@ contract LendingPool is VersionedInitializable, ILendingPool { IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); //execute action of the receiver - receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); + receiver.executeOperation(asset, amount, amountFee, params); //transfer from the receiver the amount plus the fee - IERC20(asset).safeTransferFrom(receiver, aTokenAddress, amount.add(amountFee)); + IERC20(asset).safeTransferFrom(receiverAddress, aTokenAddress, amount.add(amountFee)); //compounding the cumulated interest reserve.updateCumulativeIndexesAndTimestamp(); //compounding the received fee into the reserve - reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); + reserve.cumulateToLiquidityIndex(IERC20(aTokenAddress).totalSupply(), amountFee); //refresh interest rates reserve.updateInterestRates(asset, amountFee, 0); diff --git a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol index b1bfc8b2..610e94cd 100644 --- a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol +++ b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol @@ -13,46 +13,46 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeMath for uint256; using SafeERC20 for IERC20; + ILendingPoolAddressesProvider internal _provider; + event ExecutedWithFail(address _reserve, uint256 _amount, uint256 _fee); event ExecutedWithSuccess(address _reserve, uint256 _amount, uint256 _fee); bool failExecution = false; - constructor(ILendingPoolAddressesProvider _provider) public FlashLoanReceiverBase(_provider) {} + constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool _fail) public { failExecution = _fail; } function executeOperation( - address _reserve, - address _destination, - uint256 _amount, - uint256 _fee, - bytes memory _params + address reserve, + uint256 amount, + uint256 fee, + bytes memory params ) public override { //mint to this contract the specific amount - MintableERC20 token = MintableERC20(_reserve); + MintableERC20 token = MintableERC20(reserve); //check the contract has the specified balance require( - _amount <= IERC20(_reserve).balanceOf(address(this)), + amount <= IERC20(reserve).balanceOf(address(this)), 'Invalid balance for the contract' ); if (failExecution) { - emit ExecutedWithFail(_reserve, _amount, _fee); + emit ExecutedWithFail(reserve, amount, fee); return; } //execution does not fail - mint tokens and return them to the _destination //note: if the reserve is eth, the mock contract must receive at least _fee ETH before calling executeOperation - token.mint(_fee); + token.mint(fee); - //returning amount + fee to the destination - _transferFundsBack(_reserve, _destination, _amount.add(_fee)); + IERC20(reserve).approve(_addressesProvider.getLendingPool(), amount.add(fee)); - emit ExecutedWithSuccess(_reserve, _amount, _fee); + emit ExecutedWithSuccess(reserve, amount, fee); } } diff --git a/deployed-contracts.json b/deployed-contracts.json index 8286b8f5..74b88aa4 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -5,7 +5,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", + "address": "0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -15,7 +15,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xa4bcDF64Cdd5451b6ac3743B414124A6299B65FF", + "address": "0x4a716924Dad0c0d0E558844F304548814e7089F1", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -25,7 +25,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5A0773Ff307Bf7C71a832dBB5312237fD3437f9F", + "address": "0x798c5b4b62b1eA9D64955D6751B03075A003F123", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -53,7 +53,7 @@ "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" }, "localhost": { - "address": "0x9EC0480CF106d6dc1c7849BA141a56F874170F97" + "address": "0x193101EA4C68eb894aeb922D4aC9C612a464c735" } }, "LendingPoolDataProvider": { @@ -66,7 +66,7 @@ "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" }, "localhost": { - "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" + "address": "0xf9cD0476CFC1E983e9feA9366A2C08e10eFc9e25" } }, "PriceOracle": { @@ -75,7 +75,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x099d9fF8F818290C8b5B7Db5bFca84CEebd2714c", + "address": "0x18C3df59BEb7babb81BC20f61c5C175D0Cb7603d", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -85,7 +85,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xAF6BA11790D1942625C0c2dA07da19AB63845cfF", + "address": "0x39ed2aE701B56AD229A19E628Bf5A515795F0AA3", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -95,7 +95,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xD83D2773a7873ae2b5f8Fb92097e20a8C64F691E", + "address": "0x9434029990cF00118c28a06E014F0d7d879f28CE", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -105,7 +105,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xf91aC1098F3b154671Ce83290114aaE45ac0225f", + "address": "0xccd7A2534fd4FD5119De8E368615b226e23F8F37", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -115,7 +115,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x830bceA96E56DBC1F8578f75fBaC0AF16B32A07d", + "address": "0x4c010BA8A40e5c13Acc1E32c025c2b2aea405Dbb", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -169,7 +169,7 @@ "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" }, "localhost": { - "address": "0x3bDA11B584dDff7F66E0cFe1da1562c92B45db60" + "address": "0x2aE520a05B31f170a18C425a1e8626aB7Ef71984" } }, "WalletBalanceProvider": { @@ -178,7 +178,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x392E5355a0e88Bd394F717227c752670fb3a8020", + "address": "0xBD2244f43f7BA73eB35A64302A6D8DBf17BdF2F1", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -188,7 +188,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x7c2C195CD6D34B8F845992d380aADB2730bB9C6F", + "address": "0x11df1AF606b85226Ab9a8B1FDa90395298e7494F", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -198,7 +198,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x8858eeB3DfffA017D4BCE9801D340D36Cf895CCf", + "address": "0x8f9A92c125FFEb83d8eC808Cd9f8cb80084c1E37", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -208,7 +208,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x0078371BDeDE8aAc7DeBfFf451B74c5EDB385Af7", + "address": "0xc4007844AE6bBe168cE8D692C86a7A4414FBcD26", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -218,7 +218,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xf4e77E5Da47AC3125140c470c71cBca77B5c638c", + "address": "0xAb768C858C33DfcB6651d1174AFb750433a87Be0", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -228,7 +228,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x3619DbE27d7c1e7E91aA738697Ae7Bc5FC3eACA5", + "address": "0xA089557D64DAE4b4FcB65aB7C8A520AABb213e37", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -238,7 +238,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8", + "address": "0x20FAE2042b362E3FaB2806820b9A43CC116e2846", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -248,7 +248,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x1A1FEe7EeD918BD762173e4dc5EfDB8a78C924A8", + "address": "0x8880F314112f15C2AfF674c3B27f9a44Ca86e4d0", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -258,7 +258,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e", + "address": "0xDcb10C2e15110Db4B02C0a1df459768E680ce245", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -268,7 +268,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xc4905364b78a742ccce7B890A89514061E47068D", + "address": "0xfD408ec64Da574b1859814F810564f73ea2Ff003", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -278,7 +278,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe", + "address": "0x0006F7c3542BEE76Dd887f54eD22405Ac4ae905a", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -288,7 +288,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x8B5B7a6055E54a36fF574bbE40cf2eA68d5554b3", + "address": "0x6ca94a51c644eca3F9CA315bcC41CbA6940A66Eb", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -298,7 +298,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0", + "address": "0x6765291Cab755B980F377445eFd0F9F945CDA6C4", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -308,7 +308,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x20Ce94F404343aD2752A2D01b43fa407db9E0D00", + "address": "0xa7dB4d25Fc525d19Fbda4E74AAF447B88420FbcB", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -318,7 +318,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160", + "address": "0x273D60904A8DBa3Ae6B20505c59902644124fF0E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -328,7 +328,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x2D8553F9ddA85A9B3259F6Bf26911364B85556F5", + "address": "0xfc37dE87C1Ee39cc856782BF96fEdcB6FA5c5A7f", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -338,7 +338,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x52d3b94181f8654db2530b0fEe1B19173f519C52", + "address": "0x049228dFFEdf91ff224e9F96247aEBA700e3590c", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -348,7 +348,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xd15468525c35BDBC1eD8F2e09A00F8a173437f2f", + "address": "0xA410D1f3fEAF300842142Cd7AA1709D84944DCb7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -358,7 +358,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x7e35Eaf7e8FBd7887ad538D4A38Df5BbD073814a", + "address": "0x835973768750b3ED2D5c3EF5AdcD5eDb44d12aD4", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -368,7 +368,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5bcb88A0d20426e451332eE6C4324b0e663c50E0", + "address": "0x1181FC27dbF04B5105243E60BB1936c002e9d5C8", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -378,7 +378,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x3521eF8AaB0323004A6dD8b03CE890F4Ea3A13f5", + "address": "0x6F96975e2a0e1380b6e2e406BB33Ae96e4b6DB65", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -388,7 +388,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x53369fd4680FfE3DfF39Fc6DDa9CfbfD43daeA2E", + "address": "0xc032930653da193EDE295B4DcE3DD093a695c3b3", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -398,7 +398,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xB00cC45B4a7d3e1FEE684cFc4417998A1c183e6d", + "address": "0xb3363f4349b1160DbA55ec4D82fDe874A4123A2a", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -408,7 +408,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", + "address": "0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -417,7 +417,7 @@ "address": "0xDf73fC454FA018051D4a1509e63D11530A59DE10" }, "localhost": { - "address": "0x3b050AFb4ac4ACE646b31fF3639C1CD43aC31460" + "address": "0x18c3e48a45839B3BbC998c70A2fD41fB8D93a35D" } }, "StableDebtToken": { @@ -426,7 +426,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xA0AB1cB92A4AF81f84dCd258155B5c25D247b54E", + "address": "0x2ca7Aa6CcCdb5D77F1c1d3E6a21fF0F7ac24C825", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -436,13 +436,13 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5f7134cd38C826a7649f9Cc47dda24d834DD2967", + "address": "0x527a346011Cd6c71973f653426Ce609fa53dd59E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "AToken": { "localhost": { - "address": "0xE91bBe8ee03560E3dda2786f95335F5399813Ca0", + "address": "0x3035D5D127487Ee5Df5FD951D9624a8b877A8497", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "buidlerevm": { @@ -456,7 +456,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x7f23223A2FAf869962B38f5eC4aAB7f37454A45e", + "address": "0xAA6DfC2A802857Fadb75726B6166484e2c011cf5", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -466,7 +466,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xf784709d2317D872237C4bC22f867d1BAe2913AB", + "address": "0x2cc20bE530F92865c2ed8CeD0b020a11bFe62Fe7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -476,7 +476,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x1203D1b97BF6E546c00C45Cda035D3010ACe1180", + "address": "0xFd23fD3d937ae73a7b545B8Bfeb218395bDe9b8f", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -486,7 +486,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x8733AfE8174BA7c04c6CD694bD673294079b7E10", + "address": "0xEe821582b591CE5e4a9B7fFc4E2DAD47D3759C08", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } } diff --git a/helpers/types.ts b/helpers/types.ts index 106e5376..625da1f4 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -56,7 +56,7 @@ export enum ProtocolErrors { INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', ZERO_COLLATERAL = 'The collateral balance is 0', - INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', + TRANSFER_AMOUNT_EXCEEDS_BALANCE = 'ERC20: transfer amount exceeds balance', TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index fcda8c28..cbbda7d6 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -11,9 +11,8 @@ const {expect} = require('chai'); makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { - INCONSISTENT_PROTOCOL_BALANCE, + TRANSFER_AMOUNT_EXCEEDS_BALANCE, TOO_SMALL_FLASH_LOAN, - NOT_ENOUGH_LIQUIDITY_TO_BORROW, } = ProtocolErrors; before(async () => { @@ -99,7 +98,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ethers.utils.parseEther('0.8'), '0x10' ) - ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); it('tries to take a very small flashloan, which would result in 0 fees (revert expected)', async () => { @@ -125,8 +124,8 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { '1004415000000000000', //slightly higher than the available liquidity '0x10' ), - NOT_ENOUGH_LIQUIDITY_TO_BORROW - ).to.be.revertedWith(NOT_ENOUGH_LIQUIDITY_TO_BORROW); + TRANSFER_AMOUNT_EXCEEDS_BALANCE + ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); it('tries to take a flashloan using a non contract address as receiver (revert expected)', async () => { @@ -194,7 +193,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ethers.utils.parseEther('500'), '0x10' ), - INCONSISTENT_PROTOCOL_BALANCE - ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + TRANSFER_AMOUNT_EXCEEDS_BALANCE + ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); }); diff --git a/tests.log b/tests.log new file mode 100644 index 00000000..7b538da2 --- /dev/null +++ b/tests.log @@ -0,0 +1,2750 @@ +Compiling... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Compiled 68 contracts successfully + +-> Deploying test environment... +*** MintableERC20 *** + +Network: localhost +tx: 0xb693d33edf5fb2e4adf9cfacde9abe07350ef8327c3fabe93d99e0428ccc53fd +contract address: 0x11df1AF606b85226Ab9a8B1FDa90395298e7494F +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** DAI *** + +Network: localhost +tx: 0xb693d33edf5fb2e4adf9cfacde9abe07350ef8327c3fabe93d99e0428ccc53fd +contract address: 0x11df1AF606b85226Ab9a8B1FDa90395298e7494F +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xd445dfad2e65e07cf8c9f31b3fed0755d619544067ba4d63b5d78f3d25664fa4 +contract address: 0x8f9A92c125FFEb83d8eC808Cd9f8cb80084c1E37 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** LEND *** + +Network: localhost +tx: 0xd445dfad2e65e07cf8c9f31b3fed0755d619544067ba4d63b5d78f3d25664fa4 +contract address: 0x8f9A92c125FFEb83d8eC808Cd9f8cb80084c1E37 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xb44d3bbdb2704e5ab272306e60f99af93fcce9ecdf14a5a303daacea79c3408b +contract address: 0xc4007844AE6bBe168cE8D692C86a7A4414FBcD26 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** TUSD *** + +Network: localhost +tx: 0xb44d3bbdb2704e5ab272306e60f99af93fcce9ecdf14a5a303daacea79c3408b +contract address: 0xc4007844AE6bBe168cE8D692C86a7A4414FBcD26 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x34b1370e38c3f89c4356ede4b3ee647790dc31a6c905ca7838b50c396a77fcea +contract address: 0xAb768C858C33DfcB6651d1174AFb750433a87Be0 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** BAT *** + +Network: localhost +tx: 0x34b1370e38c3f89c4356ede4b3ee647790dc31a6c905ca7838b50c396a77fcea +contract address: 0xAb768C858C33DfcB6651d1174AFb750433a87Be0 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x514141c9d33ef8322ceb061e23a1295802aa5598e2946b639cc1f6c6b3d4edc7 +contract address: 0x2cc20bE530F92865c2ed8CeD0b020a11bFe62Fe7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** WETH *** + +Network: localhost +tx: 0x514141c9d33ef8322ceb061e23a1295802aa5598e2946b639cc1f6c6b3d4edc7 +contract address: 0x2cc20bE530F92865c2ed8CeD0b020a11bFe62Fe7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xd9646f0608c0da17edef8a6e4cd023a6863ce240164f698d9313e70fdd3c7e1f +contract address: 0xA089557D64DAE4b4FcB65aB7C8A520AABb213e37 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** USDC *** + +Network: localhost +tx: 0xd9646f0608c0da17edef8a6e4cd023a6863ce240164f698d9313e70fdd3c7e1f +contract address: 0xA089557D64DAE4b4FcB65aB7C8A520AABb213e37 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xc1be16014389ca278747424393a740bca4ec447fbd9caa4f4982e351ee266108 +contract address: 0x20FAE2042b362E3FaB2806820b9A43CC116e2846 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** USDT *** + +Network: localhost +tx: 0xc1be16014389ca278747424393a740bca4ec447fbd9caa4f4982e351ee266108 +contract address: 0x20FAE2042b362E3FaB2806820b9A43CC116e2846 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x50f85855b779985f4a404b35505783e7135433034149f253eae0cab1400ae353 +contract address: 0x8880F314112f15C2AfF674c3B27f9a44Ca86e4d0 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** SUSD *** + +Network: localhost +tx: 0x50f85855b779985f4a404b35505783e7135433034149f253eae0cab1400ae353 +contract address: 0x8880F314112f15C2AfF674c3B27f9a44Ca86e4d0 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xa51d0baa6dd5cda1f4631af260b5ed8ecae708d5f5bcde76961f31bcfd4ba7eb +contract address: 0xDcb10C2e15110Db4B02C0a1df459768E680ce245 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** ZRX *** + +Network: localhost +tx: 0xa51d0baa6dd5cda1f4631af260b5ed8ecae708d5f5bcde76961f31bcfd4ba7eb +contract address: 0xDcb10C2e15110Db4B02C0a1df459768E680ce245 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x9bfdcd29285b0fab25adf99c1fca8059bbf38cb1a9f8e59e7d3fefda8d6eb03b +contract address: 0xfD408ec64Da574b1859814F810564f73ea2Ff003 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MKR *** + +Network: localhost +tx: 0x9bfdcd29285b0fab25adf99c1fca8059bbf38cb1a9f8e59e7d3fefda8d6eb03b +contract address: 0xfD408ec64Da574b1859814F810564f73ea2Ff003 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xfd8468df934e43ccec60acba936b601c27847183c18a3f5d6535763b60e6fbaa +contract address: 0x0006F7c3542BEE76Dd887f54eD22405Ac4ae905a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** WBTC *** + +Network: localhost +tx: 0xfd8468df934e43ccec60acba936b601c27847183c18a3f5d6535763b60e6fbaa +contract address: 0x0006F7c3542BEE76Dd887f54eD22405Ac4ae905a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x657f63363d8df1a8b2e06a93e3c1d869b945f5970460101fed9b82bce2f0881c +contract address: 0x6ca94a51c644eca3F9CA315bcC41CbA6940A66Eb +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** LINK *** + +Network: localhost +tx: 0x657f63363d8df1a8b2e06a93e3c1d869b945f5970460101fed9b82bce2f0881c +contract address: 0x6ca94a51c644eca3F9CA315bcC41CbA6940A66Eb +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xc9eaaddbc4add294cbf0511d1f35096063ea66f9528a284cf1a8f2b69d8431b7 +contract address: 0x6765291Cab755B980F377445eFd0F9F945CDA6C4 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** KNC *** + +Network: localhost +tx: 0xc9eaaddbc4add294cbf0511d1f35096063ea66f9528a284cf1a8f2b69d8431b7 +contract address: 0x6765291Cab755B980F377445eFd0F9F945CDA6C4 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xd2a8b51e3d598379b72f199c37046a74bdea759e78edfbb651190fd3098ca038 +contract address: 0xa7dB4d25Fc525d19Fbda4E74AAF447B88420FbcB +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MANA *** + +Network: localhost +tx: 0xd2a8b51e3d598379b72f199c37046a74bdea759e78edfbb651190fd3098ca038 +contract address: 0xa7dB4d25Fc525d19Fbda4E74AAF447B88420FbcB +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x30da604c48ddf9d6724087a17e66a0283762c0df47e402484cb47a742f3bc3a1 +contract address: 0x273D60904A8DBa3Ae6B20505c59902644124fF0E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** REP *** + +Network: localhost +tx: 0x30da604c48ddf9d6724087a17e66a0283762c0df47e402484cb47a742f3bc3a1 +contract address: 0x273D60904A8DBa3Ae6B20505c59902644124fF0E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xf75538604aa40a916f3b53aa71f0d3f4d2985e3e313aefcdd20ec03efb03fe58 +contract address: 0xfc37dE87C1Ee39cc856782BF96fEdcB6FA5c5A7f +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** SNX *** + +Network: localhost +tx: 0xf75538604aa40a916f3b53aa71f0d3f4d2985e3e313aefcdd20ec03efb03fe58 +contract address: 0xfc37dE87C1Ee39cc856782BF96fEdcB6FA5c5A7f +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x144bd6a169a5878c72d1c1b7fed21cad13c046cc5608975a7c7f05efb6c11c79 +contract address: 0x049228dFFEdf91ff224e9F96247aEBA700e3590c +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** BUSD *** + +Network: localhost +tx: 0x144bd6a169a5878c72d1c1b7fed21cad13c046cc5608975a7c7f05efb6c11c79 +contract address: 0x049228dFFEdf91ff224e9F96247aEBA700e3590c +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770555 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x61d73d01885b056022452fb9df317c03167ce8bfa8d8b70f09f5ba3ba84087e0 +contract address: 0xA410D1f3fEAF300842142Cd7AA1709D84944DCb7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** USD *** + +Network: localhost +tx: 0x61d73d01885b056022452fb9df317c03167ce8bfa8d8b70f09f5ba3ba84087e0 +contract address: 0xA410D1f3fEAF300842142Cd7AA1709D84944DCb7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3770435 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x740b8681b0c8b7d3fbc23b29070e5a4ce1d278c456740949e6958217acb4d452 +contract address: 0x835973768750b3ED2D5c3EF5AdcD5eDb44d12aD4 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771395 + +****** + +*** UNI_DAI_ETH *** + +Network: localhost +tx: 0x740b8681b0c8b7d3fbc23b29070e5a4ce1d278c456740949e6958217acb4d452 +contract address: 0x835973768750b3ED2D5c3EF5AdcD5eDb44d12aD4 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771395 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0xfd37d9b66d1f1ab4cb4b243d14927f8b1d65e1b51001a312ccad621387838be1 +contract address: 0x1181FC27dbF04B5105243E60BB1936c002e9d5C8 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** UNI_USDC_ETH *** + +Network: localhost +tx: 0xfd37d9b66d1f1ab4cb4b243d14927f8b1d65e1b51001a312ccad621387838be1 +contract address: 0x1181FC27dbF04B5105243E60BB1936c002e9d5C8 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x6720a4ff9ab66ceb1d378c93a7254f49a646c40896274ee8f3e02e6fa1f301d6 +contract address: 0x6F96975e2a0e1380b6e2e406BB33Ae96e4b6DB65 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** UNI_SETH_ETH *** + +Network: localhost +tx: 0x6720a4ff9ab66ceb1d378c93a7254f49a646c40896274ee8f3e02e6fa1f301d6 +contract address: 0x6F96975e2a0e1380b6e2e406BB33Ae96e4b6DB65 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x7bfa83b2c563a4646d62d9a241368f64c21538d2b9b272d2dbcaebaea3003cdd +contract address: 0xc032930653da193EDE295B4DcE3DD093a695c3b3 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** UNI_LINK_ETH *** + +Network: localhost +tx: 0x7bfa83b2c563a4646d62d9a241368f64c21538d2b9b272d2dbcaebaea3003cdd +contract address: 0xc032930653da193EDE295B4DcE3DD093a695c3b3 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x710172661439f201e9e857de79517f4a10dc1c50f43431112ca14182d249e77f +contract address: 0xb3363f4349b1160DbA55ec4D82fDe874A4123A2a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771395 + +****** + +*** UNI_MKR_ETH *** + +Network: localhost +tx: 0x710172661439f201e9e857de79517f4a10dc1c50f43431112ca14182d249e77f +contract address: 0xb3363f4349b1160DbA55ec4D82fDe874A4123A2a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771395 + +****** + +*** MintableERC20 *** + +Network: localhost +tx: 0x44218a2b69f73edd259ee7531e07181321912029d61517b450235eeb7c172d26 +contract address: 0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** UNI_LEND_ETH *** + +Network: localhost +tx: 0x44218a2b69f73edd259ee7531e07181321912029d61517b450235eeb7c172d26 +contract address: 0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 3771515 + +****** + +*** LendingPoolAddressesProvider *** + +Network: localhost +tx: 0x85c590408781fb6cf1a6416f3f7f5bcafe93d00f5ef8ca42080daaf4a494ef3f +contract address: 0x4a716924Dad0c0d0E558844F304548814e7089F1 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6959345 + +****** + +*** LendingPoolAddressesProviderRegistry *** + +Network: localhost +tx: 0x7b9a2d4c2da516b51d7517aae0ba274427bceecb3e1f1905f4e98b9ae1c10884 +contract address: 0x798c5b4b62b1eA9D64955D6751B03075A003F123 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2407480 + +****** + +Deployed lending pool, address: 0x8a32f94F052F38d0436C68d6bb761619c475b987 +Added pool to addresses provider +Address is 0xf9cD0476CFC1E983e9feA9366A2C08e10eFc9e25 +implementation set, address: 0xf9cD0476CFC1E983e9feA9366A2C08e10eFc9e25 +*** LendingPoolConfigurator *** + +Network: localhost +tx: 0x468a8bb8eb2d469e3fa069cfdac02f25a48086833360a8b4e23b187b5e64aa82 +contract address: 0xd63ae78CE8D440CbBc4E9B573AA81522DBf1e4D1 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** PriceOracle *** + +Network: localhost +tx: 0x8d36bb456d6e2fb92682cfa5bd12348afb64de8c1af68ed583f34f25e381a1a0 +contract address: 0x18C3df59BEb7babb81BC20f61c5C175D0Cb7603d +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 767525 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x54bab4c8c78250e428e31baaa5cb2fcc117e90797f24eb76360fc9a37d0eacd6 +contract address: 0x4819594Fa472a722E6f08aD2d0D1f829AfF6b1D1 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524490 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xb82c4bd0a169b97cc044ce4d5d4935e440b114a9da1b7d1a3fb9cd90e4f90dbb +contract address: 0x5eD7553Dc8a0D541130020f9965Ea951cAC1b573 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x6c9e9b7c63860c736a8c93d1957e602924c30f23ea58e28897a8681b264f00d0 +contract address: 0xE0A4f15eBcC30F67782800479C89692d2E40d511 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xe06a6d27906950183f569b54bc3cab756dd3987c4c1a40a55adb9fe1a72c7396 +contract address: 0x32e036B2e3B5A998401eFA43f779d2070fAC2A7D +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x9ef232a904789a257512db57f8cc2662e7a481df6e8f95a041208503047c8368 +contract address: 0xB62f98C002fc1D336Ab1EaF7a890B26E1191F0f2 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524490 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x7384bb1e853e761e3b61bc286331e7f302a77ebcad6cfed6c9fd65f60e521c79 +contract address: 0x57Aa7e5dEF9cBb8327c764e31E7C8f0996ae0f91 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524490 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x976b29e38f1b052805164a337b21f451cbfb2328b8951882e527b8d51894310b +contract address: 0x08c4284C1645529732466fd9c322a8d0d8C6AC70 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x7b48370fe9e1e971ea386ca9647470d670ca238425dc42e13742dfbae71b1cae +contract address: 0x9e4c352aa01D2eC5c6917e79a19e74B27Ab6Be85 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524490 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xd89d74e0609f162d9ce0b6b6950c112b76f09293e0f44c75890101473de91554 +contract address: 0x022cFA026CA96fABfDae3b3a7830d1026cbbd336 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xe4fd2a196be6b31c06f4096d1b7a7800c9559df8c38d259c853bca3e408e8ed2 +contract address: 0xD7B4b736722c350c1ee35e0522fd9b38546c1b18 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xc49ce797d6f08cb184f77f1b1f45ee565cfb4313f2d2a5aefd95989ce56cfa8b +contract address: 0xCa2adc1CEe345762b823C55A18f60874d6aCd4ad +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524550 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x655ef0633e66f53aa8b80b44ccd3718497e39a27324758913867510b23ab5b35 +contract address: 0xf880fBe54ea8cc8E2DdF115435D46C7f3B050217 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x493b84ce76a92315beb3df1478893a68c0ffccf46e67601165c54ae981a68089 +contract address: 0x68730f335681eccdd55127a4ebEbbDc9e5Ee542C +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524370 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x6d76dcb43e91ee29b2a0229e73f34b831af7125fb8d7c780f3d09063c7e85a39 +contract address: 0x0bf755084d2af8df01b046e3c3981EC5C545A26A +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524370 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x4a95ea0c1029afaf14dc2b45590e0eb01da7f9ddc06486245b9e4437a45f468e +contract address: 0x85a0419D3Cbc60ffdD3128EC1b0D3737091DF748 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x5e5158c387d616d4768e2f395adab805e7071974a129b953d4d0e11f8c35dd8f +contract address: 0x9CDDBE77d2f4D505Ed8aD63Bf4061876C8E8B94d +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x2631a412a26f480d3af0ab0578736f787a4e903c7141fbfcf17ad28e00cd585d +contract address: 0x67918d986Cb2C0A8465369d4d6B21BE492E49522 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x8864f5076054fccf00faf3d933e63f8d44d191deea4e1c68674134c57fb6bb30 +contract address: 0xfa7cC137C527920Ae5E85311bAe7eFFd55d7c1B3 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xebd805e8af09d3814431b49a2fc4beeee44e54a17249dbc57dcc2065b2537d58 +contract address: 0xD7619aE561dDeB7eD73bDf7d640DAe32b643D026 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x33e4686ecfda16b719ddccf20e6e28e536a5b72dc1e77b8a7245d18c0a1a7674 +contract address: 0xB66bB20a2d1800fB08d59E6eF1C34E738aea9084 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x30f61c84c0f9dc4236b9ba4fe227989d5463e8534bddaf1fa4f046631b7324ad +contract address: 0x34Bcbf717e1Cb4Fa3f779297d6128D580B87BA23 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0xd6f95a84f6056b18218397aefa2b0a62fd2fa16071c3708ba627f468485085be +contract address: 0xe74F2b30C2AC45Ab5162795F2fFA6ACBA5C41FCe +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x7a878b5b5029bad142dda20da6f120e060bf8311ba80f22e98ff8fc539f38724 +contract address: 0xce8d1D7665832237b1eae6267C0cA5aCC11B7fE6 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** MockAggregator *** + +Network: localhost +tx: 0x2e80f1c33b474542733682528ed1e072406b585dcfaa2c158e6ce87295308b19 +contract address: 0x39ed2aE701B56AD229A19E628Bf5A515795F0AA3 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 524430 + +****** + +*** ChainlinkProxyPriceProvider *** + +Network: localhost +tx: 0x5125f9e283f93d831c4961c06e23fc7e11533d8942685c2b1d3743c1adcddb3e +contract address: 0x9434029990cF00118c28a06E014F0d7d879f28CE +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6255420 + +****** + +*** LendingRateOracle *** + +Network: localhost +tx: 0x170675f0f61bafaef087a2f9b8cc9c9d541c14dfeea7f93cd2f9e71e821ce7e6 +contract address: 0xccd7A2534fd4FD5119De8E368615b226e23F8F37 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 1720040 + +****** + +Initialize configuration +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x74ff24b7fa40f7311401945b7ce6955643e45d8ed25108917d4c59f8d374741b +contract address: 0xB7EB48C88bdaf6B8B2ea02bC822A4a132328f714 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xf67b77de54001ea7cb0e2a53b66e4b8a492921215606603453d93428dfc4a5e0 +contract address: 0xC0E8d6e5574cd52B1a8dab202Aa3fec21B74BC35 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x54278f78c259d1281c785529b330a19b1a584623e95fc645934f924c40ec3198 +contract address: 0x34Af2d98209B5F5d28faC0eec6285D4Dd65c589D +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x579e7172f7886844afffa3bdafe1a9e6dc23e1dd6507a75b67ee8b3cdcf67118 +contract address: 0xf5D5224509Abe68408d3D2080909B8EBeCa07B02 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xe350cca6989ccd7107176b683407949edba2b51cac58203f77416789f475956a +contract address: 0x8eB5127325c66e28197f2a9fB6a52a79d5fD381e +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x4d14f22ec586cd818a2dd2f77102175d8648918d7612061fd79cf78c5ebfc65a +contract address: 0xd7a76AA426EBAb1E67c63d48A22b5d7151eeac3F +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128250 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x80011ba6270adf75e11c12bc5f17ccd09c42634030675cba721f800babf4b294 +contract address: 0x43bD57b672AF17656bE2B3f21bDe64da757f08B5 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651030 + +****** + +*** AToken *** + +Network: localhost +tx: 0xd37d2e127a4f8d4a5049a13d51bbc1f705881d518aaa76237a9945d42da9fe04 +contract address: 0x98D9d1E46351945fdf5A6C8fc2b1FbB7cB4D6758 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x15a2b44162ae48fec47aaca929404375b87a57a145f479c80f4b32bd81b4e277 +contract address: 0xAACe6c4759b2bF94cF4cf3b1cF2f4fd726033784 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xdc849ac47472f3153a70895141866dc05ebfce2dce0559a21c31fb683723e2af +contract address: 0x1Cb5F6F553a5434b842AC5fE0e52C78338612B77 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x6486e963bcf1e59789b27cf4844f6a1d935a1827b35c404f03f15fff906ea60c +contract address: 0x333CF5E8039a9ecBdAA4fF4E9f7D10842f06E7b4 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0xc02452e70ab23cfe77f62e3cbdd901369a496deb798fa937a2971386793f0098 +contract address: 0x09678e127117c3F342E52014BAC7e0De59cA4B41 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x9dc14c88bfeb86024b773cb91403cf998e9fba202c9d816e4a93e5c893378b95 +contract address: 0x83c60fAD6afA5E8A38Fb7549174e216C5efe85Bd +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xd96a4d6c9d17e76b95bcfb185b2717849bd1797294195746a39a68980b5b8b09 +contract address: 0x2C6152331cA1F9AEc74523171a496d61C7203e64 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x00dd0efaa7da4dc8b1ec77ce6bfd9a3ce45233487233930f59347a3ed2ba74bb +contract address: 0xAa1b47a6139A4cad87464911812f92c0ba2db0d7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0x4526b4c92699d36aa178b319c933e71c0eaa5dfca2fd3f92467d87084e87f3bd +contract address: 0x812B84Aac96db85B65A35c1ea93789DA0d977113 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xe56d3118f791864b63d5a1d9be52bc77da65f4ab4e8b75b0e04a2e55affdf1fe +contract address: 0x5da6809Fe6d0743125Ec39AFCF9E38ea0F0B5d4E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x975b727795a15df3445b9b23ffba7f8e646a67a848d536215e1576fab58a8846 +contract address: 0xE95D3B838c8A4e52C8059cc75a18FB6d2EDA043a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x9682837a645353709ecdca94a65a8fe22eab97c3d9cf848cdd0128b36749fa24 +contract address: 0x5DaF25c6E608CFd427Dbae874B8a5441d0018339 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0xe3e27056c5b4c26fa31cfc91f6934d8cd6f0245e7fa2ce2f3d09521aa03b3a9f +contract address: 0x4aDdfb6d8994197b666c8FB167dAF9576D052d26 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x6006c2c541d8f824047b470b22314f6b85fd2d0709132fe7fd72922ce2444cfd +contract address: 0xEdA424B933c9F5C9D82718db4A5AB9CEAE3A8344 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x0a3af97e935a83b82fd9ad1cb63dbd06ee5009aa0d986977836f30acda87faaa +contract address: 0x10E99C82512838Ed9fD2FC40d71DAC29dCA497EC +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xda2e3cd3897dbfe6c0f6b73dcde49010a6cada5df7a4f0038063722e1814f5a3 +contract address: 0x6396ed1AFa51770f2B26BC582Ff9878A3e34b126 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0xb5acb13cfe7914ff8fad7e5c28b46e9f689e13a7dd5449492322c59d73f843bf +contract address: 0x09D011f96C64feB12c2C614c5BB012dEfb63E16D +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x1321448a7f01e61623fb1ee6c3db90da2adf86cf8aab197e1942b2c891e6ffce +contract address: 0xAc90A2D29a669aa51c3a5506b577D59DDc931c6e +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x19a8d0b6e4b9aa523256a4c9eed5453701647671a5779743b0f5afa3e58f11d2 +contract address: 0x3a629468EDf66d22d69F84C5EFFadc6C2BEA4d5C +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x67ac2f70267459b17f88d1a06c164322164239f9c8267b544badc2ad79790226 +contract address: 0x9BDb2e959aD37ddA24b6A770993852E99970b8F8 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x4220df2a27a81f69625a2d0cbba1f4383e4ef12158e28eef912beb0d5160b338 +contract address: 0xd1E1BC4D1C225D9029f14f8b8eFcF12F0eA51C1e +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x3296da75785d3dcbae0fbbef6cbe60f2f7a1f207a632a176c90a646febf4eb36 +contract address: 0x6d2BfF57A95f2b96d33C27b281e718C4FC76222e +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xe4d89df27c5d2e70f84c575cdf7ebff25f815b0d82f91f9423a0cf0d339c4e8f +contract address: 0xD8cF367dce091A6bFB2a9d4A3673F80a616bd8B7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xe0da49201fcb21f10c2884279ee43ad63ae346139e9f95e7991a7b7c378e0d6d +contract address: 0x629bBA58D1Bc73e9C515668A76F00DC8FE852065 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x6a19fa9c7cbc714245413d7cef76ad8d84a6f267950c8b531f4fb4403e2c57a7 +contract address: 0x2Ded2482555ABf714ebbc9Dd4b589e093C1a9eD2 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x521d14b37d34e8842e11897cbde3c6c75b991a749274e4d63dc5507c78e4f7ac +contract address: 0x2ECdf4E23a561A58E9e0f70cD109e8cD1C86A827 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x92673002c4b70c9670f154724bdb48293b9652b4d916a5ea0b9b33e808cd9270 +contract address: 0xf70adAAfe9883E4D52587197Cd39dc85C2B23c57 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xdfa31bd3eaeb3367325257b7ee283867dc5bb62ae8e8f43e42547e6c6053200f +contract address: 0xC07b1cE4372334264E2124b893b8445F34c2009f +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0x355e2ef294f2951dfa2f039db038543c0abeec606cd69bc425ccfdfc587fa0d2 +contract address: 0x1b9F3F849801E7Bc6C3124296fc35A83Fd40654b +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xefd434318327a3626c371301a42d2cc9f1b17cad2dfb4f1c42fb56b09b8e41aa +contract address: 0x501Cb4bBA78Ca688A59DEedE4E121590eEC20C77 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xe36cb2e2369f27648748e0e182329cbf906f31fd832e67de78d8686501b489a5 +contract address: 0x3346C431D2E9bA398a5A690ca49Ca4E3b13472FD +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128250 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x48fb6ae7811bd7c8fdec948249d1e9ad78439ce7a5b2a5983b92a87b844e02a8 +contract address: 0xcb82DF442005768Bd6E3f1597255dfD60Af26d57 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651030 + +****** + +*** AToken *** + +Network: localhost +tx: 0xad153aa4fdd44ad6fb893766cc7eda637b6b0cba2859fe9c56dd522bc2e65e12 +contract address: 0x6fb48b45f290a76c1331991c9D7F8ef3D9FE5C36 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x7cea4f37b50c4786e9df8ca8f09c29ed9b1daf4d05ff41210b23e4642f22cb23 +contract address: 0xaCb0e28183B6e3b27741776B9A013521d92dcf42 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x3b920d6dee6aecb25f15cf7a1a884c26e1186958fe487672f51e4fcf0ebd7f94 +contract address: 0xA1efebb06E897703b1AEC2a8FA6141e377752b1d +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xc771692ccb883a273b63235e551f1570b20fc2946b6a3a6c2f75561746acd80c +contract address: 0xb664f305eB269F7EE2Bc657C59c0d8D4101c6857 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x542ba4ab070c693dac934480a950b60c99137fe160cebe1f3092a3f5812faca3 +contract address: 0x29C059D0CB7621BA9E93467945A6336c783b2d2A +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x09b12f7981ceff6df8f318a23dae0eb46a2a00058b209e8dfea68fd4c71df420 +contract address: 0xbB405796150960679458C9F03e7da176F7daC6d3 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x5bd0106deaac62e2bcd5ed0cf584b5e833610a736e04c95c65a98ed04cc45a73 +contract address: 0xB82b53c852eABCFd35C757119C520F382eC31390 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x08f3c16876b91a7cc6beec71b7173ae2dcca520c860c744174f2110d52d3305d +contract address: 0x87F5639fAe81B9Ee55AAc08aE306fB92f5AB6e71 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0xdb1a23da614ea9b704fe3580cc9af14889a1a26814e56b28d5cca7fbf1aada4e +contract address: 0xc86eF02EB0d1F712a2A054887a5Eab982a983C3f +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x41f78876c9a8ba8372b2a0ef0fe7cc0b1c398a01e4bf28ef89f85b3e1dbb90ab +contract address: 0x84C055Cf6b1429f41673d04D17019276547c4af0 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x19dfde9cb5c45ea0b3586f752f80ebf9a6c02e55a6cf77a77688254ccf2541be +contract address: 0x52b733D5fA53E72E8A788419836e261b6Fa0eFC6 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xd36fcbb46b8cb664848df13f51120b3af95a99e333d5d324e463eec1f56f10c3 +contract address: 0x5ff9A2405b72d33911853f1d0bFFC361baCE435E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x6a864bf1910e626bfb808e92827be216bea78040f3d7f1f33b28a3e5ae18c631 +contract address: 0x9e2548EB10fC28CE3D1654BC7421808eE7092081 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xdd6117ffb11e3390a0610eadcea4520d25543dea7214686d147c75f610adea30 +contract address: 0x792d861D3791F4Cce91798260F863110D2D9E75b +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x814b1dc18904a1ca05c5ae4c5bb68ab73fac59c48e11924d1307ab5094411cfc +contract address: 0x5488bf6d62876d141cB0Db48929679D37dB265a5 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128310 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xb224b45f3831151e6dc6412f9205b442ec30b0bfd453589d5847faf8fa334c97 +contract address: 0x6F7ee89b972c3212452E1e58628dAf7a3b7E9c7e +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651090 + +****** + +*** AToken *** + +Network: localhost +tx: 0x250e2640db49570381e16d893884744d53206256dc442c74e2359374cd6c1341 +contract address: 0xe3A3fa239eE31b38E56d8136822c3af7089B5b0E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xb919389e36595914e6fa47a78b402550b70fa55140769091f682463caed539e4 +contract address: 0x0aB0E3A07e92E161D461deDCAEdDFef906993f84 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2916655 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xfde754172191e3885aeaf871e9ec3a0e7f9e5534b038cc256fd6e2164aa1e8d9 +contract address: 0xB964CE42932638Fc51cBFc7158686EF3f56D3262 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xf78ff3151eede55e5a3ce4e819f6ab262ac1704dd7a66f364339959c3fde919f +contract address: 0xa2203A921E4e6FeccCAbE83A19029B5200bEe779 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x097bb8c68f3ba3552eab3b0a91ee58b25d25d2573b2a71465687c068620bc8f9 +contract address: 0x61fCca5fcBEF2200C40c3e9ef555B9954035315D +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0xabdb3c57d8a1859003a9cc92b0a5d668eee974fdf18e30481d97ea0be5090e48 +contract address: 0x9DDc5C465F70b0dc78dF7cd02f52bc3d2751282a +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0xff60cd11c4845d9946fa1cbd5784ad799ce4dcfe5ee4c5c137eb638bc331a001 +contract address: 0x1D2a59d3276A669d1943fc6BDF997BF697D09565 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128190 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0xe7d8bc58eaadc19908c1493ba9b320a6c0a45ac29fe7572c83466df41e1f2a98 +contract address: 0x1e3Fcd041d44C88762255E8eFda30d0Fc22FEe76 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5650970 + +****** + +*** AToken *** + +Network: localhost +tx: 0x38c31626f6d081130717f3b145a156421844612f3c6eaafc89c4a179bf550c41 +contract address: 0x45585e87e657a54A0a0Fa25a6572217E63E5F2f7 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** DefaultReserveInterestRateStrategy *** + +Network: localhost +tx: 0x324b1818692ada5ed43f7aa74c2f7da29808c44cdc77fe14716cdc48c02ff31d +contract address: 0x4c010BA8A40e5c13Acc1E32c025c2b2aea405Dbb +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2917135 + +****** + +*** StableDebtToken *** + +Network: localhost +tx: 0x5ccd1b76e8d2b577890fa4bedf04152628bc7480be830247eafba3d1fc08e7d9 +contract address: 0x2ca7Aa6CcCdb5D77F1c1d3E6a21fF0F7ac24C825 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6128250 + +****** + +*** VariableDebtToken *** + +Network: localhost +tx: 0x1fbd7ae4adf29a8c8fbed413c48cbe83bfd81f2475bf87aeec7ad19496fc9624 +contract address: 0x527a346011Cd6c71973f653426Ce609fa53dd59E +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5651030 + +****** + +*** AToken *** + +Network: localhost +tx: 0x35e4a759c6f93001aa11697082373f645f9e2d12f3c2247a9c7f8245643a8db4 +contract address: 0x3035D5D127487Ee5Df5FD951D9624a8b877A8497 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** MockFlashLoanReceiver *** + +Network: localhost +tx: 0xd7ee83594c1b864fb16cf8ff63e95b122af260df3f2b56eb643dcf004e12e507 +contract address: 0x2aE520a05B31f170a18C425a1e8626aB7Ef71984 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 1730710 + +****** + +*** WalletBalanceProvider *** + +Network: localhost +tx: 0x4043a4de9ef7fe0f601dbdcf4775c9384d2db0b4c867410cdbeb92512d647ff7 +contract address: 0xBD2244f43f7BA73eB35A64302A6D8DBf17BdF2F1 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2512320 + +****** + +*** AaveProtocolTestHelpers *** + +Network: localhost +tx: 0xb406d28fc743855f784a865268662ed03bf4043f76d9a76fcafca2867b4e94c7 +contract address: 0x18c3e48a45839B3BbC998c70A2fD41fB8D93a35D +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 2818975 + +****** + +setup: 22.891s +Pool loaded +Configurator loaded + +*************** +Setup and snapshot finished +*************** + + AToken: Modifiers + ✓ Tries to invoke mint not being the LendingPool + ✓ Tries to invoke burn not being the LendingPool + ✓ Tries to invoke transferOnLiquidation not being the LendingPool + ✓ Tries to invoke transferUnderlyingTo not being the LendingPool + + AToken: Transfer + ✓ User 0 deposits 1000 DAI, transfers to user 1 + ✓ User 1 redirects interest to user 2, transfers 500 DAI back to user 0 + ✓ User 0 transfers back to user 1 + ✓ User 0 deposits 1 WETH and user 1 tries to borrow, but the aTokens received as a transfer are not available as collateral (revert expected) + ✓ User 1 sets the DAI as collateral and borrows, tries to transfer everything back to user 0 (revert expected) + ✓ User 0 tries to transfer 0 balance (revert expected) + ✓ User 1 repays the borrow, transfers aDAI back to user 0 + ✓ User 0 redirects interest to user 2, transfers 500 aDAI to user 1. User 1 redirects to user 3. User 0 transfers another 100 aDAI + ✓ User 1 transfers the whole amount to himself + + LendingPoolConfigurator + + 1) Deactivates the ETH reserve + ✓ Rectivates the ETH reserve + ✓ Check the onlyLendingPoolManager on deactivateReserve + ✓ Check the onlyLendingPoolManager on activateReserve + ✓ Freezes the ETH reserve + ✓ Unfreezes the ETH reserve + ✓ Check the onlyLendingPoolManager on freezeReserve + ✓ Check the onlyLendingPoolManager on unfreezeReserve + ✓ Deactivates the ETH reserve for borrowing + + 2) Activates the ETH reserve for borrowing + ✓ Check the onlyLendingPoolManager on disableBorrowingOnReserve + ✓ Check the onlyLendingPoolManager on enableBorrowingOnReserve + ✓ Deactivates the ETH reserve as collateral + ✓ Activates the ETH reserve as collateral + ✓ Check the onlyLendingPoolManager on disableReserveAsCollateral + ✓ Check the onlyLendingPoolManager on enableReserveAsCollateral + ✓ Disable stable borrow rate on the ETH reserve + ✓ Enables stable borrow rate on the ETH reserve + ✓ Check the onlyLendingPoolManager on disableReserveStableRate + ✓ Check the onlyLendingPoolManager on enableReserveStableRate + ✓ Changes LTV of the reserve + ✓ Check the onlyLendingPoolManager on setLtv + ✓ Changes liquidation threshold of the reserve + ✓ Check the onlyLendingPoolManager on setLiquidationThreshold + ✓ Changes liquidation bonus of the reserve + ✓ Check the onlyLendingPoolManager on setLiquidationBonus + ✓ Check the onlyLendingPoolManager on setReserveDecimals + ✓ Check the onlyLendingPoolManager on setLiquidationBonus + ✓ Reverts when trying to disable the DAI reserve with liquidity on it + + LendingPool FlashLoan function + ✓ Deposits ETH into the reserve + + 3) Takes ETH flashloan, returns the funds correctly +Total liquidity is 2000720000285388128 + + 4) Takes an ETH flashloan as big as the available liquidity + ✓ Takes WETH flashloan, does not return the funds (revert expected) + ✓ tries to take a very small flashloan, which would result in 0 fees (revert expected) + ✓ tries to take a flashloan that is bigger than the available liquidity (revert expected) + ✓ tries to take a flashloan using a non contract address as receiver (revert expected) + ✓ Deposits DAI into the reserve + + 5) Takes out a 500 DAI flashloan, returns the funds correctly + ✓ Takes out a 500 DAI flashloan, does not return the funds (revert expected) + + LendingPoolAddressesProvider + ✓ Test the accessibility of the LendingPoolAddressesProvider + + LendingPool liquidation - liquidator receiving aToken + + 6) LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1 + + 7) LIQUIDATION - Drop the health factor below 1 + + 8) LIQUIDATION - Tries to liquidate a different currency than the loan principal + + 9) LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral + + 10) LIQUIDATION - Liquidates the borrow + + 11) User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow + + LendingPool liquidation - liquidator receiving the underlying asset + + 12) LIQUIDATION - Deposits WETH, borrows DAI + + 13) LIQUIDATION - Drop the health factor below 1 + + 14) LIQUIDATION - Liquidates the borrow + + 15) User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow + + 16) User 4 deposits 1000 LEND - drops HF, liquidates the LEND, which results on a lower amount being liquidated + + LendingPool: Borrow negatives (reverts) + ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and tries to borrow 100 DAI with rate mode NONE (revert expected) + ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and tries to borrow 100 DAI with an invalid rate mode (revert expected) + + LendingPool: Borrow/repay (stable rate) + + 17) User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at stable rate + ✓ User 1 tries to borrow the rest of the DAI liquidity (revert expected) + + 18) User 1 repays the half of the DAI borrow after one year + + 19) User 1 repays the rest of the DAI borrow after one year + ✓ User 0 withdraws the deposited DAI plus interest + + 20) User 1 deposits 1000 DAI, user 2 tries to borrow 1000 DAI at a stable rate without any collateral (revert expected) + + 21) User 0 deposits 1000 DAI, user 1,2,3,4 deposit 1 WETH each and borrow 100 DAI at stable rate. Everything is repaid, user 0 withdraws + ✓ User 0 deposits 1000 DAI, user 1 deposits 2 WETH and borrow 100 DAI at stable rate first, then 100 DAI at variable rate, repays everything. User 0 withdraws + + LendingPool: Borrow/repay (variable rate) + ✓ User 2 deposits 1 DAI to account for rounding errors + ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at variable rate + ✓ User 1 tries to borrow the rest of the DAI liquidity (revert expected) + ✓ User 1 tries to repay 0 DAI (revert expected) + ✓ User 1 repays a small amount of DAI, enough to cover a small part of the interest + ✓ User 1 repays the DAI borrow after one year + ✓ User 0 withdraws the deposited DAI plus interest + ✓ User 1 withdraws the collateral + ✓ User 2 deposits a small amount of WETH to account for rounding errors + ✓ User 0 deposits 1 WETH, user 1 deposits 100 LINK as collateral and borrows 0.5 ETH at variable rate + ✓ User 1 tries to repay 0 ETH + ✓ User 2 tries to repay everything on behalf of user 1 using uint(-1) (revert expected) + ✓ User 3 repays a small amount of WETH on behalf of user 1 + ✓ User 1 repays the WETH borrow after one year + ✓ User 0 withdraws the deposited WETH plus interest + ✓ User 1 withdraws the collateral + ✓ User 2 deposits 1 USDC to account for rounding errors + ✓ User 0 deposits 1000 USDC, user 1 deposits 1 WETH as collateral and borrows 100 USDC at variable rate + + 22) User 1 tries to borrow the rest of the USDC liquidity (revert expected) + ✓ User 1 repays the USDC borrow after one year + ✓ User 0 withdraws the deposited USDC plus interest + ✓ User 1 withdraws the collateral + + 23) User 1 deposits 1000 DAI, user 3 tries to borrow 1000 DAI without any collateral (revert expected) + + 24) user 3 deposits 0.1 ETH collateral to borrow 100 DAI; 0.1 ETH is not enough to borrow 100 DAI (revert expected) + ✓ user 3 withdraws the 0.1 ETH + ✓ User 1 deposits 1000 USDC, user 3 tries to borrow 1000 USDC without any collateral (revert expected) + + 25) user 3 deposits 0.1 ETH collateral to borrow 100 USDC; 0.1 ETH is not enough to borrow 100 USDC (revert expected) + ✓ user 3 withdraws the 0.1 ETH + + 26) User 0 deposits 1000 DAI, user 6 deposits 2 WETH and borrow 100 DAI at variable rate first, then 100 DAI at stable rate, repays everything. User 0 withdraws + + LendingPool: Deposit + ✓ User 0 Deposits 1000 DAI in an empty reserve + ✓ User 1 deposits 1000 DAI after user 1 + ✓ User 0 deposits 1000 USDC in an empty reserve + ✓ User 1 deposits 1000 USDC after user 0 + ✓ User 0 deposits 1 WETH in an empty reserve + ✓ User 1 deposits 1 WETH after user 0 + ✓ User 1 deposits 0 ETH (revert expected) + ✓ User 1 deposits 0 DAI + + AToken: interest rate redirection negative test cases + ✓ User 0 deposits 1000 DAI, tries to give allowance to redirect interest to himself (revert expected) + ✓ User 1 tries to redirect the interest of user 0 without allowance (revert expected) + + 27) User 0 tries to redirect the interest to user 2 twice (revert expected) + + 28) User 3 with 0 balance tries to redirect the interest to user 2 (revert expected) + + AToken: interest rate redirection + + 29) User 0 deposits 1000 DAI, redirects the interest to user 2 + ✓ User 1 deposits 1 ETH, borrows 100 DAI, repays after one year. Users 0 deposits another 1000 DAI. Redirected balance of user 2 is updated + + 30) User 1 borrows another 100 DAI, repay the whole amount. Users 0 and User 2 withdraw + + 31) User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 0 redirects interest back to himself, user 1 borrows another 100 DAI and after another year repays the whole amount. Users 0 and User 2 withdraw + + 32) User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 2 redirects interest to user 3. user 1 borrows another 100 DAI, user 0 deposits another 100 DAI. User 1 repays the whole amount. Users 0, 2 first 1 DAI, then everything. User 3 withdraws + + LendingPool: Rebalance stable rate + ✓ User 0 tries to rebalance user 1 who has no borrows in progress (revert expected) + ✓ User 0 deposits 1000 DAI, user 1 deposits 1 ETH, borrows 100 DAI at a variable rate, user 0 rebalances user 1 (revert expected) + + 33) User 1 swaps to stable, user 0 tries to rebalance but the conditions are not met (revert expected) + + 34) User 2 deposits ETH and borrows the remaining DAI, causing the stable rates to rise (liquidity rate < user 1 borrow rate). User 0 tries to rebalance user 1 (revert expected) + + 35) User 2 borrows more DAI, causing the liquidity rate to rise above user 1 stable borrow rate User 0 rebalances user 1 + + LendingPool: Usage as collateral + ✓ User 0 Deposits 1000 DAI, disables DAI as collateral + + 36) User 1 Deposits 2 ETH, disables ETH as collateral, borrows 400 DAI (revert expected) + ✓ User 1 enables ETH as collateral, borrows 400 DAI + + 37) User 1 disables ETH as collateral (revert expected) + + LendingPool: Swap rate mode + ✓ User 0 tries to swap rate mode without any variable rate loan in progress (revert expected) + ✓ User 0 tries to swap rate mode without any stable rate loan in progress (revert expected) + + 38) User 0 deposits 1000 DAI, user 1 deposits 2 ETH as collateral, borrows 100 DAI at variable rate and swaps to stable after one year + + 39) User 1 borrows another 100 DAI, and swaps back to variable after one year, repays the loan + + LendingPool: Redeem negative test cases + ✓ Users 0 Deposits 1000 DAI and tries to redeem 0 DAI (revert expected) + + 40) Users 0 tries to redeem 1100 DAI from the 1000 DAI deposited (revert expected) + + 41) Users 1 deposits 1 WETH, borrows 100 DAI, tries to redeem the 1 WETH deposited (revert expected) + + LendingPool: withdraw + ✓ User 0 Deposits 1000 DAI in an empty reserve + ✓ User 0 withdraws half of the deposited DAI + ✓ User 0 withdraws remaining half of the deposited DAI + ✓ User 0 Deposits 1000 USDC in an empty reserve + ✓ User 0 withdraws half of the deposited USDC + ✓ User 0 withdraws remaining half of the deposited USDC + ✓ User 0 Deposits 1 WETH in an empty reserve + ✓ User 0 withdraws half of the deposited ETH + ✓ User 0 withdraws remaining half of the deposited ETH + + 42) Users 0 and 1 Deposit 1000 DAI, both withdraw + ✓ Users 0 deposits 1000 DAI, user 1 Deposit 1000 USDC and 1 WETH, borrows 100 DAI. User 1 tries to withdraw all the USDC + + Stable debt token tests + ✓ Tries to invoke mint not being the LendingPool + ✓ Tries to invoke burn not being the LendingPool + + Upgradeability +*** MockAToken *** + +Network: localhost +tx: 0xf94ff11f88ae61a553703ac61194b377d10db1eeb62a2ae4fc9200b2d3ac5ffe +contract address: 0xAA6DfC2A802857Fadb75726B6166484e2c011cf5 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 9499999 + +****** + +*** MockStableDebtToken *** + +Network: localhost +tx: 0x3f3fdd7645e067ef432956779e204f2b173baf87472e497c9673201c790e5543 +contract address: 0xFd23fD3d937ae73a7b545B8Bfeb218395bDe9b8f +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 6331580 + +****** + +*** MockVariableDebtToken *** + +Network: localhost +tx: 0xb17942d4f535a6fe4d349c74c5a480354d3c07565a0e8f10f05706dec1c59fcd +contract address: 0xEe821582b591CE5e4a9B7fFc4E2DAD47D3759C08 +deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 +gas price: 8000000000 +gas used: 5854360 + +****** + + ✓ Tries to update the DAI Atoken implementation with a different address than the lendingPoolManager + ✓ Upgrades the DAI Atoken implementation + ✓ Tries to update the DAI Stable debt token implementation with a different address than the lendingPoolManager + ✓ Upgrades the DAI stable debt token implementation + ✓ Tries to update the DAI variable debt token implementation with a different address than the lendingPoolManager + ✓ Upgrades the DAI variable debt token implementation + + Variable debt token tests + ✓ Tries to invoke mint not being the LendingPool + ✓ Tries to invoke burn not being the LendingPool + +·------------------------------------------------------------------|---------------------------|-------------|-----------------------------· +| Solc version: 0.6.8 · Optimizer enabled: true · Runs: 200 · Block limit: 10000000 gas │ +···································································|···························|·············|······························ +| Methods │ +·································|·································|·············|·············|·············|···············|·············· +| Contract · Method · Min · Max · Avg · # calls · eur (avg) │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · borrow · 310996 · 390411 · 342303 · 16 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · deposit · 163326 · 301355 · 211548 · 63 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · flashLoan · 127473 · 127485 · 127479 · 2 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · repay · 119550 · 218726 · 174340 · 12 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · setUserUseReserveAsCollateral · 83143 · 202731 · 134228 · 5 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · swapBorrowRateMode · - · - · 167109 · 1 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPool · withdraw · 165643 · 336106 · 226426 · 32 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolAddressesProvider · transferOwnership · - · - · 30839 · 1 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · activateReserve · - · - · 46817 · 4 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · disableBorrowingOnReserve · - · - · 50983 · 1 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · disableReserveAsCollateral · - · - · 50919 · 2 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · disableReserveStableRate · - · - · 51048 · 2 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · enableBorrowingOnReserve · - · - · 51559 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · enableReserveAsCollateral · - · - · 52408 · 4 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · enableReserveStableRate · - · - · 50928 · 4 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · freezeReserve · - · - · 50963 · 2 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · setLiquidationBonus · - · - · 51240 · 5 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · setLiquidationThreshold · - · - · 51241 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · setLtv · - · - · 51269 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · unfreezeReserve · - · - · 51026 · 4 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · updateAToken · - · - · 140669 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · updateStableDebtToken · - · - · 140932 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| LendingPoolConfigurator · updateVariableDebtToken · - · - · 140901 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| MintableERC20 · approve · 24907 · 44119 · 32449 · 47 · - │ +·································|·································|·············|·············|·············|···············|·············· +| MintableERC20 · mint · 35427 · 65475 · 40972 · 49 · - │ +·································|·································|·············|·············|·············|···············|·············· +| MintableERC20 · transfer · 138351 · 219471 · 178116 · 13 · - │ +·································|·································|·············|·············|·············|···············|·············· +| MockAToken · redirectInterestStream · 124867 · 144079 · 137671 · 3 · - │ +·································|·································|·············|·············|·············|···············|·············· +| MockFlashLoanReceiver · setFailExecutionTransfer · - · - · 42239 · 7 · - │ +·································|·································|·············|·············|·············|···············|·············· +| Deployments · · % of limit · │ +···································································|·············|·············|·············|···············|·············· +| MockVariableDebtToken · - · - · 1170872 · 11.7 % · - │ +···································································|·············|·············|·············|···············|·············· +| ValidationLogic · - · - · 1631264 · 16.3 % · - │ +·------------------------------------------------------------------|-------------|-------------|-------------|---------------|-------------· + + 115 passing (4m) + 42 failing + + 1) LendingPoolConfigurator + Deactivates the ETH reserve: + Error: VM Exception while processing transaction: revert The liquidity of the reserve needs to be 0 + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 2) LendingPoolConfigurator + Activates the ETH reserve for borrowing: + + AssertionError: expected '1000000000951293759814590868' to equal '1000000000000000000000000000' + + expected - actual + + -1000000000951293759814590868 + +1000000000000000000000000000 + + at /src/test/configurator.spec.ts:86:50 + at step (test/configurator.spec.ts:33:23) + at Object.next (test/configurator.spec.ts:14:53) + at fulfilled (test/configurator.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 3) LendingPool FlashLoan function + Takes ETH flashloan, returns the funds correctly: + + AssertionError: expected '2000720000285388128' to equal '1000720000000000000' + + expected - actual + + -2000720000285388128 + +1000720000000000000 + + at /src/test/flashloan.spec.ts:54:45 + at step (test/flashloan.spec.ts:33:23) + at Object.next (test/flashloan.spec.ts:14:53) + at fulfilled (test/flashloan.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 4) LendingPool FlashLoan function + Takes an ETH flashloan as big as the available liquidity: + + AssertionError: expected '2001620648285388128' to equal '1001620648000000000' + + expected - actual + + -2001620648285388128 + +1001620648000000000 + + at /src/test/flashloan.spec.ts:82:45 + at step (test/flashloan.spec.ts:33:23) + at Object.next (test/flashloan.spec.ts:14:53) + at fulfilled (test/flashloan.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 5) LendingPool FlashLoan function + Takes out a 500 DAI flashloan, returns the funds correctly: + AssertionError: Expected "3000450000000000000000" to be equal 1000450000000000000000 + at /src/test/flashloan.spec.ts:175:34 + at step (test/flashloan.spec.ts:33:23) + at Object.next (test/flashloan.spec.ts:14:53) + at fulfilled (test/flashloan.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 6) LendingPool liquidation - liquidator receiving aToken + LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1: + + AssertionError: expected '5534' to equal '8000' + + expected - actual + + -5534 + +8000 + + at /src/test/liquidation-atoken.spec.ts:66:88 + at step (test/liquidation-atoken.spec.ts:33:23) + at Object.next (test/liquidation-atoken.spec.ts:14:53) + at fulfilled (test/liquidation-atoken.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 7) LendingPool liquidation - liquidator receiving aToken + LIQUIDATION - Drop the health factor below 1: + + AssertionError: expected '1125536573927102016' to be less than '1000000000000000000' + + expected - actual + + -1125536573927102016 + +1000000000000000000 + + at /src/test/liquidation-atoken.spec.ts:90:68 + at step (test/liquidation-atoken.spec.ts:33:23) + at Object.next (test/liquidation-atoken.spec.ts:14:53) + at fulfilled (test/liquidation-atoken.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 8) LendingPool liquidation - liquidator receiving aToken + LIQUIDATION - Tries to liquidate a different currency than the loan principal: + AssertionError: Expected transaction to be reverted with User did not borrow the specified currency, but other exception was thrown: Error: VM Exception while processing transaction: revert Health factor is not below the threshold + + + 9) LendingPool liquidation - liquidator receiving aToken + LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral: + AssertionError: Expected transaction to be reverted with The collateral chosen cannot be liquidated, but other exception was thrown: Error: VM Exception while processing transaction: revert Health factor is not below the threshold + + + 10) LendingPool liquidation - liquidator receiving aToken + LIQUIDATION - Liquidates the borrow: + Error: VM Exception while processing transaction: revert Health factor is not below the threshold + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 11) LendingPool liquidation - liquidator receiving aToken + User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow: + Error: VM Exception while processing transaction: revert SafeMath: division by zero + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 12) LendingPool liquidation - liquidator receiving the underlying asset + LIQUIDATION - Deposits WETH, borrows DAI: + + AssertionError: expected '4513' to equal '8000' + + expected - actual + + -4513 + +8000 + + at /src/test/liquidation-underlying.spec.ts:68:88 + at step (test/liquidation-underlying.spec.ts:33:23) + at Object.next (test/liquidation-underlying.spec.ts:14:53) + at fulfilled (test/liquidation-underlying.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 13) LendingPool liquidation - liquidator receiving the underlying asset + LIQUIDATION - Drop the health factor below 1: + + AssertionError: expected '1072938234852519524' to be less than '1000000000000000000' + + expected - actual + + -1072938234852519524 + +1000000000000000000 + + at /src/test/liquidation-underlying.spec.ts:87:68 + at step (test/liquidation-underlying.spec.ts:33:23) + at Object.next (test/liquidation-underlying.spec.ts:14:53) + at fulfilled (test/liquidation-underlying.spec.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 14) LendingPool liquidation - liquidator receiving the underlying asset + LIQUIDATION - Liquidates the borrow: + Error: VM Exception while processing transaction: revert Health factor is not below the threshold + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 15) LendingPool liquidation - liquidator receiving the underlying asset + User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow: + Error: VM Exception while processing transaction: revert Health factor is not below the threshold + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 16) LendingPool liquidation - liquidator receiving the underlying asset + User 4 deposits 1000 LEND - drops HF, liquidates the LEND, which results on a lower amount being liquidated: + Error: VM Exception while processing transaction: revert Health factor is not below the threshold + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 17) LendingPool: Borrow/repay (stable rate) + User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at stable rate: + Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 18) LendingPool: Borrow/repay (stable rate) + User 1 repays the half of the DAI borrow after one year: + + AssertionError: expected '53496990783534834930102816' to be almost equal or equal '49997187848791270690420682' for property utilizationRate + + expected - actual + + -53496990783534834930102816 + +49997187848791270690420682 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:446:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 19) LendingPool: Borrow/repay (stable rate) + User 1 repays the rest of the DAI borrow after one year: + Error: VM Exception while processing transaction: revert 16 + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 20) LendingPool: Borrow/repay (stable rate) + User 1 deposits 1000 DAI, user 2 tries to borrow 1000 DAI at a stable rate without any collateral (revert expected): + + AssertionError: expected '0' to be almost equal or equal '428000013222681762110' for property principalStableDebt + + expected - actual + + -0 + +428000013222681762110 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:189:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 21) LendingPool: Borrow/repay (stable rate) + User 0 deposits 1000 DAI, user 1,2,3,4 deposit 1 WETH each and borrow 100 DAI at stable rate. Everything is repaid, user 0 withdraws: + Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 22) LendingPool: Borrow/repay (variable rate) + User 1 tries to borrow the rest of the USDC liquidity (revert expected): + + AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 23) LendingPool: Borrow/repay (variable rate) + User 1 deposits 1000 DAI, user 3 tries to borrow 1000 DAI without any collateral (revert expected): + + AssertionError: The collateral balance is 0: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 24) LendingPool: Borrow/repay (variable rate) + user 3 deposits 0.1 ETH collateral to borrow 100 DAI; 0.1 ETH is not enough to borrow 100 DAI (revert expected): + + AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 25) LendingPool: Borrow/repay (variable rate) + user 3 deposits 0.1 ETH collateral to borrow 100 USDC; 0.1 ETH is not enough to borrow 100 USDC (revert expected): + + AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 26) LendingPool: Borrow/repay (variable rate) + User 0 deposits 1000 DAI, user 6 deposits 2 WETH and borrow 100 DAI at variable rate first, then 100 DAI at stable rate, repays everything. User 0 withdraws: + Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 27) AToken: interest rate redirection negative test cases + User 0 tries to redirect the interest to user 2 twice (revert expected): + + AssertionError: expected '3000000004666017561994' to be almost equal or equal '3000002809866499332595' for property redirectionAddressRedirectedBalance + + expected - actual + + -3000000004666017561994 + +3000002809866499332595 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:692:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 28) AToken: interest rate redirection negative test cases + User 3 with 0 balance tries to redirect the interest to user 2 (revert expected): + + AssertionError: Interest stream can only be redirected if there is a valid balance: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 29) AToken: interest rate redirection + User 0 deposits 1000 DAI, redirects the interest to user 2: + Error: VM Exception while processing transaction: revert Interest is already redirected to the user + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 30) AToken: interest rate redirection + User 1 borrows another 100 DAI, repay the whole amount. Users 0 and User 2 withdraw: + + AssertionError: expected '1018781912658889894052315977' to be almost equal or equal '1018781912797584526993908257' for property currentATokenUserIndex + + expected - actual + + -1018781912658889894052315977 + +1018781912797584526993908257 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:267:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 31) AToken: interest rate redirection + User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 0 redirects interest back to himself, user 1 borrows another 100 DAI and after another year repays the whole amount. Users 0 and User 2 withdraw: + + AssertionError: expected '1020673495374568972552' to be almost equal or equal '1020673495380218720173' for property redirectionAddressRedirectedBalance + + expected - actual + + -1020673495374568972552 + +1020673495380218720173 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:692:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 32) AToken: interest rate redirection + User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 2 redirects interest to user 3. user 1 borrows another 100 DAI, user 0 deposits another 100 DAI. User 1 repays the whole amount. Users 0, 2 first 1 DAI, then everything. User 3 withdraws: + Error: VM Exception while processing transaction: revert Interest is already redirected to the user + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 33) LendingPool: Rebalance stable rate + User 1 swaps to stable, user 0 tries to rebalance but the conditions are not met (revert expected): + Error: VM Exception while processing transaction: revert 12 + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 34) LendingPool: Rebalance stable rate + User 2 deposits ETH and borrows the remaining DAI, causing the stable rates to rise (liquidity rate < user 1 borrow rate). User 0 tries to rebalance user 1 (revert expected): + Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 35) LendingPool: Rebalance stable rate + User 2 borrows more DAI, causing the liquidity rate to rise above user 1 stable borrow rate User 0 rebalances user 1: + Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 36) LendingPool: Usage as collateral + User 1 Deposits 2 ETH, disables ETH as collateral, borrows 400 DAI (revert expected): + + AssertionError: The collateral balance is 0: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 37) LendingPool: Usage as collateral + User 1 disables ETH as collateral (revert expected): + + AssertionError: User deposit is already being used as collateral: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 38) LendingPool: Swap rate mode + User 0 deposits 1000 DAI, user 1 deposits 2 ETH as collateral, borrows 100 DAI at variable rate and swaps to stable after one year: + Error: VM Exception while processing transaction: revert 12 + at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) + at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 + at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) + at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) + at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) + at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) + at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) + at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) + at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 39) LendingPool: Swap rate mode + User 1 borrows another 100 DAI, and swaps back to variable after one year, repays the loan: + + AssertionError: expected '10698732000442685488829' to be almost equal or equal '10652337619880722614595' for property totalLiquidity + + expected - actual + + -10698732000442685488829 + +10652337619880722614595 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:571:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + 40) LendingPool: Redeem negative test cases + Users 0 tries to redeem 1100 DAI from the 1000 DAI deposited (revert expected): + + AssertionError: User cannot redeem more than the available balance: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 41) LendingPool: Redeem negative test cases + Users 1 deposits 1 WETH, borrows 100 DAI, tries to redeem the 1 WETH deposited (revert expected): + + AssertionError: Transfer cannot be allowed.: Expected transaction to be reverted + + expected - actual + + -Transaction NOT reverted. + +Transaction reverted. + + + + 42) LendingPool: withdraw + Users 0 and 1 Deposit 1000 DAI, both withdraw: + + AssertionError: expected '100000000000000000000' to be almost equal or equal '1156444960439594400554' for property principalStableDebt + + expected - actual + + -100000000000000000000 + +1156444960439594400554 + + at expectEqual (test/helpers/actions.ts:806:26) + at /src/test/helpers/actions.ts:189:5 + at step (test/helpers/actions.ts:33:23) + at Object.next (test/helpers/actions.ts:14:53) + at fulfilled (test/helpers/actions.ts:5:58) + at runMicrotasks () + at processTicksAndRejections (internal/process/task_queues.js:97:5) + + + From e04d1881a18882640bb843bc832c89b0f6b1a9b7 Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 23 Aug 2020 18:42:15 +0200 Subject: [PATCH 05/33] Removed tests logfile --- tests.log | 2750 ----------------------------------------------------- 1 file changed, 2750 deletions(-) delete mode 100644 tests.log diff --git a/tests.log b/tests.log deleted file mode 100644 index 7b538da2..00000000 --- a/tests.log +++ /dev/null @@ -1,2750 +0,0 @@ -Compiling... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Compiled 68 contracts successfully - --> Deploying test environment... -*** MintableERC20 *** - -Network: localhost -tx: 0xb693d33edf5fb2e4adf9cfacde9abe07350ef8327c3fabe93d99e0428ccc53fd -contract address: 0x11df1AF606b85226Ab9a8B1FDa90395298e7494F -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** DAI *** - -Network: localhost -tx: 0xb693d33edf5fb2e4adf9cfacde9abe07350ef8327c3fabe93d99e0428ccc53fd -contract address: 0x11df1AF606b85226Ab9a8B1FDa90395298e7494F -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xd445dfad2e65e07cf8c9f31b3fed0755d619544067ba4d63b5d78f3d25664fa4 -contract address: 0x8f9A92c125FFEb83d8eC808Cd9f8cb80084c1E37 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** LEND *** - -Network: localhost -tx: 0xd445dfad2e65e07cf8c9f31b3fed0755d619544067ba4d63b5d78f3d25664fa4 -contract address: 0x8f9A92c125FFEb83d8eC808Cd9f8cb80084c1E37 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xb44d3bbdb2704e5ab272306e60f99af93fcce9ecdf14a5a303daacea79c3408b -contract address: 0xc4007844AE6bBe168cE8D692C86a7A4414FBcD26 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** TUSD *** - -Network: localhost -tx: 0xb44d3bbdb2704e5ab272306e60f99af93fcce9ecdf14a5a303daacea79c3408b -contract address: 0xc4007844AE6bBe168cE8D692C86a7A4414FBcD26 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x34b1370e38c3f89c4356ede4b3ee647790dc31a6c905ca7838b50c396a77fcea -contract address: 0xAb768C858C33DfcB6651d1174AFb750433a87Be0 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** BAT *** - -Network: localhost -tx: 0x34b1370e38c3f89c4356ede4b3ee647790dc31a6c905ca7838b50c396a77fcea -contract address: 0xAb768C858C33DfcB6651d1174AFb750433a87Be0 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x514141c9d33ef8322ceb061e23a1295802aa5598e2946b639cc1f6c6b3d4edc7 -contract address: 0x2cc20bE530F92865c2ed8CeD0b020a11bFe62Fe7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** WETH *** - -Network: localhost -tx: 0x514141c9d33ef8322ceb061e23a1295802aa5598e2946b639cc1f6c6b3d4edc7 -contract address: 0x2cc20bE530F92865c2ed8CeD0b020a11bFe62Fe7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xd9646f0608c0da17edef8a6e4cd023a6863ce240164f698d9313e70fdd3c7e1f -contract address: 0xA089557D64DAE4b4FcB65aB7C8A520AABb213e37 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** USDC *** - -Network: localhost -tx: 0xd9646f0608c0da17edef8a6e4cd023a6863ce240164f698d9313e70fdd3c7e1f -contract address: 0xA089557D64DAE4b4FcB65aB7C8A520AABb213e37 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xc1be16014389ca278747424393a740bca4ec447fbd9caa4f4982e351ee266108 -contract address: 0x20FAE2042b362E3FaB2806820b9A43CC116e2846 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** USDT *** - -Network: localhost -tx: 0xc1be16014389ca278747424393a740bca4ec447fbd9caa4f4982e351ee266108 -contract address: 0x20FAE2042b362E3FaB2806820b9A43CC116e2846 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x50f85855b779985f4a404b35505783e7135433034149f253eae0cab1400ae353 -contract address: 0x8880F314112f15C2AfF674c3B27f9a44Ca86e4d0 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** SUSD *** - -Network: localhost -tx: 0x50f85855b779985f4a404b35505783e7135433034149f253eae0cab1400ae353 -contract address: 0x8880F314112f15C2AfF674c3B27f9a44Ca86e4d0 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xa51d0baa6dd5cda1f4631af260b5ed8ecae708d5f5bcde76961f31bcfd4ba7eb -contract address: 0xDcb10C2e15110Db4B02C0a1df459768E680ce245 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** ZRX *** - -Network: localhost -tx: 0xa51d0baa6dd5cda1f4631af260b5ed8ecae708d5f5bcde76961f31bcfd4ba7eb -contract address: 0xDcb10C2e15110Db4B02C0a1df459768E680ce245 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x9bfdcd29285b0fab25adf99c1fca8059bbf38cb1a9f8e59e7d3fefda8d6eb03b -contract address: 0xfD408ec64Da574b1859814F810564f73ea2Ff003 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MKR *** - -Network: localhost -tx: 0x9bfdcd29285b0fab25adf99c1fca8059bbf38cb1a9f8e59e7d3fefda8d6eb03b -contract address: 0xfD408ec64Da574b1859814F810564f73ea2Ff003 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xfd8468df934e43ccec60acba936b601c27847183c18a3f5d6535763b60e6fbaa -contract address: 0x0006F7c3542BEE76Dd887f54eD22405Ac4ae905a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** WBTC *** - -Network: localhost -tx: 0xfd8468df934e43ccec60acba936b601c27847183c18a3f5d6535763b60e6fbaa -contract address: 0x0006F7c3542BEE76Dd887f54eD22405Ac4ae905a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x657f63363d8df1a8b2e06a93e3c1d869b945f5970460101fed9b82bce2f0881c -contract address: 0x6ca94a51c644eca3F9CA315bcC41CbA6940A66Eb -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** LINK *** - -Network: localhost -tx: 0x657f63363d8df1a8b2e06a93e3c1d869b945f5970460101fed9b82bce2f0881c -contract address: 0x6ca94a51c644eca3F9CA315bcC41CbA6940A66Eb -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xc9eaaddbc4add294cbf0511d1f35096063ea66f9528a284cf1a8f2b69d8431b7 -contract address: 0x6765291Cab755B980F377445eFd0F9F945CDA6C4 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** KNC *** - -Network: localhost -tx: 0xc9eaaddbc4add294cbf0511d1f35096063ea66f9528a284cf1a8f2b69d8431b7 -contract address: 0x6765291Cab755B980F377445eFd0F9F945CDA6C4 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xd2a8b51e3d598379b72f199c37046a74bdea759e78edfbb651190fd3098ca038 -contract address: 0xa7dB4d25Fc525d19Fbda4E74AAF447B88420FbcB -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MANA *** - -Network: localhost -tx: 0xd2a8b51e3d598379b72f199c37046a74bdea759e78edfbb651190fd3098ca038 -contract address: 0xa7dB4d25Fc525d19Fbda4E74AAF447B88420FbcB -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x30da604c48ddf9d6724087a17e66a0283762c0df47e402484cb47a742f3bc3a1 -contract address: 0x273D60904A8DBa3Ae6B20505c59902644124fF0E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** REP *** - -Network: localhost -tx: 0x30da604c48ddf9d6724087a17e66a0283762c0df47e402484cb47a742f3bc3a1 -contract address: 0x273D60904A8DBa3Ae6B20505c59902644124fF0E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xf75538604aa40a916f3b53aa71f0d3f4d2985e3e313aefcdd20ec03efb03fe58 -contract address: 0xfc37dE87C1Ee39cc856782BF96fEdcB6FA5c5A7f -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** SNX *** - -Network: localhost -tx: 0xf75538604aa40a916f3b53aa71f0d3f4d2985e3e313aefcdd20ec03efb03fe58 -contract address: 0xfc37dE87C1Ee39cc856782BF96fEdcB6FA5c5A7f -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x144bd6a169a5878c72d1c1b7fed21cad13c046cc5608975a7c7f05efb6c11c79 -contract address: 0x049228dFFEdf91ff224e9F96247aEBA700e3590c -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** BUSD *** - -Network: localhost -tx: 0x144bd6a169a5878c72d1c1b7fed21cad13c046cc5608975a7c7f05efb6c11c79 -contract address: 0x049228dFFEdf91ff224e9F96247aEBA700e3590c -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770555 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x61d73d01885b056022452fb9df317c03167ce8bfa8d8b70f09f5ba3ba84087e0 -contract address: 0xA410D1f3fEAF300842142Cd7AA1709D84944DCb7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** USD *** - -Network: localhost -tx: 0x61d73d01885b056022452fb9df317c03167ce8bfa8d8b70f09f5ba3ba84087e0 -contract address: 0xA410D1f3fEAF300842142Cd7AA1709D84944DCb7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3770435 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x740b8681b0c8b7d3fbc23b29070e5a4ce1d278c456740949e6958217acb4d452 -contract address: 0x835973768750b3ED2D5c3EF5AdcD5eDb44d12aD4 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771395 - -****** - -*** UNI_DAI_ETH *** - -Network: localhost -tx: 0x740b8681b0c8b7d3fbc23b29070e5a4ce1d278c456740949e6958217acb4d452 -contract address: 0x835973768750b3ED2D5c3EF5AdcD5eDb44d12aD4 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771395 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0xfd37d9b66d1f1ab4cb4b243d14927f8b1d65e1b51001a312ccad621387838be1 -contract address: 0x1181FC27dbF04B5105243E60BB1936c002e9d5C8 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** UNI_USDC_ETH *** - -Network: localhost -tx: 0xfd37d9b66d1f1ab4cb4b243d14927f8b1d65e1b51001a312ccad621387838be1 -contract address: 0x1181FC27dbF04B5105243E60BB1936c002e9d5C8 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x6720a4ff9ab66ceb1d378c93a7254f49a646c40896274ee8f3e02e6fa1f301d6 -contract address: 0x6F96975e2a0e1380b6e2e406BB33Ae96e4b6DB65 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** UNI_SETH_ETH *** - -Network: localhost -tx: 0x6720a4ff9ab66ceb1d378c93a7254f49a646c40896274ee8f3e02e6fa1f301d6 -contract address: 0x6F96975e2a0e1380b6e2e406BB33Ae96e4b6DB65 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x7bfa83b2c563a4646d62d9a241368f64c21538d2b9b272d2dbcaebaea3003cdd -contract address: 0xc032930653da193EDE295B4DcE3DD093a695c3b3 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** UNI_LINK_ETH *** - -Network: localhost -tx: 0x7bfa83b2c563a4646d62d9a241368f64c21538d2b9b272d2dbcaebaea3003cdd -contract address: 0xc032930653da193EDE295B4DcE3DD093a695c3b3 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x710172661439f201e9e857de79517f4a10dc1c50f43431112ca14182d249e77f -contract address: 0xb3363f4349b1160DbA55ec4D82fDe874A4123A2a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771395 - -****** - -*** UNI_MKR_ETH *** - -Network: localhost -tx: 0x710172661439f201e9e857de79517f4a10dc1c50f43431112ca14182d249e77f -contract address: 0xb3363f4349b1160DbA55ec4D82fDe874A4123A2a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771395 - -****** - -*** MintableERC20 *** - -Network: localhost -tx: 0x44218a2b69f73edd259ee7531e07181321912029d61517b450235eeb7c172d26 -contract address: 0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** UNI_LEND_ETH *** - -Network: localhost -tx: 0x44218a2b69f73edd259ee7531e07181321912029d61517b450235eeb7c172d26 -contract address: 0xf8c6eB390cDc5C08717bC2268aa0c1169A9B5deE -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 3771515 - -****** - -*** LendingPoolAddressesProvider *** - -Network: localhost -tx: 0x85c590408781fb6cf1a6416f3f7f5bcafe93d00f5ef8ca42080daaf4a494ef3f -contract address: 0x4a716924Dad0c0d0E558844F304548814e7089F1 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6959345 - -****** - -*** LendingPoolAddressesProviderRegistry *** - -Network: localhost -tx: 0x7b9a2d4c2da516b51d7517aae0ba274427bceecb3e1f1905f4e98b9ae1c10884 -contract address: 0x798c5b4b62b1eA9D64955D6751B03075A003F123 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2407480 - -****** - -Deployed lending pool, address: 0x8a32f94F052F38d0436C68d6bb761619c475b987 -Added pool to addresses provider -Address is 0xf9cD0476CFC1E983e9feA9366A2C08e10eFc9e25 -implementation set, address: 0xf9cD0476CFC1E983e9feA9366A2C08e10eFc9e25 -*** LendingPoolConfigurator *** - -Network: localhost -tx: 0x468a8bb8eb2d469e3fa069cfdac02f25a48086833360a8b4e23b187b5e64aa82 -contract address: 0xd63ae78CE8D440CbBc4E9B573AA81522DBf1e4D1 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** PriceOracle *** - -Network: localhost -tx: 0x8d36bb456d6e2fb92682cfa5bd12348afb64de8c1af68ed583f34f25e381a1a0 -contract address: 0x18C3df59BEb7babb81BC20f61c5C175D0Cb7603d -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 767525 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x54bab4c8c78250e428e31baaa5cb2fcc117e90797f24eb76360fc9a37d0eacd6 -contract address: 0x4819594Fa472a722E6f08aD2d0D1f829AfF6b1D1 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524490 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xb82c4bd0a169b97cc044ce4d5d4935e440b114a9da1b7d1a3fb9cd90e4f90dbb -contract address: 0x5eD7553Dc8a0D541130020f9965Ea951cAC1b573 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x6c9e9b7c63860c736a8c93d1957e602924c30f23ea58e28897a8681b264f00d0 -contract address: 0xE0A4f15eBcC30F67782800479C89692d2E40d511 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xe06a6d27906950183f569b54bc3cab756dd3987c4c1a40a55adb9fe1a72c7396 -contract address: 0x32e036B2e3B5A998401eFA43f779d2070fAC2A7D -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x9ef232a904789a257512db57f8cc2662e7a481df6e8f95a041208503047c8368 -contract address: 0xB62f98C002fc1D336Ab1EaF7a890B26E1191F0f2 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524490 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x7384bb1e853e761e3b61bc286331e7f302a77ebcad6cfed6c9fd65f60e521c79 -contract address: 0x57Aa7e5dEF9cBb8327c764e31E7C8f0996ae0f91 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524490 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x976b29e38f1b052805164a337b21f451cbfb2328b8951882e527b8d51894310b -contract address: 0x08c4284C1645529732466fd9c322a8d0d8C6AC70 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x7b48370fe9e1e971ea386ca9647470d670ca238425dc42e13742dfbae71b1cae -contract address: 0x9e4c352aa01D2eC5c6917e79a19e74B27Ab6Be85 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524490 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xd89d74e0609f162d9ce0b6b6950c112b76f09293e0f44c75890101473de91554 -contract address: 0x022cFA026CA96fABfDae3b3a7830d1026cbbd336 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xe4fd2a196be6b31c06f4096d1b7a7800c9559df8c38d259c853bca3e408e8ed2 -contract address: 0xD7B4b736722c350c1ee35e0522fd9b38546c1b18 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xc49ce797d6f08cb184f77f1b1f45ee565cfb4313f2d2a5aefd95989ce56cfa8b -contract address: 0xCa2adc1CEe345762b823C55A18f60874d6aCd4ad -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524550 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x655ef0633e66f53aa8b80b44ccd3718497e39a27324758913867510b23ab5b35 -contract address: 0xf880fBe54ea8cc8E2DdF115435D46C7f3B050217 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x493b84ce76a92315beb3df1478893a68c0ffccf46e67601165c54ae981a68089 -contract address: 0x68730f335681eccdd55127a4ebEbbDc9e5Ee542C -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524370 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x6d76dcb43e91ee29b2a0229e73f34b831af7125fb8d7c780f3d09063c7e85a39 -contract address: 0x0bf755084d2af8df01b046e3c3981EC5C545A26A -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524370 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x4a95ea0c1029afaf14dc2b45590e0eb01da7f9ddc06486245b9e4437a45f468e -contract address: 0x85a0419D3Cbc60ffdD3128EC1b0D3737091DF748 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x5e5158c387d616d4768e2f395adab805e7071974a129b953d4d0e11f8c35dd8f -contract address: 0x9CDDBE77d2f4D505Ed8aD63Bf4061876C8E8B94d -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x2631a412a26f480d3af0ab0578736f787a4e903c7141fbfcf17ad28e00cd585d -contract address: 0x67918d986Cb2C0A8465369d4d6B21BE492E49522 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x8864f5076054fccf00faf3d933e63f8d44d191deea4e1c68674134c57fb6bb30 -contract address: 0xfa7cC137C527920Ae5E85311bAe7eFFd55d7c1B3 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xebd805e8af09d3814431b49a2fc4beeee44e54a17249dbc57dcc2065b2537d58 -contract address: 0xD7619aE561dDeB7eD73bDf7d640DAe32b643D026 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x33e4686ecfda16b719ddccf20e6e28e536a5b72dc1e77b8a7245d18c0a1a7674 -contract address: 0xB66bB20a2d1800fB08d59E6eF1C34E738aea9084 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x30f61c84c0f9dc4236b9ba4fe227989d5463e8534bddaf1fa4f046631b7324ad -contract address: 0x34Bcbf717e1Cb4Fa3f779297d6128D580B87BA23 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0xd6f95a84f6056b18218397aefa2b0a62fd2fa16071c3708ba627f468485085be -contract address: 0xe74F2b30C2AC45Ab5162795F2fFA6ACBA5C41FCe -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x7a878b5b5029bad142dda20da6f120e060bf8311ba80f22e98ff8fc539f38724 -contract address: 0xce8d1D7665832237b1eae6267C0cA5aCC11B7fE6 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** MockAggregator *** - -Network: localhost -tx: 0x2e80f1c33b474542733682528ed1e072406b585dcfaa2c158e6ce87295308b19 -contract address: 0x39ed2aE701B56AD229A19E628Bf5A515795F0AA3 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 524430 - -****** - -*** ChainlinkProxyPriceProvider *** - -Network: localhost -tx: 0x5125f9e283f93d831c4961c06e23fc7e11533d8942685c2b1d3743c1adcddb3e -contract address: 0x9434029990cF00118c28a06E014F0d7d879f28CE -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6255420 - -****** - -*** LendingRateOracle *** - -Network: localhost -tx: 0x170675f0f61bafaef087a2f9b8cc9c9d541c14dfeea7f93cd2f9e71e821ce7e6 -contract address: 0xccd7A2534fd4FD5119De8E368615b226e23F8F37 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 1720040 - -****** - -Initialize configuration -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x74ff24b7fa40f7311401945b7ce6955643e45d8ed25108917d4c59f8d374741b -contract address: 0xB7EB48C88bdaf6B8B2ea02bC822A4a132328f714 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xf67b77de54001ea7cb0e2a53b66e4b8a492921215606603453d93428dfc4a5e0 -contract address: 0xC0E8d6e5574cd52B1a8dab202Aa3fec21B74BC35 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x54278f78c259d1281c785529b330a19b1a584623e95fc645934f924c40ec3198 -contract address: 0x34Af2d98209B5F5d28faC0eec6285D4Dd65c589D -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x579e7172f7886844afffa3bdafe1a9e6dc23e1dd6507a75b67ee8b3cdcf67118 -contract address: 0xf5D5224509Abe68408d3D2080909B8EBeCa07B02 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xe350cca6989ccd7107176b683407949edba2b51cac58203f77416789f475956a -contract address: 0x8eB5127325c66e28197f2a9fB6a52a79d5fD381e -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x4d14f22ec586cd818a2dd2f77102175d8648918d7612061fd79cf78c5ebfc65a -contract address: 0xd7a76AA426EBAb1E67c63d48A22b5d7151eeac3F -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128250 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x80011ba6270adf75e11c12bc5f17ccd09c42634030675cba721f800babf4b294 -contract address: 0x43bD57b672AF17656bE2B3f21bDe64da757f08B5 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651030 - -****** - -*** AToken *** - -Network: localhost -tx: 0xd37d2e127a4f8d4a5049a13d51bbc1f705881d518aaa76237a9945d42da9fe04 -contract address: 0x98D9d1E46351945fdf5A6C8fc2b1FbB7cB4D6758 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x15a2b44162ae48fec47aaca929404375b87a57a145f479c80f4b32bd81b4e277 -contract address: 0xAACe6c4759b2bF94cF4cf3b1cF2f4fd726033784 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xdc849ac47472f3153a70895141866dc05ebfce2dce0559a21c31fb683723e2af -contract address: 0x1Cb5F6F553a5434b842AC5fE0e52C78338612B77 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x6486e963bcf1e59789b27cf4844f6a1d935a1827b35c404f03f15fff906ea60c -contract address: 0x333CF5E8039a9ecBdAA4fF4E9f7D10842f06E7b4 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0xc02452e70ab23cfe77f62e3cbdd901369a496deb798fa937a2971386793f0098 -contract address: 0x09678e127117c3F342E52014BAC7e0De59cA4B41 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x9dc14c88bfeb86024b773cb91403cf998e9fba202c9d816e4a93e5c893378b95 -contract address: 0x83c60fAD6afA5E8A38Fb7549174e216C5efe85Bd -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xd96a4d6c9d17e76b95bcfb185b2717849bd1797294195746a39a68980b5b8b09 -contract address: 0x2C6152331cA1F9AEc74523171a496d61C7203e64 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x00dd0efaa7da4dc8b1ec77ce6bfd9a3ce45233487233930f59347a3ed2ba74bb -contract address: 0xAa1b47a6139A4cad87464911812f92c0ba2db0d7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0x4526b4c92699d36aa178b319c933e71c0eaa5dfca2fd3f92467d87084e87f3bd -contract address: 0x812B84Aac96db85B65A35c1ea93789DA0d977113 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xe56d3118f791864b63d5a1d9be52bc77da65f4ab4e8b75b0e04a2e55affdf1fe -contract address: 0x5da6809Fe6d0743125Ec39AFCF9E38ea0F0B5d4E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x975b727795a15df3445b9b23ffba7f8e646a67a848d536215e1576fab58a8846 -contract address: 0xE95D3B838c8A4e52C8059cc75a18FB6d2EDA043a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x9682837a645353709ecdca94a65a8fe22eab97c3d9cf848cdd0128b36749fa24 -contract address: 0x5DaF25c6E608CFd427Dbae874B8a5441d0018339 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0xe3e27056c5b4c26fa31cfc91f6934d8cd6f0245e7fa2ce2f3d09521aa03b3a9f -contract address: 0x4aDdfb6d8994197b666c8FB167dAF9576D052d26 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x6006c2c541d8f824047b470b22314f6b85fd2d0709132fe7fd72922ce2444cfd -contract address: 0xEdA424B933c9F5C9D82718db4A5AB9CEAE3A8344 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x0a3af97e935a83b82fd9ad1cb63dbd06ee5009aa0d986977836f30acda87faaa -contract address: 0x10E99C82512838Ed9fD2FC40d71DAC29dCA497EC -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xda2e3cd3897dbfe6c0f6b73dcde49010a6cada5df7a4f0038063722e1814f5a3 -contract address: 0x6396ed1AFa51770f2B26BC582Ff9878A3e34b126 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0xb5acb13cfe7914ff8fad7e5c28b46e9f689e13a7dd5449492322c59d73f843bf -contract address: 0x09D011f96C64feB12c2C614c5BB012dEfb63E16D -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x1321448a7f01e61623fb1ee6c3db90da2adf86cf8aab197e1942b2c891e6ffce -contract address: 0xAc90A2D29a669aa51c3a5506b577D59DDc931c6e -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x19a8d0b6e4b9aa523256a4c9eed5453701647671a5779743b0f5afa3e58f11d2 -contract address: 0x3a629468EDf66d22d69F84C5EFFadc6C2BEA4d5C -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x67ac2f70267459b17f88d1a06c164322164239f9c8267b544badc2ad79790226 -contract address: 0x9BDb2e959aD37ddA24b6A770993852E99970b8F8 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x4220df2a27a81f69625a2d0cbba1f4383e4ef12158e28eef912beb0d5160b338 -contract address: 0xd1E1BC4D1C225D9029f14f8b8eFcF12F0eA51C1e -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x3296da75785d3dcbae0fbbef6cbe60f2f7a1f207a632a176c90a646febf4eb36 -contract address: 0x6d2BfF57A95f2b96d33C27b281e718C4FC76222e -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xe4d89df27c5d2e70f84c575cdf7ebff25f815b0d82f91f9423a0cf0d339c4e8f -contract address: 0xD8cF367dce091A6bFB2a9d4A3673F80a616bd8B7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xe0da49201fcb21f10c2884279ee43ad63ae346139e9f95e7991a7b7c378e0d6d -contract address: 0x629bBA58D1Bc73e9C515668A76F00DC8FE852065 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x6a19fa9c7cbc714245413d7cef76ad8d84a6f267950c8b531f4fb4403e2c57a7 -contract address: 0x2Ded2482555ABf714ebbc9Dd4b589e093C1a9eD2 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x521d14b37d34e8842e11897cbde3c6c75b991a749274e4d63dc5507c78e4f7ac -contract address: 0x2ECdf4E23a561A58E9e0f70cD109e8cD1C86A827 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x92673002c4b70c9670f154724bdb48293b9652b4d916a5ea0b9b33e808cd9270 -contract address: 0xf70adAAfe9883E4D52587197Cd39dc85C2B23c57 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xdfa31bd3eaeb3367325257b7ee283867dc5bb62ae8e8f43e42547e6c6053200f -contract address: 0xC07b1cE4372334264E2124b893b8445F34c2009f -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0x355e2ef294f2951dfa2f039db038543c0abeec606cd69bc425ccfdfc587fa0d2 -contract address: 0x1b9F3F849801E7Bc6C3124296fc35A83Fd40654b -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xefd434318327a3626c371301a42d2cc9f1b17cad2dfb4f1c42fb56b09b8e41aa -contract address: 0x501Cb4bBA78Ca688A59DEedE4E121590eEC20C77 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xe36cb2e2369f27648748e0e182329cbf906f31fd832e67de78d8686501b489a5 -contract address: 0x3346C431D2E9bA398a5A690ca49Ca4E3b13472FD -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128250 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x48fb6ae7811bd7c8fdec948249d1e9ad78439ce7a5b2a5983b92a87b844e02a8 -contract address: 0xcb82DF442005768Bd6E3f1597255dfD60Af26d57 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651030 - -****** - -*** AToken *** - -Network: localhost -tx: 0xad153aa4fdd44ad6fb893766cc7eda637b6b0cba2859fe9c56dd522bc2e65e12 -contract address: 0x6fb48b45f290a76c1331991c9D7F8ef3D9FE5C36 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x7cea4f37b50c4786e9df8ca8f09c29ed9b1daf4d05ff41210b23e4642f22cb23 -contract address: 0xaCb0e28183B6e3b27741776B9A013521d92dcf42 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x3b920d6dee6aecb25f15cf7a1a884c26e1186958fe487672f51e4fcf0ebd7f94 -contract address: 0xA1efebb06E897703b1AEC2a8FA6141e377752b1d -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xc771692ccb883a273b63235e551f1570b20fc2946b6a3a6c2f75561746acd80c -contract address: 0xb664f305eB269F7EE2Bc657C59c0d8D4101c6857 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x542ba4ab070c693dac934480a950b60c99137fe160cebe1f3092a3f5812faca3 -contract address: 0x29C059D0CB7621BA9E93467945A6336c783b2d2A -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x09b12f7981ceff6df8f318a23dae0eb46a2a00058b209e8dfea68fd4c71df420 -contract address: 0xbB405796150960679458C9F03e7da176F7daC6d3 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x5bd0106deaac62e2bcd5ed0cf584b5e833610a736e04c95c65a98ed04cc45a73 -contract address: 0xB82b53c852eABCFd35C757119C520F382eC31390 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x08f3c16876b91a7cc6beec71b7173ae2dcca520c860c744174f2110d52d3305d -contract address: 0x87F5639fAe81B9Ee55AAc08aE306fB92f5AB6e71 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0xdb1a23da614ea9b704fe3580cc9af14889a1a26814e56b28d5cca7fbf1aada4e -contract address: 0xc86eF02EB0d1F712a2A054887a5Eab982a983C3f -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x41f78876c9a8ba8372b2a0ef0fe7cc0b1c398a01e4bf28ef89f85b3e1dbb90ab -contract address: 0x84C055Cf6b1429f41673d04D17019276547c4af0 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x19dfde9cb5c45ea0b3586f752f80ebf9a6c02e55a6cf77a77688254ccf2541be -contract address: 0x52b733D5fA53E72E8A788419836e261b6Fa0eFC6 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xd36fcbb46b8cb664848df13f51120b3af95a99e333d5d324e463eec1f56f10c3 -contract address: 0x5ff9A2405b72d33911853f1d0bFFC361baCE435E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x6a864bf1910e626bfb808e92827be216bea78040f3d7f1f33b28a3e5ae18c631 -contract address: 0x9e2548EB10fC28CE3D1654BC7421808eE7092081 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xdd6117ffb11e3390a0610eadcea4520d25543dea7214686d147c75f610adea30 -contract address: 0x792d861D3791F4Cce91798260F863110D2D9E75b -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x814b1dc18904a1ca05c5ae4c5bb68ab73fac59c48e11924d1307ab5094411cfc -contract address: 0x5488bf6d62876d141cB0Db48929679D37dB265a5 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128310 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xb224b45f3831151e6dc6412f9205b442ec30b0bfd453589d5847faf8fa334c97 -contract address: 0x6F7ee89b972c3212452E1e58628dAf7a3b7E9c7e -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651090 - -****** - -*** AToken *** - -Network: localhost -tx: 0x250e2640db49570381e16d893884744d53206256dc442c74e2359374cd6c1341 -contract address: 0xe3A3fa239eE31b38E56d8136822c3af7089B5b0E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xb919389e36595914e6fa47a78b402550b70fa55140769091f682463caed539e4 -contract address: 0x0aB0E3A07e92E161D461deDCAEdDFef906993f84 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2916655 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xfde754172191e3885aeaf871e9ec3a0e7f9e5534b038cc256fd6e2164aa1e8d9 -contract address: 0xB964CE42932638Fc51cBFc7158686EF3f56D3262 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xf78ff3151eede55e5a3ce4e819f6ab262ac1704dd7a66f364339959c3fde919f -contract address: 0xa2203A921E4e6FeccCAbE83A19029B5200bEe779 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x097bb8c68f3ba3552eab3b0a91ee58b25d25d2573b2a71465687c068620bc8f9 -contract address: 0x61fCca5fcBEF2200C40c3e9ef555B9954035315D -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0xabdb3c57d8a1859003a9cc92b0a5d668eee974fdf18e30481d97ea0be5090e48 -contract address: 0x9DDc5C465F70b0dc78dF7cd02f52bc3d2751282a -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0xff60cd11c4845d9946fa1cbd5784ad799ce4dcfe5ee4c5c137eb638bc331a001 -contract address: 0x1D2a59d3276A669d1943fc6BDF997BF697D09565 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128190 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0xe7d8bc58eaadc19908c1493ba9b320a6c0a45ac29fe7572c83466df41e1f2a98 -contract address: 0x1e3Fcd041d44C88762255E8eFda30d0Fc22FEe76 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5650970 - -****** - -*** AToken *** - -Network: localhost -tx: 0x38c31626f6d081130717f3b145a156421844612f3c6eaafc89c4a179bf550c41 -contract address: 0x45585e87e657a54A0a0Fa25a6572217E63E5F2f7 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** DefaultReserveInterestRateStrategy *** - -Network: localhost -tx: 0x324b1818692ada5ed43f7aa74c2f7da29808c44cdc77fe14716cdc48c02ff31d -contract address: 0x4c010BA8A40e5c13Acc1E32c025c2b2aea405Dbb -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2917135 - -****** - -*** StableDebtToken *** - -Network: localhost -tx: 0x5ccd1b76e8d2b577890fa4bedf04152628bc7480be830247eafba3d1fc08e7d9 -contract address: 0x2ca7Aa6CcCdb5D77F1c1d3E6a21fF0F7ac24C825 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6128250 - -****** - -*** VariableDebtToken *** - -Network: localhost -tx: 0x1fbd7ae4adf29a8c8fbed413c48cbe83bfd81f2475bf87aeec7ad19496fc9624 -contract address: 0x527a346011Cd6c71973f653426Ce609fa53dd59E -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5651030 - -****** - -*** AToken *** - -Network: localhost -tx: 0x35e4a759c6f93001aa11697082373f645f9e2d12f3c2247a9c7f8245643a8db4 -contract address: 0x3035D5D127487Ee5Df5FD951D9624a8b877A8497 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** MockFlashLoanReceiver *** - -Network: localhost -tx: 0xd7ee83594c1b864fb16cf8ff63e95b122af260df3f2b56eb643dcf004e12e507 -contract address: 0x2aE520a05B31f170a18C425a1e8626aB7Ef71984 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 1730710 - -****** - -*** WalletBalanceProvider *** - -Network: localhost -tx: 0x4043a4de9ef7fe0f601dbdcf4775c9384d2db0b4c867410cdbeb92512d647ff7 -contract address: 0xBD2244f43f7BA73eB35A64302A6D8DBf17BdF2F1 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2512320 - -****** - -*** AaveProtocolTestHelpers *** - -Network: localhost -tx: 0xb406d28fc743855f784a865268662ed03bf4043f76d9a76fcafca2867b4e94c7 -contract address: 0x18c3e48a45839B3BbC998c70A2fD41fB8D93a35D -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 2818975 - -****** - -setup: 22.891s -Pool loaded -Configurator loaded - -*************** -Setup and snapshot finished -*************** - - AToken: Modifiers - ✓ Tries to invoke mint not being the LendingPool - ✓ Tries to invoke burn not being the LendingPool - ✓ Tries to invoke transferOnLiquidation not being the LendingPool - ✓ Tries to invoke transferUnderlyingTo not being the LendingPool - - AToken: Transfer - ✓ User 0 deposits 1000 DAI, transfers to user 1 - ✓ User 1 redirects interest to user 2, transfers 500 DAI back to user 0 - ✓ User 0 transfers back to user 1 - ✓ User 0 deposits 1 WETH and user 1 tries to borrow, but the aTokens received as a transfer are not available as collateral (revert expected) - ✓ User 1 sets the DAI as collateral and borrows, tries to transfer everything back to user 0 (revert expected) - ✓ User 0 tries to transfer 0 balance (revert expected) - ✓ User 1 repays the borrow, transfers aDAI back to user 0 - ✓ User 0 redirects interest to user 2, transfers 500 aDAI to user 1. User 1 redirects to user 3. User 0 transfers another 100 aDAI - ✓ User 1 transfers the whole amount to himself - - LendingPoolConfigurator - - 1) Deactivates the ETH reserve - ✓ Rectivates the ETH reserve - ✓ Check the onlyLendingPoolManager on deactivateReserve - ✓ Check the onlyLendingPoolManager on activateReserve - ✓ Freezes the ETH reserve - ✓ Unfreezes the ETH reserve - ✓ Check the onlyLendingPoolManager on freezeReserve - ✓ Check the onlyLendingPoolManager on unfreezeReserve - ✓ Deactivates the ETH reserve for borrowing - - 2) Activates the ETH reserve for borrowing - ✓ Check the onlyLendingPoolManager on disableBorrowingOnReserve - ✓ Check the onlyLendingPoolManager on enableBorrowingOnReserve - ✓ Deactivates the ETH reserve as collateral - ✓ Activates the ETH reserve as collateral - ✓ Check the onlyLendingPoolManager on disableReserveAsCollateral - ✓ Check the onlyLendingPoolManager on enableReserveAsCollateral - ✓ Disable stable borrow rate on the ETH reserve - ✓ Enables stable borrow rate on the ETH reserve - ✓ Check the onlyLendingPoolManager on disableReserveStableRate - ✓ Check the onlyLendingPoolManager on enableReserveStableRate - ✓ Changes LTV of the reserve - ✓ Check the onlyLendingPoolManager on setLtv - ✓ Changes liquidation threshold of the reserve - ✓ Check the onlyLendingPoolManager on setLiquidationThreshold - ✓ Changes liquidation bonus of the reserve - ✓ Check the onlyLendingPoolManager on setLiquidationBonus - ✓ Check the onlyLendingPoolManager on setReserveDecimals - ✓ Check the onlyLendingPoolManager on setLiquidationBonus - ✓ Reverts when trying to disable the DAI reserve with liquidity on it - - LendingPool FlashLoan function - ✓ Deposits ETH into the reserve - - 3) Takes ETH flashloan, returns the funds correctly -Total liquidity is 2000720000285388128 - - 4) Takes an ETH flashloan as big as the available liquidity - ✓ Takes WETH flashloan, does not return the funds (revert expected) - ✓ tries to take a very small flashloan, which would result in 0 fees (revert expected) - ✓ tries to take a flashloan that is bigger than the available liquidity (revert expected) - ✓ tries to take a flashloan using a non contract address as receiver (revert expected) - ✓ Deposits DAI into the reserve - - 5) Takes out a 500 DAI flashloan, returns the funds correctly - ✓ Takes out a 500 DAI flashloan, does not return the funds (revert expected) - - LendingPoolAddressesProvider - ✓ Test the accessibility of the LendingPoolAddressesProvider - - LendingPool liquidation - liquidator receiving aToken - - 6) LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1 - - 7) LIQUIDATION - Drop the health factor below 1 - - 8) LIQUIDATION - Tries to liquidate a different currency than the loan principal - - 9) LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral - - 10) LIQUIDATION - Liquidates the borrow - - 11) User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow - - LendingPool liquidation - liquidator receiving the underlying asset - - 12) LIQUIDATION - Deposits WETH, borrows DAI - - 13) LIQUIDATION - Drop the health factor below 1 - - 14) LIQUIDATION - Liquidates the borrow - - 15) User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow - - 16) User 4 deposits 1000 LEND - drops HF, liquidates the LEND, which results on a lower amount being liquidated - - LendingPool: Borrow negatives (reverts) - ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and tries to borrow 100 DAI with rate mode NONE (revert expected) - ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and tries to borrow 100 DAI with an invalid rate mode (revert expected) - - LendingPool: Borrow/repay (stable rate) - - 17) User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at stable rate - ✓ User 1 tries to borrow the rest of the DAI liquidity (revert expected) - - 18) User 1 repays the half of the DAI borrow after one year - - 19) User 1 repays the rest of the DAI borrow after one year - ✓ User 0 withdraws the deposited DAI plus interest - - 20) User 1 deposits 1000 DAI, user 2 tries to borrow 1000 DAI at a stable rate without any collateral (revert expected) - - 21) User 0 deposits 1000 DAI, user 1,2,3,4 deposit 1 WETH each and borrow 100 DAI at stable rate. Everything is repaid, user 0 withdraws - ✓ User 0 deposits 1000 DAI, user 1 deposits 2 WETH and borrow 100 DAI at stable rate first, then 100 DAI at variable rate, repays everything. User 0 withdraws - - LendingPool: Borrow/repay (variable rate) - ✓ User 2 deposits 1 DAI to account for rounding errors - ✓ User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at variable rate - ✓ User 1 tries to borrow the rest of the DAI liquidity (revert expected) - ✓ User 1 tries to repay 0 DAI (revert expected) - ✓ User 1 repays a small amount of DAI, enough to cover a small part of the interest - ✓ User 1 repays the DAI borrow after one year - ✓ User 0 withdraws the deposited DAI plus interest - ✓ User 1 withdraws the collateral - ✓ User 2 deposits a small amount of WETH to account for rounding errors - ✓ User 0 deposits 1 WETH, user 1 deposits 100 LINK as collateral and borrows 0.5 ETH at variable rate - ✓ User 1 tries to repay 0 ETH - ✓ User 2 tries to repay everything on behalf of user 1 using uint(-1) (revert expected) - ✓ User 3 repays a small amount of WETH on behalf of user 1 - ✓ User 1 repays the WETH borrow after one year - ✓ User 0 withdraws the deposited WETH plus interest - ✓ User 1 withdraws the collateral - ✓ User 2 deposits 1 USDC to account for rounding errors - ✓ User 0 deposits 1000 USDC, user 1 deposits 1 WETH as collateral and borrows 100 USDC at variable rate - - 22) User 1 tries to borrow the rest of the USDC liquidity (revert expected) - ✓ User 1 repays the USDC borrow after one year - ✓ User 0 withdraws the deposited USDC plus interest - ✓ User 1 withdraws the collateral - - 23) User 1 deposits 1000 DAI, user 3 tries to borrow 1000 DAI without any collateral (revert expected) - - 24) user 3 deposits 0.1 ETH collateral to borrow 100 DAI; 0.1 ETH is not enough to borrow 100 DAI (revert expected) - ✓ user 3 withdraws the 0.1 ETH - ✓ User 1 deposits 1000 USDC, user 3 tries to borrow 1000 USDC without any collateral (revert expected) - - 25) user 3 deposits 0.1 ETH collateral to borrow 100 USDC; 0.1 ETH is not enough to borrow 100 USDC (revert expected) - ✓ user 3 withdraws the 0.1 ETH - - 26) User 0 deposits 1000 DAI, user 6 deposits 2 WETH and borrow 100 DAI at variable rate first, then 100 DAI at stable rate, repays everything. User 0 withdraws - - LendingPool: Deposit - ✓ User 0 Deposits 1000 DAI in an empty reserve - ✓ User 1 deposits 1000 DAI after user 1 - ✓ User 0 deposits 1000 USDC in an empty reserve - ✓ User 1 deposits 1000 USDC after user 0 - ✓ User 0 deposits 1 WETH in an empty reserve - ✓ User 1 deposits 1 WETH after user 0 - ✓ User 1 deposits 0 ETH (revert expected) - ✓ User 1 deposits 0 DAI - - AToken: interest rate redirection negative test cases - ✓ User 0 deposits 1000 DAI, tries to give allowance to redirect interest to himself (revert expected) - ✓ User 1 tries to redirect the interest of user 0 without allowance (revert expected) - - 27) User 0 tries to redirect the interest to user 2 twice (revert expected) - - 28) User 3 with 0 balance tries to redirect the interest to user 2 (revert expected) - - AToken: interest rate redirection - - 29) User 0 deposits 1000 DAI, redirects the interest to user 2 - ✓ User 1 deposits 1 ETH, borrows 100 DAI, repays after one year. Users 0 deposits another 1000 DAI. Redirected balance of user 2 is updated - - 30) User 1 borrows another 100 DAI, repay the whole amount. Users 0 and User 2 withdraw - - 31) User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 0 redirects interest back to himself, user 1 borrows another 100 DAI and after another year repays the whole amount. Users 0 and User 2 withdraw - - 32) User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 2 redirects interest to user 3. user 1 borrows another 100 DAI, user 0 deposits another 100 DAI. User 1 repays the whole amount. Users 0, 2 first 1 DAI, then everything. User 3 withdraws - - LendingPool: Rebalance stable rate - ✓ User 0 tries to rebalance user 1 who has no borrows in progress (revert expected) - ✓ User 0 deposits 1000 DAI, user 1 deposits 1 ETH, borrows 100 DAI at a variable rate, user 0 rebalances user 1 (revert expected) - - 33) User 1 swaps to stable, user 0 tries to rebalance but the conditions are not met (revert expected) - - 34) User 2 deposits ETH and borrows the remaining DAI, causing the stable rates to rise (liquidity rate < user 1 borrow rate). User 0 tries to rebalance user 1 (revert expected) - - 35) User 2 borrows more DAI, causing the liquidity rate to rise above user 1 stable borrow rate User 0 rebalances user 1 - - LendingPool: Usage as collateral - ✓ User 0 Deposits 1000 DAI, disables DAI as collateral - - 36) User 1 Deposits 2 ETH, disables ETH as collateral, borrows 400 DAI (revert expected) - ✓ User 1 enables ETH as collateral, borrows 400 DAI - - 37) User 1 disables ETH as collateral (revert expected) - - LendingPool: Swap rate mode - ✓ User 0 tries to swap rate mode without any variable rate loan in progress (revert expected) - ✓ User 0 tries to swap rate mode without any stable rate loan in progress (revert expected) - - 38) User 0 deposits 1000 DAI, user 1 deposits 2 ETH as collateral, borrows 100 DAI at variable rate and swaps to stable after one year - - 39) User 1 borrows another 100 DAI, and swaps back to variable after one year, repays the loan - - LendingPool: Redeem negative test cases - ✓ Users 0 Deposits 1000 DAI and tries to redeem 0 DAI (revert expected) - - 40) Users 0 tries to redeem 1100 DAI from the 1000 DAI deposited (revert expected) - - 41) Users 1 deposits 1 WETH, borrows 100 DAI, tries to redeem the 1 WETH deposited (revert expected) - - LendingPool: withdraw - ✓ User 0 Deposits 1000 DAI in an empty reserve - ✓ User 0 withdraws half of the deposited DAI - ✓ User 0 withdraws remaining half of the deposited DAI - ✓ User 0 Deposits 1000 USDC in an empty reserve - ✓ User 0 withdraws half of the deposited USDC - ✓ User 0 withdraws remaining half of the deposited USDC - ✓ User 0 Deposits 1 WETH in an empty reserve - ✓ User 0 withdraws half of the deposited ETH - ✓ User 0 withdraws remaining half of the deposited ETH - - 42) Users 0 and 1 Deposit 1000 DAI, both withdraw - ✓ Users 0 deposits 1000 DAI, user 1 Deposit 1000 USDC and 1 WETH, borrows 100 DAI. User 1 tries to withdraw all the USDC - - Stable debt token tests - ✓ Tries to invoke mint not being the LendingPool - ✓ Tries to invoke burn not being the LendingPool - - Upgradeability -*** MockAToken *** - -Network: localhost -tx: 0xf94ff11f88ae61a553703ac61194b377d10db1eeb62a2ae4fc9200b2d3ac5ffe -contract address: 0xAA6DfC2A802857Fadb75726B6166484e2c011cf5 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 9499999 - -****** - -*** MockStableDebtToken *** - -Network: localhost -tx: 0x3f3fdd7645e067ef432956779e204f2b173baf87472e497c9673201c790e5543 -contract address: 0xFd23fD3d937ae73a7b545B8Bfeb218395bDe9b8f -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 6331580 - -****** - -*** MockVariableDebtToken *** - -Network: localhost -tx: 0xb17942d4f535a6fe4d349c74c5a480354d3c07565a0e8f10f05706dec1c59fcd -contract address: 0xEe821582b591CE5e4a9B7fFc4E2DAD47D3759C08 -deployer address: 0xc783df8a850f42e7F7e57013759C285caa701eB6 -gas price: 8000000000 -gas used: 5854360 - -****** - - ✓ Tries to update the DAI Atoken implementation with a different address than the lendingPoolManager - ✓ Upgrades the DAI Atoken implementation - ✓ Tries to update the DAI Stable debt token implementation with a different address than the lendingPoolManager - ✓ Upgrades the DAI stable debt token implementation - ✓ Tries to update the DAI variable debt token implementation with a different address than the lendingPoolManager - ✓ Upgrades the DAI variable debt token implementation - - Variable debt token tests - ✓ Tries to invoke mint not being the LendingPool - ✓ Tries to invoke burn not being the LendingPool - -·------------------------------------------------------------------|---------------------------|-------------|-----------------------------· -| Solc version: 0.6.8 · Optimizer enabled: true · Runs: 200 · Block limit: 10000000 gas │ -···································································|···························|·············|······························ -| Methods │ -·································|·································|·············|·············|·············|···············|·············· -| Contract · Method · Min · Max · Avg · # calls · eur (avg) │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · borrow · 310996 · 390411 · 342303 · 16 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · deposit · 163326 · 301355 · 211548 · 63 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · flashLoan · 127473 · 127485 · 127479 · 2 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · repay · 119550 · 218726 · 174340 · 12 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · setUserUseReserveAsCollateral · 83143 · 202731 · 134228 · 5 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · swapBorrowRateMode · - · - · 167109 · 1 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPool · withdraw · 165643 · 336106 · 226426 · 32 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolAddressesProvider · transferOwnership · - · - · 30839 · 1 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · activateReserve · - · - · 46817 · 4 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · disableBorrowingOnReserve · - · - · 50983 · 1 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · disableReserveAsCollateral · - · - · 50919 · 2 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · disableReserveStableRate · - · - · 51048 · 2 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · enableBorrowingOnReserve · - · - · 51559 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · enableReserveAsCollateral · - · - · 52408 · 4 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · enableReserveStableRate · - · - · 50928 · 4 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · freezeReserve · - · - · 50963 · 2 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · setLiquidationBonus · - · - · 51240 · 5 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · setLiquidationThreshold · - · - · 51241 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · setLtv · - · - · 51269 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · unfreezeReserve · - · - · 51026 · 4 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · updateAToken · - · - · 140669 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · updateStableDebtToken · - · - · 140932 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| LendingPoolConfigurator · updateVariableDebtToken · - · - · 140901 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| MintableERC20 · approve · 24907 · 44119 · 32449 · 47 · - │ -·································|·································|·············|·············|·············|···············|·············· -| MintableERC20 · mint · 35427 · 65475 · 40972 · 49 · - │ -·································|·································|·············|·············|·············|···············|·············· -| MintableERC20 · transfer · 138351 · 219471 · 178116 · 13 · - │ -·································|·································|·············|·············|·············|···············|·············· -| MockAToken · redirectInterestStream · 124867 · 144079 · 137671 · 3 · - │ -·································|·································|·············|·············|·············|···············|·············· -| MockFlashLoanReceiver · setFailExecutionTransfer · - · - · 42239 · 7 · - │ -·································|·································|·············|·············|·············|···············|·············· -| Deployments · · % of limit · │ -···································································|·············|·············|·············|···············|·············· -| MockVariableDebtToken · - · - · 1170872 · 11.7 % · - │ -···································································|·············|·············|·············|···············|·············· -| ValidationLogic · - · - · 1631264 · 16.3 % · - │ -·------------------------------------------------------------------|-------------|-------------|-------------|---------------|-------------· - - 115 passing (4m) - 42 failing - - 1) LendingPoolConfigurator - Deactivates the ETH reserve: - Error: VM Exception while processing transaction: revert The liquidity of the reserve needs to be 0 - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 2) LendingPoolConfigurator - Activates the ETH reserve for borrowing: - - AssertionError: expected '1000000000951293759814590868' to equal '1000000000000000000000000000' - + expected - actual - - -1000000000951293759814590868 - +1000000000000000000000000000 - - at /src/test/configurator.spec.ts:86:50 - at step (test/configurator.spec.ts:33:23) - at Object.next (test/configurator.spec.ts:14:53) - at fulfilled (test/configurator.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 3) LendingPool FlashLoan function - Takes ETH flashloan, returns the funds correctly: - - AssertionError: expected '2000720000285388128' to equal '1000720000000000000' - + expected - actual - - -2000720000285388128 - +1000720000000000000 - - at /src/test/flashloan.spec.ts:54:45 - at step (test/flashloan.spec.ts:33:23) - at Object.next (test/flashloan.spec.ts:14:53) - at fulfilled (test/flashloan.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 4) LendingPool FlashLoan function - Takes an ETH flashloan as big as the available liquidity: - - AssertionError: expected '2001620648285388128' to equal '1001620648000000000' - + expected - actual - - -2001620648285388128 - +1001620648000000000 - - at /src/test/flashloan.spec.ts:82:45 - at step (test/flashloan.spec.ts:33:23) - at Object.next (test/flashloan.spec.ts:14:53) - at fulfilled (test/flashloan.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 5) LendingPool FlashLoan function - Takes out a 500 DAI flashloan, returns the funds correctly: - AssertionError: Expected "3000450000000000000000" to be equal 1000450000000000000000 - at /src/test/flashloan.spec.ts:175:34 - at step (test/flashloan.spec.ts:33:23) - at Object.next (test/flashloan.spec.ts:14:53) - at fulfilled (test/flashloan.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 6) LendingPool liquidation - liquidator receiving aToken - LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1: - - AssertionError: expected '5534' to equal '8000' - + expected - actual - - -5534 - +8000 - - at /src/test/liquidation-atoken.spec.ts:66:88 - at step (test/liquidation-atoken.spec.ts:33:23) - at Object.next (test/liquidation-atoken.spec.ts:14:53) - at fulfilled (test/liquidation-atoken.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 7) LendingPool liquidation - liquidator receiving aToken - LIQUIDATION - Drop the health factor below 1: - - AssertionError: expected '1125536573927102016' to be less than '1000000000000000000' - + expected - actual - - -1125536573927102016 - +1000000000000000000 - - at /src/test/liquidation-atoken.spec.ts:90:68 - at step (test/liquidation-atoken.spec.ts:33:23) - at Object.next (test/liquidation-atoken.spec.ts:14:53) - at fulfilled (test/liquidation-atoken.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 8) LendingPool liquidation - liquidator receiving aToken - LIQUIDATION - Tries to liquidate a different currency than the loan principal: - AssertionError: Expected transaction to be reverted with User did not borrow the specified currency, but other exception was thrown: Error: VM Exception while processing transaction: revert Health factor is not below the threshold - - - 9) LendingPool liquidation - liquidator receiving aToken - LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral: - AssertionError: Expected transaction to be reverted with The collateral chosen cannot be liquidated, but other exception was thrown: Error: VM Exception while processing transaction: revert Health factor is not below the threshold - - - 10) LendingPool liquidation - liquidator receiving aToken - LIQUIDATION - Liquidates the borrow: - Error: VM Exception while processing transaction: revert Health factor is not below the threshold - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 11) LendingPool liquidation - liquidator receiving aToken - User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow: - Error: VM Exception while processing transaction: revert SafeMath: division by zero - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 12) LendingPool liquidation - liquidator receiving the underlying asset - LIQUIDATION - Deposits WETH, borrows DAI: - - AssertionError: expected '4513' to equal '8000' - + expected - actual - - -4513 - +8000 - - at /src/test/liquidation-underlying.spec.ts:68:88 - at step (test/liquidation-underlying.spec.ts:33:23) - at Object.next (test/liquidation-underlying.spec.ts:14:53) - at fulfilled (test/liquidation-underlying.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 13) LendingPool liquidation - liquidator receiving the underlying asset - LIQUIDATION - Drop the health factor below 1: - - AssertionError: expected '1072938234852519524' to be less than '1000000000000000000' - + expected - actual - - -1072938234852519524 - +1000000000000000000 - - at /src/test/liquidation-underlying.spec.ts:87:68 - at step (test/liquidation-underlying.spec.ts:33:23) - at Object.next (test/liquidation-underlying.spec.ts:14:53) - at fulfilled (test/liquidation-underlying.spec.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 14) LendingPool liquidation - liquidator receiving the underlying asset - LIQUIDATION - Liquidates the borrow: - Error: VM Exception while processing transaction: revert Health factor is not below the threshold - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 15) LendingPool liquidation - liquidator receiving the underlying asset - User 3 deposits 1000 USDC, user 4 1 WETH, user 4 borrows - drops HF, liquidates the borrow: - Error: VM Exception while processing transaction: revert Health factor is not below the threshold - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 16) LendingPool liquidation - liquidator receiving the underlying asset - User 4 deposits 1000 LEND - drops HF, liquidates the LEND, which results on a lower amount being liquidated: - Error: VM Exception while processing transaction: revert Health factor is not below the threshold - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 17) LendingPool: Borrow/repay (stable rate) - User 0 deposits 1000 DAI, user 1 deposits 1 WETH as collateral and borrows 100 DAI at stable rate: - Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 18) LendingPool: Borrow/repay (stable rate) - User 1 repays the half of the DAI borrow after one year: - - AssertionError: expected '53496990783534834930102816' to be almost equal or equal '49997187848791270690420682' for property utilizationRate - + expected - actual - - -53496990783534834930102816 - +49997187848791270690420682 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:446:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 19) LendingPool: Borrow/repay (stable rate) - User 1 repays the rest of the DAI borrow after one year: - Error: VM Exception while processing transaction: revert 16 - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 20) LendingPool: Borrow/repay (stable rate) - User 1 deposits 1000 DAI, user 2 tries to borrow 1000 DAI at a stable rate without any collateral (revert expected): - - AssertionError: expected '0' to be almost equal or equal '428000013222681762110' for property principalStableDebt - + expected - actual - - -0 - +428000013222681762110 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:189:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 21) LendingPool: Borrow/repay (stable rate) - User 0 deposits 1000 DAI, user 1,2,3,4 deposit 1 WETH each and borrow 100 DAI at stable rate. Everything is repaid, user 0 withdraws: - Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 22) LendingPool: Borrow/repay (variable rate) - User 1 tries to borrow the rest of the USDC liquidity (revert expected): - - AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 23) LendingPool: Borrow/repay (variable rate) - User 1 deposits 1000 DAI, user 3 tries to borrow 1000 DAI without any collateral (revert expected): - - AssertionError: The collateral balance is 0: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 24) LendingPool: Borrow/repay (variable rate) - user 3 deposits 0.1 ETH collateral to borrow 100 DAI; 0.1 ETH is not enough to borrow 100 DAI (revert expected): - - AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 25) LendingPool: Borrow/repay (variable rate) - user 3 deposits 0.1 ETH collateral to borrow 100 USDC; 0.1 ETH is not enough to borrow 100 USDC (revert expected): - - AssertionError: There is not enough collateral to cover a new borrow: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 26) LendingPool: Borrow/repay (variable rate) - User 0 deposits 1000 DAI, user 6 deposits 2 WETH and borrow 100 DAI at variable rate first, then 100 DAI at stable rate, repays everything. User 0 withdraws: - Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 27) AToken: interest rate redirection negative test cases - User 0 tries to redirect the interest to user 2 twice (revert expected): - - AssertionError: expected '3000000004666017561994' to be almost equal or equal '3000002809866499332595' for property redirectionAddressRedirectedBalance - + expected - actual - - -3000000004666017561994 - +3000002809866499332595 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:692:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 28) AToken: interest rate redirection negative test cases - User 3 with 0 balance tries to redirect the interest to user 2 (revert expected): - - AssertionError: Interest stream can only be redirected if there is a valid balance: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 29) AToken: interest rate redirection - User 0 deposits 1000 DAI, redirects the interest to user 2: - Error: VM Exception while processing transaction: revert Interest is already redirected to the user - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 30) AToken: interest rate redirection - User 1 borrows another 100 DAI, repay the whole amount. Users 0 and User 2 withdraw: - - AssertionError: expected '1018781912658889894052315977' to be almost equal or equal '1018781912797584526993908257' for property currentATokenUserIndex - + expected - actual - - -1018781912658889894052315977 - +1018781912797584526993908257 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:267:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 31) AToken: interest rate redirection - User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 0 redirects interest back to himself, user 1 borrows another 100 DAI and after another year repays the whole amount. Users 0 and User 2 withdraw: - - AssertionError: expected '1020673495374568972552' to be almost equal or equal '1020673495380218720173' for property redirectionAddressRedirectedBalance - + expected - actual - - -1020673495374568972552 - +1020673495380218720173 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:692:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 32) AToken: interest rate redirection - User 0 deposits 1000 DAI, redirects interest to user 2, user 1 borrows 100 DAI. After one year, user 2 redirects interest to user 3. user 1 borrows another 100 DAI, user 0 deposits another 100 DAI. User 1 repays the whole amount. Users 0, 2 first 1 DAI, then everything. User 3 withdraws: - Error: VM Exception while processing transaction: revert Interest is already redirected to the user - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 33) LendingPool: Rebalance stable rate - User 1 swaps to stable, user 0 tries to rebalance but the conditions are not met (revert expected): - Error: VM Exception while processing transaction: revert 12 - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 34) LendingPool: Rebalance stable rate - User 2 deposits ETH and borrows the remaining DAI, causing the stable rates to rise (liquidity rate < user 1 borrow rate). User 0 tries to rebalance user 1 (revert expected): - Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 35) LendingPool: Rebalance stable rate - User 2 borrows more DAI, causing the liquidity rate to rise above user 1 stable borrow rate User 0 rebalances user 1: - Error: VM Exception while processing transaction: revert There is not enough collateral to cover a new borrow - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 36) LendingPool: Usage as collateral - User 1 Deposits 2 ETH, disables ETH as collateral, borrows 400 DAI (revert expected): - - AssertionError: The collateral balance is 0: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 37) LendingPool: Usage as collateral - User 1 disables ETH as collateral (revert expected): - - AssertionError: User deposit is already being used as collateral: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 38) LendingPool: Swap rate mode - User 0 deposits 1000 DAI, user 1 deposits 2 ETH as collateral, borrows 100 DAI at variable rate and swaps to stable after one year: - Error: VM Exception while processing transaction: revert 12 - at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34) - at getMultipliedGasEstimation (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:150:45) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:108:14 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:63:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at /src/node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:82:21 - at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12) - at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48) - at EthersProviderWrapper.JsonRpcProvider.perform (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:432:21) - at EthersProviderWrapper. (node_modules/@ethersproject/providers/src.ts/base-provider.ts:850:42) - at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23) - at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53) - at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 39) LendingPool: Swap rate mode - User 1 borrows another 100 DAI, and swaps back to variable after one year, repays the loan: - - AssertionError: expected '10698732000442685488829' to be almost equal or equal '10652337619880722614595' for property totalLiquidity - + expected - actual - - -10698732000442685488829 - +10652337619880722614595 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:571:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - 40) LendingPool: Redeem negative test cases - Users 0 tries to redeem 1100 DAI from the 1000 DAI deposited (revert expected): - - AssertionError: User cannot redeem more than the available balance: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 41) LendingPool: Redeem negative test cases - Users 1 deposits 1 WETH, borrows 100 DAI, tries to redeem the 1 WETH deposited (revert expected): - - AssertionError: Transfer cannot be allowed.: Expected transaction to be reverted - + expected - actual - - -Transaction NOT reverted. - +Transaction reverted. - - - - 42) LendingPool: withdraw - Users 0 and 1 Deposit 1000 DAI, both withdraw: - - AssertionError: expected '100000000000000000000' to be almost equal or equal '1156444960439594400554' for property principalStableDebt - + expected - actual - - -100000000000000000000 - +1156444960439594400554 - - at expectEqual (test/helpers/actions.ts:806:26) - at /src/test/helpers/actions.ts:189:5 - at step (test/helpers/actions.ts:33:23) - at Object.next (test/helpers/actions.ts:14:53) - at fulfilled (test/helpers/actions.ts:5:58) - at runMicrotasks () - at processTicksAndRejections (internal/process/task_queues.js:97:5) - - - From 928770d9d5bcb703df71511f901aa96a0e7f4fdc Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 24 Aug 2020 01:22:14 +0200 Subject: [PATCH 06/33] Updated flashloans V2 --- buidler.config.ts | 2 +- contracts/interfaces/ILendingPool.sol | 26 +-- contracts/lendingpool/LendingPool.sol | 86 ++++++-- contracts/libraries/logic/ValidationLogic.sol | 9 - helpers/types.ts | 1 + test/flashloan.spec.ts | 188 +++++++++++++----- 6 files changed, 208 insertions(+), 104 deletions(-) diff --git a/buidler.config.ts b/buidler.config.ts index d0657ab0..d21f5293 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -8,7 +8,7 @@ usePlugin('buidler-typechain'); usePlugin('solidity-coverage'); usePlugin('@nomiclabs/buidler-waffle'); usePlugin('@nomiclabs/buidler-etherscan'); -usePlugin('buidler-gas-reporter'); +//usePlugin('buidler-gas-reporter'); const DEFAULT_BLOCK_GAS_LIMIT = 10000000; const DEFAULT_GAS_PRICE = 10; diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 43bfb554..cc676666 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -63,7 +63,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, uint256 timestamp); + event Swap(address indexed reserve, address indexed user); /** * @dev emitted when a user enables a reserve as collateral @@ -91,12 +91,14 @@ interface ILendingPool { * @param reserve the address of the reserve * @param amount the amount requested * @param totalFee the total fee on the amount + * @param referralCode the referral code of the caller **/ event FlashLoan( address indexed target, address indexed reserve, uint256 amount, - uint256 totalFee + uint256 totalFee, + uint16 referralCode ); /** * @dev these events are not emitted directly by the LendingPool @@ -105,21 +107,6 @@ interface ILendingPool { * This allows to have the events in the generated ABI for LendingPool. **/ - /** - * @dev emitted when a borrow fee is liquidated - * @param collateral the address of the collateral being liquidated - * @param reserve the address of the reserve - * @param user the address of the user being liquidated - * @param feeLiquidated the total fee liquidated - * @param liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee - **/ - event OriginationFeeLiquidated( - address indexed collateral, - address indexed reserve, - address indexed user, - uint256 feeLiquidated, - uint256 liquidatedCollateralForFee - ); /** * @dev emitted when a borrower is liquidated * @param collateral the address of the collateral being liquidated @@ -238,12 +225,15 @@ interface ILendingPool { * @param receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param reserve the address of the principal reserve * @param amount the amount requested for this flashloan + * @param params a bytes array to be sent to the flashloan executor + * @param referralCode the referral code of the caller **/ function flashLoan( address receiver, address reserve, uint256 amount, - bytes calldata params + bytes calldata params, + uint16 referralCode ) external; /** diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 77f04893..0066076d 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -108,7 +108,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { //transfer to the aToken contract IERC20(asset).safeTransferFrom(msg.sender, address(aToken), amount); - //solium-disable-next-line emit Deposit(asset, msg.sender, amount, referralCode); } @@ -152,7 +151,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { aToken.burn(msg.sender, msg.sender, amountToWithdraw); - //solium-disable-next-line emit Withdraw(asset, msg.sender, amount); } @@ -320,9 +318,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { emit Swap( asset, - msg.sender, - //solium-disable-next-line - block.timestamp + msg.sender ); } @@ -441,6 +437,15 @@ contract LendingPool is VersionedInitializable, ILendingPool { } } + struct FlashLoanLocalVars{ + uint256 amountFee; + uint256 amountPlusFee; + uint256 amountPlusFeeInETH; + IFlashLoanReceiver receiver; + address aTokenAddress; + address oracle; + } + /** * @dev allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts @@ -453,40 +458,77 @@ contract LendingPool is VersionedInitializable, ILendingPool { address receiverAddress, address asset, uint256 amount, - bytes calldata params + bytes calldata params, + uint16 referralCode ) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; + FlashLoanLocalVars memory vars; - address aTokenAddress = reserve.aTokenAddress; + vars.aTokenAddress = reserve.aTokenAddress; //calculate amount fee - uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); + vars.amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); - require(amountFee > 0, 'The requested amount is too small for a FlashLoan.'); + require(vars.amountFee > 0, 'The requested amount is too small for a FlashLoan.'); //get the FlashLoanReceiver instance - IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); + vars.receiver = IFlashLoanReceiver(receiverAddress); //transfer funds to the receiver - IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); + IAToken(vars.aTokenAddress).transferUnderlyingTo(receiverAddress, amount); //execute action of the receiver - receiver.executeOperation(asset, amount, amountFee, params); + vars.receiver.executeOperation(asset, amount, vars.amountFee, params); - //transfer from the receiver the amount plus the fee - IERC20(asset).safeTransferFrom(receiverAddress, aTokenAddress, amount.add(amountFee)); - - //compounding the cumulated interest + //compounding the cumulated interest reserve.updateCumulativeIndexesAndTimestamp(); - //compounding the received fee into the reserve - reserve.cumulateToLiquidityIndex(IERC20(aTokenAddress).totalSupply(), amountFee); + vars.amountPlusFee = amount.add(vars.amountFee); - //refresh interest rates - reserve.updateInterestRates(asset, amountFee, 0); + //transfer from the receiver the amount plus the fee + try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusFee) { + //if the transfer succeeded, the executor has repaid the flashloans. + //the fee is compounded into the reserve + reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.amountFee); + //refresh interest rates + reserve.updateInterestRates(asset, vars.amountFee, 0); + emit FlashLoan(receiverAddress, asset, amount, vars.amountFee, referralCode); + } + catch(bytes memory reason){ - //solium-disable-next-line - emit FlashLoan(receiverAddress, asset, amount, amountFee); + //if the transfer didn't succeed, the executor either didn't return the funds, or didn't approve the transfer. + //we check if the caller has enough collateral to open a variable rate loan. If it does, then debt is mint to msg.sender + vars.oracle = addressesProvider.getPriceOracle(); + vars.amountPlusFeeInETH = IPriceOracleGetter(vars.oracle) + .getAssetPrice(asset) + .mul(vars.amountPlusFee) + .div(10**reserve.configuration.getDecimals()); //price is in ether + + ValidationLogic.validateBorrow( + reserve, + asset, + vars.amountPlusFee, + vars.amountPlusFeeInETH, + uint256(ReserveLogic.InterestRateMode.VARIABLE), + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + _usersConfig[msg.sender], + reservesList, + vars.oracle + ); + + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, vars.amountPlusFee); + //refresh interest rates + reserve.updateInterestRates(asset, vars.amountFee, 0); + emit Borrow( + asset, + msg.sender, + vars.amountPlusFee, + uint256(ReserveLogic.InterestRateMode.VARIABLE), + reserve.currentVariableBorrowRate, + referralCode + ); + } } /** diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index abba4592..dd3ef25a 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -62,10 +62,6 @@ library ValidationLogic { ) external view { require(amount > 0, 'Amount must be greater than 0'); - uint256 currentAvailableLiquidity = IERC20(reserveAddress).balanceOf(address(aTokenAddress)); - - require(currentAvailableLiquidity >= amount, '4'); - require(amount <= userBalance, 'User cannot withdraw more than the available balance'); require( @@ -150,11 +146,6 @@ library ValidationLogic { 'Invalid interest rate mode selected' ); - //check that the amount is available in the reserve - vars.availableLiquidity = IERC20(reserveAddress).balanceOf(address(reserve.aTokenAddress)); - - require(vars.availableLiquidity >= amount, '7'); - ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, diff --git a/helpers/types.ts b/helpers/types.ts index 625da1f4..08ca3320 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -63,6 +63,7 @@ export enum ProtocolErrors { INVALID_HF = 'Invalid health factor', USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED = 'The collateral chosen cannot be liquidated', + COLLATERAL_BALANCE_IS_0 = 'The collateral balance is 0' } export type tEthereumAddress = string; diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index cbbda7d6..dfda3085 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -1,18 +1,20 @@ -import {TestEnv, makeSuite} from './helpers/make-suite'; -import {APPROVAL_AMOUNT_LENDING_POOL, oneRay} from '../helpers/constants'; -import {convertToCurrencyDecimals, getMockFlashLoanReceiver} from '../helpers/contracts-helpers'; -import {ethers} from 'ethers'; -import {MockFlashLoanReceiver} from '../types/MockFlashLoanReceiver'; -import {ProtocolErrors} from '../helpers/types'; +import { TestEnv, makeSuite } from './helpers/make-suite'; +import { APPROVAL_AMOUNT_LENDING_POOL, oneRay } from '../helpers/constants'; +import { convertToCurrencyDecimals, getMockFlashLoanReceiver, getContract } from '../helpers/contracts-helpers'; +import { ethers } from 'ethers'; +import { MockFlashLoanReceiver } from '../types/MockFlashLoanReceiver'; +import { ProtocolErrors, eContractid } from '../helpers/types'; import BigNumber from 'bignumber.js'; +import { VariableDebtToken } from '../types/VariableDebtToken'; -const {expect} = require('chai'); +const { expect } = require('chai'); makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { TRANSFER_AMOUNT_EXCEEDS_BALANCE, TOO_SMALL_FLASH_LOAN, + COLLATERAL_BALANCE_IS_0, } = ProtocolErrors; before(async () => { @@ -20,7 +22,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Deposits ETH into the reserve', async () => { - const {pool, weth} = testEnv; + const { pool, weth } = testEnv; const amountToDeposit = ethers.utils.parseEther('1'); await weth.mint(amountToDeposit); @@ -31,13 +33,14 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes ETH flashloan, returns the funds correctly', async () => { - const {pool, deployer, weth} = testEnv; + const { pool, deployer, weth } = testEnv; await pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), - '0x10' + '0x10', + '0' ); ethers.utils.parseUnits('10000'); @@ -57,17 +60,15 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes an ETH flashloan as big as the available liquidity', async () => { - const {pool, weth} = testEnv; + const { pool, weth } = testEnv; const reserveDataBefore = await pool.getReserveData(weth.address); - - console.log("Total liquidity is ", reserveDataBefore.availableLiquidity.toString()); - const txResult = await pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1000720000000000000', - '0x10' + '0x10', + '0' ); const reserveData = await pool.getReserveData(weth.address); @@ -84,83 +85,122 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentLiquidityIndex.toString()).to.be.equal('1001620648000000000000000000'); }); - it('Takes WETH flashloan, does not return the funds (revert expected)', async () => { - const {pool, deployer, weth} = testEnv; - - // move funds to the MockFlashLoanReceiver contract to pay the fee - + it('Takes WETH flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { + const { pool, weth, users } = testEnv; + const caller = users[1]; await _mockFlashLoanReceiver.setFailExecutionTransfer(true); await expect( - pool.flashLoan( + pool + .connect(caller.signer) + .flashLoan( + _mockFlashLoanReceiver.address, + weth.address, + ethers.utils.parseEther('0.8'), + '0x10', + '0' + ) + ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); + }); + + it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds. A loan for caller is created', async () => { + const { dai, pool, weth, users } = testEnv; + + const caller = users[1]; + + await dai.connect(caller.signer).mint(await convertToCurrencyDecimals(dai.address, '1000')); + + await dai.connect(caller.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); + + const amountToDeposit = await convertToCurrencyDecimals(dai.address, '1000'); + + await pool.connect(caller.signer).deposit(dai.address, amountToDeposit, '0'); + + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); + + await pool + .connect(caller.signer) + .flashLoan( _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), - '0x10' - ) - ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); + '0x10', + '0' + ); + const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(weth.address); + + const wethDebtToken = await getContract(eContractid.VariableDebtToken, variableDebtTokenAddress); + + const callerDebt = await wethDebtToken.balanceOf(caller.address); + + expect(callerDebt.toString()).to.be.equal('800720000000000000', 'Invalid user debt'); }); it('tries to take a very small flashloan, which would result in 0 fees (revert expected)', async () => { - const {pool, weth} = testEnv; + const { pool, weth } = testEnv; await expect( pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1', //1 wei loan - '0x10' + '0x10', + '0' ) ).to.be.revertedWith(TOO_SMALL_FLASH_LOAN); }); it('tries to take a flashloan that is bigger than the available liquidity (revert expected)', async () => { - const {pool, weth} = testEnv; + const { pool, weth } = testEnv; await expect( pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1004415000000000000', //slightly higher than the available liquidity - '0x10' + '0x10', + '0' ), TRANSFER_AMOUNT_EXCEEDS_BALANCE ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); it('tries to take a flashloan using a non contract address as receiver (revert expected)', async () => { - const {pool, deployer, weth} = testEnv; + const { pool, deployer, weth } = testEnv; - await expect(pool.flashLoan(deployer.address, weth.address, '1000000000000000000', '0x10')).to - .be.reverted; + await expect(pool.flashLoan(deployer.address, weth.address, '1000000000000000000', '0x10', '0')) + .to.be.reverted; }); - it('Deposits DAI into the reserve', async () => { - const {dai, pool} = testEnv; + it('Deposits USDC into the reserve', async () => { + const { usdc, pool } = testEnv; - await dai.mint(await convertToCurrencyDecimals(dai.address, '1000')); + await usdc.mint(await convertToCurrencyDecimals(usdc.address, '1000')); - await dai.approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); + await usdc.approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); - const amountToDeposit = await convertToCurrencyDecimals(dai.address, '1000'); + const amountToDeposit = await convertToCurrencyDecimals(usdc.address, '1000'); - await pool.deposit(dai.address, amountToDeposit, '0'); + await pool.deposit(usdc.address, amountToDeposit, '0'); }); - it('Takes out a 500 DAI flashloan, returns the funds correctly', async () => { - const {dai, pool, deployer: depositor} = testEnv; + it('Takes out a 500 USDC flashloan, returns the funds correctly', async () => { + const { usdc, pool, deployer: depositor } = testEnv; await _mockFlashLoanReceiver.setFailExecutionTransfer(false); + const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); + await pool.flashLoan( _mockFlashLoanReceiver.address, - dai.address, - ethers.utils.parseEther('500'), - '0x10' + usdc.address, + flashloanAmount, + '0x10', + '0' ); - const reserveData = await pool.getReserveData(dai.address); - const userData = await pool.getUserReserveData(dai.address, depositor.address); + const reserveData = await pool.getReserveData(usdc.address); + const userData = await pool.getUserReserveData(usdc.address, depositor.address); const totalLiquidity = reserveData.availableLiquidity .add(reserveData.totalBorrowsStable) @@ -170,7 +210,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const currentLiquidityIndex = reserveData.liquidityIndex.toString(); const currentUserBalance = userData.currentATokenBalance.toString(); - const expectedLiquidity = ethers.utils.parseEther('1000.450'); + const expectedLiquidity = await convertToCurrencyDecimals(usdc.address,'1000.450'); expect(totalLiquidity).to.be.equal(expectedLiquidity, 'Invalid total liquidity'); expect(currentLiqudityRate).to.be.equal('0', 'Invalid liquidity rate'); @@ -181,19 +221,59 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentUserBalance.toString()).to.be.equal(expectedLiquidity, 'Invalid user balance'); }); - it('Takes out a 500 DAI flashloan, does not return the funds (revert expected)', async () => { - const {dai, pool} = testEnv; + it('Takes out a 500 USDC flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { + const { usdc, pool, users } = testEnv; + const caller = users[2]; + + const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); await _mockFlashLoanReceiver.setFailExecutionTransfer(true); await expect( - pool.flashLoan( + pool + .connect(caller.signer) + .flashLoan( + _mockFlashLoanReceiver.address, + usdc.address, + flashloanAmount, + '0x10', + '0' + ) + ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); + }); + + it('Caller deposits 5 ETH as collateral, Takes a USDC flashloan, does not return the funds. A loan for caller is created', async () => { + const { usdc, pool, weth, users } = testEnv; + + const caller = users[2]; + + await weth.connect(caller.signer).mint(await convertToCurrencyDecimals(weth.address, '5')); + + await weth.connect(caller.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); + + const amountToDeposit = await convertToCurrencyDecimals(weth.address, '5'); + + await pool.connect(caller.signer).deposit(weth.address, amountToDeposit, '0'); + + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); + + const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); + + await pool + .connect(caller.signer) + .flashLoan( _mockFlashLoanReceiver.address, - dai.address, - ethers.utils.parseEther('500'), - '0x10' - ), - TRANSFER_AMOUNT_EXCEEDS_BALANCE - ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); + usdc.address, + flashloanAmount, + '0x10', + '0' + ); + const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(usdc.address); + + const usdcDebtToken = await getContract(eContractid.VariableDebtToken, variableDebtTokenAddress); + + const callerDebt = await usdcDebtToken.balanceOf(caller.address); + + expect(callerDebt.toString()).to.be.equal('500450000', 'Invalid user debt'); }); }); From dce7a73dda58d4d259a8ccb920d5369acbb71d9d Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 24 Aug 2020 01:30:01 +0200 Subject: [PATCH 07/33] Renamed flashloan fee in premium --- contracts/interfaces/ILendingPool.sol | 4 +- contracts/lendingpool/LendingPool.sol | 55 ++++++++++++++------------- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index cc676666..5b15ce74 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -90,14 +90,14 @@ interface ILendingPool { * @param target the address of the flashLoanReceiver * @param reserve the address of the reserve * @param amount the amount requested - * @param totalFee the total fee on the amount + * @param totalPremium the total fee on the amount * @param referralCode the referral code of the caller **/ event FlashLoan( address indexed target, address indexed reserve, uint256 amount, - uint256 totalFee, + uint256 totalPremium, uint16 referralCode ); /** diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 0066076d..fcdc1149 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -41,7 +41,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { //main configuration parameters uint256 public constant REBALANCE_DOWN_RATE_DELTA = (1e27) / 5; uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; - uint256 public constant FLASHLOAN_FEE_TOTAL = 9; + uint256 public constant FLASHLOAN_PREMIUM_TOTAL = 9; ILendingPoolAddressesProvider internal addressesProvider; @@ -438,9 +438,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { } struct FlashLoanLocalVars{ - uint256 amountFee; - uint256 amountPlusFee; - uint256 amountPlusFeeInETH; + uint256 premium; + uint256 amountPlusPremium; + uint256 amountPlusPremiumInETH; IFlashLoanReceiver receiver; address aTokenAddress; address oracle; @@ -467,9 +467,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.aTokenAddress = reserve.aTokenAddress; //calculate amount fee - vars.amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); + vars.premium = amount.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000); - require(vars.amountFee > 0, 'The requested amount is too small for a FlashLoan.'); + require(vars.premium > 0, 'The requested amount is too small for a FlashLoan.'); //get the FlashLoanReceiver instance vars.receiver = IFlashLoanReceiver(receiverAddress); @@ -478,52 +478,53 @@ contract LendingPool is VersionedInitializable, ILendingPool { IAToken(vars.aTokenAddress).transferUnderlyingTo(receiverAddress, amount); //execute action of the receiver - vars.receiver.executeOperation(asset, amount, vars.amountFee, params); + vars.receiver.executeOperation(asset, amount, vars.premium, params); //compounding the cumulated interest reserve.updateCumulativeIndexesAndTimestamp(); - vars.amountPlusFee = amount.add(vars.amountFee); + vars.amountPlusPremium = amount.add(vars.premium); //transfer from the receiver the amount plus the fee - try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusFee) { + try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium) { //if the transfer succeeded, the executor has repaid the flashloans. //the fee is compounded into the reserve - reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.amountFee); + reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); //refresh interest rates - reserve.updateInterestRates(asset, vars.amountFee, 0); - emit FlashLoan(receiverAddress, asset, amount, vars.amountFee, referralCode); + reserve.updateInterestRates(asset, vars.premium, 0); + emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); } catch(bytes memory reason){ //if the transfer didn't succeed, the executor either didn't return the funds, or didn't approve the transfer. //we check if the caller has enough collateral to open a variable rate loan. If it does, then debt is mint to msg.sender vars.oracle = addressesProvider.getPriceOracle(); - vars.amountPlusFeeInETH = IPriceOracleGetter(vars.oracle) + vars.amountPlusPremiumInETH = IPriceOracleGetter(vars.oracle) .getAssetPrice(asset) - .mul(vars.amountPlusFee) + .mul(vars.amountPlusPremium) .div(10**reserve.configuration.getDecimals()); //price is in ether ValidationLogic.validateBorrow( - reserve, - asset, - vars.amountPlusFee, - vars.amountPlusFeeInETH, - uint256(ReserveLogic.InterestRateMode.VARIABLE), - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - _usersConfig[msg.sender], - reservesList, - vars.oracle + reserve, + asset, + vars.amountPlusPremium, + vars.amountPlusPremiumInETH, + uint256(ReserveLogic.InterestRateMode.VARIABLE), + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + _usersConfig[msg.sender], + reservesList, + vars.oracle ); - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, vars.amountPlusFee); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, vars.amountPlusPremium); //refresh interest rates - reserve.updateInterestRates(asset, vars.amountFee, 0); + reserve.updateInterestRates(asset, vars.premium, 0); + emit Borrow( asset, msg.sender, - vars.amountPlusFee, + vars.amountPlusPremium, uint256(ReserveLogic.InterestRateMode.VARIABLE), reserve.currentVariableBorrowRate, referralCode From d86aafda0c9eceb395cd005f08e4e3bf35b3e042 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 24 Aug 2020 01:32:46 +0200 Subject: [PATCH 08/33] Fix on the interest rate update --- contracts/lendingpool/LendingPool.sol | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index fcdc1149..69e4fb6e 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -487,7 +487,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { //transfer from the receiver the amount plus the fee try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium) { - //if the transfer succeeded, the executor has repaid the flashloans. + //if the transfer succeeded, the executor has repaid the flashloan. //the fee is compounded into the reserve reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); //refresh interest rates @@ -518,8 +518,8 @@ contract LendingPool is VersionedInitializable, ILendingPool { ); IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, vars.amountPlusPremium); - //refresh interest rates - reserve.updateInterestRates(asset, vars.premium, 0); + //refresh interest rate, substracting from the available liquidity the flashloan amount + reserve.updateInterestRates(asset, 0, amount); emit Borrow( asset, From b2d8a9e053fbafdbe9f87cd273d5a6c97019ed6e Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 24 Aug 2020 01:41:10 +0200 Subject: [PATCH 09/33] Removed ETH specific logic in tests --- test/helpers/utils/calculations.ts | 85 ++++++------------------------ 1 file changed, 17 insertions(+), 68 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 257573be..b3511282 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -7,15 +7,14 @@ import { EXCESS_UTILIZATION_RATE, ZERO_ADDRESS, } from '../../../helpers/constants'; -import {IReserveParams, iAavePoolAssets, RateMode} from '../../../helpers/types'; +import { IReserveParams, iAavePoolAssets, RateMode } from '../../../helpers/types'; import './math'; -import {ReserveData, UserReserveData} from './interfaces'; +import { ReserveData, UserReserveData } from './interfaces'; export const strToBN = (amount: string): BigNumber => new BigNumber(amount); interface Configuration { reservesParams: iAavePoolAssets; - ethereumAddress: string; } export const configuration: Configuration = {}; @@ -66,17 +65,7 @@ export const calcExpectedUserDataAfterDeposit = ( } expectedUserData.variableBorrowIndex = userDataBeforeAction.variableBorrowIndex; - - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - // console.log("** ETH CASE ****") - expectedUserData.walletBalance = userDataBeforeAction.walletBalance - .minus(txCost) - .minus(amountDeposited); - } else { - // console.log("** TOKEN CASE ****") - // console.log(userDataBeforeAction.walletBalance.toString()) - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(amountDeposited); - } + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(amountDeposited); expectedUserData.principalATokenBalance = expectedUserData.currentATokenBalance = calcExpectedATokenBalance( reserveDataBeforeAction, @@ -171,14 +160,7 @@ export const calcExpectedUserDataAfterWithdraw = ( } expectedUserData.variableBorrowIndex = userDataBeforeAction.variableBorrowIndex; - - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance - .minus(txCost) - .plus(amountWithdrawn); - } else { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountWithdrawn); - } + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountWithdrawn); expectedUserData.redirectedBalance = userDataBeforeAction.redirectedBalance; @@ -600,13 +582,7 @@ export const calcExpectedUserDataAfterBorrow = ( userDataBeforeAction.redirectionAddressRedirectedBalance; expectedUserData.currentATokenUserIndex = userDataBeforeAction.currentATokenUserIndex; - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance - .minus(txCost) - .plus(amountBorrowed); - } else { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountBorrowed); - } + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountBorrowed); return expectedUserData; }; @@ -657,8 +633,7 @@ export const calcExpectedUserDataAfterRepay = ( expectedUserData.stableBorrowRate = expectedUserData.stableRateLastUpdated = new BigNumber( '0' ); - } - else{ + } else { expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; expectedUserData.stableRateLastUpdated = txTimestamp; } @@ -697,14 +672,7 @@ export const calcExpectedUserDataAfterRepay = ( expectedUserData.currentATokenUserIndex = userDataBeforeAction.currentATokenUserIndex; if (user === onBehalfOf) { - //if user repaid for himself, update the wallet balances - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance - .minus(txCost) - .minus(totalRepaid); - } else { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(totalRepaid); - } + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(totalRepaid); } else { //wallet balance didn't change expectedUserData.walletBalance = userDataBeforeAction.walletBalance; @@ -719,14 +687,10 @@ export const calcExpectedUserDataAfterSetUseAsCollateral = ( userDataBeforeAction: UserReserveData, txCost: BigNumber ): UserReserveData => { - const expectedUserData = {...userDataBeforeAction}; + const expectedUserData = { ...userDataBeforeAction }; expectedUserData.usageAsCollateralEnabled = useAsCollateral; - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(txCost); - } - return expectedUserData; }; @@ -829,7 +793,7 @@ export const calcExpectedUserDataAfterSwapRateMode = ( txCost: BigNumber, txTimestamp: BigNumber ): UserReserveData => { - const expectedUserData = {...userDataBeforeAction}; + const expectedUserData = { ...userDataBeforeAction }; const variableBorrowBalance = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, @@ -892,9 +856,6 @@ export const calcExpectedUserDataAfterSwapRateMode = ( expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(txCost); - } return expectedUserData; }; @@ -976,7 +937,7 @@ export const calcExpectedUserDataAfterStableRateRebalance = ( txCost: BigNumber, txTimestamp: BigNumber ): UserReserveData => { - const expectedUserData = {...userDataBeforeAction}; + const expectedUserData = { ...userDataBeforeAction }; expectedUserData.principalVariableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, @@ -1000,12 +961,6 @@ export const calcExpectedUserDataAfterStableRateRebalance = ( expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(txCost); - } - - expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; - expectedUserData.currentATokenBalance = calcExpectedATokenBalance( reserveDataBeforeAction, userDataBeforeAction, @@ -1037,8 +992,8 @@ export const calcExpectedUsersDataAfterRedirectInterest = ( txCost: BigNumber, txTimestamp: BigNumber ): UserReserveData[] => { - const expectedFromData = {...fromDataBeforeAction}; - const expectedToData = {...toDataBeforeAction}; + const expectedFromData = { ...fromDataBeforeAction }; + const expectedToData = { ...toDataBeforeAction }; expectedFromData.currentStableDebt = calcExpectedStableDebtTokenBalance( fromDataBeforeAction, @@ -1069,12 +1024,6 @@ export const calcExpectedUsersDataAfterRedirectInterest = ( txTimestamp ); - if (isFromExecutingTx) { - if (reserveDataBeforeAction.address === configuration.ethereumAddress) { - expectedFromData.walletBalance = fromDataBeforeAction.walletBalance.minus(txCost); - } - } - expectedToData.redirectedBalance = toDataBeforeAction.redirectedBalance.plus( expectedFromData.currentATokenBalance ); @@ -1215,7 +1164,7 @@ export const calcExpectedVariableDebtTokenBalance = ( ) => { const debt = calcExpectedReserveNormalizedDebt(reserveDataBeforeAction, currentTimestamp); - const {principalVariableDebt, variableBorrowIndex} = userDataBeforeAction; + const { principalVariableDebt, variableBorrowIndex } = userDataBeforeAction; if (variableBorrowIndex.eq(0)) { return principalVariableDebt; @@ -1228,7 +1177,7 @@ export const calcExpectedStableDebtTokenBalance = ( userDataBeforeAction: UserReserveData, currentTimestamp: BigNumber ) => { - const {principalStableDebt, stableBorrowRate, stableRateLastUpdated} = userDataBeforeAction; + const { principalStableDebt, stableBorrowRate, stableRateLastUpdated } = userDataBeforeAction; if ( stableBorrowRate.eq(0) || @@ -1301,7 +1250,7 @@ const calcExpectedInterestRates = ( totalBorrowsVariable: BigNumber, averageStableBorrowRate: BigNumber ): BigNumber[] => { - const {reservesParams} = configuration; + const { reservesParams } = configuration; const reserveIndex = Object.keys(reservesParams).findIndex((value) => value === reserveSymbol); const [, reserveConfiguration] = (Object.entries(reservesParams) as [string, IReserveParams][])[ @@ -1391,7 +1340,7 @@ const calcExpectedReserveNormalizedIncome = ( reserveData: ReserveData, currentTimestamp: BigNumber ) => { - const {liquidityRate, liquidityIndex, lastUpdateTimestamp} = reserveData; + const { liquidityRate, liquidityIndex, lastUpdateTimestamp } = reserveData; //if utilization rate is 0, nothing to compound if (liquidityRate.eq('0')) { @@ -1413,7 +1362,7 @@ const calcExpectedReserveNormalizedDebt = ( reserveData: ReserveData, currentTimestamp: BigNumber ) => { - const {variableBorrowRate, variableBorrowIndex, lastUpdateTimestamp} = reserveData; + const { variableBorrowRate, variableBorrowIndex, lastUpdateTimestamp } = reserveData; //if utilization rate is 0, nothing to compound if (variableBorrowRate.eq('0')) { From dfe865fc76fd2be1c5da9ce8f7bdadc6bfc39068 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 24 Aug 2020 01:46:15 +0200 Subject: [PATCH 10/33] Removed unused code in tests --- test/helpers/utils/calculations.ts | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index b3511282..4d1c55e4 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -1421,31 +1421,3 @@ const calcExpectedVariableBorrowIndex = (reserveData: ReserveData, timestamp: Bi return cumulatedInterest.rayMul(reserveData.variableBorrowIndex); }; - -export const calculateHealthFactorFromBalances = ( - collateralBalanceETH: BigNumber, - borrowBalanceETH: BigNumber, - currentLiquidationThreshold: BigNumber -): BigNumber => { - if (borrowBalanceETH.eq(0)) { - return strToBN('-1'); // invalid number - } - return collateralBalanceETH.multipliedBy(currentLiquidationThreshold).div(borrowBalanceETH); -}; - -const calculateAvailableBorrowsETH = ( - collateralBalanceETH: BigNumber, - borrowBalanceETH: BigNumber, - currentLtv: BigNumber -): BigNumber => { - if (currentLtv.eq(0)) { - return strToBN('0'); - } - let availableBorrowsETH = collateralBalanceETH.multipliedBy(currentLtv); - if (availableBorrowsETH.lt(borrowBalanceETH)) { - return strToBN('0'); - } - availableBorrowsETH = availableBorrowsETH.minus(borrowBalanceETH); - const borrowFee = availableBorrowsETH.multipliedBy(0.0025); - return availableBorrowsETH.minus(borrowFee); -}; From da5b6738c1e8addc84b627284456a2e06958fd96 Mon Sep 17 00:00:00 2001 From: andyk Date: Mon, 24 Aug 2020 15:35:59 +0300 Subject: [PATCH 11/33] refactoring of DefaultReserveInterestRateStrategy to follow the stuileguide --- .../interfaces/IReserveInterestRateStrategy.sol | 2 +- .../DefaultReserveInterestRateStrategy.sol | 16 +++++++--------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/contracts/interfaces/IReserveInterestRateStrategy.sol b/contracts/interfaces/IReserveInterestRateStrategy.sol index 5d41c100..48311e70 100644 --- a/contracts/interfaces/IReserveInterestRateStrategy.sol +++ b/contracts/interfaces/IReserveInterestRateStrategy.sol @@ -11,7 +11,7 @@ interface IReserveInterestRateStrategy { * @dev returns the base variable borrow rate, in rays */ - function getBaseVariableBorrowRate() external view returns (uint256); + function baseVariableBorrowRate() external view returns (uint256); /** * @dev calculates the liquidity, stable, and variable rates depending on the current utilization rate diff --git a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol index 5059b7eb..c2303254 100644 --- a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol +++ b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol @@ -69,23 +69,23 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { * @dev accessors */ - function getVariableRateSlope1() external view returns (uint256) { + function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } - function getVariableRateSlope2() external view returns (uint256) { + function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } - function getStableRateSlope1() external view returns (uint256) { + function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } - function getStableRateSlope2() external view returns (uint256) { + function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } - function getBaseVariableBorrowRate() external override view returns (uint256) { + function baseVariableBorrowRate() external override view returns (uint256) { return _baseVariableBorrowRate; } @@ -121,7 +121,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { uint256 currentStableBorrowRate = 0; uint256 currentLiquidityRate = 0; - uint256 utilizationRate = (totalBorrows == 0 && availableLiquidity == 0) + uint256 utilizationRate = totalBorrows == 0 ? 0 : totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); @@ -157,9 +157,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { ) .rayMul(utilizationRate); - return (currentLiquidityRate, - currentStableBorrowRate, - currentVariableBorrowRate); + return (currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate); } /** From 4b00cde616b270eae050769decefe3583a2e2052 Mon Sep 17 00:00:00 2001 From: andyk Date: Tue, 25 Aug 2020 11:53:58 +0300 Subject: [PATCH 12/33] fixes in lendingpool folder to follow our styleguide --- contracts/lendingpool/LendingPool.sol | 178 +++++++++--------- .../lendingpool/LendingPoolConfigurator.sol | 24 +-- .../LendingPoolLiquidationManager.sol | 8 +- 3 files changed, 100 insertions(+), 110 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index bfbe9546..16b4d398 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -44,18 +44,18 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 public constant FLASHLOAN_FEE_TOTAL = 9; - ILendingPoolAddressesProvider internal addressesProvider; + ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => ReserveLogic.ReserveData) internal _reserves; mapping(address => UserConfiguration.Map) internal _usersConfig; - address[] internal reservesList; + address[] internal _reservesList; /** * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { - require(addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); + require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); _; } @@ -73,7 +73,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @param provider the address of the LendingPoolAddressesProvider registry **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { - addressesProvider = provider; + _addressesProvider = provider; } /** @@ -114,7 +114,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { } /** - * @dev withdraws the _reserves of _user. + * @dev withdraws the _reserves of user. * @param asset the address of the reserve * @param amount the underlying amount to be redeemed **/ @@ -139,8 +139,8 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { userBalance, _reserves, _usersConfig[msg.sender], - reservesList, - addressesProvider.getPriceOracle() + _reservesList, + _addressesProvider.getPriceOracle() ); reserve.updateCumulativeIndexesAndTimestamp(); @@ -173,7 +173,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ReserveLogic.ReserveData storage reserve = _reserves[asset]; UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; - uint256 amountInETH = IPriceOracleGetter(addressesProvider.getPriceOracle()) + uint256 amountInETH = IPriceOracleGetter(_addressesProvider.getPriceOracle()) .getAssetPrice(asset) .mul(amount) .div(10**reserve.configuration.getDecimals()); //price is in ether @@ -187,8 +187,8 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { MAX_STABLE_RATE_BORROW_SIZE_PERCENT, _reserves, _usersConfig[msg.sender], - reservesList, - addressesProvider.getPriceOracle() + _reservesList, + _addressesProvider.getPriceOracle() ); //caching the current stable borrow rate @@ -225,26 +225,26 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { /** * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). - * @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account, - * _onBehalfOf must be equal to msg.sender. + * @dev the target user is defined by onBehalfOf. If there is no repayment on behalf of another account, + * onBehalfOf must be equal to msg.sender. * @param asset the address of the reserve on which the user borrowed * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything - * @param _onBehalfOf the address for which msg.sender is repaying. + * @param onBehalfOf the address for which msg.sender is repaying. **/ function repay( address asset, uint256 amount, - uint256 _rateMode, - address _onBehalfOf + uint256 rateMode, + address onBehalfOf ) external override nonReentrant { ReserveLogic.ReserveData storage reserve = _reserves[asset]; - (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(_onBehalfOf, reserve); + (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); + + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); - ReserveLogic.InterestRateMode rateMode = ReserveLogic.InterestRateMode(_rateMode); - //default to max amount - uint256 paybackAmount = rateMode == ReserveLogic.InterestRateMode.STABLE + uint256 paybackAmount = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? stableDebt : variableDebt; @@ -255,8 +255,8 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ValidationLogic.validateRepay( reserve, amount, - rateMode, - _onBehalfOf, + interestRateMode, + onBehalfOf, stableDebt, variableDebt ); @@ -264,46 +264,46 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); //burns an equivalent amount of debt tokens - if (rateMode == ReserveLogic.InterestRateMode.STABLE) { - IStableDebtToken(reserve.stableDebtTokenAddress).burn(_onBehalfOf, paybackAmount); + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { + IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(_onBehalfOf, paybackAmount); + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } reserve.updateInterestRates(asset, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { - _usersConfig[_onBehalfOf].setBorrowing(reserve.index, false); + _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); } IERC20(asset).safeTransferFrom(msg.sender, reserve.aTokenAddress, paybackAmount); - emit Repay(asset, _onBehalfOf, msg.sender, paybackAmount); + emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); } /** * @dev borrowers can user this function to swap between stable and variable borrow rate modes. * @param asset the address of the reserve on which the user borrowed - * @param _rateMode the rate mode that the user wants to swap + * @param rateMode the rate mode that the user wants to swap **/ - function swapBorrowRateMode(address asset, uint256 _rateMode) external override nonReentrant { + function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); - ReserveLogic.InterestRateMode rateMode = ReserveLogic.InterestRateMode(_rateMode); + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, - rateMode + interestRateMode ); reserve.updateCumulativeIndexesAndTimestamp(); - if (rateMode == ReserveLogic.InterestRateMode.STABLE) { + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); @@ -332,14 +332,14 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair * rate. Anyone can call this function. * @param asset the address of the reserve - * @param _user the address of the user to be rebalanced + * @param user the address of the user to be rebalanced **/ - function rebalanceStableBorrowRate(address asset, address _user) external override nonReentrant { + function rebalanceStableBorrowRate(address asset, address user) external override nonReentrant { ReserveLogic.ReserveData storage reserve = _reserves[asset]; IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); - uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(_user); + uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); // user must be borrowing on asset at a stable rate require(stableBorrowBalance > 0, 'User does not have any stable rate loan for this reserve'); @@ -353,7 +353,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low. //In this case, the user is paying an interest that is too high, and needs to be rescaled down. - uint256 userStableRate = stableDebtToken.getUserStableRate(_user); + uint256 userStableRate = stableDebtToken.getUserStableRate(user); require( userStableRate < reserve.currentLiquidityRate || userStableRate > rebalanceDownRateThreshold, @@ -364,12 +364,12 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); - stableDebtToken.burn(_user, stableBorrowBalance); - stableDebtToken.mint(_user, stableBorrowBalance, reserve.currentStableBorrowRate); + stableDebtToken.burn(user, stableBorrowBalance); + stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); reserve.updateInterestRates(asset, 0, 0); - emit RebalanceStableBorrowRate(asset, _user); + emit RebalanceStableBorrowRate(asset, user); return; } @@ -377,9 +377,9 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { /** * @dev allows depositors to enable or disable a specific deposit as collateral. * @param asset the address of the reserve - * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. + * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/ - function setUserUseReserveAsCollateral(address asset, bool _useAsCollateral) + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override nonReentrant @@ -391,13 +391,13 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { asset, _reserves, _usersConfig[msg.sender], - reservesList, - addressesProvider.getPriceOracle() + _reservesList, + _addressesProvider.getPriceOracle() ); - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, _useAsCollateral); + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, useAsCollateral); - if (_useAsCollateral) { + if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); @@ -408,29 +408,29 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @dev users can invoke this function to liquidate an undercollateralized position. * @param asset the address of the collateral to liquidated * @param asset the address of the principal reserve - * @param _user the address of the borrower - * @param _purchaseAmount the amount of principal that the liquidator wants to repay - * @param _receiveAToken true if the liquidators wants to receive the aTokens, false if + * @param user the address of the borrower + * @param purchaseAmount the amount of principal that the liquidator wants to repay + * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( - address _collateral, + address collateral, address asset, - address _user, - uint256 _purchaseAmount, - bool _receiveAToken + address user, + uint256 purchaseAmount, + bool receiveAToken ) external override nonReentrant { - address liquidationManager = addressesProvider.getLendingPoolLiquidationManager(); + address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', - _collateral, + collateral, asset, - _user, - _purchaseAmount, - _receiveAToken + user, + purchaseAmount, + receiveAToken ) ); require(success, 'Liquidation call failed'); @@ -490,7 +490,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { 'The actual balance of the protocol is inconsistent' ); - //compounding the cumulated interest + //compounding the cumulated interest reserve.updateCumulativeIndexesAndTimestamp(); uint256 totalLiquidityBefore = availableLiquidityBefore @@ -595,7 +595,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ); } - function getUserAccountData(address _user) + function getUserAccountData(address user) external override view @@ -615,11 +615,11 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( - _user, + user, _reserves, - _usersConfig[_user], - reservesList, - addressesProvider.getPriceOracle() + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( @@ -629,7 +629,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ); } - function getUserReserveData(address asset, address _user) + function getUserReserveData(address asset, address user) external override view @@ -648,20 +648,20 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { { ReserveLogic.ReserveData storage reserve = _reserves[asset]; - currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(_user); - (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(_user, reserve); - (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(_user, reserve); + currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); + (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); + (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); liquidityRate = reserve.currentLiquidityRate; - stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(_user); + stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( - _user + user ); - usageAsCollateralEnabled = _usersConfig[_user].isUsingAsCollateral(reserve.index); - variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(_user); + usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); + variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(user); } function getReserves() external override view returns (address[] memory) { - return reservesList; + return _reservesList; } receive() external payable { @@ -671,21 +671,21 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { /** * @dev initializes a reserve * @param asset the address of the reserve - * @param _aTokenAddress the address of the overlying aToken contract - * @param _interestRateStrategyAddress the address of the interest rate strategy contract + * @param aTokenAddress the address of the overlying aToken contract + * @param interestRateStrategyAddress the address of the interest rate strategy contract **/ function initReserve( address asset, - address _aTokenAddress, - address _stableDebtAddress, - address _variableDebtAddress, - address _interestRateStrategyAddress + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { _reserves[asset].init( - _aTokenAddress, - _stableDebtAddress, - _variableDebtAddress, - _interestRateStrategyAddress + aTokenAddress, + stableDebtAddress, + variableDebtAddress, + interestRateStrategyAddress ); _addReserveToList(asset); } @@ -730,13 +730,13 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { **/ function _addReserveToList(address asset) internal { bool reserveAlreadyAdded = false; - for (uint256 i = 0; i < reservesList.length; i++) - if (reservesList[i] == asset) { + for (uint256 i = 0; i < _reservesList.length; i++) + if (_reservesList[i] == asset) { reserveAlreadyAdded = true; } if (!reserveAlreadyAdded) { - _reserves[asset].index = uint8(reservesList.length); - reservesList.push(asset); + _reserves[asset].index = uint8(_reservesList.length); + _reservesList.push(asset); } } @@ -782,8 +782,8 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { amount, _reserves, _usersConfig[user], - reservesList, - addressesProvider.getPriceOracle() + _reservesList, + _addressesProvider.getPriceOracle() ); } @@ -791,13 +791,13 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @dev returns the list of the initialized reserves **/ function getReservesList() external view returns (address[] memory) { - return reservesList; + return _reservesList; } /** * @dev returns the addresses provider **/ function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return addressesProvider; + return _addressesProvider; } } diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 9560b88e..5a2d732b 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -164,10 +164,10 @@ contract LendingPoolConfigurator is VersionedInitializable { /** * @dev emitted when the implementation of a variable debt token is upgraded * @param asset the address of the reserve - * @param _proxy the variable debt token proxy address - * @param _implementation the new aToken implementation + * @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 asset, address proxy, address implementation); ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; @@ -211,10 +211,7 @@ contract LendingPoolConfigurator is VersionedInitializable { uint8 underlyingAssetDecimals, address interestRateStrategyAddress ) public onlyLendingPoolManager { - address aTokenProxyAddress = _initTokenWithProxy( - aTokenImpl, - underlyingAssetDecimals - ); + address aTokenProxyAddress = _initTokenWithProxy(aTokenImpl, underlyingAssetDecimals); address stableDebtTokenProxyAddress = _initTokenWithProxy( stableDebtTokenImpl, @@ -280,6 +277,7 @@ contract LendingPoolConfigurator is VersionedInitializable { emit StableDebtTokenUpgraded(asset, stableDebtToken, implementation); } + /** * @dev updates the variable debt token implementation for the asset * @param asset the address of the reserve to be updated @@ -349,12 +347,7 @@ contract LendingPoolConfigurator is VersionedInitializable { pool.setConfiguration(asset, currentConfig.data); - emit ReserveEnabledAsCollateral( - asset, - ltv, - liquidationThreshold, - liquidationBonus - ); + emit ReserveEnabledAsCollateral(asset, ltv, liquidationThreshold, liquidationBonus); } /** @@ -553,10 +546,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param implementation the address of the implementation * @param decimals the decimals of the token **/ - function _initTokenWithProxy( - address implementation, - uint8 decimals - ) internal returns (address) { + function _initTokenWithProxy(address implementation, uint8 decimals) internal returns (address) { InitializableAdminUpgradeabilityProxy proxy = new InitializableAdminUpgradeabilityProxy(); bytes memory params = abi.encodeWithSignature( diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 17d08a03..84bf0099 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -283,8 +283,8 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl * @return principalAmountNeeded the purchase amount **/ function calculateAvailableCollateralToLiquidate( - ReserveLogic.ReserveData storage _collateralReserve, - ReserveLogic.ReserveData storage _principalReserve, + ReserveLogic.ReserveData storage collateralReserve, + ReserveLogic.ReserveData storage principalReserve, address collateralAddress, address principalAddress, uint256 purchaseAmount, @@ -300,10 +300,10 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl vars.collateralPrice = oracle.getAssetPrice(collateralAddress); vars.principalCurrencyPrice = oracle.getAssetPrice(principalAddress); - (, , vars.liquidationBonus, vars.collateralDecimals) = _collateralReserve + (, , vars.liquidationBonus, vars.collateralDecimals) = collateralReserve .configuration .getParams(); - vars.principalDecimals = _principalReserve.configuration.getDecimals(); + vars.principalDecimals = principalReserve.configuration.getDecimals(); //this is the maximum possible amount of the selected collateral that can be liquidated, given the //max amount of principal currency that is available for liquidation. From b0ddb815b82c8887488055dbd84cb803db5a2967 Mon Sep 17 00:00:00 2001 From: andyk Date: Tue, 25 Aug 2020 13:37:38 +0300 Subject: [PATCH 13/33] small lending pool gas optimization --- contracts/lendingpool/LendingPool.sol | 42 ++++++++++--------- .../LendingPoolLiquidationManager.sol | 20 ++++++--- contracts/libraries/logic/ReserveLogic.sol | 19 ++++----- 3 files changed, 45 insertions(+), 36 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 16b4d398..ec587920 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -92,22 +92,21 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ValidationLogic.validateDeposit(reserve, amount); - IAToken aToken = IAToken(reserve.aTokenAddress); - - bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0; + address aToken = reserve.aTokenAddress; reserve.updateCumulativeIndexesAndTimestamp(); - reserve.updateInterestRates(asset, amount, 0); + reserve.updateInterestRates(asset, aToken, amount, 0); + bool isFirstDeposit = IAToken(aToken).balanceOf(msg.sender) == 0; if (isFirstDeposit) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, true); } //minting AToken to user 1:1 with the specific exchange rate - aToken.mint(msg.sender, amount); + IAToken(aToken).mint(msg.sender, amount); //transfer to the aToken contract - IERC20(asset).safeTransferFrom(msg.sender, address(aToken), amount); + IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); //solium-disable-next-line emit Deposit(asset, msg.sender, amount, referralCode); @@ -121,9 +120,9 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { function withdraw(address asset, uint256 amount) external override nonReentrant { ReserveLogic.ReserveData storage reserve = _reserves[asset]; - IAToken aToken = IAToken(reserve.aTokenAddress); + address aToken = reserve.aTokenAddress; - uint256 userBalance = aToken.balanceOf(msg.sender); + uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; @@ -134,7 +133,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ValidationLogic.validateWithdraw( asset, - address(aToken), + aToken, amountToWithdraw, userBalance, _reserves, @@ -145,13 +144,13 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); - reserve.updateInterestRates(asset, 0, amountToWithdraw); + reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, false); } - aToken.burn(msg.sender, msg.sender, amountToWithdraw); + IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw); //solium-disable-next-line emit Withdraw(asset, msg.sender, amount); @@ -202,14 +201,16 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); } - reserve.updateInterestRates(asset, 0, amount); + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, 0, amount); - if (!userConfig.isBorrowing(reserve.index)) { - userConfig.setBorrowing(reserve.index, true); + uint256 reserveIndex = reserve.index; + if (!userConfig.isBorrowing(reserveIndex)) { + userConfig.setBorrowing(reserveIndex, true); } //if we reached this point, we can transfer - IAToken(reserve.aTokenAddress).transferUnderlyingTo(msg.sender, amount); + IAToken(aToken).transferUnderlyingTo(msg.sender, amount); emit Borrow( asset, @@ -270,13 +271,14 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } - reserve.updateInterestRates(asset, paybackAmount, 0); + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); } - IERC20(asset).safeTransferFrom(msg.sender, reserve.aTokenAddress, paybackAmount); + IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); } @@ -317,7 +319,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { ); } - reserve.updateInterestRates(asset, 0, 0); + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap( asset, @@ -367,7 +369,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { stableDebtToken.burn(user, stableBorrowBalance); stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); - reserve.updateInterestRates(asset, 0, 0); + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); @@ -501,7 +503,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); //refresh interest rates - reserve.updateInterestRates(asset, amountFee, 0); + reserve.updateInterestRates(asset, aTokenAddress, amountFee, 0); //solium-disable-next-line emit FlashLoan(receiverAddress, asset, amount, amountFee); diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 84bf0099..a36ed3f3 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -136,7 +136,9 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl ); } - vars.userCollateralBalance = IERC20(collateralReserve.aTokenAddress).balanceOf(user); + vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); + + vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && @@ -192,8 +194,6 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl vars.actualAmountToLiquidate = vars.principalAmountNeeded; } - vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); - //if liquidator reclaims the underlying asset, we make sure there is enough available collateral in the reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateral).balanceOf( @@ -209,7 +209,12 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl //update the principal reserve principalReserve.updateCumulativeIndexesAndTimestamp(); - principalReserve.updateInterestRates(principal, vars.actualAmountToLiquidate, 0); + principalReserve.updateInterestRates( + principal, + principalReserve.aTokenAddress, + vars.actualAmountToLiquidate, + 0 + ); if (vars.userVariableDebt >= vars.actualAmountToLiquidate) { IVariableDebtToken(principalReserve.variableDebtTokenAddress).burn( @@ -235,7 +240,12 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl //updating collateral reserve collateralReserve.updateCumulativeIndexesAndTimestamp(); - collateralReserve.updateInterestRates(collateral, 0, vars.maxCollateralToLiquidate); + collateralReserve.updateInterestRates( + collateral, + address(vars.collateralAtoken), + 0, + vars.maxCollateralToLiquidate + ); //burn the equivalent amount of atoken vars.collateralAtoken.burn(user, msg.sender, vars.maxCollateralToLiquidate); diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 6aab6932..893ca5c5 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -126,18 +126,18 @@ library ReserveLogic { IERC20(reserve.variableDebtTokenAddress).totalSupply() > 0 || IERC20(reserve.stableDebtTokenAddress).totalSupply() > 0 ) { + uint40 lastUpdateTimestamp = reserve.lastUpdateTimestamp; + uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( reserve.currentLiquidityRate, - reserve.lastUpdateTimestamp + lastUpdateTimestamp ); - reserve.lastLiquidityIndex = cumulatedLiquidityInterest.rayMul( - reserve.lastLiquidityIndex - ); + reserve.lastLiquidityIndex = cumulatedLiquidityInterest.rayMul(reserve.lastLiquidityIndex); uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( reserve.currentVariableBorrowRate, - reserve.lastUpdateTimestamp + lastUpdateTimestamp ); reserve.lastVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul( reserve.lastVariableBorrowIndex @@ -164,9 +164,7 @@ library ReserveLogic { uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray()); - reserve.lastLiquidityIndex = cumulatedLiquidity.rayMul( - reserve.lastLiquidityIndex - ); + reserve.lastLiquidityIndex = cumulatedLiquidity.rayMul(reserve.lastLiquidityIndex); } /** @@ -208,21 +206,20 @@ library ReserveLogic { function updateInterestRates( ReserveData storage reserve, address reserveAddress, + address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { uint256 currentAvgStableRate = IStableDebtToken(reserve.stableDebtTokenAddress) .getAverageStableRate(); - uint256 balance = IERC20(reserveAddress).balanceOf(reserve.aTokenAddress); - ( uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, - balance.add(liquidityAdded).sub(liquidityTaken), + IERC20(reserveAddress).balanceOf(aTokenAddress).add(liquidityAdded).sub(liquidityTaken), IERC20(reserve.stableDebtTokenAddress).totalSupply(), IERC20(reserve.variableDebtTokenAddress).totalSupply(), currentAvgStableRate From 75da6e0fbab360b78876acc9ebbaf1a7e3bdebb6 Mon Sep 17 00:00:00 2001 From: eboado Date: Tue, 25 Aug 2020 12:55:05 +0200 Subject: [PATCH 14/33] - Adapted flashLoan() for partial debt opening. --- contracts/interfaces/ILendingPool.sol | 1 + contracts/lendingpool/LendingPool.sol | 174 ++++++++++++++------------ package.json | 1 + test/flashloan.spec.ts | 86 +++++++------ 4 files changed, 145 insertions(+), 117 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 5b15ce74..a7a5e1ca 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -232,6 +232,7 @@ interface ILendingPool { address receiver, address reserve, uint256 amount, + uint256 debtType, bytes calldata params, uint16 referralCode ) external; diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 69e4fb6e..839c0c42 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -154,6 +154,15 @@ contract LendingPool is VersionedInitializable, ILendingPool { emit Withdraw(asset, msg.sender, amount); } + struct BorrowLocalVars { + address asset; + address user; + uint256 amount; + uint256 interestRateMode; + bool releaseUnderlying; + uint16 referralCode; + } + /** * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower * already deposited enough collateral. @@ -167,25 +176,35 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 interestRateMode, uint16 referralCode ) external override { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; + _executeBorrow( + BorrowLocalVars(asset, msg.sender, amount, interestRateMode, true, referralCode) + ); + } - uint256 amountInETH = IPriceOracleGetter(addressesProvider.getPriceOracle()) - .getAssetPrice(asset) - .mul(amount) - .div(10**reserve.configuration.getDecimals()); //price is in ether + /** + * @dev Internal function to execute a borrowing action, allowing to transfer or not the underlying + * @param vars Input struct for the borrowing action, in order to avoid STD errors + **/ + function _executeBorrow(BorrowLocalVars memory vars) internal { + ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; + UserConfiguration.Map storage userConfig = _usersConfig[vars.user]; + + address oracle = addressesProvider.getPriceOracle(); + uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( + 10**reserve.configuration.getDecimals() + ); ValidationLogic.validateBorrow( reserve, - asset, - amount, + vars.asset, + vars.amount, amountInETH, - interestRateMode, + vars.interestRateMode, MAX_STABLE_RATE_BORROW_SIZE_PERCENT, _reserves, - _usersConfig[msg.sender], + _usersConfig[vars.user], reservesList, - addressesProvider.getPriceOracle() + oracle ); //caching the current stable borrow rate @@ -193,30 +212,34 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); - if (ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE) { - IStableDebtToken(reserve.stableDebtTokenAddress).mint(msg.sender, amount, userStableRate); + if ( + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ) { + IStableDebtToken(reserve.stableDebtTokenAddress).mint(vars.user, vars.amount, userStableRate); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount); } - reserve.updateInterestRates(asset, 0, amount); + reserve.updateInterestRates(vars.asset, 0, vars.amount); if (!userConfig.isBorrowing(reserve.index)) { userConfig.setBorrowing(reserve.index, true); } - //if we reached this point, we can transfer - IAToken(reserve.aTokenAddress).transferUnderlyingTo(msg.sender, amount); + //if we reached this point and we need to, we can transfer + if (vars.releaseUnderlying) { + IAToken(reserve.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); + } emit Borrow( - asset, - msg.sender, - amount, - interestRateMode, - ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE + vars.asset, + vars.user, + vars.amount, + vars.interestRateMode, + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE ? userStableRate : reserve.currentVariableBorrowRate, - referralCode + vars.referralCode ); } @@ -239,7 +262,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(_onBehalfOf, reserve); ReserveLogic.InterestRateMode rateMode = ReserveLogic.InterestRateMode(_rateMode); - + //default to max amount uint256 paybackAmount = rateMode == ReserveLogic.InterestRateMode.STABLE ? stableDebt @@ -249,14 +272,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { paybackAmount = amount; } - ValidationLogic.validateRepay( - reserve, - amount, - rateMode, - _onBehalfOf, - stableDebt, - variableDebt - ); + ValidationLogic.validateRepay(reserve, amount, rateMode, _onBehalfOf, stableDebt, variableDebt); reserve.updateCumulativeIndexesAndTimestamp(); @@ -316,10 +332,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateInterestRates(asset, 0, 0); - emit Swap( - asset, - msg.sender - ); + emit Swap(asset, msg.sender); } /** @@ -374,10 +387,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param asset the address of the reserve * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/ - function setUserUseReserveAsCollateral(address asset, bool _useAsCollateral) - external - override - { + function setUserUseReserveAsCollateral(address asset, bool _useAsCollateral) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( @@ -437,10 +447,14 @@ contract LendingPool is VersionedInitializable, ILendingPool { } } - struct FlashLoanLocalVars{ + struct FlashLoanLocalVars { uint256 premium; uint256 amountPlusPremium; uint256 amountPlusPremiumInETH; + uint256 receiverBalance; + uint256 receiverAllowance; + uint256 balanceToPull; + uint256 assetPrice; IFlashLoanReceiver receiver; address aTokenAddress; address oracle; @@ -451,13 +465,17 @@ contract LendingPool is VersionedInitializable, ILendingPool { * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts * that must be kept into consideration. For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. - * @param asset the address of the principal reserve - * @param amount the amount requested for this flashloan + * @param asset The address of the principal reserve + * @param amount The amount requested for this flashloan + * @param debtType 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 params Variadic packed params to pass to the receiver as extra information + * @param referralCode Referral code of the flash loan **/ function flashLoan( address receiverAddress, address asset, uint256 amount, + uint256 debtType, bytes calldata params, uint16 referralCode ) external override { @@ -486,49 +504,51 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.amountPlusPremium = amount.add(vars.premium); //transfer from the receiver the amount plus the fee - try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium) { + try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium) { //if the transfer succeeded, the executor has repaid the flashloan. //the fee is compounded into the reserve reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); //refresh interest rates reserve.updateInterestRates(asset, vars.premium, 0); emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); - } - catch(bytes memory reason){ + } catch (bytes memory reason) { + if (debtType == 1 || debtType == 2) { + // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. + // We will try to pull all the available funds from the receiver and create a debt position with the rest owed + // if it has collateral enough - //if the transfer didn't succeed, the executor either didn't return the funds, or didn't approve the transfer. - //we check if the caller has enough collateral to open a variable rate loan. If it does, then debt is mint to msg.sender - vars.oracle = addressesProvider.getPriceOracle(); - vars.amountPlusPremiumInETH = IPriceOracleGetter(vars.oracle) - .getAssetPrice(asset) - .mul(vars.amountPlusPremium) - .div(10**reserve.configuration.getDecimals()); //price is in ether + vars.receiverBalance = IERC20(asset).balanceOf(receiverAddress); + vars.receiverAllowance = IERC20(asset).allowance(receiverAddress, address(this)); + vars.balanceToPull = (vars.receiverBalance > vars.receiverAllowance) + ? vars.receiverAllowance + : vars.receiverBalance; - ValidationLogic.validateBorrow( - reserve, - asset, - vars.amountPlusPremium, - vars.amountPlusPremiumInETH, - uint256(ReserveLogic.InterestRateMode.VARIABLE), - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - _usersConfig[msg.sender], - reservesList, - vars.oracle - ); + if (vars.balanceToPull > 0) { + IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.balanceToPull); + reserve.cumulateToLiquidityIndex( + IERC20(vars.aTokenAddress).totalSupply(), + (vars.balanceToPull > vars.premium) ? vars.premium : vars.balanceToPull + ); + reserve.updateInterestRates( + asset, + (vars.balanceToPull > vars.premium) ? vars.premium : vars.balanceToPull, + 0 + ); + } - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, vars.amountPlusPremium); - //refresh interest rate, substracting from the available liquidity the flashloan amount - reserve.updateInterestRates(asset, 0, amount); - - emit Borrow( - asset, - msg.sender, - vars.amountPlusPremium, - uint256(ReserveLogic.InterestRateMode.VARIABLE), - reserve.currentVariableBorrowRate, - referralCode - ); + _executeBorrow( + BorrowLocalVars( + asset, + msg.sender, + vars.amountPlusPremium.sub(vars.balanceToPull), + debtType, + false, + referralCode + ) + ); + } else { + revert(string(reason)); + } } } diff --git a/package.json b/package.json index 34e56bfa..606aaaf9 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "types-gen": "typechain --target ethers-v5 --outDir ./types './artifacts/*.json'", "test": "buidler test", "test-scenarios": "buidler test test/__setup.spec.ts test/scenario.spec.ts", + "test-flash": "buidler test test/__setup.spec.ts test/flashloan.spec.ts", "dev:coverage": "buidler coverage", "dev:deployment": "buidler dev-deployment", "dev:deployExample": "buidler deploy-Example", diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index dfda3085..93915783 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -1,13 +1,17 @@ -import { TestEnv, makeSuite } from './helpers/make-suite'; -import { APPROVAL_AMOUNT_LENDING_POOL, oneRay } from '../helpers/constants'; -import { convertToCurrencyDecimals, getMockFlashLoanReceiver, getContract } from '../helpers/contracts-helpers'; -import { ethers } from 'ethers'; -import { MockFlashLoanReceiver } from '../types/MockFlashLoanReceiver'; -import { ProtocolErrors, eContractid } from '../helpers/types'; +import {TestEnv, makeSuite} from './helpers/make-suite'; +import {APPROVAL_AMOUNT_LENDING_POOL, oneRay} from '../helpers/constants'; +import { + convertToCurrencyDecimals, + getMockFlashLoanReceiver, + getContract, +} from '../helpers/contracts-helpers'; +import {ethers} from 'ethers'; +import {MockFlashLoanReceiver} from '../types/MockFlashLoanReceiver'; +import {ProtocolErrors, eContractid} from '../helpers/types'; import BigNumber from 'bignumber.js'; -import { VariableDebtToken } from '../types/VariableDebtToken'; +import {VariableDebtToken} from '../types/VariableDebtToken'; -const { expect } = require('chai'); +const {expect} = require('chai'); makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; @@ -22,7 +26,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Deposits ETH into the reserve', async () => { - const { pool, weth } = testEnv; + const {pool, weth} = testEnv; const amountToDeposit = ethers.utils.parseEther('1'); await weth.mint(amountToDeposit); @@ -33,12 +37,13 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes ETH flashloan, returns the funds correctly', async () => { - const { pool, deployer, weth } = testEnv; + const {pool, deployer, weth} = testEnv; await pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), + 2, '0x10', '0' ); @@ -60,13 +65,14 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes an ETH flashloan as big as the available liquidity', async () => { - const { pool, weth } = testEnv; + const {pool, weth} = testEnv; const reserveDataBefore = await pool.getReserveData(weth.address); const txResult = await pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1000720000000000000', + 2, '0x10', '0' ); @@ -86,7 +92,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes WETH flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { - const { pool, weth, users } = testEnv; + const {pool, weth, users} = testEnv; const caller = users[1]; await _mockFlashLoanReceiver.setFailExecutionTransfer(true); @@ -97,6 +103,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), + 2, '0x10', '0' ) @@ -104,7 +111,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds. A loan for caller is created', async () => { - const { dai, pool, weth, users } = testEnv; + const {dai, pool, weth, users} = testEnv; const caller = users[1]; @@ -124,12 +131,16 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), + 2, '0x10', '0' ); const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(weth.address); - const wethDebtToken = await getContract(eContractid.VariableDebtToken, variableDebtTokenAddress); + const wethDebtToken = await getContract( + eContractid.VariableDebtToken, + variableDebtTokenAddress + ); const callerDebt = await wethDebtToken.balanceOf(caller.address); @@ -137,13 +148,14 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('tries to take a very small flashloan, which would result in 0 fees (revert expected)', async () => { - const { pool, weth } = testEnv; + const {pool, weth} = testEnv; await expect( pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1', //1 wei loan + 2, '0x10', '0' ) @@ -151,13 +163,14 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('tries to take a flashloan that is bigger than the available liquidity (revert expected)', async () => { - const { pool, weth } = testEnv; + const {pool, weth} = testEnv; await expect( pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, '1004415000000000000', //slightly higher than the available liquidity + 2, '0x10', '0' ), @@ -166,14 +179,15 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('tries to take a flashloan using a non contract address as receiver (revert expected)', async () => { - const { pool, deployer, weth } = testEnv; + const {pool, deployer, weth} = testEnv; - await expect(pool.flashLoan(deployer.address, weth.address, '1000000000000000000', '0x10', '0')) - .to.be.reverted; + await expect( + pool.flashLoan(deployer.address, weth.address, '1000000000000000000', 2, '0x10', '0') + ).to.be.reverted; }); it('Deposits USDC into the reserve', async () => { - const { usdc, pool } = testEnv; + const {usdc, pool} = testEnv; await usdc.mint(await convertToCurrencyDecimals(usdc.address, '1000')); @@ -185,7 +199,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes out a 500 USDC flashloan, returns the funds correctly', async () => { - const { usdc, pool, deployer: depositor } = testEnv; + const {usdc, pool, deployer: depositor} = testEnv; await _mockFlashLoanReceiver.setFailExecutionTransfer(false); @@ -195,6 +209,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, usdc.address, flashloanAmount, + 2, '0x10', '0' ); @@ -210,7 +225,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const currentLiquidityIndex = reserveData.liquidityIndex.toString(); const currentUserBalance = userData.currentATokenBalance.toString(); - const expectedLiquidity = await convertToCurrencyDecimals(usdc.address,'1000.450'); + const expectedLiquidity = await convertToCurrencyDecimals(usdc.address, '1000.450'); expect(totalLiquidity).to.be.equal(expectedLiquidity, 'Invalid total liquidity'); expect(currentLiqudityRate).to.be.equal('0', 'Invalid liquidity rate'); @@ -222,7 +237,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { }); it('Takes out a 500 USDC flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { - const { usdc, pool, users } = testEnv; + const {usdc, pool, users} = testEnv; const caller = users[2]; const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); @@ -232,18 +247,12 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await expect( pool .connect(caller.signer) - .flashLoan( - _mockFlashLoanReceiver.address, - usdc.address, - flashloanAmount, - '0x10', - '0' - ) + .flashLoan(_mockFlashLoanReceiver.address, usdc.address, flashloanAmount, 2, '0x10', '0') ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); }); it('Caller deposits 5 ETH as collateral, Takes a USDC flashloan, does not return the funds. A loan for caller is created', async () => { - const { usdc, pool, weth, users } = testEnv; + const {usdc, pool, weth, users} = testEnv; const caller = users[2]; @@ -256,21 +265,18 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await pool.connect(caller.signer).deposit(weth.address, amountToDeposit, '0'); await _mockFlashLoanReceiver.setFailExecutionTransfer(true); - + const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); await pool .connect(caller.signer) - .flashLoan( - _mockFlashLoanReceiver.address, - usdc.address, - flashloanAmount, - '0x10', - '0' - ); + .flashLoan(_mockFlashLoanReceiver.address, usdc.address, flashloanAmount, 2, '0x10', '0'); const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(usdc.address); - const usdcDebtToken = await getContract(eContractid.VariableDebtToken, variableDebtTokenAddress); + const usdcDebtToken = await getContract( + eContractid.VariableDebtToken, + variableDebtTokenAddress + ); const callerDebt = await usdcDebtToken.balanceOf(caller.address); From 5435620e4147a547cc1ca41aba436d996e4c1438 Mon Sep 17 00:00:00 2001 From: eboado Date: Tue, 25 Aug 2020 14:50:07 +0200 Subject: [PATCH 15/33] - Added tests to cover flashLoan(). --- .../mocks/flashloan/MockFlashLoanReceiver.sol | 26 +++++--- test/flashloan.spec.ts | 60 +++++++++++++++++++ 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol index 610e94cd..112084a7 100644 --- a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol +++ b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol @@ -18,12 +18,21 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { event ExecutedWithFail(address _reserve, uint256 _amount, uint256 _fee); event ExecutedWithSuccess(address _reserve, uint256 _amount, uint256 _fee); - bool failExecution = false; + bool _failExecution; + uint256 _amountToApprove; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} - function setFailExecutionTransfer(bool _fail) public { - failExecution = _fail; + function setFailExecutionTransfer(bool fail) public { + _failExecution = fail; + } + + function setAmountToApprove(uint256 amountToApprove) public { + _amountToApprove = amountToApprove; + } + + function amountToApprove() public view returns (uint256) { + return _amountToApprove; } function executeOperation( @@ -36,12 +45,11 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { MintableERC20 token = MintableERC20(reserve); //check the contract has the specified balance - require( - amount <= IERC20(reserve).balanceOf(address(this)), - 'Invalid balance for the contract' - ); + require(amount <= IERC20(reserve).balanceOf(address(this)), 'Invalid balance for the contract'); - if (failExecution) { + uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amount.add(fee); + + if (_failExecution) { emit ExecutedWithFail(reserve, amount, fee); return; } @@ -51,7 +59,7 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { token.mint(fee); - IERC20(reserve).approve(_addressesProvider.getLendingPool(), amount.add(fee)); + IERC20(reserve).approve(_addressesProvider.getLendingPool(), amountToReturn); emit ExecutedWithSuccess(reserve, amount, fee); } diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 93915783..689796ec 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -282,4 +282,64 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(callerDebt.toString()).to.be.equal('500450000', 'Invalid user debt'); }); + + it('Caller deposits 5 ETH as collateral, Takes a USDC flashloan, approves only partially funds. A loan for caller is created', async () => { + const {usdc, pool, weth, users} = testEnv; + + const caller = users[3]; + + await weth.connect(caller.signer).mint(await convertToCurrencyDecimals(weth.address, '5')); + + await weth.connect(caller.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); + + const amountToDeposit = await convertToCurrencyDecimals(weth.address, '5'); + + await pool.connect(caller.signer).deposit(weth.address, amountToDeposit, '0'); + + const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); + + await _mockFlashLoanReceiver.setFailExecutionTransfer(false); + + await _mockFlashLoanReceiver.setAmountToApprove(flashloanAmount.div(2)); + console.log((await _mockFlashLoanReceiver.amountToApprove()).toString()); + + await pool + .connect(caller.signer) + .flashLoan(_mockFlashLoanReceiver.address, usdc.address, flashloanAmount, 2, '0x10', '0'); + const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(usdc.address); + + const usdcDebtToken = await getContract( + eContractid.VariableDebtToken, + variableDebtTokenAddress + ); + + const callerDebt = await usdcDebtToken.balanceOf(caller.address); + + expect(callerDebt.toString()).to.be.equal('250450000', 'Invalid user debt'); + }); + + it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds and selects revert as result', async () => { + const {dai, pool, weth, users} = testEnv; + + const caller = users[3]; + + await dai.connect(caller.signer).mint(await convertToCurrencyDecimals(dai.address, '1000')); + + await dai.connect(caller.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); + + const amountToDeposit = await convertToCurrencyDecimals(dai.address, '1000'); + + await pool.connect(caller.signer).deposit(dai.address, amountToDeposit, '0'); + + const flashAmount = ethers.utils.parseEther('0.8'); + + await _mockFlashLoanReceiver.setFailExecutionTransfer(false); + await _mockFlashLoanReceiver.setAmountToApprove(flashAmount.div(2)); + + await expect( + pool + .connect(caller.signer) + .flashLoan(_mockFlashLoanReceiver.address, weth.address, flashAmount, 0, '0x10', '0') + ).to.be.revertedWith('ERC20: transfer amount exceeds allowance'); + }); }); From abe967c707c6e90af19df4accd242551ffbdf051 Mon Sep 17 00:00:00 2001 From: pol <> Date: Tue, 25 Aug 2020 15:32:22 +0200 Subject: [PATCH 16/33] Updated require message errors with constant string numbers to reduce gas --- contracts/lendingpool/LendingPool.sol | 1402 +++++++++++++------------ 1 file changed, 711 insertions(+), 691 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index ec587920..ea384125 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -6,7 +6,7 @@ import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { - VersionedInitializable + VersionedInitializable } from '../libraries/openzeppelin-upgradeability/VersionedInitializable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../tokenization/interfaces/IAToken.sol'; @@ -32,774 +32,794 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; **/ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { - using SafeMath for uint256; - using WadRayMath for uint256; - using ReserveLogic for ReserveLogic.ReserveData; - using ReserveConfiguration for ReserveConfiguration.Map; - using UserConfiguration for UserConfiguration.Map; - using SafeERC20 for IERC20; + using SafeMath for uint256; + using WadRayMath for uint256; + using ReserveLogic for ReserveLogic.ReserveData; + using ReserveConfiguration for ReserveConfiguration.Map; + using UserConfiguration for UserConfiguration.Map; + using SafeERC20 for IERC20; - //main configuration parameters - uint256 public constant REBALANCE_DOWN_RATE_DELTA = (1e27) / 5; - uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; - uint256 public constant FLASHLOAN_FEE_TOTAL = 9; + //main configuration parameters + uint256 public constant REBALANCE_DOWN_RATE_DELTA = (1e27) / 5; + uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; + uint256 public constant FLASHLOAN_FEE_TOTAL = 9; - ILendingPoolAddressesProvider internal _addressesProvider; + //require error messages + string private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '1'; // 'User does not have any stable rate loan for this reserve' + string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '2'; // 'Interest rate rebalance conditions were not met' + string private constant LIQUIDATION_CALL_FAILED = '3'; // 'Liquidation call failed' + string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '4'; // 'There is not enough liquidity available to borrow' + string private constant REQUESTED_AMOUNT_TO_SMALL = '5'; // 'The requested amount is too small for a FlashLoan.' + string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '6'; // 'The actual balance of the protocol is inconsistent' - mapping(address => ReserveLogic.ReserveData) internal _reserves; - mapping(address => UserConfiguration.Map) internal _usersConfig; + ILendingPoolAddressesProvider internal _addressesProvider; - address[] internal _reservesList; + mapping(address => ReserveLogic.ReserveData) internal _reserves; + mapping(address => UserConfiguration.Map) internal _usersConfig; - /** - * @dev only lending pools configurator can use functions affected by this modifier - **/ - modifier onlyLendingPoolConfigurator { - require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); - _; - } + address[] internal _reservesList; - uint256 public constant UINT_MAX_VALUE = uint256(-1); - - uint256 public constant LENDINGPOOL_REVISION = 0x2; - - function getRevision() internal override pure returns (uint256) { - return LENDINGPOOL_REVISION; - } - - /** - * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the - * AddressesProvider. - * @param provider the address of the LendingPoolAddressesProvider registry - **/ - function initialize(ILendingPoolAddressesProvider provider) public initializer { - _addressesProvider = provider; - } - - /** - * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) - * is minted. - * @param asset the address of the reserve - * @param amount the amount to be deposited - * @param referralCode integrators are assigned a referral code and can potentially receive rewards. - **/ - function deposit( - address asset, - uint256 amount, - uint16 referralCode - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - ValidationLogic.validateDeposit(reserve, amount); - - address aToken = reserve.aTokenAddress; - - reserve.updateCumulativeIndexesAndTimestamp(); - reserve.updateInterestRates(asset, aToken, amount, 0); - - bool isFirstDeposit = IAToken(aToken).balanceOf(msg.sender) == 0; - if (isFirstDeposit) { - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, true); + /** + * @dev only lending pools configurator can use functions affected by this modifier + **/ + modifier onlyLendingPoolConfigurator { + require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); + _; } - //minting AToken to user 1:1 with the specific exchange rate - IAToken(aToken).mint(msg.sender, amount); + uint256 public constant UINT_MAX_VALUE = uint256(-1); - //transfer to the aToken contract - IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); + uint256 public constant LENDINGPOOL_REVISION = 0x2; - //solium-disable-next-line - emit Deposit(asset, msg.sender, amount, referralCode); - } - - /** - * @dev withdraws the _reserves of user. - * @param asset the address of the reserve - * @param amount the underlying amount to be redeemed - **/ - function withdraw(address asset, uint256 amount) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - address aToken = reserve.aTokenAddress; - - uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); - - uint256 amountToWithdraw = amount; - - //if amount is equal to uint(-1), the user wants to redeem everything - if (amount == UINT_MAX_VALUE) { - amountToWithdraw = userBalance; + function getRevision() internal override pure returns (uint256) { + return LENDINGPOOL_REVISION; } - ValidationLogic.validateWithdraw( - asset, - aToken, - amountToWithdraw, - userBalance, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); - - reserve.updateCumulativeIndexesAndTimestamp(); - - reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); - - if (amountToWithdraw == userBalance) { - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, false); + /** + * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the + * AddressesProvider. + * @param provider the address of the LendingPoolAddressesProvider registry + **/ + function initialize(ILendingPoolAddressesProvider provider) public initializer { + _addressesProvider = provider; } - IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw); + /** + * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) + * is minted. + * @param asset the address of the reserve + * @param amount the amount to be deposited + * @param referralCode integrators are assigned a referral code and can potentially receive rewards. + **/ + function deposit( + address asset, + uint256 amount, + uint16 referralCode + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - //solium-disable-next-line - emit Withdraw(asset, msg.sender, amount); - } + ValidationLogic.validateDeposit(reserve, amount); - /** - * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower - * already deposited enough collateral. - * @param asset the address of the reserve - * @param amount the amount to be borrowed - * @param interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) - **/ - function borrow( - address asset, - uint256 amount, - uint256 interestRateMode, - uint16 referralCode - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; + address aToken = reserve.aTokenAddress; - uint256 amountInETH = IPriceOracleGetter(_addressesProvider.getPriceOracle()) - .getAssetPrice(asset) - .mul(amount) - .div(10**reserve.configuration.getDecimals()); //price is in ether + reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateInterestRates(asset, aToken, amount, 0); - ValidationLogic.validateBorrow( - reserve, - asset, - amount, - amountInETH, - interestRateMode, - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); + bool isFirstDeposit = IAToken(aToken).balanceOf(msg.sender) == 0; + if (isFirstDeposit) { + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, true); + } - //caching the current stable borrow rate - uint256 userStableRate = reserve.currentStableBorrowRate; + //minting AToken to user 1:1 with the specific exchange rate + IAToken(aToken).mint(msg.sender, amount); - reserve.updateCumulativeIndexesAndTimestamp(); + //transfer to the aToken contract + IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); - if (ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE) { - IStableDebtToken(reserve.stableDebtTokenAddress).mint(msg.sender, amount, userStableRate); - } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); + //solium-disable-next-line + emit Deposit(asset, msg.sender, amount, referralCode); } - address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(asset, aToken, 0, amount); + /** + * @dev withdraws the _reserves of user. + * @param asset the address of the reserve + * @param amount the underlying amount to be redeemed + **/ + function withdraw(address asset, uint256 amount) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - uint256 reserveIndex = reserve.index; - if (!userConfig.isBorrowing(reserveIndex)) { - userConfig.setBorrowing(reserveIndex, true); + address aToken = reserve.aTokenAddress; + + uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); + + uint256 amountToWithdraw = amount; + + //if amount is equal to uint(-1), the user wants to redeem everything + if (amount == UINT_MAX_VALUE) { + amountToWithdraw = userBalance; + } + + ValidationLogic.validateWithdraw( + asset, + aToken, + amountToWithdraw, + userBalance, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); + + reserve.updateCumulativeIndexesAndTimestamp(); + + reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); + + if (amountToWithdraw == userBalance) { + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, false); + } + + IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw); + + //solium-disable-next-line + emit Withdraw(asset, msg.sender, amount); } - //if we reached this point, we can transfer - IAToken(aToken).transferUnderlyingTo(msg.sender, amount); + /** + * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower + * already deposited enough collateral. + * @param asset the address of the reserve + * @param amount the amount to be borrowed + * @param interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) + **/ + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; - emit Borrow( - asset, - msg.sender, - amount, - interestRateMode, - ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ? userStableRate - : reserve.currentVariableBorrowRate, - referralCode - ); - } + uint256 amountInETH = IPriceOracleGetter(_addressesProvider.getPriceOracle()) + .getAssetPrice(asset) + .mul(amount) + .div(10**reserve.configuration.getDecimals()); //price is in ether - /** - * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). - * @dev the target user is defined by onBehalfOf. If there is no repayment on behalf of another account, - * onBehalfOf must be equal to msg.sender. - * @param asset the address of the reserve on which the user borrowed - * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything - * @param onBehalfOf the address for which msg.sender is repaying. - **/ - function repay( - address asset, - uint256 amount, - uint256 rateMode, - address onBehalfOf - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + ValidationLogic.validateBorrow( + reserve, + asset, + amount, + amountInETH, + interestRateMode, + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); - (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); + //caching the current stable borrow rate + uint256 userStableRate = reserve.currentStableBorrowRate; - ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); + reserve.updateCumulativeIndexesAndTimestamp(); - //default to max amount - uint256 paybackAmount = interestRateMode == ReserveLogic.InterestRateMode.STABLE - ? stableDebt - : variableDebt; + if ( + ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ) { + IStableDebtToken(reserve.stableDebtTokenAddress).mint( + msg.sender, + amount, + userStableRate + ); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); + } - if (amount != UINT_MAX_VALUE && amount < paybackAmount) { - paybackAmount = amount; + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, 0, amount); + + uint256 reserveIndex = reserve.index; + if (!userConfig.isBorrowing(reserveIndex)) { + userConfig.setBorrowing(reserveIndex, true); + } + + //if we reached this point, we can transfer + IAToken(aToken).transferUnderlyingTo(msg.sender, amount); + + emit Borrow( + asset, + msg.sender, + amount, + interestRateMode, + ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ? userStableRate + : reserve.currentVariableBorrowRate, + referralCode + ); } - ValidationLogic.validateRepay( - reserve, - amount, - interestRateMode, - onBehalfOf, - stableDebt, - variableDebt - ); + /** + * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). + * @dev the target user is defined by onBehalfOf. If there is no repayment on behalf of another account, + * onBehalfOf must be equal to msg.sender. + * @param asset the address of the reserve on which the user borrowed + * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything + * @param onBehalfOf the address for which msg.sender is repaying. + **/ + function repay( + address asset, + uint256 amount, + uint256 rateMode, + address onBehalfOf + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - reserve.updateCumulativeIndexesAndTimestamp(); + (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt( + onBehalfOf, + reserve + ); - //burns an equivalent amount of debt tokens - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { - IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); - } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); + + //default to max amount + uint256 paybackAmount = interestRateMode == ReserveLogic.InterestRateMode.STABLE + ? stableDebt + : variableDebt; + + if (amount != UINT_MAX_VALUE && amount < paybackAmount) { + paybackAmount = amount; + } + + ValidationLogic.validateRepay( + reserve, + amount, + interestRateMode, + onBehalfOf, + stableDebt, + variableDebt + ); + + reserve.updateCumulativeIndexesAndTimestamp(); + + //burns an equivalent amount of debt tokens + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { + IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); + } + + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, paybackAmount, 0); + + if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { + _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); + } + + IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); + + emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); } - address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(asset, aToken, paybackAmount, 0); + /** + * @dev borrowers can user this function to swap between stable and variable borrow rate modes. + * @param asset the address of the reserve on which the user borrowed + * @param rateMode the rate mode that the user wants to swap + **/ + function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { - _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); + (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt( + msg.sender, + reserve + ); + + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); + + ValidationLogic.validateSwapRateMode( + reserve, + _usersConfig[msg.sender], + stableDebt, + variableDebt, + interestRateMode + ); + + reserve.updateCumulativeIndexesAndTimestamp(); + + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { + //burn stable rate tokens, mint variable rate tokens + IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); + } else { + //do the opposite + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt); + IStableDebtToken(reserve.stableDebtTokenAddress).mint( + msg.sender, + variableDebt, + reserve.currentStableBorrowRate + ); + } + + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); + + emit Swap( + asset, + msg.sender, + //solium-disable-next-line + block.timestamp + ); } - IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); + /** + * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. + * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair + * rate. Anyone can call this function. + * @param asset the address of the reserve + * @param user the address of the user to be rebalanced + **/ + function rebalanceStableBorrowRate(address asset, address user) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); - } + IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); - /** - * @dev borrowers can user this function to swap between stable and variable borrow rate modes. - * @param asset the address of the reserve on which the user borrowed - * @param rateMode the rate mode that the user wants to swap - **/ - function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); - (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); + // user must be borrowing on asset at a stable rate + require(stableBorrowBalance > 0, NOT_ENOUGH_STABLE_BORROW_BALANCE); - ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); + uint256 rebalanceDownRateThreshold = reserve.currentStableBorrowRate.rayMul( + WadRayMath.ray().add(REBALANCE_DOWN_RATE_DELTA) + ); - ValidationLogic.validateSwapRateMode( - reserve, - _usersConfig[msg.sender], - stableDebt, - variableDebt, - interestRateMode - ); + //1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced, + //as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it) + //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low. + //In this case, the user is paying an interest that is too high, and needs to be rescaled down. - reserve.updateCumulativeIndexesAndTimestamp(); + uint256 userStableRate = stableDebtToken.getUserStableRate(user); - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { - //burn stable rate tokens, mint variable rate tokens - IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); - } else { - //do the opposite - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt); - IStableDebtToken(reserve.stableDebtTokenAddress).mint( - msg.sender, - variableDebt, - reserve.currentStableBorrowRate - ); + require( + userStableRate < reserve.currentLiquidityRate || + userStableRate > rebalanceDownRateThreshold, + INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET + ); + + //burn old debt tokens, mint new ones + + reserve.updateCumulativeIndexesAndTimestamp(); + + stableDebtToken.burn(user, stableBorrowBalance); + stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); + + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); + + emit RebalanceStableBorrowRate(asset, user); + + return; } - reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); + /** + * @dev allows depositors to enable or disable a specific deposit as collateral. + * @param asset the address of the reserve + * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. + **/ + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external + override + nonReentrant + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - emit Swap( - asset, - msg.sender, - //solium-disable-next-line - block.timestamp - ); - } + ValidationLogic.validateSetUseReserveAsCollateral( + reserve, + asset, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); - /** - * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. - * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair - * rate. Anyone can call this function. - * @param asset the address of the reserve - * @param user the address of the user to be rebalanced - **/ - function rebalanceStableBorrowRate(address asset, address user) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, useAsCollateral); - IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); - - uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); - - // user must be borrowing on asset at a stable rate - require(stableBorrowBalance > 0, 'User does not have any stable rate loan for this reserve'); - - uint256 rebalanceDownRateThreshold = reserve.currentStableBorrowRate.rayMul( - WadRayMath.ray().add(REBALANCE_DOWN_RATE_DELTA) - ); - - //1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced, - //as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it) - //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low. - //In this case, the user is paying an interest that is too high, and needs to be rescaled down. - - uint256 userStableRate = stableDebtToken.getUserStableRate(user); - - require( - userStableRate < reserve.currentLiquidityRate || userStableRate > rebalanceDownRateThreshold, - 'Interest rate rebalance conditions were not met' - ); - - //burn old debt tokens, mint new ones - - reserve.updateCumulativeIndexesAndTimestamp(); - - stableDebtToken.burn(user, stableBorrowBalance); - stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); - - reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - - emit RebalanceStableBorrowRate(asset, user); - - return; - } - - /** - * @dev allows depositors to enable or disable a specific deposit as collateral. - * @param asset the address of the reserve - * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. - **/ - function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) - external - override - nonReentrant - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - ValidationLogic.validateSetUseReserveAsCollateral( - reserve, - asset, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); - - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, useAsCollateral); - - if (useAsCollateral) { - emit ReserveUsedAsCollateralEnabled(asset, msg.sender); - } else { - emit ReserveUsedAsCollateralDisabled(asset, msg.sender); + if (useAsCollateral) { + emit ReserveUsedAsCollateralEnabled(asset, msg.sender); + } else { + emit ReserveUsedAsCollateralDisabled(asset, msg.sender); + } } - } - /** - * @dev users can invoke this function to liquidate an undercollateralized position. - * @param asset the address of the collateral to liquidated - * @param asset the address of the principal reserve - * @param user the address of the borrower - * @param purchaseAmount the amount of principal that the liquidator wants to repay - * @param receiveAToken true if the liquidators wants to receive the aTokens, false if - * he wants to receive the underlying asset directly - **/ - function liquidationCall( - address collateral, - address asset, - address user, - uint256 purchaseAmount, - bool receiveAToken - ) external override nonReentrant { - address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); + /** + * @dev users can invoke this function to liquidate an undercollateralized position. + * @param asset the address of the collateral to liquidated + * @param asset the address of the principal reserve + * @param user the address of the borrower + * @param purchaseAmount the amount of principal that the liquidator wants to repay + * @param receiveAToken true if the liquidators wants to receive the aTokens, false if + * he wants to receive the underlying asset directly + **/ + function liquidationCall( + address collateral, + address asset, + address user, + uint256 purchaseAmount, + bool receiveAToken + ) external override nonReentrant { + address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); - //solium-disable-next-line - (bool success, bytes memory result) = liquidationManager.delegatecall( - abi.encodeWithSignature( - 'liquidationCall(address,address,address,uint256,bool)', - collateral, - asset, - user, - purchaseAmount, - receiveAToken - ) - ); - require(success, 'Liquidation call failed'); + //solium-disable-next-line + (bool success, bytes memory result) = liquidationManager.delegatecall( + abi.encodeWithSignature( + 'liquidationCall(address,address,address,uint256,bool)', + collateral, + asset, + user, + purchaseAmount, + receiveAToken + ) + ); + require(success, LIQUIDATION_CALL_FAILED); - (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); + (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); - if (returnCode != 0) { - //error found - revert(string(abi.encodePacked(returnMessage))); + if (returnCode != 0) { + //error found + revert(string(abi.encodePacked(returnMessage))); + } } - } - /** - * @dev allows smartcontracts to access the liquidity of the pool within one transaction, - * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts - * that must be kept into consideration. For further details please visit https://developers.aave.com - * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. - * @param asset the address of the principal reserve - * @param amount the amount requested for this flashloan - **/ - function flashLoan( - address receiverAddress, - address asset, - uint256 amount, - bytes calldata params - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + /** + * @dev allows smartcontracts to access the liquidity of the pool within one transaction, + * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts + * that must be kept into consideration. For further details please visit https://developers.aave.com + * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. + * @param asset the address of the principal reserve + * @param amount the amount requested for this flashloan + **/ + function flashLoan( + address receiverAddress, + address asset, + uint256 amount, + bytes calldata params + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - address aTokenAddress = reserve.aTokenAddress; + address aTokenAddress = reserve.aTokenAddress; - //check that the reserve has enough available liquidity - uint256 availableLiquidityBefore = IERC20(asset).balanceOf(aTokenAddress); + //check that the reserve has enough available liquidity + uint256 availableLiquidityBefore = IERC20(asset).balanceOf(aTokenAddress); - //calculate amount fee - uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); + //calculate amount fee + uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); - require( - availableLiquidityBefore >= amount, - 'There is not enough liquidity available to borrow' - ); - require(amountFee > 0, 'The requested amount is too small for a FlashLoan.'); + require(availableLiquidityBefore >= amount, NOT_ENOUGH_LIQUIDITY_TO_BORROW); + require(amountFee > 0, REQUESTED_AMOUNT_TO_SMALL); - //get the FlashLoanReceiver instance - IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); + //get the FlashLoanReceiver instance + IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); - //transfer funds to the receiver - IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); + //transfer funds to the receiver + IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); - //execute action of the receiver - receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); + //execute action of the receiver + receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); - //check that the actual balance of the core contract includes the returned amount - uint256 availableLiquidityAfter = IERC20(asset).balanceOf(aTokenAddress); + //check that the actual balance of the core contract includes the returned amount + uint256 availableLiquidityAfter = IERC20(asset).balanceOf(aTokenAddress); - require( - availableLiquidityAfter == availableLiquidityBefore.add(amountFee), - 'The actual balance of the protocol is inconsistent' - ); + require( + availableLiquidityAfter == availableLiquidityBefore.add(amountFee), + INCONSISTENT_PROTOCOL_ACTUAL_BALANCE + ); - //compounding the cumulated interest - reserve.updateCumulativeIndexesAndTimestamp(); + //compounding the cumulated interest + reserve.updateCumulativeIndexesAndTimestamp(); - uint256 totalLiquidityBefore = availableLiquidityBefore - .add(IERC20(reserve.variableDebtTokenAddress).totalSupply()) - .add(IERC20(reserve.stableDebtTokenAddress).totalSupply()); + uint256 totalLiquidityBefore = availableLiquidityBefore + .add(IERC20(reserve.variableDebtTokenAddress).totalSupply()) + .add(IERC20(reserve.stableDebtTokenAddress).totalSupply()); - //compounding the received fee into the reserve - reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); + //compounding the received fee into the reserve + reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); - //refresh interest rates - reserve.updateInterestRates(asset, aTokenAddress, amountFee, 0); + //refresh interest rates + reserve.updateInterestRates(asset, aTokenAddress, amountFee, 0); - //solium-disable-next-line - emit FlashLoan(receiverAddress, asset, amount, amountFee); - } - - /** - * @dev accessory functions to fetch data from the core contract - **/ - - function getReserveConfigurationData(address asset) - external - override - view - returns ( - uint256 decimals, - uint256 ltv, - uint256 liquidationThreshold, - uint256 liquidationBonus, - address interestRateStrategyAddress, - bool usageAsCollateralEnabled, - bool borrowingEnabled, - bool stableBorrowRateEnabled, - bool isActive, - bool isFreezed - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - return ( - reserve.configuration.getDecimals(), - reserve.configuration.getLtv(), - reserve.configuration.getLiquidationThreshold(), - reserve.configuration.getLiquidationBonus(), - reserve.interestRateStrategyAddress, - reserve.configuration.getLtv() != 0, - reserve.configuration.getBorrowingEnabled(), - reserve.configuration.getStableRateBorrowingEnabled(), - reserve.configuration.getActive(), - reserve.configuration.getFrozen() - ); - } - - function getReserveTokensAddresses(address asset) - external - override - view - returns ( - address aTokenAddress, - address stableDebtTokenAddress, - address variableDebtTokenAddress - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - return ( - reserve.aTokenAddress, - reserve.stableDebtTokenAddress, - reserve.variableDebtTokenAddress - ); - } - - function getReserveData(address asset) - external - override - view - returns ( - uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, - uint256 liquidityRate, - uint256 variableBorrowRate, - uint256 stableBorrowRate, - uint256 averageStableBorrowRate, - uint256 liquidityIndex, - uint256 variableBorrowIndex, - uint40 lastUpdateTimestamp - ) - { - ReserveLogic.ReserveData memory reserve = _reserves[asset]; - return ( - IERC20(asset).balanceOf(reserve.aTokenAddress), - IERC20(reserve.stableDebtTokenAddress).totalSupply(), - IERC20(reserve.variableDebtTokenAddress).totalSupply(), - reserve.currentLiquidityRate, - reserve.currentVariableBorrowRate, - reserve.currentStableBorrowRate, - IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), - reserve.lastLiquidityIndex, - reserve.lastVariableBorrowIndex, - reserve.lastUpdateTimestamp - ); - } - - function getUserAccountData(address user) - external - override - view - returns ( - uint256 totalCollateralETH, - uint256 totalBorrowsETH, - uint256 availableBorrowsETH, - uint256 currentLiquidationThreshold, - uint256 ltv, - uint256 healthFactor - ) - { - ( - totalCollateralETH, - totalBorrowsETH, - ltv, - currentLiquidationThreshold, - healthFactor - ) = GenericLogic.calculateUserAccountData( - user, - _reserves, - _usersConfig[user], - _reservesList, - _addressesProvider.getPriceOracle() - ); - - availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( - totalCollateralETH, - totalBorrowsETH, - ltv - ); - } - - function getUserReserveData(address asset, address user) - external - override - view - returns ( - uint256 currentATokenBalance, - uint256 currentStableDebt, - uint256 currentVariableDebt, - uint256 principalStableDebt, - uint256 principalVariableDebt, - uint256 stableBorrowRate, - uint256 liquidityRate, - uint256 variableBorrowIndex, - uint40 stableRateLastUpdated, - bool usageAsCollateralEnabled - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); - (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); - (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); - liquidityRate = reserve.currentLiquidityRate; - stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); - stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( - user - ); - usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); - variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(user); - } - - function getReserves() external override view returns (address[] memory) { - return _reservesList; - } - - receive() external payable { - revert(); - } - - /** - * @dev initializes a reserve - * @param asset the address of the reserve - * @param aTokenAddress the address of the overlying aToken contract - * @param interestRateStrategyAddress the address of the interest rate strategy contract - **/ - function initReserve( - address asset, - address aTokenAddress, - address stableDebtAddress, - address variableDebtAddress, - address interestRateStrategyAddress - ) external override onlyLendingPoolConfigurator { - _reserves[asset].init( - aTokenAddress, - stableDebtAddress, - variableDebtAddress, - interestRateStrategyAddress - ); - _addReserveToList(asset); - } - - /** - * @dev updates the address of the interest rate strategy contract - * @param asset the address of the reserve - * @param rateStrategyAddress the address of the interest rate strategy contract - **/ - - function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) - external - override - onlyLendingPoolConfigurator - { - _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; - } - - function setConfiguration(address asset, uint256 configuration) - external - override - onlyLendingPoolConfigurator - { - _reserves[asset].configuration.data = configuration; - } - - function getConfiguration(address asset) - external - override - view - returns (ReserveConfiguration.Map memory) - { - return _reserves[asset].configuration; - } - - /** - * @notice internal functions - **/ - - /** - * @dev adds a reserve to the array of the _reserves address - **/ - function _addReserveToList(address asset) internal { - bool reserveAlreadyAdded = false; - for (uint256 i = 0; i < _reservesList.length; i++) - if (_reservesList[i] == asset) { - reserveAlreadyAdded = true; - } - if (!reserveAlreadyAdded) { - _reserves[asset].index = uint8(_reservesList.length); - _reservesList.push(asset); + //solium-disable-next-line + emit FlashLoan(receiverAddress, asset, amount, amountFee); } - } - /** - * @dev returns the normalized income per unit of asset - * @param asset the address of the reserve - * @return the reserve normalized income - */ - function getReserveNormalizedIncome(address asset) external override view returns (uint256) { - return _reserves[asset].getNormalizedIncome(); - } + /** + * @dev accessory functions to fetch data from the core contract + **/ - /** - * @dev returns the normalized variable debt per unit of asset - * @param asset the address of the reserve - * @return the reserve normalized debt - */ - function getReserveNormalizedVariableDebt(address asset) - external - override - view - returns (uint256) - { - return _reserves[asset].getNormalizedDebt(); - } + function getReserveConfigurationData(address asset) + external + override + view + returns ( + uint256 decimals, + uint256 ltv, + uint256 liquidationThreshold, + uint256 liquidationBonus, + address interestRateStrategyAddress, + bool usageAsCollateralEnabled, + bool borrowingEnabled, + bool stableBorrowRateEnabled, + bool isActive, + bool isFreezed + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - /** - * @dev validate if a balance decrease for an asset is allowed - * @param asset the address of the reserve - * @param user the user related to the balance decrease - * @param amount the amount being transferred/redeemed - * @return true if the balance decrease can be allowed, false otherwise - */ - function balanceDecreaseAllowed( - address asset, - address user, - uint256 amount - ) external override view returns (bool) { - return - GenericLogic.balanceDecreaseAllowed( - asset, - user, - amount, - _reserves, - _usersConfig[user], - _reservesList, - _addressesProvider.getPriceOracle() - ); - } + return ( + reserve.configuration.getDecimals(), + reserve.configuration.getLtv(), + reserve.configuration.getLiquidationThreshold(), + reserve.configuration.getLiquidationBonus(), + reserve.interestRateStrategyAddress, + reserve.configuration.getLtv() != 0, + reserve.configuration.getBorrowingEnabled(), + reserve.configuration.getStableRateBorrowingEnabled(), + reserve.configuration.getActive(), + reserve.configuration.getFrozen() + ); + } - /** - * @dev returns the list of the initialized reserves - **/ - function getReservesList() external view returns (address[] memory) { - return _reservesList; - } + function getReserveTokensAddresses(address asset) + external + override + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - /** - * @dev returns the addresses provider - **/ - function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return _addressesProvider; - } + return ( + reserve.aTokenAddress, + reserve.stableDebtTokenAddress, + reserve.variableDebtTokenAddress + ); + } + + function getReserveData(address asset) + external + override + view + returns ( + uint256 availableLiquidity, + uint256 totalBorrowsStable, + uint256 totalBorrowsVariable, + uint256 liquidityRate, + uint256 variableBorrowRate, + uint256 stableBorrowRate, + uint256 averageStableBorrowRate, + uint256 liquidityIndex, + uint256 variableBorrowIndex, + uint40 lastUpdateTimestamp + ) + { + ReserveLogic.ReserveData memory reserve = _reserves[asset]; + return ( + IERC20(asset).balanceOf(reserve.aTokenAddress), + IERC20(reserve.stableDebtTokenAddress).totalSupply(), + IERC20(reserve.variableDebtTokenAddress).totalSupply(), + reserve.currentLiquidityRate, + reserve.currentVariableBorrowRate, + reserve.currentStableBorrowRate, + IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), + reserve.lastLiquidityIndex, + reserve.lastVariableBorrowIndex, + reserve.lastUpdateTimestamp + ); + } + + function getUserAccountData(address user) + external + override + view + returns ( + uint256 totalCollateralETH, + uint256 totalBorrowsETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ) + { + ( + totalCollateralETH, + totalBorrowsETH, + ltv, + currentLiquidationThreshold, + healthFactor + ) = GenericLogic.calculateUserAccountData( + user, + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() + ); + + availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( + totalCollateralETH, + totalBorrowsETH, + ltv + ); + } + + function getUserReserveData(address asset, address user) + external + override + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 principalVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint256 variableBorrowIndex, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); + (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); + (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); + liquidityRate = reserve.currentLiquidityRate; + stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); + stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( + user + ); + usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); + variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex( + user + ); + } + + function getReserves() external override view returns (address[] memory) { + return _reservesList; + } + + receive() external payable { + revert(); + } + + /** + * @dev initializes a reserve + * @param asset the address of the reserve + * @param aTokenAddress the address of the overlying aToken contract + * @param interestRateStrategyAddress the address of the interest rate strategy contract + **/ + function initReserve( + address asset, + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress + ) external override onlyLendingPoolConfigurator { + _reserves[asset].init( + aTokenAddress, + stableDebtAddress, + variableDebtAddress, + interestRateStrategyAddress + ); + _addReserveToList(asset); + } + + /** + * @dev updates the address of the interest rate strategy contract + * @param asset the address of the reserve + * @param rateStrategyAddress the address of the interest rate strategy contract + **/ + + function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) + external + override + onlyLendingPoolConfigurator + { + _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; + } + + function setConfiguration(address asset, uint256 configuration) + external + override + onlyLendingPoolConfigurator + { + _reserves[asset].configuration.data = configuration; + } + + function getConfiguration(address asset) + external + override + view + returns (ReserveConfiguration.Map memory) + { + return _reserves[asset].configuration; + } + + /** + * @notice internal functions + **/ + + /** + * @dev adds a reserve to the array of the _reserves address + **/ + function _addReserveToList(address asset) internal { + bool reserveAlreadyAdded = false; + for (uint256 i = 0; i < _reservesList.length; i++) + if (_reservesList[i] == asset) { + reserveAlreadyAdded = true; + } + if (!reserveAlreadyAdded) { + _reserves[asset].index = uint8(_reservesList.length); + _reservesList.push(asset); + } + } + + /** + * @dev returns the normalized income per unit of asset + * @param asset the address of the reserve + * @return the reserve normalized income + */ + function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + return _reserves[asset].getNormalizedIncome(); + } + + /** + * @dev returns the normalized variable debt per unit of asset + * @param asset the address of the reserve + * @return the reserve normalized debt + */ + function getReserveNormalizedVariableDebt(address asset) + external + override + view + returns (uint256) + { + return _reserves[asset].getNormalizedDebt(); + } + + /** + * @dev validate if a balance decrease for an asset is allowed + * @param asset the address of the reserve + * @param user the user related to the balance decrease + * @param amount the amount being transferred/redeemed + * @return true if the balance decrease can be allowed, false otherwise + */ + function balanceDecreaseAllowed( + address asset, + address user, + uint256 amount + ) external override view returns (bool) { + return + GenericLogic.balanceDecreaseAllowed( + asset, + user, + amount, + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() + ); + } + + /** + * @dev returns the list of the initialized reserves + **/ + function getReservesList() external view returns (address[] memory) { + return _reservesList; + } + + /** + * @dev returns the addresses provider + **/ + function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { + return _addressesProvider; + } } From 0f5017cc81c7d62bca3a8c33f7c8a01c68720554 Mon Sep 17 00:00:00 2001 From: pol <> Date: Tue, 25 Aug 2020 15:51:52 +0200 Subject: [PATCH 17/33] Updated require message errors with constant string numbers to reduce gas --- .prettierrc | 1 + contracts/lendingpool/LendingPool.sol | 1407 ++++++++--------- .../lendingpool/LendingPoolConfigurator.sol | 8 +- 3 files changed, 703 insertions(+), 713 deletions(-) diff --git a/.prettierrc b/.prettierrc index ec986c7a..2caa9822 100644 --- a/.prettierrc +++ b/.prettierrc @@ -3,6 +3,7 @@ "trailingComma": "es5", "semi": true, "singleQuote": true, + "tabWidth": 2, "overrides": [ { "files": "*.sol", diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index ea384125..be4b4d18 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -6,7 +6,7 @@ import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { - VersionedInitializable + VersionedInitializable } from '../libraries/openzeppelin-upgradeability/VersionedInitializable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../tokenization/interfaces/IAToken.sol'; @@ -32,794 +32,779 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; **/ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { - using SafeMath for uint256; - using WadRayMath for uint256; - using ReserveLogic for ReserveLogic.ReserveData; - using ReserveConfiguration for ReserveConfiguration.Map; - using UserConfiguration for UserConfiguration.Map; - using SafeERC20 for IERC20; + using SafeMath for uint256; + using WadRayMath for uint256; + using ReserveLogic for ReserveLogic.ReserveData; + using ReserveConfiguration for ReserveConfiguration.Map; + using UserConfiguration for UserConfiguration.Map; + using SafeERC20 for IERC20; - //main configuration parameters - uint256 public constant REBALANCE_DOWN_RATE_DELTA = (1e27) / 5; - uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; - uint256 public constant FLASHLOAN_FEE_TOTAL = 9; + //main configuration parameters + uint256 public constant REBALANCE_DOWN_RATE_DELTA = (1e27) / 5; + uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; + uint256 public constant FLASHLOAN_FEE_TOTAL = 9; - //require error messages - string private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '1'; // 'User does not have any stable rate loan for this reserve' - string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '2'; // 'Interest rate rebalance conditions were not met' - string private constant LIQUIDATION_CALL_FAILED = '3'; // 'Liquidation call failed' - string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '4'; // 'There is not enough liquidity available to borrow' - string private constant REQUESTED_AMOUNT_TO_SMALL = '5'; // 'The requested amount is too small for a FlashLoan.' - string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '6'; // 'The actual balance of the protocol is inconsistent' + //require error messages + string private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '1'; // 'User does not have any stable rate loan for this reserve' + string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '2'; // 'Interest rate rebalance conditions were not met' + string private constant LIQUIDATION_CALL_FAILED = '3'; // 'Liquidation call failed' + string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '4'; // 'There is not enough liquidity available to borrow' + string private constant REQUESTED_AMOUNT_TO_SMALL = '5'; // 'The requested amount is too small for a FlashLoan.' + string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '6'; // 'The actual balance of the protocol is inconsistent' - ILendingPoolAddressesProvider internal _addressesProvider; + ILendingPoolAddressesProvider internal _addressesProvider; - mapping(address => ReserveLogic.ReserveData) internal _reserves; - mapping(address => UserConfiguration.Map) internal _usersConfig; + mapping(address => ReserveLogic.ReserveData) internal _reserves; + mapping(address => UserConfiguration.Map) internal _usersConfig; - address[] internal _reservesList; + address[] internal _reservesList; - /** - * @dev only lending pools configurator can use functions affected by this modifier - **/ - modifier onlyLendingPoolConfigurator { - require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); - _; + /** + * @dev only lending pools configurator can use functions affected by this modifier + **/ + modifier onlyLendingPoolConfigurator { + require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); + _; + } + + uint256 public constant UINT_MAX_VALUE = uint256(-1); + + uint256 public constant LENDINGPOOL_REVISION = 0x2; + + function getRevision() internal override pure returns (uint256) { + return LENDINGPOOL_REVISION; + } + + /** + * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the + * AddressesProvider. + * @param provider the address of the LendingPoolAddressesProvider registry + **/ + function initialize(ILendingPoolAddressesProvider provider) public initializer { + _addressesProvider = provider; + } + + /** + * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) + * is minted. + * @param asset the address of the reserve + * @param amount the amount to be deposited + * @param referralCode integrators are assigned a referral code and can potentially receive rewards. + **/ + function deposit( + address asset, + uint256 amount, + uint16 referralCode + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + ValidationLogic.validateDeposit(reserve, amount); + + address aToken = reserve.aTokenAddress; + + reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateInterestRates(asset, aToken, amount, 0); + + bool isFirstDeposit = IAToken(aToken).balanceOf(msg.sender) == 0; + if (isFirstDeposit) { + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, true); } - uint256 public constant UINT_MAX_VALUE = uint256(-1); + //minting AToken to user 1:1 with the specific exchange rate + IAToken(aToken).mint(msg.sender, amount); - uint256 public constant LENDINGPOOL_REVISION = 0x2; + //transfer to the aToken contract + IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); - function getRevision() internal override pure returns (uint256) { - return LENDINGPOOL_REVISION; + //solium-disable-next-line + emit Deposit(asset, msg.sender, amount, referralCode); + } + + /** + * @dev withdraws the _reserves of user. + * @param asset the address of the reserve + * @param amount the underlying amount to be redeemed + **/ + function withdraw(address asset, uint256 amount) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + address aToken = reserve.aTokenAddress; + + uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); + + uint256 amountToWithdraw = amount; + + //if amount is equal to uint(-1), the user wants to redeem everything + if (amount == UINT_MAX_VALUE) { + amountToWithdraw = userBalance; } - /** - * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the - * AddressesProvider. - * @param provider the address of the LendingPoolAddressesProvider registry - **/ - function initialize(ILendingPoolAddressesProvider provider) public initializer { - _addressesProvider = provider; + ValidationLogic.validateWithdraw( + asset, + aToken, + amountToWithdraw, + userBalance, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); + + reserve.updateCumulativeIndexesAndTimestamp(); + + reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); + + if (amountToWithdraw == userBalance) { + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, false); } - /** - * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) - * is minted. - * @param asset the address of the reserve - * @param amount the amount to be deposited - * @param referralCode integrators are assigned a referral code and can potentially receive rewards. - **/ - function deposit( - address asset, - uint256 amount, - uint16 referralCode - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw); - ValidationLogic.validateDeposit(reserve, amount); + //solium-disable-next-line + emit Withdraw(asset, msg.sender, amount); + } - address aToken = reserve.aTokenAddress; + /** + * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower + * already deposited enough collateral. + * @param asset the address of the reserve + * @param amount the amount to be borrowed + * @param interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) + **/ + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; - reserve.updateCumulativeIndexesAndTimestamp(); - reserve.updateInterestRates(asset, aToken, amount, 0); + uint256 amountInETH = IPriceOracleGetter(_addressesProvider.getPriceOracle()) + .getAssetPrice(asset) + .mul(amount) + .div(10**reserve.configuration.getDecimals()); //price is in ether - bool isFirstDeposit = IAToken(aToken).balanceOf(msg.sender) == 0; - if (isFirstDeposit) { - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, true); - } + ValidationLogic.validateBorrow( + reserve, + asset, + amount, + amountInETH, + interestRateMode, + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); - //minting AToken to user 1:1 with the specific exchange rate - IAToken(aToken).mint(msg.sender, amount); + //caching the current stable borrow rate + uint256 userStableRate = reserve.currentStableBorrowRate; - //transfer to the aToken contract - IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); + reserve.updateCumulativeIndexesAndTimestamp(); - //solium-disable-next-line - emit Deposit(asset, msg.sender, amount, referralCode); + if (ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE) { + IStableDebtToken(reserve.stableDebtTokenAddress).mint(msg.sender, amount, userStableRate); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); } - /** - * @dev withdraws the _reserves of user. - * @param asset the address of the reserve - * @param amount the underlying amount to be redeemed - **/ - function withdraw(address asset, uint256 amount) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, 0, amount); - address aToken = reserve.aTokenAddress; - - uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); - - uint256 amountToWithdraw = amount; - - //if amount is equal to uint(-1), the user wants to redeem everything - if (amount == UINT_MAX_VALUE) { - amountToWithdraw = userBalance; - } - - ValidationLogic.validateWithdraw( - asset, - aToken, - amountToWithdraw, - userBalance, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); - - reserve.updateCumulativeIndexesAndTimestamp(); - - reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); - - if (amountToWithdraw == userBalance) { - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, false); - } - - IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw); - - //solium-disable-next-line - emit Withdraw(asset, msg.sender, amount); + uint256 reserveIndex = reserve.index; + if (!userConfig.isBorrowing(reserveIndex)) { + userConfig.setBorrowing(reserveIndex, true); } - /** - * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower - * already deposited enough collateral. - * @param asset the address of the reserve - * @param amount the amount to be borrowed - * @param interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) - **/ - function borrow( - address asset, - uint256 amount, - uint256 interestRateMode, - uint16 referralCode - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; + //if we reached this point, we can transfer + IAToken(aToken).transferUnderlyingTo(msg.sender, amount); - uint256 amountInETH = IPriceOracleGetter(_addressesProvider.getPriceOracle()) - .getAssetPrice(asset) - .mul(amount) - .div(10**reserve.configuration.getDecimals()); //price is in ether + emit Borrow( + asset, + msg.sender, + amount, + interestRateMode, + ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ? userStableRate + : reserve.currentVariableBorrowRate, + referralCode + ); + } - ValidationLogic.validateBorrow( - reserve, - asset, - amount, - amountInETH, - interestRateMode, - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); + /** + * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). + * @dev the target user is defined by onBehalfOf. If there is no repayment on behalf of another account, + * onBehalfOf must be equal to msg.sender. + * @param asset the address of the reserve on which the user borrowed + * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything + * @param onBehalfOf the address for which msg.sender is repaying. + **/ + function repay( + address asset, + uint256 amount, + uint256 rateMode, + address onBehalfOf + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - //caching the current stable borrow rate - uint256 userStableRate = reserve.currentStableBorrowRate; + (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); - reserve.updateCumulativeIndexesAndTimestamp(); + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); - if ( - ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ) { - IStableDebtToken(reserve.stableDebtTokenAddress).mint( - msg.sender, - amount, - userStableRate - ); - } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, amount); - } + //default to max amount + uint256 paybackAmount = interestRateMode == ReserveLogic.InterestRateMode.STABLE + ? stableDebt + : variableDebt; - address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(asset, aToken, 0, amount); - - uint256 reserveIndex = reserve.index; - if (!userConfig.isBorrowing(reserveIndex)) { - userConfig.setBorrowing(reserveIndex, true); - } - - //if we reached this point, we can transfer - IAToken(aToken).transferUnderlyingTo(msg.sender, amount); - - emit Borrow( - asset, - msg.sender, - amount, - interestRateMode, - ReserveLogic.InterestRateMode(interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ? userStableRate - : reserve.currentVariableBorrowRate, - referralCode - ); + if (amount != UINT_MAX_VALUE && amount < paybackAmount) { + paybackAmount = amount; } - /** - * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). - * @dev the target user is defined by onBehalfOf. If there is no repayment on behalf of another account, - * onBehalfOf must be equal to msg.sender. - * @param asset the address of the reserve on which the user borrowed - * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything - * @param onBehalfOf the address for which msg.sender is repaying. - **/ - function repay( - address asset, - uint256 amount, - uint256 rateMode, - address onBehalfOf - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + ValidationLogic.validateRepay( + reserve, + amount, + interestRateMode, + onBehalfOf, + stableDebt, + variableDebt + ); - (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt( - onBehalfOf, - reserve - ); + reserve.updateCumulativeIndexesAndTimestamp(); - ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); - - //default to max amount - uint256 paybackAmount = interestRateMode == ReserveLogic.InterestRateMode.STABLE - ? stableDebt - : variableDebt; - - if (amount != UINT_MAX_VALUE && amount < paybackAmount) { - paybackAmount = amount; - } - - ValidationLogic.validateRepay( - reserve, - amount, - interestRateMode, - onBehalfOf, - stableDebt, - variableDebt - ); - - reserve.updateCumulativeIndexesAndTimestamp(); - - //burns an equivalent amount of debt tokens - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { - IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); - } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); - } - - address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(asset, aToken, paybackAmount, 0); - - if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { - _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); - } - - IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); - - emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); + //burns an equivalent amount of debt tokens + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { + IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } - /** - * @dev borrowers can user this function to swap between stable and variable borrow rate modes. - * @param asset the address of the reserve on which the user borrowed - * @param rateMode the rate mode that the user wants to swap - **/ - function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + address aToken = reserve.aTokenAddress; + reserve.updateInterestRates(asset, aToken, paybackAmount, 0); - (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt( - msg.sender, - reserve - ); - - ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); - - ValidationLogic.validateSwapRateMode( - reserve, - _usersConfig[msg.sender], - stableDebt, - variableDebt, - interestRateMode - ); - - reserve.updateCumulativeIndexesAndTimestamp(); - - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { - //burn stable rate tokens, mint variable rate tokens - IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); - } else { - //do the opposite - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt); - IStableDebtToken(reserve.stableDebtTokenAddress).mint( - msg.sender, - variableDebt, - reserve.currentStableBorrowRate - ); - } - - reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - - emit Swap( - asset, - msg.sender, - //solium-disable-next-line - block.timestamp - ); + if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { + _usersConfig[onBehalfOf].setBorrowing(reserve.index, false); } - /** - * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. - * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair - * rate. Anyone can call this function. - * @param asset the address of the reserve - * @param user the address of the user to be rebalanced - **/ - function rebalanceStableBorrowRate(address asset, address user) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); - IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); + emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); + } - uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); + /** + * @dev borrowers can user this function to swap between stable and variable borrow rate modes. + * @param asset the address of the reserve on which the user borrowed + * @param rateMode the rate mode that the user wants to swap + **/ + function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - // user must be borrowing on asset at a stable rate - require(stableBorrowBalance > 0, NOT_ENOUGH_STABLE_BORROW_BALANCE); + (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); - uint256 rebalanceDownRateThreshold = reserve.currentStableBorrowRate.rayMul( - WadRayMath.ray().add(REBALANCE_DOWN_RATE_DELTA) - ); + ReserveLogic.InterestRateMode interestRateMode = ReserveLogic.InterestRateMode(rateMode); - //1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced, - //as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it) - //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low. - //In this case, the user is paying an interest that is too high, and needs to be rescaled down. + ValidationLogic.validateSwapRateMode( + reserve, + _usersConfig[msg.sender], + stableDebt, + variableDebt, + interestRateMode + ); - uint256 userStableRate = stableDebtToken.getUserStableRate(user); + reserve.updateCumulativeIndexesAndTimestamp(); - require( - userStableRate < reserve.currentLiquidityRate || - userStableRate > rebalanceDownRateThreshold, - INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET - ); - - //burn old debt tokens, mint new ones - - reserve.updateCumulativeIndexesAndTimestamp(); - - stableDebtToken.burn(user, stableBorrowBalance); - stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); - - reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - - emit RebalanceStableBorrowRate(asset, user); - - return; + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { + //burn stable rate tokens, mint variable rate tokens + IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); + } else { + //do the opposite + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt); + IStableDebtToken(reserve.stableDebtTokenAddress).mint( + msg.sender, + variableDebt, + reserve.currentStableBorrowRate + ); } - /** - * @dev allows depositors to enable or disable a specific deposit as collateral. - * @param asset the address of the reserve - * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. - **/ - function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) - external - override - nonReentrant - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - ValidationLogic.validateSetUseReserveAsCollateral( - reserve, - asset, - _reserves, - _usersConfig[msg.sender], - _reservesList, - _addressesProvider.getPriceOracle() - ); + emit Swap( + asset, + msg.sender, + //solium-disable-next-line + block.timestamp + ); + } - _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, useAsCollateral); + /** + * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. + * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair + * rate. Anyone can call this function. + * @param asset the address of the reserve + * @param user the address of the user to be rebalanced + **/ + function rebalanceStableBorrowRate(address asset, address user) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - if (useAsCollateral) { - emit ReserveUsedAsCollateralEnabled(asset, msg.sender); - } else { - emit ReserveUsedAsCollateralDisabled(asset, msg.sender); - } + IStableDebtToken stableDebtToken = IStableDebtToken(reserve.stableDebtTokenAddress); + + uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); + + // user must be borrowing on asset at a stable rate + require(stableBorrowBalance > 0, NOT_ENOUGH_STABLE_BORROW_BALANCE); + + uint256 rebalanceDownRateThreshold = reserve.currentStableBorrowRate.rayMul( + WadRayMath.ray().add(REBALANCE_DOWN_RATE_DELTA) + ); + + //1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced, + //as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it) + //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low. + //In this case, the user is paying an interest that is too high, and needs to be rescaled down. + + uint256 userStableRate = stableDebtToken.getUserStableRate(user); + + require( + userStableRate < reserve.currentLiquidityRate || userStableRate > rebalanceDownRateThreshold, + INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET + ); + + //burn old debt tokens, mint new ones + + reserve.updateCumulativeIndexesAndTimestamp(); + + stableDebtToken.burn(user, stableBorrowBalance); + stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); + + reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); + + emit RebalanceStableBorrowRate(asset, user); + + return; + } + + /** + * @dev allows depositors to enable or disable a specific deposit as collateral. + * @param asset the address of the reserve + * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. + **/ + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external + override + nonReentrant + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + ValidationLogic.validateSetUseReserveAsCollateral( + reserve, + asset, + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() + ); + + _usersConfig[msg.sender].setUsingAsCollateral(reserve.index, useAsCollateral); + + if (useAsCollateral) { + emit ReserveUsedAsCollateralEnabled(asset, msg.sender); + } else { + emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } + } - /** - * @dev users can invoke this function to liquidate an undercollateralized position. - * @param asset the address of the collateral to liquidated - * @param asset the address of the principal reserve - * @param user the address of the borrower - * @param purchaseAmount the amount of principal that the liquidator wants to repay - * @param receiveAToken true if the liquidators wants to receive the aTokens, false if - * he wants to receive the underlying asset directly - **/ - function liquidationCall( - address collateral, - address asset, - address user, - uint256 purchaseAmount, - bool receiveAToken - ) external override nonReentrant { - address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); + /** + * @dev users can invoke this function to liquidate an undercollateralized position. + * @param asset the address of the collateral to liquidated + * @param asset the address of the principal reserve + * @param user the address of the borrower + * @param purchaseAmount the amount of principal that the liquidator wants to repay + * @param receiveAToken true if the liquidators wants to receive the aTokens, false if + * he wants to receive the underlying asset directly + **/ + function liquidationCall( + address collateral, + address asset, + address user, + uint256 purchaseAmount, + bool receiveAToken + ) external override nonReentrant { + address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); - //solium-disable-next-line - (bool success, bytes memory result) = liquidationManager.delegatecall( - abi.encodeWithSignature( - 'liquidationCall(address,address,address,uint256,bool)', - collateral, - asset, - user, - purchaseAmount, - receiveAToken - ) - ); - require(success, LIQUIDATION_CALL_FAILED); + //solium-disable-next-line + (bool success, bytes memory result) = liquidationManager.delegatecall( + abi.encodeWithSignature( + 'liquidationCall(address,address,address,uint256,bool)', + collateral, + asset, + user, + purchaseAmount, + receiveAToken + ) + ); + require(success, LIQUIDATION_CALL_FAILED); - (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); + (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); - if (returnCode != 0) { - //error found - revert(string(abi.encodePacked(returnMessage))); - } + if (returnCode != 0) { + //error found + revert(string(abi.encodePacked(returnMessage))); } + } - /** - * @dev allows smartcontracts to access the liquidity of the pool within one transaction, - * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts - * that must be kept into consideration. For further details please visit https://developers.aave.com - * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. - * @param asset the address of the principal reserve - * @param amount the amount requested for this flashloan - **/ - function flashLoan( - address receiverAddress, - address asset, - uint256 amount, - bytes calldata params - ) external override nonReentrant { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + /** + * @dev allows smartcontracts to access the liquidity of the pool within one transaction, + * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts + * that must be kept into consideration. For further details please visit https://developers.aave.com + * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. + * @param asset the address of the principal reserve + * @param amount the amount requested for this flashloan + **/ + function flashLoan( + address receiverAddress, + address asset, + uint256 amount, + bytes calldata params + ) external override nonReentrant { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; - address aTokenAddress = reserve.aTokenAddress; + address aTokenAddress = reserve.aTokenAddress; - //check that the reserve has enough available liquidity - uint256 availableLiquidityBefore = IERC20(asset).balanceOf(aTokenAddress); + //check that the reserve has enough available liquidity + uint256 availableLiquidityBefore = IERC20(asset).balanceOf(aTokenAddress); - //calculate amount fee - uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); + //calculate amount fee + uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); - require(availableLiquidityBefore >= amount, NOT_ENOUGH_LIQUIDITY_TO_BORROW); - require(amountFee > 0, REQUESTED_AMOUNT_TO_SMALL); + require(availableLiquidityBefore >= amount, NOT_ENOUGH_LIQUIDITY_TO_BORROW); + require(amountFee > 0, REQUESTED_AMOUNT_TO_SMALL); - //get the FlashLoanReceiver instance - IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); + //get the FlashLoanReceiver instance + IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); - //transfer funds to the receiver - IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); + //transfer funds to the receiver + IAToken(aTokenAddress).transferUnderlyingTo(receiverAddress, amount); - //execute action of the receiver - receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); + //execute action of the receiver + receiver.executeOperation(asset, aTokenAddress, amount, amountFee, params); - //check that the actual balance of the core contract includes the returned amount - uint256 availableLiquidityAfter = IERC20(asset).balanceOf(aTokenAddress); + //check that the actual balance of the core contract includes the returned amount + uint256 availableLiquidityAfter = IERC20(asset).balanceOf(aTokenAddress); - require( - availableLiquidityAfter == availableLiquidityBefore.add(amountFee), - INCONSISTENT_PROTOCOL_ACTUAL_BALANCE - ); + require( + availableLiquidityAfter == availableLiquidityBefore.add(amountFee), + INCONSISTENT_PROTOCOL_ACTUAL_BALANCE + ); - //compounding the cumulated interest - reserve.updateCumulativeIndexesAndTimestamp(); + //compounding the cumulated interest + reserve.updateCumulativeIndexesAndTimestamp(); - uint256 totalLiquidityBefore = availableLiquidityBefore - .add(IERC20(reserve.variableDebtTokenAddress).totalSupply()) - .add(IERC20(reserve.stableDebtTokenAddress).totalSupply()); + uint256 totalLiquidityBefore = availableLiquidityBefore + .add(IERC20(reserve.variableDebtTokenAddress).totalSupply()) + .add(IERC20(reserve.stableDebtTokenAddress).totalSupply()); - //compounding the received fee into the reserve - reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); + //compounding the received fee into the reserve + reserve.cumulateToLiquidityIndex(totalLiquidityBefore, amountFee); - //refresh interest rates - reserve.updateInterestRates(asset, aTokenAddress, amountFee, 0); + //refresh interest rates + reserve.updateInterestRates(asset, aTokenAddress, amountFee, 0); - //solium-disable-next-line - emit FlashLoan(receiverAddress, asset, amount, amountFee); + //solium-disable-next-line + emit FlashLoan(receiverAddress, asset, amount, amountFee); + } + + /** + * @dev accessory functions to fetch data from the core contract + **/ + + function getReserveConfigurationData(address asset) + external + override + view + returns ( + uint256 decimals, + uint256 ltv, + uint256 liquidationThreshold, + uint256 liquidationBonus, + address interestRateStrategyAddress, + bool usageAsCollateralEnabled, + bool borrowingEnabled, + bool stableBorrowRateEnabled, + bool isActive, + bool isFreezed + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + return ( + reserve.configuration.getDecimals(), + reserve.configuration.getLtv(), + reserve.configuration.getLiquidationThreshold(), + reserve.configuration.getLiquidationBonus(), + reserve.interestRateStrategyAddress, + reserve.configuration.getLtv() != 0, + reserve.configuration.getBorrowingEnabled(), + reserve.configuration.getStableRateBorrowingEnabled(), + reserve.configuration.getActive(), + reserve.configuration.getFrozen() + ); + } + + function getReserveTokensAddresses(address asset) + external + override + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + return ( + reserve.aTokenAddress, + reserve.stableDebtTokenAddress, + reserve.variableDebtTokenAddress + ); + } + + function getReserveData(address asset) + external + override + view + returns ( + uint256 availableLiquidity, + uint256 totalBorrowsStable, + uint256 totalBorrowsVariable, + uint256 liquidityRate, + uint256 variableBorrowRate, + uint256 stableBorrowRate, + uint256 averageStableBorrowRate, + uint256 liquidityIndex, + uint256 variableBorrowIndex, + uint40 lastUpdateTimestamp + ) + { + ReserveLogic.ReserveData memory reserve = _reserves[asset]; + return ( + IERC20(asset).balanceOf(reserve.aTokenAddress), + IERC20(reserve.stableDebtTokenAddress).totalSupply(), + IERC20(reserve.variableDebtTokenAddress).totalSupply(), + reserve.currentLiquidityRate, + reserve.currentVariableBorrowRate, + reserve.currentStableBorrowRate, + IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), + reserve.lastLiquidityIndex, + reserve.lastVariableBorrowIndex, + reserve.lastUpdateTimestamp + ); + } + + function getUserAccountData(address user) + external + override + view + returns ( + uint256 totalCollateralETH, + uint256 totalBorrowsETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ) + { + ( + totalCollateralETH, + totalBorrowsETH, + ltv, + currentLiquidationThreshold, + healthFactor + ) = GenericLogic.calculateUserAccountData( + user, + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() + ); + + availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( + totalCollateralETH, + totalBorrowsETH, + ltv + ); + } + + function getUserReserveData(address asset, address user) + external + override + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 principalVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint256 variableBorrowIndex, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ) + { + ReserveLogic.ReserveData storage reserve = _reserves[asset]; + + currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); + (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); + (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); + liquidityRate = reserve.currentLiquidityRate; + stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); + stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( + user + ); + usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); + variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(user); + } + + function getReserves() external override view returns (address[] memory) { + return _reservesList; + } + + receive() external payable { + revert(); + } + + /** + * @dev initializes a reserve + * @param asset the address of the reserve + * @param aTokenAddress the address of the overlying aToken contract + * @param interestRateStrategyAddress the address of the interest rate strategy contract + **/ + function initReserve( + address asset, + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress + ) external override onlyLendingPoolConfigurator { + _reserves[asset].init( + aTokenAddress, + stableDebtAddress, + variableDebtAddress, + interestRateStrategyAddress + ); + _addReserveToList(asset); + } + + /** + * @dev updates the address of the interest rate strategy contract + * @param asset the address of the reserve + * @param rateStrategyAddress the address of the interest rate strategy contract + **/ + + function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) + external + override + onlyLendingPoolConfigurator + { + _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; + } + + function setConfiguration(address asset, uint256 configuration) + external + override + onlyLendingPoolConfigurator + { + _reserves[asset].configuration.data = configuration; + } + + function getConfiguration(address asset) + external + override + view + returns (ReserveConfiguration.Map memory) + { + return _reserves[asset].configuration; + } + + /** + * @notice internal functions + **/ + + /** + * @dev adds a reserve to the array of the _reserves address + **/ + function _addReserveToList(address asset) internal { + bool reserveAlreadyAdded = false; + for (uint256 i = 0; i < _reservesList.length; i++) + if (_reservesList[i] == asset) { + reserveAlreadyAdded = true; + } + if (!reserveAlreadyAdded) { + _reserves[asset].index = uint8(_reservesList.length); + _reservesList.push(asset); } + } - /** - * @dev accessory functions to fetch data from the core contract - **/ + /** + * @dev returns the normalized income per unit of asset + * @param asset the address of the reserve + * @return the reserve normalized income + */ + function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + return _reserves[asset].getNormalizedIncome(); + } - function getReserveConfigurationData(address asset) - external - override - view - returns ( - uint256 decimals, - uint256 ltv, - uint256 liquidationThreshold, - uint256 liquidationBonus, - address interestRateStrategyAddress, - bool usageAsCollateralEnabled, - bool borrowingEnabled, - bool stableBorrowRateEnabled, - bool isActive, - bool isFreezed - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + /** + * @dev returns the normalized variable debt per unit of asset + * @param asset the address of the reserve + * @return the reserve normalized debt + */ + function getReserveNormalizedVariableDebt(address asset) + external + override + view + returns (uint256) + { + return _reserves[asset].getNormalizedDebt(); + } - return ( - reserve.configuration.getDecimals(), - reserve.configuration.getLtv(), - reserve.configuration.getLiquidationThreshold(), - reserve.configuration.getLiquidationBonus(), - reserve.interestRateStrategyAddress, - reserve.configuration.getLtv() != 0, - reserve.configuration.getBorrowingEnabled(), - reserve.configuration.getStableRateBorrowingEnabled(), - reserve.configuration.getActive(), - reserve.configuration.getFrozen() - ); - } + /** + * @dev validate if a balance decrease for an asset is allowed + * @param asset the address of the reserve + * @param user the user related to the balance decrease + * @param amount the amount being transferred/redeemed + * @return true if the balance decrease can be allowed, false otherwise + */ + function balanceDecreaseAllowed( + address asset, + address user, + uint256 amount + ) external override view returns (bool) { + return + GenericLogic.balanceDecreaseAllowed( + asset, + user, + amount, + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() + ); + } - function getReserveTokensAddresses(address asset) - external - override - view - returns ( - address aTokenAddress, - address stableDebtTokenAddress, - address variableDebtTokenAddress - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; + /** + * @dev returns the list of the initialized reserves + **/ + function getReservesList() external view returns (address[] memory) { + return _reservesList; + } - return ( - reserve.aTokenAddress, - reserve.stableDebtTokenAddress, - reserve.variableDebtTokenAddress - ); - } - - function getReserveData(address asset) - external - override - view - returns ( - uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, - uint256 liquidityRate, - uint256 variableBorrowRate, - uint256 stableBorrowRate, - uint256 averageStableBorrowRate, - uint256 liquidityIndex, - uint256 variableBorrowIndex, - uint40 lastUpdateTimestamp - ) - { - ReserveLogic.ReserveData memory reserve = _reserves[asset]; - return ( - IERC20(asset).balanceOf(reserve.aTokenAddress), - IERC20(reserve.stableDebtTokenAddress).totalSupply(), - IERC20(reserve.variableDebtTokenAddress).totalSupply(), - reserve.currentLiquidityRate, - reserve.currentVariableBorrowRate, - reserve.currentStableBorrowRate, - IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), - reserve.lastLiquidityIndex, - reserve.lastVariableBorrowIndex, - reserve.lastUpdateTimestamp - ); - } - - function getUserAccountData(address user) - external - override - view - returns ( - uint256 totalCollateralETH, - uint256 totalBorrowsETH, - uint256 availableBorrowsETH, - uint256 currentLiquidationThreshold, - uint256 ltv, - uint256 healthFactor - ) - { - ( - totalCollateralETH, - totalBorrowsETH, - ltv, - currentLiquidationThreshold, - healthFactor - ) = GenericLogic.calculateUserAccountData( - user, - _reserves, - _usersConfig[user], - _reservesList, - _addressesProvider.getPriceOracle() - ); - - availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( - totalCollateralETH, - totalBorrowsETH, - ltv - ); - } - - function getUserReserveData(address asset, address user) - external - override - view - returns ( - uint256 currentATokenBalance, - uint256 currentStableDebt, - uint256 currentVariableDebt, - uint256 principalStableDebt, - uint256 principalVariableDebt, - uint256 stableBorrowRate, - uint256 liquidityRate, - uint256 variableBorrowIndex, - uint40 stableRateLastUpdated, - bool usageAsCollateralEnabled - ) - { - ReserveLogic.ReserveData storage reserve = _reserves[asset]; - - currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); - (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); - (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); - liquidityRate = reserve.currentLiquidityRate; - stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); - stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( - user - ); - usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); - variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex( - user - ); - } - - function getReserves() external override view returns (address[] memory) { - return _reservesList; - } - - receive() external payable { - revert(); - } - - /** - * @dev initializes a reserve - * @param asset the address of the reserve - * @param aTokenAddress the address of the overlying aToken contract - * @param interestRateStrategyAddress the address of the interest rate strategy contract - **/ - function initReserve( - address asset, - address aTokenAddress, - address stableDebtAddress, - address variableDebtAddress, - address interestRateStrategyAddress - ) external override onlyLendingPoolConfigurator { - _reserves[asset].init( - aTokenAddress, - stableDebtAddress, - variableDebtAddress, - interestRateStrategyAddress - ); - _addReserveToList(asset); - } - - /** - * @dev updates the address of the interest rate strategy contract - * @param asset the address of the reserve - * @param rateStrategyAddress the address of the interest rate strategy contract - **/ - - function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) - external - override - onlyLendingPoolConfigurator - { - _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; - } - - function setConfiguration(address asset, uint256 configuration) - external - override - onlyLendingPoolConfigurator - { - _reserves[asset].configuration.data = configuration; - } - - function getConfiguration(address asset) - external - override - view - returns (ReserveConfiguration.Map memory) - { - return _reserves[asset].configuration; - } - - /** - * @notice internal functions - **/ - - /** - * @dev adds a reserve to the array of the _reserves address - **/ - function _addReserveToList(address asset) internal { - bool reserveAlreadyAdded = false; - for (uint256 i = 0; i < _reservesList.length; i++) - if (_reservesList[i] == asset) { - reserveAlreadyAdded = true; - } - if (!reserveAlreadyAdded) { - _reserves[asset].index = uint8(_reservesList.length); - _reservesList.push(asset); - } - } - - /** - * @dev returns the normalized income per unit of asset - * @param asset the address of the reserve - * @return the reserve normalized income - */ - function getReserveNormalizedIncome(address asset) external override view returns (uint256) { - return _reserves[asset].getNormalizedIncome(); - } - - /** - * @dev returns the normalized variable debt per unit of asset - * @param asset the address of the reserve - * @return the reserve normalized debt - */ - function getReserveNormalizedVariableDebt(address asset) - external - override - view - returns (uint256) - { - return _reserves[asset].getNormalizedDebt(); - } - - /** - * @dev validate if a balance decrease for an asset is allowed - * @param asset the address of the reserve - * @param user the user related to the balance decrease - * @param amount the amount being transferred/redeemed - * @return true if the balance decrease can be allowed, false otherwise - */ - function balanceDecreaseAllowed( - address asset, - address user, - uint256 amount - ) external override view returns (bool) { - return - GenericLogic.balanceDecreaseAllowed( - asset, - user, - amount, - _reserves, - _usersConfig[user], - _reservesList, - _addressesProvider.getPriceOracle() - ); - } - - /** - * @dev returns the list of the initialized reserves - **/ - function getReservesList() external view returns (address[] memory) { - return _reservesList; - } - - /** - * @dev returns the addresses provider - **/ - function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return _addressesProvider; - } + /** + * @dev returns the addresses provider + **/ + function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { + return _addressesProvider; + } } diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 5a2d732b..8ed719c7 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -25,6 +25,10 @@ contract LendingPoolConfigurator is VersionedInitializable { using SafeMath for uint256; using ReserveConfiguration for ReserveConfiguration.Map; + //require error messages + string private constant CALLER_NOT_LENDING_POOL_MANAGER = '1'; // 'The caller must be a lending pool manager' + string private constant RESERVE_LIQUIDITY_NOT_0 = '2'; // 'The liquidity of the reserve needs to be 0' + /** * @dev emitted when a reserve is initialized. * @param asset the address of the reserve @@ -178,7 +182,7 @@ contract LendingPoolConfigurator is VersionedInitializable { modifier onlyLendingPoolManager { require( addressesProvider.getLendingPoolManager() == msg.sender, - 'The caller must be a lending pool manager' + CALLER_NOT_LENDING_POOL_MANAGER ); _; } @@ -425,7 +429,7 @@ contract LendingPoolConfigurator is VersionedInitializable { ) = pool.getReserveData(asset); require( availableLiquidity == 0 && totalBorrowsStable == 0 && totalBorrowsVariable == 0, - 'The liquidity of the reserve needs to be 0' + RESERVE_LIQUIDITY_NOT_0 ); ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); From 5841e51439fd933dfb393fe2ca9ae85f2e98c711 Mon Sep 17 00:00:00 2001 From: pol <> Date: Tue, 25 Aug 2020 15:57:54 +0200 Subject: [PATCH 18/33] Updated require message errors with constant string numbers to reduce gas --- .../configuration/LendingPoolAddressesProviderRegistry.sol | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol index 07d416f8..274ff33f 100644 --- a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol +++ b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol @@ -16,6 +16,9 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP mapping(address => uint256) addressesProviders; address[] addressesProvidersList; + //require error messages + string private constant PROVIDER_NOT_REGISTERED = '1'; // 'Provider is not registered' + /** * @dev returns if an addressesProvider is registered or not * @param provider the addresses provider @@ -63,7 +66,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, 'Provider is not registered'); + require(addressesProviders[provider] > 0, PROVIDER_NOT_REGISTERED); addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } From dbcd78a098e8375444d05af1b85a4dff29a62d2e Mon Sep 17 00:00:00 2001 From: pol <> Date: Tue, 25 Aug 2020 17:27:37 +0200 Subject: [PATCH 19/33] Updated require message errors with constant string numbers to reduce gas --- contracts/libraries/logic/ReserveLogic.sol | 5 +- contracts/libraries/logic/ValidationLogic.sol | 98 +++++++++++-------- 2 files changed, 61 insertions(+), 42 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 893ca5c5..208d9024 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -21,6 +21,9 @@ library ReserveLogic { using WadRayMath for uint256; using SafeERC20 for IERC20; + //require error messages + string private constant RESERVE_ALREADY_INITIALIZED = '1'; // 'Reserve has already been initialized' + /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve @@ -180,7 +183,7 @@ library ReserveLogic { address variableDebtTokenAddress, address interestRateStrategyAddress ) external { - require(reserve.aTokenAddress == address(0), 'Reserve has already been initialized'); + require(reserve.aTokenAddress == address(0), RESERVE_ALREADY_INITIALIZED); if (reserve.lastLiquidityIndex == 0) { //if the reserve has not been initialized yet reserve.lastLiquidityIndex = WadRayMath.ray(); diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index abba4592..c262144d 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -27,20 +27,39 @@ library ValidationLogic { using ReserveConfiguration for ReserveConfiguration.Map; using UserConfiguration for UserConfiguration.Map; + //require error messages + string private constant AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' + string private constant NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' + string private constant NO_UNFREEZED_RESERVE = '3'; // 'Action requires an unfreezed reserve' + string private constant CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' + string private constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' + string private constant TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' + string private constant BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' + string private constant INVALID_INTERESTRATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' + string private constant COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' + string private constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' + string private constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' + string private constant STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled + string private constant CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed + string private constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode + string private 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 private constant NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' + string private constant NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' + string private constant NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' + string private constant UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' + string private constant DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' + /** * @dev validates a deposit. * @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 - { + function validateDeposit(ReserveLogic.ReserveData storage reserve, uint256 amount) internal view { (bool isActive, bool isFreezed, , ) = reserve.configuration.getFlags(); - require(amount > 0, 'Amount must be greater than 0'); - require(isActive, 'Action requires an active reserve'); - require(!isFreezed, 'Action requires an unfreezed reserve'); + require(amount > 0, AMOUNT_NOT_GREATER_THAN_0); + require(isActive, NO_ACTIVE_RESERVE); + require(!isFreezed, NO_UNFREEZED_RESERVE); } /** @@ -60,13 +79,13 @@ library ValidationLogic { address[] calldata reserves, address oracle ) external view { - require(amount > 0, 'Amount must be greater than 0'); + require(amount > 0, AMOUNT_NOT_GREATER_THAN_0); uint256 currentAvailableLiquidity = IERC20(reserveAddress).balanceOf(address(aTokenAddress)); - require(currentAvailableLiquidity >= amount, '4'); + require(currentAvailableLiquidity >= amount, CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); - require(amount <= userBalance, 'User cannot withdraw more than the available balance'); + require(amount <= userBalance, NOT_ENOUGH_AVAILABLE_USER_BALANCE); require( GenericLogic.balanceDecreaseAllowed( @@ -78,7 +97,7 @@ library ValidationLogic { reserves, oracle ), - 'Transfer cannot be allowed.' + TRANSFER_NOT_ALLOWED ); } @@ -138,22 +157,22 @@ library ValidationLogic { vars.stableRateBorrowingEnabled ) = reserve.configuration.getFlags(); - require(vars.isActive, 'Action requires an active reserve'); - require(!vars.isFreezed, 'Action requires an unfreezed reserve'); + require(vars.isActive, NO_ACTIVE_RESERVE); + require(!vars.isFreezed, NO_UNFREEZED_RESERVE); - require(vars.borrowingEnabled, '5'); + require(vars.borrowingEnabled, BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(ReserveLogic.InterestRateMode.VARIABLE) == interestRateMode || uint256(ReserveLogic.InterestRateMode.STABLE) == interestRateMode, - 'Invalid interest rate mode selected' + INVALID_INTERESTRATE_MODE_SELECTED ); //check that the amount is available in the reserve vars.availableLiquidity = IERC20(reserveAddress).balanceOf(address(reserve.aTokenAddress)); - require(vars.availableLiquidity >= amount, '7'); + require(vars.availableLiquidity >= amount, CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); ( vars.userCollateralBalanceETH, @@ -169,9 +188,12 @@ library ValidationLogic { oracle ); - require(vars.userCollateralBalanceETH > 0, 'The collateral balance is 0'); + require(vars.userCollateralBalanceETH > 0, COLLATERAL_BALANCE_IS_0); - require(vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, '8'); + require( + vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, + HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD + ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( @@ -180,7 +202,7 @@ library ValidationLogic { require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, - 'There is not enough collateral to cover a new borrow' + COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** @@ -195,20 +217,20 @@ 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, '11'); + require(vars.stableRateBorrowingEnabled, STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.index) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), - '12' + CALLATERAL_SAME_AS_BORROWING_CURRENCY ); //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, '13'); + require(amount <= maxLoanSizeStable, AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } @@ -230,21 +252,21 @@ library ValidationLogic { ) external view { bool isActive = reserve.configuration.getActive(); - require(isActive, 'Action requires an active reserve'); + require(isActive, NO_ACTIVE_RESERVE); - require(amountSent > 0, 'Amount must be greater than 0'); + require(amountSent > 0, AMOUNT_NOT_GREATER_THAN_0); require( (stableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.STABLE) || (variableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.VARIABLE), - '16' + NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, - 'To repay on behalf of an user an explicit amount to repay is needed' + NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } @@ -265,19 +287,13 @@ library ValidationLogic { ) external view { (bool isActive, bool isFreezed, , bool stableRateEnabled) = reserve.configuration.getFlags(); - require(isActive, 'Action requires an active reserve'); - require(!isFreezed, 'Action requires an unfreezed reserve'); + require(isActive, NO_ACTIVE_RESERVE); + require(!isFreezed, NO_UNFREEZED_RESERVE); if (currentRateMode == ReserveLogic.InterestRateMode.STABLE) { - require( - stableBorrowBalance > 0, - 'User does not have a stable rate loan in progress on this reserve' - ); + require(stableBorrowBalance > 0, NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) { - require( - variableBorrowBalance > 0, - 'User does not have a variable rate loan in progress on this reserve' - ); + require(variableBorrowBalance > 0, 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 @@ -285,17 +301,17 @@ library ValidationLogic { * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ - require(stableRateEnabled, '11'); + require(stableRateEnabled, STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.index) || reserve.configuration.getLtv() == 0 || stableBorrowBalance.add(variableBorrowBalance) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), - '12' + CALLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { - revert('Invalid interest rate mode selected'); + revert(INVALID_INTERESTRATE_MODE_SELECTED); } } @@ -318,7 +334,7 @@ library ValidationLogic { ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); - require(underlyingBalance > 0, '22'); + require(underlyingBalance > 0, UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( GenericLogic.balanceDecreaseAllowed( @@ -330,7 +346,7 @@ library ValidationLogic { reserves, oracle ), - 'User deposit is already being used as collateral' + DEPOSIT_ALREADY_IN_USE ); } } From e0c27fef3fc6691ca2b8cf7c86d179879a92d616 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 28 Aug 2020 16:44:14 +0200 Subject: [PATCH 20/33] - Moved index update on flashLoan() to before the executeOperation. - Refactor to remove try..catch. - Change on _executeBorrow() to not consider liquidityTaken when coming from flash loan. --- contracts/lendingpool/LendingPool.sol | 102 +++++++++++++------------- test/flashloan.spec.ts | 1 - 2 files changed, 53 insertions(+), 50 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 839c0c42..8551a26e 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -220,7 +220,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount); } - reserve.updateInterestRates(vars.asset, 0, vars.amount); + reserve.updateInterestRates(vars.asset, 0, (vars.releaseUnderlying) ? vars.amount : 0); if (!userConfig.isBorrowing(reserve.index)) { userConfig.setBorrowing(reserve.index, true); @@ -453,7 +453,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 amountPlusPremiumInETH; uint256 receiverBalance; uint256 receiverAllowance; - uint256 balanceToPull; + uint256 availableBalance; uint256 assetPrice; IFlashLoanReceiver receiver; address aTokenAddress; @@ -484,72 +484,76 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.aTokenAddress = reserve.aTokenAddress; - //calculate amount fee vars.premium = amount.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000); require(vars.premium > 0, 'The requested amount is too small for a FlashLoan.'); - //get the FlashLoanReceiver instance vars.receiver = IFlashLoanReceiver(receiverAddress); + // Update of the indexes until the current moment + reserve.updateCumulativeIndexesAndTimestamp(); + //transfer funds to the receiver IAToken(vars.aTokenAddress).transferUnderlyingTo(receiverAddress, amount); //execute action of the receiver vars.receiver.executeOperation(asset, amount, vars.premium, params); - //compounding the cumulated interest - reserve.updateCumulativeIndexesAndTimestamp(); - vars.amountPlusPremium = amount.add(vars.premium); - //transfer from the receiver the amount plus the fee - try IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium) { - //if the transfer succeeded, the executor has repaid the flashloan. - //the fee is compounded into the reserve + if (debtType == 0) { // To not fetch balance/allowance if no debt needs to be opened + IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); - //refresh interest rates reserve.updateInterestRates(asset, vars.premium, 0); - emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); - } catch (bytes memory reason) { - if (debtType == 1 || debtType == 2) { - // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. - // We will try to pull all the available funds from the receiver and create a debt position with the rest owed - // if it has collateral enough - - vars.receiverBalance = IERC20(asset).balanceOf(receiverAddress); - vars.receiverAllowance = IERC20(asset).allowance(receiverAddress, address(this)); - vars.balanceToPull = (vars.receiverBalance > vars.receiverAllowance) - ? vars.receiverAllowance - : vars.receiverBalance; - - if (vars.balanceToPull > 0) { - IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.balanceToPull); - reserve.cumulateToLiquidityIndex( - IERC20(vars.aTokenAddress).totalSupply(), - (vars.balanceToPull > vars.premium) ? vars.premium : vars.balanceToPull - ); - reserve.updateInterestRates( - asset, - (vars.balanceToPull > vars.premium) ? vars.premium : vars.balanceToPull, - 0 - ); - } - - _executeBorrow( - BorrowLocalVars( - asset, - msg.sender, - vars.amountPlusPremium.sub(vars.balanceToPull), - debtType, - false, - referralCode - ) - ); + } else { + vars.receiverBalance = IERC20(asset).balanceOf(receiverAddress); + vars.receiverAllowance = IERC20(asset).allowance(receiverAddress, address(this)); + if (vars.receiverBalance >= vars.amountPlusPremium && vars.receiverAllowance >= vars.amountPlusPremium) { + IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); + reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); + reserve.updateInterestRates(asset, vars.premium, 0); } else { - revert(string(reason)); + if (debtType == 1 || debtType == 2) { + // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. + // We will try to pull all the available funds from the receiver and create a debt position with the rest owed + // if it has collateral enough + vars.availableBalance = (vars.receiverBalance > vars.receiverAllowance) + ? vars.receiverAllowance + : vars.receiverBalance; + + if (vars.availableBalance > 0) { + // If not enough premium, include as premium all the funds available to pull + if (vars.availableBalance < vars.premium) { + vars.premium = vars.availableBalance; + } + IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.availableBalance); + reserve.cumulateToLiquidityIndex( + IERC20(vars.aTokenAddress).totalSupply(), + vars.premium + ); + reserve.updateInterestRates( + asset, + vars.premium, + 0 + ); + } + + _executeBorrow( + BorrowLocalVars( + asset, + msg.sender, + vars.amountPlusPremium.sub(vars.availableBalance), + debtType, + false, + referralCode + ) + ); + } else { + revert("INSUFFICIENT_FUNDS_TO_PULL"); + } } } + emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); } /** diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 689796ec..93cb2fcd 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -301,7 +301,6 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await _mockFlashLoanReceiver.setFailExecutionTransfer(false); await _mockFlashLoanReceiver.setAmountToApprove(flashloanAmount.div(2)); - console.log((await _mockFlashLoanReceiver.amountToApprove()).toString()); await pool .connect(caller.signer) From 7b4812c956a0ba68f3bedf02c47255be441c478b Mon Sep 17 00:00:00 2001 From: pol <> Date: Wed, 2 Sep 2020 15:48:38 +0200 Subject: [PATCH 21/33] Moved error messages to error lib --- contracts/lendingpool/LendingPool.sol | 9 +--- contracts/libraries/helpers/Errors.sol | 48 +++++++++++++++++++ contracts/libraries/logic/ValidationLogic.sol | 23 +-------- contracts/tokenization/AToken.sol | 24 +++++----- helpers/types.ts | 43 ++++++++++++++++- test/atoken-modifiers.spec.ts | 10 ++-- 6 files changed, 108 insertions(+), 49 deletions(-) create mode 100644 contracts/libraries/helpers/Errors.sol diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index be4b4d18..1bf63fce 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -11,6 +11,7 @@ import { import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../tokenization/interfaces/IAToken.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; +import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; @@ -44,14 +45,6 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 public constant FLASHLOAN_FEE_TOTAL = 9; - //require error messages - string private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '1'; // 'User does not have any stable rate loan for this reserve' - string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '2'; // 'Interest rate rebalance conditions were not met' - string private constant LIQUIDATION_CALL_FAILED = '3'; // 'Liquidation call failed' - string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '4'; // 'There is not enough liquidity available to borrow' - string private constant REQUESTED_AMOUNT_TO_SMALL = '5'; // 'The requested amount is too small for a FlashLoan.' - string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '6'; // 'The actual balance of the protocol is inconsistent' - ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => ReserveLogic.ReserveData) internal _reserves; diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol new file mode 100644 index 00000000..9821add4 --- /dev/null +++ b/contracts/libraries/helpers/Errors.sol @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: agpl-3.0 +pragma solidity ^0.6.8; + +/** + * @title Errors library + * @author Aave + * @notice Implements error messages. + */ +library Errors { + // require error messages - ValidationLogic + string private constant AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' + string private constant NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' + string private constant NO_UNFREEZED_RESERVE = '3'; // 'Action requires an unfreezed reserve' + string private constant CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' + string private constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' + string private constant TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' + string private constant BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' + string private constant INVALID_INTERESTRATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' + string private constant COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' + string private constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' + string private constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' + string private constant STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled + string private constant CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed + string private constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode + string private 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 private constant NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' + string private constant NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' + string private constant NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' + string private constant UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' + string private constant DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' + + // require error messages - LendingPool + string private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' + string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' + string private constant LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' + string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' + string private constant REQUESTED_AMOUNT_TO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' + string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' + + // require error messages - aToken + string private constant CALLER_MUST_BE_LENDING_POOL = '27'; // 'The caller of this function must be a lending pool' + string private constant TRANSFER_CANNOT_BE_ALLOWED = '28'; // 'Transfer cannot be allowed.' + string private constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '29'; // 'Caller is not allowed to redirect the interest of the user' + string private constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' + string private constant TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' + string private constant INTEREST_ALREADY_REDIRECTED = '32'; // 'Interest is already redirected to the user' + string private constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33'; // 'Interest stream can only be redirected if there is a valid balance' +} diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index c262144d..c21a8831 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -12,6 +12,7 @@ import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; +import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title ReserveLogic library @@ -27,28 +28,6 @@ library ValidationLogic { using ReserveConfiguration for ReserveConfiguration.Map; using UserConfiguration for UserConfiguration.Map; - //require error messages - string private constant AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' - string private constant NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' - string private constant NO_UNFREEZED_RESERVE = '3'; // 'Action requires an unfreezed reserve' - string private constant CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' - string private constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' - string private constant TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' - string private constant BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' - string private constant INVALID_INTERESTRATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' - string private constant COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' - string private constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' - string private constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' - string private constant STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled - string private constant CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed - string private constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode - string private 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 private constant NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' - string private constant NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' - string private constant NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' - string private constant UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' - string private constant DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' - /** * @dev validates a deposit. * @param reserve the reserve state on which the user is depositing diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 0deb6dc2..dc871640 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -4,6 +4,7 @@ pragma solidity ^0.6.8; import {ERC20} from './ERC20.sol'; import {LendingPool} from '../lendingpool/LendingPool.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; +import {Errors} from '../libraries/helpers/Errors'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import { VersionedInitializable @@ -34,12 +35,12 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 public constant ATOKEN_REVISION = 0x1; modifier onlyLendingPool { - require(msg.sender == address(_pool), 'The caller of this function must be a lending pool'); + require(msg.sender == address(_pool), CALLER_MUST_BE_LENDING_POOL); _; } modifier whenTransferAllowed(address from, uint256 amount) { - require(isTransferAllowed(from, amount), 'Transfer cannot be allowed.'); + require(isTransferAllowed(from, amount), TRANSFER_CANNOT_BE_ALLOWED); _; } @@ -100,7 +101,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { function redirectInterestStreamOf(address from, address to) external override { require( msg.sender == _interestRedirectionAllowances[from], - 'Caller is not allowed to redirect the interest of the user' + CALLER_NOT_ALLOWED_TO_REDIRECT_INTEREST ); _redirectInterestStream(from, to); } @@ -112,7 +113,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { * the allowance. **/ function allowInterestRedirectionTo(address to) external override { - require(to != msg.sender, 'User cannot give allowance to himself'); + require(to != msg.sender, CANNOT_GIVE_ALLOWANCE_TO_HIMSELF); _interestRedirectionAllowances[msg.sender] = to; emit InterestRedirectionAllowanceChanged(msg.sender, to); } @@ -434,15 +435,12 @@ contract AToken is VersionedInitializable, ERC20, IAToken { address to, uint256 value ) internal { - require(value > 0, 'Transferred amount needs to be greater than zero'); + require(value > 0, TRANSFER_AMOUNT_NOT_GT_0); //cumulate the balance of the sender - ( - , - uint256 fromBalance, - uint256 fromBalanceIncrease, - uint256 fromIndex - ) = _cumulateBalance(from); + (, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex) = _cumulateBalance( + from + ); //cumulate the balance of the receiver (, , uint256 toBalanceIncrease, uint256 toIndex) = _cumulateBalance(to); @@ -486,7 +484,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { function _redirectInterestStream(address from, address to) internal { address currentRedirectionAddress = _interestRedirectionAddresses[from]; - require(to != currentRedirectionAddress, 'Interest is already redirected to the user'); + require(to != currentRedirectionAddress, INTEREST_ALREADY_REDIRECTED); //accumulates the accrued interest to the principal ( @@ -496,7 +494,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 fromIndex ) = _cumulateBalance(from); - require(fromBalance > 0, 'Interest stream can only be redirected if there is a valid balance'); + require(fromBalance > 0, NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous diff --git a/helpers/types.ts b/helpers/types.ts index 106e5376..c008816d 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -44,9 +44,50 @@ export enum eContractid { } 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_INTERESTRATE_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_EPLICIT_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' + + // require error messages - LendingPool + NOT_ENOUGH_STABLE_BORROW_BALANCE = '21', // 'User does not have any stable rate loan for this reserve' + INTERESTRATE_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_TO_SMALL = '25', // 'The requested amount is too small for a FlashLoan.' + INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26', // 'The actual balance of the protocol is inconsistent' + + // require error messages - aToken + CALLER_MUST_BE_LENDING_POOL = '27', // 'The caller of this function must be a lending pool' + TRANSFER_CANNOT_BE_ALLOWED = '28', // 'Transfer cannot be allowed.' + NOT_ALLOWED_TO_REDIRECT_INTEREST = '29', // 'Caller is not allowed to redirect the interest of the user' + 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' + INTEREST_ALREADY_REDIRECTED = '32', // 'Interest is already redirected to the user' + NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33', // 'Interest stream can only be redirected if there is a valid balance' +} + +export enum OLD_ProtocolErrors { INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', - INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', + // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => CALLER_MUST_BE_LENDING_POOL INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', diff --git a/test/atoken-modifiers.spec.ts b/test/atoken-modifiers.spec.ts index 97115c0c..406d910a 100644 --- a/test/atoken-modifiers.spec.ts +++ b/test/atoken-modifiers.spec.ts @@ -3,17 +3,17 @@ import {makeSuite, TestEnv} from './helpers/make-suite'; import {ProtocolErrors} from '../helpers/types'; makeSuite('AToken: Modifiers', (testEnv: TestEnv) => { - const {INVALID_POOL_CALLER_MSG_1} = ProtocolErrors; + const {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')).to.be.revertedWith(INVALID_POOL_CALLER_MSG_1); + await expect(aDai.mint(deployer.address, '1')).to.be.revertedWith(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')).to.be.revertedWith( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); @@ -21,13 +21,13 @@ makeSuite('AToken: Modifiers', (testEnv: TestEnv) => { const {deployer, users, aDai} = testEnv; await expect( aDai.transferOnLiquidation(deployer.address, users[0].address, '1') - ).to.be.revertedWith(INVALID_POOL_CALLER_MSG_1); + ).to.be.revertedWith(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( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); }); From 6122826ef41bc82ba08280340bb4f440c7faddf1 Mon Sep 17 00:00:00 2001 From: pol <> Date: Wed, 2 Sep 2020 16:34:15 +0200 Subject: [PATCH 22/33] fixed getting error codes from error lib --- contracts/lendingpool/LendingPool.sol | 12 ++-- contracts/libraries/helpers/Errors.sol | 66 +++++++++---------- contracts/libraries/logic/ValidationLogic.sol | 64 +++++++++--------- contracts/tokenization/AToken.sol | 16 ++--- helpers/types.ts | 22 +++++++ test/stable-token.spec.ts | 6 +- test/variable-debt-token.spec.ts | 6 +- 7 files changed, 107 insertions(+), 85 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 1bf63fce..01eaad25 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -345,7 +345,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 stableBorrowBalance = IERC20(address(stableDebtToken)).balanceOf(user); // user must be borrowing on asset at a stable rate - require(stableBorrowBalance > 0, NOT_ENOUGH_STABLE_BORROW_BALANCE); + require(stableBorrowBalance > 0, Errors.NOT_ENOUGH_STABLE_BORROW_BALANCE); uint256 rebalanceDownRateThreshold = reserve.currentStableBorrowRate.rayMul( WadRayMath.ray().add(REBALANCE_DOWN_RATE_DELTA) @@ -360,7 +360,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { require( userStableRate < reserve.currentLiquidityRate || userStableRate > rebalanceDownRateThreshold, - INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET + Errors.INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET ); //burn old debt tokens, mint new ones @@ -436,7 +436,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { receiveAToken ) ); - require(success, LIQUIDATION_CALL_FAILED); + require(success, Errors.LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); @@ -470,8 +470,8 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { //calculate amount fee uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); - require(availableLiquidityBefore >= amount, NOT_ENOUGH_LIQUIDITY_TO_BORROW); - require(amountFee > 0, REQUESTED_AMOUNT_TO_SMALL); + require(availableLiquidityBefore >= amount, Errors.NOT_ENOUGH_LIQUIDITY_TO_BORROW); + require(amountFee > 0, Errors.REQUESTED_AMOUNT_TO_SMALL); //get the FlashLoanReceiver instance IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); @@ -487,7 +487,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { require( availableLiquidityAfter == availableLiquidityBefore.add(amountFee), - INCONSISTENT_PROTOCOL_ACTUAL_BALANCE + Errors.INCONSISTENT_PROTOCOL_ACTUAL_BALANCE ); //compounding the cumulated interest diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 9821add4..7db32078 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -8,41 +8,41 @@ pragma solidity ^0.6.8; */ library Errors { // require error messages - ValidationLogic - string private constant AMOUNT_NOT_GREATER_THAN_0 = '1'; // 'Amount must be greater than 0' - string private constant NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' - string private constant NO_UNFREEZED_RESERVE = '3'; // 'Action requires an unfreezed reserve' - string private constant CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' - string private constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' - string private constant TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' - string private constant BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' - string private constant INVALID_INTERESTRATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' - string private constant COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' - string private constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' - string private constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' - string private constant STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled - string private constant CALLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed - string private constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode - string private 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 private constant NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' - string private constant NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' - string private constant NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' - string private constant UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' - string private constant DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' + 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_INTERESTRATE_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_EPLICIT_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 private constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' - string private constant INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' - string private constant LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' - string private constant NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' - string private constant REQUESTED_AMOUNT_TO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' - string private constant INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' + string public constant NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' + string public constant INTERESTRATE_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_TO_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' // require error messages - aToken - string private constant CALLER_MUST_BE_LENDING_POOL = '27'; // 'The caller of this function must be a lending pool' - string private constant TRANSFER_CANNOT_BE_ALLOWED = '28'; // 'Transfer cannot be allowed.' - string private constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '29'; // 'Caller is not allowed to redirect the interest of the user' - string private constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' - string private constant TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' - string private constant INTEREST_ALREADY_REDIRECTED = '32'; // 'Interest is already redirected to the user' - string private constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33'; // 'Interest stream can only be redirected if there is a valid balance' + string public constant CALLER_MUST_BE_LENDING_POOL = '27'; // 'The caller of this function must be a lending pool' + string public constant TRANSFER_CANNOT_BE_ALLOWED = '28'; // 'Transfer cannot be allowed.' + string public constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '29'; // 'Caller is not allowed to redirect the interest of the user' + 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 INTEREST_ALREADY_REDIRECTED = '32'; // 'Interest is already redirected to the user' + string public constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33'; // 'Interest stream can only be redirected if there is a valid balance' } diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index c21a8831..09a916e5 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -12,7 +12,7 @@ import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; -import {Errors} from '../libraries/helpers/Errors.sol'; +import {Errors} from '../helpers/Errors.sol'; /** * @title ReserveLogic library @@ -36,9 +36,9 @@ library ValidationLogic { function validateDeposit(ReserveLogic.ReserveData storage reserve, uint256 amount) internal view { (bool isActive, bool isFreezed, , ) = reserve.configuration.getFlags(); - require(amount > 0, AMOUNT_NOT_GREATER_THAN_0); - require(isActive, NO_ACTIVE_RESERVE); - require(!isFreezed, NO_UNFREEZED_RESERVE); + require(amount > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); + require(isActive, Errors.NO_ACTIVE_RESERVE); + require(!isFreezed, Errors.NO_UNFREEZED_RESERVE); } /** @@ -58,13 +58,13 @@ library ValidationLogic { address[] calldata reserves, address oracle ) external view { - require(amount > 0, AMOUNT_NOT_GREATER_THAN_0); + require(amount > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); uint256 currentAvailableLiquidity = IERC20(reserveAddress).balanceOf(address(aTokenAddress)); - require(currentAvailableLiquidity >= amount, CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); + require(currentAvailableLiquidity >= amount, Errors.CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); - require(amount <= userBalance, NOT_ENOUGH_AVAILABLE_USER_BALANCE); + require(amount <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE); require( GenericLogic.balanceDecreaseAllowed( @@ -76,7 +76,7 @@ library ValidationLogic { reserves, oracle ), - TRANSFER_NOT_ALLOWED + Errors.TRANSFER_NOT_ALLOWED ); } @@ -136,22 +136,22 @@ library ValidationLogic { vars.stableRateBorrowingEnabled ) = reserve.configuration.getFlags(); - require(vars.isActive, NO_ACTIVE_RESERVE); - require(!vars.isFreezed, NO_UNFREEZED_RESERVE); + require(vars.isActive, Errors.NO_ACTIVE_RESERVE); + require(!vars.isFreezed, Errors.NO_UNFREEZED_RESERVE); - require(vars.borrowingEnabled, BORROWING_NOT_ENABLED); + require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(ReserveLogic.InterestRateMode.VARIABLE) == interestRateMode || uint256(ReserveLogic.InterestRateMode.STABLE) == interestRateMode, - INVALID_INTERESTRATE_MODE_SELECTED + Errors.INVALID_INTERESTRATE_MODE_SELECTED ); //check that the amount is available in the reserve vars.availableLiquidity = IERC20(reserveAddress).balanceOf(address(reserve.aTokenAddress)); - require(vars.availableLiquidity >= amount, CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); + require(vars.availableLiquidity >= amount, Errors.CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH); ( vars.userCollateralBalanceETH, @@ -167,11 +167,11 @@ library ValidationLogic { oracle ); - require(vars.userCollateralBalanceETH > 0, COLLATERAL_BALANCE_IS_0); + require(vars.userCollateralBalanceETH > 0, Errors.COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, - HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD + Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. @@ -181,7 +181,7 @@ library ValidationLogic { require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, - COLLATERAL_CANNOT_COVER_NEW_BORROW + Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** @@ -196,20 +196,20 @@ 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, STABLE_BORROWING_NOT_ENABLED); + require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.index) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), - CALLATERAL_SAME_AS_BORROWING_CURRENCY + Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY ); //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, AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); + require(amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } @@ -231,21 +231,21 @@ library ValidationLogic { ) external view { bool isActive = reserve.configuration.getActive(); - require(isActive, NO_ACTIVE_RESERVE); + require(isActive, Errors.NO_ACTIVE_RESERVE); - require(amountSent > 0, AMOUNT_NOT_GREATER_THAN_0); + require(amountSent > 0, Errors.AMOUNT_NOT_GREATER_THAN_0); require( (stableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.STABLE) || (variableDebt > 0 && ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.VARIABLE), - NO_DEBT_OF_SELECTED_TYPE + Errors.NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, - NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF + Errors.NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } @@ -266,13 +266,13 @@ library ValidationLogic { ) external view { (bool isActive, bool isFreezed, , bool stableRateEnabled) = reserve.configuration.getFlags(); - require(isActive, NO_ACTIVE_RESERVE); - require(!isFreezed, NO_UNFREEZED_RESERVE); + require(isActive, Errors.NO_ACTIVE_RESERVE); + require(!isFreezed, Errors.NO_UNFREEZED_RESERVE); if (currentRateMode == ReserveLogic.InterestRateMode.STABLE) { - require(stableBorrowBalance > 0, NO_STABLE_RATE_LOAN_IN_RESERVE); + require(stableBorrowBalance > 0, Errors.NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) { - require(variableBorrowBalance > 0, NO_VARIABLE_RATE_LOAN_IN_RESERVE); + require(variableBorrowBalance > 0, Errors.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 @@ -280,17 +280,17 @@ library ValidationLogic { * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ - require(stableRateEnabled, STABLE_BORROWING_NOT_ENABLED); + require(stableRateEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.index) || reserve.configuration.getLtv() == 0 || stableBorrowBalance.add(variableBorrowBalance) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), - CALLATERAL_SAME_AS_BORROWING_CURRENCY + Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { - revert(INVALID_INTERESTRATE_MODE_SELECTED); + revert(Errors.INVALID_INTERESTRATE_MODE_SELECTED); } } @@ -313,7 +313,7 @@ library ValidationLogic { ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); - require(underlyingBalance > 0, UNDERLYING_BALANCE_NOT_GREATER_THAN_0); + require(underlyingBalance > 0, Errors.UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( GenericLogic.balanceDecreaseAllowed( @@ -325,7 +325,7 @@ library ValidationLogic { reserves, oracle ), - DEPOSIT_ALREADY_IN_USE + Errors.DEPOSIT_ALREADY_IN_USE ); } } diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index dc871640..528e4997 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -4,7 +4,7 @@ pragma solidity ^0.6.8; import {ERC20} from './ERC20.sol'; import {LendingPool} from '../lendingpool/LendingPool.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; -import {Errors} from '../libraries/helpers/Errors'; +import {Errors} from '../libraries/helpers/Errors.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import { VersionedInitializable @@ -35,12 +35,12 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 public constant ATOKEN_REVISION = 0x1; modifier onlyLendingPool { - require(msg.sender == address(_pool), CALLER_MUST_BE_LENDING_POOL); + require(msg.sender == address(_pool), Errors.CALLER_MUST_BE_LENDING_POOL); _; } modifier whenTransferAllowed(address from, uint256 amount) { - require(isTransferAllowed(from, amount), TRANSFER_CANNOT_BE_ALLOWED); + require(isTransferAllowed(from, amount), Errors.TRANSFER_CANNOT_BE_ALLOWED); _; } @@ -101,7 +101,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { function redirectInterestStreamOf(address from, address to) external override { require( msg.sender == _interestRedirectionAllowances[from], - CALLER_NOT_ALLOWED_TO_REDIRECT_INTEREST + Errors.NOT_ALLOWED_TO_REDIRECT_INTEREST ); _redirectInterestStream(from, to); } @@ -113,7 +113,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { * the allowance. **/ function allowInterestRedirectionTo(address to) external override { - require(to != msg.sender, CANNOT_GIVE_ALLOWANCE_TO_HIMSELF); + require(to != msg.sender, Errors.CANNOT_GIVE_ALLOWANCE_TO_HIMSELF); _interestRedirectionAllowances[msg.sender] = to; emit InterestRedirectionAllowanceChanged(msg.sender, to); } @@ -435,7 +435,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { address to, uint256 value ) internal { - require(value > 0, TRANSFER_AMOUNT_NOT_GT_0); + require(value > 0, Errors.TRANSFER_AMOUNT_NOT_GT_0); //cumulate the balance of the sender (, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex) = _cumulateBalance( @@ -484,7 +484,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { function _redirectInterestStream(address from, address to) internal { address currentRedirectionAddress = _interestRedirectionAddresses[from]; - require(to != currentRedirectionAddress, INTEREST_ALREADY_REDIRECTED); + require(to != currentRedirectionAddress, Errors.INTEREST_ALREADY_REDIRECTED); //accumulates the accrued interest to the principal ( @@ -494,7 +494,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 fromIndex ) = _cumulateBalance(from); - require(fromBalance > 0, NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM); + require(fromBalance > 0, Errors.NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous diff --git a/helpers/types.ts b/helpers/types.ts index c008816d..478b81cd 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -82,6 +82,28 @@ export enum ProtocolErrors { TRANSFER_AMOUNT_NOT_GT_0 = '31', // 'Transferred amount needs to be greater than zero' INTEREST_ALREADY_REDIRECTED = '32', // 'Interest is already redirected to the user' NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33', // 'Interest stream can only be redirected if there is a valid balance' + + // old + + INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', + INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', + // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => CALLER_MUST_BE_LENDING_POOL + INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', + INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', + INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', + INVALID_OWNER_REVERT_MSG = 'Ownable: caller is not the owner', + INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER = 'Invalid redirected balance before transfer', + INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER = 'Invalid redirected balance after transfer', + INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', + TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', + ZERO_COLLATERAL = 'The collateral balance is 0', + INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', + TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', + // NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', + HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', + INVALID_HF = 'Invalid health factor', + USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', + THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED = 'The collateral chosen cannot be liquidated', } export enum OLD_ProtocolErrors { diff --git a/test/stable-token.spec.ts b/test/stable-token.spec.ts index e6c25573..1d6adcdb 100644 --- a/test/stable-token.spec.ts +++ b/test/stable-token.spec.ts @@ -5,7 +5,7 @@ import {getContract} from '../helpers/contracts-helpers'; import {StableDebtToken} from '../types/StableDebtToken'; makeSuite('Stable debt token tests', (testEnv: TestEnv) => { - const {INVALID_POOL_CALLER_MSG_1} = ProtocolErrors; + const {CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; it('Tries to invoke mint not being the LendingPool', async () => { const {deployer, pool, dai} = testEnv; @@ -19,7 +19,7 @@ makeSuite('Stable debt token tests', (testEnv: TestEnv) => { ); await expect(stableDebtContract.mint(deployer.address, '1', '1')).to.be.revertedWith( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); @@ -35,7 +35,7 @@ makeSuite('Stable debt token tests', (testEnv: TestEnv) => { ); await expect(stableDebtContract.burn(deployer.address, '1')).to.be.revertedWith( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); }); diff --git a/test/variable-debt-token.spec.ts b/test/variable-debt-token.spec.ts index 28b35849..89bb1acc 100644 --- a/test/variable-debt-token.spec.ts +++ b/test/variable-debt-token.spec.ts @@ -5,7 +5,7 @@ import {getContract} from '../helpers/contracts-helpers'; import {VariableDebtToken} from '../types/VariableDebtToken'; makeSuite('Variable debt token tests', (testEnv: TestEnv) => { - const {INVALID_POOL_CALLER_MSG_1} = ProtocolErrors; + const {CALLER_MUST_BE_LENDING_POOL} = ProtocolErrors; it('Tries to invoke mint not being the LendingPool', async () => { const {deployer, pool, dai} = testEnv; @@ -19,7 +19,7 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { ); await expect(variableDebtContract.mint(deployer.address, '1')).to.be.revertedWith( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); @@ -35,7 +35,7 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { ); await expect(variableDebtContract.burn(deployer.address, '1')).to.be.revertedWith( - INVALID_POOL_CALLER_MSG_1 + CALLER_MUST_BE_LENDING_POOL ); }); }); From 76b4fc6b2dcd1b60d0491aa08fe731203c846f1b Mon Sep 17 00:00:00 2001 From: pol <> Date: Wed, 2 Sep 2020 17:54:34 +0200 Subject: [PATCH 23/33] All tests working. WIP look at old error messages to remove them all --- .../LendingPoolAddressesProviderRegistry.sol | 6 +- .../lendingpool/LendingPoolConfigurator.sol | 9 +-- contracts/libraries/helpers/Errors.sol | 21 ++++-- contracts/libraries/logic/ReserveLogic.sol | 6 +- contracts/tokenization/AToken.sol | 2 +- contracts/tokenization/base/DebtTokenBase.sol | 3 +- helpers/types.ts | 37 +++++++---- test/atoken-transfer.spec.ts | 28 ++++---- test/configurator.spec.ts | 66 +++++++++---------- test/flashloan.spec.ts | 14 ++-- test/upgradeability.spec.ts | 60 +++++++++-------- 11 files changed, 136 insertions(+), 116 deletions(-) diff --git a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol index 274ff33f..ee0caf16 100644 --- a/contracts/configuration/LendingPoolAddressesProviderRegistry.sol +++ b/contracts/configuration/LendingPoolAddressesProviderRegistry.sol @@ -5,6 +5,7 @@ import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../interfaces/ILendingPoolAddressesProviderRegistry.sol'; +import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract @@ -16,9 +17,6 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP mapping(address => uint256) addressesProviders; address[] addressesProvidersList; - //require error messages - string private constant PROVIDER_NOT_REGISTERED = '1'; // 'Provider is not registered' - /** * @dev returns if an addressesProvider is registered or not * @param provider the addresses provider @@ -66,7 +64,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, PROVIDER_NOT_REGISTERED); + require(addressesProviders[provider] > 0, Errors.PROVIDER_NOT_REGISTERED); addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 8ed719c7..e9c0a292 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -13,6 +13,7 @@ import {ReserveConfiguration} from '../libraries/configuration/ReserveConfigurat import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../interfaces/IERC20Detailed.sol'; +import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolConfigurator contract @@ -25,10 +26,6 @@ contract LendingPoolConfigurator is VersionedInitializable { using SafeMath for uint256; using ReserveConfiguration for ReserveConfiguration.Map; - //require error messages - string private constant CALLER_NOT_LENDING_POOL_MANAGER = '1'; // 'The caller must be a lending pool manager' - string private constant RESERVE_LIQUIDITY_NOT_0 = '2'; // 'The liquidity of the reserve needs to be 0' - /** * @dev emitted when a reserve is initialized. * @param asset the address of the reserve @@ -182,7 +179,7 @@ contract LendingPoolConfigurator is VersionedInitializable { modifier onlyLendingPoolManager { require( addressesProvider.getLendingPoolManager() == msg.sender, - CALLER_NOT_LENDING_POOL_MANAGER + Errors.CALLER_NOT_LENDING_POOL_MANAGER ); _; } @@ -429,7 +426,7 @@ contract LendingPoolConfigurator is VersionedInitializable { ) = pool.getReserveData(asset); require( availableLiquidity == 0 && totalBorrowsStable == 0 && totalBorrowsVariable == 0, - RESERVE_LIQUIDITY_NOT_0 + Errors.RESERVE_LIQUIDITY_NOT_0 ); ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 7db32078..388ea88f 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -39,10 +39,19 @@ library Errors { // require error messages - aToken string public constant CALLER_MUST_BE_LENDING_POOL = '27'; // 'The caller of this function must be a lending pool' - string public constant TRANSFER_CANNOT_BE_ALLOWED = '28'; // 'Transfer cannot be allowed.' - string public constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '29'; // 'Caller is not allowed to redirect the interest of the user' - 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 INTEREST_ALREADY_REDIRECTED = '32'; // 'Interest is already redirected to the user' - string public constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33'; // 'Interest stream can only be redirected if there is a valid balance' + string public constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '28'; // 'Caller is not allowed to redirect the interest of the user' + string public constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '29'; // 'User cannot give allowance to himself' + string public constant TRANSFER_AMOUNT_NOT_GT_0 = '30'; // 'Transferred amount needs to be greater than zero' + string public constant INTEREST_ALREADY_REDIRECTED = '31'; // 'Interest is already redirected to the user' + string public constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '32'; // 'Interest stream can only be redirected if there is a valid balance' + + // require error messages - ReserveLogic + string public constant RESERVE_ALREADY_INITIALIZED = '33'; // 'Reserve has already been initialized' + + //require error messages - LendingPoolConfiguration + string public constant CALLER_NOT_LENDING_POOL_MANAGER = '34'; // 'The caller must be a lending pool manager' + string public constant RESERVE_LIQUIDITY_NOT_0 = '35'; // 'The liquidity of the reserve needs to be 0' + + //require error messages - LendingPoolAddressesProviderRegistry + string public constant PROVIDER_NOT_REGISTERED = '36'; // 'Provider is not registered' } diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 208d9024..c4871668 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -10,6 +10,7 @@ import {IStableDebtToken} from '../../tokenization/interfaces/IStableDebtToken.s import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; +import {Errors} from '../helpers/Errors.sol'; /** * @title ReserveLogic library @@ -21,9 +22,6 @@ library ReserveLogic { using WadRayMath for uint256; using SafeERC20 for IERC20; - //require error messages - string private constant RESERVE_ALREADY_INITIALIZED = '1'; // 'Reserve has already been initialized' - /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve @@ -183,7 +181,7 @@ library ReserveLogic { address variableDebtTokenAddress, address interestRateStrategyAddress ) external { - require(reserve.aTokenAddress == address(0), RESERVE_ALREADY_INITIALIZED); + require(reserve.aTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED); if (reserve.lastLiquidityIndex == 0) { //if the reserve has not been initialized yet reserve.lastLiquidityIndex = WadRayMath.ray(); diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 528e4997..2c6e8541 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -40,7 +40,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { } modifier whenTransferAllowed(address from, uint256 amount) { - require(isTransferAllowed(from, amount), Errors.TRANSFER_CANNOT_BE_ALLOWED); + require(isTransferAllowed(from, amount), Errors.TRANSFER_NOT_ALLOWED); _; } diff --git a/contracts/tokenization/base/DebtTokenBase.sol b/contracts/tokenization/base/DebtTokenBase.sol index 87b83e0e..33d7222d 100644 --- a/contracts/tokenization/base/DebtTokenBase.sol +++ b/contracts/tokenization/base/DebtTokenBase.sol @@ -9,6 +9,7 @@ import { VersionedInitializable } from '../../libraries/openzeppelin-upgradeability/VersionedInitializable.sol'; import {IERC20Detailed} from '../../interfaces/IERC20Detailed.sol'; +import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title contract DebtTokenBase @@ -33,7 +34,7 @@ abstract contract DebtTokenBase is IERC20Detailed, VersionedInitializable { * @dev only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { - require(msg.sender == address(_pool), 'The caller of this function must be a lending pool'); + require(msg.sender == address(_pool), Errors.CALLER_MUST_BE_LENDING_POOL); _; } diff --git a/helpers/types.ts b/helpers/types.ts index 478b81cd..3d6aca55 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -76,30 +76,39 @@ export enum ProtocolErrors { // require error messages - aToken CALLER_MUST_BE_LENDING_POOL = '27', // 'The caller of this function must be a lending pool' - TRANSFER_CANNOT_BE_ALLOWED = '28', // 'Transfer cannot be allowed.' - NOT_ALLOWED_TO_REDIRECT_INTEREST = '29', // 'Caller is not allowed to redirect the interest of the user' - 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' - INTEREST_ALREADY_REDIRECTED = '32', // 'Interest is already redirected to the user' - NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '33', // 'Interest stream can only be redirected if there is a valid balance' + NOT_ALLOWED_TO_REDIRECT_INTEREST = '28', // 'Caller is not allowed to redirect the interest of the user' + CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '29', // 'User cannot give allowance to himself' + TRANSFER_AMOUNT_NOT_GT_0 = '30', // 'Transferred amount needs to be greater than zero' + INTEREST_ALREADY_REDIRECTED = '31', // 'Interest is already redirected to the user' + NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '32', // 'Interest stream can only be redirected if there is a valid balance' + + // require error messages - ReserveLogic + RESERVE_ALREADY_INITIALIZED = '33', // 'Reserve has already been initialized' + + //require error messages - LendingPoolConfiguration + CALLER_NOT_LENDING_POOL_MANAGER = '34', // 'The caller must be a lending pool manager' + RESERVE_LIQUIDITY_NOT_0 = '35', // 'The liquidity of the reserve needs to be 0' + + //require error messages - LendingPoolAddressesProviderRegistry + PROVIDER_NOT_REGISTERED = '36', // 'Provider is not registered' // old INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', - // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => CALLER_MUST_BE_LENDING_POOL - INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', + // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => 27 + // INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', => 34 INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_OWNER_REVERT_MSG = 'Ownable: caller is not the owner', INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER = 'Invalid redirected balance before transfer', INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER = 'Invalid redirected balance after transfer', INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', - TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', - ZERO_COLLATERAL = 'The collateral balance is 0', - INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', - TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', - // NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', + // TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', => 30 + // ZERO_COLLATERAL = 'The collateral balance is 0', + // INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', => 26 + // TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', => 25 + // NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', => 24 HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', INVALID_HF = 'Invalid health factor', USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', @@ -109,7 +118,7 @@ export enum ProtocolErrors { export enum OLD_ProtocolErrors { INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', - // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => CALLER_MUST_BE_LENDING_POOL + INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', diff --git a/test/atoken-transfer.spec.ts b/test/atoken-transfer.spec.ts index 138eda61..1c161608 100644 --- a/test/atoken-transfer.spec.ts +++ b/test/atoken-transfer.spec.ts @@ -17,8 +17,10 @@ makeSuite('AToken: Transfer', (testEnv: TestEnv) => { INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER, INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER, INVALID_REDIRECTION_ADDRESS, - ZERO_COLLATERAL, - TRANSFERRED_AMOUNT_GT_ZERO, + // ZERO_COLLATERAL, + TRANSFER_AMOUNT_NOT_GT_0, + COLLATERAL_BALANCE_IS_0, + TRANSFER_NOT_ALLOWED, } = ProtocolErrors; it('User 0 deposits 1000 DAI, transfers to user 1', async () => { @@ -96,16 +98,14 @@ makeSuite('AToken: Transfer', (testEnv: TestEnv) => { await weth.connect(users[0].signer).mint(await convertToCurrencyDecimals(weth.address, '1')); await weth.connect(users[0].signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); - - await pool - .connect(users[0].signer) - .deposit(weth.address, ethers.utils.parseEther('1.0'), '0'); + + await pool.connect(users[0].signer).deposit(weth.address, ethers.utils.parseEther('1.0'), '0'); await expect( pool .connect(users[1].signer) .borrow(weth.address, ethers.utils.parseEther('0.1'), RateMode.Stable, AAVE_REFERRAL), - ZERO_COLLATERAL - ).to.be.revertedWith(ZERO_COLLATERAL); + COLLATERAL_BALANCE_IS_0 + ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); }); it('User 1 sets the DAI as collateral and borrows, tries to transfer everything back to user 0 (revert expected)', async () => { @@ -120,25 +120,25 @@ makeSuite('AToken: Transfer', (testEnv: TestEnv) => { await expect( aDai.connect(users[1].signer).transfer(users[0].address, aDAItoTransfer), - 'Transfer cannot be allowed.' - ).to.be.revertedWith('Transfer cannot be allowed.'); + TRANSFER_NOT_ALLOWED + ).to.be.revertedWith(TRANSFER_NOT_ALLOWED); }); it('User 0 tries to transfer 0 balance (revert expected)', async () => { const {users, pool, aDai, dai, weth} = testEnv; await expect( aDai.connect(users[0].signer).transfer(users[1].address, '0'), - TRANSFERRED_AMOUNT_GT_ZERO - ).to.be.revertedWith(TRANSFERRED_AMOUNT_GT_ZERO); + TRANSFER_AMOUNT_NOT_GT_0 + ).to.be.revertedWith(TRANSFER_AMOUNT_NOT_GT_0); }); it('User 1 repays the borrow, transfers aDAI back to user 0', async () => { const {users, pool, aDai, dai, weth} = testEnv; - + await weth.connect(users[1].signer).mint(await convertToCurrencyDecimals(weth.address, '2')); await weth.connect(users[1].signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); - + await pool .connect(users[1].signer) .repay(weth.address, MAX_UINT_AMOUNT, RateMode.Stable, users[1].address); diff --git a/test/configurator.spec.ts b/test/configurator.spec.ts index 182f2f2b..a6513e54 100644 --- a/test/configurator.spec.ts +++ b/test/configurator.spec.ts @@ -6,7 +6,7 @@ import {ProtocolErrors} from '../helpers/types'; const {expect} = require('chai'); makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { - const {INVALID_POOL_MANAGER_CALLER_MSG} = ProtocolErrors; + const {CALLER_NOT_LENDING_POOL_MANAGER, RESERVE_LIQUIDITY_NOT_0} = ProtocolErrors; it('Deactivates the ETH reserve', async () => { const {configurator, pool, weth} = testEnv; @@ -27,16 +27,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).deactivateReserve(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on activateReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).activateReserve(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Freezes the ETH reserve', async () => { @@ -58,16 +58,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).freezeReserve(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on unfreezeReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).unfreezeReserve(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Deactivates the ETH reserve for borrowing', async () => { @@ -90,16 +90,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).disableBorrowingOnReserve(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on enableBorrowingOnReserve ', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).enableBorrowingOnReserve(weth.address, true), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Deactivates the ETH reserve as collateral', async () => { @@ -121,8 +121,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).disableReserveAsCollateral(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on enableReserveAsCollateral ', async () => { @@ -131,8 +131,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { configurator .connect(users[2].signer) .enableReserveAsCollateral(weth.address, '75', '80', '105'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Disable stable borrow rate on the ETH reserve', async () => { @@ -153,16 +153,16 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).disableReserveStableRate(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on enableReserveStableRate', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).enableReserveStableRate(weth.address), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Changes LTV of the reserve', async () => { @@ -176,8 +176,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLtv(weth.address, '75'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Changes liquidation threshold of the reserve', async () => { @@ -194,8 +194,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationThreshold(weth.address, '80'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Changes liquidation bonus of the reserve', async () => { @@ -212,24 +212,24 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationBonus(weth.address, '80'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on setReserveDecimals', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setReserveDecimals(weth.address, '80'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Check the onlyLendingPoolManager on setLiquidationBonus', async () => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setLiquidationBonus(weth.address, '80'), - INVALID_POOL_MANAGER_CALLER_MSG - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Reverts when trying to disable the DAI reserve with liquidity on it', async () => { @@ -246,7 +246,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { await expect( configurator.deactivateReserve(dai.address), - 'The liquidity of the reserve needs to be 0' - ).to.be.revertedWith('The liquidity of the reserve needs to be 0'); + RESERVE_LIQUIDITY_NOT_0 + ).to.be.revertedWith(RESERVE_LIQUIDITY_NOT_0); }); }); diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index fcda8c28..dfd7be16 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -11,8 +11,8 @@ const {expect} = require('chai'); makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { - INCONSISTENT_PROTOCOL_BALANCE, - TOO_SMALL_FLASH_LOAN, + INCONSISTENT_PROTOCOL_ACTUAL_BALANCE, + REQUESTED_AMOUNT_TO_SMALL, NOT_ENOUGH_LIQUIDITY_TO_BORROW, } = ProtocolErrors; @@ -62,7 +62,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const reserveDataBefore = await pool.getReserveData(weth.address); - console.log("Total liquidity is ", reserveDataBefore.availableLiquidity.toString()); + console.log('Total liquidity is ', reserveDataBefore.availableLiquidity.toString()); const txResult = await pool.flashLoan( _mockFlashLoanReceiver.address, @@ -99,7 +99,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ethers.utils.parseEther('0.8'), '0x10' ) - ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + ).to.be.revertedWith(INCONSISTENT_PROTOCOL_ACTUAL_BALANCE); }); it('tries to take a very small flashloan, which would result in 0 fees (revert expected)', async () => { @@ -112,7 +112,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { '1', //1 wei loan '0x10' ) - ).to.be.revertedWith(TOO_SMALL_FLASH_LOAN); + ).to.be.revertedWith(REQUESTED_AMOUNT_TO_SMALL); }); it('tries to take a flashloan that is bigger than the available liquidity (revert expected)', async () => { @@ -194,7 +194,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ethers.utils.parseEther('500'), '0x10' ), - INCONSISTENT_PROTOCOL_BALANCE - ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + INCONSISTENT_PROTOCOL_ACTUAL_BALANCE + ).to.be.revertedWith(INCONSISTENT_PROTOCOL_ACTUAL_BALANCE); }); }); diff --git a/test/upgradeability.spec.ts b/test/upgradeability.spec.ts index 41fc60ea..b2f50179 100644 --- a/test/upgradeability.spec.ts +++ b/test/upgradeability.spec.ts @@ -1,18 +1,22 @@ import {expect} from 'chai'; import {makeSuite, TestEnv} from './helpers/make-suite'; import {ProtocolErrors, eContractid} from '../helpers/types'; -import {deployGenericAToken, getAToken, deployContract, getContract} from '../helpers/contracts-helpers'; +import { + deployGenericAToken, + getAToken, + deployContract, + getContract, +} from '../helpers/contracts-helpers'; import {MockAToken} from '../types/MockAToken'; -import { MockStableDebtToken } from '../types/MockStableDebtToken'; -import { MockVariableDebtToken } from '../types/MockVariableDebtToken'; +import {MockStableDebtToken} from '../types/MockStableDebtToken'; +import {MockVariableDebtToken} from '../types/MockVariableDebtToken'; makeSuite('Upgradeability', (testEnv: TestEnv) => { - const {INVALID_POOL_MANAGER_CALLER_MSG} = ProtocolErrors; + const {CALLER_NOT_LENDING_POOL_MANAGER} = ProtocolErrors; let newATokenAddress: string; let newStableTokenAddress: string; let newVariableTokenAddress: string; - before('deploying instances', async () => { const {dai, pool} = testEnv; const aTokenInstance = await deployContract(eContractid.MockAToken, [ @@ -22,24 +26,19 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { 'aDAI', ]); - const stableDebtTokenInstance = await deployContract(eContractid.MockStableDebtToken, [ - pool.address, - dai.address, - 'Aave stable debt bearing DAI updated', - 'stableDebtDAI', - ]); + const stableDebtTokenInstance = await deployContract( + eContractid.MockStableDebtToken, + [pool.address, dai.address, 'Aave stable debt bearing DAI updated', 'stableDebtDAI'] + ); - const variableDebtTokenInstance = await deployContract(eContractid.MockVariableDebtToken, [ - pool.address, - dai.address, - 'Aave variable debt bearing DAI updated', - 'variableDebtDAI', - ]); + const variableDebtTokenInstance = await deployContract( + eContractid.MockVariableDebtToken, + [pool.address, dai.address, 'Aave variable debt bearing DAI updated', 'variableDebtDAI'] + ); newATokenAddress = aTokenInstance.address; newVariableTokenAddress = variableDebtTokenInstance.address; newStableTokenAddress = stableDebtTokenInstance.address; - }); it('Tries to update the DAI Atoken implementation with a different address than the lendingPoolManager', async () => { @@ -47,7 +46,7 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { await expect( configurator.connect(users[1].signer).updateAToken(dai.address, newATokenAddress) - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Upgrades the DAI Atoken implementation ', async () => { @@ -66,8 +65,10 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {dai, configurator, users} = testEnv; await expect( - configurator.connect(users[1].signer).updateStableDebtToken(dai.address, newStableTokenAddress) - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + configurator + .connect(users[1].signer) + .updateStableDebtToken(dai.address, newStableTokenAddress) + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Upgrades the DAI stable debt token implementation ', async () => { @@ -79,7 +80,10 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {stableDebtTokenAddress} = await pool.getReserveTokensAddresses(dai.address); - const debtToken = await getContract(eContractid.MockStableDebtToken, stableDebtTokenAddress); + const debtToken = await getContract( + eContractid.MockStableDebtToken, + stableDebtTokenAddress + ); const tokenName = await debtToken.name(); @@ -90,8 +94,10 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {dai, configurator, users} = testEnv; await expect( - configurator.connect(users[1].signer).updateVariableDebtToken(dai.address, newVariableTokenAddress) - ).to.be.revertedWith(INVALID_POOL_MANAGER_CALLER_MSG); + configurator + .connect(users[1].signer) + .updateVariableDebtToken(dai.address, newVariableTokenAddress) + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); it('Upgrades the DAI variable debt token implementation ', async () => { @@ -103,11 +109,13 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(dai.address); - const debtToken = await getContract(eContractid.MockStableDebtToken, variableDebtTokenAddress); + const debtToken = await getContract( + eContractid.MockStableDebtToken, + variableDebtTokenAddress + ); const tokenName = await debtToken.name(); expect(tokenName).to.be.eq('Aave variable debt bearing DAI updated', 'Invalid token name'); }); - }); From ab88aa64bf111935c083cb19119d39e0b3e46815 Mon Sep 17 00:00:00 2001 From: emilio Date: Wed, 2 Sep 2020 18:10:16 +0200 Subject: [PATCH 24/33] Fixed merge issues --- contracts/lendingpool/LendingPool.sol | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 1cf33799..265b9ce6 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -188,7 +188,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; UserConfiguration.Map storage userConfig = _usersConfig[vars.user]; - address oracle = addressesProvider.getPriceOracle(); + address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); @@ -202,7 +202,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { MAX_STABLE_RATE_BORROW_SIZE_PERCENT, _reserves, _usersConfig[vars.user], - reservesList, + _reservesList, oracle ); @@ -220,7 +220,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { } address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(asset, aToken, 0, amount); + reserve.updateInterestRates(vars.asset, aToken, 0, vars.amount); uint256 reserveIndex = reserve.index; if (!userConfig.isBorrowing(reserveIndex)) { @@ -308,7 +308,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param asset the address of the reserve on which the user borrowed * @param rateMode the rate mode that the user wants to swap **/ - function swapBorrowRateMode(address asset, uint256 rateMode) external override nonReentrant { + function swapBorrowRateMode(address asset, uint256 rateMode) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); @@ -516,14 +516,14 @@ contract LendingPool is VersionedInitializable, ILendingPool { if (debtType == 0) { // To not fetch balance/allowance if no debt needs to be opened IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); - reserve.updateInterestRates(asset, vars.premium, 0); + reserve.updateInterestRates(asset, vars.aTokenAddress, vars.premium, 0); } else { vars.receiverBalance = IERC20(asset).balanceOf(receiverAddress); vars.receiverAllowance = IERC20(asset).allowance(receiverAddress, address(this)); if (vars.receiverBalance >= vars.amountPlusPremium && vars.receiverAllowance >= vars.amountPlusPremium) { IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); - reserve.updateInterestRates(asset, vars.premium, 0); + reserve.updateInterestRates(asset, vars.aTokenAddress, vars.premium, 0); } else { if (debtType == 1 || debtType == 2) { // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. @@ -545,6 +545,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { ); reserve.updateInterestRates( asset, + vars.aTokenAddress, vars.premium, 0 ); From 5b5f8ae74a1a4283f2faa448dd23b90737c36d01 Mon Sep 17 00:00:00 2001 From: pol <> Date: Wed, 2 Sep 2020 18:18:17 +0200 Subject: [PATCH 25/33] cleaned comments --- helpers/types.ts | 31 ------------------------------- 1 file changed, 31 deletions(-) diff --git a/helpers/types.ts b/helpers/types.ts index 3d6aca55..713b9510 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -94,43 +94,12 @@ export enum ProtocolErrors { // old - INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', - INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', - // INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', => 27 - // INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', => 34 INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', INVALID_OWNER_REVERT_MSG = 'Ownable: caller is not the owner', INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER = 'Invalid redirected balance before transfer', INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER = 'Invalid redirected balance after transfer', INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', - // TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', => 30 - // ZERO_COLLATERAL = 'The collateral balance is 0', - // INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', => 26 - // TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', => 25 - // NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', => 24 - HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', - INVALID_HF = 'Invalid health factor', - USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', - THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED = 'The collateral chosen cannot be liquidated', -} - -export enum OLD_ProtocolErrors { - INVALID_CONFIGURATOR_CALLER_MSG = 'The caller must be a lending pool configurator contract', - INVALID_POOL_CALLER_MSG = 'The caller must be a lending pool contract', - INVALID_POOL_CALLER_MSG_1 = 'The caller of this function must be a lending pool', - INVALID_POOL_MANAGER_CALLER_MSG = 'The caller must be a lending pool manager', - INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', - INVALID_TO_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', - INVALID_OWNER_REVERT_MSG = 'Ownable: caller is not the owner', - INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER = 'Invalid redirected balance before transfer', - INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER = 'Invalid redirected balance after transfer', - INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', - TRANSFERRED_AMOUNT_GT_ZERO = 'Transferred amount needs to be greater than zero', - ZERO_COLLATERAL = 'The collateral balance is 0', - INCONSISTENT_PROTOCOL_BALANCE = 'The actual balance of the protocol is inconsistent', - TOO_SMALL_FLASH_LOAN = 'The requested amount is too small for a FlashLoan.', - NOT_ENOUGH_LIQUIDITY_TO_BORROW = 'There is not enough liquidity available to borrow', HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', INVALID_HF = 'Invalid health factor', USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', From 288d8f288973c25da696f83f0c5296fb5541e953 Mon Sep 17 00:00:00 2001 From: pol <> Date: Wed, 2 Sep 2020 18:53:39 +0200 Subject: [PATCH 26/33] Added LendingPoolLiquidationManager error messages to error lib, and updated tests. --- .../lendingpool/LendingPoolLiquidationManager.sol | 11 ++++++----- contracts/libraries/helpers/Errors.sol | 7 +++++++ helpers/types.ts | 10 +++++++--- test/liquidation-atoken.spec.ts | 12 ++++++------ test/liquidation-underlying.spec.ts | 11 +++-------- 5 files changed, 29 insertions(+), 22 deletions(-) diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index a36ed3f3..27a29277 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -21,6 +21,7 @@ import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; +import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolLiquidationManager contract @@ -132,7 +133,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl if (vars.healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(LiquidationErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), - 'Health factor is not below the threshold' + Errors.HEALTH_FACTOR_NOT_BELLOW_THRESHOLD ); } @@ -148,7 +149,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl if (!vars.isCollateralEnabled) { return ( uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), - 'The collateral chosen cannot be liquidated' + Errors.COLLATERAL_CANNOT_BE_LIQUIDATED ); } @@ -161,7 +162,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl if (vars.userStableDebt == 0 && vars.userVariableDebt == 0) { return ( uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED), - 'User did not borrow the specified currency' + Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } @@ -202,7 +203,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(LiquidationErrors.NOT_ENOUGH_LIQUIDITY), - "There isn't enough liquidity available to liquidate" + Errors.NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } @@ -268,7 +269,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl receiveAToken ); - return (uint256(LiquidationErrors.NO_ERROR), 'No errors'); + return (uint256(LiquidationErrors.NO_ERROR), Errors.NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 388ea88f..1b3f6980 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -54,4 +54,11 @@ library Errors { //require error messages - LendingPoolAddressesProviderRegistry string public constant PROVIDER_NOT_REGISTERED = '36'; // 'Provider is not registered' + + //return error messages - LendingPoolLiquidationManager + string public constant HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '37'; // 'Health factor is not below the threshold' + string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '38'; // 'The collateral chosen cannot be liquidated' + string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '39'; // 'User did not borrow the specified currency' + string public constant NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '40'; // "There isn't enough liquidity available to liquidate" + string public constant NO_ERRORS = '41'; // 'No errors' } diff --git a/helpers/types.ts b/helpers/types.ts index 713b9510..e98e5a3c 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -92,6 +92,13 @@ export enum ProtocolErrors { //require error messages - LendingPoolAddressesProviderRegistry PROVIDER_NOT_REGISTERED = '36', // 'Provider is not registered' + //return error messages - LendingPoolLiquidationManager + HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '37', // 'Health factor is not below the threshold' + COLLATERAL_CANNOT_BE_LIQUIDATED = '38', // 'The collateral chosen cannot be liquidated' + SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '39', // 'User did not borrow the specified currency' + NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '40', // "There isn't enough liquidity available to liquidate" + NO_ERRORS = '41', // 'No errors' + // old INVALID_FROM_BALANCE_AFTER_TRANSFER = 'Invalid from balance after transfer', @@ -100,10 +107,7 @@ export enum ProtocolErrors { INVALID_REDIRECTED_BALANCE_BEFORE_TRANSFER = 'Invalid redirected balance before transfer', INVALID_REDIRECTED_BALANCE_AFTER_TRANSFER = 'Invalid redirected balance after transfer', INVALID_REDIRECTION_ADDRESS = 'Invalid redirection address', - HF_IS_NOT_BELLOW_THRESHOLD = 'Health factor is not below the threshold', INVALID_HF = 'Invalid health factor', - USER_DID_NOT_BORROW_SPECIFIED = 'User did not borrow the specified currency', - THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED = 'The collateral chosen cannot be liquidated', } export type tEthereumAddress = string; diff --git a/test/liquidation-atoken.spec.ts b/test/liquidation-atoken.spec.ts index 6e4af1e1..155b7c25 100644 --- a/test/liquidation-atoken.spec.ts +++ b/test/liquidation-atoken.spec.ts @@ -13,10 +13,10 @@ const {expect} = chai; makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => { const { - HF_IS_NOT_BELLOW_THRESHOLD, + HEALTH_FACTOR_NOT_BELLOW_THRESHOLD, INVALID_HF, - USER_DID_NOT_BORROW_SPECIFIED, - THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED, + SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER, + COLLATERAL_CANNOT_BE_LIQUIDATED, } = ProtocolErrors; it('LIQUIDATION - Deposits WETH, borrows DAI/Check liquidation fails because health factor is above 1', async () => { @@ -71,7 +71,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(HF_IS_NOT_BELLOW_THRESHOLD); + ).to.be.revertedWith(HEALTH_FACTOR_NOT_BELLOW_THRESHOLD); }); it('LIQUIDATION - Drop the health factor below 1', async () => { @@ -96,7 +96,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(USER_DID_NOT_BORROW_SPECIFIED); + ).revertedWith(SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); }); it('LIQUIDATION - Tries to liquidate a different collateral than the borrower collateral', async () => { @@ -105,7 +105,7 @@ makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => await expect( pool.liquidationCall(dai.address, dai.address, borrower.address, oneEther.toString(), true) - ).revertedWith(THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED); + ).revertedWith(COLLATERAL_CANNOT_BE_LIQUIDATED); }); it('LIQUIDATION - Liquidates the borrow', async () => { diff --git a/test/liquidation-underlying.spec.ts b/test/liquidation-underlying.spec.ts index 676c9c26..064e3856 100644 --- a/test/liquidation-underlying.spec.ts +++ b/test/liquidation-underlying.spec.ts @@ -13,12 +13,7 @@ const chai = require('chai'); const {expect} = chai; makeSuite('LendingPool liquidation - liquidator receiving the underlying asset', (testEnv) => { - const { - HF_IS_NOT_BELLOW_THRESHOLD, - INVALID_HF, - USER_DID_NOT_BORROW_SPECIFIED, - THE_COLLATERAL_CHOSEN_CANNOT_BE_LIQUIDATED, - } = ProtocolErrors; + const {INVALID_HF} = ProtocolErrors; it('LIQUIDATION - Deposits WETH, borrows DAI', async () => { const {dai, weth, users, pool, oracle} = testEnv; @@ -67,7 +62,7 @@ makeSuite('LendingPool liquidation - liquidator receiving the underlying asset', expect(userGlobalDataAfter.currentLiquidationThreshold.toString()).to.be.bignumber.equal( '8000', - 'Invalid liquidation threshold' + INVALID_HF ); }); @@ -86,7 +81,7 @@ makeSuite('LendingPool liquidation - liquidator receiving the underlying asset', expect(userGlobalData.healthFactor.toString()).to.be.bignumber.lt( oneEther.toFixed(0), - 'Invalid health factor' + INVALID_HF ); }); From 714c2ff3fdcf510a4d266d630198d4eccf6e3351 Mon Sep 17 00:00:00 2001 From: pol <> Date: Thu, 3 Sep 2020 10:33:15 +0200 Subject: [PATCH 27/33] Refactored as per the PR comments --- contracts/lendingpool/LendingPool.sol | 9 +++-- contracts/libraries/helpers/Errors.sol | 39 ++++++++++--------- contracts/libraries/logic/ValidationLogic.sol | 6 +-- contracts/tokenization/AToken.sol | 4 +- helpers/types.ts | 39 ++++++++++--------- test/flashloan.spec.ts | 4 +- 6 files changed, 53 insertions(+), 48 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 01eaad25..e38ee13a 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -56,7 +56,10 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { - require(_addressesProvider.getLendingPoolConfigurator() == msg.sender, '30'); + require( + _addressesProvider.getLendingPoolConfigurator() == msg.sender, + Errors.CALLER_NOT_LENDING_POOL_CONFIGURATOR + ); _; } @@ -360,7 +363,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { require( userStableRate < reserve.currentLiquidityRate || userStableRate > rebalanceDownRateThreshold, - Errors.INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET + Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); //burn old debt tokens, mint new ones @@ -471,7 +474,7 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool { uint256 amountFee = amount.mul(FLASHLOAN_FEE_TOTAL).div(10000); require(availableLiquidityBefore >= amount, Errors.NOT_ENOUGH_LIQUIDITY_TO_BORROW); - require(amountFee > 0, Errors.REQUESTED_AMOUNT_TO_SMALL); + require(amountFee > 0, Errors.REQUESTED_AMOUNT_TOO_SMALL); //get the FlashLoanReceiver instance IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 1b3f6980..db239d1f 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -15,7 +15,7 @@ library Errors { 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_INTERESTRATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' + 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' @@ -23,7 +23,7 @@ library Errors { 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_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' + 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' @@ -31,34 +31,35 @@ library Errors { // 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 INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' + 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_TO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' + 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' // require error messages - aToken - string public constant CALLER_MUST_BE_LENDING_POOL = '27'; // 'The caller of this function must be a lending pool' - string public constant NOT_ALLOWED_TO_REDIRECT_INTEREST = '28'; // 'Caller is not allowed to redirect the interest of the user' - string public constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '29'; // 'User cannot give allowance to himself' - string public constant TRANSFER_AMOUNT_NOT_GT_0 = '30'; // 'Transferred amount needs to be greater than zero' - string public constant INTEREST_ALREADY_REDIRECTED = '31'; // 'Interest is already redirected to the user' - string public constant NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '32'; // 'Interest stream can only be redirected if there is a valid balance' + string public constant CALLER_MUST_BE_LENDING_POOL = '28'; // 'The caller of this function must be a lending pool' + string public constant INTEREST_REDIRECTION_NOT_ALLOWED = '29'; // 'Caller is not allowed to redirect the interest of the user' + 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 INTEREST_ALREADY_REDIRECTED = '32'; // 'Interest is already redirected to the user' + string public constant NO_VALID_BALANCE_FOR_REDIRECTION = '33'; // 'Interest stream can only be redirected if there is a valid balance' // require error messages - ReserveLogic - string public constant RESERVE_ALREADY_INITIALIZED = '33'; // 'Reserve has already been initialized' + string public constant RESERVE_ALREADY_INITIALIZED = '34'; // 'Reserve has already been initialized' //require error messages - LendingPoolConfiguration - string public constant CALLER_NOT_LENDING_POOL_MANAGER = '34'; // 'The caller must be a lending pool manager' - string public constant RESERVE_LIQUIDITY_NOT_0 = '35'; // 'The liquidity of the reserve needs to be 0' + string public constant CALLER_NOT_LENDING_POOL_MANAGER = '35'; // 'The caller must be a lending pool manager' + string public constant RESERVE_LIQUIDITY_NOT_0 = '36'; // 'The liquidity of the reserve needs to be 0' //require error messages - LendingPoolAddressesProviderRegistry - string public constant PROVIDER_NOT_REGISTERED = '36'; // 'Provider is not registered' + string public constant PROVIDER_NOT_REGISTERED = '37'; // 'Provider is not registered' //return error messages - LendingPoolLiquidationManager - string public constant HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '37'; // 'Health factor is not below the threshold' - string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '38'; // 'The collateral chosen cannot be liquidated' - string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '39'; // 'User did not borrow the specified currency' - string public constant NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '40'; // "There isn't enough liquidity available to liquidate" - string public constant NO_ERRORS = '41'; // 'No errors' + string public constant HEALTH_FACTOR_NOT_BELLOW_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' } diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 09a916e5..4541f489 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -145,7 +145,7 @@ library ValidationLogic { require( uint256(ReserveLogic.InterestRateMode.VARIABLE) == interestRateMode || uint256(ReserveLogic.InterestRateMode.STABLE) == interestRateMode, - Errors.INVALID_INTERESTRATE_MODE_SELECTED + Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); //check that the amount is available in the reserve @@ -245,7 +245,7 @@ library ValidationLogic { require( amountSent != uint256(-1) || msg.sender == onBehalfOf, - Errors.NO_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF + Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } @@ -290,7 +290,7 @@ library ValidationLogic { Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { - revert(Errors.INVALID_INTERESTRATE_MODE_SELECTED); + revert(Errors.INVALID_INTEREST_RATE_MODE_SELECTED); } } diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 2c6e8541..3ec3eac5 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -101,7 +101,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { function redirectInterestStreamOf(address from, address to) external override { require( msg.sender == _interestRedirectionAllowances[from], - Errors.NOT_ALLOWED_TO_REDIRECT_INTEREST + Errors.INTEREST_REDIRECTION_NOT_ALLOWED ); _redirectInterestStream(from, to); } @@ -494,7 +494,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 fromIndex ) = _cumulateBalance(from); - require(fromBalance > 0, Errors.NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM); + require(fromBalance > 0, Errors.NO_VALID_BALANCE_FOR_REDIRECTION); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous diff --git a/helpers/types.ts b/helpers/types.ts index e98e5a3c..fc3ca1d7 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -52,7 +52,7 @@ export enum ProtocolErrors { 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_INTERESTRATE_MODE_SELECTED = '8', // 'Invalid interest rate mode selected' + 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' @@ -60,7 +60,7 @@ export enum ProtocolErrors { 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_EPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16', // 'To repay on behalf of an user an explicit amount to repay is needed' + 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' @@ -68,36 +68,37 @@ export enum ProtocolErrors { // require error messages - LendingPool NOT_ENOUGH_STABLE_BORROW_BALANCE = '21', // 'User does not have any stable rate loan for this reserve' - INTERESTRATE_REBALANCE_CONDITIONS_NOT_MET = '22', // 'Interest rate rebalance conditions were not met' + 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_TO_SMALL = '25', // 'The requested amount is too small for a FlashLoan.' + 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' // require error messages - aToken - CALLER_MUST_BE_LENDING_POOL = '27', // 'The caller of this function must be a lending pool' - NOT_ALLOWED_TO_REDIRECT_INTEREST = '28', // 'Caller is not allowed to redirect the interest of the user' - CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '29', // 'User cannot give allowance to himself' - TRANSFER_AMOUNT_NOT_GT_0 = '30', // 'Transferred amount needs to be greater than zero' - INTEREST_ALREADY_REDIRECTED = '31', // 'Interest is already redirected to the user' - NO_VALID_BALANCE_FOR_REDIRECT_INT_STREAM = '32', // 'Interest stream can only be redirected if there is a valid balance' + CALLER_MUST_BE_LENDING_POOL = '28', // 'The caller of this function must be a lending pool' + INTEREST_REDIRECTION_NOT_ALLOWED = '29', // 'Caller is not allowed to redirect the interest of the user' + 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' + INTEREST_ALREADY_REDIRECTED = '32', // 'Interest is already redirected to the user' + NO_VALID_BALANCE_FOR_REDIRECTION = '33', // 'Interest stream can only be redirected if there is a valid balance' // require error messages - ReserveLogic - RESERVE_ALREADY_INITIALIZED = '33', // 'Reserve has already been initialized' + RESERVE_ALREADY_INITIALIZED = '34', // 'Reserve has already been initialized' //require error messages - LendingPoolConfiguration - CALLER_NOT_LENDING_POOL_MANAGER = '34', // 'The caller must be a lending pool manager' - RESERVE_LIQUIDITY_NOT_0 = '35', // 'The liquidity of the reserve needs to be 0' + CALLER_NOT_LENDING_POOL_MANAGER = '35', // 'The caller must be a lending pool manager' + RESERVE_LIQUIDITY_NOT_0 = '36', // 'The liquidity of the reserve needs to be 0' //require error messages - LendingPoolAddressesProviderRegistry - PROVIDER_NOT_REGISTERED = '36', // 'Provider is not registered' + PROVIDER_NOT_REGISTERED = '37', // 'Provider is not registered' //return error messages - LendingPoolLiquidationManager - HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '37', // 'Health factor is not below the threshold' - COLLATERAL_CANNOT_BE_LIQUIDATED = '38', // 'The collateral chosen cannot be liquidated' - SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '39', // 'User did not borrow the specified currency' - NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '40', // "There isn't enough liquidity available to liquidate" - NO_ERRORS = '41', // 'No errors' + HEALTH_FACTOR_NOT_BELLOW_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' // old diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index dfd7be16..223ea890 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -12,7 +12,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; const { INCONSISTENT_PROTOCOL_ACTUAL_BALANCE, - REQUESTED_AMOUNT_TO_SMALL, + REQUESTED_AMOUNT_TOO_SMALL, NOT_ENOUGH_LIQUIDITY_TO_BORROW, } = ProtocolErrors; @@ -112,7 +112,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { '1', //1 wei loan '0x10' ) - ).to.be.revertedWith(REQUESTED_AMOUNT_TO_SMALL); + ).to.be.revertedWith(REQUESTED_AMOUNT_TOO_SMALL); }); it('tries to take a flashloan that is bigger than the available liquidity (revert expected)', async () => { From 07007fa933170fa622dc37a076031f6a816a15a1 Mon Sep 17 00:00:00 2001 From: pol <> Date: Thu, 3 Sep 2020 11:17:49 +0200 Subject: [PATCH 28/33] Fixed sintax errors --- contracts/lendingpool/LendingPoolLiquidationManager.sol | 2 +- contracts/libraries/helpers/Errors.sol | 2 +- helpers/types.ts | 2 +- test/liquidation-atoken.spec.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 27a29277..34cb6f38 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -133,7 +133,7 @@ contract LendingPoolLiquidationManager is ReentrancyGuard, VersionedInitializabl if (vars.healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(LiquidationErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), - Errors.HEALTH_FACTOR_NOT_BELLOW_THRESHOLD + Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index db239d1f..079d1b9f 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -57,7 +57,7 @@ library Errors { string public constant PROVIDER_NOT_REGISTERED = '37'; // 'Provider is not registered' //return error messages - LendingPoolLiquidationManager - string public constant HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '38'; // 'Health factor is not below the threshold' + 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" diff --git a/helpers/types.ts b/helpers/types.ts index fc3ca1d7..f17d5e9f 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -94,7 +94,7 @@ export enum ProtocolErrors { PROVIDER_NOT_REGISTERED = '37', // 'Provider is not registered' //return error messages - LendingPoolLiquidationManager - HEALTH_FACTOR_NOT_BELLOW_THRESHOLD = '38', // 'Health factor is not below the threshold' + 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" diff --git a/test/liquidation-atoken.spec.ts b/test/liquidation-atoken.spec.ts index 155b7c25..921114f0 100644 --- a/test/liquidation-atoken.spec.ts +++ b/test/liquidation-atoken.spec.ts @@ -13,7 +13,7 @@ const {expect} = chai; makeSuite('LendingPool liquidation - liquidator receiving aToken', (testEnv) => { const { - HEALTH_FACTOR_NOT_BELLOW_THRESHOLD, + HEALTH_FACTOR_NOT_BELOW_THRESHOLD, INVALID_HF, SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER, COLLATERAL_CANNOT_BE_LIQUIDATED, @@ -71,7 +71,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_BELLOW_THRESHOLD); + ).to.be.revertedWith(HEALTH_FACTOR_NOT_BELOW_THRESHOLD); }); it('LIQUIDATION - Drop the health factor below 1', async () => { From 16fc0d49711c39ab6d4a061f66ec2207c51bb515 Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 3 Sep 2020 15:17:46 +0200 Subject: [PATCH 29/33] Updated flashloans --- contracts/lendingpool/LendingPool.sol | 252 ++++++++---------- contracts/libraries/logic/ValidationLogic.sol | 10 + test/flashloan.spec.ts | 42 +-- 3 files changed, 131 insertions(+), 173 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 265b9ce6..aa483faf 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -153,21 +153,13 @@ contract LendingPool is VersionedInitializable, ILendingPool { emit Withdraw(asset, msg.sender, amount); } - struct BorrowLocalVars { - address asset; - address user; - uint256 amount; - uint256 interestRateMode; - bool releaseUnderlying; - uint16 referralCode; - } - /** * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower * already deposited enough collateral. * @param asset the address of the reserve * @param amount the amount to be borrowed * @param interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) + * @param referralCode a referral code for integrators **/ function borrow( address asset, @@ -176,71 +168,15 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint16 referralCode ) external override { _executeBorrow( - BorrowLocalVars(asset, msg.sender, amount, interestRateMode, true, referralCode) - ); - } - - /** - * @dev Internal function to execute a borrowing action, allowing to transfer or not the underlying - * @param vars Input struct for the borrowing action, in order to avoid STD errors - **/ - function _executeBorrow(BorrowLocalVars memory vars) internal { - ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; - UserConfiguration.Map storage userConfig = _usersConfig[vars.user]; - - address oracle = _addressesProvider.getPriceOracle(); - uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( - 10**reserve.configuration.getDecimals() - ); - - ValidationLogic.validateBorrow( - reserve, - vars.asset, - vars.amount, - amountInETH, - vars.interestRateMode, - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - _usersConfig[vars.user], - _reservesList, - oracle - ); - - //caching the current stable borrow rate - uint256 userStableRate = reserve.currentStableBorrowRate; - - reserve.updateCumulativeIndexesAndTimestamp(); - - if ( - ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ) { - IStableDebtToken(reserve.stableDebtTokenAddress).mint(vars.user, vars.amount, userStableRate); - } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount); - } - - address aToken = reserve.aTokenAddress; - reserve.updateInterestRates(vars.asset, aToken, 0, vars.amount); - - uint256 reserveIndex = reserve.index; - if (!userConfig.isBorrowing(reserveIndex)) { - userConfig.setBorrowing(reserveIndex, true); - } - - //if we reached this point and we need to, we can transfer - if (vars.releaseUnderlying) { - IAToken(aToken).transferUnderlyingTo(vars.user, vars.amount); - } - - emit Borrow( - vars.asset, - vars.user, - vars.amount, - vars.interestRateMode, - ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ? userStableRate - : reserve.currentVariableBorrowRate, - vars.referralCode + ExecuteBorrowParams( + asset, + msg.sender, + amount, + interestRateMode, + _reserves[asset].aTokenAddress, + referralCode, + true + ) ); } @@ -396,10 +332,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param asset the address of the reserve * @param useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/ - function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) - external - override - { + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override { ReserveLogic.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( @@ -473,13 +406,13 @@ contract LendingPool is VersionedInitializable, ILendingPool { } /** - * @dev allows smartcontracts to access the liquidity of the pool within one transaction, + * @dev allows smart contracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts * that must be kept into consideration. For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param asset The address of the principal reserve * @param amount The amount requested for this flashloan - * @param debtType 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 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 params Variadic packed params to pass to the receiver as extra information * @param referralCode Referral code of the flash loan **/ @@ -487,7 +420,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { address receiverAddress, address asset, uint256 amount, - uint256 debtType, + uint256 mode, bytes calldata params, uint16 referralCode ) external override { @@ -498,13 +431,12 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.premium = amount.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000); - require(vars.premium > 0, 'The requested amount is too small for a FlashLoan.'); + ReserveLogic.InterestRateMode debtMode = ReserveLogic.InterestRateMode(mode); + + ValidationLogic.validateFlashloan(debtMode, vars.premium); vars.receiver = IFlashLoanReceiver(receiverAddress); - // Update of the indexes until the current moment - reserve.updateCumulativeIndexesAndTimestamp(); - //transfer funds to the receiver IAToken(vars.aTokenAddress).transferUnderlyingTo(receiverAddress, amount); @@ -513,60 +445,30 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.amountPlusPremium = amount.add(vars.premium); - if (debtType == 0) { // To not fetch balance/allowance if no debt needs to be opened + if (debtMode == ReserveLogic.InterestRateMode.NONE) { + IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); + + reserve.updateCumulativeIndexesAndTimestamp(); reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); reserve.updateInterestRates(asset, vars.aTokenAddress, vars.premium, 0); + + emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); + } else { - vars.receiverBalance = IERC20(asset).balanceOf(receiverAddress); - vars.receiverAllowance = IERC20(asset).allowance(receiverAddress, address(this)); - if (vars.receiverBalance >= vars.amountPlusPremium && vars.receiverAllowance >= vars.amountPlusPremium) { - IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); - reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); - reserve.updateInterestRates(asset, vars.aTokenAddress, vars.premium, 0); - } else { - if (debtType == 1 || debtType == 2) { - // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. - // We will try to pull all the available funds from the receiver and create a debt position with the rest owed - // if it has collateral enough - vars.availableBalance = (vars.receiverBalance > vars.receiverAllowance) - ? vars.receiverAllowance - : vars.receiverBalance; - - if (vars.availableBalance > 0) { - // If not enough premium, include as premium all the funds available to pull - if (vars.availableBalance < vars.premium) { - vars.premium = vars.availableBalance; - } - IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.availableBalance); - reserve.cumulateToLiquidityIndex( - IERC20(vars.aTokenAddress).totalSupply(), - vars.premium - ); - reserve.updateInterestRates( - asset, - vars.aTokenAddress, - vars.premium, - 0 - ); - } - - _executeBorrow( - BorrowLocalVars( - asset, - msg.sender, - vars.amountPlusPremium.sub(vars.availableBalance), - debtType, - false, - referralCode - ) - ); - } else { - revert("INSUFFICIENT_FUNDS_TO_PULL"); - } - } + // If the transfer didn't succeed, the receiver either didn't return the funds, or didn't approve the transfer. + _executeBorrow( + ExecuteBorrowParams( + asset, + msg.sender, + vars.amountPlusPremium.sub(vars.availableBalance), + mode, + vars.aTokenAddress, + referralCode, + false + ) + ); } - emit FlashLoan(receiverAddress, asset, amount, vars.premium, referralCode); } /** @@ -783,9 +685,89 @@ contract LendingPool is VersionedInitializable, ILendingPool { return _reserves[asset].configuration; } + // internal functions + + struct ExecuteBorrowParams { + address asset; + address user; + uint256 amount; + uint256 interestRateMode; + address aTokenAddress; + uint16 referralCode; + bool releaseUnderlying; + } + /** - * @notice internal functions + * @dev Internal function to execute a borrowing action, allowing to transfer or not the underlying + * @param vars Input struct for the borrowing action, in order to avoid STD errors **/ + function _executeBorrow(ExecuteBorrowParams memory vars) internal { + ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; + UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; + + address oracle = _addressesProvider.getPriceOracle(); + + uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( + 10**reserve.configuration.getDecimals() + ); + + ValidationLogic.validateBorrow( + reserve, + vars.asset, + vars.amount, + amountInETH, + vars.interestRateMode, + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + userConfig, + _reservesList, + oracle + ); + + + uint256 reserveIndex = reserve.index; + if (!userConfig.isBorrowing(reserveIndex)) { + userConfig.setBorrowing(reserveIndex, true); + } + + + reserve.updateCumulativeIndexesAndTimestamp(); + + //caching the current stable borrow rate + uint256 currentStableRate = 0; + + if ( + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ) { + currentStableRate = reserve.currentStableBorrowRate; + + IStableDebtToken(reserve.stableDebtTokenAddress).mint( + vars.user, + vars.amount, + currentStableRate + ); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount); + } + + reserve.updateInterestRates(vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0); + + if(vars.releaseUnderlying){ + IAToken(vars.aTokenAddress).transferUnderlyingTo(msg.sender, vars.amount); + } + + + emit Borrow( + vars.asset, + msg.sender, + vars.amount, + vars.interestRateMode, + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ? currentStableRate + : reserve.currentVariableBorrowRate, + vars.referralCode + ); + } /** * @dev adds a reserve to the array of the _reserves address diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index dd3ef25a..b4edbf2d 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -324,4 +324,14 @@ library ValidationLogic { 'User deposit is already being used as collateral' ); } + + /** + * @dev validates a flashloan action + * @param mode the flashloan mode (NONE = classic flashloan, STABLE = open a stable rate loan, VARIABLE = open a variable rate loan) + * @param premium the premium paid on the flashloan + **/ + function validateFlashloan(ReserveLogic.InterestRateMode mode, uint256 premium) internal pure { + require(premium > 0, 'The requested amount is too small for a FlashLoan.'); + require(mode <= ReserveLogic.InterestRateMode.VARIABLE, 'Invalid flashloan mode selected'); + } } diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 93cb2fcd..ced409e2 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -36,14 +36,14 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await pool.deposit(weth.address, amountToDeposit, '0'); }); - it('Takes ETH flashloan, returns the funds correctly', async () => { + it('Takes WETH flashloan, returns the funds correctly', async () => { const {pool, deployer, weth} = testEnv; await pool.flashLoan( _mockFlashLoanReceiver.address, weth.address, ethers.utils.parseEther('0.8'), - 2, + 0, '0x10', '0' ); @@ -72,7 +72,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, weth.address, '1000720000000000000', - 2, + 0, '0x10', '0' ); @@ -209,7 +209,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, usdc.address, flashloanAmount, - 2, + 0, '0x10', '0' ); @@ -283,40 +283,6 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(callerDebt.toString()).to.be.equal('500450000', 'Invalid user debt'); }); - it('Caller deposits 5 ETH as collateral, Takes a USDC flashloan, approves only partially funds. A loan for caller is created', async () => { - const {usdc, pool, weth, users} = testEnv; - - const caller = users[3]; - - await weth.connect(caller.signer).mint(await convertToCurrencyDecimals(weth.address, '5')); - - await weth.connect(caller.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL); - - const amountToDeposit = await convertToCurrencyDecimals(weth.address, '5'); - - await pool.connect(caller.signer).deposit(weth.address, amountToDeposit, '0'); - - const flashloanAmount = await convertToCurrencyDecimals(usdc.address, '500'); - - await _mockFlashLoanReceiver.setFailExecutionTransfer(false); - - await _mockFlashLoanReceiver.setAmountToApprove(flashloanAmount.div(2)); - - await pool - .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, usdc.address, flashloanAmount, 2, '0x10', '0'); - const {variableDebtTokenAddress} = await pool.getReserveTokensAddresses(usdc.address); - - const usdcDebtToken = await getContract( - eContractid.VariableDebtToken, - variableDebtTokenAddress - ); - - const callerDebt = await usdcDebtToken.balanceOf(caller.address); - - expect(callerDebt.toString()).to.be.equal('250450000', 'Invalid user debt'); - }); - it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds and selects revert as result', async () => { const {dai, pool, weth, users} = testEnv; From 1486cee7749f962a37da1d7a8535e2c475aa090f Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 3 Sep 2020 15:53:18 +0200 Subject: [PATCH 30/33] Fixed tests on flashloan --- test/flashloan.spec.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index aaa0fcb7..063adc96 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -36,7 +36,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await pool.deposit(weth.address, amountToDeposit, '0'); }); - it('Takes WETH flashloan, returns the funds correctly', async () => { + it('Takes WETH flashloan with mode = 0, returns the funds correctly', async () => { const {pool, deployer, weth} = testEnv; await pool.flashLoan( @@ -64,7 +64,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentLiquidityIndex.toString()).to.be.equal('1000720000000000000000000000'); }); - it('Takes an ETH flashloan as big as the available liquidity', async () => { + it('Takes an ETH flashloan with mode = 0 as big as the available liquidity', async () => { const {pool, weth} = testEnv; const reserveDataBefore = await pool.getReserveData(weth.address); @@ -91,7 +91,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentLiquidityIndex.toString()).to.be.equal('1001620648000000000000000000'); }); - it('Takes WETH flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { + it('Takes WETH flashloan, does not return the funds with mode = 0. (revert expected)', async () => { const {pool, weth, users} = testEnv; const caller = users[1]; await _mockFlashLoanReceiver.setFailExecutionTransfer(true); @@ -107,10 +107,10 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { '0x10', '0' ) - ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); + ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); - it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds. A loan for caller is created', async () => { + 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 () => { const {dai, pool, weth, users} = testEnv; const caller = users[1]; @@ -236,7 +236,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentUserBalance.toString()).to.be.equal(expectedLiquidity, 'Invalid user balance'); }); - it('Takes out a 500 USDC flashloan, does not return the funds. Caller does not have any collateral (revert expected)', async () => { + it('Takes out a 500 USDC flashloan with mode = 0, does not return the funds. Caller does not have any collateral (revert expected)', async () => { const {usdc, pool, users} = testEnv; const caller = users[2]; From 48438f59f5d2b98e1a8c770fd9968835984a737c Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 3 Sep 2020 16:29:14 +0200 Subject: [PATCH 31/33] Added a new test to check an invalid interest rate mode --- contracts/lendingpool/LendingPool.sol | 5 +++-- contracts/libraries/logic/ValidationLogic.sol | 6 ++--- helpers/types.ts | 1 + test/flashloan.spec.ts | 22 ++++++++++++++++++- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 503612f6..47a260d6 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -435,9 +435,10 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.premium = amount.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000); - ReserveLogic.InterestRateMode debtMode = ReserveLogic.InterestRateMode(mode); - ValidationLogic.validateFlashloan(debtMode, vars.premium); + ValidationLogic.validateFlashloan(mode, vars.premium); + + ReserveLogic.InterestRateMode debtMode = ReserveLogic.InterestRateMode(mode); vars.receiver = IFlashLoanReceiver(receiverAddress); diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 4d9649e5..7a640458 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -322,11 +322,11 @@ library ValidationLogic { /** * @dev validates a flashloan action - * @param mode the flashloan mode (NONE = classic flashloan, STABLE = open a stable rate loan, VARIABLE = open a variable rate loan) + * @param mode the flashloan mode (0 = classic flashloan, 1 = open a stable rate loan, 2 = open a variable rate loan) * @param premium the premium paid on the flashloan **/ - function validateFlashloan(ReserveLogic.InterestRateMode mode, uint256 premium) internal pure { + function validateFlashloan(uint256 mode, uint256 premium) internal pure { require(premium > 0, Errors.REQUESTED_AMOUNT_TOO_SMALL); - require(mode <= ReserveLogic.InterestRateMode.VARIABLE, Errors.INVALID_FLASHLOAN_MODE); + require(mode <= uint256(ReserveLogic.InterestRateMode.VARIABLE), Errors.INVALID_FLASHLOAN_MODE); } } diff --git a/helpers/types.ts b/helpers/types.ts index 60edd765..7757bc45 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -99,6 +99,7 @@ export enum ProtocolErrors { 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 // old diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 063adc96..87e31b8d 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -18,7 +18,8 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const { COLLATERAL_BALANCE_IS_0, REQUESTED_AMOUNT_TOO_SMALL, - TRANSFER_AMOUNT_EXCEEDS_BALANCE + TRANSFER_AMOUNT_EXCEEDS_BALANCE, + INVALID_FLASHLOAN_MODE } = ProtocolErrors; before(async () => { @@ -110,6 +111,25 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ).to.be.revertedWith(TRANSFER_AMOUNT_EXCEEDS_BALANCE); }); + it('Takes a WETH flashloan with an invalid mode. (revert expected)', async () => { + const {pool, weth, users} = testEnv; + const caller = users[1]; + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); + + await expect( + pool + .connect(caller.signer) + .flashLoan( + _mockFlashLoanReceiver.address, + weth.address, + ethers.utils.parseEther('0.8'), + 4, + '0x10', + '0' + ) + ).to.be.revertedWith(INVALID_FLASHLOAN_MODE); + }); + 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 () => { const {dai, pool, weth, users} = testEnv; From bb822035a863b42b3b58631218dce39b99d61ad5 Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 3 Sep 2020 18:14:39 +0200 Subject: [PATCH 32/33] Added further test on flashloan for stable rate borrowing --- test/flashloan.spec.ts | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 87e31b8d..8ef3f4e8 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -10,6 +10,7 @@ import {MockFlashLoanReceiver} from '../types/MockFlashLoanReceiver'; import {ProtocolErrors, eContractid} from '../helpers/types'; import BigNumber from 'bignumber.js'; import {VariableDebtToken} from '../types/VariableDebtToken'; +import {StableDebtToken} from '../types/StableDebtToken'; const {expect} = require('chai'); @@ -256,7 +257,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(currentUserBalance.toString()).to.be.equal(expectedLiquidity, 'Invalid user balance'); }); - it('Takes out a 500 USDC flashloan with mode = 0, does not return the funds. Caller does not have any collateral (revert expected)', async () => { + it('Takes out a 500 USDC flashloan with mode = 0, does not return the funds. (revert expected)', async () => { const {usdc, pool, users} = testEnv; const caller = users[2]; @@ -271,7 +272,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { ).to.be.revertedWith(COLLATERAL_BALANCE_IS_0); }); - it('Caller deposits 5 ETH as collateral, Takes a USDC flashloan, does not return the funds. A loan for caller is created', async () => { + 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 () => { const {usdc, pool, weth, users} = testEnv; const caller = users[2]; @@ -303,7 +304,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { expect(callerDebt.toString()).to.be.equal('500450000', 'Invalid user debt'); }); - it('Caller deposits 1000 DAI as collateral, Takes WETH flashloan, does not return the funds and selects revert as result', async () => { + it('Caller deposits 1000 DAI as collateral, Takes a WETH flashloan with mode = 0, does not approve the transfer of the funds', async () => { const {dai, pool, weth, users} = testEnv; const caller = users[3]; @@ -327,4 +328,30 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { .flashLoan(_mockFlashLoanReceiver.address, weth.address, flashAmount, 0, '0x10', '0') ).to.be.revertedWith('ERC20: transfer amount exceeds allowance'); }); + + it('Caller takes a WETH flashloan with mode = 1', async () => { + const {dai, pool, weth, users} = testEnv; + + const caller = users[3]; + + const flashAmount = ethers.utils.parseEther('0.8'); + + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); + + await pool + .connect(caller.signer) + .flashLoan(_mockFlashLoanReceiver.address, weth.address, flashAmount, 1, '0x10', '0'); + + const {stableDebtTokenAddress} = await pool.getReserveTokensAddresses(weth.address); + + const wethDebtToken = await getContract( + eContractid.VariableDebtToken, + stableDebtTokenAddress + ); + + const callerDebt = await wethDebtToken.balanceOf(caller.address); + + expect(callerDebt.toString()).to.be.equal('800720000000000000', 'Invalid user debt'); + + }); }); From 78d9d4af74985c55c42bdfa3c6491c9c0cec0f0b Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 3 Sep 2020 18:25:50 +0200 Subject: [PATCH 33/33] Removed space --- contracts/lendingpool/LendingPool.sol | 1 - 1 file changed, 1 deletion(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 47a260d6..1cd4bc55 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -435,7 +435,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { vars.premium = amount.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000); - ValidationLogic.validateFlashloan(mode, vars.premium); ReserveLogic.InterestRateMode debtMode = ReserveLogic.InterestRateMode(mode);