Updated libraries, renamed internal methods

This commit is contained in:
The3D 2020-08-21 18:18:12 +02:00
parent 78cf1d5bfd
commit 1864c7abf4
12 changed files with 199 additions and 205 deletions

View File

@ -52,7 +52,7 @@ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider
* @param pool the new lending pool implementation * @param pool the new lending pool implementation
**/ **/
function setLendingPoolImpl(address pool) external override onlyOwner { function setLendingPoolImpl(address pool) external override onlyOwner {
updateImplInternal(LENDING_POOL, pool); _updateImpl(LENDING_POOL, pool);
emit LendingPoolUpdated(pool); emit LendingPoolUpdated(pool);
} }
@ -69,7 +69,7 @@ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider
* @param configurator the new lending pool configurator implementation * @param configurator the new lending pool configurator implementation
**/ **/
function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner {
updateImplInternal(LENDING_POOL_CONFIGURATOR, configurator); _updateImpl(LENDING_POOL_CONFIGURATOR, configurator);
emit LendingPoolConfiguratorUpdated(configurator); emit LendingPoolConfiguratorUpdated(configurator);
} }
@ -130,7 +130,7 @@ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider
* @param id the id of the contract to be updated * @param id the id of the contract to be updated
* @param newAddress the address of the new implementation * @param newAddress the address of the new implementation
**/ **/
function updateImplInternal(bytes32 id, address newAddress) internal { function _updateImpl(bytes32 id, address newAddress) internal {
address payable proxyAddress = payable(_addresses[id]); address payable proxyAddress = payable(_addresses[id]);
InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy( InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(

View File

@ -56,7 +56,7 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP
**/ **/
function registerAddressesProvider(address _provider, uint256 _id) public override onlyOwner { function registerAddressesProvider(address _provider, uint256 _id) public override onlyOwner {
addressesProviders[_provider] = _id; addressesProviders[_provider] = _id;
addToAddressesProvidersListInternal(_provider); _addToAddressesProvidersList(_provider);
emit AddressesProviderRegistered(_provider); emit AddressesProviderRegistered(_provider);
} }
@ -74,7 +74,7 @@ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesP
* @dev adds to the list of the addresses providers, if it wasn't already added before * @dev adds to the list of the addresses providers, if it wasn't already added before
* @param _provider the pool address to be added * @param _provider the pool address to be added
**/ **/
function addToAddressesProvidersListInternal(address _provider) internal { function _addToAddressesProvidersList(address _provider) internal {
for (uint256 i = 0; i < addressesProvidersList.length; i++) { for (uint256 i = 0; i < addressesProvidersList.length; i++) {
if (addressesProvidersList[i] == _provider) { if (addressesProvidersList[i] == _provider) {
return; return;

View File

@ -20,15 +20,15 @@ abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
receive() external payable {} receive() external payable {}
function transferFundsBackInternal( function _transferFundsBack(
address _reserve, address _reserve,
address _destination, address _destination,
uint256 _amount uint256 _amount
) internal { ) internal {
transferInternal(_destination, _reserve, _amount); _transfer(_destination, _reserve, _amount);
} }
function transferInternal( function _transfer(
address _destination, address _destination,
address _reserve, address _reserve,
uint256 _amount uint256 _amount

View File

@ -149,7 +149,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {
); );
} }
currentLiquidityRate = getOverallBorrowRateInternal( currentLiquidityRate = _getOverallBorrowRate(
totalBorrowsStable, totalBorrowsStable,
totalBorrowsVariable, totalBorrowsVariable,
currentVariableBorrowRate, currentVariableBorrowRate,
@ -170,7 +170,7 @@ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {
* @param currentAverageStableBorrowRate the weighted average of all the stable rate borrows * @param currentAverageStableBorrowRate the weighted average of all the stable rate borrows
* @return the weighted averaged borrow rate * @return the weighted averaged borrow rate
**/ **/
function getOverallBorrowRateInternal( function _getOverallBorrowRate(
uint256 totalBorrowsStable, uint256 totalBorrowsStable,
uint256 totalBorrowsVariable, uint256 totalBorrowsVariable,
uint256 currentVariableBorrowRate, uint256 currentVariableBorrowRate,

View File

@ -377,11 +377,11 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool {
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(_onBehalfOf, reserve); (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(_onBehalfOf, reserve);
ReserveLogic.InterestRateMode rateMode = ReserveLogic.InterestRateMode(_rateMode); ReserveLogic.InterestRateMode rateMode = ReserveLogic.InterestRateMode(_rateMode);
//default to max amount //default to max amount
uint256 paybackAmount = rateMode == ReserveLogic.InterestRateMode.STABLE uint256 paybackAmount = rateMode == ReserveLogic.InterestRateMode.STABLE
? stableDebt ? IERC20(reserve.stableDebtTokenAddress).balanceOf(_onBehalfOf)
: variableDebt; : IERC20(reserve.variableDebtTokenAddress).balanceOf(_onBehalfOf);
if (amount != UINT_MAX_VALUE && amount < paybackAmount) { if (amount != UINT_MAX_VALUE && amount < paybackAmount) {
paybackAmount = amount; paybackAmount = amount;
@ -389,13 +389,11 @@ contract LendingPool is ReentrancyGuard, VersionedInitializable, ILendingPool {
ValidationLogic.validateRepay( ValidationLogic.validateRepay(
reserve, reserve,
asset,
amount, amount,
rateMode, rateMode,
_onBehalfOf, _onBehalfOf,
stableDebt, stableDebt,
variableDebt, variableDebt
paybackAmount
); );
reserve.updateCumulativeIndexesAndTimestamp(); reserve.updateCumulativeIndexesAndTimestamp();

View File

@ -178,8 +178,8 @@ library ReserveLogic {
function init( function init(
ReserveData storage reserve, ReserveData storage reserve,
address aTokenAddress, address aTokenAddress,
address _stableDebtAddress, address stableDebtTokenAddress,
address _variableDebtAddress, address variableDebtTokenAddress,
address interestRateStrategyAddress address interestRateStrategyAddress
) external { ) external {
require(reserve.aTokenAddress == address(0), 'Reserve has already been initialized'); require(reserve.aTokenAddress == address(0), 'Reserve has already been initialized');
@ -193,8 +193,8 @@ library ReserveLogic {
} }
reserve.aTokenAddress = aTokenAddress; reserve.aTokenAddress = aTokenAddress;
reserve.stableDebtTokenAddress = _stableDebtAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress;
reserve.variableDebtTokenAddress = _variableDebtAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress;
} }
@ -202,14 +202,14 @@ library ReserveLogic {
* @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl. * @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl.
* Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information. * Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information.
* @param reserve the address of the reserve to be updated * @param reserve the address of the reserve to be updated
* @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow) * @param liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow)
**/ **/
function updateInterestRates( function updateInterestRates(
ReserveData storage reserve, ReserveData storage reserve,
address reserveAddress, address reserveAddress,
uint256 _liquidityAdded, uint256 liquidityAdded,
uint256 _liquidityTaken uint256 liquidityTaken
) internal { ) internal {
uint256 currentAvgStableRate = IStableDebtToken(reserve.stableDebtTokenAddress) uint256 currentAvgStableRate = IStableDebtToken(reserve.stableDebtTokenAddress)
.getAverageStableRate(); .getAverageStableRate();
@ -222,7 +222,7 @@ library ReserveLogic {
uint256 newVariableRate uint256 newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress, reserveAddress,
balance.add(_liquidityAdded).sub(_liquidityTaken), balance.add(liquidityAdded).sub(liquidityTaken),
IERC20(reserve.stableDebtTokenAddress).totalSupply(), IERC20(reserve.stableDebtTokenAddress).totalSupply(),
IERC20(reserve.variableDebtTokenAddress).totalSupply(), IERC20(reserve.variableDebtTokenAddress).totalSupply(),
currentAvgStableRate currentAvgStableRate

View File

@ -29,54 +29,54 @@ library ValidationLogic {
/** /**
* @dev validates a deposit. * @dev validates a deposit.
* @param _reserve the reserve state on which the user is depositing * @param reserve the reserve state on which the user is depositing
* @param _amount the amount to be deposited * @param amount the amount to be deposited
*/ */
function validateDeposit(ReserveLogic.ReserveData storage _reserve, uint256 _amount) function validateDeposit(ReserveLogic.ReserveData storage reserve, uint256 amount)
internal internal
view view
{ {
(bool isActive, bool isFreezed, , ) = _reserve.configuration.getFlags(); (bool isActive, bool isFreezed, , ) = reserve.configuration.getFlags();
require(_amount > 0, 'Amount must be greater than 0'); require(amount > 0, 'Amount must be greater than 0');
require(isActive, 'Action requires an active reserve'); require(isActive, 'Action requires an active reserve');
require(!isFreezed, 'Action requires an unfreezed reserve'); require(!isFreezed, 'Action requires an unfreezed reserve');
} }
/** /**
* @dev validates a withdraw action. * @dev validates a withdraw action.
* @param _reserveAddress the address of the reserve * @param reserveAddress the address of the reserve
* @param _aTokenAddress the address of the aToken for the reserve * @param aTokenAddress the address of the aToken for the reserve
* @param _amount the amount to be withdrawn * @param amount the amount to be withdrawn
* @param _userBalance the balance of the user * @param userBalance the balance of the user
*/ */
function validateWithdraw( function validateWithdraw(
address _reserveAddress, address reserveAddress,
address _aTokenAddress, address aTokenAddress,
uint256 _amount, uint256 amount,
uint256 _userBalance, uint256 userBalance,
mapping(address => ReserveLogic.ReserveData) storage _reservesData, mapping(address => ReserveLogic.ReserveData) storage reservesData,
UserConfiguration.Map storage _userConfig, UserConfiguration.Map storage userConfig,
address[] calldata _reserves, address[] calldata reserves,
address _oracle address oracle
) external view { ) external view {
require(_amount > 0, 'Amount must be greater than 0'); require(amount > 0, 'Amount must be greater than 0');
uint256 currentAvailableLiquidity = IERC20(_reserveAddress).balanceOf(address(_aTokenAddress)); uint256 currentAvailableLiquidity = IERC20(reserveAddress).balanceOf(address(aTokenAddress));
require(currentAvailableLiquidity >= _amount, '4'); require(currentAvailableLiquidity >= amount, '4');
require(_amount <= _userBalance, 'User cannot withdraw more than the available balance'); require(amount <= userBalance, 'User cannot withdraw more than the available balance');
require( require(
GenericLogic.balanceDecreaseAllowed( GenericLogic.balanceDecreaseAllowed(
_reserveAddress, reserveAddress,
msg.sender, msg.sender,
_userBalance, userBalance,
_reservesData, reservesData,
_userConfig, userConfig,
_reserves, reserves,
_oracle oracle
), ),
'Transfer cannot be allowed.' 'Transfer cannot be allowed.'
); );
@ -105,29 +105,29 @@ library ValidationLogic {
/** /**
* @dev validates a borrow. * @dev validates a borrow.
* @param _reserve the reserve state from which the user is borrowing * @param reserve the reserve state from which the user is borrowing
* @param _reserveAddress the address of the reserve * @param reserveAddress the address of the reserve
* @param _amount the amount to be borrowed * @param amount the amount to be borrowed
* @param _amountInETH the amount to be borrowed, in ETH * @param amountInETH the amount to be borrowed, in ETH
* @param _interestRateMode the interest rate mode at which the user is borrowing * @param interestRateMode the interest rate mode at which the user is borrowing
* @param _maxStableLoanPercent the max amount of the liquidity that can be borrowed at stable rate, in percentage * @param maxStableLoanPercent the max amount of the liquidity that can be borrowed at stable rate, in percentage
* @param _reservesData the state of all the reserves * @param reservesData the state of all the reserves
* @param _userConfig the state of the user for the specific reserve * @param userConfig the state of the user for the specific reserve
* @param _reserves the addresses of all the active reserves * @param reserves the addresses of all the active reserves
* @param _oracle the price oracle * @param oracle the price oracle
*/ */
function validateBorrow( function validateBorrow(
ReserveLogic.ReserveData storage _reserve, ReserveLogic.ReserveData storage reserve,
address _reserveAddress, address reserveAddress,
uint256 _amount, uint256 amount,
uint256 _amountInETH, uint256 amountInETH,
uint256 _interestRateMode, uint256 interestRateMode,
uint256 _maxStableLoanPercent, uint256 maxStableLoanPercent,
mapping(address => ReserveLogic.ReserveData) storage _reservesData, mapping(address => ReserveLogic.ReserveData) storage reservesData,
UserConfiguration.Map storage _userConfig, UserConfiguration.Map storage userConfig,
address[] calldata _reserves, address[] calldata reserves,
address _oracle address oracle
) external view { ) external view {
ValidateBorrowLocalVars memory vars; ValidateBorrowLocalVars memory vars;
@ -136,7 +136,7 @@ library ValidationLogic {
vars.isFreezed, vars.isFreezed,
vars.borrowingEnabled, vars.borrowingEnabled,
vars.stableRateBorrowingEnabled vars.stableRateBorrowingEnabled
) = _reserve.configuration.getFlags(); ) = reserve.configuration.getFlags();
require(vars.isActive, 'Action requires an active reserve'); require(vars.isActive, 'Action requires an active reserve');
require(!vars.isFreezed, 'Action requires an unfreezed reserve'); require(!vars.isFreezed, 'Action requires an unfreezed reserve');
@ -145,15 +145,15 @@ library ValidationLogic {
//validate interest rate mode //validate interest rate mode
require( require(
uint256(ReserveLogic.InterestRateMode.VARIABLE) == _interestRateMode || uint256(ReserveLogic.InterestRateMode.VARIABLE) == interestRateMode ||
uint256(ReserveLogic.InterestRateMode.STABLE) == _interestRateMode, uint256(ReserveLogic.InterestRateMode.STABLE) == interestRateMode,
'Invalid interest rate mode selected' 'Invalid interest rate mode selected'
); );
//check that the amount is available in the reserve //check that the amount is available in the reserve
vars.availableLiquidity = IERC20(_reserveAddress).balanceOf(address(_reserve.aTokenAddress)); vars.availableLiquidity = IERC20(reserveAddress).balanceOf(address(reserve.aTokenAddress));
require(vars.availableLiquidity >= _amount, '7'); require(vars.availableLiquidity >= amount, '7');
( (
vars.userCollateralBalanceETH, vars.userCollateralBalanceETH,
@ -163,10 +163,10 @@ library ValidationLogic {
vars.healthFactor vars.healthFactor
) = GenericLogic.calculateUserAccountData( ) = GenericLogic.calculateUserAccountData(
msg.sender, msg.sender,
_reservesData, reservesData,
_userConfig, userConfig,
_reserves, reserves,
_oracle oracle
); );
require(vars.userCollateralBalanceETH > 0, 'The collateral balance is 0'); require(vars.userCollateralBalanceETH > 0, 'The collateral balance is 0');
@ -174,7 +174,7 @@ library ValidationLogic {
require(vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, '8'); require(vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, '8');
//add the current already borrowed amount to the amount requested to calculate the total collateral needed. //add the current already borrowed amount to the amount requested to calculate the total collateral needed.
vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(_amountInETH).percentDiv( vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv(
vars.currentLtv vars.currentLtv
); //LTV is calculated in percentage ); //LTV is calculated in percentage
@ -198,88 +198,84 @@ library ValidationLogic {
require(vars.stableRateBorrowingEnabled, '11'); require(vars.stableRateBorrowingEnabled, '11');
require( require(
!_userConfig.isUsingAsCollateral(_reserve.index) || !userConfig.isUsingAsCollateral(reserve.index) ||
_reserve.configuration.getLtv() == 0 || reserve.configuration.getLtv() == 0 ||
_amount > IERC20(_reserve.aTokenAddress).balanceOf(msg.sender), amount > IERC20(reserve.aTokenAddress).balanceOf(msg.sender),
'12' '12'
); );
//calculate the max available loan size in stable rate mode as a percentage of the //calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity //available liquidity
uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(_maxStableLoanPercent); uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(_amount <= maxLoanSizeStable, '13'); require(amount <= maxLoanSizeStable, '13');
} }
} }
/** /**
* @dev validates a repay. * @dev validates a repay.
* @param _reserve the reserve state from which the user is repaying * @param reserve the reserve state from which the user is repaying
* @param _reserveAddress the address of the reserve * @param amountSent the amount sent for the repayment. Can be an actual value or uint(-1)
* @param _amountSent the amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf the address of the user msg.sender is repaying for
* @param _onBehalfOf the address of the user msg.sender is repaying for * @param stableBorrowBalance the borrow balance of the user
* @param _stableBorrowBalance the borrow balance of the user * @param variableBorrowBalance the borrow balance of the user
* @param _variableBorrowBalance the borrow balance of the user
* @param _actualPaybackAmount the actual amount being repaid
*/ */
function validateRepay( function validateRepay(
ReserveLogic.ReserveData storage _reserve, ReserveLogic.ReserveData storage reserve,
address _reserveAddress, uint256 amountSent,
uint256 _amountSent, ReserveLogic.InterestRateMode rateMode,
ReserveLogic.InterestRateMode _rateMode, address onBehalfOf,
address _onBehalfOf, uint256 stableBorrowBalance,
uint256 _stableBorrowBalance, uint256 variableBorrowBalance
uint256 _variableBorrowBalance,
uint256 _actualPaybackAmount
) external view { ) external view {
bool isActive = _reserve.configuration.getActive(); bool isActive = reserve.configuration.getActive();
require(isActive, 'Action requires an active reserve'); require(isActive, 'Action requires an active reserve');
require(_amountSent > 0, 'Amount must be greater than 0'); require(amountSent > 0, 'Amount must be greater than 0');
require( require(
(_stableBorrowBalance > 0 && (stableBorrowBalance > 0 &&
ReserveLogic.InterestRateMode(_rateMode) == ReserveLogic.InterestRateMode.STABLE) || ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.STABLE) ||
(_variableBorrowBalance > 0 && (variableBorrowBalance > 0 &&
ReserveLogic.InterestRateMode(_rateMode) == ReserveLogic.InterestRateMode.VARIABLE), ReserveLogic.InterestRateMode(rateMode) == ReserveLogic.InterestRateMode.VARIABLE),
'16' '16'
); );
require( require(
_amountSent != uint256(-1) || msg.sender == _onBehalfOf, amountSent != uint256(-1) || msg.sender == onBehalfOf,
'To repay on behalf of an user an explicit amount to repay is needed' 'To repay on behalf of an user an explicit amount to repay is needed'
); );
} }
/** /**
* @dev validates a swap of borrow rate mode. * @dev validates a swap of borrow rate mode.
* @param _reserve the reserve state on which the user is swapping the rate * @param reserve the reserve state on which the user is swapping the rate
* @param _userConfig the user reserves configuration * @param userConfig the user reserves configuration
* @param _stableBorrowBalance the stable borrow balance of the user * @param stableBorrowBalance the stable borrow balance of the user
* @param _variableBorrowBalance the stable borrow balance of the user * @param variableBorrowBalance the stable borrow balance of the user
* @param _currentRateMode the rate mode of the borrow * @param currentRateMode the rate mode of the borrow
*/ */
function validateSwapRateMode( function validateSwapRateMode(
ReserveLogic.ReserveData storage _reserve, ReserveLogic.ReserveData storage reserve,
UserConfiguration.Map storage _userConfig, UserConfiguration.Map storage userConfig,
uint256 _stableBorrowBalance, uint256 stableBorrowBalance,
uint256 _variableBorrowBalance, uint256 variableBorrowBalance,
ReserveLogic.InterestRateMode _currentRateMode ReserveLogic.InterestRateMode currentRateMode
) external view { ) external view {
(bool isActive, bool isFreezed, , bool stableRateEnabled) = _reserve.configuration.getFlags(); (bool isActive, bool isFreezed, , bool stableRateEnabled) = reserve.configuration.getFlags();
require(isActive, 'Action requires an active reserve'); require(isActive, 'Action requires an active reserve');
require(!isFreezed, 'Action requires an unfreezed reserve'); require(!isFreezed, 'Action requires an unfreezed reserve');
if (_currentRateMode == ReserveLogic.InterestRateMode.STABLE) { if (currentRateMode == ReserveLogic.InterestRateMode.STABLE) {
require( require(
_stableBorrowBalance > 0, stableBorrowBalance > 0,
'User does not have a stable rate loan in progress on this reserve' 'User does not have a stable rate loan in progress on this reserve'
); );
} else if (_currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) { } else if (currentRateMode == ReserveLogic.InterestRateMode.VARIABLE) {
require( require(
_variableBorrowBalance > 0, variableBorrowBalance > 0,
'User does not have a variable rate loan in progress on this reserve' 'User does not have a variable rate loan in progress on this reserve'
); );
/** /**
@ -292,10 +288,10 @@ library ValidationLogic {
require(stableRateEnabled, '11'); require(stableRateEnabled, '11');
require( require(
!_userConfig.isUsingAsCollateral(_reserve.index) || !userConfig.isUsingAsCollateral(reserve.index) ||
_reserve.configuration.getLtv() == 0 || reserve.configuration.getLtv() == 0 ||
_stableBorrowBalance.add(_variableBorrowBalance) > stableBorrowBalance.add(variableBorrowBalance) >
IERC20(_reserve.aTokenAddress).balanceOf(msg.sender), IERC20(reserve.aTokenAddress).balanceOf(msg.sender),
'12' '12'
); );
} else { } else {
@ -305,34 +301,34 @@ library ValidationLogic {
/** /**
* @dev validates the choice of a user of setting (or not) an asset as collateral * @dev validates the choice of a user of setting (or not) an asset as collateral
* @param _reserve the state of the reserve that the user is enabling or disabling as collateral * @param reserve the state of the reserve that the user is enabling or disabling as collateral
* @param _reserveAddress the address of the reserve * @param reserveAddress the address of the reserve
* @param _reservesData the data of all the reserves * @param reservesData the data of all the reserves
* @param _userConfig the state of the user for the specific reserve * @param userConfig the state of the user for the specific reserve
* @param _reserves the addresses of all the active reserves * @param reserves the addresses of all the active reserves
* @param _oracle the price oracle * @param oracle the price oracle
*/ */
function validateSetUseReserveAsCollateral( function validateSetUseReserveAsCollateral(
ReserveLogic.ReserveData storage _reserve, ReserveLogic.ReserveData storage reserve,
address _reserveAddress, address reserveAddress,
mapping(address => ReserveLogic.ReserveData) storage _reservesData, mapping(address => ReserveLogic.ReserveData) storage reservesData,
UserConfiguration.Map storage _userConfig, UserConfiguration.Map storage userConfig,
address[] calldata _reserves, address[] calldata reserves,
address _oracle address oracle
) external view { ) external view {
uint256 underlyingBalance = IERC20(_reserve.aTokenAddress).balanceOf(msg.sender); uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender);
require(underlyingBalance > 0, '22'); require(underlyingBalance > 0, '22');
require( require(
GenericLogic.balanceDecreaseAllowed( GenericLogic.balanceDecreaseAllowed(
_reserveAddress, reserveAddress,
msg.sender, msg.sender,
underlyingBalance, underlyingBalance,
_reservesData, reservesData,
_userConfig, userConfig,
_reserves, reserves,
_oracle oracle
), ),
'User deposit is already being used as collateral' 'User deposit is already being used as collateral'
); );

View File

@ -12,22 +12,22 @@ library MathUtils {
/** /**
* @dev function to calculate the interest using a linear interest rate formula * @dev function to calculate the interest using a linear interest rate formula
* @param _rate the interest rate, in ray * @param rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest * @param lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate linearly accumulated during the timeDelta, in ray * @return the interest rate linearly accumulated during the timeDelta, in ray
**/ **/
function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp) function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal internal
view view
returns (uint256) returns (uint256)
{ {
//solium-disable-next-line //solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay()); uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay());
return _rate.rayMul(timeDelta).add(WadRayMath.ray()); return rate.rayMul(timeDelta).add(WadRayMath.ray());
} }
/** /**
@ -39,17 +39,17 @@ library MathUtils {
* The approximation slightly underpays liquidity providers, with the advantage of great gas cost reductions. * The approximation slightly underpays liquidity providers, with the advantage of great gas cost reductions.
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods. * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods.
* *
* @param _rate the interest rate, in ray * @param rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest * @param lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate compounded during the timeDelta, in ray * @return the interest rate compounded during the timeDelta, in ray
**/ **/
function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp) function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal internal
view view
returns (uint256) returns (uint256)
{ {
//solium-disable-next-line //solium-disable-next-line
uint256 exp = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 exp = block.timestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) { if (exp == 0) {
return WadRayMath.ray(); return WadRayMath.ray();
@ -59,7 +59,7 @@ library MathUtils {
uint256 expMinusTwo = exp > 2 ? exp.sub(2) : 0; uint256 expMinusTwo = exp > 2 ? exp.sub(2) : 0;
uint256 ratePerSecond = _rate.div(31536000); uint256 ratePerSecond = rate.div(31536000);
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);

View File

@ -19,23 +19,23 @@ library PercentageMath {
/** /**
* @dev executes a percentage multiplication * @dev executes a percentage multiplication
* @param _value the value of which the percentage needs to be calculated * @param value the value of which the percentage needs to be calculated
* @param _percentage the percentage of the value to be calculated * @param percentage the percentage of the value to be calculated
* @return the _percentage of _value * @return the percentage of value
**/ **/
function percentMul(uint256 _value, uint256 _percentage) internal pure returns (uint256) { function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
return HALF_PERCENT.add(_value.mul(_percentage)).div(PERCENTAGE_FACTOR); return HALF_PERCENT.add(value.mul(percentage)).div(PERCENTAGE_FACTOR);
} }
/** /**
* @dev executes a percentage division * @dev executes a percentage division
* @param _value the value of which the percentage needs to be calculated * @param value the value of which the percentage needs to be calculated
* @param _percentage the percentage of the value to be calculated * @param percentage the percentage of the value to be calculated
* @return the _value divided the _percentage * @return the value divided the percentage
**/ **/
function percentDiv(uint256 _value, uint256 _percentage) internal pure returns (uint256) { function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
uint256 halfPercentage = _percentage / 2; uint256 halfPercentage = percentage / 2;
return halfPercentage.add(_value.mul(PERCENTAGE_FACTOR)).div(_percentage); return halfPercentage.add(value.mul(PERCENTAGE_FACTOR)).div(percentage);
} }
} }

View File

@ -15,22 +15,22 @@ contract InitializableAdminUpgradeabilityProxy is
{ {
/** /**
* Contract initializer. * Contract initializer.
* @param _logic address of the initial implementation. * @param logic address of the initial implementation.
* @param _admin Address of the proxy administrator. * @param admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * @param data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in * It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/ */
function initialize( function initialize(
address _logic, address logic,
address _admin, address admin,
bytes memory _data bytes memory data
) public payable { ) public payable {
require(_implementation() == address(0)); require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data); InitializableUpgradeabilityProxy.initialize(logic, data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin); _setAdmin(admin);
} }
/** /**

View File

@ -51,7 +51,7 @@ contract MockFlashLoanReceiver is FlashLoanReceiverBase {
token.mint(_fee); token.mint(_fee);
//returning amount + fee to the destination //returning amount + fee to the destination
transferFundsBackInternal(_reserve, _destination, _amount.add(_fee)); _transferFundsBack(_reserve, _destination, _amount.add(_fee));
emit ExecutedWithSuccess(_reserve, _amount, _fee); emit ExecutedWithSuccess(_reserve, _amount, _fee);
} }

View File

@ -154,7 +154,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
address to, address to,
uint256 amount uint256 amount
) internal override whenTransferAllowed(from, amount) { ) internal override whenTransferAllowed(from, amount) {
executeTransferInternal(from, to, amount); _executeTransfer(from, to, amount);
} }
/** /**
@ -164,7 +164,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param to the address to which the interest will be redirected * @param to the address to which the interest will be redirected
**/ **/
function redirectInterestStream(address to) external override { function redirectInterestStream(address to) external override {
redirectInterestStreamInternal(msg.sender, to); _redirectInterestStream(msg.sender, to);
} }
/** /**
@ -180,7 +180,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
msg.sender == _interestRedirectionAllowances[from], msg.sender == _interestRedirectionAllowances[from],
'Caller is not allowed to redirect the interest of the user' 'Caller is not allowed to redirect the interest of the user'
); );
redirectInterestStreamInternal(from, to); _redirectInterestStream(from, to);
} }
/** /**
@ -206,12 +206,12 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
uint256 amount uint256 amount
) external override onlyLendingPool { ) external override onlyLendingPool {
//cumulates the balance of the user //cumulates the balance of the user
(, uint256 currentBalance, uint256 balanceIncrease) = calculateBalanceIncreaseInternal(user); (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user);
//if the user is redirecting his interest towards someone else, //if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest, //we update the redirected balance of the redirection address by adding the accrued interest,
//and removing the amount to redeem //and removing the amount to redeem
updateRedirectedBalanceOfRedirectionAddressInternal(user, balanceIncrease, amount); _updateRedirectedBalanceOfRedirectionAddress(user, balanceIncrease, amount);
if (balanceIncrease > amount) { if (balanceIncrease > amount) {
_mint(user, balanceIncrease.sub(amount)); _mint(user, balanceIncrease.sub(amount));
@ -223,7 +223,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
//reset the user data if the remaining balance is 0 //reset the user data if the remaining balance is 0
if (currentBalance.sub(amount) == 0) { if (currentBalance.sub(amount) == 0) {
resetDataOnZeroBalanceInternal(user); _resetDataOnZeroBalance(user);
} else { } else {
//updates the user index //updates the user index
userIndex = _userIndexes[user] = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); userIndex = _userIndexes[user] = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS);
@ -243,7 +243,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
*/ */
function mint(address user, uint256 amount) external override onlyLendingPool { function mint(address user, uint256 amount) external override onlyLendingPool {
//cumulates the balance of the user //cumulates the balance of the user
(, , uint256 balanceIncrease) = calculateBalanceIncreaseInternal(user); (, , uint256 balanceIncrease) = _calculateBalanceIncrease(user);
//updates the user index //updates the user index
uint256 index = _userIndexes[user] = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); uint256 index = _userIndexes[user] = _pool.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS);
@ -251,7 +251,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
//if the user is redirecting his interest towards someone else, //if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest //we update the redirected balance of the redirection address by adding the accrued interest
//and the amount deposited //and the amount deposited
updateRedirectedBalanceOfRedirectionAddressInternal(user, balanceIncrease.add(amount), 0); _updateRedirectedBalanceOfRedirectionAddress(user, balanceIncrease.add(amount), 0);
//mint an equivalent amount of tokens to cover the new deposit //mint an equivalent amount of tokens to cover the new deposit
_mint(user, amount.add(balanceIncrease)); _mint(user, amount.add(balanceIncrease));
@ -273,7 +273,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
) external override onlyLendingPool { ) external override onlyLendingPool {
//being a normal transfer, the Transfer() and BalanceTransfer() are emitted //being a normal transfer, the Transfer() and BalanceTransfer() are emitted
//so no need to emit a specific event here //so no need to emit a specific event here
executeTransferInternal(from, to, value); _executeTransfer(from, to, value);
} }
/** /**
@ -298,7 +298,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
//accruing for himself means that both the principal balance and //accruing for himself means that both the principal balance and
//the redirected balance partecipate in the interest //the redirected balance partecipate in the interest
return return
calculateCumulatedBalanceInternal(user, currentPrincipalBalance.add(redirectedBalance)).sub( _calculateCumulatedBalance(user, currentPrincipalBalance.add(redirectedBalance)).sub(
redirectedBalance redirectedBalance
); );
} else { } else {
@ -307,7 +307,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
//by the redirected balance is added to the current principal balance. //by the redirected balance is added to the current principal balance.
return return
currentPrincipalBalance.add( currentPrincipalBalance.add(
calculateCumulatedBalanceInternal(user, redirectedBalance).sub(redirectedBalance) _calculateCumulatedBalance(user, redirectedBalance).sub(redirectedBalance)
); );
} }
} }
@ -385,7 +385,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param user the address of the user * @param user the address of the user
* @return the last user principal balance, the current balance and the balance increase * @return the last user principal balance, the current balance and the balance increase
**/ **/
function calculateBalanceIncreaseInternal(address user) function _calculateBalanceIncrease(address user)
internal internal
view view
returns ( returns (
@ -413,7 +413,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @return the previous principal balance, the new principal balance, the balance increase * @return the previous principal balance, the new principal balance, the balance increase
* and the new user index * and the new user index
**/ **/
function cumulateBalanceInternal(address user) function _cumulateBalance(address user)
internal internal
returns ( returns (
uint256, uint256,
@ -426,7 +426,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
uint256 previousBalance, uint256 previousBalance,
uint256 currentBalance, uint256 currentBalance,
uint256 balanceIncrease uint256 balanceIncrease
) = calculateBalanceIncreaseInternal(user); ) = _calculateBalanceIncrease(user);
_mint(user, balanceIncrease); _mint(user, balanceIncrease);
@ -443,7 +443,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param balanceToAdd the amount to add to the redirected balance * @param balanceToAdd the amount to add to the redirected balance
* @param balanceToRemove the amount to remove from the redirected balance * @param balanceToRemove the amount to remove from the redirected balance
**/ **/
function updateRedirectedBalanceOfRedirectionAddressInternal( function _updateRedirectedBalanceOfRedirectionAddress(
address user, address user,
uint256 balanceToAdd, uint256 balanceToAdd,
uint256 balanceToRemove uint256 balanceToRemove
@ -455,7 +455,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
} }
//compound balances of the redirected address //compound balances of the redirected address
(, , uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress); (, , uint256 balanceIncrease, uint256 index) = _cumulateBalance(redirectionAddress);
//updating the redirected balance //updating the redirected balance
_redirectedBalances[redirectionAddress] = _redirectedBalances[redirectionAddress] _redirectedBalances[redirectionAddress] = _redirectedBalances[redirectionAddress]
@ -469,7 +469,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
// if the redirection address is also redirecting the interest, we accumulate his balance // if the redirection address is also redirecting the interest, we accumulate his balance
// and update his chain of redirection // and update his chain of redirection
if (targetOfRedirectionAddress != address(0)) { if (targetOfRedirectionAddress != address(0)) {
updateRedirectedBalanceOfRedirectionAddressInternal(redirectionAddress, balanceIncrease, 0); _updateRedirectedBalanceOfRedirectionAddress(redirectionAddress, balanceIncrease, 0);
} }
emit RedirectedBalanceUpdated( emit RedirectedBalanceUpdated(
@ -487,7 +487,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param balance the balance on which the interest is calculated * @param balance the balance on which the interest is calculated
* @return the interest rate accrued * @return the interest rate accrued
**/ **/
function calculateCumulatedBalanceInternal(address user, uint256 balance) function _calculateCumulatedBalance(address user, uint256 balance)
internal internal
view view
returns (uint256) returns (uint256)
@ -507,7 +507,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param to the destination address * @param to the destination address
* @param value the amount to transfer * @param value the amount to transfer
**/ **/
function executeTransferInternal( function _executeTransfer(
address from, address from,
address to, address to,
uint256 value uint256 value
@ -520,20 +520,20 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
uint256 fromBalance, uint256 fromBalance,
uint256 fromBalanceIncrease, uint256 fromBalanceIncrease,
uint256 fromIndex uint256 fromIndex
) = cumulateBalanceInternal(from); ) = _cumulateBalance(from);
//cumulate the balance of the receiver //cumulate the balance of the receiver
(, , uint256 toBalanceIncrease, uint256 toIndex) = cumulateBalanceInternal(to); (, , uint256 toBalanceIncrease, uint256 toIndex) = _cumulateBalance(to);
//if the sender is redirecting his interest towards someone else, //if the sender is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and removes the amount //adds to the redirected balance the accrued interest and removes the amount
//being transferred //being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(from, fromBalanceIncrease, value); _updateRedirectedBalanceOfRedirectionAddress(from, fromBalanceIncrease, value);
//if the receiver is redirecting his interest towards someone else, //if the receiver is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and the amount //adds to the redirected balance the accrued interest and the amount
//being transferred //being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(to, toBalanceIncrease.add(value), 0); _updateRedirectedBalanceOfRedirectionAddress(to, toBalanceIncrease.add(value), 0);
//performs the transfer //performs the transfer
super._transfer(from, to, value); super._transfer(from, to, value);
@ -541,7 +541,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
bool fromIndexReset = false; bool fromIndexReset = false;
//reset the user data if the remaining balance is 0 //reset the user data if the remaining balance is 0
if (fromBalance.sub(value) == 0 && from != to) { if (fromBalance.sub(value) == 0 && from != to) {
fromIndexReset = resetDataOnZeroBalanceInternal(from); fromIndexReset = _resetDataOnZeroBalance(from);
} }
emit BalanceTransfer( emit BalanceTransfer(
@ -561,7 +561,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param from the address from which transfer the aTokens * @param from the address from which transfer the aTokens
* @param to the destination address * @param to the destination address
**/ **/
function redirectInterestStreamInternal(address from, address to) internal { function _redirectInterestStream(address from, address to) internal {
address currentRedirectionAddress = _interestRedirectionAddresses[from]; address currentRedirectionAddress = _interestRedirectionAddresses[from];
require(to != currentRedirectionAddress, 'Interest is already redirected to the user'); require(to != currentRedirectionAddress, 'Interest is already redirected to the user');
@ -572,7 +572,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
uint256 fromBalance, uint256 fromBalance,
uint256 balanceIncrease, uint256 balanceIncrease,
uint256 fromIndex uint256 fromIndex
) = cumulateBalanceInternal(from); ) = _cumulateBalance(from);
require(fromBalance > 0, 'Interest stream can only be redirected if there is a valid balance'); require(fromBalance > 0, 'Interest stream can only be redirected if there is a valid balance');
@ -580,7 +580,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
//the redirection address we substract the redirected balance of the previous //the redirection address we substract the redirected balance of the previous
//recipient //recipient
if (currentRedirectionAddress != address(0)) { if (currentRedirectionAddress != address(0)) {
updateRedirectedBalanceOfRedirectionAddressInternal(from, 0, previousPrincipalBalance); _updateRedirectedBalanceOfRedirectionAddress(from, 0, previousPrincipalBalance);
} }
//if the user is redirecting the interest back to himself, //if the user is redirecting the interest back to himself,
@ -595,7 +595,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
_interestRedirectionAddresses[from] = to; _interestRedirectionAddresses[from] = to;
//adds the user balance to the redirected balance of the destination //adds the user balance to the redirected balance of the destination
updateRedirectedBalanceOfRedirectionAddressInternal(from, fromBalance, 0); _updateRedirectedBalanceOfRedirectionAddress(from, fromBalance, 0);
emit InterestStreamRedirected(from, to, fromBalance, balanceIncrease, fromIndex); emit InterestStreamRedirected(from, to, fromBalance, balanceIncrease, fromIndex);
} }
@ -606,7 +606,7 @@ contract AToken is VersionedInitializable, ERC20, IAToken {
* @param user the address of the user * @param user the address of the user
* @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value * @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value
**/ **/
function resetDataOnZeroBalanceInternal(address user) internal returns (bool) { function _resetDataOnZeroBalance(address user) internal returns (bool) {
//if the user has 0 principal balance, the interest stream redirection gets reset //if the user has 0 principal balance, the interest stream redirection gets reset
_interestRedirectionAddresses[user] = address(0); _interestRedirectionAddresses[user] = address(0);