From 3df87a8e5d8f289c80612cbe756f66900c2874e9 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 11:25:45 +0200 Subject: [PATCH 01/45] Initial commit --- contracts/tokenization/StableDebtToken.sol | 25 ++++++++ contracts/tokenization/VariableDebtToken.sol | 62 ++++--------------- contracts/tokenization/base/DebtTokenBase.sol | 23 ------- .../interfaces/IVariableDebtToken.sol | 12 ---- 4 files changed, 38 insertions(+), 84 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 4fdcad09..a30219e3 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -182,4 +182,29 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { emit BurnDebt(user, amount, previousBalance, currentBalance, balanceIncrease); } + + + /** + * @dev Calculates the increase in balance since the last user interaction + * @param user The address of the user for which the interest is being accumulated + * @return The previous principal balance, the new principal balance, the balance increase + * and the new user index + **/ + function _calculateBalanceIncrease(address user) internal view returns (uint256, uint256, uint256) { + uint256 previousPrincipalBalance = principalBalanceOf(user); + + if (previousPrincipalBalance == 0) { + return (0, 0, 0); + } + + // Calculation of the accrued interest since the last accumulation + uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); + + return ( + previousPrincipalBalance, + previousPrincipalBalance.add(balanceIncrease), + balanceIncrease + ); + } + } diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 580151eb..1fcda07a 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -38,27 +38,15 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @return the debt balance of the user **/ function balanceOf(address user) public virtual override view returns (uint256) { - uint256 userBalance = principalBalanceOf(user); - uint256 index = _usersData[user]; - if (userBalance == 0) { + uint256 scaledBalance = principalBalanceOf(user); + + if (scaledBalance == 0) { return 0; } return - userBalance - .wadToRay() - .rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)) - .rayDiv(index) - .rayToWad(); - } - - /** - * @dev returns the index of the last user action - * @return the user index - **/ - - function getUserIndex(address user) external virtual override view returns (uint256) { - return _usersData[user]; + scaledBalance + .rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); } /** @@ -66,20 +54,12 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @param user the user receiving the debt * @param amount the amount of debt being minted **/ - function mint(address user, uint256 amount) external override onlyLendingPool { - ( - uint256 previousBalance, - uint256 currentBalance, - uint256 balanceIncrease - ) = _calculateBalanceIncrease(user); + function mint(address user, uint256 amount) external override onlyLendingPool { + + uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); - _mint(user, amount.add(balanceIncrease)); - - uint256 newUserIndex = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); - require(newUserIndex < (1 << 128), "Debt token: Index overflow"); - _usersData[user] = newUserIndex; - - emit MintDebt(user, amount, previousBalance, currentBalance, balanceIncrease, newUserIndex); + _mint(user, amount.rayDiv(index)); + emit MintDebt(user, amount, index); } /** @@ -88,26 +68,10 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @param amount the amount of debt being burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { - ( - uint256 previousBalance, - uint256 currentBalance, - uint256 balanceIncrease - ) = _calculateBalanceIncrease(user); - if (balanceIncrease > amount) { - _mint(user, balanceIncrease.sub(amount)); - } else { - _burn(user, amount.sub(balanceIncrease)); - } + uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); + _burn(user, amount.rayDiv(index)); - uint256 newUserIndex = 0; - //if user not repaid everything - if (currentBalance != amount) { - newUserIndex = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); - require(newUserIndex < (1 << 128), "Debt token: Index overflow"); - } - _usersData[user] = newUserIndex; - - emit BurnDebt(user, amount, previousBalance, currentBalance, balanceIncrease, newUserIndex); + emit BurnDebt(user, amount, index); } } diff --git a/contracts/tokenization/base/DebtTokenBase.sol b/contracts/tokenization/base/DebtTokenBase.sol index 04009023..ec021951 100644 --- a/contracts/tokenization/base/DebtTokenBase.sol +++ b/contracts/tokenization/base/DebtTokenBase.sol @@ -104,27 +104,4 @@ abstract contract DebtTokenBase is ERC20, VersionedInitializable { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } - - /** - * @dev Calculates the increase in balance since the last user interaction - * @param user The address of the user for which the interest is being accumulated - * @return The previous principal balance, the new principal balance, the balance increase - * and the new user index - **/ - function _calculateBalanceIncrease(address user) internal view returns (uint256, uint256, uint256) { - uint256 previousPrincipalBalance = principalBalanceOf(user); - - if (previousPrincipalBalance == 0) { - return (0, 0, 0); - } - - // Calculation of the accrued interest since the last accumulation - uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); - - return ( - previousPrincipalBalance, - previousPrincipalBalance.add(balanceIncrease), - balanceIncrease - ); - } } diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index fdd86a0d..e979b4a5 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -12,17 +12,11 @@ interface IVariableDebtToken { * @dev emitted when new variable debt is minted * @param user the user receiving the debt * @param amount the amount of debt being minted - * @param previousBalance the previous balance of the user - * @param currentBalance the current balance of the user - * @param balanceIncrease the debt accumulated since the last action * @param index the index of the user **/ event MintDebt( address user, uint256 amount, - uint256 previousBalance, - uint256 currentBalance, - uint256 balanceIncrease, uint256 index ); @@ -30,17 +24,11 @@ interface IVariableDebtToken { * @dev emitted when variable debt is burnt * @param user the user which debt has been burned * @param amount the amount of debt being burned - * @param previousBalance the previous balance of the user - * @param currentBalance the current balance of the user - * @param balanceIncrease the debt accumulated since the last action * @param index the index of the user **/ event BurnDebt( address user, uint256 amount, - uint256 previousBalance, - uint256 currentBalance, - uint256 balanceIncrease, uint256 index ); From 4a1e1156f48447526e38d194d8a217a8cdb626ca Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 12:51:52 +0200 Subject: [PATCH 02/45] Merge local branch --- contracts/interfaces/ILendingPool.sol | 1 - .../IReserveInterestRateStrategy.sol | 3 +- .../DefaultReserveInterestRateStrategy.sol | 48 ++++++++++++------- contracts/lendingpool/LendingPool.sol | 44 +++++++++++++++-- .../LendingPoolLiquidationManager.sol | 38 +++++++++++++-- .../configuration/ReserveConfiguration.sol | 19 ++++++++ contracts/libraries/logic/ReserveLogic.sol | 3 +- contracts/mocks/upgradeability/MockAToken.sol | 2 +- contracts/tokenization/AToken.sol | 8 ++++ contracts/tokenization/VariableDebtToken.sol | 12 ++++- contracts/tokenization/base/DebtTokenBase.sol | 2 +- contracts/tokenization/interfaces/IAToken.sol | 8 ++++ .../interfaces/IVariableDebtToken.sol | 5 -- 13 files changed, 158 insertions(+), 35 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index a7a5e1ca..12119a3a 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -305,7 +305,6 @@ interface ILendingPool { uint256 principalVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, - uint256 variableBorrowIndex, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); diff --git a/contracts/interfaces/IReserveInterestRateStrategy.sol b/contracts/interfaces/IReserveInterestRateStrategy.sol index 48311e70..acc097bf 100644 --- a/contracts/interfaces/IReserveInterestRateStrategy.sol +++ b/contracts/interfaces/IReserveInterestRateStrategy.sol @@ -23,7 +23,8 @@ interface IReserveInterestRateStrategy { uint256 utilizationRate, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, - uint256 averageStableBorrowRate + uint256 averageStableBorrowRate, + uint256 reserveFactor ) external view diff --git a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol index c2303254..c93e6c38 100644 --- a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol +++ b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol @@ -49,6 +49,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { //slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; + constructor( LendingPoolAddressesProvider provider, uint256 baseVariableBorrowRate, @@ -89,6 +90,15 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { return _baseVariableBorrowRate; } + struct CalcInterestRatesLocalVars { + + uint256 totalBorrows; + uint256 currentVariableBorrowRate; + uint256 currentStableBorrowRate; + uint256 currentLiquidityRate; + uint256 utilizationRate; + } + /** * @dev calculates the interest rates depending on the available liquidity and the total borrowed. * @param reserve the address of the reserve @@ -96,6 +106,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { * @param totalBorrowsStable the total borrowed from the reserve a stable rate * @param totalBorrowsVariable the total borrowed from the reserve at a variable rate * @param averageStableBorrowRate the weighted average of all the stable rate borrows + * @param reserveFactor the reserve portion of the interest to redirect to the reserve treasury * @return currentLiquidityRate the liquidity rate * @return currentStableBorrowRate stable borrow rate * @return currentVariableBorrowRate variable borrow rate @@ -105,7 +116,8 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, - uint256 averageStableBorrowRate + uint256 averageStableBorrowRate, + uint256 reserveFactor ) external override @@ -116,16 +128,19 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { uint256 ) { - uint256 totalBorrows = totalBorrowsStable.add(totalBorrowsVariable); - uint256 currentVariableBorrowRate = 0; - uint256 currentStableBorrowRate = 0; - uint256 currentLiquidityRate = 0; - uint256 utilizationRate = totalBorrows == 0 + CalcInterestRatesLocalVars memory vars; + + vars.totalBorrows = totalBorrowsStable.add(totalBorrowsVariable); + vars.currentVariableBorrowRate = 0; + vars.currentStableBorrowRate = 0; + vars.currentLiquidityRate = 0; + + uint256 utilizationRate = vars.totalBorrows == 0 ? 0 - : totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); + : vars.totalBorrows.rayDiv(availableLiquidity.add(vars.totalBorrows)); - currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) + vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (utilizationRate > OPTIMAL_UTILIZATION_RATE) { @@ -133,31 +148,32 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { EXCESS_UTILIZATION_RATE ); - currentStableBorrowRate = currentStableBorrowRate.add(_stableRateSlope1).add( + vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); - currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( + vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { - currentStableBorrowRate = currentStableBorrowRate.add( + vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); - currentVariableBorrowRate = _baseVariableBorrowRate.add( + vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE).rayMul(_variableRateSlope1) ); } - currentLiquidityRate = _getOverallBorrowRate( + vars.currentLiquidityRate = _getOverallBorrowRate( totalBorrowsStable, totalBorrowsVariable, - currentVariableBorrowRate, + vars.currentVariableBorrowRate, averageStableBorrowRate ) - .rayMul(utilizationRate); + .rayMul(utilizationRate) + .rayMul(WadRayMath.ray().sub(reserveFactor)); - return (currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate); + return (vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate); } /** diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 9e4e6707..50944f9f 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -12,6 +12,7 @@ import {IAToken} from '../tokenization/interfaces/IAToken.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; +import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; @@ -19,12 +20,12 @@ import {ReserveConfiguration} from '../libraries/configuration/ReserveConfigurat import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; 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 {LendingPoolLiquidationManager} from './LendingPoolLiquidationManager.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; - /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data @@ -34,6 +35,7 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; contract LendingPool is VersionedInitializable, ILendingPool { using SafeMath for uint256; using WadRayMath for uint256; + using PercentageMath for uint256; using ReserveLogic for ReserveLogic.ReserveData; using ReserveConfiguration for ReserveConfiguration.Map; using UserConfiguration for UserConfiguration.Map; @@ -224,6 +226,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); + address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress : reserve.variableDebtTokenAddress; + _mintToReserveTreasury(reserve, onBehalfOf, debtTokenAddress); + //burns an equivalent amount of debt tokens if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); @@ -265,6 +270,10 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); + address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress : reserve.variableDebtTokenAddress; + _mintToReserveTreasury(reserve, msg.sender, debtTokenAddress); + + if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); @@ -321,6 +330,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); + _mintToReserveTreasury(reserve, user, address(stableDebtToken)); + + stableDebtToken.burn(user, stableBorrowBalance); stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); @@ -609,7 +621,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 principalVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, - uint256 variableBorrowIndex, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) @@ -625,7 +636,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { user ); usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.index); - variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(user); } function getReserves() external override view returns (address[] memory) { @@ -706,6 +716,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param vars Input struct for the borrowing action, in order to avoid STD errors **/ function _executeBorrow(ExecuteBorrowParams memory vars) internal { + ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; @@ -730,13 +741,21 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 reserveIndex = reserve.index; + if (!userConfig.isBorrowing(reserveIndex)) { userConfig.setBorrowing(reserveIndex, true); } + address debtTokenAddress = ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE ? + reserve.stableDebtTokenAddress + : + reserve.variableDebtTokenAddress; + reserve.updateCumulativeIndexesAndTimestamp(); + _mintToReserveTreasury(reserve, vars.user, debtTokenAddress); + //caching the current stable borrow rate uint256 currentStableRate = 0; @@ -745,13 +764,13 @@ contract LendingPool is VersionedInitializable, ILendingPool { ) { currentStableRate = reserve.currentStableBorrowRate; - IStableDebtToken(reserve.stableDebtTokenAddress).mint( + IStableDebtToken(debtTokenAddress).mint( vars.user, vars.amount, currentStableRate ); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount); + IVariableDebtToken(debtTokenAddress).mint(vars.user, vars.amount); } reserve.updateInterestRates(vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0); @@ -848,4 +867,19 @@ contract LendingPool is VersionedInitializable, ILendingPool { function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { return _addressesProvider; } + + function _mintToReserveTreasury(ReserveLogic.ReserveData storage reserve, address user, address debtTokenAddress) internal { + + uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); + //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor + if(currentPrincipalBalance > 0){ + + uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub(currentPrincipalBalance); + + uint256 amountForReserveFactor = balanceIncrease.percentMul(reserve.configuration.getReserveFactor()); + + IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); + } + + } } diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 12ecf777..dee6d90c 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -10,6 +10,7 @@ import {LendingPoolAddressesProvider} from '../configuration/LendingPoolAddresse import {IAToken} from '../tokenization/interfaces/IAToken.sol'; import {IStableDebtToken} from '../tokenization/interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../tokenization/interfaces/IVariableDebtToken.sol'; +import {DebtTokenBase} from '../tokenization/base/DebtTokenBase.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; @@ -208,6 +209,9 @@ contract LendingPoolLiquidationManager is VersionedInitializable { //update the principal reserve principalReserve.updateCumulativeIndexesAndTimestamp(); + + + principalReserve.updateInterestRates( principal, principalReserve.aTokenAddress, @@ -216,16 +220,29 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ); if (vars.userVariableDebt >= vars.actualAmountToLiquidate) { - IVariableDebtToken(principalReserve.variableDebtTokenAddress).burn( + + address tokenAddress = principalReserve.variableDebtTokenAddress; + + _mintToReserveTreasury(principalReserve, user, tokenAddress); + + IVariableDebtToken(tokenAddress).burn( user, vars.actualAmountToLiquidate ); } else { - IVariableDebtToken(principalReserve.variableDebtTokenAddress).burn( + + address tokenAddress = principalReserve.variableDebtTokenAddress; + + _mintToReserveTreasury(principalReserve, user, tokenAddress); + + IVariableDebtToken(tokenAddress).burn( user, vars.userVariableDebt ); - IStableDebtToken(principalReserve.stableDebtTokenAddress).burn( + + tokenAddress = principalReserve.stableDebtTokenAddress; + + IStableDebtToken(tokenAddress).burn( user, vars.actualAmountToLiquidate.sub(vars.userVariableDebt) ); @@ -337,4 +354,19 @@ contract LendingPoolLiquidationManager is VersionedInitializable { } return (collateralAmount, principalAmountNeeded); } + + function _mintToReserveTreasury(ReserveLogic.ReserveData storage reserve, address user, address debtTokenAddress) internal { + + uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); + //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor + if(currentPrincipalBalance > 0){ + + uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub(currentPrincipalBalance); + + uint256 amountForReserveFactor = balanceIncrease.percentMul(reserve.configuration.getReserveFactor()); + + IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); + } + + } } diff --git a/contracts/libraries/configuration/ReserveConfiguration.sol b/contracts/libraries/configuration/ReserveConfiguration.sol index 46ad9ba9..96c0024c 100644 --- a/contracts/libraries/configuration/ReserveConfiguration.sol +++ b/contracts/libraries/configuration/ReserveConfiguration.sol @@ -21,6 +21,7 @@ library ReserveConfiguration { uint256 constant FROZEN_MASK = 0xDFFFFFFFFFFFFFF; uint256 constant BORROWING_MASK = 0xBFFFFFFFFFFFFFF; uint256 constant STABLE_BORROWING_MASK = 0x7FFFFFFFFFFFFFF; + uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFF; struct Map { //bit 0-15: LTV @@ -31,9 +32,27 @@ library ReserveConfiguration { //bit 57: reserve is freezed //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled + //bit 64-79: reserve factor uint256 data; } + /** + * @dev sets the reserve factor of the reserve + * @param self the reserve configuration + * @param ltv the new ltv + **/ + function setReserveFactor(ReserveConfiguration.Map memory self, uint256 ltv) internal pure { + self.data = (self.data & RESERVE_FACTOR_MASK) | ltv; + } + + /** + * @dev gets the reserve factor of the reserve + * @param self the reserve configuration + * @return the reserve factor + **/ + function getReserveFactor(ReserveConfiguration.Map storage self) internal view returns (uint256) { + return self.data & ~RESERVE_FACTOR_MASK; + } /** * @dev sets the Loan to Value of the reserve * @param self the reserve configuration diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 607c8c63..90ed10cf 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -246,7 +246,8 @@ library ReserveLogic { vars.availableLiquidity.add(liquidityAdded).sub(liquidityTaken), IERC20(vars.stableDebtTokenAddress).totalSupply(), IERC20(reserve.variableDebtTokenAddress).totalSupply(), - vars.currentAvgStableRate + vars.currentAvgStableRate, + reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate < (1 << 128), "ReserveLogic: Liquidity rate overflow"); require(vars.newStableRate < (1 << 128), "ReserveLogic: Stable borrow rate overflow"); diff --git a/contracts/mocks/upgradeability/MockAToken.sol b/contracts/mocks/upgradeability/MockAToken.sol index 05f0db4e..a0368535 100644 --- a/contracts/mocks/upgradeability/MockAToken.sol +++ b/contracts/mocks/upgradeability/MockAToken.sol @@ -10,7 +10,7 @@ contract MockAToken is AToken { address _underlyingAssetAddress, string memory _tokenName, string memory _tokenSymbol - ) public AToken(_pool, _underlyingAssetAddress, _tokenName, _tokenSymbol) {} + ) public AToken(_pool, _underlyingAssetAddress,address(0), _tokenName, _tokenSymbol) {} function getRevision() internal override pure returns (uint256) { return 0x2; diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index de178819..36ca5ecb 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -25,6 +25,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { uint256 public constant UINT_MAX_VALUE = uint256(-1); address public immutable UNDERLYING_ASSET_ADDRESS; + address public immutable RESERVE_TREASURY_ADDRESS; mapping(address => uint256) private _userIndexes; mapping(address => address) private _interestRedirectionAddresses; @@ -48,11 +49,13 @@ contract AToken is VersionedInitializable, ERC20, IAToken { constructor( LendingPool pool, address underlyingAssetAddress, + address reserveTreasuryAddress, string memory tokenName, string memory tokenSymbol ) public ERC20(tokenName, tokenSymbol, 18) { _pool = pool; UNDERLYING_ASSET_ADDRESS = underlyingAssetAddress; + RESERVE_TREASURY_ADDRESS = reserveTreasuryAddress; } function getRevision() internal virtual override pure returns (uint256) { @@ -183,6 +186,11 @@ contract AToken is VersionedInitializable, ERC20, IAToken { emit Mint(user, amount, balanceIncrease, index); } + function mintToReserve(uint256 amount) external override onlyLendingPool { + uint256 index = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); + _mint(RESERVE_TREASURY_ADDRESS, amount.div(index)); + } + /** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * only lending pools can call this function diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 1fcda07a..80f626f9 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -17,6 +17,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; + mapping(address => uint256) _userIndexes; constructor( address pool, @@ -59,6 +60,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); _mint(user, amount.rayDiv(index)); + _userIndexes[user] = index; emit MintDebt(user, amount, index); } @@ -71,7 +73,15 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); _burn(user, amount.rayDiv(index)); - + _userIndexes[user] = index; emit BurnDebt(user, amount, index); } + + /** + * @dev Returns the principal debt balance of the user from + * @return The debt balance of the user since the last burn/mint action + **/ + function principalBalanceOf(address user) public virtual override view returns (uint256) { + return super.balanceOf(user).rayMul(_userIndexes[user]); + } } diff --git a/contracts/tokenization/base/DebtTokenBase.sol b/contracts/tokenization/base/DebtTokenBase.sol index ec021951..21d4dcf6 100644 --- a/contracts/tokenization/base/DebtTokenBase.sol +++ b/contracts/tokenization/base/DebtTokenBase.sol @@ -67,7 +67,7 @@ abstract contract DebtTokenBase is ERC20, VersionedInitializable { * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ - function principalBalanceOf(address user) public view returns (uint256) { + function principalBalanceOf(address user) public virtual view returns (uint256) { return super.balanceOf(user); } diff --git a/contracts/tokenization/interfaces/IAToken.sol b/contracts/tokenization/interfaces/IAToken.sol index 65ad0cfa..ec6898fe 100644 --- a/contracts/tokenization/interfaces/IAToken.sol +++ b/contracts/tokenization/interfaces/IAToken.sol @@ -127,6 +127,14 @@ interface IAToken is IERC20 { */ function mint(address user, uint256 amount) external; + /** + * @dev mints aTokens to reserve, based on the reserveFactor value + * only lending pools can call this function + * @param amount the amount of tokens to mint + */ + function mintToReserve(uint256 amount) external; + + /** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * only lending pools can call this function diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index e979b4a5..6f58e2d2 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -46,9 +46,4 @@ interface IVariableDebtToken { **/ function burn(address user, uint256 amount) external; - /** - * @dev returns the last index of the user - * @return the index of the user - **/ - function getUserIndex(address user) external view returns (uint256); } From de8ae523c8b0373df7a408003ae9241508d57d85 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 13:05:02 +0200 Subject: [PATCH 03/45] Fixed total supply, tests --- contracts/interfaces/ILendingPool.sol | 1 + contracts/lendingpool/LendingPool.sol | 2 ++ contracts/tokenization/VariableDebtToken.sol | 14 +++++++++++++- .../tokenization/interfaces/IVariableDebtToken.sol | 6 ++++++ helpers/contracts-helpers.ts | 5 ++++- test/__setup.spec.ts | 1 + test/helpers/utils/calculations.ts | 7 ++----- test/helpers/utils/helpers.ts | 2 +- test/helpers/utils/interfaces/index.ts | 2 +- 9 files changed, 31 insertions(+), 9 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 12119a3a..177f04d8 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -303,6 +303,7 @@ interface ILendingPool { uint256 currentVariableDebt, uint256 principalStableDebt, uint256 principalVariableDebt, + uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 50944f9f..902388f0 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -619,6 +619,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 currentVariableDebt, uint256 principalStableDebt, uint256 principalVariableDebt, + uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, @@ -630,6 +631,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); + scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 80f626f9..0fb4c0bd 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -39,7 +39,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @return the debt balance of the user **/ function balanceOf(address user) public virtual override view returns (uint256) { - uint256 scaledBalance = principalBalanceOf(user); + uint256 scaledBalance = super.principalBalanceOf(user); if (scaledBalance == 0) { return 0; @@ -84,4 +84,16 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { function principalBalanceOf(address user) public virtual override view returns (uint256) { return super.balanceOf(user).rayMul(_userIndexes[user]); } + + /** + * @dev Returns the principal debt balance of the user from + * @return The debt balance of the user since the last burn/mint action + **/ + function scaledBalanceOf(address user) public virtual override view returns (uint256) { + return super.balanceOf(user); + } + + function totalSupply() public virtual override view returns(uint256) { + return super.totalSupply().rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); + } } diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index 6f58e2d2..01b2aaca 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -46,4 +46,10 @@ interface IVariableDebtToken { **/ function burn(address user, uint256 amount) external; + /** + * @dev returns the scaled balance of the variable debt token + * @param user the user + **/ + function scaledBalanceOf(address user) external view returns(uint256); + } diff --git a/helpers/contracts-helpers.ts b/helpers/contracts-helpers.ts index b5b483d3..1743b416 100644 --- a/helpers/contracts-helpers.ts +++ b/helpers/contracts-helpers.ts @@ -31,6 +31,7 @@ import BigNumber from 'bignumber.js'; import {Ierc20Detailed} from '../types/Ierc20Detailed'; import {StableDebtToken} from '../types/StableDebtToken'; import {VariableDebtToken} from '../types/VariableDebtToken'; +import { ZERO_ADDRESS } from './constants'; export const registerContractInJsonDb = async (contractId: string, contractInstance: Contract) => { const currentNetwork = BRE.network.name; @@ -277,7 +278,8 @@ export const deployVariableDebtToken = async ([name, symbol, underlyingAsset, po return token; }; -export const deployGenericAToken = async ([poolAddress, underlyingAssetAddress, name, symbol]: [ +export const deployGenericAToken = async ([poolAddress, underlyingAssetAddress, reserveTreasuryAddress, name, symbol]: [ + tEthereumAddress, tEthereumAddress, tEthereumAddress, string, @@ -286,6 +288,7 @@ export const deployGenericAToken = async ([poolAddress, underlyingAssetAddress, const token = await deployContract(eContractid.AToken, [ poolAddress, underlyingAssetAddress, + ZERO_ADDRESS, name, symbol, ]); diff --git a/test/__setup.spec.ts b/test/__setup.spec.ts index 342b7b64..fa4d557f 100644 --- a/test/__setup.spec.ts +++ b/test/__setup.spec.ts @@ -241,6 +241,7 @@ const initReserves = async ( const aToken = await deployGenericAToken([ lendingPool.address, tokenAddress, + ZERO_ADDRESS, `Aave interest bearing ${assetSymbol === 'WETH' ? 'ETH' : assetSymbol}`, `a${assetSymbol === 'WETH' ? 'ETH' : assetSymbol}`, ]); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 4ff03b19..c50703d9 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -1164,13 +1164,10 @@ export const calcExpectedVariableDebtTokenBalance = ( ) => { const debt = calcExpectedReserveNormalizedDebt(reserveDataBeforeAction, currentTimestamp); - const { principalVariableDebt, variableBorrowIndex } = userDataBeforeAction; + const { scaledVariableDebt } = userDataBeforeAction; - if (variableBorrowIndex.eq(0)) { - return principalVariableDebt; - } - return principalVariableDebt.wadToRay().rayMul(debt).rayDiv(variableBorrowIndex).rayToWad(); + return scaledVariableDebt.rayMul(debt); }; export const calcExpectedStableDebtTokenBalance = ( diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index c20c67ac..1e0218b1 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -90,7 +90,7 @@ export const getUserData = async ( currentVariableDebt: new BigNumber(userData.currentVariableDebt.toString()), principalStableDebt: new BigNumber(userData.principalStableDebt.toString()), principalVariableDebt: new BigNumber(userData.principalVariableDebt.toString()), - variableBorrowIndex: new BigNumber(userData.variableBorrowIndex.toString()), + scaledVariableDebt: new BigNumber(userData.scaledVariableDebt.toString()), stableBorrowRate: new BigNumber(userData.stableBorrowRate.toString()), liquidityRate: new BigNumber(userData.liquidityRate.toString()), usageAsCollateralEnabled: userData.usageAsCollateralEnabled, diff --git a/test/helpers/utils/interfaces/index.ts b/test/helpers/utils/interfaces/index.ts index aa84ad3d..952bbf25 100644 --- a/test/helpers/utils/interfaces/index.ts +++ b/test/helpers/utils/interfaces/index.ts @@ -11,7 +11,7 @@ export interface UserReserveData { currentVariableDebt: BigNumber; principalStableDebt: BigNumber; principalVariableDebt: BigNumber; - variableBorrowIndex: BigNumber; + scaledVariableDebt: BigNumber; liquidityRate: BigNumber; stableBorrowRate: BigNumber; stableRateLastUpdated: BigNumber; From af362141fd9d18dc053dc198a5891a68818ac065 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 13:16:32 +0200 Subject: [PATCH 04/45] Added reserveFactor to getReserveConfigurationData --- contracts/interfaces/ILendingPool.sol | 1 + contracts/lendingpool/LendingPool.sol | 9 ++++++++- contracts/lendingpool/LendingPoolConfigurator.sol | 2 +- contracts/misc/WalletBalanceProvider.sol | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 177f04d8..587e151b 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -249,6 +249,7 @@ interface ILendingPool { uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, + uint256 reserveFactor, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 902388f0..2cd1a962 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -500,6 +500,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, + uint256 reserveFactor, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, @@ -515,6 +516,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.configuration.getLtv(), reserve.configuration.getLiquidationThreshold(), reserve.configuration.getLiquidationBonus(), + reserve.configuration.getReserveFactor(), reserve.interestRateStrategyAddress, reserve.configuration.getLtv() != 0, reserve.configuration.getBorrowingEnabled(), @@ -872,13 +874,18 @@ contract LendingPool is VersionedInitializable, ILendingPool { function _mintToReserveTreasury(ReserveLogic.ReserveData storage reserve, address user, address debtTokenAddress) internal { + uint256 reserveFactor = reserve.configuration.getReserveFactor(); + if(reserveFactor == 0) { + return; + } + uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor if(currentPrincipalBalance > 0){ uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub(currentPrincipalBalance); - uint256 amountForReserveFactor = balanceIncrease.percentMul(reserve.configuration.getReserveFactor()); + uint256 amountForReserveFactor = balanceIncrease.percentMul(reserveFactor); IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); } diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index e9c0a292..97998556 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -571,7 +571,7 @@ contract LendingPoolConfigurator is VersionedInitializable { payable(proxyAddress) ); - (uint256 decimals, , , , , , , , , ) = pool.getReserveConfigurationData(asset); + (uint256 decimals, , , , , , , , , , ) = pool.getReserveConfigurationData(asset); bytes memory params = abi.encodeWithSignature( 'initialize(uint8,string,string)', diff --git a/contracts/misc/WalletBalanceProvider.sol b/contracts/misc/WalletBalanceProvider.sol index d4497178..c52b5f21 100644 --- a/contracts/misc/WalletBalanceProvider.sol +++ b/contracts/misc/WalletBalanceProvider.sol @@ -91,7 +91,7 @@ contract WalletBalanceProvider { uint256[] memory balances = new uint256[](reserves.length); for (uint256 j = 0; j < reserves.length; j++) { - (, , , , , , , , bool isActive, ) = pool.getReserveConfigurationData(reserves[j]); + (, , , , , , , , , bool isActive, ) = pool.getReserveConfigurationData(reserves[j]); if (!isActive) { balances[j] = 0; From c3b1ab0585772efa4c88402b877fab650841e9c9 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 13:21:50 +0200 Subject: [PATCH 05/45] Refactored interestRateStrategy --- contracts/lendingpool/DefaultReserveInterestRateStrategy.sol | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol index c93e6c38..f03b3c94 100644 --- a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol +++ b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol @@ -4,6 +4,7 @@ pragma solidity ^0.6.8; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; +import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {LendingPoolAddressesProvider} from '../configuration/LendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../interfaces/ILendingRateOracle.sol'; @@ -17,7 +18,7 @@ import {ILendingRateOracle} from '../interfaces/ILendingRateOracle.sol'; contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; - + using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates * expressed in ray @@ -171,7 +172,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { averageStableBorrowRate ) .rayMul(utilizationRate) - .rayMul(WadRayMath.ray().sub(reserveFactor)); + .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return (vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate); } From 3563f1379d852721d212ddbccd8f3165850351e0 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 13:26:02 +0200 Subject: [PATCH 06/45] Updated configurator for the reserve factor --- .../lendingpool/LendingPoolConfigurator.sol | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 97998556..42cbffb3 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -118,6 +118,13 @@ contract LendingPoolConfigurator is VersionedInitializable { **/ event ReserveBaseLtvChanged(address 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); + /** * @dev emitted when a reserve liquidation threshold is updated * @param asset the address of the reserve @@ -467,7 +474,7 @@ contract LendingPoolConfigurator is VersionedInitializable { } /** - * @dev emitted when a reserve loan to value is updated + * @dev updates the ltv of a reserve * @param asset the address of the reserve * @param ltv the new value for the loan to value **/ @@ -481,6 +488,22 @@ contract LendingPoolConfigurator is VersionedInitializable { emit ReserveBaseLtvChanged(asset, ltv); } + /** + * @dev updates the reserve factor of a reserve + * @param asset the address of the reserve + * @param reserveFactor the new reserve factor of the reserve + **/ + function setReserveFactor(address asset, uint256 reserveFactor) external onlyLendingPoolManager { + ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); + + currentConfig.setReserveFactor(reserveFactor); + + pool.setConfiguration(asset, currentConfig.data); + + emit ReserveFactorChanged(asset, reserveFactor); + } + + /** * @dev updates the liquidation threshold of a reserve. * @param asset the address of the reserve From 73d7ca001c3e637e9c2a2c5de70e1e99388b86dd Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 10 Sep 2020 13:52:07 +0200 Subject: [PATCH 07/45] added configurator tests --- .../configuration/ReserveConfiguration.sol | 27 ++++++++++--------- test/configurator.spec.ts | 17 ++++++++++++ test/scenario.spec.ts | 2 +- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/contracts/libraries/configuration/ReserveConfiguration.sol b/contracts/libraries/configuration/ReserveConfiguration.sol index 96c0024c..10471f6e 100644 --- a/contracts/libraries/configuration/ReserveConfiguration.sol +++ b/contracts/libraries/configuration/ReserveConfiguration.sol @@ -6,6 +6,7 @@ import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {ReserveLogic} from '../logic/ReserveLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; +import "@nomiclabs/buidler/console.sol"; /** * @title ReserveConfiguration library @@ -13,14 +14,14 @@ import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { - uint256 constant LTV_MASK = 0xFFFFFFFFFFF0000; - uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFF0000FFFF; - uint256 constant LIQUIDATION_BONUS_MASK = 0xFFF0000FFFFFFFF; - uint256 constant DECIMALS_MASK = 0xF00FFFFFFFFFFFF; - uint256 constant ACTIVE_MASK = 0xEFFFFFFFFFFFFFF; - uint256 constant FROZEN_MASK = 0xDFFFFFFFFFFFFFF; - uint256 constant BORROWING_MASK = 0xBFFFFFFFFFFFFFF; - uint256 constant STABLE_BORROWING_MASK = 0x7FFFFFFFFFFFFFF; + uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFF0000; + uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFF0000FFFF; + uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFF0000FFFFFFFF; + uint256 constant DECIMALS_MASK = 0xFFFFFF00FFFFFFFFFFFF; + uint256 constant ACTIVE_MASK = 0xFFFFFEFFFFFFFFFFFFFF; + uint256 constant FROZEN_MASK = 0xFFFFFDFFFFFFFFFFFFFF; + uint256 constant BORROWING_MASK = 0xFFFFFBFFFFFFFFFFFFFF; + uint256 constant STABLE_BORROWING_MASK = 0xFFFF07FFFFFFFFFFFFFF; uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFF; struct Map { @@ -39,10 +40,12 @@ library ReserveConfiguration { /** * @dev sets the reserve factor of the reserve * @param self the reserve configuration - * @param ltv the new ltv + * @param reserveFactor the reserve factor **/ - function setReserveFactor(ReserveConfiguration.Map memory self, uint256 ltv) internal pure { - self.data = (self.data & RESERVE_FACTOR_MASK) | ltv; + function setReserveFactor(ReserveConfiguration.Map memory self, uint256 reserveFactor) internal view { + console.log("Setting reserve factor to %s", reserveFactor); + + self.data = (self.data & RESERVE_FACTOR_MASK) | reserveFactor << 64; } /** @@ -51,7 +54,7 @@ library ReserveConfiguration { * @return the reserve factor **/ function getReserveFactor(ReserveConfiguration.Map storage self) internal view returns (uint256) { - return self.data & ~RESERVE_FACTOR_MASK; + return (self.data & ~RESERVE_FACTOR_MASK) >> 64; } /** * @dev sets the Loan to Value of the reserve diff --git a/test/configurator.spec.ts b/test/configurator.spec.ts index a6513e54..8b694afb 100644 --- a/test/configurator.spec.ts +++ b/test/configurator.spec.ts @@ -180,6 +180,23 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); }); + + it('Changes the reserve factor of the reserve', async () => { + const {configurator, pool, weth} = testEnv; + await configurator.setReserveFactor(weth.address, '1000'); + const {reserveFactor} = await pool.getReserveConfigurationData(weth.address); + expect(reserveFactor.toString()).to.be.bignumber.equal('1000', 'Invalid reserve factor'); + }); + + it('Check the onlyLendingPoolManager on setReserveFactor', async () => { + const {configurator, users, weth} = testEnv; + await expect( + configurator.connect(users[2].signer).setReserveFactor(weth.address, '2000'), + CALLER_NOT_LENDING_POOL_MANAGER + ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); + }); + + it('Changes liquidation threshold of the reserve', async () => { const {configurator, pool, weth} = testEnv; await configurator.setLiquidationThreshold(weth.address, '75'); diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 5d449d76..025bc720 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -12,7 +12,7 @@ BigNumber.config({DECIMAL_PLACES: 0, ROUNDING_MODE: BigNumber.ROUND_DOWN}); const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = []; +const selectedScenarios: string[] = ['']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From b5efaa740f6457896aff791c81399c255f6d0e62 Mon Sep 17 00:00:00 2001 From: The3D Date: Fri, 11 Sep 2020 15:22:54 +0200 Subject: [PATCH 08/45] Added total supply timestamp on the stable debt token --- contracts/tokenization/StableDebtToken.sol | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index a30219e3..1ae900de 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -21,6 +21,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 private _avgStableRate; mapping(address => uint40) _timestamps; + uint40 _totalSupplyTimestamp; constructor( address pool, @@ -122,7 +123,8 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _usersData[user] = vars.newStableRate; //solium-disable-next-line - _timestamps[user] = uint40(block.timestamp); + _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); + //calculates the updated average stable rate _avgStableRate = _avgStableRate @@ -171,7 +173,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _timestamps[user] = 0; } else { //solium-disable-next-line - _timestamps[user] = uint40(block.timestamp); + _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); } if (balanceIncrease > amount) { From edfcdd6db4ce4d18f120ace94d554f0c714fb866 Mon Sep 17 00:00:00 2001 From: The3D Date: Sun, 13 Sep 2020 10:58:36 +0200 Subject: [PATCH 09/45] Removed timestamp from stableDebtToken --- contracts/tokenization/StableDebtToken.sol | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 1ae900de..ba2c9d66 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -21,7 +21,6 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 private _avgStableRate; mapping(address => uint40) _timestamps; - uint40 _totalSupplyTimestamp; constructor( address pool, @@ -123,7 +122,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _usersData[user] = vars.newStableRate; //solium-disable-next-line - _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); + _timestamps[user] = uint40(block.timestamp); //calculates the updated average stable rate @@ -173,7 +172,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _timestamps[user] = 0; } else { //solium-disable-next-line - _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); + _timestamps[user] = uint40(block.timestamp); } if (balanceIncrease > amount) { From 162c7924a9da6f53643eb3917aa62957bfd3a83d Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 09:33:53 +0200 Subject: [PATCH 10/45] Added index to mint and burn of variableDebtToken --- contracts/lendingpool/LendingPool.sol | 58 ++++++++++--------- contracts/tokenization/VariableDebtToken.sol | 12 ++-- .../interfaces/IVariableDebtToken.sol | 6 +- 3 files changed, 39 insertions(+), 37 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 453b9ac2..34d8e1aa 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -26,6 +26,7 @@ import {LendingPoolLiquidationManager} from './LendingPoolLiquidationManager.sol import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; + /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data @@ -238,14 +239,17 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); - address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress : reserve.variableDebtTokenAddress; + address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE + ? reserve.stableDebtTokenAddress + : reserve.variableDebtTokenAddress; + _mintToReserveTreasury(reserve, onBehalfOf, debtTokenAddress); //burns an equivalent amount of debt tokens if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount); + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount, reserve.variableBorrowIndex); } address aToken = reserve.aTokenAddress; @@ -282,10 +286,12 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateCumulativeIndexesAndTimestamp(); - address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress : reserve.variableDebtTokenAddress; + address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE + ? reserve.stableDebtTokenAddress + : reserve.variableDebtTokenAddress; + _mintToReserveTreasury(reserve, msg.sender, debtTokenAddress); - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); @@ -344,7 +350,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { _mintToReserveTreasury(reserve, user, address(stableDebtToken)); - stableDebtToken.burn(user, stableBorrowBalance); stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); @@ -779,7 +784,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param vars Input struct for the borrowing action, in order to avoid STD errors **/ function _executeBorrow(ExecuteBorrowParams memory vars) internal { - ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; @@ -807,16 +811,15 @@ contract LendingPool is VersionedInitializable, ILendingPool { userConfig.setBorrowing(reserveId, true); } - address debtTokenAddress = ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE ? - reserve.stableDebtTokenAddress - : - reserve.variableDebtTokenAddress; - - - reserve.updateCumulativeIndexesAndTimestamp(); + address debtTokenAddress = ReserveLogic.InterestRateMode(vars.interestRateMode) == + ReserveLogic.InterestRateMode.STABLE + ? reserve.stableDebtTokenAddress + : reserve.variableDebtTokenAddress; _mintToReserveTreasury(reserve, vars.user, debtTokenAddress); + reserve.updateCumulativeIndexesAndTimestamp(); + //caching the current stable borrow rate uint256 currentStableRate = 0; @@ -825,13 +828,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { ) { currentStableRate = reserve.currentStableBorrowRate; - IStableDebtToken(debtTokenAddress).mint( - vars.user, - vars.amount, - currentStableRate - ); + IStableDebtToken(debtTokenAddress).mint(vars.user, vars.amount, currentStableRate); } else { - IVariableDebtToken(debtTokenAddress).mint(vars.user, vars.amount); + IVariableDebtToken(debtTokenAddress).mint(vars.user, vars.amount, reserve.variableBorrowIndex); } reserve.updateInterestRates( @@ -933,23 +932,26 @@ contract LendingPool is VersionedInitializable, ILendingPool { return _addressesProvider; } - function _mintToReserveTreasury(ReserveLogic.ReserveData storage reserve, address user, address debtTokenAddress) internal { - + function _mintToReserveTreasury( + ReserveLogic.ReserveData storage reserve, + address user, + address debtTokenAddress + ) internal { uint256 reserveFactor = reserve.configuration.getReserveFactor(); - if(reserveFactor == 0) { + if (reserveFactor == 0) { return; } uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor - if(currentPrincipalBalance > 0){ - - uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub(currentPrincipalBalance); + if (currentPrincipalBalance > 0) { + uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub( + currentPrincipalBalance + ); uint256 amountForReserveFactor = balanceIncrease.percentMul(reserveFactor); - IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); - } - + IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); + } } } diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 9bdff0e7..b43cbec4 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -54,23 +54,21 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @dev mints new variable debt * @param user the user receiving the debt * @param amount the amount of debt being minted + * @param index the variable debt index of the reserve **/ - function mint(address user, uint256 amount) external override onlyLendingPool { - - uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); + function mint(address user, uint256 amount, uint256 index) external override onlyLendingPool { _mint(user, amount.rayDiv(index)); + emit MintDebt(user, amount, index); } /** * @dev burns user variable debt * @param user the user which debt is burnt - * @param amount the amount of debt being burned + * @param index the variable debt index of the reserve **/ - function burn(address user, uint256 amount) external override onlyLendingPool { - - uint256 index = POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET); + function burn(address user, uint256 amount, uint256 index) external override onlyLendingPool { _burn(user, amount.rayDiv(index)); _userIndexes[user] = index; emit BurnDebt(user, amount, index); diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index 01b2aaca..3d26ed6e 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -36,15 +36,17 @@ interface IVariableDebtToken { * @dev mints new variable debt * @param user the user receiving the debt * @param amount the amount of debt being minted + * @param index the variable debt index of the reserve **/ - function mint(address user, uint256 amount) external; + function mint(address user, uint256 amount, uint256 index) external; /** * @dev burns user variable debt * @param user the user which debt is burnt * @param amount the amount of debt being burned + * @param index the variable debt index of the reserve **/ - function burn(address user, uint256 amount) external; + function burn(address user, uint256 amount, uint256 index) external; /** * @dev returns the scaled balance of the variable debt token From fc2852e94e1d1aae18e25852fe366f5725670dd9 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 09:53:21 +0200 Subject: [PATCH 11/45] Rename updateIndexesAndTimestamp to updateState --- contracts/lendingpool/LendingPool.sol | 37 ++++--------------- .../LendingPoolLiquidationManager.sol | 8 ++-- contracts/libraries/logic/ReserveLogic.sol | 4 +- 3 files changed, 14 insertions(+), 35 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 34d8e1aa..88df63af 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -103,7 +103,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { address aToken = reserve.aTokenAddress; - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); bool isFirstDeposit = IAToken(aToken).balanceOf(onBehalfOf) == 0; @@ -149,7 +149,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _addressesProvider.getPriceOracle() ); - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); @@ -237,7 +237,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { variableDebt ); - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress @@ -284,7 +284,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { interestRateMode ); - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE ? reserve.stableDebtTokenAddress @@ -346,7 +346,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { //burn old debt tokens, mint new ones - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); _mintToReserveTreasury(reserve, user, address(stableDebtToken)); @@ -529,7 +529,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { if (debtMode == ReserveLogic.InterestRateMode.NONE) { IERC20(asset).transferFrom(receiverAddress, vars.aTokenAddress, vars.amountPlusPremium); - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); reserve.cumulateToLiquidityIndex(IERC20(vars.aTokenAddress).totalSupply(), vars.premium); reserve.updateInterestRates(asset, vars.aTokenAddress, vars.premium, 0); @@ -818,7 +818,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _mintToReserveTreasury(reserve, vars.user, debtTokenAddress); - reserve.updateCumulativeIndexesAndTimestamp(); + reserve.updateState(); //caching the current stable borrow rate uint256 currentStableRate = 0; @@ -931,27 +931,4 @@ contract LendingPool is VersionedInitializable, ILendingPool { function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { return _addressesProvider; } - - function _mintToReserveTreasury( - ReserveLogic.ReserveData storage reserve, - address user, - address debtTokenAddress - ) internal { - uint256 reserveFactor = reserve.configuration.getReserveFactor(); - if (reserveFactor == 0) { - return; - } - - uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); - //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor - if (currentPrincipalBalance > 0) { - uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub( - currentPrincipalBalance - ); - - uint256 amountForReserveFactor = balanceIncrease.percentMul(reserveFactor); - - IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); - } - } } diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 83f37172..848aaffb 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -232,7 +232,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { } //update the principal reserve - principalReserve.updateCumulativeIndexesAndTimestamp(); + principalReserve.updateState(); @@ -279,7 +279,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { //otherwise receives the underlying asset //updating collateral reserve - collateralReserve.updateCumulativeIndexesAndTimestamp(); + collateralReserve.updateState(); collateralReserve.updateInterestRates( collateral, address(vars.collateralAtoken), @@ -406,7 +406,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { vars.actualAmountToLiquidate = vars.principalAmountNeeded; } //updating collateral reserve indexes - collateralReserve.updateCumulativeIndexesAndTimestamp(); + collateralReserve.updateState(); vars.collateralAtoken.burn(user, receiver, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex); @@ -426,7 +426,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ); //updating debt reserve - debtReserve.updateCumulativeIndexesAndTimestamp(); + debtReserve.updateState(); debtReserve.updateInterestRates(principal, principalAToken, vars.actualAmountToLiquidate, 0); IERC20(principal).transferFrom(receiver, principalAToken, vars.actualAmountToLiquidate); diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 3d688b75..e2f3df70 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -125,7 +125,9 @@ library ReserveLogic { * a formal specification. * @param reserve the reserve object **/ - function updateCumulativeIndexesAndTimestamp(ReserveData storage reserve) internal { + function updateState(ReserveData storage reserve) internal { + + uint256 currentLiquidityRate = reserve.currentLiquidityRate; //only cumulating if there is any income being produced From 3c8018fab9d9c8bda7f2b717b7268c69120aef3d Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 10:43:30 +0200 Subject: [PATCH 12/45] Cleaned up code, converted addressesProvider to immutable in LendingPool --- contracts/lendingpool/LendingPool.sol | 247 ++++++++---------- contracts/libraries/logic/ReserveLogic.sol | 71 ++--- contracts/tokenization/VariableDebtToken.sol | 12 + .../interfaces/IVariableDebtToken.sol | 6 + 4 files changed, 163 insertions(+), 173 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 88df63af..1d969b1d 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -47,7 +47,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 public constant FLASHLOAN_PREMIUM_TOTAL = 9; - ILendingPoolAddressesProvider internal _addressesProvider; + ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; mapping(address => ReserveLogic.ReserveData) internal _reserves; mapping(address => UserConfiguration.Map) internal _usersConfig; @@ -61,7 +61,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { **/ modifier onlyLendingPoolConfigurator { require( - _addressesProvider.getLendingPoolConfigurator() == msg.sender, + ADDRESSES_PROVIDER.getLendingPoolConfigurator() == msg.sender, Errors.CALLER_NOT_LENDING_POOL_CONFIGURATOR ); _; @@ -81,7 +81,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param provider the address of the LendingPoolAddressesProvider registry **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { - _addressesProvider = provider; + ADDRESSES_PROVIDER = provider; } /** @@ -146,7 +146,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[msg.sender], _reservesList, - _addressesProvider.getPriceOracle() + ADDRESSES_PROVIDER.getPriceOracle() ); reserve.updateState(); @@ -203,16 +203,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 rateMode, address onBehalfOf ) external override { - _executeRepay(asset, msg.sender, amount, rateMode, onBehalfOf); - } - - function _executeRepay( - address asset, - address user, - uint256 amount, - uint256 rateMode, - address onBehalfOf - ) internal { ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); @@ -239,12 +229,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateState(); - address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE - ? reserve.stableDebtTokenAddress - : reserve.variableDebtTokenAddress; - - _mintToReserveTreasury(reserve, onBehalfOf, debtTokenAddress); - //burns an equivalent amount of debt tokens if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); @@ -286,12 +270,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { reserve.updateState(); - address debtTokenAddress = interestRateMode == ReserveLogic.InterestRateMode.STABLE - ? reserve.stableDebtTokenAddress - : reserve.variableDebtTokenAddress; - - _mintToReserveTreasury(reserve, msg.sender, debtTokenAddress); - if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); @@ -344,12 +322,10 @@ contract LendingPool is VersionedInitializable, ILendingPool { Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); - //burn old debt tokens, mint new ones reserve.updateState(); - _mintToReserveTreasury(reserve, user, address(stableDebtToken)); - + //burn old debt tokens, mint new ones stableDebtToken.burn(user, stableBorrowBalance); stableDebtToken.mint(user, stableBorrowBalance, reserve.currentStableBorrowRate); @@ -374,7 +350,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[msg.sender], _reservesList, - _addressesProvider.getPriceOracle() + ADDRESSES_PROVIDER.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); @@ -402,7 +378,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 purchaseAmount, bool receiveAToken ) external override { - address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); + address liquidationManager = ADDRESSES_PROVIDER.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( @@ -461,7 +437,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { require(!_flashLiquidationLocked, Errors.REENTRANCY_NOT_ALLOWED); _flashLiquidationLocked = true; - address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); + address liquidationManager = ADDRESSES_PROVIDER.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( @@ -664,7 +640,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[user], _reservesList, - _addressesProvider.getPriceOracle() + ADDRESSES_PROVIDER.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( @@ -767,110 +743,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { return _reserves[asset].configuration; } - // internal functions - - struct ExecuteBorrowParams { - address asset; - address user; - uint256 amount; - uint256 interestRateMode; - address aTokenAddress; - uint16 referralCode; - bool releaseUnderlying; - } - - /** - * @dev Internal function to execute a borrowing action, allowing to transfer or not the underlying - * @param vars Input struct for the borrowing action, in order to avoid STD errors - **/ - function _executeBorrow(ExecuteBorrowParams memory vars) internal { - ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; - UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; - - address oracle = _addressesProvider.getPriceOracle(); - - uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( - 10**reserve.configuration.getDecimals() - ); - - ValidationLogic.validateBorrow( - reserve, - vars.asset, - vars.amount, - amountInETH, - vars.interestRateMode, - MAX_STABLE_RATE_BORROW_SIZE_PERCENT, - _reserves, - userConfig, - _reservesList, - oracle - ); - - uint256 reserveId = reserve.id; - if (!userConfig.isBorrowing(reserveId)) { - userConfig.setBorrowing(reserveId, true); - } - - address debtTokenAddress = ReserveLogic.InterestRateMode(vars.interestRateMode) == - ReserveLogic.InterestRateMode.STABLE - ? reserve.stableDebtTokenAddress - : reserve.variableDebtTokenAddress; - - _mintToReserveTreasury(reserve, vars.user, debtTokenAddress); - - reserve.updateState(); - - //caching the current stable borrow rate - uint256 currentStableRate = 0; - - if ( - ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ) { - currentStableRate = reserve.currentStableBorrowRate; - - IStableDebtToken(debtTokenAddress).mint(vars.user, vars.amount, currentStableRate); - } else { - IVariableDebtToken(debtTokenAddress).mint(vars.user, vars.amount, reserve.variableBorrowIndex); - } - - reserve.updateInterestRates( - vars.asset, - vars.aTokenAddress, - 0, - vars.releaseUnderlying ? vars.amount : 0 - ); - - if (vars.releaseUnderlying) { - IAToken(vars.aTokenAddress).transferUnderlyingTo(msg.sender, vars.amount); - } - - emit Borrow( - vars.asset, - msg.sender, - vars.amount, - vars.interestRateMode, - ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE - ? currentStableRate - : reserve.currentVariableBorrowRate, - vars.referralCode - ); - } - - /** - * @dev adds a reserve to the array of the _reserves address - **/ - function _addReserveToList(address asset) internal { - bool reserveAlreadyAdded = false; - for (uint256 i = 0; i < _reservesList.length; i++) - if (_reservesList[i] == asset) { - reserveAlreadyAdded = true; - } - if (!reserveAlreadyAdded) { - _reserves[asset].id = uint8(_reservesList.length); - _reservesList.push(asset); - } - } - /** * @dev returns the normalized income per unit of asset * @param asset the address of the reserve @@ -914,7 +786,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[user], _reservesList, - _addressesProvider.getPriceOracle() + ADDRESSES_PROVIDER.getPriceOracle() ); } @@ -929,6 +801,103 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @dev returns the addresses provider **/ function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return _addressesProvider; + return ADDRESSES_PROVIDER; + } + + // internal functions + + struct ExecuteBorrowParams { + address asset; + address user; + uint256 amount; + uint256 interestRateMode; + address aTokenAddress; + uint16 referralCode; + bool releaseUnderlying; + } + + /** + * @dev Internal function to execute a borrowing action, allowing to transfer or not the underlying + * @param vars Input struct for the borrowing action, in order to avoid STD errors + **/ + function _executeBorrow(ExecuteBorrowParams memory vars) internal { + ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; + UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; + + address oracle = ADDRESSES_PROVIDER.getPriceOracle(); + + uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( + 10**reserve.configuration.getDecimals() + ); + + ValidationLogic.validateBorrow( + reserve, + vars.asset, + vars.amount, + amountInETH, + vars.interestRateMode, + MAX_STABLE_RATE_BORROW_SIZE_PERCENT, + _reserves, + userConfig, + _reservesList, + oracle + ); + + uint256 reserveId = reserve.id; + if (!userConfig.isBorrowing(reserveId)) { + userConfig.setBorrowing(reserveId, true); + } + + reserve.updateState(); + + //caching the current stable borrow rate + uint256 currentStableRate = 0; + + if ( + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ) { + currentStableRate = reserve.currentStableBorrowRate; + + IStableDebtToken(reserve.stableDebtTokenAddress).mint(vars.user, vars.amount, currentStableRate); + } else { + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount, reserve.variableBorrowIndex); + } + + reserve.updateInterestRates( + vars.asset, + vars.aTokenAddress, + 0, + vars.releaseUnderlying ? vars.amount : 0 + ); + + if (vars.releaseUnderlying) { + IAToken(vars.aTokenAddress).transferUnderlyingTo(msg.sender, vars.amount); + } + + emit Borrow( + vars.asset, + msg.sender, + vars.amount, + vars.interestRateMode, + ReserveLogic.InterestRateMode(vars.interestRateMode) == ReserveLogic.InterestRateMode.STABLE + ? currentStableRate + : reserve.currentVariableBorrowRate, + vars.referralCode + ); + } + + /** + * @dev adds a reserve to the array of the _reserves address + **/ + function _addReserveToList(address asset) internal { + bool reserveAlreadyAdded = false; + for (uint256 i = 0; i < _reservesList.length; i++) + if (_reservesList[i] == asset) { + reserveAlreadyAdded = true; + } + if (!reserveAlreadyAdded) { + _reserves[asset].id = uint8(_reservesList.length); + _reservesList.push(asset); + } } } diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index e2f3df70..acb1e501 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -67,7 +67,7 @@ library ReserveLogic { address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; - + //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves @@ -121,42 +121,13 @@ library ReserveLogic { } /** - * @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for - * a formal specification. + * @dev Updates the state of the reserve by minting to the reserve treasury and calculate the new + * reserve indexes * @param reserve the reserve object **/ function updateState(ReserveData storage reserve) internal { - - - uint256 currentLiquidityRate = reserve.currentLiquidityRate; - - //only cumulating if there is any income being produced - if (currentLiquidityRate > 0) { - uint40 lastUpdateTimestamp = reserve.lastUpdateTimestamp; - uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( - currentLiquidityRate, - lastUpdateTimestamp - ); - uint256 index = cumulatedLiquidityInterest.rayMul(reserve.liquidityIndex); - require(index < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); - - reserve.liquidityIndex = uint128(index); - - //as the liquidity rate might come only from stable rate loans, we need to ensure - //that there is actual variable debt before accumulating - if (IERC20(reserve.variableDebtTokenAddress).totalSupply() > 0) { - uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( - reserve.currentVariableBorrowRate, - lastUpdateTimestamp - ); - index = cumulatedVariableBorrowInterest.rayMul(reserve.variableBorrowIndex); - require(index < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); - reserve.variableBorrowIndex = uint128(index); - } - } - - //solium-disable-next-line - reserve.lastUpdateTimestamp = uint40(block.timestamp); + _mintToTreasury(reserve); + _updateIndexes(reserve); } /** @@ -270,4 +241,36 @@ library ReserveLogic { reserve.variableBorrowIndex ); } + + function _updateIndexes(ReserveData storage reserve) internal { + uint256 currentLiquidityRate = reserve.currentLiquidityRate; + + //only cumulating if there is any income being produced + if (currentLiquidityRate > 0) { + uint40 lastUpdateTimestamp = reserve.lastUpdateTimestamp; + uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( + currentLiquidityRate, + lastUpdateTimestamp + ); + uint256 index = cumulatedLiquidityInterest.rayMul(reserve.liquidityIndex); + require(index < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); + + reserve.liquidityIndex = uint128(index); + + //as the liquidity rate might come only from stable rate loans, we need to ensure + //that there is actual variable debt before accumulating + if (IERC20(reserve.variableDebtTokenAddress).totalSupply() > 0) { + uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( + reserve.currentVariableBorrowRate, + lastUpdateTimestamp + ); + index = cumulatedVariableBorrowInterest.rayMul(reserve.variableBorrowIndex); + require(index < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); + reserve.variableBorrowIndex = uint128(index); + } + } + + //solium-disable-next-line + reserve.lastUpdateTimestamp = uint40(block.timestamp); + } } diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index b43cbec4..d9a423eb 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -82,7 +82,19 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { return super.balanceOf(user); } + /** + * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users + * @return the total supply + **/ function totalSupply() public virtual override view returns(uint256) { return super.totalSupply().rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); } + + /** + * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) + * @return the scaled total supply + **/ + function scaledTotalSupply() public virtual override view returns(uint256) { + return super.totalSupply(); + } } diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index 3d26ed6e..320d0f5a 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -53,5 +53,11 @@ interface IVariableDebtToken { * @param user the user **/ function scaledBalanceOf(address user) external view returns(uint256); + + /** + * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) + * @return the scaled total supply + **/ + function scaledTotalSupply() external view returns(uint256); } From 5061aab9cc29c32c006b472a772557002c13b3c1 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 11:09:47 +0200 Subject: [PATCH 13/45] Added the total supply on stable debt token --- contracts/libraries/logic/ReserveLogic.sol | 6 +++++ contracts/tokenization/StableDebtToken.sol | 23 ++++++++++++++++--- .../interfaces/IStableDebtToken.sol | 7 ++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index acb1e501..58bf29bd 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -240,6 +240,12 @@ library ReserveLogic { reserve.liquidityIndex, reserve.variableBorrowIndex ); + } + + function _mintToTreasury(ReserveData storage reserve) internal { + + + } function _updateIndexes(ReserveData storage reserve) internal { diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 8d5a18e1..cf50fb18 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -21,6 +21,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 private _avgStableRate; mapping(address => uint40) _timestamps; + uint40 _totalSupplyTimestamp; constructor( address pool, @@ -76,7 +77,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { stableRate, _timestamps[account] ); - return accountBalance.wadToRay().rayMul(cumulatedInterest).rayToWad(); + return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { @@ -122,7 +123,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _usersData[user] = vars.newStableRate; //solium-disable-next-line - _timestamps[user] = uint40(block.timestamp); + _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); //calculates the updated average stable rate @@ -172,7 +173,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _timestamps[user] = 0; } else { //solium-disable-next-line - _timestamps[user] = uint40(block.timestamp); + _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); } if (balanceIncrease > amount) { @@ -208,4 +209,20 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ); } + function principalTotalSupply() public override view returns(uint256) { + return super.totalSupply(); + } + + function totalSupply() public override view returns(uint256) { + uint256 principalSupply = super.totalSupply(); + if (principalSupply == 0) { + return 0; + } + uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest( + _avgStableRate, + _totalSupplyTimestamp + ); + return principalSupply.rayMul(cumulatedInterest); + } + } diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 0aaccd26..fc15e00f 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -84,4 +84,11 @@ interface IStableDebtToken { * @return the timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); + + /** + * @dev returns the principal total supply + **/ + function principalTotalSupply() external view returns (uint40); + + } From 13f77ec0d200b9eb97916d55b0709825979f0e6b Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 11:34:40 +0200 Subject: [PATCH 14/45] Fixed repay --- contracts/lendingpool/LendingPool.sol | 4 ++-- contracts/libraries/logic/ReserveLogic.sol | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index eeeb0d9a..79940ef2 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -241,9 +241,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } - IERC20(asset).safeTransferFrom(user, aToken, paybackAmount); + IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); - emit Repay(asset, onBehalfOf, user, paybackAmount); + emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); } /** diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 58bf29bd..0cb07416 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -243,7 +243,7 @@ library ReserveLogic { } function _mintToTreasury(ReserveData storage reserve) internal { - + } From 6e92575ac2fff0284b6d70c60981c5659757e254 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 11:41:14 +0200 Subject: [PATCH 15/45] add code to _mintToTreasury --- contracts/libraries/logic/ReserveLogic.sol | 13 ++++++++++++- .../tokenization/interfaces/IStableDebtToken.sol | 2 -- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 0cb07416..0530e650 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -7,6 +7,7 @@ import {MathUtils} from '../math/MathUtils.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {IStableDebtToken} from '../../tokenization/interfaces/IStableDebtToken.sol'; +import {IVariableDebtToken} from '../../tokenization/interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; @@ -244,7 +245,17 @@ library ReserveLogic { function _mintToTreasury(ReserveData storage reserve) internal { - + address stableDebtToken = reserve.stableDebtTokenAddress; + address variableDebtToken = reserve.variableDebtTokenAddress; + + uint256 currentVariableDebt = IERC20(variableDebtToken).totalSupply(); + uint256 currentStableDebt = IERC20(stableDebtToken).totalSupply(); + + uint256 principalStableDebt = IStableDebtToken(stableDebtToken).principalTotalSupply(); + uint256 scaledVariableDebt = IVariableDebtToken(variableDebtToken).scaledTotalSupply(); + + + } diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index fc15e00f..4c3800e0 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -89,6 +89,4 @@ interface IStableDebtToken { * @dev returns the principal total supply **/ function principalTotalSupply() external view returns (uint40); - - } From bb4e1b5c4b3da4528408c29b6d9feb19e9c43d11 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 15:09:16 +0200 Subject: [PATCH 16/45] Fixed errors --- contracts/interfaces/ILendingPool.sol | 1 - contracts/lendingpool/LendingPool.sol | 31 +++---- .../LendingPoolLiquidationManager.sol | 64 ++++++-------- contracts/libraries/helpers/Helpers.sol | 17 ---- contracts/libraries/logic/ReserveLogic.sol | 87 +++++++++++++++---- contracts/tokenization/AToken.sol | 3 +- contracts/tokenization/StableDebtToken.sol | 31 +++++-- contracts/tokenization/VariableDebtToken.sol | 2 +- contracts/tokenization/base/DebtTokenBase.sol | 8 -- contracts/tokenization/interfaces/IAToken.sol | 14 +-- .../interfaces/IStableDebtToken.sol | 11 ++- test/helpers/utils/calculations.ts | 76 ++++++++-------- test/helpers/utils/helpers.ts | 1 - test/helpers/utils/interfaces/index.ts | 1 - test/scenario.spec.ts | 2 +- test/variable-debt-token.spec.ts | 4 +- 16 files changed, 189 insertions(+), 164 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index c13fe2e5..4b3c8385 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -326,7 +326,6 @@ interface ILendingPool { uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, - uint256 principalVariableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 79940ef2..93716948 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -49,10 +49,9 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 public constant UINT_MAX_VALUE = uint256(-1); uint256 public constant LENDINGPOOL_REVISION = 0x2; - ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; - mapping(address => ReserveLogic.ReserveData) internal _reserves; mapping(address => UserConfiguration.Map) internal _usersConfig; + ILendingPoolAddressesProvider internal _addressesProvider; address[] internal _reservesList; @@ -63,7 +62,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { **/ modifier onlyLendingPoolConfigurator { require( - ADDRESSES_PROVIDER.getLendingPoolConfigurator() == msg.sender, + _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.CALLER_NOT_LENDING_POOL_CONFIGURATOR ); _; @@ -79,7 +78,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @param provider the address of the LendingPoolAddressesProvider registry **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { - ADDRESSES_PROVIDER = provider; + _addressesProvider = provider; } /** @@ -144,7 +143,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[msg.sender], _reservesList, - ADDRESSES_PROVIDER.getPriceOracle() + _addressesProvider.getPriceOracle() ); reserve.updateState(); @@ -271,10 +270,10 @@ contract LendingPool is VersionedInitializable, ILendingPool { if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt, reserve.variableBorrowIndex); } else { //do the opposite - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt); + IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt, reserve.variableBorrowIndex); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, variableDebt, @@ -348,7 +347,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[msg.sender], _reservesList, - ADDRESSES_PROVIDER.getPriceOracle() + _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); @@ -376,7 +375,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 purchaseAmount, bool receiveAToken ) external override { - address liquidationManager = ADDRESSES_PROVIDER.getLendingPoolLiquidationManager(); + address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( @@ -435,7 +434,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { require(!_flashLiquidationLocked, Errors.REENTRANCY_NOT_ALLOWED); _flashLiquidationLocked = true; - address liquidationManager = ADDRESSES_PROVIDER.getLendingPoolLiquidationManager(); + address liquidationManager = _addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( @@ -638,7 +637,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[user], _reservesList, - ADDRESSES_PROVIDER.getPriceOracle() + _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( @@ -657,7 +656,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, - uint256 variableBorrowIndex, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, @@ -669,7 +667,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { currentATokenBalance = IERC20(reserve.aTokenAddress).balanceOf(user); (currentStableDebt, currentVariableDebt) = Helpers.getUserCurrentDebt(user, reserve); - (principalStableDebt, principalVariableDebt) = Helpers.getUserPrincipalDebt(user, reserve); + principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); @@ -677,7 +675,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { user ); usageAsCollateralEnabled = _usersConfig[user].isUsingAsCollateral(reserve.id); - variableBorrowIndex = IVariableDebtToken(reserve.variableDebtTokenAddress).getUserIndex(user); } function getReserves() external override view returns (address[] memory) { @@ -784,7 +781,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { _reserves, _usersConfig[user], _reservesList, - ADDRESSES_PROVIDER.getPriceOracle() + _addressesProvider.getPriceOracle() ); } @@ -799,7 +796,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { * @dev returns the addresses provider **/ function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return ADDRESSES_PROVIDER; + return _addressesProvider; } // internal functions @@ -822,7 +819,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { ReserveLogic.ReserveData storage reserve = _reserves[vars.asset]; UserConfiguration.Map storage userConfig = _usersConfig[msg.sender]; - address oracle = ADDRESSES_PROVIDER.getPriceOracle(); + address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 848aaffb..8a018489 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -234,8 +234,6 @@ contract LendingPoolLiquidationManager is VersionedInitializable { //update the principal reserve principalReserve.updateState(); - - principalReserve.updateInterestRates( principal, principalReserve.aTokenAddress, @@ -244,29 +242,19 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ); if (vars.userVariableDebt >= vars.actualAmountToLiquidate) { - - address tokenAddress = principalReserve.variableDebtTokenAddress; - - _mintToReserveTreasury(principalReserve, user, tokenAddress); - - IVariableDebtToken(tokenAddress).burn( + IVariableDebtToken(principalReserve.variableDebtTokenAddress).burn( user, - vars.actualAmountToLiquidate + vars.actualAmountToLiquidate, + principalReserve.variableBorrowIndex ); } else { - - address tokenAddress = principalReserve.variableDebtTokenAddress; - - _mintToReserveTreasury(principalReserve, user, tokenAddress); - - IVariableDebtToken(tokenAddress).burn( + IVariableDebtToken(principalReserve.variableDebtTokenAddress).burn( user, - vars.userVariableDebt + vars.userVariableDebt, + principalReserve.variableBorrowIndex ); - tokenAddress = principalReserve.stableDebtTokenAddress; - - IStableDebtToken(tokenAddress).burn( + IStableDebtToken(principalReserve.stableDebtTokenAddress).burn( user, vars.actualAmountToLiquidate.sub(vars.userVariableDebt) ); @@ -288,7 +276,12 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ); //burn the equivalent amount of atoken - vars.collateralAtoken.burn(user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex); + vars.collateralAtoken.burn( + user, + msg.sender, + vars.maxCollateralToLiquidate, + collateralReserve.liquidityIndex + ); } //transfers the principal currency to the aToken @@ -408,7 +401,12 @@ contract LendingPoolLiquidationManager is VersionedInitializable { //updating collateral reserve indexes collateralReserve.updateState(); - vars.collateralAtoken.burn(user, receiver, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex); + vars.collateralAtoken.burn( + user, + receiver, + vars.maxCollateralToLiquidate, + collateralReserve.liquidityIndex + ); if (vars.userCollateralBalance == vars.maxCollateralToLiquidate) { usersConfig[user].setUsingAsCollateral(collateralReserve.id, false); @@ -433,10 +431,15 @@ contract LendingPoolLiquidationManager is VersionedInitializable { if (vars.userVariableDebt >= vars.actualAmountToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, - vars.actualAmountToLiquidate + vars.actualAmountToLiquidate, + debtReserve.variableBorrowIndex ); } else { - IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(user, vars.userVariableDebt); + IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( + user, + vars.userVariableDebt, + debtReserve.variableBorrowIndex + ); IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualAmountToLiquidate.sub(vars.userVariableDebt) @@ -530,19 +533,4 @@ contract LendingPoolLiquidationManager is VersionedInitializable { } return (collateralAmount, principalAmountNeeded); } - - function _mintToReserveTreasury(ReserveLogic.ReserveData storage reserve, address user, address debtTokenAddress) internal { - - uint256 currentPrincipalBalance = DebtTokenBase(debtTokenAddress).principalBalanceOf(user); - //calculating the interest accrued since the last borrow and minting the equivalent amount to the reserve factor - if(currentPrincipalBalance > 0){ - - uint256 balanceIncrease = IERC20(debtTokenAddress).balanceOf(user).sub(currentPrincipalBalance); - - uint256 amountForReserveFactor = balanceIncrease.percentMul(reserve.configuration.getReserveFactor()); - - IAToken(reserve.aTokenAddress).mintToReserve(amountForReserveFactor); - } - - } } diff --git a/contracts/libraries/helpers/Helpers.sol b/contracts/libraries/helpers/Helpers.sol index dda22eb4..e1d65502 100644 --- a/contracts/libraries/helpers/Helpers.sol +++ b/contracts/libraries/helpers/Helpers.sol @@ -26,21 +26,4 @@ library Helpers { DebtTokenBase(reserve.variableDebtTokenAddress).balanceOf(user) ); } - - /** - * @dev fetches the user principal stable and variable debt balances - * @param user the user - * @param reserve the reserve object - * @return the stable and variable debt balance - **/ - function getUserPrincipalDebt(address user, ReserveLogic.ReserveData storage reserve) - internal - view - returns (uint256, uint256) - { - return ( - DebtTokenBase(reserve.stableDebtTokenAddress).principalBalanceOf(user), - DebtTokenBase(reserve.variableDebtTokenAddress).principalBalanceOf(user) - ); - } } diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index 0530e650..b287094a 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -6,11 +6,13 @@ import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; +import {IAToken} from '../../tokenization/interfaces/IAToken.sol'; import {IStableDebtToken} from '../../tokenization/interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../tokenization/interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; +import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; /** @@ -21,6 +23,7 @@ import {Errors} from '../helpers/Errors.sol'; library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; + using PercentageMath for uint256; using SafeERC20 for IERC20; /** @@ -63,14 +66,12 @@ library ReserveLogic { //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; - //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; - //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } @@ -127,8 +128,14 @@ library ReserveLogic { * @param reserve the reserve object **/ function updateState(ReserveData storage reserve) internal { - _mintToTreasury(reserve); - _updateIndexes(reserve); + address stableDebtToken = reserve.stableDebtTokenAddress; + address variableDebtToken = reserve.variableDebtTokenAddress; + uint256 variableBorrowIndex = reserve.variableBorrowIndex; + uint256 liquidityIndex = reserve.liquidityIndex; + uint40 timestamp = reserve.lastUpdateTimestamp; + + _mintToTreasury(reserve, stableDebtToken, variableDebtToken, liquidityIndex, variableBorrowIndex, timestamp); + _updateIndexes(reserve, variableDebtToken, liquidityIndex, variableBorrowIndex, timestamp); } /** @@ -243,28 +250,70 @@ library ReserveLogic { ); } - function _mintToTreasury(ReserveData storage reserve) internal { - - address stableDebtToken = reserve.stableDebtTokenAddress; - address variableDebtToken = reserve.variableDebtTokenAddress; + struct MintToTreasuryLocalVars { + uint256 currentTotalDebt; + uint256 principalStableDebt; + uint256 avgStableRate; + uint256 scaledVariableDebt; + uint256 cumulatedStableInterest; + uint256 variableDebtOnLastUpdate; + uint256 stableDebtOnLastUpdate; + uint256 totalInterestAccrued; + uint256 amountToMint; + uint256 reserveFactor; + } - uint256 currentVariableDebt = IERC20(variableDebtToken).totalSupply(); - uint256 currentStableDebt = IERC20(stableDebtToken).totalSupply(); + function _mintToTreasury( + ReserveData storage reserve, + address stableDebtToken, + address variableDebtToken, + uint256 liquidityIndex, + uint256 variableBorrowIndex, + uint40 lastUpdateTimestamp + ) internal { + + MintToTreasuryLocalVars memory vars; - uint256 principalStableDebt = IStableDebtToken(stableDebtToken).principalTotalSupply(); - uint256 scaledVariableDebt = IVariableDebtToken(variableDebtToken).scaledTotalSupply(); - - - + vars.reserveFactor = reserve.configuration.getReserveFactor(); + + if(vars.reserveFactor == 0){ + return; + } + + vars.currentTotalDebt = IERC20(variableDebtToken).totalSupply().add(IERC20(stableDebtToken).totalSupply()); + + (vars.principalStableDebt, vars.avgStableRate) = IStableDebtToken(stableDebtToken) + .getPrincipalSupplyAndAvgRate(); + + vars.scaledVariableDebt = IVariableDebtToken(variableDebtToken).scaledTotalSupply(); + + vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( + vars.avgStableRate, + lastUpdateTimestamp + ); + + vars.variableDebtOnLastUpdate = vars.scaledVariableDebt.rayMul(variableBorrowIndex); + vars.stableDebtOnLastUpdate = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); + + vars.totalInterestAccrued =vars.currentTotalDebt.sub(vars.variableDebtOnLastUpdate.add(vars.stableDebtOnLastUpdate)); + + vars.amountToMint = vars.totalInterestAccrued.percentMul(vars.reserveFactor); + + IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, liquidityIndex); } - function _updateIndexes(ReserveData storage reserve) internal { + function _updateIndexes( + ReserveData storage reserve, + address variableDebtToken, + uint256 liquidityIndex, + uint256 variableBorrowIndex, + uint40 lastUpdateTimestamp + ) internal { uint256 currentLiquidityRate = reserve.currentLiquidityRate; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { - uint40 lastUpdateTimestamp = reserve.lastUpdateTimestamp; uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( currentLiquidityRate, lastUpdateTimestamp @@ -276,12 +325,12 @@ library ReserveLogic { //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating - if (IERC20(reserve.variableDebtTokenAddress).totalSupply() > 0) { + if (IERC20(variableDebtToken).totalSupply() > 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( reserve.currentVariableBorrowRate, lastUpdateTimestamp ); - index = cumulatedVariableBorrowInterest.rayMul(reserve.variableBorrowIndex); + index = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require(index < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); reserve.variableBorrowIndex = uint128(index); } diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 9df145ba..cd270ccb 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -105,8 +105,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken { emit Mint(user, amount, index); } - function mintToReserve(uint256 amount) external override onlyLendingPool { - uint256 index = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); + function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { _mint(RESERVE_TREASURY_ADDRESS, amount.div(index)); } diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index cf50fb18..1d166c8f 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -68,7 +68,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { * @return the accumulated debt of the user **/ function balanceOf(address account) public virtual override view returns (uint256) { - uint256 accountBalance = principalBalanceOf(account); + uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersData[account]; if (accountBalance == 0) { return 0; @@ -125,7 +125,6 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { //solium-disable-next-line _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); - //calculates the updated average stable rate _avgStableRate = _avgStableRate .rayMul(vars.supplyBeforeMint.wadToRay()) @@ -185,15 +184,22 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { emit BurnDebt(user, amount, previousBalance, currentBalance, balanceIncrease); } - /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance, the balance increase * and the new user index **/ - function _calculateBalanceIncrease(address user) internal view returns (uint256, uint256, uint256) { - uint256 previousPrincipalBalance = principalBalanceOf(user); + function _calculateBalanceIncrease(address user) + internal + view + returns ( + uint256, + uint256, + uint256 + ) + { + uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); @@ -209,11 +215,11 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ); } - function principalTotalSupply() public override view returns(uint256) { - return super.totalSupply(); + function getPrincipalSupplyAndAvgRate() public override view returns (uint256, uint256) { + return (super.totalSupply(), _avgStableRate); } - - function totalSupply() public override view returns(uint256) { + + function totalSupply() public override view returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; @@ -225,4 +231,11 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { return principalSupply.rayMul(cumulatedInterest); } + /** + * @dev Returns the principal debt balance of the user from + * @return The debt balance of the user since the last burn/mint action + **/ + function principalBalanceOf(address user) external virtual override view returns (uint256) { + return super.balanceOf(user); + } } diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index d9a423eb..8a70f31c 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -39,7 +39,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @return the debt balance of the user **/ function balanceOf(address user) public virtual override view returns (uint256) { - uint256 scaledBalance = super.principalBalanceOf(user); + uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; diff --git a/contracts/tokenization/base/DebtTokenBase.sol b/contracts/tokenization/base/DebtTokenBase.sol index d8798906..ff0070b8 100644 --- a/contracts/tokenization/base/DebtTokenBase.sol +++ b/contracts/tokenization/base/DebtTokenBase.sol @@ -64,14 +64,6 @@ abstract contract DebtTokenBase is ERC20, VersionedInitializable { return UNDERLYING_ASSET; } - /** - * @dev Returns the principal debt balance of the user from - * @return The debt balance of the user since the last burn/mint action - **/ - function principalBalanceOf(address user) public virtual view returns (uint256) { - return super.balanceOf(user); - } - /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. diff --git a/contracts/tokenization/interfaces/IAToken.sol b/contracts/tokenization/interfaces/IAToken.sol index c188162e..de8b0d3c 100644 --- a/contracts/tokenization/interfaces/IAToken.sol +++ b/contracts/tokenization/interfaces/IAToken.sol @@ -62,12 +62,11 @@ interface IAToken is IERC20 { function mint(address user, uint256 amount, uint256 index) external; /** - * @dev mints aTokens to reserve, based on the reserveFactor value - * only lending pools can call this function - * @param amount the amount of tokens to mint - */ - function mintToReserve(uint256 amount) external; - + * @dev mints aTokens to the reserve treasury + * @param amount the amount to mint + * @param index the liquidity index of the reserve + **/ + function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken @@ -104,6 +103,7 @@ interface IAToken is IERC20 { * @param amount the amount to transfer * @return the amount transferred **/ - function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); + + } diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 4c3800e0..c1e97388 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -86,7 +86,14 @@ interface IStableDebtToken { function getUserLastUpdated(address user) external view returns (uint40); /** - * @dev returns the principal total supply + * @dev returns the principal total supply and the average stable rate **/ - function principalTotalSupply() external view returns (uint40); + function getPrincipalSupplyAndAvgRate() external view returns (uint256, uint256); + + /** + * @dev Returns the principal debt balance of the user + * @return The debt balance of the user since the last burn/mint action + **/ + function principalBalanceOf(address user) external view returns (uint256); + } diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 861f5a94..b9f9ebe2 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -273,19 +273,16 @@ export const calcExpectedReserveDataAfterBorrow = ( const amountBorrowedBN = new BigNumber(amountBorrowed); - const userStableBorrowBalance = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, - txTimestamp - ); + const userStableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); - const userVariableBorrowBalance = calcExpectedVariableDebtTokenBalance( + const userVariableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, userDataBeforeAction, txTimestamp ); if (borrowRateMode == RateMode.Stable) { - const debtAccrued = userStableBorrowBalance.minus(userDataBeforeAction.principalStableDebt); + const debtAccrued = userStableDebt.minus(userDataBeforeAction.principalStableDebt); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); @@ -301,7 +298,11 @@ export const calcExpectedReserveDataAfterBorrow = ( ); expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; } else { - const debtAccrued = userVariableBorrowBalance.minus(userDataBeforeAction.principalVariableDebt); + const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( + reserveDataBeforeAction.variableBorrowIndex + ); + + const debtAccrued = userVariableDebt.minus(variableDebtBefore); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable .plus(amountBorrowedBN) @@ -362,12 +363,9 @@ export const calcExpectedReserveDataAfterRepay = ( let amountRepaidBN = new BigNumber(amountRepaid); - const userStableBorrowBalance = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, - txTimestamp - ); + const userStableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); - const userVariableBorrowBalance = calcExpectedVariableDebtTokenBalance( + const userVariableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, userDataBeforeAction, txTimestamp @@ -376,14 +374,14 @@ export const calcExpectedReserveDataAfterRepay = ( //if amount repaid = MAX_UINT_AMOUNT, user is repaying everything if (amountRepaidBN.abs().eq(MAX_UINT_AMOUNT)) { if (borrowRateMode == RateMode.Stable) { - amountRepaidBN = userStableBorrowBalance; + amountRepaidBN = userStableDebt; } else { - amountRepaidBN = userVariableBorrowBalance; + amountRepaidBN = userVariableDebt; } } if (borrowRateMode == RateMode.Stable) { - const debtAccrued = userStableBorrowBalance.minus(userDataBeforeAction.principalStableDebt); + const debtAccrued = userStableDebt.minus(userDataBeforeAction.principalStableDebt); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); @@ -399,7 +397,11 @@ export const calcExpectedReserveDataAfterRepay = ( ); expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; } else { - const debtAccrued = userVariableBorrowBalance.minus(userDataBeforeAction.principalVariableDebt); + const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( + reserveDataBeforeAction.variableBorrowIndex + ); + + const debtAccrued = userVariableDebt.minus(variableDebtBefore); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); @@ -477,7 +479,7 @@ export const calcExpectedUserDataAfterBorrow = ( const debtAccrued = currentStableDebt.minus(userDataBeforeAction.principalStableDebt); expectedUserData.principalStableDebt = currentStableDebt.plus(amountBorrowed); - expectedUserData.principalVariableDebt = userDataBeforeAction.principalVariableDebt; + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.stableBorrowRate = calcExpectedUserStableRate( userDataBeforeAction.principalStableDebt.plus(debtAccrued), @@ -510,8 +512,8 @@ export const calcExpectedUserDataAfterBorrow = ( expectedDataAfterAction, { ...userDataBeforeAction, - currentVariableDebt: expectedUserData.principalVariableDebt, - principalVariableDebt: expectedUserData.principalVariableDebt, + currentVariableDebt: expectedUserData.scaledVariableDebt.rayMul(reserveDataBeforeAction.variableBorrowIndex), + scaledVariableDebt: expectedUserData.scaledVariableDebt, variableBorrowIndex: interestRateMode == RateMode.Variable ? expectedDataAfterAction.variableBorrowIndex @@ -520,7 +522,7 @@ export const calcExpectedUserDataAfterBorrow = ( currentTimestamp ); - if (expectedUserData.principalVariableDebt.eq(0)) { + if (expectedUserData.scaledVariableDebt.eq(0)) { expectedUserData.variableBorrowIndex = new BigNumber(0); } else { expectedUserData.variableBorrowIndex = @@ -539,7 +541,7 @@ export const calcExpectedUserDataAfterBorrow = ( currentTimestamp ); expectedUserData.scaledATokenBalance = userDataBeforeAction.scaledATokenBalance; - + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountBorrowed); return expectedUserData; @@ -623,7 +625,7 @@ export const calcExpectedUserDataAfterRepay = ( txTimestamp ); expectedUserData.scaledATokenBalance = userDataBeforeAction.scaledATokenBalance; - + if (user === onBehalfOf) { expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(totalRepaid); } else { @@ -657,51 +659,52 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( expectedReserveData.address = reserveDataBeforeAction.address; - const variableBorrowBalance = calcExpectedVariableDebtTokenBalance( + const variableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, userDataBeforeAction, txTimestamp ); - const stableBorrowBalance = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); + const stableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity; if (rateMode === RateMode.Stable) { //swap user stable debt to variable - const debtAccrued = stableBorrowBalance.minus(userDataBeforeAction.principalStableDebt); + const debtAccrued = stableDebt.minus(userDataBeforeAction.principalStableDebt); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, reserveDataBeforeAction.totalBorrowsStable.plus(debtAccrued), - stableBorrowBalance.negated(), + stableDebt.negated(), userDataBeforeAction.stableBorrowRate ); expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable.plus( - stableBorrowBalance + stableDebt ); expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable.minus( userDataBeforeAction.principalStableDebt ); } else { - const debtAccrued = variableBorrowBalance.minus(userDataBeforeAction.principalVariableDebt); + const totalDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul(reserveDataBeforeAction.variableBorrowIndex); + const debtAccrued = variableDebt.minus(totalDebtBefore); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable.minus( - userDataBeforeAction.principalVariableDebt - ); + + expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable.plus( - variableBorrowBalance + variableDebt ); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, reserveDataBeforeAction.totalBorrowsStable, - variableBorrowBalance, + variableDebt, reserveDataBeforeAction.stableBorrowRate ); } @@ -926,9 +929,7 @@ const calcExpectedATokenBalance = ( ) => { const index = calcExpectedReserveNormalizedIncome(reserveDataBeforeAction, currentTimestamp); - const { - scaledATokenBalance: scaledBalanceBeforeAction, - } = userDataBeforeAction; + const {scaledATokenBalance: scaledBalanceBeforeAction} = userDataBeforeAction; return scaledBalanceBeforeAction.rayMul(index); }; @@ -969,8 +970,7 @@ export const calcExpectedVariableDebtTokenBalance = ( ) => { const debt = calcExpectedReserveNormalizedDebt(reserveDataBeforeAction, currentTimestamp); - const { scaledVariableDebt } = userDataBeforeAction; - + const {scaledVariableDebt} = userDataBeforeAction; return scaledVariableDebt.rayMul(debt); }; diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index 59eb600a..1d2516ad 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -79,7 +79,6 @@ export const getUserData = async ( currentStableDebt: new BigNumber(userData.currentStableDebt.toString()), currentVariableDebt: new BigNumber(userData.currentVariableDebt.toString()), principalStableDebt: new BigNumber(userData.principalStableDebt.toString()), - principalVariableDebt: new BigNumber(userData.principalVariableDebt.toString()), scaledVariableDebt: new BigNumber(userData.scaledVariableDebt.toString()), stableBorrowRate: new BigNumber(userData.stableBorrowRate.toString()), liquidityRate: new BigNumber(userData.liquidityRate.toString()), diff --git a/test/helpers/utils/interfaces/index.ts b/test/helpers/utils/interfaces/index.ts index 646e6b10..2acbfa31 100644 --- a/test/helpers/utils/interfaces/index.ts +++ b/test/helpers/utils/interfaces/index.ts @@ -6,7 +6,6 @@ export interface UserReserveData { currentStableDebt: BigNumber; currentVariableDebt: BigNumber; principalStableDebt: BigNumber; - principalVariableDebt: BigNumber; scaledVariableDebt: BigNumber; liquidityRate: BigNumber; stableBorrowRate: BigNumber; diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 1d8da5e9..17830d1c 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['']; +const selectedScenarios: string[] = ['deposit.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; diff --git a/test/variable-debt-token.spec.ts b/test/variable-debt-token.spec.ts index 89bb1acc..a79bdde2 100644 --- a/test/variable-debt-token.spec.ts +++ b/test/variable-debt-token.spec.ts @@ -18,7 +18,7 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { daiVariableDebtTokenAddress ); - await expect(variableDebtContract.mint(deployer.address, '1')).to.be.revertedWith( + await expect(variableDebtContract.mint(deployer.address, '1', '1')).to.be.revertedWith( CALLER_MUST_BE_LENDING_POOL ); }); @@ -34,7 +34,7 @@ makeSuite('Variable debt token tests', (testEnv: TestEnv) => { daiVariableDebtTokenAddress ); - await expect(variableDebtContract.burn(deployer.address, '1')).to.be.revertedWith( + await expect(variableDebtContract.burn(deployer.address, '1', '1')).to.be.revertedWith( CALLER_MUST_BE_LENDING_POOL ); }); From b2ec4dd2fabad7b577a289432b0032ee53c9b03c Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 15:13:30 +0200 Subject: [PATCH 17/45] Renamed totalBorrowsStable, totalBorrowsVariable --- contracts/interfaces/ILendingPool.sol | 4 +- .../IReserveInterestRateStrategy.sol | 4 +- .../DefaultReserveInterestRateStrategy.sol | 28 ++-- contracts/lendingpool/LendingPool.sol | 4 +- .../lendingpool/LendingPoolConfigurator.sol | 6 +- .../flash-liquidation-with-collateral.spec.ts | 12 +- test/flashloan.spec.ts | 12 +- test/helpers/utils/calculations.ts | 132 +++++++++--------- test/helpers/utils/helpers.ts | 12 +- test/helpers/utils/interfaces/index.ts | 4 +- 10 files changed, 109 insertions(+), 109 deletions(-) diff --git a/contracts/interfaces/ILendingPool.sol b/contracts/interfaces/ILendingPool.sol index 4b3c8385..4daf85e0 100644 --- a/contracts/interfaces/ILendingPool.sol +++ b/contracts/interfaces/ILendingPool.sol @@ -295,8 +295,8 @@ interface ILendingPool { view returns ( uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, diff --git a/contracts/interfaces/IReserveInterestRateStrategy.sol b/contracts/interfaces/IReserveInterestRateStrategy.sol index acc097bf..99f30b78 100644 --- a/contracts/interfaces/IReserveInterestRateStrategy.sol +++ b/contracts/interfaces/IReserveInterestRateStrategy.sol @@ -21,8 +21,8 @@ interface IReserveInterestRateStrategy { function calculateInterestRates( address reserve, uint256 utilizationRate, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) diff --git a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol index f03b3c94..045e9358 100644 --- a/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol +++ b/contracts/lendingpool/DefaultReserveInterestRateStrategy.sol @@ -104,8 +104,8 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { * @dev calculates the interest rates depending on the available liquidity and the total borrowed. * @param reserve the address of the reserve * @param availableLiquidity the liquidity available in the reserve - * @param totalBorrowsStable the total borrowed from the reserve a stable rate - * @param totalBorrowsVariable the total borrowed from the reserve at a variable rate + * @param totalStableDebt the total borrowed from the reserve a stable rate + * @param totalVariableDebt the total borrowed from the reserve at a variable rate * @param averageStableBorrowRate the weighted average of all the stable rate borrows * @param reserveFactor the reserve portion of the interest to redirect to the reserve treasury * @return currentLiquidityRate the liquidity rate @@ -115,8 +115,8 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { function calculateInterestRates( address reserve, uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) @@ -132,7 +132,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { CalcInterestRatesLocalVars memory vars; - vars.totalBorrows = totalBorrowsStable.add(totalBorrowsVariable); + vars.totalBorrows = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; @@ -166,8 +166,8 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { } vars.currentLiquidityRate = _getOverallBorrowRate( - totalBorrowsStable, - totalBorrowsVariable, + totalStableDebt, + totalVariableDebt, vars.currentVariableBorrowRate, averageStableBorrowRate ) @@ -179,27 +179,27 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { /** * @dev calculates the overall borrow rate as the weighted average between the total variable borrows and total stable borrows. - * @param totalBorrowsStable the total borrowed from the reserve a stable rate - * @param totalBorrowsVariable the total borrowed from the reserve at a variable rate + * @param totalStableDebt the total borrowed from the reserve a stable rate + * @param totalVariableDebt the total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate the current variable borrow rate * @param currentAverageStableBorrowRate the weighted average of all the stable rate borrows * @return the weighted averaged borrow rate **/ function _getOverallBorrowRate( - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { - uint256 totalBorrows = totalBorrowsStable.add(totalBorrowsVariable); + uint256 totalBorrows = totalStableDebt.add(totalVariableDebt); if (totalBorrows == 0) return 0; - uint256 weightedVariableRate = totalBorrowsVariable.wadToRay().rayMul( + uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul( currentVariableBorrowRate ); - uint256 weightedStableRate = totalBorrowsStable.wadToRay().rayMul( + uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul( currentAverageStableBorrowRate ); diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 93716948..1ccfc467 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -587,8 +587,8 @@ contract LendingPool is VersionedInitializable, ILendingPool { view returns ( uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 42cbffb3..c41d14ba 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -421,8 +421,8 @@ contract LendingPoolConfigurator is VersionedInitializable { function deactivateReserve(address asset) external onlyLendingPoolManager { ( uint256 availableLiquidity, - uint256 totalBorrowsStable, - uint256 totalBorrowsVariable, + uint256 totalStableDebt, + uint256 totalVariableDebt, , , , @@ -432,7 +432,7 @@ contract LendingPoolConfigurator is VersionedInitializable { ) = pool.getReserveData(asset); require( - availableLiquidity == 0 && totalBorrowsStable == 0 && totalBorrowsVariable == 0, + availableLiquidity == 0 && totalStableDebt == 0 && totalVariableDebt == 0, Errors.RESERVE_LIQUIDITY_NOT_0 ); diff --git a/test/flash-liquidation-with-collateral.spec.ts b/test/flash-liquidation-with-collateral.spec.ts index c48b5e99..be1db606 100644 --- a/test/flash-liquidation-with-collateral.spec.ts +++ b/test/flash-liquidation-with-collateral.spec.ts @@ -233,7 +233,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn userData: usdcUserDataBefore, } = await getContractsData(usdc.address, user.address, testEnv); - const amountToRepay = usdcReserveDataBefore.totalBorrowsVariable.dividedBy(2).toFixed(0); + const amountToRepay = usdcReserveDataBefore.totalVariableDebt.dividedBy(2).toFixed(0); await mockSwapAdapter.setAmountToReturn(amountToRepay); await waitForTx( @@ -368,7 +368,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn userData: usdcUserDataBefore, } = await getContractsData(usdc.address, user.address, testEnv); - const amountToRepay = usdcReserveDataBefore.totalBorrowsVariable.toFixed(0); + const amountToRepay = usdcReserveDataBefore.totalVariableDebt.toFixed(0); await mockSwapAdapter.setAmountToReturn(amountToRepay); await waitForTx( @@ -486,7 +486,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn testEnv ); - const amountToRepay = daiReserveDataBefore.totalBorrowsVariable.toString(); + const amountToRepay = daiReserveDataBefore.totalVariableDebt.toString(); await waitForTx(await mockSwapAdapter.setTryReentrancy(true)); @@ -522,7 +522,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn ); // First half - const amountToRepay = daiReserveDataBefore.totalBorrowsVariable.dividedBy(2).toString(); + const amountToRepay = daiReserveDataBefore.totalVariableDebt.dividedBy(2).toString(); await mockSwapAdapter.setAmountToReturn(amountToRepay); await expect( @@ -568,7 +568,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn ); // First half - const amountToRepay = daiReserveDataBefore.totalBorrowsVariable.multipliedBy(0.6).toString(); + const amountToRepay = daiReserveDataBefore.totalVariableDebt.multipliedBy(0.6).toString(); await mockSwapAdapter.setAmountToReturn(amountToRepay); await waitForTx( @@ -654,7 +654,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn await increaseTime(1000); // Repay the remaining DAI - const amountToRepay = daiReserveDataBefore.totalBorrowsVariable.toString(); + const amountToRepay = daiReserveDataBefore.totalVariableDebt.toString(); await mockSwapAdapter.setAmountToReturn(amountToRepay); const receipt = await waitForTx( diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index 952bdab4..ad8e7e08 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -60,8 +60,8 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const currentLiquidityIndex = reserveData.liquidityIndex; const totalLiquidity = new BigNumber(reserveData.availableLiquidity.toString()) - .plus(reserveData.totalBorrowsStable.toString()) - .plus(reserveData.totalBorrowsVariable.toString()); + .plus(reserveData.totalStableDebt.toString()) + .plus(reserveData.totalVariableDebt.toString()); expect(totalLiquidity.toString()).to.be.equal('1000720000000000000'); expect(currentLiquidityRate.toString()).to.be.equal('0'); @@ -87,8 +87,8 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const currentLiquidityIndex = reserveData.liquidityIndex; const totalLiquidity = new BigNumber(reserveData.availableLiquidity.toString()) - .plus(reserveData.totalBorrowsStable.toString()) - .plus(reserveData.totalBorrowsVariable.toString()); + .plus(reserveData.totalStableDebt.toString()) + .plus(reserveData.totalVariableDebt.toString()); expect(totalLiquidity.toString()).to.be.equal('1001620648000000000'); expect(currentLiqudityRate.toString()).to.be.equal('0'); @@ -242,8 +242,8 @@ makeSuite('LendingPool FlashLoan function', (testEnv: TestEnv) => { const userData = await pool.getUserReserveData(usdc.address, depositor.address); const totalLiquidity = reserveData.availableLiquidity - .add(reserveData.totalBorrowsStable) - .add(reserveData.totalBorrowsVariable) + .add(reserveData.totalStableDebt) + .add(reserveData.totalVariableDebt) .toString(); const currentLiqudityRate = reserveData.liquidityRate.toString(); const currentLiquidityIndex = reserveData.liquidityIndex.toString(); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index b9f9ebe2..9c84d851 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -166,21 +166,21 @@ export const calcExpectedReserveDataAfterDeposit = ( reserveDataBeforeAction.availableLiquidity ).plus(amountDeposited); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable; - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); const rates = calcExpectedInterestRates( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); expectedReserveData.liquidityRate = rates[0]; @@ -225,21 +225,21 @@ export const calcExpectedReserveDataAfterWithdraw = ( reserveDataBeforeAction.availableLiquidity ).minus(amountWithdrawn); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable; - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); const rates = calcExpectedInterestRates( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); expectedReserveData.liquidityRate = rates[0]; @@ -286,17 +286,17 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt .plus(amountBorrowedBN) .plus(debtAccrued); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalBorrowsStable.plus(debtAccrued), + reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), amountBorrowedBN, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; } else { const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( reserveDataBeforeAction.variableBorrowIndex @@ -304,10 +304,10 @@ export const calcExpectedReserveDataAfterBorrow = ( const debtAccrued = userVariableDebt.minus(variableDebtBefore); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt .plus(amountBorrowedBN) .plus(debtAccrued); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable; + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; } @@ -316,8 +316,8 @@ export const calcExpectedReserveDataAfterBorrow = ( ); expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); @@ -325,8 +325,8 @@ export const calcExpectedReserveDataAfterBorrow = ( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); expectedReserveData.liquidityRate = rates[0]; @@ -385,17 +385,17 @@ export const calcExpectedReserveDataAfterRepay = ( expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt .minus(amountRepaidBN) .plus(debtAccrued); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalBorrowsStable.plus(debtAccrued), + reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), amountRepaidBN.negated(), userDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; } else { const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( reserveDataBeforeAction.variableBorrowIndex @@ -405,11 +405,11 @@ export const calcExpectedReserveDataAfterRepay = ( expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt .plus(debtAccrued) .minus(amountRepaidBN); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable; + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; } @@ -422,8 +422,8 @@ export const calcExpectedReserveDataAfterRepay = ( ); expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); @@ -431,8 +431,8 @@ export const calcExpectedReserveDataAfterRepay = ( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); expectedReserveData.liquidityRate = rates[0]; @@ -677,16 +677,16 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalBorrowsStable.plus(debtAccrued), + reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), stableDebt.negated(), userDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable.plus( + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt.plus( stableDebt ); - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable.minus( + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.minus( userDataBeforeAction.principalStableDebt ); } else { @@ -695,23 +695,23 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable.plus( + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( variableDebt ); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalBorrowsStable, + reserveDataBeforeAction.totalStableDebt, variableDebt, reserveDataBeforeAction.stableBorrowRate ); } expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); @@ -719,8 +719,8 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); expectedReserveData.liquidityRate = rates[0]; @@ -824,7 +824,7 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( const avgRateBefore = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalBorrowsStable.plus(debtAccrued), + reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), stableBorrowBalance.negated(), userDataBeforeAction.stableBorrowRate ); @@ -832,19 +832,19 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( avgRateBefore, - reserveDataBeforeAction.totalBorrowsStable.minus(userDataBeforeAction.principalStableDebt), + reserveDataBeforeAction.totalStableDebt.minus(userDataBeforeAction.principalStableDebt), stableBorrowBalance, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalBorrowsVariable = reserveDataBeforeAction.totalBorrowsVariable; - expectedReserveData.totalBorrowsStable = reserveDataBeforeAction.totalBorrowsStable.plus( + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( debtAccrued ); expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); @@ -852,8 +852,8 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, expectedReserveData.utilizationRate, - expectedReserveData.totalBorrowsStable, - expectedReserveData.totalBorrowsVariable, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, expectedReserveData.averageStableBorrowRate ); @@ -936,13 +936,13 @@ const calcExpectedATokenBalance = ( const calcExpectedAverageStableBorrowRate = ( avgStableRateBefore: BigNumber, - totalBorrowsStableBefore: BigNumber, + totalStableDebtBefore: BigNumber, amountChanged: string | BigNumber, rate: BigNumber ) => { - const weightedTotalBorrows = avgStableRateBefore.multipliedBy(totalBorrowsStableBefore); + const weightedTotalBorrows = avgStableRateBefore.multipliedBy(totalStableDebtBefore); const weightedAmountBorrowed = rate.multipliedBy(amountChanged); - const totalBorrowedStable = totalBorrowsStableBefore.plus(new BigNumber(amountChanged)); + const totalBorrowedStable = totalStableDebtBefore.plus(new BigNumber(amountChanged)); if (totalBorrowedStable.eq(0)) return new BigNumber('0'); @@ -1048,8 +1048,8 @@ const calcExpectedInterestRates = ( reserveSymbol: string, marketStableRate: BigNumber, utilizationRate: BigNumber, - totalBorrowsStable: BigNumber, - totalBorrowsVariable: BigNumber, + totalStableDebt: BigNumber, + totalVariableDebt: BigNumber, averageStableBorrowRate: BigNumber ): BigNumber[] => { const {reservesParams} = configuration; @@ -1093,8 +1093,8 @@ const calcExpectedInterestRates = ( } const expectedOverallRate = calcExpectedOverallBorrowRate( - totalBorrowsStable, - totalBorrowsVariable, + totalStableDebt, + totalVariableDebt, variableBorrowRate, averageStableBorrowRate ); @@ -1104,18 +1104,18 @@ const calcExpectedInterestRates = ( }; const calcExpectedOverallBorrowRate = ( - totalBorrowsStable: BigNumber, - totalBorrowsVariable: BigNumber, + totalStableDebt: BigNumber, + totalVariableDebt: BigNumber, currentVariableBorrowRate: BigNumber, currentAverageStableBorrowRate: BigNumber ): BigNumber => { - const totalBorrows = totalBorrowsStable.plus(totalBorrowsVariable); + const totalBorrows = totalStableDebt.plus(totalVariableDebt); if (totalBorrows.eq(0)) return strToBN('0'); - const weightedVariableRate = totalBorrowsVariable.wadToRay().rayMul(currentVariableBorrowRate); + const weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); - const weightedStableRate = totalBorrowsStable.wadToRay().rayMul(currentAverageStableBorrowRate); + const weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); const overallBorrowRate = weightedVariableRate .plus(weightedStableRate) @@ -1125,15 +1125,15 @@ const calcExpectedOverallBorrowRate = ( }; const calcExpectedUtilizationRate = ( - totalBorrowsStable: BigNumber, - totalBorrowsVariable: BigNumber, + totalStableDebt: BigNumber, + totalVariableDebt: BigNumber, totalLiquidity: BigNumber ): BigNumber => { - if (totalBorrowsStable.eq('0') && totalBorrowsVariable.eq('0')) { + if (totalStableDebt.eq('0') && totalVariableDebt.eq('0')) { return strToBN('0'); } - const utilization = totalBorrowsStable.plus(totalBorrowsVariable).rayDiv(totalLiquidity); + const utilization = totalStableDebt.plus(totalVariableDebt).rayDiv(totalLiquidity); return utilization; }; @@ -1210,8 +1210,8 @@ const calcExpectedLiquidityIndex = (reserveData: ReserveData, timestamp: BigNumb }; const calcExpectedVariableBorrowIndex = (reserveData: ReserveData, timestamp: BigNumber) => { - //if totalBorrowsVariable is 0, nothing to compound - if (reserveData.totalBorrowsVariable.eq('0')) { + //if totalVariableDebt is 0, nothing to compound + if (reserveData.totalVariableDebt.eq('0')) { return reserveData.variableBorrowIndex; } diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index 1d2516ad..2289c7ad 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -26,14 +26,14 @@ export const getReserveData = async ( const decimals = new BigNumber(await token.decimals()); const totalLiquidity = new BigNumber(data.availableLiquidity.toString()) - .plus(data.totalBorrowsStable.toString()) - .plus(data.totalBorrowsVariable.toString()); + .plus(data.totalStableDebt.toString()) + .plus(data.totalVariableDebt.toString()); const utilizationRate = new BigNumber( totalLiquidity.eq(0) ? 0 - : new BigNumber(data.totalBorrowsStable.toString()) - .plus(data.totalBorrowsVariable.toString()) + : new BigNumber(data.totalStableDebt.toString()) + .plus(data.totalVariableDebt.toString()) .rayDiv(totalLiquidity) ); @@ -41,8 +41,8 @@ export const getReserveData = async ( totalLiquidity, utilizationRate, availableLiquidity: new BigNumber(data.availableLiquidity.toString()), - totalBorrowsStable: new BigNumber(data.totalBorrowsStable.toString()), - totalBorrowsVariable: new BigNumber(data.totalBorrowsVariable.toString()), + totalStableDebt: new BigNumber(data.totalStableDebt.toString()), + totalVariableDebt: new BigNumber(data.totalVariableDebt.toString()), liquidityRate: new BigNumber(data.liquidityRate.toString()), variableBorrowRate: new BigNumber(data.variableBorrowRate.toString()), stableBorrowRate: new BigNumber(data.stableBorrowRate.toString()), diff --git a/test/helpers/utils/interfaces/index.ts b/test/helpers/utils/interfaces/index.ts index 2acbfa31..b0497592 100644 --- a/test/helpers/utils/interfaces/index.ts +++ b/test/helpers/utils/interfaces/index.ts @@ -21,8 +21,8 @@ export interface ReserveData { decimals: BigNumber; totalLiquidity: BigNumber; availableLiquidity: BigNumber; - totalBorrowsStable: BigNumber; - totalBorrowsVariable: BigNumber; + totalStableDebt: BigNumber; + totalVariableDebt: BigNumber; averageStableBorrowRate: BigNumber; variableBorrowRate: BigNumber; stableBorrowRate: BigNumber; From d542f098c14ca31f60286eb75c158c7b4b656872 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 19:25:45 +0200 Subject: [PATCH 18/45] fixed deposit, withdraw tests --- contracts/libraries/logic/ReserveLogic.sol | 20 ++-- contracts/tokenization/StableDebtToken.sol | 32 ++++-- .../interfaces/IStableDebtToken.sol | 16 ++- helpers/contracts-helpers.ts | 15 +++ test/helpers/utils/calculations.ts | 97 ++++++++++++------- test/helpers/utils/helpers.ts | 55 ++++++----- test/helpers/utils/interfaces/index.ts | 2 + test/scenario.spec.ts | 2 +- 8 files changed, 157 insertions(+), 82 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index b287094a..73b68f17 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -31,7 +31,6 @@ library ReserveLogic { * @param reserve the address of the reserve * @param liquidityRate the new liquidity rate * @param stableBorrowRate the new stable borrow rate - * @param averageStableBorrowRate the new average stable borrow rate * @param variableBorrowRate the new variable borrow rate * @param liquidityIndex the new liquidity index * @param variableBorrowIndex the new variable borrow index @@ -40,7 +39,6 @@ library ReserveLogic { address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, - uint256 averageStableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex @@ -190,12 +188,13 @@ library ReserveLogic { } struct UpdateInterestRatesLocalVars { - uint256 currentAvgStableRate; - uint256 availableLiquidity; address stableDebtTokenAddress; + uint256 availableLiquidity; + uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; + uint256 avgStableRate; } /** @@ -215,8 +214,10 @@ library ReserveLogic { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; - vars.currentAvgStableRate = IStableDebtToken(vars.stableDebtTokenAddress) - .getAverageStableRate(); + + (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) + .getTotalSupplyAndAvgRate(); + vars.availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress); ( @@ -226,9 +227,9 @@ library ReserveLogic { ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, vars.availableLiquidity.add(liquidityAdded).sub(liquidityTaken), - IERC20(vars.stableDebtTokenAddress).totalSupply(), + vars.totalStableDebt, IERC20(reserve.variableDebtTokenAddress).totalSupply(), - vars.currentAvgStableRate, + vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate < (1 << 128), 'ReserveLogic: Liquidity rate overflow'); @@ -243,7 +244,6 @@ library ReserveLogic { reserveAddress, vars.newLiquidityRate, vars.newStableRate, - vars.currentAvgStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex @@ -318,7 +318,7 @@ library ReserveLogic { currentLiquidityRate, lastUpdateTimestamp ); - uint256 index = cumulatedLiquidityInterest.rayMul(reserve.liquidityIndex); + uint256 index = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(index < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(index); diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 1d166c8f..0434906f 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -219,18 +219,18 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { return (super.totalSupply(), _avgStableRate); } - function totalSupply() public override view returns (uint256) { - uint256 principalSupply = super.totalSupply(); - if (principalSupply == 0) { - return 0; - } - uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest( - _avgStableRate, - _totalSupplyTimestamp - ); - return principalSupply.rayMul(cumulatedInterest); + function getTotalSupplyAndAvgRate() public override view returns (uint256, uint256) { + uint256 avgRate = _avgStableRate; + return (_calcTotalSupply(avgRate), avgRate); } + function totalSupply() public override view returns (uint256) { + _calcTotalSupply(_avgStableRate); + } + + function getTotalSupplyLastUpdated() public override view returns(uint40) { + return _totalSupplyTimestamp; + } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action @@ -238,4 +238,16 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { function principalBalanceOf(address user) external virtual override view returns (uint256) { return super.balanceOf(user); } + + function _calcTotalSupply(uint256 avgRate) internal view returns(uint256) { + uint256 principalSupply = super.totalSupply(); + if (principalSupply == 0) { + return 0; + } + uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest( + avgRate, + _totalSupplyTimestamp + ); + return principalSupply.rayMul(cumulatedInterest); + } } diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index c1e97388..46324e88 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -90,10 +90,20 @@ interface IStableDebtToken { **/ function getPrincipalSupplyAndAvgRate() external view returns (uint256, uint256); - /** - * @dev Returns the principal debt balance of the user + /** + * @dev returns the timestamp of the last update of the total supply + * @return the timestamp + **/ + function getTotalSupplyLastUpdated() external view returns (uint40); + + /** + * @dev returns the total supply and the average stable rate + **/ + function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); + + /** + * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); - } diff --git a/helpers/contracts-helpers.ts b/helpers/contracts-helpers.ts index 11780c11..c5edc9da 100644 --- a/helpers/contracts-helpers.ts +++ b/helpers/contracts-helpers.ts @@ -348,6 +348,21 @@ export const getAToken = async (address?: tEthereumAddress) => { ); }; +export const getStableDebtToken = async (address?: tEthereumAddress) => { + return await getContract( + eContractid.StableDebtToken, + address || (await getDb().get(`${eContractid.StableDebtToken}.${BRE.network.name}`).value()).address + ); +}; + +export const getVariableDebtToken = async (address?: tEthereumAddress) => { + return await getContract( + eContractid.VariableDebtToken, + address || (await getDb().get(`${eContractid.VariableDebtToken}.${BRE.network.name}`).value()).address + ); +}; + + export const getMintableErc20 = async (address: tEthereumAddress) => { return await getContract( eContractid.MintableERC20, diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 9c84d851..98d52cf2 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -42,7 +42,7 @@ export const calcExpectedUserDataAfterDeposit = ( ); expectedUserData.principalStableDebt = userDataBeforeAction.principalStableDebt; - expectedUserData.principalVariableDebt = userDataBeforeAction.principalVariableDebt; + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.variableBorrowIndex = userDataBeforeAction.variableBorrowIndex; expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; expectedUserData.stableRateLastUpdated = userDataBeforeAction.stableRateLastUpdated; @@ -115,7 +115,7 @@ export const calcExpectedUserDataAfterWithdraw = ( expectedUserData.currentATokenBalance = aTokenBalance.minus(amountWithdrawn); expectedUserData.principalStableDebt = userDataBeforeAction.principalStableDebt; - expectedUserData.principalVariableDebt = userDataBeforeAction.principalVariableDebt; + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( userDataBeforeAction, @@ -166,9 +166,28 @@ export const calcExpectedReserveDataAfterDeposit = ( reserveDataBeforeAction.availableLiquidity ).plus(amountDeposited); - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( + reserveDataBeforeAction, + txTimestamp + ); + + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( + reserveDataBeforeAction, + expectedReserveData.variableBorrowIndex + ); + + + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, @@ -186,17 +205,7 @@ export const calcExpectedReserveDataAfterDeposit = ( expectedReserveData.liquidityRate = rates[0]; expectedReserveData.stableBorrowRate = rates[1]; expectedReserveData.variableBorrowRate = rates[2]; - - expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - + return expectedReserveData; }; @@ -225,8 +234,21 @@ export const calcExpectedReserveDataAfterWithdraw = ( reserveDataBeforeAction.availableLiquidity ).minus(amountWithdrawn); - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; + + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( + reserveDataBeforeAction, + txTimestamp + ); + + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt(reserveDataBeforeAction, txTimestamp); + expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt(reserveDataBeforeAction, expectedReserveData.variableBorrowIndex); + expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; expectedReserveData.utilizationRate = calcExpectedUtilizationRate( @@ -246,16 +268,6 @@ export const calcExpectedReserveDataAfterWithdraw = ( expectedReserveData.stableBorrowRate = rates[1]; expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - return expectedReserveData; }; @@ -512,7 +524,9 @@ export const calcExpectedUserDataAfterBorrow = ( expectedDataAfterAction, { ...userDataBeforeAction, - currentVariableDebt: expectedUserData.scaledVariableDebt.rayMul(reserveDataBeforeAction.variableBorrowIndex), + currentVariableDebt: expectedUserData.scaledVariableDebt.rayMul( + reserveDataBeforeAction.variableBorrowIndex + ), scaledVariableDebt: expectedUserData.scaledVariableDebt, variableBorrowIndex: interestRateMode == RateMode.Variable @@ -690,13 +704,14 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( userDataBeforeAction.principalStableDebt ); } else { - const totalDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul(reserveDataBeforeAction.variableBorrowIndex); + const totalDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( + reserveDataBeforeAction.variableBorrowIndex + ); const debtAccrued = variableDebt.minus(totalDebtBefore); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( variableDebt @@ -838,9 +853,7 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( ); expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( - debtAccrued - ); + expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus(debtAccrued); expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, @@ -1223,3 +1236,19 @@ const calcExpectedVariableBorrowIndex = (reserveData: ReserveData, timestamp: Bi return cumulatedInterest.rayMul(reserveData.variableBorrowIndex); }; + +const calcExpectedTotalStableDebt = (reserveData: ReserveData, timestamp: BigNumber) => { + + const cumulatedInterest = calcCompoundedInterest( + reserveData.averageStableBorrowRate, + timestamp, + reserveData.lastUpdateTimestamp + ); + + return cumulatedInterest.rayMul(reserveData.principalStableDebt); +} + +const calcExpectedTotalVariableDebt = (reserveData: ReserveData, expectedVariableDebtIndex: BigNumber) => { + + return reserveData.scaledVariableDebt.rayMul(expectedVariableDebtIndex); +} diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index 2289c7ad..3f3a2ec8 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -4,9 +4,8 @@ import { getLendingRateOracle, getIErc20Detailed, getMintableErc20, - getAToken, + getAToken, getStableDebtToken, getVariableDebtToken } from '../../../helpers/contracts-helpers'; -import {ZERO_ADDRESS} from '../../../helpers/constants'; import {tEthereumAddress} from '../../../helpers/types'; import BigNumber from 'bignumber.js'; import {getDb, BRE} from '../../../helpers/misc-utils'; @@ -15,41 +14,51 @@ export const getReserveData = async ( pool: LendingPool, reserve: tEthereumAddress ): Promise => { - const data = await pool.getReserveData(reserve); - const tokenAddresses = await pool.getReserveTokensAddresses(reserve); - const rateOracle = await getLendingRateOracle(); + const [reserveData, tokenAddresses, rateOracle, token] = await Promise.all([ + pool.getReserveData(reserve), + pool.getReserveTokensAddresses(reserve), + getLendingRateOracle(), + getIErc20Detailed(reserve), + ]); + + const stableDebtToken = await getStableDebtToken(tokenAddresses.stableDebtTokenAddress); + const variableDebtToken = await getVariableDebtToken(tokenAddresses.variableDebtTokenAddress); + + const [principalStableDebt] = await stableDebtToken.getPrincipalSupplyAndAvgRate(); + + const scaledVariableDebt = await variableDebtToken.scaledTotalSupply(); const rate = (await rateOracle.getMarketBorrowRate(reserve)).toString(); - - const token = await getIErc20Detailed(reserve); const symbol = await token.symbol(); const decimals = new BigNumber(await token.decimals()); - const totalLiquidity = new BigNumber(data.availableLiquidity.toString()) - .plus(data.totalStableDebt.toString()) - .plus(data.totalVariableDebt.toString()); + const totalLiquidity = new BigNumber(reserveData.availableLiquidity.toString()) + .plus(reserveData.totalStableDebt.toString()) + .plus(reserveData.totalVariableDebt.toString()); const utilizationRate = new BigNumber( totalLiquidity.eq(0) ? 0 - : new BigNumber(data.totalStableDebt.toString()) - .plus(data.totalVariableDebt.toString()) + : new BigNumber(reserveData.totalStableDebt.toString()) + .plus(reserveData.totalVariableDebt.toString()) .rayDiv(totalLiquidity) ); return { totalLiquidity, utilizationRate, - availableLiquidity: new BigNumber(data.availableLiquidity.toString()), - totalStableDebt: new BigNumber(data.totalStableDebt.toString()), - totalVariableDebt: new BigNumber(data.totalVariableDebt.toString()), - liquidityRate: new BigNumber(data.liquidityRate.toString()), - variableBorrowRate: new BigNumber(data.variableBorrowRate.toString()), - stableBorrowRate: new BigNumber(data.stableBorrowRate.toString()), - averageStableBorrowRate: new BigNumber(data.averageStableBorrowRate.toString()), - liquidityIndex: new BigNumber(data.liquidityIndex.toString()), - variableBorrowIndex: new BigNumber(data.variableBorrowIndex.toString()), - lastUpdateTimestamp: new BigNumber(data.lastUpdateTimestamp), + availableLiquidity: new BigNumber(reserveData.availableLiquidity.toString()), + totalStableDebt: new BigNumber(reserveData.totalStableDebt.toString()), + totalVariableDebt: new BigNumber(reserveData.totalVariableDebt.toString()), + liquidityRate: new BigNumber(reserveData.liquidityRate.toString()), + variableBorrowRate: new BigNumber(reserveData.variableBorrowRate.toString()), + stableBorrowRate: new BigNumber(reserveData.stableBorrowRate.toString()), + averageStableBorrowRate: new BigNumber(reserveData.averageStableBorrowRate.toString()), + liquidityIndex: new BigNumber(reserveData.liquidityIndex.toString()), + variableBorrowIndex: new BigNumber(reserveData.variableBorrowIndex.toString()), + lastUpdateTimestamp: new BigNumber(reserveData.lastUpdateTimestamp), + principalStableDebt: new BigNumber(principalStableDebt.toString()), + scaledVariableDebt: new BigNumber(scaledVariableDebt.toString()), address: reserve, aTokenAddress: tokenAddresses.aTokenAddress, symbol, @@ -69,7 +78,6 @@ export const getUserData = async ( getATokenUserData(reserve, user, pool), ]); - const token = await getMintableErc20(reserve); const walletBalance = new BigNumber((await token.balanceOf(sender || user)).toString()); @@ -106,5 +114,4 @@ const getATokenUserData = async (reserve: string, user: string, pool: LendingPoo const scaledBalance = await aToken.scaledBalanceOf(user); return scaledBalance.toString(); - }; diff --git a/test/helpers/utils/interfaces/index.ts b/test/helpers/utils/interfaces/index.ts index b0497592..3162e398 100644 --- a/test/helpers/utils/interfaces/index.ts +++ b/test/helpers/utils/interfaces/index.ts @@ -23,6 +23,8 @@ export interface ReserveData { availableLiquidity: BigNumber; totalStableDebt: BigNumber; totalVariableDebt: BigNumber; + principalStableDebt: BigNumber, + scaledVariableDebt: BigNumber, averageStableBorrowRate: BigNumber; variableBorrowRate: BigNumber; stableBorrowRate: BigNumber; diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 17830d1c..ee45a08f 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['deposit.json']; +const selectedScenarios: string[] = ['withdraw.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From d0d1db5e4d7e686ad44993310526282a158bc239 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 14 Sep 2020 20:04:49 +0200 Subject: [PATCH 19/45] Initial fix of the borrow tests --- test/helpers/utils/calculations.ts | 28 ++++++++++------------------ test/scenario.spec.ts | 2 +- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 98d52cf2..4c6d951e 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -30,12 +30,12 @@ export const calcExpectedUserDataAfterDeposit = ( ): UserReserveData => { const expectedUserData = {}; - expectedUserData.currentStableDebt = expectedUserData.principalStableDebt = calcExpectedStableDebtTokenBalance( + expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( userDataBeforeAction, txTimestamp ); - expectedUserData.currentVariableDebt = expectedUserData.principalStableDebt = calcExpectedVariableDebtTokenBalance( + expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, userDataBeforeAction, txTimestamp @@ -285,22 +285,23 @@ export const calcExpectedReserveDataAfterBorrow = ( const amountBorrowedBN = new BigNumber(amountBorrowed); - const userStableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); - - const userVariableDebt = calcExpectedVariableDebtTokenBalance( + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( reserveDataBeforeAction, - userDataBeforeAction, txTimestamp ); if (borrowRateMode == RateMode.Stable) { + + expectedReserveData. const debtAccrued = userStableDebt.minus(userDataBeforeAction.principalStableDebt); expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt - .plus(amountBorrowedBN) - .plus(debtAccrued); + expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, @@ -347,15 +348,6 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.lastUpdateTimestamp = txTimestamp; return expectedReserveData; diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index ee45a08f..98e0c164 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['withdraw.json']; +const selectedScenarios: string[] = ['borrow-repay-variable.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 04a67d3df0bbc95c24e882255fff2c5c93c5ec54 Mon Sep 17 00:00:00 2001 From: The3D Date: Tue, 15 Sep 2020 18:49:53 +0200 Subject: [PATCH 20/45] updated stabledebttoken --- contracts/tokenization/StableDebtToken.sol | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 85277ddc..7ba4ad31 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -81,10 +81,11 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } struct MintLocalVars { - uint256 supplyAfterMint; - uint256 supplyBeforeMint; + uint256 currentPrincipalSupply; + uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; + uint256 currentAvgStableRate; } /** @@ -108,8 +109,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 balanceIncrease ) = _calculateBalanceIncrease(user); - vars.supplyBeforeMint = totalSupply().add(balanceIncrease); - vars.supplyAfterMint = vars.supplyBeforeMint.add(amount); + vars.currentPrincipalSupply = totalSupply(); + vars.currentAvgStableRate = _avgStableRate; + vars.nextSupply = _totalSupply = _calcTotalSupply(vars.currentAvgStableRate).add(amount); vars.amountInRay = amount.wadToRay(); @@ -126,10 +128,10 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); //calculates the updated average stable rate - _avgStableRate = _avgStableRate - .rayMul(vars.supplyBeforeMint.wadToRay()) + _avgStableRate = vars.currentAvgStableRate + .rayMul(vars.currentPrincipalSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) - .rayDiv(vars.supplyAfterMint.wadToRay()); + .rayDiv(vars.nextSupply.wadToRay()); _mint(user, amount.add(balanceIncrease)); @@ -237,6 +239,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { function getTotalSupplyLastUpdated() public override view returns(uint40) { return _totalSupplyTimestamp; } + /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action From d873b630829e97ba63b0afc18fb0d0e157197477 Mon Sep 17 00:00:00 2001 From: The3D Date: Tue, 15 Sep 2020 18:54:59 +0200 Subject: [PATCH 21/45] Removed unused flashloan vars --- contracts/lendingpool/LendingPool.sol | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 2c9ad98a..36335e94 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -453,19 +453,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { } } - struct FlashLoanLocalVars { - uint256 premium; - uint256 amountPlusPremium; - uint256 amountPlusPremiumInETH; - uint256 receiverBalance; - uint256 receiverAllowance; - uint256 availableBalance; - uint256 assetPrice; - IFlashLoanReceiver receiver; - address aTokenAddress; - address oracle; - } - /** * @dev flashes the underlying collateral on an user to swap for the owed asset and repay * - Both the owner of the position and other liquidators can execute it @@ -514,6 +501,14 @@ contract LendingPool is VersionedInitializable, ILendingPool { _flashLiquidationLocked = false; } + struct FlashLoanLocalVars { + uint256 premium; + uint256 amountPlusPremium; + IFlashLoanReceiver receiver; + address aTokenAddress; + address oracle; + } + /** * @dev allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts @@ -569,7 +564,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { asset, msg.sender, msg.sender, - vars.amountPlusPremium.sub(vars.availableBalance), + vars.amountPlusPremium, mode, vars.aTokenAddress, referralCode, From 77c812b975c1278a29d9350a3c027951b8001567 Mon Sep 17 00:00:00 2001 From: andyk Date: Wed, 16 Sep 2020 13:16:51 +0300 Subject: [PATCH 22/45] Refactor the storage of lendingpool to LendingPoolStorage parent contract --- contracts/lendingpool/LendingPool.sol | 40 +--- .../LendingPoolLiquidationManager.sol | 65 +++---- contracts/lendingpool/LendingPoolStorage.sol | 39 ++++ deployed-contracts.json | 173 +++++++++++++++++- 4 files changed, 241 insertions(+), 76 deletions(-) create mode 100644 contracts/lendingpool/LendingPoolStorage.sol diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 69a92b6f..aa3a758b 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -25,6 +25,7 @@ import {LendingPoolLiquidationManager} from './LendingPoolLiquidationManager.sol import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; +import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract @@ -32,12 +33,9 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; * @author Aave **/ -contract LendingPool is VersionedInitializable, ILendingPool { +contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; - using ReserveLogic for ReserveLogic.ReserveData; - using ReserveConfiguration for ReserveConfiguration.Map; - using UserConfiguration for UserConfiguration.Map; using SafeERC20 for IERC20; //main configuration parameters @@ -45,18 +43,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 public constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 public constant FLASHLOAN_PREMIUM_TOTAL = 9; - ILendingPoolAddressesProvider internal _addressesProvider; - - mapping(address => ReserveLogic.ReserveData) internal _reserves; - mapping(address => UserConfiguration.Map) internal _usersConfig; - // debt token address => user who gives allowance => user who receives allowance => amount - mapping(address => mapping(address => mapping(address => uint256))) internal _borrowAllowance; - - address[] internal _reservesList; - - bool internal _flashLiquidationLocked; - bool internal _paused; - /** * @dev only lending pools configurator can use functions affected by this modifier **/ @@ -78,8 +64,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { require(!_paused, Errors.IS_PAUSED); } - uint256 public constant UINT_MAX_VALUE = uint256(-1); - uint256 public constant LENDINGPOOL_REVISION = 0x2; function getRevision() internal override pure returns (uint256) { @@ -147,7 +131,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { uint256 amountToWithdraw = amount; //if amount is equal to uint(-1), the user wants to redeem everything - if (amount == UINT_MAX_VALUE) { + if (amount == type(uint256).max) { amountToWithdraw = userBalance; } @@ -283,7 +267,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { ? stableDebt : variableDebt; - if (amount != UINT_MAX_VALUE && amount < paybackAmount) { + if (amount != type(uint256).max && amount < paybackAmount) { paybackAmount = amount; } @@ -1003,20 +987,6 @@ contract LendingPool is VersionedInitializable, ILendingPool { ); } - /** - * @dev returns the list of the initialized reserves - **/ - function getReservesList() external view returns (address[] memory) { - return _reservesList; - } - - /** - * @dev returns the addresses provider - **/ - function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { - return _addressesProvider; - } - /** * @dev Set the _pause state * @param val the boolean value to set the current pause state of LendingPool @@ -1035,7 +1005,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { /** * @dev Returns if the LendingPool is paused */ - function paused() external view override returns(bool) { + function paused() external override view returns (bool) { return _paused; } } diff --git a/contracts/lendingpool/LendingPoolLiquidationManager.sol b/contracts/lendingpool/LendingPoolLiquidationManager.sol index 6adc18d9..6e488428 100644 --- a/contracts/lendingpool/LendingPoolLiquidationManager.sol +++ b/contracts/lendingpool/LendingPoolLiquidationManager.sol @@ -6,14 +6,12 @@ import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { VersionedInitializable } from '../libraries/openzeppelin-upgradeability/VersionedInitializable.sol'; -import {LendingPoolAddressesProvider} from '../configuration/LendingPoolAddressesProvider.sol'; import {IAToken} from '../tokenization/interfaces/IAToken.sol'; import {IStableDebtToken} from '../tokenization/interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../tokenization/interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; -import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; @@ -22,6 +20,7 @@ import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/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'; /** * @title LendingPoolLiquidationManager contract @@ -29,29 +28,15 @@ import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; * @notice Implements the liquidation function. * @dev LendingPoolLiquidationManager inherits Pausable from OpenZeppelin to have the same storage layout as LendingPool **/ -contract LendingPoolLiquidationManager is VersionedInitializable { +contract LendingPoolLiquidationManager is VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; - using ReserveLogic for ReserveLogic.ReserveData; - using ReserveConfiguration for ReserveConfiguration.Map; - using UserConfiguration for UserConfiguration.Map; // IMPORTANT The storage layout of the LendingPool is reproduced here because this contract // is gonna be used through DELEGATECALL - LendingPoolAddressesProvider internal addressesProvider; - - mapping(address => ReserveLogic.ReserveData) internal reserves; - mapping(address => UserConfiguration.Map) internal usersConfig; - mapping(address => mapping(address => mapping(address => uint256))) internal _borrowAllowance; - - address[] internal reservesList; - - bool internal _flashLiquidationLocked; - bool public _paused; - uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; /** @@ -156,18 +141,18 @@ contract LendingPoolLiquidationManager is VersionedInitializable { uint256 purchaseAmount, bool receiveAToken ) external returns (uint256, string memory) { - ReserveLogic.ReserveData storage collateralReserve = reserves[collateral]; - ReserveLogic.ReserveData storage principalReserve = reserves[principal]; - UserConfiguration.Map storage userConfig = usersConfig[user]; + ReserveLogic.ReserveData storage collateralReserve = _reserves[collateral]; + ReserveLogic.ReserveData storage principalReserve = _reserves[principal]; + UserConfiguration.Map storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, - reserves, - usersConfig[user], - reservesList, - addressesProvider.getPriceOracle() + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() ); //if the user hasn't borrowed the specific currency defined by asset, it cannot be liquidated @@ -323,18 +308,18 @@ contract LendingPoolLiquidationManager is VersionedInitializable { address receiver, bytes calldata params ) external returns (uint256, string memory) { - ReserveLogic.ReserveData storage collateralReserve = reserves[collateral]; - ReserveLogic.ReserveData storage debtReserve = reserves[principal]; - UserConfiguration.Map storage userConfig = usersConfig[user]; + ReserveLogic.ReserveData storage collateralReserve = _reserves[collateral]; + ReserveLogic.ReserveData storage debtReserve = _reserves[principal]; + UserConfiguration.Map storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, - reserves, - usersConfig[user], - reservesList, - addressesProvider.getPriceOracle() + _reserves, + _usersConfig[user], + _reservesList, + _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); @@ -391,7 +376,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ); if (vars.userCollateralBalance == vars.maxCollateralToLiquidate) { - usersConfig[user].setUsingAsCollateral(collateralReserve.id, false); + _usersConfig[user].setUsingAsCollateral(collateralReserve.id, false); } vars.principalAToken = debtReserve.aTokenAddress; @@ -463,8 +448,8 @@ contract LendingPoolLiquidationManager is VersionedInitializable { uint256 amountToSwap, bytes calldata params ) external returns (uint256, string memory) { - ReserveLogic.ReserveData storage fromReserve = reserves[fromAsset]; - ReserveLogic.ReserveData storage toReserve = reserves[toAsset]; + ReserveLogic.ReserveData storage fromReserve = _reserves[fromAsset]; + ReserveLogic.ReserveData storage toReserve = _reserves[toAsset]; // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables SwapLiquidityLocalVars memory vars; @@ -487,7 +472,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { toReserve.updateCumulativeIndexesAndTimestamp(); if (vars.fromReserveAToken.balanceOf(msg.sender) == amountToSwap) { - usersConfig[msg.sender].setUsingAsCollateral(fromReserve.id, false); + _usersConfig[msg.sender].setUsingAsCollateral(fromReserve.id, false); } fromReserve.updateInterestRates(fromAsset, address(vars.fromReserveAToken), 0, amountToSwap); @@ -525,10 +510,10 @@ contract LendingPoolLiquidationManager is VersionedInitializable { (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( msg.sender, - reserves, - usersConfig[msg.sender], - reservesList, - addressesProvider.getPriceOracle() + _reserves, + _usersConfig[msg.sender], + _reservesList, + _addressesProvider.getPriceOracle() ); if (vars.healthFactor < GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { @@ -562,7 +547,7 @@ contract LendingPoolLiquidationManager is VersionedInitializable { ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 principalAmountNeeded = 0; - IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); + IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables AvailableCollateralToLiquidateLocalVars memory vars; diff --git a/contracts/lendingpool/LendingPoolStorage.sol b/contracts/lendingpool/LendingPoolStorage.sol new file mode 100644 index 00000000..1f1e6d2e --- /dev/null +++ b/contracts/lendingpool/LendingPoolStorage.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: agpl-3.0 +pragma solidity ^0.6.8; + +import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; +import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; +import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; +import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; + +contract LendingPoolStorage { + using ReserveLogic for ReserveLogic.ReserveData; + using ReserveConfiguration for ReserveConfiguration.Map; + using UserConfiguration for UserConfiguration.Map; + + ILendingPoolAddressesProvider internal _addressesProvider; + + mapping(address => ReserveLogic.ReserveData) internal _reserves; + mapping(address => UserConfiguration.Map) internal _usersConfig; + // debt token address => user who gives allowance => user who receives allowance => amount + mapping(address => mapping(address => mapping(address => uint256))) internal _borrowAllowance; + + address[] internal _reservesList; + + bool internal _flashLiquidationLocked; + bool internal _paused; + + /** + * @dev returns the list of the initialized reserves + **/ + function getReservesList() external view returns (address[] memory) { + return _reservesList; + } + + /** + * @dev returns the addresses provider + **/ + function getAddressesProvider() external view returns (ILendingPoolAddressesProvider) { + return _addressesProvider; + } +} diff --git a/deployed-contracts.json b/deployed-contracts.json index 9981b17c..60c63dd8 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -7,6 +7,10 @@ "localhost": { "address": "0x9Dc554694756dC303a087e04bA6918C333Bc26a7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPoolAddressesProvider": { @@ -17,6 +21,10 @@ "localhost": { "address": "0xAfC307938C1c0035942c141c31524504c89Aaa8B", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xa4bcDF64Cdd5451b6ac3743B414124A6299B65FF", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPoolAddressesProviderRegistry": { @@ -27,6 +35,10 @@ "localhost": { "address": "0x73DE1e0ab6A5C221258703bc546E0CAAcCc6EC87", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x5A0773Ff307Bf7C71a832dBB5312237fD3437f9F", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "FeeProvider": { @@ -54,6 +66,9 @@ }, "localhost": { "address": "0x65e0Cd5B8904A02f2e00BC6f58bf881998D54BDe" + }, + "coverage": { + "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" } }, "LendingPoolDataProvider": { @@ -67,6 +82,9 @@ }, "localhost": { "address": "0x5d12dDe3286D94E0d85F9D3B01B7099cfA0aBCf1" + }, + "coverage": { + "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" } }, "PriceOracle": { @@ -77,6 +95,10 @@ "localhost": { "address": "0xbeA90474c2F3C7c43bC7c36CaAf5272c927Af5a1", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x1750499D05Ed1674d822430FB960d5F6731fDf64", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MockAggregator": { @@ -87,6 +109,10 @@ "localhost": { "address": "0x19E42cA990cF697D3dda0e59131215C43bB6989F", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xEC1C93A9f6a9e18E97784c76aC52053587FcDB89", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "ChainlinkProxyPriceProvider": { @@ -97,6 +123,10 @@ "localhost": { "address": "0xE30c3983E51bC9d6baE3E9437710a1459e21e81F", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x7B6C3e5486D9e6959441ab554A889099eed76290", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingRateOracle": { @@ -107,6 +137,10 @@ "localhost": { "address": "0xDf69898e844197a24C658CcF9fD53dF15948dc8b", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xD83D2773a7873ae2b5f8Fb92097e20a8C64F691E", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "DefaultReserveInterestRateStrategy": { @@ -117,6 +151,10 @@ "localhost": { "address": "0xBe6d8642382C241c9B4B50c89574DbF3f4181E7D", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x626FdE749F9d499d3777320CAf29484B624ab84a", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LendingPoolLiquidationManager": { @@ -170,6 +208,9 @@ }, "localhost": { "address": "0xAd49512dFBaD6fc13D67d3935283c0606812E962" + }, + "coverage": { + "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" } }, "WalletBalanceProvider": { @@ -180,6 +221,10 @@ "localhost": { "address": "0xA29C2A7e59aa49C71aF084695337E3AA5e820758", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xDf73fC454FA018051D4a1509e63D11530A59DE10", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "DAI": { @@ -190,6 +235,10 @@ "localhost": { "address": "0xbe66dC9DFEe580ED968403e35dF7b5159f873df8", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x7c2C195CD6D34B8F845992d380aADB2730bB9C6F", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LEND": { @@ -200,6 +249,10 @@ "localhost": { "address": "0x93AfC6Df4bB8F62F2493B19e577f8382c0BA9EBC", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x8858eeB3DfffA017D4BCE9801D340D36Cf895CCf", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "TUSD": { @@ -210,6 +263,10 @@ "localhost": { "address": "0x75Ded61646B5945BdDd0CD9a9Db7c8288DA6F810", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x0078371BDeDE8aAc7DeBfFf451B74c5EDB385Af7", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "BAT": { @@ -220,6 +277,10 @@ "localhost": { "address": "0xdE7c40e675bF1aA45c18cCbaEb9662B16b0Ddf7E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xf4e77E5Da47AC3125140c470c71cBca77B5c638c", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "USDC": { @@ -230,6 +291,10 @@ "localhost": { "address": "0xDFbeeed692AA81E7f86E72F7ACbEA2A1C4d63544", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x3619DbE27d7c1e7E91aA738697Ae7Bc5FC3eACA5", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "USDT": { @@ -240,6 +305,10 @@ "localhost": { "address": "0x5191aA68c7dB195181Dd2441dBE23A48EA24b040", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "SUSD": { @@ -250,6 +319,10 @@ "localhost": { "address": "0x8F9422aa37215c8b3D1Ea1674138107F84D68F26", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x1A1FEe7EeD918BD762173e4dc5EfDB8a78C924A8", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "ZRX": { @@ -260,6 +333,10 @@ "localhost": { "address": "0xa89E20284Bd638F31b0011D0fC754Fc9d2fa73e3", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MKR": { @@ -270,6 +347,10 @@ "localhost": { "address": "0xaA935993065F2dDB1d13623B1941C7AEE3A60F23", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xc4905364b78a742ccce7B890A89514061E47068D", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "WBTC": { @@ -280,6 +361,10 @@ "localhost": { "address": "0x35A2624888e207e4B3434E9a9E250bF6Ee68FeA3", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "LINK": { @@ -290,6 +375,10 @@ "localhost": { "address": "0x1f569c307949a908A4b8Ff7453a88Ca0b8D8df13", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x8B5B7a6055E54a36fF574bbE40cf2eA68d5554b3", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "KNC": { @@ -300,6 +389,10 @@ "localhost": { "address": "0x4301cb254CCc126B9eb9cbBE030C6FDA2FA16D4a", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MANA": { @@ -310,6 +403,10 @@ "localhost": { "address": "0x0766c9592a8686CAB0081b4f35449462c6e82F11", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x20Ce94F404343aD2752A2D01b43fa407db9E0D00", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "REP": { @@ -320,6 +417,10 @@ "localhost": { "address": "0xaF6D34adD35E1A565be4539E4d1069c48A49C953", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "SNX": { @@ -330,6 +431,10 @@ "localhost": { "address": "0x48bb3E35D2D6994374db457a6Bf61de2d9cC8E49", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x2D8553F9ddA85A9B3259F6Bf26911364B85556F5", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "BUSD": { @@ -340,6 +445,10 @@ "localhost": { "address": "0x1E59BA56B1F61c3Ee946D8c7e2994B4A9b0cA45C", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x52d3b94181f8654db2530b0fEe1B19173f519C52", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "USD": { @@ -350,6 +459,10 @@ "localhost": { "address": "0x53813198c75959DDB604462831d8989C29152164", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xd15468525c35BDBC1eD8F2e09A00F8a173437f2f", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_DAI_ETH": { @@ -360,6 +473,10 @@ "localhost": { "address": "0x0eD6115873ce6B807a03FE0df1f940387779b729", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x7e35Eaf7e8FBd7887ad538D4A38Df5BbD073814a", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_USDC_ETH": { @@ -370,6 +487,10 @@ "localhost": { "address": "0xFFfDa24e7E3d5F89a24278f53d6f0F81B3bE0d6B", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x5bcb88A0d20426e451332eE6C4324b0e663c50E0", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_SETH_ETH": { @@ -380,6 +501,10 @@ "localhost": { "address": "0x5889354f21A1C8D8D2f82669d778f6Dab778B519", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x3521eF8AaB0323004A6dD8b03CE890F4Ea3A13f5", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_LINK_ETH": { @@ -390,6 +515,10 @@ "localhost": { "address": "0x09F7bF33B3F8922268B34103af3a8AF83148C9B1", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x53369fd4680FfE3DfF39Fc6DDa9CfbfD43daeA2E", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_MKR_ETH": { @@ -400,6 +529,10 @@ "localhost": { "address": "0x8f3966F7d53Fd5f12b701C8835e1e32541613869", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xB00cC45B4a7d3e1FEE684cFc4417998A1c183e6d", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "UNI_LEND_ETH": { @@ -410,6 +543,10 @@ "localhost": { "address": "0x9Dc554694756dC303a087e04bA6918C333Bc26a7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "AaveProtocolTestHelpers": { @@ -418,6 +555,9 @@ }, "localhost": { "address": "0x9305d862ee95a899b83906Cd9CB666aC269E5f66" + }, + "coverage": { + "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" } }, "StableDebtToken": { @@ -428,6 +568,10 @@ "localhost": { "address": "0x02BB514187B830d6A2111197cd7D8cb60650B970", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xB660Fdd109a95718cB9d20E3A89EE6cE342aDcB6", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "VariableDebtToken": { @@ -438,6 +582,10 @@ "localhost": { "address": "0x6774Ce86Abf5EBB22E9F45b5f55daCbB4170aD7f", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x830bceA96E56DBC1F8578f75fBaC0AF16B32A07d", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "AToken": { @@ -448,6 +596,10 @@ "buidlerevm": { "address": "0xA0AB1cB92A4AF81f84dCd258155B5c25D247b54E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xA0AB1cB92A4AF81f84dCd258155B5c25D247b54E", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MockAToken": { @@ -458,6 +610,10 @@ "localhost": { "address": "0xFBdF1E93D0D88145e3CcA63bf8d513F83FB0903b", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x392E5355a0e88Bd394F717227c752670fb3a8020", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "WETH": { @@ -468,6 +624,10 @@ "localhost": { "address": "0xEcb928A3c079a1696Aa5244779eEc3dE1717fACd", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xf784709d2317D872237C4bC22f867d1BAe2913AB", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MockStableDebtToken": { @@ -478,6 +638,10 @@ "localhost": { "address": "0xE45fF4A0A8D0E9734C73874c034E03594E15ba28", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0x3b050AFb4ac4ACE646b31fF3639C1CD43aC31460", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MockVariableDebtToken": { @@ -488,11 +652,18 @@ "localhost": { "address": "0x5cCC6Abc4c9F7262B9485797a848Ec6CC28A11dF", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" + }, + "coverage": { + "address": "0xEBAB67ee3ef604D5c250A53b4b8fcbBC6ec3007C", + "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "MockSwapAdapter": { "buidlerevm": { "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" + }, + "coverage": { + "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" } } -} +} \ No newline at end of file From 570a81a1b24e4c183ba5ec3336622456aa353a44 Mon Sep 17 00:00:00 2001 From: The3D Date: Wed, 16 Sep 2020 16:44:27 +0200 Subject: [PATCH 23/45] Fixed aToken deployment function --- contracts/lendingpool/LendingPool.sol | 1 - contracts/tokenization/StableDebtToken.sol | 6 +++--- helpers/contracts-helpers.ts | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 7ea95be3..288de674 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -33,7 +33,6 @@ import {ILendingPool} from '../interfaces/ILendingPool.sol'; * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data * @author Aave **/ - contract LendingPool is VersionedInitializable, ILendingPool { using SafeMath for uint256; using WadRayMath for uint256; diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 75771d18..5b286e93 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -82,7 +82,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } struct MintLocalVars { - uint256 currentPrincipalSupply; + uint256 currentSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; @@ -110,9 +110,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 balanceIncrease ) = _calculateBalanceIncrease(user); - vars.currentPrincipalSupply = totalSupply(); + vars.currentSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; - vars.nextSupply = _totalSupply = _calcTotalSupply(vars.currentAvgStableRate).add(amount); + vars.nextSupply = vars.currentSupply.add(amount); vars.amountInRay = amount.wadToRay(); diff --git a/helpers/contracts-helpers.ts b/helpers/contracts-helpers.ts index 3c3a66bb..e871f469 100644 --- a/helpers/contracts-helpers.ts +++ b/helpers/contracts-helpers.ts @@ -299,7 +299,7 @@ export const deployGenericAToken = async ([ const token = await deployContract(eContractid.AToken, [ poolAddress, underlyingAssetAddress, - ZERO_ADDRESS, + reserveTreasuryAddress, name, symbol, incentivesController, From bcdef6fa7e39e7dd6fa2111dbf8ba89c00faca6d Mon Sep 17 00:00:00 2001 From: The3D Date: Wed, 16 Sep 2020 20:00:13 +0200 Subject: [PATCH 24/45] Added change to the stabledebttoken --- contracts/tokenization/StableDebtToken.sol | 11 +++++++---- .../tokenization/interfaces/IStableDebtToken.sol | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 5b286e93..610b2ae8 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -110,7 +110,8 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 balanceIncrease ) = _calculateBalanceIncrease(user); - vars.currentSupply = totalSupply(); + //accrueing the interest accumulation to the stored total supply and caching it + vars.currentSupply = _totalSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = vars.currentSupply.add(amount); @@ -125,12 +126,13 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { require(vars.newStableRate < (1 << 128), 'Debt token: stable rate overflow'); _usersData[user] = vars.newStableRate; + //updating the user and supply timestamp //solium-disable-next-line _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); //calculates the updated average stable rate _avgStableRate = vars.currentAvgStableRate - .rayMul(vars.currentPrincipalSupply.wadToRay()) + .rayMul(vars.currentSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); @@ -224,8 +226,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ); } - function getPrincipalSupplyAndAvgRate() public override view returns (uint256, uint256) { - return (super.totalSupply(), _avgStableRate); + function getSupplyData() public override view returns (uint256, uint256, uint256) { + uint256 avgRate = _avgStableRate; + return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate); } function getTotalSupplyAndAvgRate() public override view returns (uint256, uint256) { diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 46324e88..0e75bae4 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -86,9 +86,9 @@ interface IStableDebtToken { function getUserLastUpdated(address user) external view returns (uint40); /** - * @dev returns the principal total supply and the average stable rate + * @dev returns the principal, the total supply and the average stable rate **/ - function getPrincipalSupplyAndAvgRate() external view returns (uint256, uint256); + function getSupplyData() external view returns (uint256, uint256, uint256); /** * @dev returns the timestamp of the last update of the total supply From 7986a4704b98b3fa0f63fefc8f2fce01feb48426 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 10:53:55 +0200 Subject: [PATCH 25/45] Fixed mintToTreasury function --- contracts/libraries/logic/ReserveLogic.sol | 102 ++++++++++++------ contracts/tokenization/StableDebtToken.sol | 23 ++-- .../interfaces/IVariableDebtToken.sol | 2 +- test/helpers/utils/calculations.ts | 3 +- 4 files changed, 85 insertions(+), 45 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index aed82e45..ecd96954 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -150,12 +150,28 @@ library ReserveLogic { function updateState(ReserveData storage reserve) internal { address stableDebtToken = reserve.stableDebtTokenAddress; address variableDebtToken = reserve.variableDebtTokenAddress; - uint256 variableBorrowIndex = reserve.variableBorrowIndex; - uint256 liquidityIndex = reserve.liquidityIndex; + uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; + uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 timestamp = reserve.lastUpdateTimestamp; - _mintToTreasury(reserve, stableDebtToken, variableDebtToken, liquidityIndex, variableBorrowIndex, timestamp); - _updateIndexes(reserve, variableDebtToken, liquidityIndex, variableBorrowIndex, timestamp); + (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( + reserve, + variableDebtToken, + previousLiquidityIndex, + previousVariableBorrowIndex, + timestamp + ); + + _mintToTreasury( + reserve, + stableDebtToken, + variableDebtToken, + previousLiquidityIndex, + previousVariableBorrowIndex, + newLiquidityIndex, + newVariableBorrowIndex, + timestamp + ); } /** @@ -212,7 +228,7 @@ library ReserveLogic { struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; - uint256 totalStableDebt; + uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; @@ -273,14 +289,15 @@ library ReserveLogic { } struct MintToTreasuryLocalVars { - uint256 currentTotalDebt; + uint256 currentStableDebt; uint256 principalStableDebt; - uint256 avgStableRate; + uint256 previousStableDebt; + uint256 currentVariableDebt; uint256 scaledVariableDebt; + uint256 previousVariableDebt; + uint256 avgStableRate; uint256 cumulatedStableInterest; - uint256 variableDebtOnLastUpdate; - uint256 stableDebtOnLastUpdate; - uint256 totalInterestAccrued; + uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; } @@ -289,40 +306,53 @@ library ReserveLogic { ReserveData storage reserve, address stableDebtToken, address variableDebtToken, - uint256 liquidityIndex, - uint256 variableBorrowIndex, - uint40 lastUpdateTimestamp + uint256 previousLiquidityIndex, + uint256 previousVariableBorrowIndex, + uint256 newLiquidityIndex, + uint256 newVariableBorrowIndex, + uint40 previousTimestamp ) internal { - MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); - if(vars.reserveFactor == 0){ + if (vars.reserveFactor == 0) { return; } - vars.currentTotalDebt = IERC20(variableDebtToken).totalSupply().add(IERC20(stableDebtToken).totalSupply()); - - (vars.principalStableDebt, vars.avgStableRate) = IStableDebtToken(stableDebtToken) - .getPrincipalSupplyAndAvgRate(); - + //fetching the last scaled total variable debt vars.scaledVariableDebt = IVariableDebtToken(variableDebtToken).scaledTotalSupply(); + //fetching the principal, total stable debt and the avg stable rate + (vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate) = IStableDebtToken( + stableDebtToken + ) + .getSupplyData(); + + //calculate the last principal variable debt + vars.previousVariableDebt = vars.scaledVariableDebt.rayMul(previousVariableBorrowIndex); + + //calculate the new total supply after accumulation of the index + vars.currentVariableDebt = vars.scaledVariableDebt.rayMul(newVariableBorrowIndex); + + //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, - lastUpdateTimestamp + previousTimestamp ); - vars.variableDebtOnLastUpdate = vars.scaledVariableDebt.rayMul(variableBorrowIndex); - vars.stableDebtOnLastUpdate = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); + vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); - vars.totalInterestAccrued =vars.currentTotalDebt.sub(vars.variableDebtOnLastUpdate.add(vars.stableDebtOnLastUpdate)); + //debt accrued is the sum of the current debt minus the sum of the debt at the last update + vars.totalDebtAccrued = vars + .currentVariableDebt + .add(vars.currentStableDebt) + .sub(vars.previousVariableDebt) + .sub(vars.previousStableDebt); - vars.amountToMint = vars.totalInterestAccrued.percentMul(vars.reserveFactor); - - IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, liquidityIndex); + vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); + IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } function _updateIndexes( @@ -331,19 +361,22 @@ library ReserveLogic { uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp - ) internal { + ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; + uint256 newLiquidityIndex = liquidityIndex; + uint256 newVariableBorrowIndex = variableBorrowIndex; + //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( currentLiquidityRate, lastUpdateTimestamp ); - uint256 index = cumulatedLiquidityInterest.rayMul(liquidityIndex); - require(index < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); + newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); + require(newLiquidityIndex < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); - reserve.liquidityIndex = uint128(index); + reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating @@ -352,13 +385,14 @@ library ReserveLogic { reserve.currentVariableBorrowRate, lastUpdateTimestamp ); - index = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); - require(index < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); - reserve.variableBorrowIndex = uint128(index); + newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); + require(newVariableBorrowIndex < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); + reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); + return (newLiquidityIndex, newVariableBorrowIndex); } } diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 610b2ae8..5c31e0cf 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -111,9 +111,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ) = _calculateBalanceIncrease(user); //accrueing the interest accumulation to the stored total supply and caching it - vars.currentSupply = _totalSupply = totalSupply(); + vars.currentSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; - vars.nextSupply = vars.currentSupply.add(amount); + vars.nextSupply = _totalSupply = vars.currentSupply.add(amount); vars.amountInRay = amount.wadToRay(); @@ -163,25 +163,32 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 balanceIncrease ) = _calculateBalanceIncrease(user); - uint256 supplyBeforeBurn = totalSupply().add(balanceIncrease); - uint256 supplyAfterBurn = supplyBeforeBurn.sub(amount); + + uint256 currentSupply = totalSupply(); + uint256 currentAvgStableRate = _avgStableRate; + - if (supplyAfterBurn == 0) { + if (currentSupply <= amount) { _avgStableRate = 0; + _totalSupply = 0; } else { + uint256 nextSupply = _totalSupply = currentSupply.sub(amount); _avgStableRate = _avgStableRate - .rayMul(supplyBeforeBurn.wadToRay()) + .rayMul(currentSupply.wadToRay()) .sub(_usersData[user].rayMul(amount.wadToRay())) - .rayDiv(supplyAfterBurn.wadToRay()); + .rayDiv(nextSupply.wadToRay()); } if (amount == currentBalance) { _usersData[user] = 0; _timestamps[user] = 0; + } else { //solium-disable-next-line - _totalSupplyTimestamp = _timestamps[user] = uint40(block.timestamp); + _timestamps[user] = uint40(block.timestamp); } + //solium-disable-next-line + _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { _mint(user, balanceIncrease.sub(amount)); diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index 320d0f5a..0b680f51 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -58,6 +58,6 @@ interface IVariableDebtToken { * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) * @return the scaled total supply **/ - function scaledTotalSupply() external view returns(uint256); + function scaledTotalSupply() external view returns(uint256); } diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 1d0fa82b..fc98ccd4 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -296,8 +296,7 @@ export const calcExpectedReserveDataAfterBorrow = ( if (borrowRateMode == RateMode.Stable) { - expectedReserveData. - const debtAccrued = userStableDebt.minus(userDataBeforeAction.principalStableDebt); + //if the borrow rate mode expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); From 5b38bb144b3025fe6fcc9f25fe23e00e5390db87 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 11:52:10 +0200 Subject: [PATCH 26/45] Updated borrow calculations on scenarios --- test/helpers/utils/calculations.ts | 115 ++++++++++++++++++----------- test/scenario.spec.ts | 2 +- 2 files changed, 74 insertions(+), 43 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index fc98ccd4..f8ccc4ce 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -185,7 +185,6 @@ export const calcExpectedReserveDataAfterDeposit = ( expectedReserveData.variableBorrowIndex ); - expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; @@ -205,7 +204,7 @@ export const calcExpectedReserveDataAfterDeposit = ( expectedReserveData.liquidityRate = rates[0]; expectedReserveData.stableBorrowRate = rates[1]; expectedReserveData.variableBorrowRate = rates[2]; - + return expectedReserveData; }; @@ -246,8 +245,14 @@ export const calcExpectedReserveDataAfterWithdraw = ( txTimestamp ); - expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt(reserveDataBeforeAction, txTimestamp); - expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt(reserveDataBeforeAction, expectedReserveData.variableBorrowIndex); + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( + reserveDataBeforeAction, + expectedReserveData.variableBorrowIndex + ); expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; @@ -295,60 +300,85 @@ export const calcExpectedReserveDataAfterBorrow = ( ); if (borrowRateMode == RateMode.Stable) { + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); - //if the borrow rate mode - - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - - + const totalStableDebtUntilTx = calcExpectedTotalStableDebt( + reserveDataBeforeAction, + txTimestamp + ); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), + totalStableDebtUntilTx, amountBorrowedBN, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - } else { - const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( - reserveDataBeforeAction.variableBorrowIndex + + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( + { + ...reserveDataBeforeAction, + principalStableDebt: totalStableDebtUntilTx.plus(amountBorrowedBN), + averageStableBorrowRate: expectedReserveData.averageStableBorrowRate, + }, + currentTimestamp ); - const debtAccrued = userVariableDebt.minus(variableDebtBefore); - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt - .plus(amountBorrowedBN) - .plus(debtAccrued); - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; - expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; + expectedReserveData.totalLiquidity = reserveDataBeforeAction.availableLiquidity + .minus(amountBorrowedBN) + .plus(expectedReserveData.totalVariableDebt) + .plus(expectedReserveData.totalStableDebt); + } else { + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; + expectedReserveData.totalStableDebt = calcExpectedStableDebtTokenBalance( + userDataBeforeAction, + currentTimestamp + ); + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( + amountBorrowedBN.rayDiv(expectedReserveData.variableBorrowIndex) + ); + const totalVariableDebtAfterTx = reserveDataBeforeAction.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); + + const rates = calcExpectedInterestRates( + reserveDataBeforeAction.symbol, + reserveDataBeforeAction.marketStableRate, + expectedReserveData.utilizationRate, + expectedReserveData.totalStableDebt, + totalVariableDebtAfterTx, + expectedReserveData.averageStableBorrowRate + ); + + expectedReserveData.liquidityRate = rates[0]; + + expectedReserveData.stableBorrowRate = rates[1]; + + expectedReserveData.variableBorrowRate = rates[2]; + + expectedReserveData.lastUpdateTimestamp = txTimestamp; + + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + calcExpectedReserveNormalizedDebt(expectedReserveData, currentTimestamp) + ); } expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity.minus( amountBorrowedBN ); + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(expectedReserveData.totalVariableDebt); + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); - const rates = calcExpectedInterestRates( - reserveDataBeforeAction.symbol, - reserveDataBeforeAction.marketStableRate, - expectedReserveData.utilizationRate, - expectedReserveData.totalStableDebt, - expectedReserveData.totalVariableDebt, - expectedReserveData.averageStableBorrowRate - ); - expectedReserveData.liquidityRate = rates[0]; - - expectedReserveData.stableBorrowRate = rates[1]; - - expectedReserveData.variableBorrowRate = rates[2]; - - expectedReserveData.lastUpdateTimestamp = txTimestamp; - return expectedReserveData; }; @@ -1229,7 +1259,6 @@ const calcExpectedVariableBorrowIndex = (reserveData: ReserveData, timestamp: Bi }; const calcExpectedTotalStableDebt = (reserveData: ReserveData, timestamp: BigNumber) => { - const cumulatedInterest = calcCompoundedInterest( reserveData.averageStableBorrowRate, timestamp, @@ -1237,9 +1266,11 @@ const calcExpectedTotalStableDebt = (reserveData: ReserveData, timestamp: BigNum ); return cumulatedInterest.rayMul(reserveData.principalStableDebt); -} - -const calcExpectedTotalVariableDebt = (reserveData: ReserveData, expectedVariableDebtIndex: BigNumber) => { +}; +const calcExpectedTotalVariableDebt = ( + reserveData: ReserveData, + expectedVariableDebtIndex: BigNumber +) => { return reserveData.scaledVariableDebt.rayMul(expectedVariableDebtIndex); -} +}; diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 98e0c164..17830d1c 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['borrow-repay-variable.json']; +const selectedScenarios: string[] = ['deposit.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From bfe0657b1aa05d6a250d2c65cca794c2e827297e Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 16:37:51 +0200 Subject: [PATCH 27/45] Updated code to fix deposit and withdraw tests --- contracts/lendingpool/LendingPool.sol | 2 + .../lendingpool/LendingPoolConfigurator.sol | 2 +- .../configuration/ReserveConfiguration.sol | 3 +- contracts/libraries/logic/ReserveLogic.sol | 4 +- contracts/tokenization/StableDebtToken.sol | 51 ++-- test/configurator.spec.ts | 4 +- test/helpers/actions.ts | 13 + test/helpers/utils/calculations.ts | 226 +++++++++++------- test/helpers/utils/helpers.ts | 2 +- test/scenario.spec.ts | 2 +- 10 files changed, 196 insertions(+), 113 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index 275843a7..9fd5ce71 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -27,6 +27,7 @@ import {LendingPoolCollateralManager} from './LendingPoolCollateralManager.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; +import "@nomiclabs/buidler/console.sol"; /** * @title LendingPool contract @@ -702,6 +703,7 @@ contract LendingPool is VersionedInitializable, ILendingPool { ) { ReserveLogic.ReserveData memory reserve = _reserves[asset]; + return ( IERC20(asset).balanceOf(reserve.aTokenAddress), IERC20(reserve.stableDebtTokenAddress).totalSupply(), diff --git a/contracts/lendingpool/LendingPoolConfigurator.sol b/contracts/lendingpool/LendingPoolConfigurator.sol index 0b5b472f..6bedff76 100644 --- a/contracts/lendingpool/LendingPoolConfigurator.sol +++ b/contracts/lendingpool/LendingPoolConfigurator.sol @@ -484,7 +484,7 @@ contract LendingPoolConfigurator is VersionedInitializable { * @param asset the address of the reserve * @param reserveFactor the new reserve factor of the reserve **/ - function setReserveFactor(address asset, uint256 reserveFactor) external onlyLendingPoolManager { + function setReserveFactor(address asset, uint256 reserveFactor) external onlyAaveAdmin { ReserveConfiguration.Map memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); diff --git a/contracts/libraries/configuration/ReserveConfiguration.sol b/contracts/libraries/configuration/ReserveConfiguration.sol index 10471f6e..ed4df31e 100644 --- a/contracts/libraries/configuration/ReserveConfiguration.sol +++ b/contracts/libraries/configuration/ReserveConfiguration.sol @@ -42,8 +42,7 @@ library ReserveConfiguration { * @param self the reserve configuration * @param reserveFactor the reserve factor **/ - function setReserveFactor(ReserveConfiguration.Map memory self, uint256 reserveFactor) internal view { - console.log("Setting reserve factor to %s", reserveFactor); + function setReserveFactor(ReserveConfiguration.Map memory self, uint256 reserveFactor) internal pure { self.data = (self.data & RESERVE_FACTOR_MASK) | reserveFactor << 64; } diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index ecd96954..e5eac57a 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -147,7 +147,7 @@ library ReserveLogic { * a formal specification. * @param reserve the reserve object **/ - function updateState(ReserveData storage reserve) internal { + function updateState(ReserveData storage reserve) external { address stableDebtToken = reserve.stableDebtTokenAddress; address variableDebtToken = reserve.variableDebtTokenAddress; uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; @@ -166,7 +166,6 @@ library ReserveLogic { reserve, stableDebtToken, variableDebtToken, - previousLiquidityIndex, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, @@ -306,7 +305,6 @@ library ReserveLogic { ReserveData storage reserve, address stableDebtToken, address variableDebtToken, - uint256 previousLiquidityIndex, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 5c31e0cf..6401bfc9 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -8,6 +8,7 @@ import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from './interfaces/IStableDebtToken.sol'; +import "@nomiclabs/buidler/console.sol"; /** * @title contract StableDebtToken @@ -82,7 +83,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } struct MintLocalVars { - uint256 currentSupply; + uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; @@ -111,9 +112,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ) = _calculateBalanceIncrease(user); //accrueing the interest accumulation to the stored total supply and caching it - vars.currentSupply = totalSupply(); + vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; - vars.nextSupply = _totalSupply = vars.currentSupply.add(amount); + vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); @@ -132,11 +133,11 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { //calculates the updated average stable rate _avgStableRate = vars.currentAvgStableRate - .rayMul(vars.currentSupply.wadToRay()) + .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); - _mint(user, amount.add(balanceIncrease)); + _mint(user, amount.add(balanceIncrease), vars.previousSupply); // transfer event to track balances emit Transfer(address(0), user, amount); @@ -164,17 +165,15 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ) = _calculateBalanceIncrease(user); - uint256 currentSupply = totalSupply(); - uint256 currentAvgStableRate = _avgStableRate; - + uint256 previousSupply = totalSupply(); - if (currentSupply <= amount) { + if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { - uint256 nextSupply = _totalSupply = currentSupply.sub(amount); + uint256 nextSupply = _totalSupply = previousSupply.sub(amount); _avgStableRate = _avgStableRate - .rayMul(currentSupply.wadToRay()) + .rayMul(previousSupply.wadToRay()) .sub(_usersData[user].rayMul(amount.wadToRay())) .rayDiv(nextSupply.wadToRay()); } @@ -191,9 +190,9 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { - _mint(user, balanceIncrease.sub(amount)); + _mint(user, balanceIncrease.sub(amount), previousSupply); } else { - _burn(user, amount.sub(balanceIncrease)); + _burn(user, amount.sub(balanceIncrease), previousSupply); } // transfer event to track balances @@ -244,7 +243,7 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } function totalSupply() public override view returns (uint256) { - _calcTotalSupply(_avgStableRate); + return _calcTotalSupply(_avgStableRate); } function getTotalSupplyLastUpdated() public override view returns(uint40) { @@ -261,13 +260,37 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { function _calcTotalSupply(uint256 avgRate) internal view returns(uint256) { uint256 principalSupply = super.totalSupply(); + if (principalSupply == 0) { return 0; } + uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest( avgRate, _totalSupplyTimestamp ); + return principalSupply.rayMul(cumulatedInterest); } + + function _mint(address account, uint256 amount, uint256 oldTotalSupply) internal { + + uint256 oldAccountBalance = _balances[account]; + _balances[account] = oldAccountBalance.add(amount); + + if (address(_incentivesController) != address(0)) { + _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); + } + } + + function _burn(address account, uint256 amount, uint256 oldTotalSupply) internal { + + + uint256 oldAccountBalance = _balances[account]; + _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); + + if (address(_incentivesController) != address(0)) { + _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); + } + } } diff --git a/test/configurator.spec.ts b/test/configurator.spec.ts index 66f7ef82..0fa3289c 100644 --- a/test/configurator.spec.ts +++ b/test/configurator.spec.ts @@ -192,8 +192,8 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => { const {configurator, users, weth} = testEnv; await expect( configurator.connect(users[2].signer).setReserveFactor(weth.address, '2000'), - CALLER_NOT_LENDING_POOL_MANAGER - ).to.be.revertedWith(CALLER_NOT_LENDING_POOL_MANAGER); + CALLER_NOT_AAVE_ADMIN + ).to.be.revertedWith(CALLER_NOT_AAVE_ADMIN); }); diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 3e60955d..0d1d2775 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -375,6 +375,19 @@ export const borrow = async ( txCost ); + console.log("Expected available liquidity: ", expectedReserveData.availableLiquidity.toFixed()); + console.log("Expected total liquidity: ", expectedReserveData.totalLiquidity.toFixed()); + console.log("Expected total debt stable: ", expectedReserveData.totalStableDebt.toFixed()); + console.log("Expected total debt variable: ", expectedReserveData.totalVariableDebt.toFixed()); + console.log("Expected utilization rate: ", expectedReserveData.utilizationRate.toFixed()); + + console.log("actual available liquidity: ", reserveDataAfter.availableLiquidity.toFixed()); + console.log("actual total liquidity: ", reserveDataAfter.totalLiquidity.toFixed()); + console.log("actual total debt stable: ", reserveDataAfter.totalStableDebt.toFixed()); + console.log("actual total debt variable: ", reserveDataAfter.totalVariableDebt.toFixed()); + console.log("actual utilization rate: ", reserveDataAfter.utilizationRate.toFixed()); + console.log("User debt: ", userDataAfter.currentStableDebt.toFixed(0)); + expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index f8ccc4ce..d394a8ff 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -31,7 +31,9 @@ export const calcExpectedUserDataAfterDeposit = ( const expectedUserData = {}; expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, txTimestamp ); @@ -71,7 +73,9 @@ export const calcExpectedUserDataAfterDeposit = ( expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(amountDeposited); expectedUserData.currentStableDebt = expectedUserData.principalStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, txTimestamp ); @@ -118,7 +122,9 @@ export const calcExpectedUserDataAfterWithdraw = ( expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, txTimestamp ); @@ -294,13 +300,21 @@ export const calcExpectedReserveDataAfterBorrow = ( reserveDataBeforeAction, txTimestamp ); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( reserveDataBeforeAction, txTimestamp ); + expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity.minus( + amountBorrowedBN + ); + + expectedReserveData.lastUpdateTimestamp = txTimestamp; + if (borrowRateMode == RateMode.Stable) { expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.scaledVariableDebt.rayMul( expectedReserveData.variableBorrowIndex ); @@ -317,32 +331,68 @@ export const calcExpectedReserveDataAfterBorrow = ( reserveDataBeforeAction.stableBorrowRate ); + expectedReserveData.principalStableDebt = totalStableDebtUntilTx.plus(amountBorrowedBN); + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( { ...reserveDataBeforeAction, - principalStableDebt: totalStableDebtUntilTx.plus(amountBorrowedBN), + principalStableDebt: expectedReserveData.principalStableDebt, averageStableBorrowRate: expectedReserveData.averageStableBorrowRate, + lastUpdateTimestamp: txTimestamp, }, currentTimestamp ); - expectedReserveData.totalLiquidity = reserveDataBeforeAction.availableLiquidity - .minus(amountBorrowedBN) + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity .plus(expectedReserveData.totalVariableDebt) .plus(expectedReserveData.totalStableDebt); + + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, + expectedReserveData.totalLiquidity + ); + + const rates = calcExpectedInterestRates( + reserveDataBeforeAction.symbol, + reserveDataBeforeAction.marketStableRate, + expectedReserveData.utilizationRate, + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, + expectedReserveData.averageStableBorrowRate + ); + + expectedReserveData.liquidityRate = rates[0]; + + expectedReserveData.stableBorrowRate = rates[1]; + + expectedReserveData.variableBorrowRate = rates[2]; } else { expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; + expectedReserveData.totalStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, currentTimestamp ); + expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( amountBorrowedBN.rayDiv(expectedReserveData.variableBorrowIndex) ); - const totalVariableDebtAfterTx = reserveDataBeforeAction.scaledVariableDebt.rayMul( + const totalVariableDebtAfterTx = expectedReserveData.scaledVariableDebt.rayMul( expectedReserveData.variableBorrowIndex ); + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( + expectedReserveData.totalStableDebt, + totalVariableDebtAfterTx, + expectedReserveData.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(totalVariableDebtAfterTx) + ); + const rates = calcExpectedInterestRates( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, @@ -358,27 +408,15 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.lastUpdateTimestamp = txTimestamp; - expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( calcExpectedReserveNormalizedDebt(expectedReserveData, currentTimestamp) ); } - expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity.minus( - amountBorrowedBN - ); - expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity .plus(expectedReserveData.totalStableDebt) .plus(expectedReserveData.totalVariableDebt); - expectedReserveData.utilizationRate = calcExpectedUtilizationRate( - expectedReserveData.totalStableDebt, - expectedReserveData.totalVariableDebt, - expectedReserveData.totalLiquidity - ); - return expectedReserveData; }; @@ -396,7 +434,12 @@ export const calcExpectedReserveDataAfterRepay = ( let amountRepaidBN = new BigNumber(amountRepaid); - const userStableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); + const userStableDebt = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + txTimestamp + ); const userVariableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, @@ -500,29 +543,50 @@ export const calcExpectedUserDataAfterBorrow = ( ): UserReserveData => { const expectedUserData = {}; - const currentStableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); - - const currentVariableDebt = calcExpectedVariableDebtTokenBalance( - reserveDataBeforeAction, - userDataBeforeAction, - txTimestamp - ); + const amountBorrowedBN = new BigNumber(amountBorrowed); if (interestRateMode == RateMode.Stable) { - const debtAccrued = currentStableDebt.minus(userDataBeforeAction.principalStableDebt); + const stableDebtUntilTx = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + txTimestamp + ); - expectedUserData.principalStableDebt = currentStableDebt.plus(amountBorrowed); - expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; + expectedUserData.principalStableDebt = stableDebtUntilTx.plus(amountBorrowed); + expectedUserData.stableRateLastUpdated = txTimestamp; expectedUserData.stableBorrowRate = calcExpectedUserStableRate( - userDataBeforeAction.principalStableDebt.plus(debtAccrued), + stableDebtUntilTx, userDataBeforeAction.stableBorrowRate, - new BigNumber(amountBorrowed), + amountBorrowedBN, reserveDataBeforeAction.stableBorrowRate ); - expectedUserData.stableRateLastUpdated = txTimestamp; + + console.log("Principal stable debt: ",expectedUserData.principalStableDebt.toFixed() ); + console.log("stable borrow rate: ",expectedUserData.stableBorrowRate.toFixed() ); + + expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( + expectedUserData.principalStableDebt, + expectedUserData.stableBorrowRate, + txTimestamp, + currentTimestamp + ); + + console.log("expected stable debt: ", expectedUserData.currentStableDebt); + + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; + + expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( + expectedDataAfterAction, + expectedUserData, + currentTimestamp + ); } else { - expectedUserData.principalVariableDebt = currentVariableDebt.plus(amountBorrowed); + expectedUserData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( + amountBorrowedBN.rayDiv(expectedDataAfterAction.variableBorrowIndex) + ); + expectedUserData.principalStableDebt = userDataBeforeAction.principalStableDebt; expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; @@ -530,42 +594,6 @@ export const calcExpectedUserDataAfterBorrow = ( expectedUserData.stableRateLastUpdated = userDataBeforeAction.stableRateLastUpdated; } - expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( - { - ...userDataBeforeAction, - currentStableDebt: expectedUserData.principalStableDebt, - principalStableDebt: expectedUserData.principalStableDebt, - stableBorrowRate: expectedUserData.stableBorrowRate, - stableRateLastUpdated: expectedUserData.stableRateLastUpdated, - }, - currentTimestamp - ); - - expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( - expectedDataAfterAction, - { - ...userDataBeforeAction, - currentVariableDebt: expectedUserData.scaledVariableDebt.rayMul( - reserveDataBeforeAction.variableBorrowIndex - ), - scaledVariableDebt: expectedUserData.scaledVariableDebt, - variableBorrowIndex: - interestRateMode == RateMode.Variable - ? expectedDataAfterAction.variableBorrowIndex - : userDataBeforeAction.variableBorrowIndex, - }, - currentTimestamp - ); - - if (expectedUserData.scaledVariableDebt.eq(0)) { - expectedUserData.variableBorrowIndex = new BigNumber(0); - } else { - expectedUserData.variableBorrowIndex = - interestRateMode == RateMode.Variable - ? expectedDataAfterAction.variableBorrowIndex - : userDataBeforeAction.variableBorrowIndex; - } - expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; expectedUserData.usageAsCollateralEnabled = userDataBeforeAction.usageAsCollateralEnabled; @@ -575,6 +603,7 @@ export const calcExpectedUserDataAfterBorrow = ( userDataBeforeAction, currentTimestamp ); + expectedUserData.scaledATokenBalance = userDataBeforeAction.scaledATokenBalance; expectedUserData.walletBalance = userDataBeforeAction.walletBalance.plus(amountBorrowed); @@ -603,7 +632,9 @@ export const calcExpectedUserDataAfterRepay = ( ); const stableBorrowBalance = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, currentTimestamp ); @@ -700,7 +731,12 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( txTimestamp ); - const stableDebt = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); + const stableDebt = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + txTimestamp + ); expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity; @@ -793,7 +829,12 @@ export const calcExpectedUserDataAfterSwapRateMode = ( txTimestamp ); - const stableBorrowBalance = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); + const stableBorrowBalance = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + txTimestamp + ); expectedUserData.currentATokenBalance = calcExpectedATokenBalance( reserveDataBeforeAction, @@ -848,7 +889,12 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( expectedReserveData.address = reserveDataBeforeAction.address; - const stableBorrowBalance = calcExpectedStableDebtTokenBalance(userDataBeforeAction, txTimestamp); + const stableBorrowBalance = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + txTimestamp + ); const debtAccrued = stableBorrowBalance.minus(userDataBeforeAction.principalStableDebt); @@ -924,7 +970,9 @@ export const calcExpectedUserDataAfterStableRateRebalance = ( txTimestamp ); expectedUserData.currentStableDebt = expectedUserData.principalStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction, + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, txTimestamp ); @@ -957,13 +1005,13 @@ const calcExpectedScaledATokenBalance = ( }; export const calcExpectedATokenBalance = ( - reserveDataBeforeAction: ReserveData, - userDataBeforeAction: UserReserveData, + reserveData: ReserveData, + userData: UserReserveData, currentTimestamp: BigNumber ) => { - const index = calcExpectedReserveNormalizedIncome(reserveDataBeforeAction, currentTimestamp); + const index = calcExpectedReserveNormalizedIncome(reserveData, currentTimestamp); - const {scaledATokenBalance: scaledBalanceBeforeAction} = userDataBeforeAction; + const {scaledATokenBalance: scaledBalanceBeforeAction} = userData; return scaledBalanceBeforeAction.rayMul(index); }; @@ -998,23 +1046,23 @@ const calcExpectedVariableDebtUserIndex = ( }; export const calcExpectedVariableDebtTokenBalance = ( - reserveDataBeforeAction: ReserveData, - userDataBeforeAction: UserReserveData, + reserveData: ReserveData, + userData: UserReserveData, currentTimestamp: BigNumber ) => { - const debt = calcExpectedReserveNormalizedDebt(reserveDataBeforeAction, currentTimestamp); + const normalizedDebt = calcExpectedReserveNormalizedDebt(reserveData, currentTimestamp); - const {scaledVariableDebt} = userDataBeforeAction; + const {scaledVariableDebt} = userData; - return scaledVariableDebt.rayMul(debt); + return scaledVariableDebt.rayMul(normalizedDebt); }; export const calcExpectedStableDebtTokenBalance = ( - userDataBeforeAction: UserReserveData, + principalStableDebt: BigNumber, + stableBorrowRate: BigNumber, + stableRateLastUpdated: BigNumber, currentTimestamp: BigNumber ) => { - const {principalStableDebt, stableBorrowRate, stableRateLastUpdated} = userDataBeforeAction; - if ( stableBorrowRate.eq(0) || currentTimestamp.eq(stableRateLastUpdated) || @@ -1029,7 +1077,7 @@ export const calcExpectedStableDebtTokenBalance = ( stableRateLastUpdated ); - return principalStableDebt.wadToRay().rayMul(cumulatedInterest).rayToWad(); + return principalStableDebt.rayMul(cumulatedInterest); }; const calcLinearInterest = ( diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index 3f3a2ec8..b98ba688 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -24,7 +24,7 @@ export const getReserveData = async ( const stableDebtToken = await getStableDebtToken(tokenAddresses.stableDebtTokenAddress); const variableDebtToken = await getVariableDebtToken(tokenAddresses.variableDebtTokenAddress); - const [principalStableDebt] = await stableDebtToken.getPrincipalSupplyAndAvgRate(); + const [principalStableDebt] = await stableDebtToken.getSupplyData(); const scaledVariableDebt = await variableDebtToken.scaledTotalSupply(); diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 17830d1c..ee45a08f 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['deposit.json']; +const selectedScenarios: string[] = ['withdraw.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 6df8a7a6e0050de79aa4ca299cf196ced5f86ce4 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 16:38:15 +0200 Subject: [PATCH 28/45] Removed console.log --- test/helpers/utils/calculations.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index d394a8ff..7343e593 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -563,9 +563,6 @@ export const calcExpectedUserDataAfterBorrow = ( reserveDataBeforeAction.stableBorrowRate ); - console.log("Principal stable debt: ",expectedUserData.principalStableDebt.toFixed() ); - console.log("stable borrow rate: ",expectedUserData.stableBorrowRate.toFixed() ); - expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( expectedUserData.principalStableDebt, expectedUserData.stableBorrowRate, @@ -573,8 +570,6 @@ export const calcExpectedUserDataAfterBorrow = ( currentTimestamp ); - console.log("expected stable debt: ", expectedUserData.currentStableDebt); - expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( From 72e2102529b9c9659f36fc11221e1d769f824c83 Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 16:40:23 +0200 Subject: [PATCH 29/45] removed other console.log --- test/helpers/actions.ts | 13 ------------- test/scenario.spec.ts | 2 +- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 0d1d2775..3e60955d 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -375,19 +375,6 @@ export const borrow = async ( txCost ); - console.log("Expected available liquidity: ", expectedReserveData.availableLiquidity.toFixed()); - console.log("Expected total liquidity: ", expectedReserveData.totalLiquidity.toFixed()); - console.log("Expected total debt stable: ", expectedReserveData.totalStableDebt.toFixed()); - console.log("Expected total debt variable: ", expectedReserveData.totalVariableDebt.toFixed()); - console.log("Expected utilization rate: ", expectedReserveData.utilizationRate.toFixed()); - - console.log("actual available liquidity: ", reserveDataAfter.availableLiquidity.toFixed()); - console.log("actual total liquidity: ", reserveDataAfter.totalLiquidity.toFixed()); - console.log("actual total debt stable: ", reserveDataAfter.totalStableDebt.toFixed()); - console.log("actual total debt variable: ", reserveDataAfter.totalVariableDebt.toFixed()); - console.log("actual utilization rate: ", reserveDataAfter.utilizationRate.toFixed()); - console.log("User debt: ", userDataAfter.currentStableDebt.toFixed(0)); - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index ee45a08f..98e0c164 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['withdraw.json']; +const selectedScenarios: string[] = ['borrow-repay-variable.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 13f6c264b3b65f3e514c98b18343e24787447a0d Mon Sep 17 00:00:00 2001 From: The3D Date: Thu, 17 Sep 2020 19:05:22 +0200 Subject: [PATCH 30/45] Partially fixed repay tests --- buidler.config.ts | 2 +- deployed-contracts.json | 83 +++++----- .../flash-liquidation-with-collateral.spec.ts | 4 +- test/helpers/utils/calculations.ts | 145 +++++++++--------- test/liquidation-underlying.spec.ts | 4 +- test/repay-with-collateral.spec.ts | 4 +- test/scenario.spec.ts | 2 +- 7 files changed, 126 insertions(+), 118 deletions(-) diff --git a/buidler.config.ts b/buidler.config.ts index 47eba1e2..9db632a2 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -9,7 +9,7 @@ usePlugin('buidler-typechain'); usePlugin('solidity-coverage'); usePlugin('@nomiclabs/buidler-waffle'); usePlugin('@nomiclabs/buidler-etherscan'); -//usePlugin('buidler-gas-reporter'); +usePlugin('buidler-gas-reporter'); const DEFAULT_BLOCK_GAS_LIMIT = 10000000; const DEFAULT_GAS_PRICE = 10; const HARDFORK = 'istanbul'; diff --git a/deployed-contracts.json b/deployed-contracts.json index 00c4ef4f..b0a60439 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -5,7 +5,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x9Dc554694756dC303a087e04bA6918C333Bc26a7", + "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -15,7 +15,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xAfC307938C1c0035942c141c31524504c89Aaa8B", + "address": "0xa4bcDF64Cdd5451b6ac3743B414124A6299B65FF", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -25,7 +25,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x73DE1e0ab6A5C221258703bc546E0CAAcCc6EC87", + "address": "0x5A0773Ff307Bf7C71a832dBB5312237fD3437f9F", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -53,7 +53,7 @@ "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" }, "localhost": { - "address": "0x65e0Cd5B8904A02f2e00BC6f58bf881998D54BDe" + "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" } }, "LendingPoolDataProvider": { @@ -66,7 +66,7 @@ "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" }, "localhost": { - "address": "0x5d12dDe3286D94E0d85F9D3B01B7099cfA0aBCf1" + "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" } }, "PriceOracle": { @@ -75,7 +75,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xbeA90474c2F3C7c43bC7c36CaAf5272c927Af5a1", + "address": "0x1750499D05Ed1674d822430FB960d5F6731fDf64", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -85,7 +85,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x19E42cA990cF697D3dda0e59131215C43bB6989F", + "address": "0xEC1C93A9f6a9e18E97784c76aC52053587FcDB89", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -95,7 +95,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xE30c3983E51bC9d6baE3E9437710a1459e21e81F", + "address": "0x7B6C3e5486D9e6959441ab554A889099eed76290", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -105,7 +105,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xDf69898e844197a24C658CcF9fD53dF15948dc8b", + "address": "0xD83D2773a7873ae2b5f8Fb92097e20a8C64F691E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -115,7 +115,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xBe6d8642382C241c9B4B50c89574DbF3f4181E7D", + "address": "0x626FdE749F9d499d3777320CAf29484B624ab84a", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -169,7 +169,7 @@ "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" }, "localhost": { - "address": "0xAd49512dFBaD6fc13D67d3935283c0606812E962" + "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" } }, "WalletBalanceProvider": { @@ -178,7 +178,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xA29C2A7e59aa49C71aF084695337E3AA5e820758", + "address": "0xDf73fC454FA018051D4a1509e63D11530A59DE10", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -188,7 +188,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xbe66dC9DFEe580ED968403e35dF7b5159f873df8", + "address": "0x7c2C195CD6D34B8F845992d380aADB2730bB9C6F", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -198,7 +198,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x93AfC6Df4bB8F62F2493B19e577f8382c0BA9EBC", + "address": "0x8858eeB3DfffA017D4BCE9801D340D36Cf895CCf", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -208,7 +208,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x75Ded61646B5945BdDd0CD9a9Db7c8288DA6F810", + "address": "0x0078371BDeDE8aAc7DeBfFf451B74c5EDB385Af7", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -218,7 +218,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xdE7c40e675bF1aA45c18cCbaEb9662B16b0Ddf7E", + "address": "0xf4e77E5Da47AC3125140c470c71cBca77B5c638c", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -228,7 +228,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xDFbeeed692AA81E7f86E72F7ACbEA2A1C4d63544", + "address": "0x3619DbE27d7c1e7E91aA738697Ae7Bc5FC3eACA5", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -238,7 +238,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5191aA68c7dB195181Dd2441dBE23A48EA24b040", + "address": "0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -248,7 +248,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x8F9422aa37215c8b3D1Ea1674138107F84D68F26", + "address": "0x1A1FEe7EeD918BD762173e4dc5EfDB8a78C924A8", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -258,7 +258,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xa89E20284Bd638F31b0011D0fC754Fc9d2fa73e3", + "address": "0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -268,7 +268,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xaA935993065F2dDB1d13623B1941C7AEE3A60F23", + "address": "0xc4905364b78a742ccce7B890A89514061E47068D", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -278,7 +278,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x35A2624888e207e4B3434E9a9E250bF6Ee68FeA3", + "address": "0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -288,7 +288,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x1f569c307949a908A4b8Ff7453a88Ca0b8D8df13", + "address": "0x8B5B7a6055E54a36fF574bbE40cf2eA68d5554b3", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -298,7 +298,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x4301cb254CCc126B9eb9cbBE030C6FDA2FA16D4a", + "address": "0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -308,7 +308,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x0766c9592a8686CAB0081b4f35449462c6e82F11", + "address": "0x20Ce94F404343aD2752A2D01b43fa407db9E0D00", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -318,7 +318,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xaF6D34adD35E1A565be4539E4d1069c48A49C953", + "address": "0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -328,7 +328,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x48bb3E35D2D6994374db457a6Bf61de2d9cC8E49", + "address": "0x2D8553F9ddA85A9B3259F6Bf26911364B85556F5", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -338,7 +338,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x1E59BA56B1F61c3Ee946D8c7e2994B4A9b0cA45C", + "address": "0x52d3b94181f8654db2530b0fEe1B19173f519C52", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -348,7 +348,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x53813198c75959DDB604462831d8989C29152164", + "address": "0xd15468525c35BDBC1eD8F2e09A00F8a173437f2f", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -358,7 +358,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x0eD6115873ce6B807a03FE0df1f940387779b729", + "address": "0x7e35Eaf7e8FBd7887ad538D4A38Df5BbD073814a", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -368,7 +368,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xFFfDa24e7E3d5F89a24278f53d6f0F81B3bE0d6B", + "address": "0x5bcb88A0d20426e451332eE6C4324b0e663c50E0", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -378,7 +378,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5889354f21A1C8D8D2f82669d778f6Dab778B519", + "address": "0x3521eF8AaB0323004A6dD8b03CE890F4Ea3A13f5", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -388,7 +388,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x09F7bF33B3F8922268B34103af3a8AF83148C9B1", + "address": "0x53369fd4680FfE3DfF39Fc6DDa9CfbfD43daeA2E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -398,7 +398,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x8f3966F7d53Fd5f12b701C8835e1e32541613869", + "address": "0xB00cC45B4a7d3e1FEE684cFc4417998A1c183e6d", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -408,7 +408,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x9Dc554694756dC303a087e04bA6918C333Bc26a7", + "address": "0x58F132FBB86E21545A4Bace3C19f1C05d86d7A22", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -417,7 +417,7 @@ "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" }, "localhost": { - "address": "0x9305d862ee95a899b83906Cd9CB666aC269E5f66" + "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" } }, "StableDebtToken": { @@ -426,7 +426,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x02BB514187B830d6A2111197cd7D8cb60650B970", + "address": "0xB660Fdd109a95718cB9d20E3A89EE6cE342aDcB6", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -436,13 +436,13 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x6774Ce86Abf5EBB22E9F45b5f55daCbB4170aD7f", + "address": "0x830bceA96E56DBC1F8578f75fBaC0AF16B32A07d", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, "AToken": { "localhost": { - "address": "0x007C1a44e85bDa8F562F916685A9DC8BdC6542bF", + "address": "0xA0AB1cB92A4AF81f84dCd258155B5c25D247b54E", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "buidlerevm": { @@ -466,7 +466,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xEcb928A3c079a1696Aa5244779eEc3dE1717fACd", + "address": "0xf784709d2317D872237C4bC22f867d1BAe2913AB", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" } }, @@ -493,6 +493,9 @@ "MockSwapAdapter": { "buidlerevm": { "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" + }, + "localhost": { + "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" } } } \ No newline at end of file diff --git a/test/flash-liquidation-with-collateral.spec.ts b/test/flash-liquidation-with-collateral.spec.ts index 01a8fec0..7298cb9b 100644 --- a/test/flash-liquidation-with-collateral.spec.ts +++ b/test/flash-liquidation-with-collateral.spec.ts @@ -125,7 +125,9 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn ).minus(usdcUserDataBefore.currentVariableDebt); const expectedStableDebtIncrease = calcExpectedStableDebtTokenBalance( - usdcUserDataBefore, + usdcUserDataBefore.principalStableDebt, + usdcUserDataBefore.stableBorrowRate, + usdcUserDataBefore.stableRateLastUpdated, new BigNumber(repayWithCollateralTimestamp) ).minus(usdcUserDataBefore.currentStableDebt); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 7343e593..795dbaa3 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -319,19 +319,16 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.variableBorrowIndex ); - const totalStableDebtUntilTx = calcExpectedTotalStableDebt( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - totalStableDebtUntilTx, + reserveDataBeforeAction.totalStableDebt, amountBorrowedBN, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.principalStableDebt = totalStableDebtUntilTx.plus(amountBorrowedBN); + expectedReserveData.principalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( + amountBorrowedBN + ); expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( { @@ -385,7 +382,7 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.variableBorrowIndex ); - expectedReserveData.utilizationRate = calcExpectedUtilizationRate( + const utilizationRateAfterTx = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, totalVariableDebtAfterTx, expectedReserveData.availableLiquidity @@ -396,7 +393,7 @@ export const calcExpectedReserveDataAfterBorrow = ( const rates = calcExpectedInterestRates( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, - expectedReserveData.utilizationRate, + utilizationRateAfterTx, expectedReserveData.totalStableDebt, totalVariableDebtAfterTx, expectedReserveData.averageStableBorrowRate @@ -411,11 +408,17 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( calcExpectedReserveNormalizedDebt(expectedReserveData, currentTimestamp) ); - } - expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity - .plus(expectedReserveData.totalStableDebt) - .plus(expectedReserveData.totalVariableDebt); + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(expectedReserveData.totalVariableDebt); + + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( + expectedReserveData.totalStableDebt, + expectedReserveData.totalVariableDebt, + expectedReserveData.totalLiquidity + ); + } return expectedReserveData; }; @@ -447,7 +450,7 @@ export const calcExpectedReserveDataAfterRepay = ( txTimestamp ); - //if amount repaid = MAX_UINT_AMOUNT, user is repaying everything + //if amount repaid == MAX_UINT_AMOUNT, user is repaying everything if (amountRepaidBN.abs().eq(MAX_UINT_AMOUNT)) { if (borrowRateMode == RateMode.Stable) { amountRepaidBN = userStableDebt; @@ -456,36 +459,40 @@ export const calcExpectedReserveDataAfterRepay = ( } } + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( + reserveDataBeforeAction, + txTimestamp + ); + if (borrowRateMode == RateMode.Stable) { - const debtAccrued = userStableDebt.minus(userDataBeforeAction.principalStableDebt); - - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt - .minus(amountRepaidBN) - .plus(debtAccrued); + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.minus( + amountRepaidBN + ); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), + reserveDataBeforeAction.totalStableDebt, amountRepaidBN.negated(), userDataBeforeAction.stableBorrowRate ); + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; } else { - const variableDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( - reserveDataBeforeAction.variableBorrowIndex + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.minus( + amountRepaidBN.rayDiv(expectedReserveData.variableBorrowIndex) ); - const debtAccrued = userVariableDebt.minus(variableDebtBefore); - - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); - - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt - .plus(debtAccrued) - .minus(amountRepaidBN); + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt; + expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; } @@ -493,9 +500,9 @@ export const calcExpectedReserveDataAfterRepay = ( amountRepaidBN ); - expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity.plus( - amountRepaidBN - ); + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(expectedReserveData.totalVariableDebt); expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, @@ -517,15 +524,6 @@ export const calcExpectedReserveDataAfterRepay = ( expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.lastUpdateTimestamp = txTimestamp; return expectedReserveData; @@ -571,12 +569,6 @@ export const calcExpectedUserDataAfterBorrow = ( ); expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; - - expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( - expectedDataAfterAction, - expectedUserData, - currentTimestamp - ); } else { expectedUserData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( amountBorrowedBN.rayDiv(expectedDataAfterAction.variableBorrowIndex) @@ -587,8 +579,20 @@ export const calcExpectedUserDataAfterBorrow = ( expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; expectedUserData.stableRateLastUpdated = userDataBeforeAction.stableRateLastUpdated; + + expectedUserData.currentStableDebt = calcExpectedStableDebtTokenBalance( + userDataBeforeAction.principalStableDebt, + userDataBeforeAction.stableBorrowRate, + userDataBeforeAction.stableRateLastUpdated, + currentTimestamp + ); } + expectedUserData.currentVariableDebt = calcExpectedVariableDebtTokenBalance( + expectedDataAfterAction, + expectedUserData, + currentTimestamp + ); expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; expectedUserData.usageAsCollateralEnabled = userDataBeforeAction.usageAsCollateralEnabled; @@ -620,32 +624,33 @@ export const calcExpectedUserDataAfterRepay = ( ): UserReserveData => { const expectedUserData = {}; - const variableBorrowBalance = calcExpectedVariableDebtTokenBalance( + const variableDebt = calcExpectedVariableDebtTokenBalance( reserveDataBeforeAction, userDataBeforeAction, currentTimestamp ); - const stableBorrowBalance = calcExpectedStableDebtTokenBalance( + const stableDebt = calcExpectedStableDebtTokenBalance( userDataBeforeAction.principalStableDebt, userDataBeforeAction.stableBorrowRate, userDataBeforeAction.stableRateLastUpdated, currentTimestamp ); - - if (new BigNumber(totalRepaid).abs().eq(MAX_UINT_AMOUNT)) { - totalRepaid = + + let totalRepaidBN = new BigNumber(totalRepaid); + if (totalRepaidBN.abs().eq(MAX_UINT_AMOUNT)) { + totalRepaidBN = rateMode == RateMode.Stable - ? stableBorrowBalance.toFixed(0) - : variableBorrowBalance.toFixed(); + ? stableDebt + : variableDebt; } if (rateMode == RateMode.Stable) { - expectedUserData.principalVariableDebt = userDataBeforeAction.principalVariableDebt; - expectedUserData.currentVariableDebt = variableBorrowBalance; - expectedUserData.variableBorrowIndex = userDataBeforeAction.variableBorrowIndex; - expectedUserData.currentStableDebt = expectedUserData.principalStableDebt = stableBorrowBalance.minus( + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; + expectedUserData.currentVariableDebt = userDataBeforeAction.currentVariableDebt; + + expectedUserData.principalStableDebt = expectedUserData.currentStableDebt = stableDebt.minus( totalRepaid ); @@ -659,21 +664,15 @@ export const calcExpectedUserDataAfterRepay = ( expectedUserData.stableRateLastUpdated = txTimestamp; } } else { - expectedUserData.currentStableDebt = stableBorrowBalance; - expectedUserData.principalStableDebt = userDataBeforeAction.principalStableDebt; + + expectedUserData.currentStableDebt = userDataBeforeAction.principalStableDebt; + expectedUserData.principalStableDebt = stableDebt; expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; expectedUserData.stableRateLastUpdated = userDataBeforeAction.stableRateLastUpdated; + + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt.minus(totalRepaidBN.rayDiv(expectedDataAfterAction.variableBorrowIndex)); + expectedUserData.currentVariableDebt = expectedUserData.scaledVariableDebt.rayMul(expectedDataAfterAction.variableBorrowIndex); - expectedUserData.currentVariableDebt = expectedUserData.principalVariableDebt = variableBorrowBalance.minus( - totalRepaid - ); - - if (expectedUserData.currentVariableDebt.eq('0')) { - //user repaid everything - expectedUserData.variableBorrowIndex = new BigNumber('0'); - } else { - expectedUserData.variableBorrowIndex = expectedDataAfterAction.variableBorrowIndex; - } } expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; @@ -688,7 +687,7 @@ export const calcExpectedUserDataAfterRepay = ( expectedUserData.scaledATokenBalance = userDataBeforeAction.scaledATokenBalance; if (user === onBehalfOf) { - expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(totalRepaid); + expectedUserData.walletBalance = userDataBeforeAction.walletBalance.minus(totalRepaidBN); } else { //wallet balance didn't change expectedUserData.walletBalance = userDataBeforeAction.walletBalance; diff --git a/test/liquidation-underlying.spec.ts b/test/liquidation-underlying.spec.ts index 26f10ced..df1e9404 100644 --- a/test/liquidation-underlying.spec.ts +++ b/test/liquidation-underlying.spec.ts @@ -175,7 +175,9 @@ makeSuite('LendingPool liquidation - liquidator receiving the underlying asset', ); const stableDebtBeforeTx = calcExpectedStableDebtTokenBalance( - userReserveDataBefore, + userReserveDataBefore.principalStableDebt, + userReserveDataBefore.stableBorrowRate, + userReserveDataBefore.stableRateLastUpdated, txTimestamp ); diff --git a/test/repay-with-collateral.spec.ts b/test/repay-with-collateral.spec.ts index 41e9060f..455520f5 100644 --- a/test/repay-with-collateral.spec.ts +++ b/test/repay-with-collateral.spec.ts @@ -420,7 +420,9 @@ makeSuite('LendingPool. repayWithCollateral()', (testEnv: TestEnv) => { ).minus(usdcUserDataBefore.currentVariableDebt); const expectedStableDebtIncrease = calcExpectedStableDebtTokenBalance( - usdcUserDataBefore, + usdcUserDataBefore.principalStableDebt, + usdcUserDataBefore.stableBorrowRate, + usdcUserDataBefore.stableRateLastUpdated, new BigNumber(repayWithCollateralTimestamp) ).minus(usdcUserDataBefore.currentStableDebt); diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 98e0c164..54fe7433 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['borrow-repay-variable.json']; +const selectedScenarios: string[] = []; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 5868a4844fd4bae919ace682cb5a1a40c16f36e3 Mon Sep 17 00:00:00 2001 From: The3D Date: Fri, 18 Sep 2020 17:56:33 +0200 Subject: [PATCH 31/45] Updated testsW --- buidler.config.ts | 3 +- contracts/tokenization/StableDebtToken.sol | 38 ++++- test/helpers/actions.ts | 23 ++- test/helpers/utils/calculations.ts | 181 +++++++++++++-------- test/scenario.spec.ts | 2 +- 5 files changed, 173 insertions(+), 74 deletions(-) diff --git a/buidler.config.ts b/buidler.config.ts index 9db632a2..03f42645 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -9,7 +9,8 @@ usePlugin('buidler-typechain'); usePlugin('solidity-coverage'); usePlugin('@nomiclabs/buidler-waffle'); usePlugin('@nomiclabs/buidler-etherscan'); -usePlugin('buidler-gas-reporter'); +//usePlugin('buidler-gas-reporter'); + const DEFAULT_BLOCK_GAS_LIMIT = 10000000; const DEFAULT_GAS_PRICE = 10; const HARDFORK = 'istanbul'; diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index 6401bfc9..fe352b32 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -167,6 +167,10 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { uint256 previousSupply = totalSupply(); + //since the total supply and each single user debt accrue separately, + //there might be accumulation errors so that the last borrower repaying + //might actually try to repay more than the available debt supply. + //in this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; @@ -232,32 +236,51 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { ); } + /** + * @dev returns the principal, total supply and the average borrow rate + **/ function getSupplyData() public override view returns (uint256, uint256, uint256) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate); } + /** + * @dev returns the the total supply and the average stable rate + **/ function getTotalSupplyAndAvgRate() public override view returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } + /** + * @dev returns the total supply + **/ function totalSupply() public override view returns (uint256) { return _calcTotalSupply(_avgStableRate); } - + + /** + * @dev returns the timestamp at which the total supply was updated + **/ function getTotalSupplyLastUpdated() public override view returns(uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from + * @param user the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external virtual override view returns (uint256) { return super.balanceOf(user); } + + /** + * @dev calculates the total supply + * @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) { uint256 principalSupply = super.totalSupply(); @@ -273,6 +296,12 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { return principalSupply.rayMul(cumulatedInterest); } + /** + * @dev mints stable debt tokens to an user + * @param account the account receiving the debt tokens + * @param amount the amount being minted + * @param oldTotalSupply the total supply before the minting event + **/ function _mint(address account, uint256 amount, uint256 oldTotalSupply) internal { uint256 oldAccountBalance = _balances[account]; @@ -283,9 +312,14 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } } + /** + * @dev burns stable debt tokens of an user + * @param account the user getting his debt burned + * @param amount the amount being burned + * @param oldTotalSupply the total supply before the burning event + **/ function _burn(address account, uint256 amount, uint256 oldTotalSupply) internal { - uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 3e60955d..ba874e6e 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -375,6 +375,12 @@ export const borrow = async ( txCost ); + console.log("total stable debt actual: ", reserveDataAfter.totalStableDebt.toFixed()); + console.log("total stable debt expected: ", expectedReserveData.totalStableDebt.toFixed()); + + console.log("total variable debt actual: ", reserveDataAfter.totalVariableDebt.toFixed()); + console.log("total variable debt expected: ", expectedReserveData.totalVariableDebt.toFixed()); + expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); @@ -479,6 +485,14 @@ export const repay = async ( txCost ); + + console.log("total stable debt actual: ", reserveDataAfter.totalStableDebt.toFixed()); + console.log("total stable debt expected: ", expectedReserveData.totalStableDebt.toFixed()); + + console.log("total variable debt actual: ", reserveDataAfter.totalVariableDebt.toFixed()); + console.log("total variable debt expected: ", expectedReserveData.totalVariableDebt.toFixed()); + + expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); @@ -741,9 +755,12 @@ export const getContractsData = async ( sender?: string ) => { const {pool} = testEnv; - const reserveData = await getReserveData(pool, reserve); - const userData = await getUserData(pool, reserve, user, sender || user); - const timestamp = await timeLatest(); + + const [userData, reserveData, timestamp] = await Promise.all([ + getUserData(pool, reserve, user, sender || user), + getReserveData(pool, reserve), + timeLatest(), + ]); return { reserveData, diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 795dbaa3..3cd05b69 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -97,6 +97,8 @@ export const calcExpectedUserDataAfterWithdraw = ( currentTimestamp: BigNumber, txCost: BigNumber ): UserReserveData => { + console.log('Checking withdraw'); + const expectedUserData = {}; const aTokenBalance = calcExpectedATokenBalance( @@ -183,7 +185,9 @@ export const calcExpectedReserveDataAfterDeposit = ( ); expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( - reserveDataBeforeAction, + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, txTimestamp ); expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( @@ -252,7 +256,9 @@ export const calcExpectedReserveDataAfterWithdraw = ( ); expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( - reserveDataBeforeAction, + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, txTimestamp ); expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( @@ -313,33 +319,71 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.lastUpdateTimestamp = txTimestamp; if (borrowRateMode == RateMode.Stable) { + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.scaledVariableDebt.rayMul( - expectedReserveData.variableBorrowIndex + const expectedVariableDebtAfterTx = calcExpectedTotalVariableDebt( + reserveDataBeforeAction, + txTimestamp ); + const expectedStableDebtUntilTx = calcExpectedTotalStableDebt( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, + txTimestamp + ); + + expectedReserveData.principalStableDebt = expectedStableDebtUntilTx.plus(amountBorrowedBN); + expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt, + expectedStableDebtUntilTx, amountBorrowedBN, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.principalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( - amountBorrowedBN + const totalLiquidityAfterTx = expectedReserveData.availableLiquidity + .plus(expectedReserveData.principalStableDebt) + .plus(expectedVariableDebtAfterTx); + + const utilizationRateAfterTx = calcExpectedUtilizationRate( + expectedReserveData.principalStableDebt, //the expected principal debt is the total debt immediately after the tx + expectedVariableDebtAfterTx, + totalLiquidityAfterTx ); + const ratesAfterTx = calcExpectedInterestRates( + reserveDataBeforeAction.symbol, + reserveDataBeforeAction.marketStableRate, + utilizationRateAfterTx, + expectedReserveData.principalStableDebt, + expectedVariableDebtAfterTx, + expectedReserveData.averageStableBorrowRate + ); + + expectedReserveData.liquidityRate = ratesAfterTx[0]; + + expectedReserveData.stableBorrowRate = ratesAfterTx[1]; + + expectedReserveData.variableBorrowRate = ratesAfterTx[2]; + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( - { - ...reserveDataBeforeAction, - principalStableDebt: expectedReserveData.principalStableDebt, - averageStableBorrowRate: expectedReserveData.averageStableBorrowRate, - lastUpdateTimestamp: txTimestamp, - }, + expectedReserveData.principalStableDebt, + expectedReserveData.averageStableBorrowRate, + txTimestamp, currentTimestamp ); + expectedReserveData.totalVariableDebt = reserveDataBeforeAction.scaledVariableDebt.rayMul( + calcExpectedReserveNormalizedDebt( + expectedReserveData.variableBorrowRate, + expectedReserveData.variableBorrowIndex, + txTimestamp, + currentTimestamp + ) + ); + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity .plus(expectedReserveData.totalVariableDebt) .plus(expectedReserveData.totalStableDebt); @@ -349,21 +393,6 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalVariableDebt, expectedReserveData.totalLiquidity ); - - const rates = calcExpectedInterestRates( - reserveDataBeforeAction.symbol, - reserveDataBeforeAction.marketStableRate, - expectedReserveData.utilizationRate, - expectedReserveData.totalStableDebt, - expectedReserveData.totalVariableDebt, - expectedReserveData.averageStableBorrowRate - ); - - expectedReserveData.liquidityRate = rates[0]; - - expectedReserveData.stableBorrowRate = rates[1]; - - expectedReserveData.variableBorrowRate = rates[2]; } else { expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; @@ -406,7 +435,12 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.variableBorrowRate = rates[2]; expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( - calcExpectedReserveNormalizedDebt(expectedReserveData, currentTimestamp) + calcExpectedReserveNormalizedDebt( + expectedReserveData.variableBorrowRate, + expectedReserveData.variableBorrowIndex, + txTimestamp, + currentTimestamp + ) ); expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity @@ -469,16 +503,32 @@ export const calcExpectedReserveDataAfterRepay = ( ); if (borrowRateMode == RateMode.Stable) { - expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.minus( - amountRepaidBN + const expectedDebt = calcExpectedTotalStableDebt( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, + txTimestamp ); - expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( - reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt, - amountRepaidBN.negated(), - userDataBeforeAction.stableBorrowRate + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = expectedDebt.minus( + amountRepaidBN ); + //due to accumulation errors, the total stable debt might be smaller than the last user debt. + //in this case we simply set the total supply and avg stable rate to 0. + if (expectedReserveData.principalStableDebt.lt(0)) { + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = new BigNumber( + 0 + ); + expectedReserveData.averageStableBorrowRate = new BigNumber(0); + } else { + expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( + reserveDataBeforeAction.averageStableBorrowRate, + expectedDebt, + amountRepaidBN.negated(), + userDataBeforeAction.stableBorrowRate + ); + } + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; } else { @@ -636,22 +686,18 @@ export const calcExpectedUserDataAfterRepay = ( userDataBeforeAction.stableRateLastUpdated, currentTimestamp ); - + let totalRepaidBN = new BigNumber(totalRepaid); if (totalRepaidBN.abs().eq(MAX_UINT_AMOUNT)) { - totalRepaidBN = - rateMode == RateMode.Stable - ? stableDebt - : variableDebt; + totalRepaidBN = rateMode == RateMode.Stable ? stableDebt : variableDebt; } if (rateMode == RateMode.Stable) { - expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; expectedUserData.currentVariableDebt = userDataBeforeAction.currentVariableDebt; expectedUserData.principalStableDebt = expectedUserData.currentStableDebt = stableDebt.minus( - totalRepaid + totalRepaidBN ); if (expectedUserData.currentStableDebt.eq('0')) { @@ -664,15 +710,17 @@ export const calcExpectedUserDataAfterRepay = ( expectedUserData.stableRateLastUpdated = txTimestamp; } } else { - expectedUserData.currentStableDebt = userDataBeforeAction.principalStableDebt; expectedUserData.principalStableDebt = stableDebt; expectedUserData.stableBorrowRate = userDataBeforeAction.stableBorrowRate; expectedUserData.stableRateLastUpdated = userDataBeforeAction.stableRateLastUpdated; - - expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt.minus(totalRepaidBN.rayDiv(expectedDataAfterAction.variableBorrowIndex)); - expectedUserData.currentVariableDebt = expectedUserData.scaledVariableDebt.rayMul(expectedDataAfterAction.variableBorrowIndex); + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt.minus( + totalRepaidBN.rayDiv(expectedDataAfterAction.variableBorrowIndex) + ); + expectedUserData.currentVariableDebt = expectedUserData.scaledVariableDebt.rayMul( + expectedDataAfterAction.variableBorrowIndex + ); } expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; @@ -1028,23 +1076,17 @@ const calcExpectedAverageStableBorrowRate = ( .decimalPlaces(0, BigNumber.ROUND_DOWN); }; -const calcExpectedVariableDebtUserIndex = ( - reserveDataBeforeAction: ReserveData, - expectedUserBalanceAfterAction: BigNumber, - currentTimestamp: BigNumber -) => { - if (expectedUserBalanceAfterAction.eq(0)) { - return new BigNumber(0); - } - return calcExpectedReserveNormalizedDebt(reserveDataBeforeAction, currentTimestamp); -}; - export const calcExpectedVariableDebtTokenBalance = ( reserveData: ReserveData, userData: UserReserveData, currentTimestamp: BigNumber ) => { - const normalizedDebt = calcExpectedReserveNormalizedDebt(reserveData, currentTimestamp); + const normalizedDebt = calcExpectedReserveNormalizedDebt( + reserveData.variableBorrowRate, + reserveData.variableBorrowIndex, + reserveData.lastUpdateTimestamp, + currentTimestamp + ); const {scaledVariableDebt} = userData; @@ -1237,11 +1279,11 @@ const calcExpectedReserveNormalizedIncome = ( }; const calcExpectedReserveNormalizedDebt = ( - reserveData: ReserveData, + variableBorrowRate: BigNumber, + variableBorrowIndex: BigNumber, + lastUpdateTimestamp: BigNumber, currentTimestamp: BigNumber ) => { - const {variableBorrowRate, variableBorrowIndex, lastUpdateTimestamp} = reserveData; - //if utilization rate is 0, nothing to compound if (variableBorrowRate.eq('0')) { return variableBorrowIndex; @@ -1300,14 +1342,19 @@ const calcExpectedVariableBorrowIndex = (reserveData: ReserveData, timestamp: Bi return cumulatedInterest.rayMul(reserveData.variableBorrowIndex); }; -const calcExpectedTotalStableDebt = (reserveData: ReserveData, timestamp: BigNumber) => { +const calcExpectedTotalStableDebt = ( + principalStableDebt: BigNumber, + averageStableBorrowRate: BigNumber, + lastUpdateTimestamp: BigNumber, + currentTimestamp: BigNumber +) => { const cumulatedInterest = calcCompoundedInterest( - reserveData.averageStableBorrowRate, - timestamp, - reserveData.lastUpdateTimestamp + averageStableBorrowRate, + currentTimestamp, + lastUpdateTimestamp ); - return cumulatedInterest.rayMul(reserveData.principalStableDebt); + return cumulatedInterest.rayMul(principalStableDebt); }; const calcExpectedTotalVariableDebt = ( diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 54fe7433..98e0c164 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = []; +const selectedScenarios: string[] = ['borrow-repay-variable.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 52033bae21518bbed67ef54a9142cd3d4c3655b0 Mon Sep 17 00:00:00 2001 From: The3D Date: Fri, 18 Sep 2020 18:03:38 +0200 Subject: [PATCH 32/45] Added console logs --- test/helpers/actions.ts | 4 ++++ test/scenario.spec.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index ba874e6e..4921e66c 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -377,9 +377,13 @@ export const borrow = async ( console.log("total stable debt actual: ", reserveDataAfter.totalStableDebt.toFixed()); console.log("total stable debt expected: ", expectedReserveData.totalStableDebt.toFixed()); + console.log("total avg stable rate actual: ", reserveDataAfter.averageStableBorrowRate.toFixed()); + console.log("total avg stable rate expected: ", expectedReserveData.averageStableBorrowRate.toFixed()); console.log("total variable debt actual: ", reserveDataAfter.totalVariableDebt.toFixed()); console.log("total variable debt expected: ", expectedReserveData.totalVariableDebt.toFixed()); + console.log("variable borrow rate actual: ", reserveDataAfter.variableBorrowRate.toFixed()); + console.log("variable borrow rate expected: ", expectedReserveData.variableBorrowRate.toFixed()); expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 98e0c164..d9edd4ac 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['borrow-repay-variable.json']; +const selectedScenarios: string[] = ['borrow-repay-stable.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From f188a212215e9c1ea9a71a93cec33d1e1ac70c9b Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 10:12:04 +0200 Subject: [PATCH 33/45] Fixed deployed-contracts --- deployed-contracts.json | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/deployed-contracts.json b/deployed-contracts.json index e37c68bd..daecd72c 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -65,12 +65,9 @@ "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" }, "localhost": { -<<<<<<< HEAD -======= "address": "0x65e0Cd5B8904A02f2e00BC6f58bf881998D54BDe" }, "coverage": { ->>>>>>> master "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" } }, @@ -84,12 +81,9 @@ "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" }, "localhost": { -<<<<<<< HEAD -======= "address": "0x5d12dDe3286D94E0d85F9D3B01B7099cfA0aBCf1" }, "coverage": { ->>>>>>> master "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" } }, @@ -213,12 +207,9 @@ "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" }, "localhost": { -<<<<<<< HEAD -======= "address": "0xAd49512dFBaD6fc13D67d3935283c0606812E962" }, "coverage": { ->>>>>>> master "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" } }, @@ -563,12 +554,9 @@ "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" }, "localhost": { -<<<<<<< HEAD -======= "address": "0x9305d862ee95a899b83906Cd9CB666aC269E5f66" }, "coverage": { ->>>>>>> master "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" } }, @@ -674,11 +662,7 @@ "buidlerevm": { "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" }, -<<<<<<< HEAD - "localhost": { -======= "coverage": { ->>>>>>> master "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" } } From c8b044aecfdd5a2f208840b1d887d12c92f480ba Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 12:29:33 +0200 Subject: [PATCH 34/45] Fixed borrow tests --- test/helpers/actions.ts | 23 +-------- .../scenarios/borrow-repay-stable.json | 11 ++++ test/helpers/utils/calculations.ts | 51 +++++++++++-------- test/scenario.spec.ts | 2 +- 4 files changed, 44 insertions(+), 43 deletions(-) diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 4921e66c..c9bf4bcf 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -32,6 +32,7 @@ import {waitForTx} from '../__setup.spec'; import {ContractReceipt} from 'ethers'; import {AToken} from '../../types/AToken'; import {RateMode, tEthereumAddress} from '../../helpers/types'; +import { time } from 'console'; const {expect} = chai; @@ -262,10 +263,6 @@ export const withdraw = async ( txCost ); - const actualAmountWithdrawn = userDataBefore.currentATokenBalance.minus( - expectedUserData.currentATokenBalance - ); - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); @@ -375,16 +372,6 @@ export const borrow = async ( txCost ); - console.log("total stable debt actual: ", reserveDataAfter.totalStableDebt.toFixed()); - console.log("total stable debt expected: ", expectedReserveData.totalStableDebt.toFixed()); - console.log("total avg stable rate actual: ", reserveDataAfter.averageStableBorrowRate.toFixed()); - console.log("total avg stable rate expected: ", expectedReserveData.averageStableBorrowRate.toFixed()); - - console.log("total variable debt actual: ", reserveDataAfter.totalVariableDebt.toFixed()); - console.log("total variable debt expected: ", expectedReserveData.totalVariableDebt.toFixed()); - console.log("variable borrow rate actual: ", reserveDataAfter.variableBorrowRate.toFixed()); - console.log("variable borrow rate expected: ", expectedReserveData.variableBorrowRate.toFixed()); - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); @@ -489,14 +476,6 @@ export const repay = async ( txCost ); - - console.log("total stable debt actual: ", reserveDataAfter.totalStableDebt.toFixed()); - console.log("total stable debt expected: ", expectedReserveData.totalStableDebt.toFixed()); - - console.log("total variable debt actual: ", reserveDataAfter.totalVariableDebt.toFixed()); - console.log("total variable debt expected: ", expectedReserveData.totalVariableDebt.toFixed()); - - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/helpers/scenarios/borrow-repay-stable.json b/test/helpers/scenarios/borrow-repay-stable.json index 9d2348e9..87e7de0b 100644 --- a/test/helpers/scenarios/borrow-repay-stable.json +++ b/test/helpers/scenarios/borrow-repay-stable.json @@ -626,6 +626,17 @@ }, "expected": "success" }, + { + "name": "repay", + "args": { + "reserve": "DAI", + "amount": "-1", + "user": "1", + "onBehalfOf": "1", + "borrowRateMode": "variable" + }, + "expected": "success" + }, { "name": "withdraw", "args": { diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 3cd05b69..671e6205 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -97,8 +97,6 @@ export const calcExpectedUserDataAfterWithdraw = ( currentTimestamp: BigNumber, txCost: BigNumber ): UserReserveData => { - console.log('Checking withdraw'); - const expectedUserData = {}; const aTokenBalance = calcExpectedATokenBalance( @@ -236,9 +234,6 @@ export const calcExpectedReserveDataAfterWithdraw = ( ).toFixed(); } - expectedReserveData.totalLiquidity = new BigNumber(reserveDataBeforeAction.totalLiquidity).minus( - amountWithdrawn - ); expectedReserveData.availableLiquidity = new BigNumber( reserveDataBeforeAction.availableLiquidity ).minus(amountWithdrawn); @@ -261,13 +256,17 @@ export const calcExpectedReserveDataAfterWithdraw = ( reserveDataBeforeAction.lastUpdateTimestamp, txTimestamp ); - expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( - reserveDataBeforeAction, + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( expectedReserveData.variableBorrowIndex ); expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; + expectedReserveData.totalLiquidity = new BigNumber(reserveDataBeforeAction.availableLiquidity) + .minus(amountWithdrawn) + .plus(expectedReserveData.totalVariableDebt) + .plus(expectedReserveData.totalStableDebt); + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, expectedReserveData.totalVariableDebt, @@ -319,12 +318,10 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.lastUpdateTimestamp = txTimestamp; if (borrowRateMode == RateMode.Stable) { - expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; - const expectedVariableDebtAfterTx = calcExpectedTotalVariableDebt( - reserveDataBeforeAction, - txTimestamp + const expectedVariableDebtAfterTx = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex ); const expectedStableDebtUntilTx = calcExpectedTotalStableDebt( @@ -394,28 +391,38 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalLiquidity ); } else { + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; - expectedReserveData.totalStableDebt = calcExpectedStableDebtTokenBalance( - userDataBeforeAction.principalStableDebt, - userDataBeforeAction.stableBorrowRate, - userDataBeforeAction.stableRateLastUpdated, + const totalStableDebtAfterTx = calcExpectedStableDebtTokenBalance( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, + txTimestamp + ); + + expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, currentTimestamp ); + expectedReserveData.averageStableBorrowRate = reserveDataBeforeAction.averageStableBorrowRate; expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( amountBorrowedBN.rayDiv(expectedReserveData.variableBorrowIndex) ); + const totalVariableDebtAfterTx = expectedReserveData.scaledVariableDebt.rayMul( expectedReserveData.variableBorrowIndex ); const utilizationRateAfterTx = calcExpectedUtilizationRate( - expectedReserveData.totalStableDebt, + totalStableDebtAfterTx, totalVariableDebtAfterTx, expectedReserveData.availableLiquidity - .plus(expectedReserveData.totalStableDebt) + .plus(totalStableDebtAfterTx) .plus(totalVariableDebtAfterTx) ); @@ -423,7 +430,7 @@ export const calcExpectedReserveDataAfterBorrow = ( reserveDataBeforeAction.symbol, reserveDataBeforeAction.marketStableRate, utilizationRateAfterTx, - expectedReserveData.totalStableDebt, + totalStableDebtAfterTx, totalVariableDebtAfterTx, expectedReserveData.averageStableBorrowRate ); @@ -513,6 +520,7 @@ export const calcExpectedReserveDataAfterRepay = ( expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = expectedDebt.minus( amountRepaidBN ); + //due to accumulation errors, the total stable debt might be smaller than the last user debt. //in this case we simply set the total supply and avg stable rate to 0. if (expectedReserveData.principalStableDebt.lt(0)) { @@ -530,7 +538,10 @@ export const calcExpectedReserveDataAfterRepay = ( } expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; + + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); } else { expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.minus( amountRepaidBN.rayDiv(expectedReserveData.variableBorrowIndex) @@ -694,7 +705,7 @@ export const calcExpectedUserDataAfterRepay = ( if (rateMode == RateMode.Stable) { expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; - expectedUserData.currentVariableDebt = userDataBeforeAction.currentVariableDebt; + expectedUserData.currentVariableDebt = variableDebt; expectedUserData.principalStableDebt = expectedUserData.currentStableDebt = stableDebt.minus( totalRepaidBN diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index d9edd4ac..be3f2977 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['borrow-repay-stable.json']; +const selectedScenarios: string[] = ['borrow-repay-stable.json','borrow-repay-variable.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 8792515f5b45907323b304e63b1b80fe20d05e25 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 14:29:59 +0200 Subject: [PATCH 35/45] fixed swap rate mode tests --- test/helpers/utils/calculations.ts | 105 ++++++++++++++++------------- test/scenario.spec.ts | 2 +- 2 files changed, 59 insertions(+), 48 deletions(-) diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 671e6205..8f029d9a 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -391,7 +391,6 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalLiquidity ); } else { - expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; const totalStableDebtAfterTx = calcExpectedStableDebtTokenBalance( @@ -791,41 +790,59 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( txTimestamp ); + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); + + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( + reserveDataBeforeAction, + txTimestamp + ); + expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity; + const totalStableDebtUntilTx = calcExpectedTotalStableDebt( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.lastUpdateTimestamp, + txTimestamp + ); + if (rateMode === RateMode.Stable) { //swap user stable debt to variable - const debtAccrued = stableDebt.minus(userDataBeforeAction.principalStableDebt); + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( + stableDebt.rayDiv(expectedReserveData.variableBorrowIndex) + ); - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); + + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = totalStableDebtUntilTx.minus(stableDebt); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), + expectedReserveData.principalStableDebt.plus(stableDebt), stableDebt.negated(), userDataBeforeAction.stableBorrowRate ); - - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt.plus( - stableDebt - ); - - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.minus( - userDataBeforeAction.principalStableDebt - ); } else { - const totalDebtBefore = userDataBeforeAction.scaledVariableDebt.rayMul( - reserveDataBeforeAction.variableBorrowIndex - ); - const debtAccrued = variableDebt.minus(totalDebtBefore); - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); + //swap variable to stable - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus( + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = totalStableDebtUntilTx.plus( variableDebt ); + + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.minus( + variableDebt.rayDiv(expectedReserveData.variableBorrowIndex) + ); + + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); + expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, reserveDataBeforeAction.totalStableDebt, @@ -834,6 +851,10 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( ); } + expectedReserveData.totalLiquidity = reserveDataBeforeAction.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(expectedReserveData.totalVariableDebt); + expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, expectedReserveData.totalVariableDebt, @@ -854,15 +875,6 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - return expectedReserveData; }; @@ -876,19 +888,19 @@ export const calcExpectedUserDataAfterSwapRateMode = ( ): UserReserveData => { const expectedUserData = {...userDataBeforeAction}; - const variableBorrowBalance = calcExpectedVariableDebtTokenBalance( - reserveDataBeforeAction, - userDataBeforeAction, - txTimestamp - ); - - const stableBorrowBalance = calcExpectedStableDebtTokenBalance( + const stableDebtBalance = calcExpectedStableDebtTokenBalance( userDataBeforeAction.principalStableDebt, userDataBeforeAction.stableBorrowRate, userDataBeforeAction.stableRateLastUpdated, txTimestamp ); + const variableDebtBalance = calcExpectedVariableDebtTokenBalance( + reserveDataBeforeAction, + userDataBeforeAction, + txTimestamp + ); + expectedUserData.currentATokenBalance = calcExpectedATokenBalance( reserveDataBeforeAction, userDataBeforeAction, @@ -901,31 +913,30 @@ export const calcExpectedUserDataAfterSwapRateMode = ( expectedUserData.stableBorrowRate = new BigNumber(0); - expectedUserData.principalVariableDebt = expectedUserData.currentVariableDebt = userDataBeforeAction.currentVariableDebt.plus( - stableBorrowBalance + expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt.plus( + stableDebtBalance.rayDiv(expectedDataAfterAction.variableBorrowIndex) ); - expectedUserData.variableBorrowIndex = expectedDataAfterAction.variableBorrowIndex; + expectedUserData.currentVariableDebt = expectedUserData.scaledVariableDebt.rayMul( + expectedDataAfterAction.variableBorrowIndex + ); + expectedUserData.stableRateLastUpdated = new BigNumber(0); } else { expectedUserData.principalStableDebt = expectedUserData.currentStableDebt = userDataBeforeAction.currentStableDebt.plus( - variableBorrowBalance + variableDebtBalance ); //weighted average of the previous and the current expectedUserData.stableBorrowRate = calcExpectedUserStableRate( - userDataBeforeAction.principalStableDebt, + stableDebtBalance, userDataBeforeAction.stableBorrowRate, - variableBorrowBalance, + variableDebtBalance, reserveDataBeforeAction.stableBorrowRate ); expectedUserData.stableRateLastUpdated = txTimestamp; - expectedUserData.currentVariableDebt = expectedUserData.principalVariableDebt = new BigNumber( - 0 - ); - - expectedUserData.variableBorrowIndex = new BigNumber(0); + expectedUserData.currentVariableDebt = expectedUserData.scaledVariableDebt = new BigNumber(0); } expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index be3f2977..8a14d4e2 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['borrow-repay-stable.json','borrow-repay-variable.json']; +const selectedScenarios: string[] = ['swap-rate-mode.json']; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From a1a45d392a7bb1b0e7b1d0781825b4600c536f1e Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 15:27:53 +0200 Subject: [PATCH 36/45] Updating rebalance rate tests --- test/helpers/actions.ts | 28 +++++++++- test/helpers/utils/calculations.ts | 72 +++++++++++++++----------- test/helpers/utils/helpers.ts | 3 ++ test/helpers/utils/interfaces/index.ts | 1 + test/scenario.spec.ts | 2 +- 5 files changed, 74 insertions(+), 32 deletions(-) diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index c9bf4bcf..44c134eb 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -49,7 +49,8 @@ const almostEqualOrEqual = function ( key === 'marketStableRate' || key === 'symbol' || key === 'aTokenAddress' || - key === 'decimals' + key === 'decimals' || + key === 'totalStableDebtLastUpdated' ) { // skipping consistency check on accessory data return; @@ -369,9 +370,23 @@ export const borrow = async ( userDataBefore, txTimestamp, timestamp, - txCost + onBehalfOf, + user.address ); + console.log("total debt stable exp ", expectedReserveData.totalStableDebt.toFixed()); + console.log("total debt stable act ", reserveDataAfter.totalStableDebt.toFixed()); + + console.log("total debt variable exp ", expectedReserveData.totalVariableDebt.toFixed()); + console.log("total debt variable act ", reserveDataAfter.totalVariableDebt.toFixed()); + + console.log("avl liquidity exp ", expectedReserveData.availableLiquidity.toFixed()); + console.log("avl liquidity exp ", reserveDataAfter.availableLiquidity.toFixed()); + + console.log("avg borrow rate exp ", expectedReserveData.averageStableBorrowRate.toFixed()); + console.log("avl borrow rate exp ", reserveDataAfter.averageStableBorrowRate.toFixed()); + + expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); @@ -664,6 +679,15 @@ export const rebalanceStableBorrowRate = async ( txTimestamp ); + console.log("total debt stable exp ", expectedReserveData.totalStableDebt.toFixed()); + console.log("total debt stable act ", reserveDataAfter.totalStableDebt.toFixed()); + + console.log("total debt variable exp ", expectedReserveData.totalVariableDebt.toFixed()); + console.log("total debt variable act ", reserveDataAfter.totalVariableDebt.toFixed()); + + console.log("avl liquidity exp ", expectedReserveData.availableLiquidity.toFixed()); + console.log("avl liquidity exp ", reserveDataAfter.availableLiquidity.toFixed()); + expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 8f029d9a..6d76db67 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -7,7 +7,7 @@ import { EXCESS_UTILIZATION_RATE, ZERO_ADDRESS, } from '../../../helpers/constants'; -import {IReserveParams, iAavePoolAssets, RateMode} from '../../../helpers/types'; +import {IReserveParams, iAavePoolAssets, RateMode, tEthereumAddress} from '../../../helpers/types'; import './math'; import {ReserveData, UserReserveData} from './interfaces'; @@ -185,7 +185,7 @@ export const calcExpectedReserveDataAfterDeposit = ( expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); expectedReserveData.totalVariableDebt = calcExpectedTotalVariableDebt( @@ -253,7 +253,7 @@ export const calcExpectedReserveDataAfterWithdraw = ( expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( @@ -318,6 +318,7 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.lastUpdateTimestamp = txTimestamp; if (borrowRateMode == RateMode.Stable) { + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; const expectedVariableDebtAfterTx = expectedReserveData.scaledVariableDebt.rayMul( @@ -327,7 +328,7 @@ export const calcExpectedReserveDataAfterBorrow = ( const expectedStableDebtUntilTx = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); @@ -403,7 +404,7 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, currentTimestamp ); @@ -512,7 +513,7 @@ export const calcExpectedReserveDataAfterRepay = ( const expectedDebt = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); @@ -597,13 +598,15 @@ export const calcExpectedUserDataAfterBorrow = ( userDataBeforeAction: UserReserveData, txTimestamp: BigNumber, currentTimestamp: BigNumber, - txCost: BigNumber + user: tEthereumAddress, + onBehalfOf: tEthereumAddress ): UserReserveData => { const expectedUserData = {}; const amountBorrowedBN = new BigNumber(amountBorrowed); if (interestRateMode == RateMode.Stable) { + const stableDebtUntilTx = calcExpectedStableDebtTokenBalance( userDataBeforeAction.principalStableDebt, userDataBeforeAction.stableBorrowRate, @@ -805,7 +808,7 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( const totalStableDebtUntilTx = calcExpectedTotalStableDebt( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); @@ -819,7 +822,9 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( expectedReserveData.variableBorrowIndex ); - expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = totalStableDebtUntilTx.minus(stableDebt); + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = totalStableDebtUntilTx.minus( + stableDebt + ); expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, @@ -828,7 +833,6 @@ export const calcExpectedReserveDataAfterSwapRateMode = ( userDataBeforeAction.stableBorrowRate ); } else { - //swap variable to stable expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = totalStableDebtUntilTx.plus( @@ -953,39 +957,58 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( expectedReserveData.address = reserveDataBeforeAction.address; - const stableBorrowBalance = calcExpectedStableDebtTokenBalance( + const userStableDebt = calcExpectedStableDebtTokenBalance( userDataBeforeAction.principalStableDebt, userDataBeforeAction.stableBorrowRate, userDataBeforeAction.stableRateLastUpdated, txTimestamp ); - const debtAccrued = stableBorrowBalance.minus(userDataBeforeAction.principalStableDebt); + expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( + reserveDataBeforeAction, + txTimestamp + ); - expectedReserveData.totalLiquidity = reserveDataBeforeAction.totalLiquidity.plus(debtAccrued); + expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( + reserveDataBeforeAction, + txTimestamp + ); + + expectedReserveData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt; + expectedReserveData.totalVariableDebt = expectedReserveData.scaledVariableDebt.rayMul( + expectedReserveData.variableBorrowIndex + ); + + expectedReserveData.principalStableDebt = expectedReserveData.totalStableDebt = calcExpectedTotalStableDebt( + reserveDataBeforeAction.principalStableDebt, + reserveDataBeforeAction.averageStableBorrowRate, + reserveDataBeforeAction.totalStableDebtLastUpdated, + txTimestamp + ); expectedReserveData.availableLiquidity = reserveDataBeforeAction.availableLiquidity; + expectedReserveData.totalLiquidity = expectedReserveData.availableLiquidity + .plus(expectedReserveData.totalStableDebt) + .plus(expectedReserveData.totalVariableDebt); + //removing the stable liquidity at the old rate const avgRateBefore = calcExpectedAverageStableBorrowRate( reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.totalStableDebt.plus(debtAccrued), - stableBorrowBalance.negated(), + expectedReserveData.totalStableDebt, + userStableDebt.negated(), userDataBeforeAction.stableBorrowRate ); // adding it again at the new rate expectedReserveData.averageStableBorrowRate = calcExpectedAverageStableBorrowRate( avgRateBefore, - reserveDataBeforeAction.totalStableDebt.minus(userDataBeforeAction.principalStableDebt), - stableBorrowBalance, + expectedReserveData.totalStableDebt.minus(userStableDebt), + userStableDebt, reserveDataBeforeAction.stableBorrowRate ); - expectedReserveData.totalVariableDebt = reserveDataBeforeAction.totalVariableDebt; - expectedReserveData.totalStableDebt = reserveDataBeforeAction.totalStableDebt.plus(debtAccrued); - expectedReserveData.utilizationRate = calcExpectedUtilizationRate( expectedReserveData.totalStableDebt, expectedReserveData.totalVariableDebt, @@ -1007,15 +1030,6 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( expectedReserveData.variableBorrowRate = rates[2]; - expectedReserveData.liquidityIndex = calcExpectedLiquidityIndex( - reserveDataBeforeAction, - txTimestamp - ); - expectedReserveData.variableBorrowIndex = calcExpectedVariableBorrowIndex( - reserveDataBeforeAction, - txTimestamp - ); - return expectedReserveData; }; diff --git a/test/helpers/utils/helpers.ts b/test/helpers/utils/helpers.ts index b98ba688..7c3dbd2a 100644 --- a/test/helpers/utils/helpers.ts +++ b/test/helpers/utils/helpers.ts @@ -25,6 +25,8 @@ export const getReserveData = async ( const variableDebtToken = await getVariableDebtToken(tokenAddresses.variableDebtTokenAddress); const [principalStableDebt] = await stableDebtToken.getSupplyData(); + const totalStableDebtLastUpdated = await stableDebtToken.getTotalSupplyLastUpdated(); + const scaledVariableDebt = await variableDebtToken.scaledTotalSupply(); @@ -57,6 +59,7 @@ export const getReserveData = async ( liquidityIndex: new BigNumber(reserveData.liquidityIndex.toString()), variableBorrowIndex: new BigNumber(reserveData.variableBorrowIndex.toString()), lastUpdateTimestamp: new BigNumber(reserveData.lastUpdateTimestamp), + totalStableDebtLastUpdated: new BigNumber(totalStableDebtLastUpdated), principalStableDebt: new BigNumber(principalStableDebt.toString()), scaledVariableDebt: new BigNumber(scaledVariableDebt.toString()), address: reserve, diff --git a/test/helpers/utils/interfaces/index.ts b/test/helpers/utils/interfaces/index.ts index 3162e398..72b30708 100644 --- a/test/helpers/utils/interfaces/index.ts +++ b/test/helpers/utils/interfaces/index.ts @@ -34,6 +34,7 @@ export interface ReserveData { aTokenAddress: string; marketStableRate: BigNumber; lastUpdateTimestamp: BigNumber; + totalStableDebtLastUpdated: BigNumber; liquidityRate: BigNumber; [key: string]: BigNumber | string; } diff --git a/test/scenario.spec.ts b/test/scenario.spec.ts index 8a14d4e2..54fe7433 100644 --- a/test/scenario.spec.ts +++ b/test/scenario.spec.ts @@ -10,7 +10,7 @@ import {executeStory} from './helpers/scenario-engine'; const scenarioFolder = './test/helpers/scenarios/'; -const selectedScenarios: string[] = ['swap-rate-mode.json']; +const selectedScenarios: string[] = []; fs.readdirSync(scenarioFolder).forEach((file) => { if (selectedScenarios.length > 0 && !selectedScenarios.includes(file)) return; From 6f9ff11e497dc5688b67a1cb8d205d439e0dbefe Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 15:35:22 +0200 Subject: [PATCH 37/45] Fixed credit delegation tests --- contracts/lendingpool/LendingPool.sol | 39 +++++++++++++++++++-------- test/helpers/actions.ts | 14 +++++----- test/helpers/utils/calculations.ts | 7 ++--- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/contracts/lendingpool/LendingPool.sol b/contracts/lendingpool/LendingPool.sol index a63f11df..53721f53 100644 --- a/contracts/lendingpool/LendingPool.sol +++ b/contracts/lendingpool/LendingPool.sol @@ -47,7 +47,6 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage uint256 public constant UINT_MAX_VALUE = uint256(-1); uint256 public constant LENDINGPOOL_REVISION = 0x2; - /** * @dev only lending pools configurator can use functions affected by this modifier **/ @@ -68,7 +67,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage function whenNotPaused() internal view { require(!_paused, Errors.IS_PAUSED); } - + function getRevision() internal override pure returns (uint256) { return LENDINGPOOL_REVISION; } @@ -248,9 +247,8 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage uint256 rateMode, address onBehalfOf ) external override { - whenNotPaused(); - + ReserveLogic.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); @@ -281,7 +279,11 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount, reserve.variableBorrowIndex); + IVariableDebtToken(reserve.variableDebtTokenAddress).burn( + onBehalfOf, + paybackAmount, + reserve.variableBorrowIndex + ); } address aToken = reserve.aTokenAddress; @@ -322,10 +324,18 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage if (interestRateMode == ReserveLogic.InterestRateMode.STABLE) { //burn stable rate tokens, mint variable rate tokens IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(msg.sender, stableDebt, reserve.variableBorrowIndex); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint( + msg.sender, + stableDebt, + reserve.variableBorrowIndex + ); } else { //do the opposite - IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt, reserve.variableBorrowIndex); + IVariableDebtToken(reserve.variableDebtTokenAddress).burn( + msg.sender, + variableDebt, + reserve.variableBorrowIndex + ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, variableDebt, @@ -372,7 +382,6 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); - reserve.updateState(); //burn old debt tokens, mint new ones @@ -502,7 +511,7 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage _flashLiquidationLocked = false; } - struct FlashLoanLocalVars { + struct FlashLoanLocalVars { uint256 premium; uint256 amountPlusPremium; IFlashLoanReceiver receiver; @@ -883,9 +892,17 @@ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage ) { currentStableRate = reserve.currentStableBorrowRate; - IStableDebtToken(reserve.stableDebtTokenAddress).mint(vars.user, vars.amount, currentStableRate); + IStableDebtToken(reserve.stableDebtTokenAddress).mint( + vars.onBehalfOf, + vars.amount, + currentStableRate + ); } else { - IVariableDebtToken(reserve.variableDebtTokenAddress).mint(vars.user, vars.amount, reserve.variableBorrowIndex); + IVariableDebtToken(reserve.variableDebtTokenAddress).mint( + vars.onBehalfOf, + vars.amount, + reserve.variableBorrowIndex + ); } reserve.updateInterestRates( diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index 44c134eb..b1e60e0d 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -369,9 +369,7 @@ export const borrow = async ( expectedReserveData, userDataBefore, txTimestamp, - timestamp, - onBehalfOf, - user.address + timestamp ); console.log("total debt stable exp ", expectedReserveData.totalStableDebt.toFixed()); @@ -381,10 +379,13 @@ export const borrow = async ( console.log("total debt variable act ", reserveDataAfter.totalVariableDebt.toFixed()); console.log("avl liquidity exp ", expectedReserveData.availableLiquidity.toFixed()); - console.log("avl liquidity exp ", reserveDataAfter.availableLiquidity.toFixed()); + console.log("avl liquidity act ", reserveDataAfter.availableLiquidity.toFixed()); console.log("avg borrow rate exp ", expectedReserveData.averageStableBorrowRate.toFixed()); - console.log("avl borrow rate exp ", reserveDataAfter.averageStableBorrowRate.toFixed()); + console.log("avl borrow rate act ", reserveDataAfter.averageStableBorrowRate.toFixed()); + + console.log("liquidity rate exp ", expectedReserveData.averageStableBorrowRate.toFixed()); + console.log("avl borrow rate act ", reserveDataAfter.averageStableBorrowRate.toFixed()); expectEqual(reserveDataAfter, expectedReserveData); @@ -487,8 +488,7 @@ export const repay = async ( user.address, onBehalfOf.address, txTimestamp, - timestamp, - txCost + timestamp ); expectEqual(reserveDataAfter, expectedReserveData); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 6d76db67..10f1127a 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -597,9 +597,7 @@ export const calcExpectedUserDataAfterBorrow = ( expectedDataAfterAction: ReserveData, userDataBeforeAction: UserReserveData, txTimestamp: BigNumber, - currentTimestamp: BigNumber, - user: tEthereumAddress, - onBehalfOf: tEthereumAddress + currentTimestamp: BigNumber ): UserReserveData => { const expectedUserData = {}; @@ -682,8 +680,7 @@ export const calcExpectedUserDataAfterRepay = ( user: string, onBehalfOf: string, txTimestamp: BigNumber, - currentTimestamp: BigNumber, - txCost: BigNumber + currentTimestamp: BigNumber ): UserReserveData => { const expectedUserData = {}; From 56be9304c24ff0f1f4246248ac45147a176bb3fd Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 15:52:53 +0200 Subject: [PATCH 38/45] Fixed rebalance rate tests --- test/helpers/actions.ts | 16 ---------------- test/helpers/utils/calculations.ts | 8 +++++++- test/upgradeability.spec.ts | 3 ++- 3 files changed, 9 insertions(+), 18 deletions(-) diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index b1e60e0d..e1b55fc9 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -372,22 +372,6 @@ export const borrow = async ( timestamp ); - console.log("total debt stable exp ", expectedReserveData.totalStableDebt.toFixed()); - console.log("total debt stable act ", reserveDataAfter.totalStableDebt.toFixed()); - - console.log("total debt variable exp ", expectedReserveData.totalVariableDebt.toFixed()); - console.log("total debt variable act ", reserveDataAfter.totalVariableDebt.toFixed()); - - console.log("avl liquidity exp ", expectedReserveData.availableLiquidity.toFixed()); - console.log("avl liquidity act ", reserveDataAfter.availableLiquidity.toFixed()); - - console.log("avg borrow rate exp ", expectedReserveData.averageStableBorrowRate.toFixed()); - console.log("avl borrow rate act ", reserveDataAfter.averageStableBorrowRate.toFixed()); - - console.log("liquidity rate exp ", expectedReserveData.averageStableBorrowRate.toFixed()); - console.log("avl borrow rate act ", reserveDataAfter.averageStableBorrowRate.toFixed()); - - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index 10f1127a..be0a8c3f 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -392,12 +392,13 @@ export const calcExpectedReserveDataAfterBorrow = ( expectedReserveData.totalLiquidity ); } else { + expectedReserveData.principalStableDebt = reserveDataBeforeAction.principalStableDebt; const totalStableDebtAfterTx = calcExpectedStableDebtTokenBalance( reserveDataBeforeAction.principalStableDebt, reserveDataBeforeAction.averageStableBorrowRate, - reserveDataBeforeAction.lastUpdateTimestamp, + reserveDataBeforeAction.totalStableDebtLastUpdated, txTimestamp ); @@ -630,7 +631,9 @@ export const calcExpectedUserDataAfterBorrow = ( ); expectedUserData.scaledVariableDebt = userDataBeforeAction.scaledVariableDebt; + } else { + expectedUserData.scaledVariableDebt = reserveDataBeforeAction.scaledVariableDebt.plus( amountBorrowedBN.rayDiv(expectedDataAfterAction.variableBorrowIndex) ); @@ -654,6 +657,7 @@ export const calcExpectedUserDataAfterBorrow = ( expectedUserData, currentTimestamp ); + expectedUserData.liquidityRate = expectedDataAfterAction.liquidityRate; expectedUserData.usageAsCollateralEnabled = userDataBeforeAction.usageAsCollateralEnabled; @@ -952,6 +956,8 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( ): ReserveData => { const expectedReserveData: ReserveData = {}; + console.log("Rebalancing"); + expectedReserveData.address = reserveDataBeforeAction.address; const userStableDebt = calcExpectedStableDebtTokenBalance( diff --git a/test/upgradeability.spec.ts b/test/upgradeability.spec.ts index 47c452bf..29f2da40 100644 --- a/test/upgradeability.spec.ts +++ b/test/upgradeability.spec.ts @@ -23,9 +23,10 @@ makeSuite('Upgradeability', (testEnv: TestEnv) => { const aTokenInstance = await deployContract(eContractid.MockAToken, [ pool.address, dai.address, + ZERO_ADDRESS, 'Aave Interest bearing DAI updated', 'aDAI', - ZERO_ADDRESS, + ZERO_ADDRESS ]); const stableDebtTokenInstance = await deployContract( From b7c4a255a96815f65287e24f7e482b0ff04b522c Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 15:58:19 +0200 Subject: [PATCH 39/45] Refactored aToken --- contracts/tokenization/AToken.sol | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index eef9ffa4..00025c05 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -20,19 +20,9 @@ import {SafeERC20} from '../misc/SafeERC20.sol'; */ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { using WadRayMath for uint256; - using SafeERC20 for IncentivizedERC20; + using SafeERC20 for IERC20; - uint256 public constant UINT_MAX_VALUE = uint256(-1); - address public immutable UNDERLYING_ASSET_ADDRESS; - address public immutable RESERVE_TREASURY_ADDRESS; - LendingPool public immutable POOL; - /// @dev owner => next valid nonce to submit with permit() - mapping(address => uint256) public _nonces; - - uint256 public constant ATOKEN_REVISION = 0x1; - - bytes32 public DOMAIN_SEPARATOR; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' @@ -41,6 +31,17 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); + uint256 public constant UINT_MAX_VALUE = uint256(-1); + uint256 public constant ATOKEN_REVISION = 0x1; + address public immutable UNDERLYING_ASSET_ADDRESS; + address public immutable RESERVE_TREASURY_ADDRESS; + LendingPool public immutable POOL; + + /// @dev owner => next valid nonce to submit with permit() + mapping(address => uint256) public _nonces; + + bytes32 public DOMAIN_SEPARATOR; + modifier onlyLendingPool { require(msg.sender == address(POOL), Errors.CALLER_MUST_BE_LENDING_POOL); _; @@ -110,7 +111,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { _burn(user, scaledAmount); //transfers the underlying to the target - IncentivizedERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount); + IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount); //transfer event to track balances emit Transfer(user, address(0), amount); @@ -239,7 +240,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { onlyLendingPool returns (uint256) { - IncentivizedERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(target, amount); + IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(target, amount); return amount; } From 8ed9b88163e51e115e9cf94b9bca98035ca0b0a4 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 16:07:26 +0200 Subject: [PATCH 40/45] fixed last tests on repayWithCollateral --- test/flash-liquidation-with-collateral.spec.ts | 6 +++--- test/helpers/actions.ts | 9 --------- test/helpers/utils/calculations.ts | 2 -- test/repay-with-collateral.spec.ts | 4 ++-- 4 files changed, 5 insertions(+), 16 deletions(-) diff --git a/test/flash-liquidation-with-collateral.spec.ts b/test/flash-liquidation-with-collateral.spec.ts index 7298cb9b..3b20f79c 100644 --- a/test/flash-liquidation-with-collateral.spec.ts +++ b/test/flash-liquidation-with-collateral.spec.ts @@ -297,7 +297,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn 'INVALID_DEBT_POSITION' ); - expect(wethUserDataAfter.currentATokenBalance).to.be.bignumber.equal( + expect(wethUserDataAfter.currentATokenBalance).to.be.bignumber.almostEqual( new BigNumber(wethUserDataBefore.currentATokenBalance).minus( expectedCollateralLiquidated.toString() ), @@ -570,7 +570,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn ); // First half - const amountToRepay = daiReserveDataBefore.totalVariableDebt.multipliedBy(0.6).toString(); + const amountToRepay = daiReserveDataBefore.totalVariableDebt.multipliedBy(0.6).toFixed(0).toString(); await mockSwapAdapter.setAmountToReturn(amountToRepay); await waitForTx( @@ -818,7 +818,7 @@ makeSuite('LendingPool. repayWithCollateral() with liquidator', (testEnv: TestEn new BigNumber(repayWithCollateralTimestamp) ).minus(usdcUserDataBefore.currentVariableDebt); - expect(usdcUserDataAfter.currentVariableDebt).to.be.bignumber.equal( + expect(usdcUserDataAfter.currentVariableDebt).to.be.bignumber.almostEqual( new BigNumber(usdcUserDataBefore.currentVariableDebt) .minus(expectedDebtCovered.toString()) .plus(expectedVariableDebtIncrease), diff --git a/test/helpers/actions.ts b/test/helpers/actions.ts index e1b55fc9..69c9c6ce 100644 --- a/test/helpers/actions.ts +++ b/test/helpers/actions.ts @@ -663,15 +663,6 @@ export const rebalanceStableBorrowRate = async ( txTimestamp ); - console.log("total debt stable exp ", expectedReserveData.totalStableDebt.toFixed()); - console.log("total debt stable act ", reserveDataAfter.totalStableDebt.toFixed()); - - console.log("total debt variable exp ", expectedReserveData.totalVariableDebt.toFixed()); - console.log("total debt variable act ", reserveDataAfter.totalVariableDebt.toFixed()); - - console.log("avl liquidity exp ", expectedReserveData.availableLiquidity.toFixed()); - console.log("avl liquidity exp ", reserveDataAfter.availableLiquidity.toFixed()); - expectEqual(reserveDataAfter, expectedReserveData); expectEqual(userDataAfter, expectedUserData); diff --git a/test/helpers/utils/calculations.ts b/test/helpers/utils/calculations.ts index be0a8c3f..7ef73c48 100644 --- a/test/helpers/utils/calculations.ts +++ b/test/helpers/utils/calculations.ts @@ -956,8 +956,6 @@ export const calcExpectedReserveDataAfterStableRateRebalance = ( ): ReserveData => { const expectedReserveData: ReserveData = {}; - console.log("Rebalancing"); - expectedReserveData.address = reserveDataBeforeAction.address; const userStableDebt = calcExpectedStableDebtTokenBalance( diff --git a/test/repay-with-collateral.spec.ts b/test/repay-with-collateral.spec.ts index 455520f5..7fe7d714 100644 --- a/test/repay-with-collateral.spec.ts +++ b/test/repay-with-collateral.spec.ts @@ -558,14 +558,14 @@ makeSuite('LendingPool. repayWithCollateral()', (testEnv: TestEnv) => { new BigNumber(repayWithCollateralTimestamp) ).minus(daiUserDataBefore.currentVariableDebt); - expect(daiUserDataAfter.currentVariableDebt).to.be.bignumber.equal( + expect(daiUserDataAfter.currentVariableDebt).to.be.bignumber.almostEqual( new BigNumber(daiUserDataBefore.currentVariableDebt) .minus(expectedDebtCovered.toString()) .plus(expectedVariableDebtIncrease), 'INVALID_VARIABLE_DEBT_POSITION' ); - expect(wethUserDataAfter.currentATokenBalance).to.be.bignumber.equal(0); + expect(wethUserDataAfter.currentATokenBalance).to.be.bignumber.almostEqual(0); expect(wethUserDataAfter.usageAsCollateralEnabled).to.be.false; }); From 2ebe34a051331ca0abc8d99f90e5b8d1b27c8745 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 16:11:14 +0200 Subject: [PATCH 41/45] removed userIndex from variabledebttoken --- contracts/tokenization/AToken.sol | 1 - contracts/tokenization/VariableDebtToken.sol | 49 +++++++++++--------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 00025c05..45f623a3 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -115,7 +115,6 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { //transfer event to track balances emit Transfer(user, address(0), amount); - emit Burn(msg.sender, receiverOfUnderlying, amount, index); } diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index feae82e0..a94f16aa 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -17,7 +17,6 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; - mapping(address => uint256) _userIndexes; constructor( address pool, @@ -41,14 +40,12 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { **/ function balanceOf(address user) public virtual override view returns (uint256) { uint256 scaledBalance = super.balanceOf(user); - + if (scaledBalance == 0) { return 0; } - return - scaledBalance - .rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); + return scaledBalance.rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); } /** @@ -57,10 +54,13 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @param amount the amount of debt being minted * @param index the variable debt index of the reserve **/ - function mint(address user, uint256 amount, uint256 index) external override onlyLendingPool { - + function mint( + address user, + uint256 amount, + uint256 index + ) external override onlyLendingPool { _mint(user, amount.rayDiv(index)); - + emit Transfer(address(0), user, amount); emit MintDebt(user, amount, index); } @@ -70,35 +70,38 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { * @param user the user which debt is burnt * @param index the variable debt index of the reserve **/ - function burn(address user, uint256 amount, uint256 index) external override onlyLendingPool { - _burn(user, amount.rayDiv(index)); - _userIndexes[user] = index; - + function burn( + address user, + uint256 amount, + uint256 index + ) external override onlyLendingPool { + _burn(user, amount.rayDiv(index)); + emit Transfer(user, address(0), amount); emit BurnDebt(user, amount, index); } /** - * @dev Returns the principal debt balance of the user from - * @return The debt balance of the user since the last burn/mint action - **/ + * @dev Returns the principal debt balance of the user from + * @return The debt balance of the user since the last burn/mint action + **/ function scaledBalanceOf(address user) public virtual override view returns (uint256) { return super.balanceOf(user); } /** - * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users - * @return the total supply - **/ - function totalSupply() public virtual override view returns(uint256) { + * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users + * @return the total supply + **/ + function totalSupply() public virtual override view returns (uint256) { return super.totalSupply().rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET)); } /** - * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) - * @return the scaled total supply - **/ - function scaledTotalSupply() public virtual override view returns(uint256) { + * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) + * @return the scaled total supply + **/ + function scaledTotalSupply() public virtual override view returns (uint256) { return super.totalSupply(); } } From 9d1c13cf960f48af7dfce0a5b61fcafddda4db42 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 17:41:38 +0200 Subject: [PATCH 42/45] added events to mintToTreasury() --- contracts/tokenization/AToken.sol | 19 +++++-- contracts/tokenization/VariableDebtToken.sol | 15 +++++- contracts/tokenization/interfaces/IAToken.sol | 45 ++-------------- .../interfaces/IScaledBalanceToken.sol | 49 +++++++++++++++++ .../interfaces/IVariableDebtToken.sol | 53 +++++-------------- 5 files changed, 93 insertions(+), 88 deletions(-) create mode 100644 contracts/tokenization/interfaces/IScaledBalanceToken.sol diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index 45f623a3..fe270785 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -22,7 +22,6 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; - bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' @@ -39,9 +38,9 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; - + bytes32 public DOMAIN_SEPARATOR; - + modifier onlyLendingPool { require(msg.sender == address(POOL), Errors.CALLER_MUST_BE_LENDING_POOL); _; @@ -140,7 +139,11 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { } function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { - _mint(RESERVE_TREASURY_ADDRESS, amount.div(index)); + _mint(RESERVE_TREASURY_ADDRESS, amount.div(index)); + + //transfer event to track balances + emit Transfer(address(0), RESERVE_TREASURY_ADDRESS, amount); + emit Mint(RESERVE_TREASURY_ADDRESS, amount, index); } /** @@ -216,6 +219,14 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { return currentSupplyScaled.rayMul(POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS)); } + /** + * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) + * @return the scaled total supply + **/ + function scaledTotalSupply() public virtual override view returns (uint256) { + return super.totalSupply(); + } + /** * @dev Used to validate transfers before actually executing them. * @param user address of the user to check diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index a94f16aa..600ef08d 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -62,7 +62,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { _mint(user, amount.rayDiv(index)); emit Transfer(address(0), user, amount); - emit MintDebt(user, amount, index); + emit Mint(user, amount, index); } /** @@ -78,7 +78,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { _burn(user, amount.rayDiv(index)); emit Transfer(user, address(0), amount); - emit BurnDebt(user, amount, index); + emit Burn(user, amount, index); } /** @@ -104,4 +104,15 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { function scaledTotalSupply() public virtual override view returns (uint256) { return super.totalSupply(); } + + /** + * @dev returns the principal balance of the user and principal total supply. + * @param user the address of the user + * @return the principal balance of the user + * @return the principal total supply + **/ + function getScaledUserBalanceAndSupply(address user) external override view returns (uint256, uint256){ + return (super.balanceOf(user), super.totalSupply()); + } + } diff --git a/contracts/tokenization/interfaces/IAToken.sol b/contracts/tokenization/interfaces/IAToken.sol index a9fbc49b..b5e182bc 100644 --- a/contracts/tokenization/interfaces/IAToken.sol +++ b/contracts/tokenization/interfaces/IAToken.sol @@ -2,8 +2,9 @@ pragma solidity ^0.6.8; import {IERC20} from '../../interfaces/IERC20.sol'; +import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; -interface IAToken is IERC20 { +interface IAToken is IERC20, IScaledBalanceToken { /** * @dev emitted after aTokens are burned * @param from the address performing the redeem @@ -16,15 +17,6 @@ interface IAToken is IERC20 { uint256 value, uint256 index ); - - /** - * @dev emitted after the mint action - * @param from the address performing the mint - * @param value the amount to be minted - * @param index the last index of the reserve - **/ - event Mint(address indexed from, uint256 value, uint256 index); - /** * @dev emitted during the transfer action * @param from the address from which the tokens are being transferred @@ -38,7 +30,6 @@ interface IAToken is IERC20 { uint256 value, uint256 index ); - /** * @dev burns the aTokens and sends the equivalent amount of underlying to the target. * only lending pools can call this function @@ -52,15 +43,6 @@ interface IAToken is IERC20 { uint256 index ) external; - /** - * @dev mints aTokens to user - * only lending pools can call this function - * @param user the address receiving the minted tokens - * @param amount the amount of tokens to mint - * @param index the liquidity index - */ - function mint(address user, uint256 amount, uint256 index) external; - /** * @dev mints aTokens to the reserve treasury * @param amount the amount to mint @@ -81,28 +63,7 @@ interface IAToken is IERC20 { uint256 value ) external; - /** - * @dev returns the principal balance of the user. The principal balance is the last - * updated stored balance, which does not consider the perpetually accruing interest. - * @param user the address of the user - * @return the principal balance of the user - **/ - function scaledBalanceOf(address user) external view returns (uint256); - - /** - * @dev returns the principal balance of the user and principal total supply. - * @param user the address of the user - * @return the principal balance of the user - * @return the principal total supply - **/ - function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); - - /** - * @dev Used to validate transfers before actually executing them. - * @param user address of the user to check - * @param amount the amount to check - * @return true if the user can transfer amount, false otherwise - **/ + function isTransferAllowed(address user, uint256 amount) external view returns (bool); /** diff --git a/contracts/tokenization/interfaces/IScaledBalanceToken.sol b/contracts/tokenization/interfaces/IScaledBalanceToken.sol new file mode 100644 index 00000000..9bcd2427 --- /dev/null +++ b/contracts/tokenization/interfaces/IScaledBalanceToken.sol @@ -0,0 +1,49 @@ + +// SPDX-License-Identifier: agpl-3.0 +pragma solidity ^0.6.8; + +interface IScaledBalanceToken { + + /** + * @dev emitted after the mint action + * @param from the address performing the mint + * @param value the amount to be minted + * @param index the last index of the reserve + **/ + event Mint(address indexed from, uint256 value, uint256 index); + + /** + * @dev mints aTokens to user + * only lending pools can call this function + * @param user the address receiving the minted tokens + * @param amount the amount of tokens to mint + * @param index the liquidity index + */ + function mint( + address user, + uint256 amount, + uint256 index + ) external; + + /** + * @dev returns the principal balance of the user. The principal balance is the last + * updated stored balance, which does not consider the perpetually accruing interest. + * @param user the address of the user + * @return the principal balance of the user + **/ + function scaledBalanceOf(address user) external view returns (uint256); + + /** + * @dev returns the principal balance of the user and principal total supply. + * @param user the address of the user + * @return the principal balance of the user + * @return the principal total supply + **/ + function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); + + /** + * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) + * @return the scaled total supply + **/ + function scaledTotalSupply() external view returns (uint256); +} diff --git a/contracts/tokenization/interfaces/IVariableDebtToken.sol b/contracts/tokenization/interfaces/IVariableDebtToken.sol index 0b680f51..2e6bae93 100644 --- a/contracts/tokenization/interfaces/IVariableDebtToken.sol +++ b/contracts/tokenization/interfaces/IVariableDebtToken.sol @@ -1,63 +1,36 @@ // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; +import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; + /** * @title interface IVariableDebtToken * @author Aave * @notice defines the basic interface for a variable debt token. - * @dev does not inherit from IERC20 to save in contract size **/ -interface IVariableDebtToken { - /** - * @dev emitted when new variable debt is minted - * @param user the user receiving the debt - * @param amount the amount of debt being minted - * @param index the index of the user - **/ - event MintDebt( - address user, - uint256 amount, - uint256 index - ); - +interface IVariableDebtToken is IScaledBalanceToken { + /** * @dev emitted when variable debt is burnt * @param user the user which debt has been burned * @param amount the amount of debt being burned * @param index the index of the user **/ - event BurnDebt( - address user, + event Burn( + address indexed user, uint256 amount, uint256 index ); - /** - * @dev mints new variable debt - * @param user the user receiving the debt - * @param amount the amount of debt being minted - * @param index the variable debt index of the reserve - **/ - function mint(address user, uint256 amount, uint256 index) external; - - /** + /** * @dev burns user variable debt * @param user the user which debt is burnt - * @param amount the amount of debt being burned * @param index the variable debt index of the reserve **/ - function burn(address user, uint256 amount, uint256 index) external; - - /** - * @dev returns the scaled balance of the variable debt token - * @param user the user - **/ - function scaledBalanceOf(address user) external view returns(uint256); - - /** - * @dev Returns the scaled total supply of the variable debt token. Represents sum(borrows/index) - * @return the scaled total supply - **/ - function scaledTotalSupply() external view returns(uint256); - + function burn( + address user, + uint256 amount, + uint256 index + ) external; + } From e348c334e3d05cc3cd1e614f1f3903a88f3bc8d2 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 17:58:02 +0200 Subject: [PATCH 43/45] Cleaned up aToken, debt tokens code --- contracts/tokenization/AToken.sol | 32 +++++++++++--------- contracts/tokenization/VariableDebtToken.sol | 1 + deployed-contracts.json | 17 ++++++----- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/contracts/tokenization/AToken.sol b/contracts/tokenization/AToken.sol index fe270785..98c54bcd 100644 --- a/contracts/tokenization/AToken.sol +++ b/contracts/tokenization/AToken.sol @@ -101,13 +101,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { uint256 amount, uint256 index ) external override onlyLendingPool { - uint256 currentBalance = balanceOf(user); - - require(amount <= currentBalance, Errors.INVALID_ATOKEN_BALANCE); - - uint256 scaledAmount = amount.rayDiv(index); - - _burn(user, scaledAmount); + _burn(user, amount.rayDiv(index)); //transfers the underlying to the target IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount); @@ -128,10 +122,8 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { uint256 amount, uint256 index ) external override onlyLendingPool { - uint256 scaledAmount = amount.rayDiv(index); - //mint an equivalent amount of tokens to cover the new deposit - _mint(user, scaledAmount); + _mint(user, amount.rayDiv(index)); //transfer event to track balances emit Transfer(address(0), user, amount); @@ -140,7 +132,7 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { _mint(RESERVE_TREASURY_ADDRESS, amount.div(index)); - + //transfer event to track balances emit Transfer(address(0), RESERVE_TREASURY_ADDRESS, amount); emit Mint(RESERVE_TREASURY_ADDRESS, amount, index); @@ -289,6 +281,14 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { _approve(owner, spender, value); } + /** + * @dev transfers the aTokens between two users. Validates the transfer + * (ie checks for valid HF after the transfer) if required + * @param from the source address + * @param to the destination address + * @param amount the amount to transfer + * @param validate true if the transfer needs to be validated + **/ function _transfer( address from, address to, @@ -301,13 +301,17 @@ contract AToken is VersionedInitializable, IncentivizedERC20, IAToken { uint256 index = POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); - uint256 scaledAmount = amount.rayDiv(index); - - super._transfer(from, to, scaledAmount); + super._transfer(from, to, amount.rayDiv(index)); emit BalanceTransfer(from, to, amount, index); } + /** + * @dev overrides the parent _transfer to force validated transfer() and transferFrom() + * @param from the source address + * @param to the destination address + * @param amount the amount to transfer + **/ function _transfer( address from, address to, diff --git a/contracts/tokenization/VariableDebtToken.sol b/contracts/tokenization/VariableDebtToken.sol index 600ef08d..5e0f2dff 100644 --- a/contracts/tokenization/VariableDebtToken.sol +++ b/contracts/tokenization/VariableDebtToken.sol @@ -59,6 +59,7 @@ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { uint256 amount, uint256 index ) external override onlyLendingPool { + _mint(user, amount.rayDiv(index)); emit Transfer(address(0), user, amount); diff --git a/deployed-contracts.json b/deployed-contracts.json index daecd72c..dd305039 100644 --- a/deployed-contracts.json +++ b/deployed-contracts.json @@ -65,7 +65,7 @@ "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" }, "localhost": { - "address": "0x65e0Cd5B8904A02f2e00BC6f58bf881998D54BDe" + "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" }, "coverage": { "address": "0x6642B57e4265BAD868C17Fc1d1F4F88DBBA04Aa8" @@ -81,7 +81,7 @@ "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" }, "localhost": { - "address": "0x5d12dDe3286D94E0d85F9D3B01B7099cfA0aBCf1" + "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" }, "coverage": { "address": "0xD9273d497eDBC967F39d419461CfcF382a0A822e" @@ -207,7 +207,7 @@ "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" }, "localhost": { - "address": "0xAd49512dFBaD6fc13D67d3935283c0606812E962" + "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" }, "coverage": { "address": "0x2B681757d757fbB80cc51c6094cEF5eE75bF55aA" @@ -554,7 +554,7 @@ "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" }, "localhost": { - "address": "0x9305d862ee95a899b83906Cd9CB666aC269E5f66" + "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" }, "coverage": { "address": "0x2cfcA5785261fbC88EFFDd46fCFc04c22525F9e4" @@ -608,7 +608,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xFBdF1E93D0D88145e3CcA63bf8d513F83FB0903b", + "address": "0xEcb928A3c079a1696Aa5244779eEc3dE1717fACd", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "coverage": { @@ -636,7 +636,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0xE45fF4A0A8D0E9734C73874c034E03594E15ba28", + "address": "0xDFbeeed692AA81E7f86E72F7ACbEA2A1C4d63544", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "coverage": { @@ -650,7 +650,7 @@ "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "localhost": { - "address": "0x5cCC6Abc4c9F7262B9485797a848Ec6CC28A11dF", + "address": "0x5191aA68c7dB195181Dd2441dBE23A48EA24b040", "deployer": "0xc783df8a850f42e7F7e57013759C285caa701eB6" }, "coverage": { @@ -664,6 +664,9 @@ }, "coverage": { "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" + }, + "localhost": { + "address": "0xBEF0d4b9c089a5883741fC14cbA352055f35DDA2" } } } \ No newline at end of file From c278832e5a32dd0208464fe1680ee1ba659215fd Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 17:59:44 +0200 Subject: [PATCH 44/45] Removed unused error code --- contracts/libraries/helpers/Errors.sol | 1 - 1 file changed, 1 deletion(-) diff --git a/contracts/libraries/helpers/Errors.sol b/contracts/libraries/helpers/Errors.sol index d25b041b..4f3f6daa 100644 --- a/contracts/libraries/helpers/Errors.sol +++ b/contracts/libraries/helpers/Errors.sol @@ -48,7 +48,6 @@ library Errors { string public constant CALLER_MUST_BE_LENDING_POOL = '28'; // 'The caller of this function must be a lending pool' string public constant CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' - string public constant INVALID_ATOKEN_BALANCE = '52'; // balance on burning is invalid // require error messages - ReserveLogic string public constant RESERVE_ALREADY_INITIALIZED = '34'; // 'Reserve has already been initialized' From c346251df03b192897215c6185870e0aa982a134 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 21 Sep 2020 18:51:51 +0200 Subject: [PATCH 45/45] Added comments --- contracts/libraries/logic/ReserveLogic.sol | 52 ++++++++++++------- contracts/tokenization/StableDebtToken.sol | 6 +-- .../interfaces/IStableDebtToken.sol | 2 +- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/contracts/libraries/logic/ReserveLogic.sol b/contracts/libraries/logic/ReserveLogic.sol index e5eac57a..8f6069ab 100644 --- a/contracts/libraries/logic/ReserveLogic.sol +++ b/contracts/libraries/logic/ReserveLogic.sol @@ -148,28 +148,23 @@ library ReserveLogic { * @param reserve the reserve object **/ function updateState(ReserveData storage reserve) external { - address stableDebtToken = reserve.stableDebtTokenAddress; address variableDebtToken = reserve.variableDebtTokenAddress; uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; - uint40 timestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, variableDebtToken, previousLiquidityIndex, - previousVariableBorrowIndex, - timestamp + previousVariableBorrowIndex ); _mintToTreasury( reserve, - stableDebtToken, variableDebtToken, previousVariableBorrowIndex, newLiquidityIndex, - newVariableBorrowIndex, - timestamp + newVariableBorrowIndex ); } @@ -299,16 +294,24 @@ library ReserveLogic { uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; + uint40 stableSupplyUpdatedTimestamp; } + /** + * @dev mints part of the repaid interest to the reserve treasury, depending on the reserveFactor for the + * specific asset. + * @param reserve the reserve reserve to be updated + * @param variableDebtToken the debt token address + * @param previousVariableBorrowIndex the variable borrow index before the last accumulation of the interest + * @param newLiquidityIndex the new liquidity index + * @param newVariableBorrowIndex the variable borrow index after the last accumulation of the interest + **/ function _mintToTreasury( ReserveData storage reserve, - address stableDebtToken, address variableDebtToken, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, - uint256 newVariableBorrowIndex, - uint40 previousTimestamp + uint256 newVariableBorrowIndex ) internal { MintToTreasuryLocalVars memory vars; @@ -322,10 +325,12 @@ library ReserveLogic { vars.scaledVariableDebt = IVariableDebtToken(variableDebtToken).scaledTotalSupply(); //fetching the principal, total stable debt and the avg stable rate - (vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate) = IStableDebtToken( - stableDebtToken - ) - .getSupplyData(); + ( + vars.principalStableDebt, + vars.currentStableDebt, + vars.avgStableRate, + vars.stableSupplyUpdatedTimestamp + ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = vars.scaledVariableDebt.rayMul(previousVariableBorrowIndex); @@ -336,7 +341,7 @@ library ReserveLogic { //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, - previousTimestamp + vars.stableSupplyUpdatedTimestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); @@ -353,13 +358,22 @@ library ReserveLogic { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } + /** + * @dev updates the reserve indexes and the timestamp of the update + * @param reserve the reserve reserve to be updated + * @param variableDebtToken the debt token address + * @param liquidityIndex the last stored liquidity index + * @param variableBorrowIndex the last stored variable borrow index + **/ function _updateIndexes( ReserveData storage reserve, address variableDebtToken, uint256 liquidityIndex, - uint256 variableBorrowIndex, - uint40 lastUpdateTimestamp + uint256 variableBorrowIndex ) internal returns (uint256, uint256) { + + uint40 timestamp = reserve.lastUpdateTimestamp; + uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; @@ -369,7 +383,7 @@ library ReserveLogic { if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest( currentLiquidityRate, - lastUpdateTimestamp + timestamp ); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex < (1 << 128), Errors.LIQUIDITY_INDEX_OVERFLOW); @@ -381,7 +395,7 @@ library ReserveLogic { if (IERC20(variableDebtToken).totalSupply() > 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( reserve.currentVariableBorrowRate, - lastUpdateTimestamp + timestamp ); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require(newVariableBorrowIndex < (1 << 128), Errors.VARIABLE_BORROW_INDEX_OVERFLOW); diff --git a/contracts/tokenization/StableDebtToken.sol b/contracts/tokenization/StableDebtToken.sol index fe352b32..1974d51e 100644 --- a/contracts/tokenization/StableDebtToken.sol +++ b/contracts/tokenization/StableDebtToken.sol @@ -237,11 +237,11 @@ contract StableDebtToken is IStableDebtToken, DebtTokenBase { } /** - * @dev returns the principal, total supply and the average borrow rate + * @dev returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ - function getSupplyData() public override view returns (uint256, uint256, uint256) { + function getSupplyData() public override view returns (uint256, uint256, uint256,uint40) { uint256 avgRate = _avgStableRate; - return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate); + return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** diff --git a/contracts/tokenization/interfaces/IStableDebtToken.sol b/contracts/tokenization/interfaces/IStableDebtToken.sol index 0e75bae4..901a1178 100644 --- a/contracts/tokenization/interfaces/IStableDebtToken.sol +++ b/contracts/tokenization/interfaces/IStableDebtToken.sol @@ -88,7 +88,7 @@ interface IStableDebtToken { /** * @dev returns the principal, the total supply and the average stable rate **/ - function getSupplyData() external view returns (uint256, uint256, uint256); + function getSupplyData() external view returns (uint256, uint256, uint256, uint40); /** * @dev returns the timestamp of the last update of the total supply