From 224712f9d5cee8b4a4c37af6b4a5d0ee46b540bd Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Thu, 15 Oct 2020 00:59:12 +0300 Subject: [PATCH 01/22] Aave integration - first step --- contracts/tokenization/StableDebtToken.sol | 2 +- runUserConfigCLI.sh | 1 + runVariableTokenCLI.sh | 1 + specs/StableDebtToken.spec | 165 +++++++++++++ specs/UserConfiguration.spec | 66 +++++ specs/VariableDebtToken.spec | 173 +++++++++++++ specs/harness/LendingPoolHarness.sol | 273 +++++++++++++++++++++ specs/harness/StableDebtTokenHarness.sol | 31 +++ specs/harness/UserConfigurationHarness.sol | 78 ++++++ 9 files changed, 789 insertions(+), 1 deletion(-) create mode 100644 runUserConfigCLI.sh create mode 100644 runVariableTokenCLI.sh create mode 100644 specs/StableDebtToken.spec create mode 100644 specs/UserConfiguration.spec create mode 100644 specs/VariableDebtToken.spec create mode 100644 specs/harness/LendingPoolHarness.sol create mode 100644 specs/harness/StableDebtTokenHarness.sol create mode 100644 specs/harness/UserConfigurationHarness.sol diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 160d0f88..e0f48836 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -280,7 +280,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { * @param avgRate the average rate at which calculate the total supply * @return The debt balance of the user since the last burn/mint action **/ - function _calcTotalSupply(uint256 avgRate) internal view returns(uint256) { + function _calcTotalSupply(uint256 avgRate) internal virtual view returns(uint256) { // Certora: Added virtual modifier uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { diff --git a/runUserConfigCLI.sh b/runUserConfigCLI.sh new file mode 100644 index 00000000..f3ddbacc --- /dev/null +++ b/runUserConfigCLI.sh @@ -0,0 +1 @@ +certoraRun specs/harness/UserConfigurationHarness.sol --solc solc6.8 --verify UserConfigurationHarness:specs/UserConfiguration.spec --settings -useBitVectorTheory --staging master diff --git a/runVariableTokenCLI.sh b/runVariableTokenCLI.sh new file mode 100644 index 00000000..2b7abdc4 --- /dev/null +++ b/runVariableTokenCLI.sh @@ -0,0 +1 @@ +certoraRun contracts/tokenization/VariableDebtToken.sol:VariableDebtToken specs/harness/LendingPoolHarness.sol --solc solc6.8 --link VariableDebtToken:POOL=LendingPoolHarness --verify VariableDebtToken:specs/VariableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache VariableDebtToken --staging master \ No newline at end of file diff --git a/specs/StableDebtToken.spec b/specs/StableDebtToken.spec new file mode 100644 index 00000000..fba0f8ba --- /dev/null +++ b/specs/StableDebtToken.spec @@ -0,0 +1,165 @@ +methods { + getUserLastUpdated(address) returns uint40 envfree +} + +ghost ghostSupply() returns uint256; + +hook Sstore (slot 0)[address a] uint256 balance (uint256 old_balance) STORAGE { + require old_balance <= ghostSupply(); + havoc ghostSupply assuming ghostSupply@new() == ghostSupply@old() + (balance - old_balance); +} + +rule integrityTimeStamp(address user, method f) { + env e; + require sinvoke getIncentivesController(e) == 0; + require getUserLastUpdated(user) <= e.block.timestamp; + calldataarg arg; + sinvoke f(e,arg); + assert getUserLastUpdated(user) <= e.block.timestamp; +} + +rule totalSupplyInvariant(method f) { + env e; + require sinvoke getIncentivesController(e) == 0; + require totalSupply(e) == ghostSupply(); + calldataarg arg; + sinvoke f(e, arg); + assert totalSupply(e) == ghostSupply(); +} + +/** +TotalSupply is the sum of all users’ balances + +totalSupply(t) = Σaddress u. balanceOf(u,t) + +Check that each possible opertaion changes the balance of at most one user +*/ +rule balanceOfChange(address a, address b, method f ) +{ + env e; + require a!=b; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 balanceBBefore = sinvoke balanceOf(e,b); + + calldataarg arg; + sinvoke f(e, arg); + + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 balanceBAfter = sinvoke balanceOf(e,b); + + assert ( balanceABefore == balanceAAfter || balanceBBefore == balanceBAfter ); +} + +/** +Check that the change to total supply is coherent with the changes to balance +*/ +rule integirtyBalanceOfTotalSupply(address a, method f ) +{ + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 totalSupplyBefore = sinvoke totalSupply(e); + + calldataarg arg; + sinvoke f(e, arg); + require (f.selector != burn(address,uint256).selector ); + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 totalSupplyAfter = sinvoke totalSupply(e); + + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/* Burn behaves differently and due to accumulation errors might have less total supply than the balance +*/ +rule integirtyBalanceOfTotalSupplyOnBurn(address a, method f) +{ + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 balanceABefore = sinvoke balanceOf(e,a); + uint256 totalSupplyBefore = sinvoke totalSupply(e); + + uint256 x; + sinvoke burn(e, a, x); + uint256 balanceAAfter = sinvoke balanceOf(e,a); + uint256 totalSupplyAfter = sinvoke totalSupply(e); + if (totalSupplyBefore > x) + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); + else + assert (totalSupplyAfter == 0 ); +} + +/** +Mint inceases the balanceOf user a as expected +*/ +rule integrityMint(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke mint(e,a,x,index); + + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balanceAfter == balancebefore+x; +} + +/** +Mint is additive, can performed either all at once or gradually +mint(u,x); mint(u,y) ~ mint(u,x+y) at the same timestamp +*/ +rule additiveMint(address a, uint256 x, uint256 y) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + storage initialStorage = lastStorage; + sinvoke mint(e,a,x,index); + sinvoke mint(e,a,y,index); + uint256 balanceScenario1 = sinvoke balanceOf(e,a); + uint t = x + y; + sinvoke mint(e,a, t ,index) at initialStorage; + + uint256 balanceScenario2 = sinvoke balanceOf(e,a); + assert balanceScenario1 == balanceScenario2, "mint is not additive"; +} + +rule integrityBurn(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke burn(e,a,x); + + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balanceAfter == balancebefore - x; +} + +rule additiveBurn(address a, uint256 x, uint256 y) { + env e; + require sinvoke getIncentivesController(e) == 0; + storage initialStorage = lastStorage; + sinvoke burn(e, a, x); + sinvoke burn(e, a, y); + uint256 balanceScenario1 = balanceOf(e, a); + uint t = x + y; + sinvoke burn(e, a, t) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "burn is not additive"; +} + + +/** +mint and burn are inverse operations +Thus, totalSupply is back to initial state +BalanceOf user is back to initial state */ +rule inverseMintBurn(address a, uint256 x) { + env e; + require sinvoke getIncentivesController(e) == 0; + uint256 index; + uint256 balancebefore = sinvoke balanceOf(e,a); + sinvoke mint(e,a,x,index); + sinvoke burn(e,a,x); + uint256 balanceAfter = sinvoke balanceOf(e,a); + assert balancebefore == balanceAfter, "burn is not inverse of mint"; +} + diff --git a/specs/UserConfiguration.spec b/specs/UserConfiguration.spec new file mode 100644 index 00000000..14fce3a6 --- /dev/null +++ b/specs/UserConfiguration.spec @@ -0,0 +1,66 @@ +methods { + setBorrowing(address, uint256, bool) envfree + setUsingAsCollateral(address, uint256, bool) envfree + isUsingAsCollateralOrBorrowing(address, uint256) returns bool envfree + isBorrowing(address, uint256) returns bool envfree + isUsingAsCollateral(address, uint256) returns bool envfree + isBorrowingAny(address ) returns bool envfree + isEmpty(address ) returns bool envfree +} + +invariant empty(address user, uint256 reserveIndex ) + isEmpty(user) => !isBorrowingAny(user) && !isUsingAsCollateralOrBorrowing(user, reserveIndex) + +invariant notEmpty(address user, uint256 reserveIndex ) + ( isBorrowingAny(user) || isUsingAsCollateral(user, reserveIndex)) => !isEmpty(user) + + +invariant borrowing(address user, uint256 reserveIndex ) + isBorrowing(user, reserveIndex) => isBorrowingAny(user) + +invariant collateralOrBorrowing(address user, uint256 reserveIndex ) + ( isUsingAsCollateral(user, reserveIndex) || isBorrowing(user, reserveIndex) ) <=> isUsingAsCollateralOrBorrowing(user, reserveIndex) + + + +rule setBorrowing(address user, uint256 reserveIndex, bool borrowing) +{ + require reserveIndex < 128; + + setBorrowing(user, reserveIndex, borrowing); + assert isBorrowing(user, reserveIndex) == borrowing, "unexpected result"; +} + +rule setBorrowingNoChangeToOther(address user, uint256 reserveIndex, uint256 reserveIndexOther, bool borrowing) +{ + require reserveIndexOther != reserveIndex; + require reserveIndexOther < 128 && reserveIndex < 128; + bool otherReserveBorrowing = isBorrowing(user, reserveIndexOther); + bool otherReserveCollateral = isUsingAsCollateral(user,reserveIndexOther); + + setBorrowing(user, reserveIndex, borrowing); + assert otherReserveBorrowing == isBorrowing(user, reserveIndexOther) && + otherReserveCollateral == isUsingAsCollateral(user,reserveIndexOther), "changed to other reserve"; +} + + +rule setUsingAsCollateral(address user, uint256 reserveIndex, bool usingAsCollateral) +{ + require reserveIndex < 128; + + setUsingAsCollateral(user, reserveIndex, usingAsCollateral); + assert isUsingAsCollateral(user, reserveIndex) == usingAsCollateral, "unexpected result"; +} + + +rule setUsingAsCollateralNoChangeToOther(address user, uint256 reserveIndex, uint256 reserveIndexOther, bool usingAsCollateral) +{ + require reserveIndexOther != reserveIndex; + require reserveIndexOther < 128 && reserveIndex < 128; + bool otherReserveBorrowing = isBorrowing(user, reserveIndexOther); + bool otherReserveCollateral = isUsingAsCollateral(user,reserveIndexOther); + + setUsingAsCollateral(user, reserveIndex, usingAsCollateral); + assert otherReserveBorrowing == isBorrowing(user, reserveIndexOther) && + otherReserveCollateral == isUsingAsCollateral(user,reserveIndexOther), "changed to other reserve"; +} diff --git a/specs/VariableDebtToken.spec b/specs/VariableDebtToken.spec new file mode 100644 index 00000000..854ee9d7 --- /dev/null +++ b/specs/VariableDebtToken.spec @@ -0,0 +1,173 @@ +using LendingPoolHarness as POOL +/** +TotalSupply is the sum of all users’ balances + +totalSupply(t) = Σaddress u. balanceOf(u,t) + +Check that each possible opertaion changes the balance of at most one user +*/ +rule balanceOfChange(address a, address b, method f) +{ + env e; + require a!=b ; + uint256 balanceABefore = sinvoke balanceOf(e, a); + uint256 balanceBBefore = sinvoke balanceOf(e, b); + + calldataarg arg; + sinvoke f(e, arg); + + uint256 balanceAAfter = sinvoke balanceOf(e, a); + uint256 balanceBAfter = sinvoke balanceOf(e, b); + + assert ( balanceABefore == balanceAAfter || balanceBBefore == balanceBAfter ); +} + +/* +Check that the changed to total supply is coherent with the changes to balance +*/ + +rule integirtyBalanceOfTotalSupply(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + calldataarg arg; + sinvoke f(e, arg); + require (f.selector != burn(address, uint256, uint256).selector && + f.selector != mint(address, uint256, uint256).selector ) ; + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/* Burn behaves deferently and due to accumulation errors might hace less total supply then the balance +*/ + +rule integirtyBalanceOfTotalSupplyOnBurn(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + uint256 x; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + sinvoke burn(e, a, x, index); + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +rule integirtyBalanceOfTotalSupplyOnMint(address a, method f ) +{ + env e; + + uint256 balanceABefore = balanceOf(e, a); + uint256 totalSupplyBefore = totalSupply(e); + + uint256 x; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + sinvoke mint(e, a, x, index); + uint256 balanceAAfter = balanceOf(e, a); + uint256 totalSupplyAfter = totalSupply(e); + assert (balanceAAfter != balanceABefore => ( balanceAAfter - balanceABefore == totalSupplyAfter - totalSupplyBefore)); +} + +/** +Minting an amount of x tokens for user u increases their balance by x, up to rounding errors. +{ b= balanceOf(u,t) } +mint(u,x,index) +{ balanceOf(u,t) = b + x } + +*/ +rule integrityMint(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e,asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke mint(e, a, x, index); + + uint256 balanceAfter = balanceOf(e, a); + assert balanceAfter == balancebefore+x; +} + +/** +Mint is additive, can performed either all at once or gradually +mint(u,x); mint(u,y) ~ mint(u,x+y) at the same timestamp +*/ +rule additiveMint(address a, uint256 x, uint256 y) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + storage initialStorage = lastStorage; + sinvoke mint(e, a, x, index); + sinvoke mint(e, a, y, index); + uint256 balanceScenario1 = balanceOf(e, a); + uint t = x + y; + sinvoke mint(e, a, t ,index) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "mint is not additive"; +} + +/** +Transfer of x amount of tokens from user u where receiver is user u’ +{bu = balanceOf(u) } + burn(u, u’, x) +{balanceOf(u) = bu - x } +*/ +rule integrityBurn(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke burn(e, a, x, index); + + uint256 balanceAfter = balanceOf(e, a); + assert balanceAfter == balancebefore - x; +} +/** +Minting is additive, i.e., it can be performed either all at once or in steps. + +burn(u, u’, x); burn(u, u’, y) ~ burn(u, u’, x+y) +*/ +rule additiveBurn(address a, uint256 x, uint256 y) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + storage initialStorage = lastStorage; + sinvoke burn(e, a, x, index); + sinvoke burn(e, a, y, index); + uint256 balanceScenario1 = balanceOf(e, a); + uint t = x + y; + sinvoke burn(e, a, t ,index) at initialStorage; + + uint256 balanceScenario2 = balanceOf(e, a); + assert balanceScenario1 == balanceScenario2, "burn is not additive"; +} + +/** +Minting and burning are inverse operations. + +{bu = balanceOf(u) } +mint(u,x); burn(u, u, x) + {balanceOf(u) = bu } +*/ +rule inverseMintBurn(address a, uint256 x) { + env e; + address asset; + uint256 index = POOL.getReserveNormalizedVariableDebt(e, asset); + uint256 balancebefore = balanceOf(e, a); + sinvoke mint(e, a, x, index); + sinvoke burn(e, a, x, index); + uint256 balanceAfter = balanceOf(e, a); + assert balancebefore == balanceAfter, "burn is not inverse of mint"; +} + + + diff --git a/specs/harness/LendingPoolHarness.sol b/specs/harness/LendingPoolHarness.sol new file mode 100644 index 00000000..7c099ab2 --- /dev/null +++ b/specs/harness/LendingPoolHarness.sol @@ -0,0 +1,273 @@ +pragma solidity ^0.6.8; +pragma experimental ABIEncoderV2; + +import {ReserveConfiguration} from '../../contracts/libraries/configuration/ReserveConfiguration.sol'; +import {ILendingPool} from '../../contracts/interfaces/ILendingPool.sol'; +import {LendingPool} from '../../contracts/lendingpool/LendingPool.sol'; + +/* +Certora: Harness that delegates calls to the original LendingPool. +*/ +contract LendingPoolHarness is ILendingPool { + + LendingPool private originalPool; + + function deposit( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external override { + originalPool.deposit(asset, amount, onBehalfOf, referralCode); + } + + function withdraw(address asset, uint256 amount) external override { + originalPool.withdraw(asset, amount); + } + + function getBorrowAllowance( + address fromUser, + address toUser, + address asset, + uint256 interestRateMode + ) external override view returns (uint256) { + return originalPool.getBorrowAllowance(fromUser, toUser, asset, interestRateMode); + } + + function delegateBorrowAllowance( + address asset, + address user, + uint256 interestRateMode, + uint256 amount + ) external override { + originalPool.delegateBorrowAllowance(asset, user, interestRateMode, amount); + } + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external override { + originalPool.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf); + } + + function repay( + address asset, + uint256 amount, + uint256 rateMode, + address onBehalfOf + ) external override { + originalPool.repay(asset, amount, rateMode, onBehalfOf); + } + + function swapBorrowRateMode(address asset, uint256 rateMode) external override { + originalPool.swapBorrowRateMode(asset, rateMode); + } + + function rebalanceStableBorrowRate(address asset, address user) external override { + originalPool.rebalanceStableBorrowRate(asset, user); + } + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override { + originalPool.setUserUseReserveAsCollateral(asset, useAsCollateral); + } + + function liquidationCall( + address collateral, + address asset, + address user, + uint256 purchaseAmount, + bool receiveAToken + ) external override { + originalPool.liquidationCall(collateral, asset, user, purchaseAmount, receiveAToken); + } + + function repayWithCollateral( + address collateral, + address principal, + address user, + uint256 principalAmount, + address receiver, + bytes calldata params + ) external override { + originalPool.repayWithCollateral(collateral, principal, user, principalAmount, receiver, params); + } + + function flashLoan( + address receiverAddress, + address asset, + uint256 amount, + uint256 mode, + bytes calldata params, + uint16 referralCode + ) external override { + originalPool.flashLoan(receiverAddress, asset, amount, mode, params, referralCode); + } + + function swapLiquidity( + address receiverAddress, + address fromAsset, + address toAsset, + uint256 amountToSwap, + bytes calldata params + ) external override { + originalPool.swapLiquidity(receiverAddress, fromAsset, toAsset, amountToSwap, params); + } + + function getReserveConfigurationData(address asset) + external + override + view + returns ( + uint256 decimals, + uint256 ltv, + uint256 liquidationThreshold, + uint256 liquidationBonus, + uint256 reserveFactor, + address interestRateStrategyAddress, + bool usageAsCollateralEnabled, + bool borrowingEnabled, + bool stableBorrowRateEnabled, + bool isActive, + bool isFreezed + ) + { + return originalPool.getReserveConfigurationData(asset); + } + + function getReserveTokensAddresses(address asset) + external + override + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ) + { + return originalPool.getReserveTokensAddresses(asset); + } + + function getReserveData(address asset) + external + override + view + returns ( + uint256 availableLiquidity, + uint256 totalStableDebt, + uint256 totalVariableDebt, + uint256 liquidityRate, + uint256 variableBorrowRate, + uint256 stableBorrowRate, + uint256 averageStableBorrowRate, + uint256 liquidityIndex, + uint256 variableBorrowIndex, + uint40 lastUpdateTimestamp + ) + { + return originalPool.getReserveData(asset); + } + + function getUserAccountData(address user) + external + override + view + returns ( + uint256 totalCollateralETH, + uint256 totalBorrowsETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ) + { + return originalPool.getUserAccountData(user); + } + + function getUserReserveData(address asset, address user) + external + override + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ) + { + return originalPool.getUserReserveData(asset, user); + } + + function getReserves() external override view returns (address[] memory) { + return originalPool.getReserves(); + } + + function initReserve( + address asset, + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress + ) external override { + originalPool.initReserve(asset, aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress); + } + + function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) + external + override + { + originalPool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); + } + + function setConfiguration(address asset, uint256 configuration) external override { + originalPool.setConfiguration(asset, configuration); + } + + function getConfiguration(address asset) + external + override + view + returns (ReserveConfiguration.Map memory) + { + return originalPool.getConfiguration(asset); + } + + function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + return originalPool.getReserveNormalizedIncome(asset); + } + + mapping(uint256 => uint256) private reserveNormalizedVariableDebt; + + function getReserveNormalizedVariableDebt(address asset) + external + override + view + returns (uint256) + { + require(reserveNormalizedVariableDebt[block.timestamp] == 1e27); + return reserveNormalizedVariableDebt[block.timestamp]; + } + + function balanceDecreaseAllowed( + address asset, + address user, + uint256 amount + ) external override view returns (bool) { + return originalPool.balanceDecreaseAllowed(asset, user, amount); + } + + function setPause(bool val) external override { + originalPool.setPause(val); + } + + function paused() external override view returns (bool) { + return originalPool.paused(); + } +} \ No newline at end of file diff --git a/specs/harness/StableDebtTokenHarness.sol b/specs/harness/StableDebtTokenHarness.sol new file mode 100644 index 00000000..be2471be --- /dev/null +++ b/specs/harness/StableDebtTokenHarness.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.6.8; + +import {Context} from '@openzeppelin/contracts/GSN/Context.sol'; +import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; +import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; +import {StableDebtToken} from '../../contracts/tokenization/StableDebtToken.sol'; +import {IncentivizedERC20} from '../../contracts/tokenization/IncentivizedERC20.sol'; + +contract StableDebtTokenHarness is StableDebtToken { + + constructor( + address pool, + address underlyingAsset, + string memory name, + string memory symbol, + address incentivesController + ) public StableDebtToken(pool, underlyingAsset, name, symbol, incentivesController) {} + + function balanceOf(address account) public override view returns (uint256) { + return IncentivizedERC20.balanceOf(account); + } + + function _calcTotalSupply(uint256 avgRate) internal override view returns (uint256) { + return IncentivizedERC20.totalSupply(); + } + + function getIncentivesController() public view returns (address) { + return address(_incentivesController); + } + +} \ No newline at end of file diff --git a/specs/harness/UserConfigurationHarness.sol b/specs/harness/UserConfigurationHarness.sol new file mode 100644 index 00000000..03574a99 --- /dev/null +++ b/specs/harness/UserConfigurationHarness.sol @@ -0,0 +1,78 @@ +pragma solidity ^0.6.8; +pragma experimental ABIEncoderV2; + +import {UserConfiguration} from 'contracts/libraries/configuration/UserConfiguration.sol'; + + +/* +A wrapper contract for calling functions from the library UserConfiguration. +*/ +contract UserConfigurationHarness { + + UserConfiguration.Map internal usersConfig; + + function setBorrowing( + address user, + uint256 reserveIndex, + bool borrowing + ) public { + UserConfiguration.setBorrowing(usersConfig, reserveIndex, borrowing); + } + + function setUsingAsCollateral( + address user, + uint256 reserveIndex, + bool _usingAsCollateral + ) public { + UserConfiguration.setUsingAsCollateral(usersConfig, reserveIndex, _usingAsCollateral); + } + + function isUsingAsCollateralOrBorrowing( + address user, + uint256 reserveIndex) + public + view + returns (bool) { + return UserConfiguration.isUsingAsCollateralOrBorrowing(usersConfig, reserveIndex); + } + + function isBorrowing( + address user, + uint256 reserveIndex) + public + view + returns (bool) { + return UserConfiguration.isBorrowing(usersConfig, reserveIndex); + } + + function isUsingAsCollateral( + address user, + uint256 reserveIndex) + public + view + returns (bool) { + return UserConfiguration.isUsingAsCollateral(usersConfig, reserveIndex); + } + + function isBorrowingAny( + address user) + public + view + returns (bool) { + return UserConfiguration.isBorrowingAny(usersConfig); + } + + function isEmpty( + address user) + public + view + returns (bool) { + return UserConfiguration.isEmpty(usersConfig); + } + + /* + Mimics the original constructor of the contract. + */ + function init_state() public { } +} + From a2127a5b56ebdd78e29b22b9aac96b1e9fe67c1a Mon Sep 17 00:00:00 2001 From: Shelly Grossman Date: Mon, 19 Oct 2020 14:15:33 +0300 Subject: [PATCH 02/22] runner script for stable token --- runStableTokenCLI.sh | 1 + 1 file changed, 1 insertion(+) create mode 100644 runStableTokenCLI.sh diff --git a/runStableTokenCLI.sh b/runStableTokenCLI.sh new file mode 100644 index 00000000..658c7663 --- /dev/null +++ b/runStableTokenCLI.sh @@ -0,0 +1 @@ +certoraRun specs/harness/StableDebtTokenHarness.sol:StableDebtTokenHarness --solc solc6.8 --verify StableDebtTokenHarness:specs/StableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache StableDebtToken --staging master \ No newline at end of file From 3f714b9dc848d28d1753fd8a673038fda4f024ed Mon Sep 17 00:00:00 2001 From: eboado Date: Wed, 28 Oct 2020 11:48:55 +0100 Subject: [PATCH 03/22] - Fixed non-initialized availableLiquidity on validateBorrow() --- contracts/lendingpool/LendingPool.sol | 1 + contracts/libraries/logic/ValidationLogic.sol | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index c63ff348..b387f59f 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -844,6 +844,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ); ValidationLogic.validateBorrow( + vars.asset, reserve, vars.onBehalfOf, vars.amount, diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 947d84ea..08f0ba35 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -99,6 +99,7 @@ library ValidationLogic { /** * @dev validates a borrow. + * @param asset the address of the asset to borrow * @param reserve the reserve state from which the user is borrowing * @param userAddress the address of the user * @param amount the amount to be borrowed @@ -112,6 +113,7 @@ library ValidationLogic { */ function validateBorrow( + address asset, ReserveLogic.ReserveData storage reserve, address userAddress, uint256 amount, @@ -198,6 +200,8 @@ library ValidationLogic { Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY ); + vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); + //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); From a63e337222c6ccf17465d6240a6ed3e87e2d728e Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Thu, 29 Oct 2020 01:20:38 +0200 Subject: [PATCH 04/22] Updated spec harness and run.sh for VariableDebtToken contract --- runVariableTokenCLI.sh | 2 +- specs/VariableDebtToken.spec | 2 +- specs/harness/LendingPoolHarness.sol | 273 ------------------ ...LendingPoolHarnessForVariableDebtToken.sol | 193 +++++++++++++ 4 files changed, 195 insertions(+), 275 deletions(-) delete mode 100644 specs/harness/LendingPoolHarness.sol create mode 100644 specs/harness/LendingPoolHarnessForVariableDebtToken.sol diff --git a/runVariableTokenCLI.sh b/runVariableTokenCLI.sh index 2b7abdc4..483e152e 100644 --- a/runVariableTokenCLI.sh +++ b/runVariableTokenCLI.sh @@ -1 +1 @@ -certoraRun contracts/tokenization/VariableDebtToken.sol:VariableDebtToken specs/harness/LendingPoolHarness.sol --solc solc6.8 --link VariableDebtToken:POOL=LendingPoolHarness --verify VariableDebtToken:specs/VariableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache VariableDebtToken --staging master \ No newline at end of file +certoraRun contracts/tokenization/VariableDebtToken.sol:VariableDebtToken specs/harness/LendingPoolHarnessForVariableDebtToken.sol --solc solc6.8 --link VariableDebtToken:POOL=LendingPoolHarnessForVariableDebtToken --verify VariableDebtToken:specs/VariableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache VariableDebtToken --staging \ No newline at end of file diff --git a/specs/VariableDebtToken.spec b/specs/VariableDebtToken.spec index 854ee9d7..73e7e39c 100644 --- a/specs/VariableDebtToken.spec +++ b/specs/VariableDebtToken.spec @@ -1,4 +1,4 @@ -using LendingPoolHarness as POOL +using LendingPoolHarnessForVariableDebtToken as POOL /** TotalSupply is the sum of all users’ balances diff --git a/specs/harness/LendingPoolHarness.sol b/specs/harness/LendingPoolHarness.sol deleted file mode 100644 index 7c099ab2..00000000 --- a/specs/harness/LendingPoolHarness.sol +++ /dev/null @@ -1,273 +0,0 @@ -pragma solidity ^0.6.8; -pragma experimental ABIEncoderV2; - -import {ReserveConfiguration} from '../../contracts/libraries/configuration/ReserveConfiguration.sol'; -import {ILendingPool} from '../../contracts/interfaces/ILendingPool.sol'; -import {LendingPool} from '../../contracts/lendingpool/LendingPool.sol'; - -/* -Certora: Harness that delegates calls to the original LendingPool. -*/ -contract LendingPoolHarness is ILendingPool { - - LendingPool private originalPool; - - function deposit( - address asset, - uint256 amount, - address onBehalfOf, - uint16 referralCode - ) external override { - originalPool.deposit(asset, amount, onBehalfOf, referralCode); - } - - function withdraw(address asset, uint256 amount) external override { - originalPool.withdraw(asset, amount); - } - - function getBorrowAllowance( - address fromUser, - address toUser, - address asset, - uint256 interestRateMode - ) external override view returns (uint256) { - return originalPool.getBorrowAllowance(fromUser, toUser, asset, interestRateMode); - } - - function delegateBorrowAllowance( - address asset, - address user, - uint256 interestRateMode, - uint256 amount - ) external override { - originalPool.delegateBorrowAllowance(asset, user, interestRateMode, amount); - } - - function borrow( - address asset, - uint256 amount, - uint256 interestRateMode, - uint16 referralCode, - address onBehalfOf - ) external override { - originalPool.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf); - } - - function repay( - address asset, - uint256 amount, - uint256 rateMode, - address onBehalfOf - ) external override { - originalPool.repay(asset, amount, rateMode, onBehalfOf); - } - - function swapBorrowRateMode(address asset, uint256 rateMode) external override { - originalPool.swapBorrowRateMode(asset, rateMode); - } - - function rebalanceStableBorrowRate(address asset, address user) external override { - originalPool.rebalanceStableBorrowRate(asset, user); - } - - function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override { - originalPool.setUserUseReserveAsCollateral(asset, useAsCollateral); - } - - function liquidationCall( - address collateral, - address asset, - address user, - uint256 purchaseAmount, - bool receiveAToken - ) external override { - originalPool.liquidationCall(collateral, asset, user, purchaseAmount, receiveAToken); - } - - function repayWithCollateral( - address collateral, - address principal, - address user, - uint256 principalAmount, - address receiver, - bytes calldata params - ) external override { - originalPool.repayWithCollateral(collateral, principal, user, principalAmount, receiver, params); - } - - function flashLoan( - address receiverAddress, - address asset, - uint256 amount, - uint256 mode, - bytes calldata params, - uint16 referralCode - ) external override { - originalPool.flashLoan(receiverAddress, asset, amount, mode, params, referralCode); - } - - function swapLiquidity( - address receiverAddress, - address fromAsset, - address toAsset, - uint256 amountToSwap, - bytes calldata params - ) external override { - originalPool.swapLiquidity(receiverAddress, fromAsset, toAsset, amountToSwap, params); - } - - function getReserveConfigurationData(address asset) - external - override - view - returns ( - uint256 decimals, - uint256 ltv, - uint256 liquidationThreshold, - uint256 liquidationBonus, - uint256 reserveFactor, - address interestRateStrategyAddress, - bool usageAsCollateralEnabled, - bool borrowingEnabled, - bool stableBorrowRateEnabled, - bool isActive, - bool isFreezed - ) - { - return originalPool.getReserveConfigurationData(asset); - } - - function getReserveTokensAddresses(address asset) - external - override - view - returns ( - address aTokenAddress, - address stableDebtTokenAddress, - address variableDebtTokenAddress - ) - { - return originalPool.getReserveTokensAddresses(asset); - } - - function getReserveData(address asset) - external - override - view - returns ( - uint256 availableLiquidity, - uint256 totalStableDebt, - uint256 totalVariableDebt, - uint256 liquidityRate, - uint256 variableBorrowRate, - uint256 stableBorrowRate, - uint256 averageStableBorrowRate, - uint256 liquidityIndex, - uint256 variableBorrowIndex, - uint40 lastUpdateTimestamp - ) - { - return originalPool.getReserveData(asset); - } - - function getUserAccountData(address user) - external - override - view - returns ( - uint256 totalCollateralETH, - uint256 totalBorrowsETH, - uint256 availableBorrowsETH, - uint256 currentLiquidationThreshold, - uint256 ltv, - uint256 healthFactor - ) - { - return originalPool.getUserAccountData(user); - } - - function getUserReserveData(address asset, address user) - external - override - view - returns ( - uint256 currentATokenBalance, - uint256 currentStableDebt, - uint256 currentVariableDebt, - uint256 principalStableDebt, - uint256 scaledVariableDebt, - uint256 stableBorrowRate, - uint256 liquidityRate, - uint40 stableRateLastUpdated, - bool usageAsCollateralEnabled - ) - { - return originalPool.getUserReserveData(asset, user); - } - - function getReserves() external override view returns (address[] memory) { - return originalPool.getReserves(); - } - - function initReserve( - address asset, - address aTokenAddress, - address stableDebtAddress, - address variableDebtAddress, - address interestRateStrategyAddress - ) external override { - originalPool.initReserve(asset, aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress); - } - - function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) - external - override - { - originalPool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); - } - - function setConfiguration(address asset, uint256 configuration) external override { - originalPool.setConfiguration(asset, configuration); - } - - function getConfiguration(address asset) - external - override - view - returns (ReserveConfiguration.Map memory) - { - return originalPool.getConfiguration(asset); - } - - function getReserveNormalizedIncome(address asset) external override view returns (uint256) { - return originalPool.getReserveNormalizedIncome(asset); - } - - mapping(uint256 => uint256) private reserveNormalizedVariableDebt; - - function getReserveNormalizedVariableDebt(address asset) - external - override - view - returns (uint256) - { - require(reserveNormalizedVariableDebt[block.timestamp] == 1e27); - return reserveNormalizedVariableDebt[block.timestamp]; - } - - function balanceDecreaseAllowed( - address asset, - address user, - uint256 amount - ) external override view returns (bool) { - return originalPool.balanceDecreaseAllowed(asset, user, amount); - } - - function setPause(bool val) external override { - originalPool.setPause(val); - } - - function paused() external override view returns (bool) { - return originalPool.paused(); - } -} \ No newline at end of file diff --git a/specs/harness/LendingPoolHarnessForVariableDebtToken.sol b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol new file mode 100644 index 00000000..6cd8ec38 --- /dev/null +++ b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol @@ -0,0 +1,193 @@ +pragma solidity ^0.6.8; +pragma experimental ABIEncoderV2; + +import {ReserveConfiguration} from '../../contracts/libraries/configuration/ReserveConfiguration.sol'; +import {UserConfiguration} from '../../contracts/libraries/configuration/UserConfiguration.sol'; +import {ReserveLogic} from '../../contracts/libraries/logic/ReserveLogic.sol'; +import {ILendingPool} from '../../contracts/interfaces/ILendingPool.sol'; +import {LendingPool} from '../../contracts/lendingpool/LendingPool.sol'; + +/* +Certora: Harness that delegates calls to the original LendingPool. +Used for the verification of the VariableDebtToken contract. +*/ +contract LendingPoolHarnessForVariableDebtToken is ILendingPool { + + LendingPool private originalPool; + + function deposit( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external override { + originalPool.deposit(asset, amount, onBehalfOf, referralCode); + } + + function withdraw(address asset, uint256 amount) external override { + originalPool.withdraw(asset, amount); + } + + function getBorrowAllowance( + address fromUser, + address toUser, + address asset, + uint256 interestRateMode + ) external override view returns (uint256) { + return originalPool.getBorrowAllowance(fromUser, toUser, asset, interestRateMode); + } + + function delegateBorrowAllowance( + address asset, + address user, + uint256 interestRateMode, + uint256 amount + ) external override { + originalPool.delegateBorrowAllowance(asset, user, interestRateMode, amount); + } + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external override { + originalPool.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf); + } + + function repay( + address asset, + uint256 amount, + uint256 rateMode, + address onBehalfOf + ) external override { + originalPool.repay(asset, amount, rateMode, onBehalfOf); + } + + function swapBorrowRateMode(address asset, uint256 rateMode) external override { + originalPool.swapBorrowRateMode(asset, rateMode); + } + + function rebalanceStableBorrowRate(address asset, address user) external override { + originalPool.rebalanceStableBorrowRate(asset, user); + } + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override { + originalPool.setUserUseReserveAsCollateral(asset, useAsCollateral); + } + + function liquidationCall( + address collateral, + address asset, + address user, + uint256 purchaseAmount, + bool receiveAToken + ) external override { + originalPool.liquidationCall(collateral, asset, user, purchaseAmount, receiveAToken); + } + + function flashLoan( + address receiver, + address[] calldata assets, + uint256[] calldata amounts, + uint256 mode, + bytes calldata params, + uint16 referralCode + ) external override { + originalPool.flashLoan(receiver, assets, amounts, mode, params, referralCode); + } + + function getReservesList() external override view returns (address[] memory) { + return originalPool.getReservesList(); + } + + function getReserveData(address asset) external override view returns (ReserveLogic.ReserveData memory) { + return originalPool.getReserveData(asset); + } + + function getUserConfiguration(address user) external override view returns (UserConfiguration.Map memory) { + return originalPool.getUserConfiguration(user); + } + + function getUserAccountData(address user) + external + override + view + returns ( + uint256 totalCollateralETH, + uint256 totalBorrowsETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ) + { + return originalPool.getUserAccountData(user); + } + + function initReserve( + address asset, + address aTokenAddress, + address stableDebtAddress, + address variableDebtAddress, + address interestRateStrategyAddress + ) external override { + originalPool.initReserve(asset, aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress); + } + + function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) + external + override + { + originalPool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); + } + + function setConfiguration(address asset, uint256 configuration) external override { + originalPool.setConfiguration(asset, configuration); + } + + function getConfiguration(address asset) + external + override + view + returns (ReserveConfiguration.Map memory) + { + return originalPool.getConfiguration(asset); + } + + mapping(uint256 => uint256) private reserveNormalizedIncome; + + function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + require(reserveNormalizedIncome[block.timestamp] == 1e27); + return reserveNormalizedIncome[block.timestamp]; + } + + mapping(uint256 => uint256) private reserveNormalizedVariableDebt; + + function getReserveNormalizedVariableDebt(address asset) + external + override + view + returns (uint256) + { + require(reserveNormalizedVariableDebt[block.timestamp] == 1e27); + return reserveNormalizedVariableDebt[block.timestamp]; + } + + function balanceDecreaseAllowed( + address asset, + address user, + uint256 amount + ) external override view returns (bool) { + return originalPool.balanceDecreaseAllowed(asset, user, amount); + } + + function setPause(bool val) external override { + originalPool.setPause(val); + } + + function paused() external override view returns (bool) { + return originalPool.paused(); + } +} From 4030d487877f29d5e669b5f4efbfaeaa9db1d96e Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Thu, 29 Oct 2020 01:57:15 +0200 Subject: [PATCH 05/22] Fixes to run on StableDebtToken contract --- contracts/tokenization/StableDebtToken.sol | 2 +- specs/StableDebtToken.spec | 16 ---------------- specs/harness/StableDebtTokenHarness.sol | 3 --- 3 files changed, 1 insertion(+), 20 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 346d9719..a026cfc9 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -286,7 +286,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { * @param avgRate the average rate at which calculate the total supply * @return The debt balance of the user since the last burn/mint action **/ - function _calcTotalSupply(uint256 avgRate) internal view returns (uint256) { + function _calcTotalSupply(uint256 avgRate) internal virtual view returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { diff --git a/specs/StableDebtToken.spec b/specs/StableDebtToken.spec index fba0f8ba..718dcb60 100644 --- a/specs/StableDebtToken.spec +++ b/specs/StableDebtToken.spec @@ -2,13 +2,6 @@ methods { getUserLastUpdated(address) returns uint40 envfree } -ghost ghostSupply() returns uint256; - -hook Sstore (slot 0)[address a] uint256 balance (uint256 old_balance) STORAGE { - require old_balance <= ghostSupply(); - havoc ghostSupply assuming ghostSupply@new() == ghostSupply@old() + (balance - old_balance); -} - rule integrityTimeStamp(address user, method f) { env e; require sinvoke getIncentivesController(e) == 0; @@ -18,15 +11,6 @@ rule integrityTimeStamp(address user, method f) { assert getUserLastUpdated(user) <= e.block.timestamp; } -rule totalSupplyInvariant(method f) { - env e; - require sinvoke getIncentivesController(e) == 0; - require totalSupply(e) == ghostSupply(); - calldataarg arg; - sinvoke f(e, arg); - assert totalSupply(e) == ghostSupply(); -} - /** TotalSupply is the sum of all users’ balances diff --git a/specs/harness/StableDebtTokenHarness.sol b/specs/harness/StableDebtTokenHarness.sol index be2471be..d314f8f0 100644 --- a/specs/harness/StableDebtTokenHarness.sol +++ b/specs/harness/StableDebtTokenHarness.sol @@ -1,8 +1,5 @@ pragma solidity ^0.6.8; -import {Context} from '@openzeppelin/contracts/GSN/Context.sol'; -import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; -import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {StableDebtToken} from '../../contracts/tokenization/StableDebtToken.sol'; import {IncentivizedERC20} from '../../contracts/tokenization/IncentivizedERC20.sol'; From d4f0e05f06dd96fa877946c8dcee9264a8d4cbed Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Thu, 29 Oct 2020 01:58:20 +0200 Subject: [PATCH 06/22] Fixes to run on UserConfiguration library --- specs/harness/UserConfigurationHarness.sol | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/specs/harness/UserConfigurationHarness.sol b/specs/harness/UserConfigurationHarness.sol index 03574a99..81b2444e 100644 --- a/specs/harness/UserConfigurationHarness.sol +++ b/specs/harness/UserConfigurationHarness.sol @@ -1,8 +1,7 @@ pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; -import {UserConfiguration} from 'contracts/libraries/configuration/UserConfiguration.sol'; - +import {UserConfiguration} from '../../contracts/libraries/configuration/UserConfiguration.sol'; /* A wrapper contract for calling functions from the library UserConfiguration. From edfe17bd971301fbb070a9514c76d04c8d53d0cf Mon Sep 17 00:00:00 2001 From: eboado Date: Thu, 29 Oct 2020 14:36:01 +0100 Subject: [PATCH 07/22] - Added batch to credit delegation --- contracts/interfaces/ILendingPool.sol | 20 ++++++++--------- contracts/lendingpool/LendingPool.sol | 30 ++++++++++++++++---------- contracts/libraries/helpers/Errors.sol | 3 +++ test/helpers/actions.ts | 25 +++++++++++++-------- test/helpers/scenario-engine.ts | 6 +++--- test/pausable-functions.spec.ts | 2 +- 6 files changed, 52 insertions(+), 34 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index f44a458a..49869817 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -32,11 +32,11 @@ interface ILendingPool { event Withdraw(address indexed reserve, address indexed user, uint256 amount); event BorrowAllowanceDelegated( - address indexed asset, address indexed fromUser, address indexed toUser, - uint256 interestRateMode, - uint256 amount + address[] assets, + uint256[] interestRateModes, + uint256[] amounts ); /** * @dev emitted on borrow @@ -189,17 +189,17 @@ interface ILendingPool { function withdraw(address reserve, uint256 amount) external; /** - * @dev Sets allowance to borrow on a certain type of debt asset for a certain user address - * @param asset The underlying asset of the debt token + * @dev Sets allowance to borrow on a certain type of debt assets for a certain user address + * @param assets The underlying asset of each debt token * @param user The user to give allowance to - * @param interestRateMode Type of debt: 1 for stable, 2 for variable - * @param amount Allowance amount to borrow + * @param interestRateModes Types of debt: 1 for stable, 2 for variable + * @param amounts Allowance amounts to borrow **/ function delegateBorrowAllowance( - address asset, + address[] calldata assets, address user, - uint256 interestRateMode, - uint256 amount + uint256[] calldata interestRateModes, + uint256[] calldata amounts ) external; function getBorrowAllowance( diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 3f490365..f77aac9d 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -179,23 +179,32 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage } /** - * @dev Sets allowance to borrow on a certain type of debt asset for a certain user address - * @param asset The underlying asset of the debt token + * @dev Sets allowance to borrow on a certain type of debt assets for a certain user address + * @param assets The underlying asset of each debt token * @param user The user to give allowance to - * @param interestRateMode Type of debt: 1 for stable, 2 for variable - * @param amount Allowance amount to borrow + * @param interestRateModes Types of debt: 1 for stable, 2 for variable + * @param amounts Allowance amounts to borrow **/ function delegateBorrowAllowance( - address asset, + address[] calldata assets, address user, - uint256 interestRateMode, - uint256 amount + uint256[] calldata interestRateModes, + uint256[] calldata amounts ) external override { _whenNotPaused(); - address debtToken = _reserves[asset].getDebtTokenAddress(interestRateMode); - _borrowAllowance[debtToken][msg.sender][user] = amount; - emit BorrowAllowanceDelegated(asset, msg.sender, user, interestRateMode, amount); + uint256 countAssets = assets.length; + require( + countAssets == interestRateModes.length && countAssets == amounts.length, + Errors.INCONSISTENT_PARAMS_LENGTH + ); + + for (uint256 i = 0; i < countAssets; i++) { + address debtToken = _reserves[assets[i]].getDebtTokenAddress(interestRateModes[i]); + _borrowAllowance[debtToken][msg.sender][user] = amounts[i]; + } + + emit BorrowAllowanceDelegated(msg.sender, user, assets, interestRateModes, amounts); } /** @@ -913,7 +922,6 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @dev adds a reserve to the array of the _reserves address **/ function _addReserveToList(address asset) internal { - uint256 reservesCount = _reservesCount; require(reservesCount < MAX_NUMBER_RESERVES, Errors.NO_MORE_RESERVES_ALLOWED); diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index 9ed7b07e..2bd24743 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -97,6 +97,9 @@ library Errors { string public constant INVALID_DECIMALS = '73'; string public constant INVALID_RESERVE_FACTOR = '74'; + // Credit delegation + string public constant INCONSISTENT_PARAMS_LENGTH = '75'; + enum CollateralManagerErrors { NO_ERROR, diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 85d3eb00..60feac6a 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -279,9 +279,9 @@ export const withdraw = async ( }; export const delegateBorrowAllowance = async ( - reserveSymbol: string, - amount: string, - interestRateMode: string, + reserveSymbols: string[], + amounts: string[], + interestRateModes: string[], user: SignerWithAddress, receiver: tEthereumAddress, expectedResult: string, @@ -290,20 +290,27 @@ export const delegateBorrowAllowance = async ( ) => { const {pool} = testEnv; - const reserve = await getReserveAddressFromSymbol(reserveSymbol); - const amountToDelegate = await convertToCurrencyDecimals(reserve, amount); + const reserves : tEthereumAddress[] = [] + const amountsToDelegate: tEthereumAddress[] = [] + for (const reserveSymbol of reserveSymbols) { + const newLength = reserves.push(await getReserveAddressFromSymbol(reserveSymbol)) + amountsToDelegate.push(await (await convertToCurrencyDecimals(reserves[newLength-1], amounts[newLength-1])).toString()) + } const delegateAllowancePromise = pool .connect(user.signer) - .delegateBorrowAllowance(reserve, receiver, interestRateMode, amountToDelegate.toString()); + .delegateBorrowAllowance(reserves, receiver, interestRateModes, amountsToDelegate); if (expectedResult === 'revert') { await expect(delegateAllowancePromise, revertMessage).to.be.reverted; return; } else { await delegateAllowancePromise; - expect( - (await pool.getBorrowAllowance(user.address, receiver, reserve, interestRateMode)).toString() - ).to.be.equal(amountToDelegate.toString(), 'borrowAllowance are set incorrectly'); + for (const [i, reserve] of reserves.entries()) { + expect( + (await pool.getBorrowAllowance(user.address, receiver, reserve, interestRateModes[i])).toString() + ).to.be.equal(amountsToDelegate[i], 'borrowAllowance are set incorrectly'); + } + } }; diff --git a/test/helpers/scenario-engine.ts b/test/helpers/scenario-engine.ts index bb4f82f8..fe2e302a 100644 --- a/test/helpers/scenario-engine.ts +++ b/test/helpers/scenario-engine.ts @@ -121,9 +121,9 @@ const executeAction = async (action: Action, users: SignerWithAddress[], testEnv } await delegateBorrowAllowance( - reserve, - amount, - rateMode, + [reserve], + [amount], + [rateMode], user, toUser, expected, diff --git a/test/pausable-functions.spec.ts b/test/pausable-functions.spec.ts index 48c50ee2..a15ceb61 100644 --- a/test/pausable-functions.spec.ts +++ b/test/pausable-functions.spec.ts @@ -132,7 +132,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // Try to execute liquidation await expect( - pool.connect(user.signer).delegateBorrowAllowance(dai.address, toUser.address, '1', '1') + pool.connect(user.signer).delegateBorrowAllowance([dai.address], toUser.address, ['1'], ['1']) ).revertedWith(IS_PAUSED); // Unpause the pool From 38bb760112fe23f09eb5efb88e1ee24900c59fa7 Mon Sep 17 00:00:00 2001 From: eboado Date: Thu, 29 Oct 2020 14:55:11 +0100 Subject: [PATCH 08/22] - Added return of is first borrowing on debt tokens mint() --- contracts/lendingpool/LendingPool.sol | 17 +++++++++-------- contracts/tokenization/StableDebtToken.sol | 4 +++- .../interfaces/IStableDebtToken.sol | 2 +- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 3f490365..1a589091 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -857,34 +857,35 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage oracle ); - uint256 reserveId = reserve.id; - if (!userConfig.isBorrowing(reserveId)) { - userConfig.setBorrowing(reserveId, true); - } - reserve.updateState(); //caching the current stable borrow rate uint256 currentStableRate = 0; - + + bool isFirstBorrowing = false; if ( ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE ) { currentStableRate = reserve.currentStableBorrowRate; - IStableDebtToken(reserve.stableDebtTokenAddress).mint( + isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.onBehalfOf, vars.amount, currentStableRate ); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint( + isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } + uint256 reserveId = reserve.id; + if (isFirstBorrowing) { + userConfig.setBorrowing(reserveId, true); + } + reserve.updateInterestRates( vars.asset, vars.aTokenAddress, diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 346d9719..29781919 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -97,7 +97,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { address user, uint256 amount, uint256 rate - ) external override onlyLendingPool { + ) external override onlyLendingPool returns(bool) { MintLocalVars memory vars; //cumulates the user debt @@ -148,6 +148,8 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { vars.newStableRate, vars.currentAvgStableRate ); + + return currentBalance == 0; } /** diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 4c0d5940..4e04f704 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -62,7 +62,7 @@ interface IStableDebtToken { address user, uint256 amount, uint256 rate - ) external; + ) external returns(bool); /** * @dev burns debt of the target user. From 913a6a923756297b45d0ce6bd40d03414fd8df9a Mon Sep 17 00:00:00 2001 From: eboado Date: Thu, 29 Oct 2020 15:14:28 +0100 Subject: [PATCH 09/22] - Added batch of modes to flashLoan() --- contracts/interfaces/ILendingPool.sol | 6 ++--- contracts/lendingpool/LendingPool.sol | 13 +++++----- contracts/libraries/logic/ValidationLogic.sol | 17 +++++++++--- test/flashloan.spec.ts | 26 +++++++++---------- test/pausable-functions.spec.ts | 2 +- 5 files changed, 36 insertions(+), 28 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index f44a458a..4d12b60f 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -106,7 +106,7 @@ interface ILendingPool { **/ event FlashLoan( address indexed target, - uint256 mode, + uint256[] modes, address[] assets, uint256[] amounts, uint256[] premiums, @@ -286,7 +286,7 @@ interface ILendingPool { * @param receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param assets the address of the principal reserve * @param amounts the amount requested for this flashloan - * @param mode the flashloan mode + * @param modes the flashloan mode * @param params a bytes array to be sent to the flashloan executor * @param referralCode the referral code of the caller **/ @@ -294,7 +294,7 @@ interface ILendingPool { address receiver, address[] calldata assets, uint256[] calldata amounts, - uint256 mode, + uint256[] calldata modes, bytes calldata params, uint16 referralCode ) external; diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index b0f960b3..618bd508 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -502,7 +502,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @param receiverAddress The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param assets The addresss of the assets being flashborrowed * @param amounts The amounts requested for this flashloan for each asset - * @param mode Type of the debt to open if the flash loan is not returned. 0 -> Don't open any debt, just revert, 1 -> stable, 2 -> variable + * @param modes Types of the debt to open if the flash loan is not returned. 0 -> Don't open any debt, just revert, 1 -> stable, 2 -> variable * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Referral code of the flash loan **/ @@ -510,7 +510,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage address receiverAddress, address[] calldata assets, uint256[] calldata amounts, - uint256 mode, + uint256[] calldata modes, bytes calldata params, uint16 referralCode ) external override { @@ -518,13 +518,12 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage FlashLoanLocalVars memory vars; - ValidationLogic.validateFlashloan(assets, amounts, mode); + ValidationLogic.validateFlashloan(assets, amounts, modes); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); - vars.debtMode = ReserveLogic.InterestRateMode(mode); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; @@ -546,7 +545,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; - + vars.debtMode = ReserveLogic.InterestRateMode(modes[vars.i]); vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (vars.debtMode == ReserveLogic.InterestRateMode.NONE) { @@ -576,14 +575,14 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage msg.sender, msg.sender, vars.currentAmount, - mode, + modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } - emit FlashLoan(receiverAddress, mode, assets, amounts, premiums, referralCode); + emit FlashLoan(receiverAddress, modes, assets, amounts, premiums, referralCode); } } diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 947d84ea..c2019fd6 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -326,17 +326,26 @@ library ValidationLogic { /** * @dev validates a flashloan action - * @param mode the flashloan mode (0 = classic flashloan, 1 = open a stable rate loan, 2 = open a variable rate loan) + * @param modes the flashloan modes (0 = classic flashloan, 1 = open a stable rate loan, 2 = open a variable rate loan) * @param assets the assets being flashborrowed * @param amounts the amounts for each asset being borrowed **/ function validateFlashloan( address[] memory assets, uint256[] memory amounts, - uint256 mode + uint256[] memory modes ) internal pure { - require(mode <= uint256(ReserveLogic.InterestRateMode.VARIABLE), Errors.INVALID_FLASHLOAN_MODE); - require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS); + require( + assets.length == amounts.length && assets.length == modes.length, + Errors.INCONSISTENT_FLASHLOAN_PARAMS + ); + + for (uint256 i = 0; i < modes.length; i++) { + require( + modes[i] <= uint256(ReserveLogic.InterestRateMode.VARIABLE), + Errors.INVALID_FLASHLOAN_MODE + ); + } } /** diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 305d674f..6df207c8 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -47,7 +47,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], '0x10', '0' ); @@ -76,7 +76,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], ['1000720000000000000'], - 0, + [0], '0x10', '0' ); @@ -107,7 +107,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], '0x10', '0' ) @@ -127,7 +127,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 0, + [0], '0x10', '0' ) @@ -147,7 +147,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 4, + [4], '0x10', '0' ) @@ -175,7 +175,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], [ethers.utils.parseEther('0.8')], - 2, + [2], '0x10', '0' ); @@ -201,7 +201,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [weth.address], ['1004415000000000000'], //slightly higher than the available liquidity - 2, + [2], '0x10', '0' ), @@ -213,7 +213,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const {pool, deployer, weth} = testEnv; await expect( - pool.flashLoan(deployer.address, [weth.address], ['1000000000000000000'], 2, '0x10', '0') + pool.flashLoan(deployer.address, [weth.address], ['1000000000000000000'], [2], '0x10', '0') ).to.be.reverted; }); @@ -241,7 +241,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], - 0, + [0], '0x10', '0' ); @@ -283,7 +283,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { _mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], - 2, + [2], '0x10', '0' ) @@ -309,7 +309,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await pool .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], 2, '0x10', '0'); + .flashLoan(_mockFlashLoanReceiver.address, [usdc.address], [flashloanAmount], [2], '0x10', '0'); const {variableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses( usdc.address ); @@ -344,7 +344,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await expect( pool .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], 0, '0x10', '0') + .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], [0], '0x10', '0') ).to.be.revertedWith(SAFEERC20_LOWLEVEL_CALL); }); @@ -359,7 +359,7 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { await pool .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], 1, '0x10', '0'); + .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], [1], '0x10', '0'); const {stableDebtTokenAddress} = await helpersContract.getReserveTokensAddresses(weth.address); diff --git a/test/pausable-functions.spec.ts b/test/pausable-functions.spec.ts index 2bf8be21..ae7e3874 100644 --- a/test/pausable-functions.spec.ts +++ b/test/pausable-functions.spec.ts @@ -187,7 +187,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { await expect( pool .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], 1, '0x10', '0') + .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], [1], '0x10', '0') ).revertedWith(IS_PAUSED); // Unpause pool From e4dc22e50ed2864787f06fd8154b1bc46483f571 Mon Sep 17 00:00:00 2001 From: emilio Date: Thu, 29 Oct 2020 18:03:19 +0100 Subject: [PATCH 10/22] Fixed events, removed unused constants in addressesProvider --- .../LendingPoolAddressesProvider.sol | 5 ----- contracts/interfaces/ILendingPool.sol | 2 +- contracts/lendingpool/LendingPool.sol | 2 +- .../lendingpool/LendingPoolConfigurator.sol | 20 +++++++++---------- deployed-contracts.json | 9 +++++---- 5 files changed, 17 insertions(+), 21 deletions(-) diff --git a/contracts/configuration/LendingPoolAddressesProvider.sol b/contracts/configuration/LendingPoolAddressesProvider.sol index 15b37635..38aa1280 100644 --- a/contracts/configuration/LendingPoolAddressesProvider.sol +++ b/contracts/configuration/LendingPoolAddressesProvider.sol @@ -19,16 +19,11 @@ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; - bytes32 private constant LENDING_POOL_CORE = 'LENDING_POOL_CORE'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant AAVE_ADMIN = 'AAVE_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; - bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = 'FLASHLOAN_PROVIDER'; - bytes32 private constant DATA_PROVIDER = 'DATA_PROVIDER'; - bytes32 private constant ETHEREUM_ADDRESS = 'ETHEREUM_ADDRESS'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; - bytes32 private constant WALLET_BALANCE_PROVIDER = 'WALLET_BALANCE_PROVIDER'; /** * @dev Sets an address for an id, allowing to cover it or not with a proxy diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 450def2d..2e4e2d94 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -74,7 +74,7 @@ interface ILendingPool { * @param reserve the address of the reserve * @param user the address of the user executing the swap **/ - event Swap(address indexed reserve, address indexed user); + event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev emitted when a user enables a reserve as collateral diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 539b6ac6..2aa45f84 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -352,7 +352,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); - emit Swap(asset, msg.sender); + emit Swap(asset, msg.sender, rateMode); } /** diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index c3da634c..1428805e 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -47,7 +47,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param asset the address of the reserve * @param stableRateEnabled true if stable rate borrowing is enabled, false otherwise **/ - event BorrowingEnabledOnReserve(address asset, bool stableRateEnabled); + event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev emitted when borrowing is disabled on a reserve @@ -116,42 +116,42 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param asset the address of the reserve * @param ltv the new value for the loan to value **/ - event ReserveBaseLtvChanged(address asset, uint256 ltv); + event ReserveBaseLtvChanged(address indexed asset, uint256 ltv); /** * @dev emitted when a reserve factor is updated * @param asset the address of the reserve * @param factor the new reserve factor **/ - event ReserveFactorChanged(address asset, uint256 factor); + event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev emitted when a reserve liquidation threshold is updated * @param asset the address of the reserve * @param threshold the new value for the liquidation threshold **/ - event ReserveLiquidationThresholdChanged(address asset, uint256 threshold); + event ReserveLiquidationThresholdChanged(address indexed asset, uint256 threshold); /** * @dev emitted when a reserve liquidation bonus is updated * @param asset the address of the reserve * @param bonus the new value for the liquidation bonus **/ - event ReserveLiquidationBonusChanged(address asset, uint256 bonus); + event ReserveLiquidationBonusChanged(address indexed asset, uint256 bonus); /** * @dev emitted when the reserve decimals are updated * @param asset the address of the reserve * @param decimals the new decimals **/ - event ReserveDecimalsChanged(address asset, uint256 decimals); + event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev emitted when a reserve interest strategy contract is updated * @param asset the address of the reserve * @param strategy the new address of the interest strategy contract **/ - event ReserveInterestRateStrategyChanged(address asset, address strategy); + event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev emitted when an aToken implementation is upgraded @@ -159,7 +159,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the aToken proxy address * @param implementation the new aToken implementation **/ - event ATokenUpgraded(address asset, address proxy, address implementation); + event ATokenUpgraded(address indexed asset, address indexed proxy, address indexed implementation); /** * @dev emitted when the implementation of a stable debt token is upgraded @@ -167,7 +167,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the stable debt token proxy address * @param implementation the new aToken implementation **/ - event StableDebtTokenUpgraded(address asset, address proxy, address implementation); + event StableDebtTokenUpgraded(address indexed asset, address indexed proxy, address indexed implementation); /** * @dev emitted when the implementation of a variable debt token is upgraded @@ -175,7 +175,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param proxy the variable debt token proxy address * @param implementation the new aToken implementation **/ - event VariableDebtTokenUpgraded(address asset, address proxy, address implementation); + event VariableDebtTokenUpgraded(address indexed asset, address indexed proxy, address indexed implementation); ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; diff --git a/deployed-contracts.json b/deployed-contracts.json index 9690522a..401a2694 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -163,25 +163,26 @@ }, "ReserveLogic": { "buidlerevm": { - "address": "0xFAe0fd738dAbc8a0426F47437322b6d026A9FD95", + "address": "0x78Ee8Fb9fE5abD5e347Fc94c2fb85596d1f60e3c", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "GenericLogic": { "buidlerevm": { - "address": "0x6082731fdAba4761277Fb31299ebC782AD3bCf24", + "address": "0x920d847fE49E54C19047ba8bc236C45A8068Bca7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "ValidationLogic": { "buidlerevm": { - "address": "0x8456161947DFc1fC159A0B26c025cD2b4bba0c3e", + "address": "0xA4765Ff72A9F3CfE73089bb2c3a41B838DF71574", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPool": { "buidlerevm": { - "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" + "address": "0x35c1419Da7cf0Ff885B8Ef8EA9242FEF6800c99b", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPoolConfigurator": { From 5cc6acce8612597bdcd43c8e217739770400c144 Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Thu, 29 Oct 2020 23:19:11 +0200 Subject: [PATCH 11/22] Updates in the specification of StableDebtToken --- runStableTokenCLI.sh | 2 +- specs/StableDebtToken.spec | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/runStableTokenCLI.sh b/runStableTokenCLI.sh index 658c7663..8903f2f9 100644 --- a/runStableTokenCLI.sh +++ b/runStableTokenCLI.sh @@ -1 +1 @@ -certoraRun specs/harness/StableDebtTokenHarness.sol:StableDebtTokenHarness --solc solc6.8 --verify StableDebtTokenHarness:specs/StableDebtToken.spec --settings -assumeUnwindCond,-useNonLinearArithmetic --cache StableDebtToken --staging master \ No newline at end of file +certoraRun specs/harness/StableDebtTokenHarness.sol:StableDebtTokenHarness --solc solc6.8 --verify StableDebtTokenHarness:specs/StableDebtToken.spec --settings -assumeUnwindCond --cache StableDebtToken --staging master \ No newline at end of file diff --git a/specs/StableDebtToken.spec b/specs/StableDebtToken.spec index 718dcb60..0d6e0c5d 100644 --- a/specs/StableDebtToken.spec +++ b/specs/StableDebtToken.spec @@ -90,19 +90,25 @@ rule integrityMint(address a, uint256 x) { /** Mint is additive, can performed either all at once or gradually mint(u,x); mint(u,y) ~ mint(u,x+y) at the same timestamp + +Note: We assume that the stable rate of the user is 0. +The case where the rate is non-zero takes much more time to prove, +and therefore it is currently excluded from the CI. */ rule additiveMint(address a, uint256 x, uint256 y) { env e; require sinvoke getIncentivesController(e) == 0; + require getUserStableRate(e,a) == 0; uint256 index; storage initialStorage = lastStorage; sinvoke mint(e,a,x,index); sinvoke mint(e,a,y,index); uint256 balanceScenario1 = sinvoke balanceOf(e,a); - uint t = x + y; + + uint256 t = x + y; sinvoke mint(e,a, t ,index) at initialStorage; - - uint256 balanceScenario2 = sinvoke balanceOf(e,a); + + uint256 balanceScenario2 = sinvoke balanceOf(e,a); assert balanceScenario1 == balanceScenario2, "mint is not additive"; } @@ -124,7 +130,7 @@ rule additiveBurn(address a, uint256 x, uint256 y) { sinvoke burn(e, a, x); sinvoke burn(e, a, y); uint256 balanceScenario1 = balanceOf(e, a); - uint t = x + y; + uint256 t = x + y; sinvoke burn(e, a, t) at initialStorage; uint256 balanceScenario2 = balanceOf(e, a); From 22353eeee583426bf9525b4a3d08ee16e80633b8 Mon Sep 17 00:00:00 2001 From: pistiner <59415933+orpistiner@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:07:30 +0200 Subject: [PATCH 12/22] Fixes to run on VariableDebtToken --- contracts/lendingpool/LendingPool.sol | 2 +- ...LendingPoolHarnessForVariableDebtToken.sol | 43 +++++++++++-------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 539b6ac6..34a36c96 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -691,7 +691,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @param asset the address of the reserve * @return the reserve normalized income */ - function getReserveNormalizedIncome(address asset) external override view returns (uint256) { + function getReserveNormalizedIncome(address asset) external virtual override view returns (uint256) { return _reserves[asset].getNormalizedIncome(); } diff --git a/specs/harness/LendingPoolHarnessForVariableDebtToken.sol b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol index 6cd8ec38..1fdeffb0 100644 --- a/specs/harness/LendingPoolHarnessForVariableDebtToken.sol +++ b/specs/harness/LendingPoolHarnessForVariableDebtToken.sol @@ -87,17 +87,6 @@ contract LendingPoolHarnessForVariableDebtToken is ILendingPool { originalPool.liquidationCall(collateral, asset, user, purchaseAmount, receiveAToken); } - function flashLoan( - address receiver, - address[] calldata assets, - uint256[] calldata amounts, - uint256 mode, - bytes calldata params, - uint16 referralCode - ) external override { - originalPool.flashLoan(receiver, assets, amounts, mode, params, referralCode); - } - function getReservesList() external override view returns (address[] memory) { return originalPool.getReservesList(); } @@ -175,14 +164,6 @@ contract LendingPoolHarnessForVariableDebtToken is ILendingPool { return reserveNormalizedVariableDebt[block.timestamp]; } - function balanceDecreaseAllowed( - address asset, - address user, - uint256 amount - ) external override view returns (bool) { - return originalPool.balanceDecreaseAllowed(asset, user, amount); - } - function setPause(bool val) external override { originalPool.setPause(val); } @@ -190,4 +171,28 @@ contract LendingPoolHarnessForVariableDebtToken is ILendingPool { function paused() external override view returns (bool) { return originalPool.paused(); } + + function flashLoan( + address receiver, + address[] calldata assets, + uint256[] calldata amounts, + uint256 mode, + address onBehalfOf, + bytes calldata params, + uint16 referralCode + ) external override { + originalPool.flashLoan(receiver, assets, amounts, mode, onBehalfOf, params, referralCode); + } + + function finalizeTransfer( + address asset, + address from, + address to, + uint256 amount, + uint256 balanceFromAfter, + uint256 balanceToBefore + ) external override { + originalPool.finalizeTransfer(asset, from, to, amount, balanceFromAfter, balanceToBefore); + } + } From 7ae9a2df8f6acd99f25ac02f3a0020e5d9b04782 Mon Sep 17 00:00:00 2001 From: emilio Date: Fri, 30 Oct 2020 11:36:53 +0100 Subject: [PATCH 13/22] Updated variable names --- contracts/libraries/logic/ValidationLogic.sol | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index 78f74154..d9824835 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -258,8 +258,8 @@ library ValidationLogic { function validateSwapRateMode( ReserveLogic.ReserveData storage reserve, UserConfiguration.Map storage userConfig, - uint256 stableBorrowBalance, - uint256 variableBorrowBalance, + uint256 stableDebt, + uint256 variableDebt, ReserveLogic.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFreezed, , bool stableRateEnabled) = reserve.configuration.getFlags(); @@ -268,9 +268,9 @@ library ValidationLogic { require(!isFreezed, Errors.NO_UNFREEZED_RESERVE); if (currentRateMode == ReserveLogic.InterestRateMode.STABLE) { - require(stableBorrowBalance > 0, Errors.NO_STABLE_RATE_LOAN_IN_RESERVE); + require(stableDebt > 0, Errors.NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) { - require(variableBorrowBalance > 0, Errors.NO_VARIABLE_RATE_LOAN_IN_RESERVE); + require(variableDebt > 0, Errors.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 @@ -283,7 +283,7 @@ library ValidationLogic { require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || - stableBorrowBalance.add(variableBorrowBalance) > + stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.CALLATERAL_SAME_AS_BORROWING_CURRENCY ); From a49f2744ee888f16e88ed79c6f9893d64249e6c2 Mon Sep 17 00:00:00 2001 From: emilio Date: Fri, 30 Oct 2020 11:38:49 +0100 Subject: [PATCH 14/22] Updated comments --- contracts/libraries/logic/ValidationLogic.sol | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index d9824835..adbfdfc7 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -251,8 +251,8 @@ library ValidationLogic { * @dev validates a swap of borrow rate mode. * @param reserve the reserve state on which the user is swapping the rate * @param userConfig the user reserves configuration - * @param stableBorrowBalance the stable borrow balance of the user - * @param variableBorrowBalance the stable borrow balance of the user + * @param stableDebt the stable debt of the user + * @param variableDebt the variable debt of the user * @param currentRateMode the rate mode of the borrow */ function validateSwapRateMode( From de7ec39f24b8a4e44a7c82226a5bbd0df459eb98 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 11:42:27 +0100 Subject: [PATCH 15/22] - Fixed comment on ILendingPool --- contracts/interfaces/ILendingPool.sol | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index a9a176f7..9dbb7c89 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -99,15 +99,13 @@ interface ILendingPool { /** * @dev emitted when a flashloan is executed * @param target the address of the flashLoanReceiver - * @param asset the address of the assets being flashborrowed + * @param asset the address of the asset being flashborrowed * @param amount the amount requested * @param premium the total fee on the amount * @param referralCode the referral code of the caller **/ event FlashLoan( address indexed target, - // uint256[] modes, - // address indexed onBehalfOf, address asset, uint256 amount, uint256 premium, From 092aacc85a162a45d56fcf69b53529d3fe586970 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 11:49:23 +0100 Subject: [PATCH 16/22] - Added initiator to flash loan event. --- contracts/interfaces/ILendingPool.sol | 2 ++ contracts/lendingpool/LendingPool.sol | 1 + 2 files changed, 3 insertions(+) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 9dbb7c89..55362ec1 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -99,6 +99,7 @@ interface ILendingPool { /** * @dev emitted when a flashloan is executed * @param target the address of the flashLoanReceiver + * @param initiator the address initiating the flash loan * @param asset the address of the asset being flashborrowed * @param amount the amount requested * @param premium the total fee on the amount @@ -106,6 +107,7 @@ interface ILendingPool { **/ event FlashLoan( address indexed target, + address initiator, address asset, uint256 amount, uint256 premium, diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index a90fc385..987d8eb9 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -595,6 +595,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage } emit FlashLoan( receiverAddress, + msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, From 910fa2dce6eba2a60aee033f9a0d5aaff63bd531 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 11:52:00 +0100 Subject: [PATCH 17/22] - Added indexed to flash loan events. --- contracts/interfaces/ILendingPool.sol | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 55362ec1..564392db 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -107,8 +107,8 @@ interface ILendingPool { **/ event FlashLoan( address indexed target, - address initiator, - address asset, + address indexed initiator, + address indexed asset, uint256 amount, uint256 premium, uint16 referralCode From af6b370f0e5da3e6aabb231e918c0bfda9615f40 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 11:55:28 +0100 Subject: [PATCH 18/22] - Removed from memory struct debtMode on flashLoan() --- contracts/lendingpool/LendingPool.sol | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 987d8eb9..471d986c 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -486,7 +486,6 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; - ReserveLogic.InterestRateMode debtMode; uint256 i; address currentAsset; address currentATokenAddress; @@ -548,10 +547,9 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; - vars.debtMode = ReserveLogic.InterestRateMode(modes[vars.i]); vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); - if (vars.debtMode == ReserveLogic.InterestRateMode.NONE) { + if (ReserveLogic.InterestRateMode(modes[vars.i]) == ReserveLogic.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), From decf652e192e95f38952658a690a82f2c5dafdc4 Mon Sep 17 00:00:00 2001 From: emilio Date: Fri, 30 Oct 2020 11:55:50 +0100 Subject: [PATCH 19/22] Removed variable --- contracts/lendingpool/LendingPool.sol | 3 +-- deployed-contracts.json | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 1a589091..88ce5e9a 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -881,9 +881,8 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ); } - uint256 reserveId = reserve.id; if (isFirstBorrowing) { - userConfig.setBorrowing(reserveId, true); + userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( diff --git a/deployed-contracts.json b/deployed-contracts.json index d7001b2a..4b961b6c 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -628,4 +628,4 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } } -} +} \ No newline at end of file From 7227717a7a292353fd364fcf17123ee7a0f39429 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 12:06:02 +0100 Subject: [PATCH 20/22] - Removed modes from validateFlashLoan. Not needed as executeBorrow() will fail. --- contracts/lendingpool/LendingPool.sol | 2 +- contracts/libraries/logic/ValidationLogic.sol | 19 ++----------------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 471d986c..7e29b92d 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -520,7 +520,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage FlashLoanLocalVars memory vars; - ValidationLogic.validateFlashloan(assets, amounts, modes); + ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); diff --git a/contracts/libraries/logic/ValidationLogic.sol b/contracts/libraries/logic/ValidationLogic.sol index cc771f8b..b677f34e 100644 --- a/contracts/libraries/logic/ValidationLogic.sol +++ b/contracts/libraries/logic/ValidationLogic.sol @@ -331,26 +331,11 @@ library ValidationLogic { /** * @dev validates a flashloan action - * @param modes the flashloan modes (0 = classic flashloan, 1 = open a stable rate loan, 2 = open a variable rate loan) * @param assets the assets being flashborrowed * @param amounts the amounts for each asset being borrowed **/ - function validateFlashloan( - address[] calldata assets, - uint256[] calldata amounts, - uint256[] calldata modes - ) external pure { - require( - assets.length == amounts.length && assets.length == modes.length, - Errors.INCONSISTENT_FLASHLOAN_PARAMS - ); - - for (uint256 i = 0; i < modes.length; i++) { - require( - modes[i] <= uint256(ReserveLogic.InterestRateMode.VARIABLE), - Errors.INVALID_FLASHLOAN_MODE - ); - } + function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { + require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS); } /** From b2bbe62822bff23bfd1339b8084624e1fe29b735 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 12:38:41 +0100 Subject: [PATCH 21/22] - Added `to` to withdraw() --- contracts/interfaces/ILendingPool.sol | 10 ++++++++-- contracts/lendingpool/LendingPool.sol | 13 +++++++++---- test/helpers/actions.ts | 8 +++++--- test/pausable-functions.spec.ts | 12 ++++++++++-- 4 files changed, 32 insertions(+), 11 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 2e4e2d94..4848df78 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -27,9 +27,10 @@ interface ILendingPool { * @dev emitted during a withdraw action. * @param reserve the address of the reserve * @param user the address of the user + * @param to address that will receive the underlying * @param amount the amount to be withdrawn **/ - event Withdraw(address indexed reserve, address indexed user, uint256 amount); + event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); event BorrowAllowanceDelegated( address indexed asset, @@ -188,8 +189,13 @@ interface ILendingPool { * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed + * @param to address that will receive the underlying **/ - function withdraw(address reserve, uint256 amount) external; + function withdraw( + address reserve, + uint256 amount, + address to + ) external; /** * @dev Sets allowance to borrow on a certain type of debt asset for a certain user address diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 3c2fcd8a..4faae912 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -120,8 +120,13 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage * @dev withdraws the _reserves of user. * @param asset the address of the reserve * @param amount the underlying amount to be redeemed + * @param to address that will receive the underlying **/ - function withdraw(address asset, uint256 amount) external override { + function withdraw( + address asset, + uint256 amount, + address to + ) external override { _whenNotPaused(); ReserveLogic.ReserveData storage reserve = _reserves[asset]; @@ -155,9 +160,9 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); } - IAToken(aToken).burn(msg.sender, msg.sender, amountToWithdraw, reserve.liquidityIndex); + IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); - emit Withdraw(asset, msg.sender, amountToWithdraw); + emit Withdraw(asset, msg.sender, to, amountToWithdraw); } /** @@ -892,7 +897,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage //caching the current stable borrow rate uint256 currentStableRate = 0; - + bool isFirstBorrowing = false; if ( ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 422b0455..82701087 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -231,7 +231,7 @@ export const withdraw = async ( if (expectedResult === 'success') { const txResult = await waitForTx( - await pool.connect(user.signer).withdraw(reserve, amountToWithdraw) + await pool.connect(user.signer).withdraw(reserve, amountToWithdraw, user.address) ); const { @@ -269,8 +269,10 @@ export const withdraw = async ( // ); // }); } else if (expectedResult === 'revert') { - await expect(pool.connect(user.signer).withdraw(reserve, amountToWithdraw), revertMessage).to.be - .reverted; + await expect( + pool.connect(user.signer).withdraw(reserve, amountToWithdraw, user.address), + revertMessage + ).to.be.reverted; } }; diff --git a/test/pausable-functions.spec.ts b/test/pausable-functions.spec.ts index 7a24da2d..72be7ada 100644 --- a/test/pausable-functions.spec.ts +++ b/test/pausable-functions.spec.ts @@ -116,7 +116,7 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { // user tries to burn await expect( - pool.connect(users[0].signer).withdraw(dai.address, amountDAItoDeposit) + pool.connect(users[0].signer).withdraw(dai.address, amountDAItoDeposit, users[0].address) ).to.revertedWith(IS_PAUSED); // Configurator unpauses the pool @@ -187,7 +187,15 @@ makeSuite('Pausable Pool', (testEnv: TestEnv) => { await expect( pool .connect(caller.signer) - .flashLoan(_mockFlashLoanReceiver.address, [weth.address], [flashAmount], 1, caller.address, '0x10', '0') + .flashLoan( + _mockFlashLoanReceiver.address, + [weth.address], + [flashAmount], + 1, + caller.address, + '0x10', + '0' + ) ).revertedWith(IS_PAUSED); // Unpause pool From 631d6ebfcbcd6fadb0ea11baf5220e9b57863866 Mon Sep 17 00:00:00 2001 From: eboado Date: Fri, 30 Oct 2020 13:32:42 +0100 Subject: [PATCH 22/22] - Passed `initiator` param to flashLoan()'s executeOperation() receiver. - Removed unused ISwapAdapter. --- .../interfaces/IFlashLoanReceiver.sol | 1 + contracts/interfaces/ISwapAdapter.sol | 20 ------------------- contracts/lendingpool/LendingPool.sol | 5 ++--- .../LendingPoolCollateralManager.sol | 1 - .../mocks/flashloan/MockFlashLoanReceiver.sol | 2 ++ 5 files changed, 5 insertions(+), 24 deletions(-) delete mode 100644 contracts/interfaces/ISwapAdapter.sol diff --git a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol index 784d0fa3..af9e384f 100644 --- a/contracts/flashloan/interfaces/IFlashLoanReceiver.sol +++ b/contracts/flashloan/interfaces/IFlashLoanReceiver.sol @@ -12,6 +12,7 @@ interface IFlashLoanReceiver { address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, + address initiator, bytes calldata params ) external returns (bool); } diff --git a/contracts/interfaces/ISwapAdapter.sol b/contracts/interfaces/ISwapAdapter.sol deleted file mode 100644 index ed91f95f..00000000 --- a/contracts/interfaces/ISwapAdapter.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: agpl-3.0 -pragma solidity ^0.6.8; - -interface ISwapAdapter { - /** - * @dev Swaps an `amountToSwap` of an asset to another, approving a `fundsDestination` to pull the funds - * @param assetToSwapFrom Origin asset - * @param assetToSwapTo Destination asset - * @param amountToSwap How much `assetToSwapFrom` needs to be swapped - * @param fundsDestination Address that will be pulling the swapped funds - * @param params Additional variadic field to include extra params - */ - function executeOperation( - address assetToSwapFrom, - address assetToSwapTo, - uint256 amountToSwap, - address fundsDestination, - bytes calldata params - ) external; -} diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 3c2fcd8a..c6455947 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -20,7 +20,6 @@ import {IStableDebtToken} from '../tokenization/interfaces/IStableDebtToken.sol' import {IVariableDebtToken} from '../tokenization/interfaces/IVariableDebtToken.sol'; import {DebtTokenBase} from '../tokenization/base/DebtTokenBase.sol'; import {IFlashLoanReceiver} from '../flashloan/interfaces/IFlashLoanReceiver.sol'; -import {ISwapAdapter} from '../interfaces/ISwapAdapter.sol'; import {LendingPoolCollateralManager} from './LendingPoolCollateralManager.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; @@ -539,7 +538,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage //execute action of the receiver require( - vars.receiver.executeOperation(assets, amounts, premiums, params), + vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.INVALID_FLASH_LOAN_EXECUTOR_RETURN ); @@ -892,7 +891,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage //caching the current stable borrow rate uint256 currentStableRate = 0; - + bool isFirstBorrowing = false; if ( ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE diff --git a/contracts/lendingpool/LendingPoolCollateralManager.sol b/contracts/lendingpool/LendingPoolCollateralManager.sol index 16abdd10..96f555d3 100644 --- a/contracts/lendingpool/LendingPoolCollateralManager.sol +++ b/contracts/lendingpool/LendingPoolCollateralManager.sol @@ -15,7 +15,6 @@ import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; -import {ISwapAdapter} from '../interfaces/ISwapAdapter.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; diff --git a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol index 7b72c2cb..215746ae 100644 --- a/contracts/mocks/flashloan/MockFlashLoanReceiver.sol +++ b/contracts/mocks/flashloan/MockFlashLoanReceiver.sol @@ -47,9 +47,11 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase { address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, + address initiator, bytes memory params ) public override returns (bool) { params; + initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums);