Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
7
// Adds whitelisted minters
function addMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == false, "Address already exists"); minters[minter_address] = true; minters_array.push(minter_address); emit MinterAdded(minter_address); }
function addMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == false, "Address already exists"); minters[minter_address] = true; minters_array.push(minter_address); emit MinterAdded(minter_address); }
5,407
5
// contract will multiply this value by the premium to credit passengers
uint private constant premiumMultiplier = 2;
uint private constant premiumMultiplier = 2;
39,521
38
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
require(newOwner != address(0) || renounce, "Ownable: zero address");
5,786
5
// Withdraw To MemberB
(bool withdrawMemberB, ) = teamMemberB.call{value: memberBAmount}("");
(bool withdrawMemberB, ) = teamMemberB.call{value: memberBAmount}("");
14,506
40
// Estimates amount return amount Token amount duration In secondsreturn returned Amount /
function estimateAmountReturn(uint256 amount, uint256 duration) public pure returns (uint256 returned)
function estimateAmountReturn(uint256 amount, uint256 duration) public pure returns (uint256 returned)
26,616
163
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
EnumerableMap.UintToAddressMap private _tokenOwners;
35,557
261
// Increment count for given Generation/Series
primeCountByGenAndSeries[uint8(_generation)][uint8(_series)]++;
primeCountByGenAndSeries[uint8(_generation)][uint8(_series)]++;
53,351
3
// tx info status/uninitialized,locked,redeemed,revoked
enum TxStatus {None, Locked, Redeemed, Revoked, AssetLocked, DebtLocked} /** * * STRUCTURES * */ /// @notice struct of HTLC user mint lock parameters struct HTLCUserParams { bytes32 xHash; /// hash of HTLC random number bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value uint lockFee; /// exchange token value uint lockedTime; /// HTLC lock time }
enum TxStatus {None, Locked, Redeemed, Revoked, AssetLocked, DebtLocked} /** * * STRUCTURES * */ /// @notice struct of HTLC user mint lock parameters struct HTLCUserParams { bytes32 xHash; /// hash of HTLC random number bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value uint lockFee; /// exchange token value uint lockedTime; /// HTLC lock time }
14,526
11
// Function returns stage of sale at any point in time /
function isSaleStarted() external view returns(bool) { if(block.timestamp >= saleStartTime) { return true; } return false; }
function isSaleStarted() external view returns(bool) { if(block.timestamp >= saleStartTime) { return true; } return false; }
9,143
478
// LendingPoolCore contractAaveHolds the state of the lending pool and all the funds depositedNOTE: The core does not enforce security checks on the update of the state (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve). The check that an action can be performed is a duty of the overlying LendingPool contract./
contract LendingPoolCore is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using CoreLibrary for CoreLibrary.ReserveData; using CoreLibrary for CoreLibrary.UserReserveData; using SafeERC20 for ERC20; using Address for address payable; /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve * @param liquidityRate the new liquidity rate * @param stableBorrowRate the new stable borrow rate * @param variableBorrowRate the new variable borrow rate * @param liquidityIndex the new liquidity index * @param variableBorrowIndex the new variable borrow index **/ event ReserveUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); address public lendingPoolAddress; LendingPoolAddressesProvider public addressesProvider; /** * @dev only lending pools can use functions affected by this modifier **/ modifier onlyLendingPool { require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract"); _; } /** * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { require( addressesProvider.getLendingPoolConfigurator() == msg.sender, "The caller must be a lending pool configurator contract" ); _; } mapping(address => CoreLibrary.ReserveData) internal reserves; mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData; address[] public reservesList; uint256 public constant CORE_REVISION = 0x4; /** * @dev returns the revision number of the contract **/ function getRevision() internal pure returns (uint256) { return CORE_REVISION; } /** * @dev initializes the Core contract, invoked upon registration on the AddressesProvider * @param _addressesProvider the addressesProvider contract **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; refreshConfigInternal(); } /** * @dev updates the state of the core as a result of a deposit action * @param _reserve the address of the reserve in which the deposit is happening * @param _user the address of the the user depositing * @param _amount the amount being deposited * @param _isFirstDeposit true if the user is depositing for the first time **/ function updateStateOnDeposit( address _reserve, address _user, uint256 _amount, bool _isFirstDeposit ) external onlyLendingPool { reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0); if (_isFirstDeposit) { //if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral setUserUseReserveAsCollateral(_reserve, _user, true); } } /** * @dev updates the state of the core as a result of a redeem action * @param _reserve the address of the reserve in which the redeem is happening * @param _user the address of the the user redeeming * @param _amountRedeemed the amount being redeemed * @param _userRedeemedEverything true if the user is redeeming everything **/ function updateStateOnRedeem( address _reserve, address _user, uint256 _amountRedeemed, bool _userRedeemedEverything ) external onlyLendingPool { //compound liquidity and variable borrow interests reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed); //if user redeemed everything the useReserveAsCollateral flag is reset if (_userRedeemedEverything) { setUserUseReserveAsCollateral(_reserve, _user, false); } } /** * @dev updates the state of the core as a result of a flashloan action * @param _reserve the address of the reserve in which the flashloan is happening * @param _income the income of the protocol as a result of the action **/ function updateStateOnFlashLoan( address _reserve, uint256 _availableLiquidityBefore, uint256 _income, uint256 _protocolFee ) external onlyLendingPool { transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee); //compounding the cumulated interest reserves[_reserve].updateCumulativeIndexes(); uint256 totalLiquidityBefore = _availableLiquidityBefore.add( getReserveTotalBorrows(_reserve) ); //compounding the received fee into the reserve reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income); //refresh interest rates updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0); } /** * @dev updates the state of the core as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the new amount borrowed * @param _borrowFee the fee on the amount borrowed * @param _rateMode the borrow rate mode (stable, variable) * @return the new borrow rate for the user **/ function updateStateOnBorrow( address _reserve, address _user, uint256 _amountBorrowed, uint256 _borrowFee, CoreLibrary.InterestRateMode _rateMode ) external onlyLendingPool returns (uint256, uint256) { // getting the previous borrow data of the user (uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances( _reserve, _user ); updateReserveStateOnBorrowInternal( _reserve, _user, principalBorrowBalance, balanceIncrease, _amountBorrowed, _rateMode ); updateUserStateOnBorrowInternal( _reserve, _user, _amountBorrowed, balanceIncrease, _borrowFee, _rateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed); return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease); } /** * @dev updates the state of the core as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateStateOnRepay( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) external onlyLendingPool { updateReserveStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _balanceIncrease ); updateUserStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _originationFeeRepaid, _balanceIncrease, _repaidWholeLoan ); updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0); } /** * @dev updates the state of the core as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _principalBorrowBalance the amount borrowed by the user * @param _compoundedBorrowBalance the amount borrowed plus accrued interest * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current interest rate mode for the user **/ function updateStateOnSwapRate( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) { updateReserveStateOnSwapRateInternal( _reserve, _user, _principalBorrowBalance, _compoundedBorrowBalance, _currentRateMode ); CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal( _reserve, _user, _balanceIncrease, _currentRateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return (newRateMode, getUserCurrentBorrowRate(_reserve, _user)); } /** * @dev updates the state of the core as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _collateralReserve the address of the collateral reserve that is being liquidated * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _collateralToLiquidate the amount of collateral being liquidated * @param _feeLiquidated the amount of origination fee being liquidated * @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus * @param _balanceIncrease the accrued interest on the borrowed amount * @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise **/ function updateStateOnLiquidation( address _principalReserve, address _collateralReserve, address _user, uint256 _amountToLiquidate, uint256 _collateralToLiquidate, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _balanceIncrease, bool _liquidatorReceivesAToken ) external onlyLendingPool { updatePrincipalReserveStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _balanceIncrease ); updateCollateralReserveStateOnLiquidationInternal( _collateralReserve ); updateUserStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _feeLiquidated, _balanceIncrease ); updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0); if (!_liquidatorReceivesAToken) { updateReserveInterestRatesAndTimestampInternal( _collateralReserve, 0, _collateralToLiquidate.add(_liquidatedCollateralForFee) ); } } /** * @dev updates the state of the core as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @return the new stable rate for the user **/ function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease) external onlyLendingPool returns (uint256) { updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); //update user data and rebalance the rate updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return usersReserveData[_user][_reserve].stableBorrowRate; } /** * @dev enables or disables a reserve as collateral * @param _reserve the address of the principal reserve where the user deposited * @param _user the address of the depositor * @param _useAsCollateral true if the depositor wants to use the reserve as collateral **/ function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral) public onlyLendingPool { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; user.useAsCollateral = _useAsCollateral; } /** * @notice ETH/token transfer functions **/ /** * @dev fallback function enforces that the caller is a contract, to support flashloan transfers **/ function() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core"); } /** * @dev transfers to the user a specific amount from the reserve. * @param _reserve the address of the reserve where the transfer is happening * @param _user the address of the user receiving the transfer * @param _amount the amount being transferred **/ function transferToUser(address _reserve, address payable _user, uint256 _amount) external onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { ERC20(_reserve).safeTransfer(_user, _amount); } else { //solium-disable-next-line (bool result, ) = _user.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the protocol fees to the fees collection address * @param _token the address of the token being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function transferToFeeCollectionAddress( address _token, address _user, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable if (_token != EthAddressLib.ethAddress()) { require( msg.value == 0, "User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction" ); ERC20(_token).safeTransferFrom(_user, feeAddress, _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the fees to the fees collection address in the case of liquidation * @param _token the address of the token being transferred * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function liquidateFee( address _token, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable require( msg.value == 0, "Fee liquidation does not require any transfer of value" ); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(feeAddress, _amount); } else { //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers an amount from a user to the destination reserve * @param _reserve the address of the reserve where the amount is being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred **/ function transferToReserve(address _reserve, address payable _user, uint256 _amount) external payable onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { require(msg.value == 0, "User is sending ETH along with the ERC20 transfer."); ERC20(_reserve).safeTransferFrom(_user, address(this), _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); if (msg.value > _amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(_amount); //solium-disable-next-line (bool result, ) = _user.call.value(excessAmount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } } /** * @notice data access functions **/ /** * @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral) * needed to calculate the global account data in the LendingPoolDataProvider * @param _reserve the address of the reserve * @param _user the address of the user * @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not **/ function getUserBasicReserveData(address _reserve, address _user) external view returns (uint256, uint256, uint256, bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user); if (user.principalBorrowBalance == 0) { return (underlyingBalance, 0, 0, user.useAsCollateral); } return ( underlyingBalance, user.getCompoundedBorrowBalance(reserve), user.originationFee, user.useAsCollateral ); } /** * @dev checks if a user is allowed to borrow at a stable rate * @param _reserve the reserve address * @param _user the user * @param _amount the amount the the user wants to borrow * @return true if the user is allowed to borrow at a stable rate, false otherwise **/ function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (!reserve.isStableBorrowRateEnabled) return false; return !user.useAsCollateral || !reserve.usageAsCollateralEnabled || _amount > getUserUnderlyingAssetBalance(_reserve, _user); } /** * @dev gets the underlying asset balance of a user based on the corresponding aToken balance. * @param _reserve the reserve address * @param _user the user address * @return the underlying deposit balance of the user **/ function getUserUnderlyingAssetBalance(address _reserve, address _user) public view returns (uint256) { AToken aToken = AToken(reserves[_reserve].aTokenAddress); return aToken.balanceOf(_user); } /** * @dev gets the interest rate strategy contract address for the reserve * @param _reserve the reserve address * @return the address of the interest rate strategy contract **/ function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.interestRateStrategyAddress; } /** * @dev gets the aToken contract address for the reserve * @param _reserve the reserve address * @return the address of the aToken contract **/ function getReserveATokenAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.aTokenAddress; } /** * @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract * @param _reserve the reserve address * @return the available liquidity **/ function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) { uint256 balance = 0; if (_reserve == EthAddressLib.ethAddress()) { balance = address(this).balance; } else { balance = IERC20(_reserve).balanceOf(address(this)); } return balance; } /** * @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows * @param _reserve the reserve address * @return the total liquidity **/ function getReserveTotalLiquidity(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows()); } /** * @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there * there has been 100% income. * @param _reserve the reserve address * @return the reserve normalized income **/ function getReserveNormalizedIncome(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.getNormalizedIncome(); } /** * @dev gets the reserve total borrows * @param _reserve the reserve address * @return the total borrows (stable + variable) **/ function getReserveTotalBorrows(address _reserve) public view returns (uint256) { return reserves[_reserve].getTotalBorrows(); } /** * @dev gets the reserve total borrows stable * @param _reserve the reserve address * @return the total borrows stable **/ function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsStable; } /** * @dev gets the reserve total borrows variable * @param _reserve the reserve address * @return the total borrows variable **/ function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsVariable; } /** * @dev gets the reserve liquidation threshold * @param _reserve the reserve address * @return the reserve liquidation threshold **/ function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationThreshold; } /** * @dev gets the reserve liquidation bonus * @param _reserve the reserve address * @return the reserve liquidation bonus **/ function getReserveLiquidationBonus(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationBonus; } /** * @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current variable borrow rate **/ function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (reserve.currentVariableBorrowRate == 0) { return IReserveInterestRateStrategy(reserve.interestRateStrategyAddress) .getBaseVariableBorrowRate(); } return reserve.currentVariableBorrowRate; } /** * @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current stable borrow rate **/ function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle()); if (reserve.currentStableBorrowRate == 0) { //no stable rate borrows yet return oracle.getMarketBorrowRate(_reserve); } return reserve.currentStableBorrowRate; } /** * @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average * of all the loans taken at stable rate. * @param _reserve the reserve address * @return the reserve current average borrow rate **/ function getReserveCurrentAverageStableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentAverageStableBorrowRate; } /** * @dev gets the reserve liquidity rate * @param _reserve the reserve address * @return the reserve liquidity rate **/ function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentLiquidityRate; } /** * @dev gets the reserve liquidity cumulative index * @param _reserve the reserve address * @return the reserve liquidity cumulative index **/ function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastLiquidityCumulativeIndex; } /** * @dev gets the reserve variable borrow index * @param _reserve the reserve address * @return the reserve variable borrow index **/ function getReserveVariableBorrowsCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastVariableBorrowCumulativeIndex; } /** * @dev this function aggregates the configuration parameters of the reserve. * It's used in the LendingPoolDataProvider specifically to save gas, and avoid * multiple external contract calls to fetch the same data. * @param _reserve the reserve address * @return the reserve decimals * @return the base ltv as collateral * @return the liquidation threshold * @return if the reserve is used as collateral or not **/ function getReserveConfiguration(address _reserve) external view returns (uint256, uint256, uint256, bool) { uint256 decimals; uint256 baseLTVasCollateral; uint256 liquidationThreshold; bool usageAsCollateralEnabled; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; decimals = reserve.decimals; baseLTVasCollateral = reserve.baseLTVasCollateral; liquidationThreshold = reserve.liquidationThreshold; usageAsCollateralEnabled = reserve.usageAsCollateralEnabled; return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled); } /** * @dev returns the decimals of the reserve * @param _reserve the reserve address * @return the reserve decimals **/ function getReserveDecimals(address _reserve) external view returns (uint256) { return reserves[_reserve].decimals; } /** * @dev returns true if the reserve is enabled for borrowing * @param _reserve the reserve address * @return true if the reserve is enabled for borrowing, false otherwise **/ function isReserveBorrowingEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.borrowingEnabled; } /** * @dev returns true if the reserve is enabled as collateral * @param _reserve the reserve address * @return true if the reserve is enabled as collateral, false otherwise **/ function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.usageAsCollateralEnabled; } /** * @dev returns true if the stable rate is enabled on reserve * @param _reserve the reserve address * @return true if the stable rate is enabled on reserve, false otherwise **/ function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isStableBorrowRateEnabled; } /** * @dev returns true if the reserve is active * @param _reserve the reserve address * @return true if the reserve is active, false otherwise **/ function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; } /** * @notice returns if a reserve is freezed * @param _reserve the reserve for which the information is needed * @return true if the reserve is freezed, false otherwise **/ function getReserveIsFreezed(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isFreezed; } /** * @notice returns the timestamp of the last action on the reserve * @param _reserve the reserve for which the information is needed * @return the last updated timestamp of the reserve **/ function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; timestamp = reserve.lastUpdateTimestamp; } /** * @dev returns the utilization rate U of a specific reserve * @param _reserve the reserve for which the information is needed * @return the utilization rate in ray **/ function getReserveUtilizationRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; uint256 totalBorrows = reserve.getTotalBorrows(); if (totalBorrows == 0) { return 0; } uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve); return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); } /** * @return the array of reserves configured on the core **/ function getReserves() external view returns (address[] memory) { return reservesList; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return true if the user has chosen to use the reserve as collateral, false otherwise **/ function isUserUseReserveAsCollateralEnabled(address _reserve, address _user) external view returns (bool) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the origination fee for the user **/ function getUserOriginationFee(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.originationFee; } /** * @dev users with no loans in progress have NONE as borrow rate mode * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate mode for the user, **/ function getUserCurrentBorrowRateMode(address _reserve, address _user) public view returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return CoreLibrary.InterestRateMode.NONE; } return user.stableBorrowRate > 0 ? CoreLibrary.InterestRateMode.STABLE : CoreLibrary.InterestRateMode.VARIABLE; } /** * @dev gets the current borrow rate of the user * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate for the user, **/ function getUserCurrentBorrowRate(address _reserve, address _user) internal view returns (uint256) { CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user); if (rateMode == CoreLibrary.InterestRateMode.NONE) { return 0; } return rateMode == CoreLibrary.InterestRateMode.STABLE ? usersReserveData[_user][_reserve].stableBorrowRate : reserves[_reserve].currentVariableBorrowRate; } /** * @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the user stable rate **/ function getUserCurrentStableBorrowRate(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.stableBorrowRate; } /** * @dev calculates and returns the borrow balances of the user * @param _reserve the address of the reserve * @param _user the address of the user * @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance **/ function getUserBorrowBalances(address _reserve, address _user) public view returns (uint256, uint256, uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserVariableBorrowCumulativeIndex(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.lastVariableBorrowCumulativeIndex; } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserLastUpdate(address _reserve, address _user) external view returns (uint256 timestamp) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; timestamp = user.lastUpdateTimestamp; } /** * @dev updates the lending pool core configuration **/ function refreshConfiguration() external onlyLendingPoolConfigurator { refreshConfigInternal(); } /** * @dev initializes a reserve * @param _reserve the address of the reserve * @param _aTokenAddress the address of the overlying aToken contract * @param _decimals the decimals of the reserve currency * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function initReserve( address _reserve, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external onlyLendingPoolConfigurator { reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress); addReserveToListInternal(_reserve); } /** * @dev removes the last added reserve in the reservesList array * @param _reserveToRemove the address of the reserve **/ function removeLastAddedReserve(address _reserveToRemove) external onlyLendingPoolConfigurator { address lastReserve = reservesList[reservesList.length-1]; require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested"); //as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited"); reserves[lastReserve].isActive = false; reserves[lastReserve].aTokenAddress = address(0); reserves[lastReserve].decimals = 0; reserves[lastReserve].lastLiquidityCumulativeIndex = 0; reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0; reserves[lastReserve].borrowingEnabled = false; reserves[lastReserve].usageAsCollateralEnabled = false; reserves[lastReserve].baseLTVasCollateral = 0; reserves[lastReserve].liquidationThreshold = 0; reserves[lastReserve].liquidationBonus = 0; reserves[lastReserve].interestRateStrategyAddress = address(0); reservesList.pop(); } /** * @dev updates the address of the interest rate strategy contract * @param _reserve the address of the reserve * @param _rateStrategyAddress the address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress) external onlyLendingPoolConfigurator { reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress; } /** * @dev enables borrowing on a reserve. Also sets the stable rate borrowing * @param _reserve the address of the reserve * @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise **/ function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled) external onlyLendingPoolConfigurator { reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled); } /** * @dev disables borrowing on a reserve * @param _reserve the address of the reserve **/ function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableBorrowing(); } /** * @dev enables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function enableReserveAsCollateral( address _reserve, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external onlyLendingPoolConfigurator { reserves[_reserve].enableAsCollateral( _baseLTVasCollateral, _liquidationThreshold, _liquidationBonus ); } /** * @dev disables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableAsCollateral(); } /** * @dev enable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = true; } /** * @dev disable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = false; } /** * @dev activates a reserve * @param _reserve the address of the reserve **/ function activateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; require( reserve.lastLiquidityCumulativeIndex > 0 && reserve.lastVariableBorrowCumulativeIndex > 0, "Reserve has not been initialized yet" ); reserve.isActive = true; } /** * @dev deactivates a reserve * @param _reserve the address of the reserve **/ function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isActive = false; } /** * @notice allows the configurator to freeze the reserve. * A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance. * @param _reserve the address of the reserve **/ function freezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = true; } /** * @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed. * @param _reserve the address of the reserve **/ function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = false; } /** * @notice allows the configurator to update the loan to value of a reserve * @param _reserve the address of the reserve * @param _ltv the new loan to value **/ function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.baseLTVasCollateral = _ltv; } /** * @notice allows the configurator to update the liquidation threshold of a reserve * @param _reserve the address of the reserve * @param _threshold the new liquidation threshold **/ function setReserveLiquidationThreshold(address _reserve, uint256 _threshold) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationThreshold = _threshold; } /** * @notice allows the configurator to update the liquidation bonus of a reserve * @param _reserve the address of the reserve * @param _bonus the new liquidation bonus **/ function setReserveLiquidationBonus(address _reserve, uint256 _bonus) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationBonus = _bonus; } /** * @notice allows the configurator to update the reserve decimals * @param _reserve the address of the reserve * @param _decimals the decimals of the reserve **/ function setReserveDecimals(address _reserve, uint256 _decimals) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.decimals = _decimals; } /** * @notice internal functions **/ /** * @dev updates the state of a reserve as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _principalBorrowBalance the previous borrow balance of the borrower before the action * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _amountBorrowed the new amount borrowed * @param _rateMode the borrow rate mode (stable, variable) **/ function updateReserveStateOnBorrowInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _rateMode ) internal { reserves[_reserve].updateCumulativeIndexes(); //increasing reserve total borrows to account for the new borrow balance of the user //NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa updateReserveTotalBorrowsByRateModeInternal( _reserve, _user, _principalBorrowBalance, _balanceIncrease, _amountBorrowed, _rateMode ); } /** * @dev updates the state of a user as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the amount borrowed * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _rateMode the borrow rate mode (stable, variable) * @return the final borrow rate for the user. Emitted by the borrow() event **/ function updateUserStateOnBorrowInternal( address _reserve, address _user, uint256 _amountBorrowed, uint256 _balanceIncrease, uint256 _fee, CoreLibrary.InterestRateMode _rateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (_rateMode == CoreLibrary.InterestRateMode.STABLE) { //stable //reset the user variable index, and update the stable rate user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) { //variable //reset the user stable rate, and store the new borrow index user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid borrow rate mode"); } //increase the principal borrows and the origination fee user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add( _balanceIncrease ); user.originationFee = user.originationFee.add(_fee); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_reserve][_user]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } } /** * @dev updates the state of the user as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateUserStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _paybackAmountMinusFees ); user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; //if the balance decrease is equal to the previous principal (user is repaying the whole loan) //and the rate mode is stable, we reset the interest rate mode of the user if (_repaidWholeLoan) { user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = 0; } user.originationFee = user.originationFee.sub(_originationFeeRepaid); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the rate swap * @param _user the address of the borrower * @param _principalBorrowBalance the the principal amount borrowed by the user * @param _compoundedBorrowBalance the principal amount plus the accrued interest * @param _currentRateMode the rate mode at which the user borrowed **/ function updateReserveStateOnSwapRateInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, CoreLibrary.InterestRateMode _currentRateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //compounding reserve indexes reserve.updateCumulativeIndexes(); if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { uint256 userCurrentStableRate = user.stableBorrowRate; //swap to variable reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBorrowBalance, userCurrentStableRate ); //decreasing stable from old principal balance reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows } else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //swap to stable uint256 currentStableRate = reserve.currentStableBorrowRate; reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _compoundedBorrowBalance, currentStableRate ); } else { revert("Invalid rate mode received"); } } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the swap * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current rate mode of the user **/ function updateUserStateOnSwapRateInternal( address _reserve, address _user, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) internal returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE; if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //switch to stable newMode = CoreLibrary.InterestRateMode.STABLE; user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { newMode = CoreLibrary.InterestRateMode.VARIABLE; user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid interest rate mode received"); } //compounding cumulated interest user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); return newMode; } /** * @dev updates the state of the principal reserve as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updatePrincipalReserveStateOnLiquidationInternal( address _principalReserve, address _user, uint256 _amountToLiquidate, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_principalReserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve]; //update principal reserve data reserve.updateCumulativeIndexes(); CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode( _principalReserve, _user ); if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _amountToLiquidate, user.stableBorrowRate ); } else { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsVariable(_balanceIncrease); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsVariable(_amountToLiquidate); } } /** * @dev updates the state of the collateral reserve as a consequence of a liquidation action. * @param _collateralReserve the address of the collateral reserve that is being liquidated **/ function updateCollateralReserveStateOnLiquidationInternal( address _collateralReserve ) internal { //update collateral reserve reserves[_collateralReserve].updateCumulativeIndexes(); } /** * @dev updates the state of the user being liquidated as a consequence of a liquidation action. * @param _reserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _feeLiquidated the amount of origination fee being liquidated * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnLiquidationInternal( address _reserve, address _user, uint256 _amountToLiquidate, uint256 _feeLiquidated, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; //first increase by the compounded interest, then decrease by the liquidated amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _amountToLiquidate ); if ( getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE ) { user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } if(_feeLiquidated > 0){ user.originationFee = user.originationFee.sub(_feeLiquidated); } //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); user.stableBorrowRate = reserve.currentStableBorrowRate; //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _amountBorrowed the accrued interest on the borrowed amount **/ function updateReserveTotalBorrowsByRateModeInternal( address _reserve, address _user, uint256 _principalBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _newBorrowRateMode ) internal { CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode( _reserve, _user ); CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBalance, user.stableBorrowRate ); } else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.decreaseTotalBorrowsVariable(_principalBalance); } uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed); if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( newPrincipalAmount, reserve.currentStableBorrowRate ); } else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.increaseTotalBorrowsVariable(newPrincipalAmount); } else { revert("Invalid new borrow rate mode"); } } /** * @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. * @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 _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow) **/ function updateReserveInterestRatesAndTimestampInternal( address _reserve, uint256 _liquidityAdded, uint256 _liquidityTaken ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy( reserve .interestRateStrategyAddress ) .calculateInterestRates( _reserve, getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken), reserve.totalBorrowsStable, reserve.totalBorrowsVariable, reserve.currentAverageStableBorrowRate ); reserve.currentLiquidityRate = newLiquidityRate; reserve.currentStableBorrowRate = newStableRate; reserve.currentVariableBorrowRate = newVariableRate; //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); emit ReserveUpdated( _reserve, newLiquidityRate, newStableRate, newVariableRate, reserve.lastLiquidityCumulativeIndex, reserve.lastVariableBorrowCumulativeIndex ); } /** * @dev transfers to the protocol fees of a flashloan to the fees collection address * @param _token the address of the token being transferred * @param _amount the amount being transferred **/ function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal { address payable receiver = address(uint160(addressesProvider.getTokenDistributor())); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(receiver, _amount); } else { receiver.transfer(_amount); } } /** * @dev updates the internal configuration of the core **/ function refreshConfigInternal() internal { lendingPoolAddress = addressesProvider.getLendingPool(); } /** * @dev adds a reserve to the array of the reserves address **/ function addReserveToListInternal(address _reserve) internal { bool reserveAlreadyAdded = false; for (uint256 i = 0; i < reservesList.length; i++) if (reservesList[i] == _reserve) { reserveAlreadyAdded = true; } if (!reserveAlreadyAdded) reservesList.push(_reserve); } }
contract LendingPoolCore is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using CoreLibrary for CoreLibrary.ReserveData; using CoreLibrary for CoreLibrary.UserReserveData; using SafeERC20 for ERC20; using Address for address payable; /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve * @param liquidityRate the new liquidity rate * @param stableBorrowRate the new stable borrow rate * @param variableBorrowRate the new variable borrow rate * @param liquidityIndex the new liquidity index * @param variableBorrowIndex the new variable borrow index **/ event ReserveUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); address public lendingPoolAddress; LendingPoolAddressesProvider public addressesProvider; /** * @dev only lending pools can use functions affected by this modifier **/ modifier onlyLendingPool { require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract"); _; } /** * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { require( addressesProvider.getLendingPoolConfigurator() == msg.sender, "The caller must be a lending pool configurator contract" ); _; } mapping(address => CoreLibrary.ReserveData) internal reserves; mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData; address[] public reservesList; uint256 public constant CORE_REVISION = 0x4; /** * @dev returns the revision number of the contract **/ function getRevision() internal pure returns (uint256) { return CORE_REVISION; } /** * @dev initializes the Core contract, invoked upon registration on the AddressesProvider * @param _addressesProvider the addressesProvider contract **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; refreshConfigInternal(); } /** * @dev updates the state of the core as a result of a deposit action * @param _reserve the address of the reserve in which the deposit is happening * @param _user the address of the the user depositing * @param _amount the amount being deposited * @param _isFirstDeposit true if the user is depositing for the first time **/ function updateStateOnDeposit( address _reserve, address _user, uint256 _amount, bool _isFirstDeposit ) external onlyLendingPool { reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0); if (_isFirstDeposit) { //if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral setUserUseReserveAsCollateral(_reserve, _user, true); } } /** * @dev updates the state of the core as a result of a redeem action * @param _reserve the address of the reserve in which the redeem is happening * @param _user the address of the the user redeeming * @param _amountRedeemed the amount being redeemed * @param _userRedeemedEverything true if the user is redeeming everything **/ function updateStateOnRedeem( address _reserve, address _user, uint256 _amountRedeemed, bool _userRedeemedEverything ) external onlyLendingPool { //compound liquidity and variable borrow interests reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed); //if user redeemed everything the useReserveAsCollateral flag is reset if (_userRedeemedEverything) { setUserUseReserveAsCollateral(_reserve, _user, false); } } /** * @dev updates the state of the core as a result of a flashloan action * @param _reserve the address of the reserve in which the flashloan is happening * @param _income the income of the protocol as a result of the action **/ function updateStateOnFlashLoan( address _reserve, uint256 _availableLiquidityBefore, uint256 _income, uint256 _protocolFee ) external onlyLendingPool { transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee); //compounding the cumulated interest reserves[_reserve].updateCumulativeIndexes(); uint256 totalLiquidityBefore = _availableLiquidityBefore.add( getReserveTotalBorrows(_reserve) ); //compounding the received fee into the reserve reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income); //refresh interest rates updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0); } /** * @dev updates the state of the core as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the new amount borrowed * @param _borrowFee the fee on the amount borrowed * @param _rateMode the borrow rate mode (stable, variable) * @return the new borrow rate for the user **/ function updateStateOnBorrow( address _reserve, address _user, uint256 _amountBorrowed, uint256 _borrowFee, CoreLibrary.InterestRateMode _rateMode ) external onlyLendingPool returns (uint256, uint256) { // getting the previous borrow data of the user (uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances( _reserve, _user ); updateReserveStateOnBorrowInternal( _reserve, _user, principalBorrowBalance, balanceIncrease, _amountBorrowed, _rateMode ); updateUserStateOnBorrowInternal( _reserve, _user, _amountBorrowed, balanceIncrease, _borrowFee, _rateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed); return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease); } /** * @dev updates the state of the core as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateStateOnRepay( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) external onlyLendingPool { updateReserveStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _balanceIncrease ); updateUserStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _originationFeeRepaid, _balanceIncrease, _repaidWholeLoan ); updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0); } /** * @dev updates the state of the core as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _principalBorrowBalance the amount borrowed by the user * @param _compoundedBorrowBalance the amount borrowed plus accrued interest * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current interest rate mode for the user **/ function updateStateOnSwapRate( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) { updateReserveStateOnSwapRateInternal( _reserve, _user, _principalBorrowBalance, _compoundedBorrowBalance, _currentRateMode ); CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal( _reserve, _user, _balanceIncrease, _currentRateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return (newRateMode, getUserCurrentBorrowRate(_reserve, _user)); } /** * @dev updates the state of the core as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _collateralReserve the address of the collateral reserve that is being liquidated * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _collateralToLiquidate the amount of collateral being liquidated * @param _feeLiquidated the amount of origination fee being liquidated * @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus * @param _balanceIncrease the accrued interest on the borrowed amount * @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise **/ function updateStateOnLiquidation( address _principalReserve, address _collateralReserve, address _user, uint256 _amountToLiquidate, uint256 _collateralToLiquidate, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _balanceIncrease, bool _liquidatorReceivesAToken ) external onlyLendingPool { updatePrincipalReserveStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _balanceIncrease ); updateCollateralReserveStateOnLiquidationInternal( _collateralReserve ); updateUserStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _feeLiquidated, _balanceIncrease ); updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0); if (!_liquidatorReceivesAToken) { updateReserveInterestRatesAndTimestampInternal( _collateralReserve, 0, _collateralToLiquidate.add(_liquidatedCollateralForFee) ); } } /** * @dev updates the state of the core as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @return the new stable rate for the user **/ function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease) external onlyLendingPool returns (uint256) { updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); //update user data and rebalance the rate updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return usersReserveData[_user][_reserve].stableBorrowRate; } /** * @dev enables or disables a reserve as collateral * @param _reserve the address of the principal reserve where the user deposited * @param _user the address of the depositor * @param _useAsCollateral true if the depositor wants to use the reserve as collateral **/ function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral) public onlyLendingPool { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; user.useAsCollateral = _useAsCollateral; } /** * @notice ETH/token transfer functions **/ /** * @dev fallback function enforces that the caller is a contract, to support flashloan transfers **/ function() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core"); } /** * @dev transfers to the user a specific amount from the reserve. * @param _reserve the address of the reserve where the transfer is happening * @param _user the address of the user receiving the transfer * @param _amount the amount being transferred **/ function transferToUser(address _reserve, address payable _user, uint256 _amount) external onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { ERC20(_reserve).safeTransfer(_user, _amount); } else { //solium-disable-next-line (bool result, ) = _user.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the protocol fees to the fees collection address * @param _token the address of the token being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function transferToFeeCollectionAddress( address _token, address _user, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable if (_token != EthAddressLib.ethAddress()) { require( msg.value == 0, "User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction" ); ERC20(_token).safeTransferFrom(_user, feeAddress, _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the fees to the fees collection address in the case of liquidation * @param _token the address of the token being transferred * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function liquidateFee( address _token, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable require( msg.value == 0, "Fee liquidation does not require any transfer of value" ); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(feeAddress, _amount); } else { //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers an amount from a user to the destination reserve * @param _reserve the address of the reserve where the amount is being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred **/ function transferToReserve(address _reserve, address payable _user, uint256 _amount) external payable onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { require(msg.value == 0, "User is sending ETH along with the ERC20 transfer."); ERC20(_reserve).safeTransferFrom(_user, address(this), _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); if (msg.value > _amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(_amount); //solium-disable-next-line (bool result, ) = _user.call.value(excessAmount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } } /** * @notice data access functions **/ /** * @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral) * needed to calculate the global account data in the LendingPoolDataProvider * @param _reserve the address of the reserve * @param _user the address of the user * @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not **/ function getUserBasicReserveData(address _reserve, address _user) external view returns (uint256, uint256, uint256, bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user); if (user.principalBorrowBalance == 0) { return (underlyingBalance, 0, 0, user.useAsCollateral); } return ( underlyingBalance, user.getCompoundedBorrowBalance(reserve), user.originationFee, user.useAsCollateral ); } /** * @dev checks if a user is allowed to borrow at a stable rate * @param _reserve the reserve address * @param _user the user * @param _amount the amount the the user wants to borrow * @return true if the user is allowed to borrow at a stable rate, false otherwise **/ function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (!reserve.isStableBorrowRateEnabled) return false; return !user.useAsCollateral || !reserve.usageAsCollateralEnabled || _amount > getUserUnderlyingAssetBalance(_reserve, _user); } /** * @dev gets the underlying asset balance of a user based on the corresponding aToken balance. * @param _reserve the reserve address * @param _user the user address * @return the underlying deposit balance of the user **/ function getUserUnderlyingAssetBalance(address _reserve, address _user) public view returns (uint256) { AToken aToken = AToken(reserves[_reserve].aTokenAddress); return aToken.balanceOf(_user); } /** * @dev gets the interest rate strategy contract address for the reserve * @param _reserve the reserve address * @return the address of the interest rate strategy contract **/ function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.interestRateStrategyAddress; } /** * @dev gets the aToken contract address for the reserve * @param _reserve the reserve address * @return the address of the aToken contract **/ function getReserveATokenAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.aTokenAddress; } /** * @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract * @param _reserve the reserve address * @return the available liquidity **/ function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) { uint256 balance = 0; if (_reserve == EthAddressLib.ethAddress()) { balance = address(this).balance; } else { balance = IERC20(_reserve).balanceOf(address(this)); } return balance; } /** * @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows * @param _reserve the reserve address * @return the total liquidity **/ function getReserveTotalLiquidity(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows()); } /** * @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there * there has been 100% income. * @param _reserve the reserve address * @return the reserve normalized income **/ function getReserveNormalizedIncome(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.getNormalizedIncome(); } /** * @dev gets the reserve total borrows * @param _reserve the reserve address * @return the total borrows (stable + variable) **/ function getReserveTotalBorrows(address _reserve) public view returns (uint256) { return reserves[_reserve].getTotalBorrows(); } /** * @dev gets the reserve total borrows stable * @param _reserve the reserve address * @return the total borrows stable **/ function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsStable; } /** * @dev gets the reserve total borrows variable * @param _reserve the reserve address * @return the total borrows variable **/ function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsVariable; } /** * @dev gets the reserve liquidation threshold * @param _reserve the reserve address * @return the reserve liquidation threshold **/ function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationThreshold; } /** * @dev gets the reserve liquidation bonus * @param _reserve the reserve address * @return the reserve liquidation bonus **/ function getReserveLiquidationBonus(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationBonus; } /** * @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current variable borrow rate **/ function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (reserve.currentVariableBorrowRate == 0) { return IReserveInterestRateStrategy(reserve.interestRateStrategyAddress) .getBaseVariableBorrowRate(); } return reserve.currentVariableBorrowRate; } /** * @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current stable borrow rate **/ function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle()); if (reserve.currentStableBorrowRate == 0) { //no stable rate borrows yet return oracle.getMarketBorrowRate(_reserve); } return reserve.currentStableBorrowRate; } /** * @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average * of all the loans taken at stable rate. * @param _reserve the reserve address * @return the reserve current average borrow rate **/ function getReserveCurrentAverageStableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentAverageStableBorrowRate; } /** * @dev gets the reserve liquidity rate * @param _reserve the reserve address * @return the reserve liquidity rate **/ function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentLiquidityRate; } /** * @dev gets the reserve liquidity cumulative index * @param _reserve the reserve address * @return the reserve liquidity cumulative index **/ function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastLiquidityCumulativeIndex; } /** * @dev gets the reserve variable borrow index * @param _reserve the reserve address * @return the reserve variable borrow index **/ function getReserveVariableBorrowsCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastVariableBorrowCumulativeIndex; } /** * @dev this function aggregates the configuration parameters of the reserve. * It's used in the LendingPoolDataProvider specifically to save gas, and avoid * multiple external contract calls to fetch the same data. * @param _reserve the reserve address * @return the reserve decimals * @return the base ltv as collateral * @return the liquidation threshold * @return if the reserve is used as collateral or not **/ function getReserveConfiguration(address _reserve) external view returns (uint256, uint256, uint256, bool) { uint256 decimals; uint256 baseLTVasCollateral; uint256 liquidationThreshold; bool usageAsCollateralEnabled; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; decimals = reserve.decimals; baseLTVasCollateral = reserve.baseLTVasCollateral; liquidationThreshold = reserve.liquidationThreshold; usageAsCollateralEnabled = reserve.usageAsCollateralEnabled; return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled); } /** * @dev returns the decimals of the reserve * @param _reserve the reserve address * @return the reserve decimals **/ function getReserveDecimals(address _reserve) external view returns (uint256) { return reserves[_reserve].decimals; } /** * @dev returns true if the reserve is enabled for borrowing * @param _reserve the reserve address * @return true if the reserve is enabled for borrowing, false otherwise **/ function isReserveBorrowingEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.borrowingEnabled; } /** * @dev returns true if the reserve is enabled as collateral * @param _reserve the reserve address * @return true if the reserve is enabled as collateral, false otherwise **/ function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.usageAsCollateralEnabled; } /** * @dev returns true if the stable rate is enabled on reserve * @param _reserve the reserve address * @return true if the stable rate is enabled on reserve, false otherwise **/ function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isStableBorrowRateEnabled; } /** * @dev returns true if the reserve is active * @param _reserve the reserve address * @return true if the reserve is active, false otherwise **/ function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; } /** * @notice returns if a reserve is freezed * @param _reserve the reserve for which the information is needed * @return true if the reserve is freezed, false otherwise **/ function getReserveIsFreezed(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isFreezed; } /** * @notice returns the timestamp of the last action on the reserve * @param _reserve the reserve for which the information is needed * @return the last updated timestamp of the reserve **/ function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; timestamp = reserve.lastUpdateTimestamp; } /** * @dev returns the utilization rate U of a specific reserve * @param _reserve the reserve for which the information is needed * @return the utilization rate in ray **/ function getReserveUtilizationRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; uint256 totalBorrows = reserve.getTotalBorrows(); if (totalBorrows == 0) { return 0; } uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve); return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); } /** * @return the array of reserves configured on the core **/ function getReserves() external view returns (address[] memory) { return reservesList; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return true if the user has chosen to use the reserve as collateral, false otherwise **/ function isUserUseReserveAsCollateralEnabled(address _reserve, address _user) external view returns (bool) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the origination fee for the user **/ function getUserOriginationFee(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.originationFee; } /** * @dev users with no loans in progress have NONE as borrow rate mode * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate mode for the user, **/ function getUserCurrentBorrowRateMode(address _reserve, address _user) public view returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return CoreLibrary.InterestRateMode.NONE; } return user.stableBorrowRate > 0 ? CoreLibrary.InterestRateMode.STABLE : CoreLibrary.InterestRateMode.VARIABLE; } /** * @dev gets the current borrow rate of the user * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate for the user, **/ function getUserCurrentBorrowRate(address _reserve, address _user) internal view returns (uint256) { CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user); if (rateMode == CoreLibrary.InterestRateMode.NONE) { return 0; } return rateMode == CoreLibrary.InterestRateMode.STABLE ? usersReserveData[_user][_reserve].stableBorrowRate : reserves[_reserve].currentVariableBorrowRate; } /** * @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the user stable rate **/ function getUserCurrentStableBorrowRate(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.stableBorrowRate; } /** * @dev calculates and returns the borrow balances of the user * @param _reserve the address of the reserve * @param _user the address of the user * @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance **/ function getUserBorrowBalances(address _reserve, address _user) public view returns (uint256, uint256, uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserVariableBorrowCumulativeIndex(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.lastVariableBorrowCumulativeIndex; } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserLastUpdate(address _reserve, address _user) external view returns (uint256 timestamp) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; timestamp = user.lastUpdateTimestamp; } /** * @dev updates the lending pool core configuration **/ function refreshConfiguration() external onlyLendingPoolConfigurator { refreshConfigInternal(); } /** * @dev initializes a reserve * @param _reserve the address of the reserve * @param _aTokenAddress the address of the overlying aToken contract * @param _decimals the decimals of the reserve currency * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function initReserve( address _reserve, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external onlyLendingPoolConfigurator { reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress); addReserveToListInternal(_reserve); } /** * @dev removes the last added reserve in the reservesList array * @param _reserveToRemove the address of the reserve **/ function removeLastAddedReserve(address _reserveToRemove) external onlyLendingPoolConfigurator { address lastReserve = reservesList[reservesList.length-1]; require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested"); //as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited"); reserves[lastReserve].isActive = false; reserves[lastReserve].aTokenAddress = address(0); reserves[lastReserve].decimals = 0; reserves[lastReserve].lastLiquidityCumulativeIndex = 0; reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0; reserves[lastReserve].borrowingEnabled = false; reserves[lastReserve].usageAsCollateralEnabled = false; reserves[lastReserve].baseLTVasCollateral = 0; reserves[lastReserve].liquidationThreshold = 0; reserves[lastReserve].liquidationBonus = 0; reserves[lastReserve].interestRateStrategyAddress = address(0); reservesList.pop(); } /** * @dev updates the address of the interest rate strategy contract * @param _reserve the address of the reserve * @param _rateStrategyAddress the address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress) external onlyLendingPoolConfigurator { reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress; } /** * @dev enables borrowing on a reserve. Also sets the stable rate borrowing * @param _reserve the address of the reserve * @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise **/ function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled) external onlyLendingPoolConfigurator { reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled); } /** * @dev disables borrowing on a reserve * @param _reserve the address of the reserve **/ function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableBorrowing(); } /** * @dev enables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function enableReserveAsCollateral( address _reserve, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external onlyLendingPoolConfigurator { reserves[_reserve].enableAsCollateral( _baseLTVasCollateral, _liquidationThreshold, _liquidationBonus ); } /** * @dev disables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableAsCollateral(); } /** * @dev enable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = true; } /** * @dev disable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = false; } /** * @dev activates a reserve * @param _reserve the address of the reserve **/ function activateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; require( reserve.lastLiquidityCumulativeIndex > 0 && reserve.lastVariableBorrowCumulativeIndex > 0, "Reserve has not been initialized yet" ); reserve.isActive = true; } /** * @dev deactivates a reserve * @param _reserve the address of the reserve **/ function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isActive = false; } /** * @notice allows the configurator to freeze the reserve. * A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance. * @param _reserve the address of the reserve **/ function freezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = true; } /** * @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed. * @param _reserve the address of the reserve **/ function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = false; } /** * @notice allows the configurator to update the loan to value of a reserve * @param _reserve the address of the reserve * @param _ltv the new loan to value **/ function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.baseLTVasCollateral = _ltv; } /** * @notice allows the configurator to update the liquidation threshold of a reserve * @param _reserve the address of the reserve * @param _threshold the new liquidation threshold **/ function setReserveLiquidationThreshold(address _reserve, uint256 _threshold) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationThreshold = _threshold; } /** * @notice allows the configurator to update the liquidation bonus of a reserve * @param _reserve the address of the reserve * @param _bonus the new liquidation bonus **/ function setReserveLiquidationBonus(address _reserve, uint256 _bonus) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationBonus = _bonus; } /** * @notice allows the configurator to update the reserve decimals * @param _reserve the address of the reserve * @param _decimals the decimals of the reserve **/ function setReserveDecimals(address _reserve, uint256 _decimals) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.decimals = _decimals; } /** * @notice internal functions **/ /** * @dev updates the state of a reserve as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _principalBorrowBalance the previous borrow balance of the borrower before the action * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _amountBorrowed the new amount borrowed * @param _rateMode the borrow rate mode (stable, variable) **/ function updateReserveStateOnBorrowInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _rateMode ) internal { reserves[_reserve].updateCumulativeIndexes(); //increasing reserve total borrows to account for the new borrow balance of the user //NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa updateReserveTotalBorrowsByRateModeInternal( _reserve, _user, _principalBorrowBalance, _balanceIncrease, _amountBorrowed, _rateMode ); } /** * @dev updates the state of a user as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the amount borrowed * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _rateMode the borrow rate mode (stable, variable) * @return the final borrow rate for the user. Emitted by the borrow() event **/ function updateUserStateOnBorrowInternal( address _reserve, address _user, uint256 _amountBorrowed, uint256 _balanceIncrease, uint256 _fee, CoreLibrary.InterestRateMode _rateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (_rateMode == CoreLibrary.InterestRateMode.STABLE) { //stable //reset the user variable index, and update the stable rate user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) { //variable //reset the user stable rate, and store the new borrow index user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid borrow rate mode"); } //increase the principal borrows and the origination fee user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add( _balanceIncrease ); user.originationFee = user.originationFee.add(_fee); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_reserve][_user]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } } /** * @dev updates the state of the user as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateUserStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _paybackAmountMinusFees ); user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; //if the balance decrease is equal to the previous principal (user is repaying the whole loan) //and the rate mode is stable, we reset the interest rate mode of the user if (_repaidWholeLoan) { user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = 0; } user.originationFee = user.originationFee.sub(_originationFeeRepaid); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the rate swap * @param _user the address of the borrower * @param _principalBorrowBalance the the principal amount borrowed by the user * @param _compoundedBorrowBalance the principal amount plus the accrued interest * @param _currentRateMode the rate mode at which the user borrowed **/ function updateReserveStateOnSwapRateInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, CoreLibrary.InterestRateMode _currentRateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //compounding reserve indexes reserve.updateCumulativeIndexes(); if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { uint256 userCurrentStableRate = user.stableBorrowRate; //swap to variable reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBorrowBalance, userCurrentStableRate ); //decreasing stable from old principal balance reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows } else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //swap to stable uint256 currentStableRate = reserve.currentStableBorrowRate; reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _compoundedBorrowBalance, currentStableRate ); } else { revert("Invalid rate mode received"); } } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the swap * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current rate mode of the user **/ function updateUserStateOnSwapRateInternal( address _reserve, address _user, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) internal returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE; if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //switch to stable newMode = CoreLibrary.InterestRateMode.STABLE; user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { newMode = CoreLibrary.InterestRateMode.VARIABLE; user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid interest rate mode received"); } //compounding cumulated interest user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); return newMode; } /** * @dev updates the state of the principal reserve as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updatePrincipalReserveStateOnLiquidationInternal( address _principalReserve, address _user, uint256 _amountToLiquidate, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_principalReserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve]; //update principal reserve data reserve.updateCumulativeIndexes(); CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode( _principalReserve, _user ); if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _amountToLiquidate, user.stableBorrowRate ); } else { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsVariable(_balanceIncrease); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsVariable(_amountToLiquidate); } } /** * @dev updates the state of the collateral reserve as a consequence of a liquidation action. * @param _collateralReserve the address of the collateral reserve that is being liquidated **/ function updateCollateralReserveStateOnLiquidationInternal( address _collateralReserve ) internal { //update collateral reserve reserves[_collateralReserve].updateCumulativeIndexes(); } /** * @dev updates the state of the user being liquidated as a consequence of a liquidation action. * @param _reserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _feeLiquidated the amount of origination fee being liquidated * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnLiquidationInternal( address _reserve, address _user, uint256 _amountToLiquidate, uint256 _feeLiquidated, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; //first increase by the compounded interest, then decrease by the liquidated amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _amountToLiquidate ); if ( getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE ) { user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } if(_feeLiquidated > 0){ user.originationFee = user.originationFee.sub(_feeLiquidated); } //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); user.stableBorrowRate = reserve.currentStableBorrowRate; //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _amountBorrowed the accrued interest on the borrowed amount **/ function updateReserveTotalBorrowsByRateModeInternal( address _reserve, address _user, uint256 _principalBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _newBorrowRateMode ) internal { CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode( _reserve, _user ); CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBalance, user.stableBorrowRate ); } else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.decreaseTotalBorrowsVariable(_principalBalance); } uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed); if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( newPrincipalAmount, reserve.currentStableBorrowRate ); } else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.increaseTotalBorrowsVariable(newPrincipalAmount); } else { revert("Invalid new borrow rate mode"); } } /** * @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. * @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 _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow) **/ function updateReserveInterestRatesAndTimestampInternal( address _reserve, uint256 _liquidityAdded, uint256 _liquidityTaken ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy( reserve .interestRateStrategyAddress ) .calculateInterestRates( _reserve, getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken), reserve.totalBorrowsStable, reserve.totalBorrowsVariable, reserve.currentAverageStableBorrowRate ); reserve.currentLiquidityRate = newLiquidityRate; reserve.currentStableBorrowRate = newStableRate; reserve.currentVariableBorrowRate = newVariableRate; //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); emit ReserveUpdated( _reserve, newLiquidityRate, newStableRate, newVariableRate, reserve.lastLiquidityCumulativeIndex, reserve.lastVariableBorrowCumulativeIndex ); } /** * @dev transfers to the protocol fees of a flashloan to the fees collection address * @param _token the address of the token being transferred * @param _amount the amount being transferred **/ function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal { address payable receiver = address(uint160(addressesProvider.getTokenDistributor())); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(receiver, _amount); } else { receiver.transfer(_amount); } } /** * @dev updates the internal configuration of the core **/ function refreshConfigInternal() internal { lendingPoolAddress = addressesProvider.getLendingPool(); } /** * @dev adds a reserve to the array of the reserves address **/ function addReserveToListInternal(address _reserve) internal { bool reserveAlreadyAdded = false; for (uint256 i = 0; i < reservesList.length; i++) if (reservesList[i] == _reserve) { reserveAlreadyAdded = true; } if (!reserveAlreadyAdded) reservesList.push(_reserve); } }
56,094
30
// Contract to convert liquidity from other market makers (Uniswap/Mooniswap) to our pairs. /
contract AliumVamp is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint constant LIQUIDITY_DEADLINE = 10 * 20; // 10 minutes in blocks, ~3 sec per block struct LPTokenInfo { address lpToken; uint16 tokenType; // Token type: 0 - uniswap (default), 1 - mooniswap } IERC20[] public allowedTokens; // List of tokens that we accept // Info of each third-party lp-token. LPTokenInfo[] public lpTokensInfo; IUniswapV2Router01 public ourRouter; event Deposit(address indexed user, address indexed token, uint256 amount); event AllowedTokenAdded(address indexed token); event AllowedTokenRemoved(address indexed token); event LPTokenAdded(address indexed token, uint256 tokenType); event LPTokenChanged(address indexed oldToken, address indexed newToken, uint256 oldType, uint256 newType); event RouterChanged(address indexed oldRouter, address indexed newRouter); constructor( address[] memory _lptokens, uint8[] memory _types, address _ourrouter ) public { require(_lptokens.length > 0, "AliumVamp: _lptokens length should not be 0!"); require(_lptokens.length == _types.length, "AliumVamp: array lengths should be equal"); require(_ourrouter != address(0), "AliumVamp: _ourrouter address should not be 0"); for (uint256 i = 0; i < _lptokens.length; i++) { lpTokensInfo.push( LPTokenInfo({lpToken: _lptokens[i], tokenType: _types[i]}) ); } ourRouter = IUniswapV2Router01(_ourrouter); } /** * @dev Returns length of allowed tokens private array */ function getAllowedTokensLength() external view returns (uint256) { return allowedTokens.length; } function lpTokensInfoLength() external view returns (uint256) { return lpTokensInfo.length; } /** * @dev Returns pair base tokens */ function lpTokenDetailedInfo(uint256 _pid) external view returns (address, address) { require(_pid < lpTokensInfo.length, "AliumVamp: _pid should be less than lpTokensInfo"); if (lpTokensInfo[_pid].tokenType == 0) { // this is uniswap IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); return (lpToken.token0(), lpToken.token1()); } else { // this is mooniswap IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); return (address(t[0]), address(t[1])); } } /** * @dev Adds new entry to the list of allowed tokens (if it is not exist yet) */ function addAllowedToken(address _token) external onlyOwner { require(_token != address(0),"AliumVamp: _token address should not be 0"); for (uint256 i = 0; i < allowedTokens.length; i++) { if (address(allowedTokens[i]) == _token) { require(false, "AliumVamp: Token already exists!"); } } emit AllowedTokenAdded(_token); allowedTokens.push(IERC20(_token)); } /** * @dev Remove entry from the list of allowed tokens */ function removeAllowedToken(uint _idx) external onlyOwner { require(_idx < allowedTokens.length, "AliumVamp: _idx out of range"); emit AllowedTokenRemoved(address(allowedTokens[_idx])); delete allowedTokens[_idx]; } /** * @dev Adds new entry to the list of convertible LP-tokens */ function addLPToken(address _token, uint16 _tokenType) external onlyOwner returns (uint256) { require(_token != address(0),"AliumVamp: _token address should not be 0!"); require(_tokenType < 2,"AliumVamp: wrong token type!"); for (uint256 i = 0; i < lpTokensInfo.length; i++) { if (lpTokensInfo[i].lpToken == _token) { require(false, "AliumVamp: Token already exists!"); } } lpTokensInfo.push( LPTokenInfo({lpToken: _token, tokenType: _tokenType}) ); emit LPTokenAdded(_token, _tokenType); return lpTokensInfo.length; } /** * @dev Remove entry from the list of convertible LP-tokens */ function changeLPToken(uint _idx, address _token, uint16 _tokenType) external onlyOwner { require(_idx < lpTokensInfo.length, "AliumVamp: _idx out of range"); require(_token != address(0), "AliumVamp: _token address should not be 0!"); require(_tokenType < 2, "AliumVamp: wrong tokenType"); emit LPTokenChanged(lpTokensInfo[_idx].lpToken, _token, lpTokensInfo[_idx].tokenType, _tokenType); lpTokensInfo[_idx].lpToken = _token; lpTokensInfo[_idx].tokenType = _tokenType; } /** * @dev Change router address */ function changeRouter(address _newRouter) external onlyOwner { require(_newRouter != address(0), "New Router address is wrong"); emit RouterChanged(address(ourRouter), _newRouter); ourRouter = IUniswapV2Router01(_newRouter); } // Deposit LP tokens to us /** * @dev Main function that converts third-party liquidity (represented by LP-tokens) to our own LP-tokens */ function deposit(uint256 _pid, uint256 _amount) external { require(_pid < lpTokensInfo.length, "AliumVamp: _pid out of range!"); if (lpTokensInfo[_pid].tokenType == 0) { _depositUniswap(_pid, _amount); } else if (lpTokensInfo[_pid].tokenType == 1) { _depositMooniswap(_pid, _amount); } else { return; } emit Deposit(msg.sender, lpTokensInfo[_pid].lpToken, _amount); } /** * @dev Actual function that converts third-party Uniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositUniswap(uint256 _pid, uint256 _amount) internal { IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); // check pair existance IERC20 token0 = IERC20(lpToken.token0()); IERC20 token1 = IERC20(lpToken.token1()); // transfer to us TransferHelper.safeTransferFrom(address(lpToken), address(msg.sender), address(lpToken), _amount); // get liquidity (uint256 amountIn0, uint256 amountIn1) = lpToken.burn(address(this)); _addLiquidity( address(token0), address(token1), amountIn0, amountIn1, msg.sender ); } function _addLiquidity( address _token0, address _token1, uint256 _amount0, uint256 _amount1, address _receiver ) internal { TransferHelper.safeApprove(_token0, address(ourRouter), _amount0); TransferHelper.safeApprove(_token1, address(ourRouter), _amount1); (uint256 amountOut0, uint256 amountOut1, ) = ourRouter.addLiquidity( address(_token0), address(_token1), _amount0, _amount1, 0, 0, _receiver, block.timestamp + LIQUIDITY_DEADLINE ); // return the change if (amountOut0 < _amount0) { // consumed less tokens than given TransferHelper.safeTransfer( _token0, address(msg.sender), _amount0.sub(amountOut0) ); } if (amountOut1 < _amount1) { // consumed less tokens than given TransferHelper.safeTransfer( _token1, address(msg.sender), _amount1.sub(amountOut1) ); } TransferHelper.safeApprove(_token0, address(ourRouter), 0); TransferHelper.safeApprove(_token1, address(ourRouter), 0); } /** * @dev Actual function that converts third-party Mooniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositMooniswap(uint256 _pid, uint256 _amount) internal { IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); // check pair existance IERC20 token0 = IERC20(t[0]); IERC20 token1 = IERC20(t[1]); // transfer to us TransferHelper.safeTransferFrom(address(lpToken), address(msg.sender), address(this), _amount); uint256 amountBefore0 = token0.balanceOf(address(this)); uint256 amountBefore1 = token1.balanceOf(address(this)); uint256[] memory minVals = new uint256[](2); lpToken.withdraw(_amount, minVals); // get liquidity uint256 amount0 = token0.balanceOf(address(this)).sub(amountBefore0); uint256 amount1 = token1.balanceOf(address(this)).sub(amountBefore1); _addLiquidity( address(token0), address(token1), amount0, amount1, msg.sender ); } /** * @dev Function check for LP token pair availability. Return _pid or 0 if none exists */ function isPairAvailable(address _token0, address _token1) external view returns (uint16) { require(_token0 != address(0), "AliumVamp: _token0 address should not be 0!"); require(_token1 != address(0), "AliumVamp: _token1 address should not be 0!"); for (uint16 i = 0; i < lpTokensInfo.length; i++) { address t0 = address(0); address t1 = address(0); if (lpTokensInfo[i].tokenType == 0) { IUniswapV2Pair lpt = IUniswapV2Pair(lpTokensInfo[i].lpToken); t0 = lpt.token0(); t1 = lpt.token1(); } else if (lpTokensInfo[i].tokenType == 1) { IMooniswap lpToken = IMooniswap(lpTokensInfo[i].lpToken); IERC20[] memory t = lpToken.getTokens(); t0 = address(t[0]); t1 = address(t[1]); } else { return 0; } if ( (t0 == _token0 && t1 == _token1) || (t1 == _token0 && t0 == _token1) ) { return 1; } } return 0; } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token( address tokenAddress, address beneficiary, uint256 amount ) external onlyOwner returns (bool success) { require(tokenAddress != address(0), "AliumVamp: Token address cannot be 0"); return IERC20(tokenAddress).transfer(beneficiary, amount); } }
contract AliumVamp is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint constant LIQUIDITY_DEADLINE = 10 * 20; // 10 minutes in blocks, ~3 sec per block struct LPTokenInfo { address lpToken; uint16 tokenType; // Token type: 0 - uniswap (default), 1 - mooniswap } IERC20[] public allowedTokens; // List of tokens that we accept // Info of each third-party lp-token. LPTokenInfo[] public lpTokensInfo; IUniswapV2Router01 public ourRouter; event Deposit(address indexed user, address indexed token, uint256 amount); event AllowedTokenAdded(address indexed token); event AllowedTokenRemoved(address indexed token); event LPTokenAdded(address indexed token, uint256 tokenType); event LPTokenChanged(address indexed oldToken, address indexed newToken, uint256 oldType, uint256 newType); event RouterChanged(address indexed oldRouter, address indexed newRouter); constructor( address[] memory _lptokens, uint8[] memory _types, address _ourrouter ) public { require(_lptokens.length > 0, "AliumVamp: _lptokens length should not be 0!"); require(_lptokens.length == _types.length, "AliumVamp: array lengths should be equal"); require(_ourrouter != address(0), "AliumVamp: _ourrouter address should not be 0"); for (uint256 i = 0; i < _lptokens.length; i++) { lpTokensInfo.push( LPTokenInfo({lpToken: _lptokens[i], tokenType: _types[i]}) ); } ourRouter = IUniswapV2Router01(_ourrouter); } /** * @dev Returns length of allowed tokens private array */ function getAllowedTokensLength() external view returns (uint256) { return allowedTokens.length; } function lpTokensInfoLength() external view returns (uint256) { return lpTokensInfo.length; } /** * @dev Returns pair base tokens */ function lpTokenDetailedInfo(uint256 _pid) external view returns (address, address) { require(_pid < lpTokensInfo.length, "AliumVamp: _pid should be less than lpTokensInfo"); if (lpTokensInfo[_pid].tokenType == 0) { // this is uniswap IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); return (lpToken.token0(), lpToken.token1()); } else { // this is mooniswap IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); return (address(t[0]), address(t[1])); } } /** * @dev Adds new entry to the list of allowed tokens (if it is not exist yet) */ function addAllowedToken(address _token) external onlyOwner { require(_token != address(0),"AliumVamp: _token address should not be 0"); for (uint256 i = 0; i < allowedTokens.length; i++) { if (address(allowedTokens[i]) == _token) { require(false, "AliumVamp: Token already exists!"); } } emit AllowedTokenAdded(_token); allowedTokens.push(IERC20(_token)); } /** * @dev Remove entry from the list of allowed tokens */ function removeAllowedToken(uint _idx) external onlyOwner { require(_idx < allowedTokens.length, "AliumVamp: _idx out of range"); emit AllowedTokenRemoved(address(allowedTokens[_idx])); delete allowedTokens[_idx]; } /** * @dev Adds new entry to the list of convertible LP-tokens */ function addLPToken(address _token, uint16 _tokenType) external onlyOwner returns (uint256) { require(_token != address(0),"AliumVamp: _token address should not be 0!"); require(_tokenType < 2,"AliumVamp: wrong token type!"); for (uint256 i = 0; i < lpTokensInfo.length; i++) { if (lpTokensInfo[i].lpToken == _token) { require(false, "AliumVamp: Token already exists!"); } } lpTokensInfo.push( LPTokenInfo({lpToken: _token, tokenType: _tokenType}) ); emit LPTokenAdded(_token, _tokenType); return lpTokensInfo.length; } /** * @dev Remove entry from the list of convertible LP-tokens */ function changeLPToken(uint _idx, address _token, uint16 _tokenType) external onlyOwner { require(_idx < lpTokensInfo.length, "AliumVamp: _idx out of range"); require(_token != address(0), "AliumVamp: _token address should not be 0!"); require(_tokenType < 2, "AliumVamp: wrong tokenType"); emit LPTokenChanged(lpTokensInfo[_idx].lpToken, _token, lpTokensInfo[_idx].tokenType, _tokenType); lpTokensInfo[_idx].lpToken = _token; lpTokensInfo[_idx].tokenType = _tokenType; } /** * @dev Change router address */ function changeRouter(address _newRouter) external onlyOwner { require(_newRouter != address(0), "New Router address is wrong"); emit RouterChanged(address(ourRouter), _newRouter); ourRouter = IUniswapV2Router01(_newRouter); } // Deposit LP tokens to us /** * @dev Main function that converts third-party liquidity (represented by LP-tokens) to our own LP-tokens */ function deposit(uint256 _pid, uint256 _amount) external { require(_pid < lpTokensInfo.length, "AliumVamp: _pid out of range!"); if (lpTokensInfo[_pid].tokenType == 0) { _depositUniswap(_pid, _amount); } else if (lpTokensInfo[_pid].tokenType == 1) { _depositMooniswap(_pid, _amount); } else { return; } emit Deposit(msg.sender, lpTokensInfo[_pid].lpToken, _amount); } /** * @dev Actual function that converts third-party Uniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositUniswap(uint256 _pid, uint256 _amount) internal { IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); // check pair existance IERC20 token0 = IERC20(lpToken.token0()); IERC20 token1 = IERC20(lpToken.token1()); // transfer to us TransferHelper.safeTransferFrom(address(lpToken), address(msg.sender), address(lpToken), _amount); // get liquidity (uint256 amountIn0, uint256 amountIn1) = lpToken.burn(address(this)); _addLiquidity( address(token0), address(token1), amountIn0, amountIn1, msg.sender ); } function _addLiquidity( address _token0, address _token1, uint256 _amount0, uint256 _amount1, address _receiver ) internal { TransferHelper.safeApprove(_token0, address(ourRouter), _amount0); TransferHelper.safeApprove(_token1, address(ourRouter), _amount1); (uint256 amountOut0, uint256 amountOut1, ) = ourRouter.addLiquidity( address(_token0), address(_token1), _amount0, _amount1, 0, 0, _receiver, block.timestamp + LIQUIDITY_DEADLINE ); // return the change if (amountOut0 < _amount0) { // consumed less tokens than given TransferHelper.safeTransfer( _token0, address(msg.sender), _amount0.sub(amountOut0) ); } if (amountOut1 < _amount1) { // consumed less tokens than given TransferHelper.safeTransfer( _token1, address(msg.sender), _amount1.sub(amountOut1) ); } TransferHelper.safeApprove(_token0, address(ourRouter), 0); TransferHelper.safeApprove(_token1, address(ourRouter), 0); } /** * @dev Actual function that converts third-party Mooniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositMooniswap(uint256 _pid, uint256 _amount) internal { IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); // check pair existance IERC20 token0 = IERC20(t[0]); IERC20 token1 = IERC20(t[1]); // transfer to us TransferHelper.safeTransferFrom(address(lpToken), address(msg.sender), address(this), _amount); uint256 amountBefore0 = token0.balanceOf(address(this)); uint256 amountBefore1 = token1.balanceOf(address(this)); uint256[] memory minVals = new uint256[](2); lpToken.withdraw(_amount, minVals); // get liquidity uint256 amount0 = token0.balanceOf(address(this)).sub(amountBefore0); uint256 amount1 = token1.balanceOf(address(this)).sub(amountBefore1); _addLiquidity( address(token0), address(token1), amount0, amount1, msg.sender ); } /** * @dev Function check for LP token pair availability. Return _pid or 0 if none exists */ function isPairAvailable(address _token0, address _token1) external view returns (uint16) { require(_token0 != address(0), "AliumVamp: _token0 address should not be 0!"); require(_token1 != address(0), "AliumVamp: _token1 address should not be 0!"); for (uint16 i = 0; i < lpTokensInfo.length; i++) { address t0 = address(0); address t1 = address(0); if (lpTokensInfo[i].tokenType == 0) { IUniswapV2Pair lpt = IUniswapV2Pair(lpTokensInfo[i].lpToken); t0 = lpt.token0(); t1 = lpt.token1(); } else if (lpTokensInfo[i].tokenType == 1) { IMooniswap lpToken = IMooniswap(lpTokensInfo[i].lpToken); IERC20[] memory t = lpToken.getTokens(); t0 = address(t[0]); t1 = address(t[1]); } else { return 0; } if ( (t0 == _token0 && t1 == _token1) || (t1 == _token0 && t0 == _token1) ) { return 1; } } return 0; } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token( address tokenAddress, address beneficiary, uint256 amount ) external onlyOwner returns (bool success) { require(tokenAddress != address(0), "AliumVamp: Token address cannot be 0"); return IERC20(tokenAddress).transfer(beneficiary, amount); } }
16,318
1,170
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee);
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee);
49,546
7
// Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supplyreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function mint(uint mintAmount) override external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256)", mintAmount)); return abi.decode(data, (uint)); }
function mint(uint mintAmount) override external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256)", mintAmount)); return abi.decode(data, (uint)); }
11,706
2
// Storage // Modifiers // Checks that the the account passed is a valid switch To be used in any situation where the function performs a check of existing/valid switches account The account to check the validity of /
modifier onlyValid(address account) { require(users[account].isValid && users[account].amount > 0, "Not a valid account query"); _; }
modifier onlyValid(address account) { require(users[account].isValid && users[account].amount > 0, "Not a valid account query"); _; }
30,882
6
// Dev address
address private _dev;
address private _dev;
14,720
38
// The nodehash of this label
bytes32 nodehash = keccak256(abi.encodePacked(base.baseNode(), vars.label));
bytes32 nodehash = keccak256(abi.encodePacked(base.baseNode(), vars.label));
25,282
43
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.sub(_amount); } else {
if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.sub(_amount); } else {
25,232
60
// more liquidity was minted
event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to);
event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to);
38,734
2
// VaultAdmin.sol
function setPriceProvider(address _priceProvider) external; function priceProvider() external view returns (address); function setRedeemFeeBps(uint256 _redeemFeeBps) external; function redeemFeeBps() external view returns (uint256); function setVaultBuffer(uint256 _vaultBuffer) external;
function setPriceProvider(address _priceProvider) external; function priceProvider() external view returns (address); function setRedeemFeeBps(uint256 _redeemFeeBps) external; function redeemFeeBps() external view returns (uint256); function setVaultBuffer(uint256 _vaultBuffer) external;
5,006
102
// Utility method which contains the logic of the constructor.This is a useful trick to instantiate a contract when it is cloned. /
function init( address interoperableInterfaceModel, string memory name, string memory symbol
function init( address interoperableInterfaceModel, string memory name, string memory symbol
23,321
79
// Interface Views //Gets a specified subcourt's non primitive properties._subcourtID The ID of the subcourt. return children The subcourt's child court list. return timesPerPeriod The subcourt's time per period. /
function getSubcourt( uint96 _subcourtID
function getSubcourt( uint96 _subcourtID
12,439
5
// Operation address.
address public operationaddr;
address public operationaddr;
26,412
64
// restrictions on amounts during the crowdfunding event stages
maxPreSale = 30000000 * 1 ether; maxIco = 60000000 * 1 ether;
maxPreSale = 30000000 * 1 ether; maxIco = 60000000 * 1 ether;
28,607
17
// Multiplies two numbers, throws on overflow./
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
136
16
// Register first airline
if (registeredAirlines.length == 0) { result = flightSuretyData.registerAirline(name, addr); } else if (
if (registeredAirlines.length == 0) { result = flightSuretyData.registerAirline(name, addr); } else if (
47,245
45
// |/Transfers amount of an _id from the _from address to the _to address specifiedMUST emit TransferSingle event on success Caller must be approved to manage the _from account's tokens (see isApprovedForAll) MUST throw if `_to` is the zero address MUST throw if balance of sender for token `_id` is lower than the `_amount` sent MUST throw on any other error When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`_fromSource address_toTarget address_idID of the token
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
28,270
48
// Update debt position token
debtPositions[_tokenId].supplied -= _suppliedAmount; debtPositions[_tokenId].borrowed -= _amount;
debtPositions[_tokenId].supplied -= _suppliedAmount; debtPositions[_tokenId].borrowed -= _amount;
22,877
266
// Require the amount of capital held to be greater than the previously credited units
require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase");
require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase");
49,732
55
// send tokens to the address who refferred the airdrop
if (REFERRAL_AMOUNT > 0 && _referralAddress != 0x0000000000000000000000000000000000000000) { token.transferFrom(AIRDROPPER, _referralAddress, REFERRAL_AMOUNT); }
if (REFERRAL_AMOUNT > 0 && _referralAddress != 0x0000000000000000000000000000000000000000) { token.transferFrom(AIRDROPPER, _referralAddress, REFERRAL_AMOUNT); }
53,365
634
// require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender));
bytes4 minIACurr;
bytes4 minIACurr;
6,114
18
// after bit shift left 12 bytes are zeros automatically
executor := shr(96, blob) gasLimit := and(shr(64, blob), 0xffffffff) dataType := byte(26, blob)
executor := shr(96, blob) gasLimit := and(shr(64, blob), 0xffffffff) dataType := byte(26, blob)
50,192
143
// Distribute funds to multiple addresses using ETH sendto this payable function. Array length must be equal, ETH sent must equal the sum of amounts. receivers list of addresses amounts list of amounts /
function distributeFunds( address payable[] calldata receivers, uint[] calldata amounts ) external payable
function distributeFunds( address payable[] calldata receivers, uint[] calldata amounts ) external payable
34,738
131
// Get token balance of proxy after redeem
uint256 afterTokenAmount = IERC20(token).balanceOf(address(this));
uint256 afterTokenAmount = IERC20(token).balanceOf(address(this));
70,921
0
// Token that serves as a reserve for PYLON
address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public pylonAddress;
address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public pylonAddress;
30,087
5
// Pool Configuration with a Weighted Interest Rate Model and Ranged CollectionCollateral Filter MetaStreet Labs /
contract WeightedRateMerkleCollectionPool is Pool, WeightedInterestRateModel, MerkleCollectionCollateralFilter { /**************************************************************************/ /* State */ /**************************************************************************/ /** * @notice Initialized boolean */ bool private _initialized; /**************************************************************************/ /* Constructor */ /**************************************************************************/ /** * @notice Pool constructor * @param collateralLiquidator Collateral liquidator * @param delegationRegistry Delegation registry contract * @param collateralWrappers Collateral wrappers * @param parameters WeightedInterestRateModel parameters */ constructor( address collateralLiquidator, address delegationRegistry, address[] memory collateralWrappers, WeightedInterestRateModel.Parameters memory parameters ) Pool(collateralLiquidator, delegationRegistry, collateralWrappers) WeightedInterestRateModel(parameters) { /* Disable initialization of implementation contract */ _initialized = true; } /**************************************************************************/ /* Initializer */ /**************************************************************************/ function initialize(bytes memory params) external { require(!_initialized, "Already initialized"); _initialized = true; /* Decode parameters */ ( address collateralToken_, bytes32 merkleRoot_, uint32 nodeCount_, string memory metadataURI_, address currencyToken_, uint64[] memory durations_, uint64[] memory rates_ ) = abi.decode(params, (address, bytes32, uint32, string, address, uint64[], uint64[])); /* Initialize Collateral Filter */ MerkleCollectionCollateralFilter._initialize(collateralToken_, merkleRoot_, nodeCount_, metadataURI_); /* Initialize Pool */ Pool._initialize(currencyToken_, durations_, rates_); } /**************************************************************************/ /* Name */ /**************************************************************************/ /** * @inheritdoc Pool */ function IMPLEMENTATION_NAME() external pure override returns (string memory) { return "WeightedRateMerkleCollectionPool"; } }
contract WeightedRateMerkleCollectionPool is Pool, WeightedInterestRateModel, MerkleCollectionCollateralFilter { /**************************************************************************/ /* State */ /**************************************************************************/ /** * @notice Initialized boolean */ bool private _initialized; /**************************************************************************/ /* Constructor */ /**************************************************************************/ /** * @notice Pool constructor * @param collateralLiquidator Collateral liquidator * @param delegationRegistry Delegation registry contract * @param collateralWrappers Collateral wrappers * @param parameters WeightedInterestRateModel parameters */ constructor( address collateralLiquidator, address delegationRegistry, address[] memory collateralWrappers, WeightedInterestRateModel.Parameters memory parameters ) Pool(collateralLiquidator, delegationRegistry, collateralWrappers) WeightedInterestRateModel(parameters) { /* Disable initialization of implementation contract */ _initialized = true; } /**************************************************************************/ /* Initializer */ /**************************************************************************/ function initialize(bytes memory params) external { require(!_initialized, "Already initialized"); _initialized = true; /* Decode parameters */ ( address collateralToken_, bytes32 merkleRoot_, uint32 nodeCount_, string memory metadataURI_, address currencyToken_, uint64[] memory durations_, uint64[] memory rates_ ) = abi.decode(params, (address, bytes32, uint32, string, address, uint64[], uint64[])); /* Initialize Collateral Filter */ MerkleCollectionCollateralFilter._initialize(collateralToken_, merkleRoot_, nodeCount_, metadataURI_); /* Initialize Pool */ Pool._initialize(currencyToken_, durations_, rates_); } /**************************************************************************/ /* Name */ /**************************************************************************/ /** * @inheritdoc Pool */ function IMPLEMENTATION_NAME() external pure override returns (string memory) { return "WeightedRateMerkleCollectionPool"; } }
13,475
93
// Do we need to pay royalty?
bool _payRoyalty = IERC20Upgradeable(ara).balanceOf(lot.seller) < araAmount; if (_payRoyalty) { _payRoyalty = IERC721Upgradeable(rad).balanceOf(lot.seller) < 1; }
bool _payRoyalty = IERC20Upgradeable(ara).balanceOf(lot.seller) < araAmount; if (_payRoyalty) { _payRoyalty = IERC721Upgradeable(rad).balanceOf(lot.seller) < 1; }
57,856
117
// Distributes payouts for a project with the distribution limit of its current funding cycle./Payouts are sent to the preprogrammed splits. Any leftover is sent to the project's owner./Anyone can distribute payouts on a project's behalf. The project can preconfigure a wildcard split that is used to send funds to msg.sender. This can be used to incentivize calling this function./All funds distributed outside of this contract or any feeless terminals incure the protocol fee./_projectId The ID of the project having its payouts distributed./_amount The amount of terminal tokens to distribute, as a fixed point number with same number of decimals as
function _distributePayoutsOf( uint256 _projectId, uint256 _amount, uint256 _currency, uint256 _minReturnedTokens, bytes calldata _metadata
function _distributePayoutsOf( uint256 _projectId, uint256 _amount, uint256 _currency, uint256 _minReturnedTokens, bytes calldata _metadata
30,229
179
// if there are winners then calculate the rise in admin fee & update both admin fee & interest accordingly
adminfeeShareForDifference = (difference * adminFee) / 100; totalGameInterest = difference > 0 ? _grossInterest - (_adminFeeAmount[0] + adminfeeShareForDifference) : totalGameInterest;
adminfeeShareForDifference = (difference * adminFee) / 100; totalGameInterest = difference > 0 ? _grossInterest - (_adminFeeAmount[0] + adminfeeShareForDifference) : totalGameInterest;
17,957
121
// Accrue interest
extraAmount = uint256(_totalBorrow.elastic).mul(_accrueInfo.interestPerSecond).mul(elapsedTime) / 1e18; _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount.to128()); uint256 fullAssetAmount = bentoBox.toAmount(asset, _totalAsset.elastic, false).add(_totalBorrow.elastic); uint256 feeAmount = extraAmount.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of interest paid goes to fee feeFraction = feeAmount.mul(_totalAsset.base) / fullAssetAmount; _accrueInfo.feesEarnedFraction = _accrueInfo.feesEarnedFraction.add(feeFraction.to128()); totalAsset.base = _totalAsset.base.add(feeFraction.to128()); totalBorrow = _totalBorrow;
extraAmount = uint256(_totalBorrow.elastic).mul(_accrueInfo.interestPerSecond).mul(elapsedTime) / 1e18; _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount.to128()); uint256 fullAssetAmount = bentoBox.toAmount(asset, _totalAsset.elastic, false).add(_totalBorrow.elastic); uint256 feeAmount = extraAmount.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of interest paid goes to fee feeFraction = feeAmount.mul(_totalAsset.base) / fullAssetAmount; _accrueInfo.feesEarnedFraction = _accrueInfo.feesEarnedFraction.add(feeFraction.to128()); totalAsset.base = _totalAsset.base.add(feeFraction.to128()); totalBorrow = _totalBorrow;
9,177
7
// This function deploys a EulerUser contract associated with a/ given public key. Anybody can call this function from a multisig./pubkey: The user pubkey
function new_user( uint256 pubkey ) public view returns ( address addr )
function new_user( uint256 pubkey ) public view returns ( address addr )
34,417
271
// Update existing digitalMedia's metadata, totalSupply, collaborated, royaltyand immutable attribute. Once a media is immutable you cannot call this function /
function updateManyMedias(DigitalMediaUpdateRequest[] memory requests)
function updateManyMedias(DigitalMediaUpdateRequest[] memory requests)
81,934
23
// Ether and Wei. This is the value {ERC20} uses, unless this function isoverridden; NOTE: This information is only used for _display_ purposes: it inno way affects any of the arithmetic of the contract, including{IERC20-balanceOf} and {IERC20-transfer}. /
function decimals() public view virtual override returns (uint8) { return 18; }
function decimals() public view virtual override returns (uint8) { return 18; }
202
131
// URI's default URI prefix
string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id);
string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id);
23,144
267
// Sets the implementation address of the proxy. newImplementation Address of the new implementation. /
function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
2,468
86
// Nametag Manager.Nametag is the canonical profile manager for Zer0net. /
contract Nametag is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'nametag'; event Update( string indexed nametag, string indexed field, bytes data ); event Permissions( address indexed owner, address indexed delegate, bytes permissions ); event Respect( address indexed owner, address indexed peer, uint respect ); /*************************************************************************** * * Constructor */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. // _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Nametag(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" nametag owner. */ modifier onlyNametagOwner( string _nametag ) { /* Calculate owner hash. */ bytes32 ownerHash = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.owner' )); /* Retrieve nametag owner. */ address nametagOwner = _zer0netDb.getAddress(ownerHash); /* Validate nametag owner. */ require(msg.sender == nametagOwner); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Give Respect (To Another Peer) */ function giveRespect( address _peer, uint _respect ) public returns (bool success) { /* Set respect. */ return _setRespect(msg.sender, _peer, _respect); } /** * Give Respect (To Another Peer by Relayer) */ function giveRespect( address _peer, uint _respect, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _peer, _respect, _expires, _nonce )); bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', hash)); /* Retrieve the authorized signer. */ address signer = _ecRecovery().recover(sigHash, _signature); /* Set respect. */ return _setRespect(signer, _peer, _respect); } /** * Show Respect (For Another Peer) */ function showRespectFor( address _peer ) external view returns (uint respect) { /* Show respect (value). */ return _getRespect(msg.sender, _peer); } /** * Show Respect (Between Two Peers) */ function showRespect( address _owner, address _peer ) external view returns ( uint respect, uint reciprocal ) { /* Retriieve respect (value). */ respect = _getRespect(_owner, _peer); /* Retriieve respect (value). */ reciprocal = _getRespect(_peer, _owner); } /*************************************************************************** * * GETTERS * */ /** * Get Data * * Retrieves the value for the given nametag id and data field. */ function getData( string _nametag, string _field ) external view returns (bytes data) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _field )); /* Retrieve data. */ data = _zer0netDb.getBytes(dataId); } /** * Get Permissions * * Owners can grant authority to delegated accounts with pre-determined * abilities for managing the primary account. * * This allows them to carry-out normal, everyday functions without * exposing the security of a more secure account. */ function getPermissions( string _nametag, address _owner, address _delegate ) external view returns (bytes permissions) { /* Set hash. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _owner, '.', _delegate, '.permissions' )); /* Save data to database. */ permissions = _zer0netDb.getBytes(dataId); } /** * Get Respect */ function _getRespect( address _owner, address _peer ) private view returns (uint respect) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _owner, '.respect.for.', _peer )); /* Retrieve data from database. */ respect = _zer0netDb.getUint(dataId); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /*************************************************************************** * * SETTERS * */ /** * Set (Nametag) Data * * NOTE: Nametags are NOT permanent, and WILL become vacated after an * extended period of inactivity. * * *** LIMIT OF ONE AUTHORIZED ACCOUNT / ADDRESS PER NAMETAG *** */ function setData( string _nametag, string _field, bytes _data ) external onlyNametagOwner(_nametag) returns (bool success) { /* Set data. */ return _setData( _nametag, _field, _data ); } /** * Set (Nametag) Data (by Relayer) */ function setData( string _nametag, string _field, bytes _data, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _nametag, _field, _data, _expires, _nonce )); /* Validate signature. */ if (!_validateSignature(_nametag, hash, _signature)) { revert('Oops! Your signature is INVALID.'); } /* Set data. */ return _setData( _nametag, _field, _data ); } /** * @notice Set nametag info. * * @dev Calculate the `_root` hash and use it to store a * definition string in the eternal database. * * NOTE: Markdown will be the default format for definitions. */ function _setData( string _nametag, string _field, bytes _data ) private returns (bool success) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _field )); /* Save data to database. */ _zer0netDb.setBytes(dataId, _data); /* Broadcast event. */ emit Update( _nametag, _field, _data ); /* Return success. */ return true; } /** * Set Permissions */ function setPermissions( string _nametag, address _delegate, bytes _permissions ) external returns (bool success) { /* Set permissions. */ return _setPermissions( _nametag, msg.sender, _delegate, _permissions ); } /** * Set Permissions */ function setPermissions( string _nametag, address _owner, address _delegate, bytes _permissions, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _nametag, _owner, _delegate, _permissions, _expires, _nonce )); /* Validate signature. */ if (!_validateSignature(_nametag, hash, _signature)) { revert('Oops! Your signature is INVALID.'); } /* Set permissions. */ return _setPermissions( _nametag, _owner, _delegate, _permissions ); } /** * Set Permissions * * Allows owners to delegate another Ethereum account * to proxy commands as if they are the primary account. * * Permissions are encoded as TWO (2) bytes in a bytes array. ALL permissions * are assumed to be false, unless explicitly specified in this bytes array. * * Proposed Permissions List * ------------------------- * * TODO Review Web3 JSON api for best (data access) structure. * (see https://web3js.readthedocs.io/en/1.0/web3.html) * * Profile Management (0x10__) * 0x1001 => Modify Public Info * 0x1002 => Modify Private Info * 0x1003 => Modify Permissions * * HODL Management (0x20__) * 0x2001 => Deposit Tokens * 0x2002 => Withdraw Tokens * * SPEDN Management (0x30__) * 0x3001 => Transfer ANY ERC * 0x3002 => Transfer ERC-20 * 0x3003 => Transfer ERC-721 * * STAEK Management (0x40__) * 0x4001 => Increase Staek * 0x4002 => Decrease Staek * 0x4003 => Shift/Transfer Staek * * Exchange / Trade Execution (0x50__) * 0x5001 => Place Order (Maker) * 0x5002 => Place Order (Taker) * 0x5003 => Margin Account * * Voting & Governance (0x60__) * 0x6001 => Cast Vote * * (this specification is in active development and subject to change) * * NOTE: Permissions WILL NOT be transferred between owners. */ function _setPermissions( string _nametag, address _owner, address _delegate, bytes _permissions ) private returns (bool success) { /* Set data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _owner, '.', _delegate, '.permissions' )); /* Save data to database. */ _zer0netDb.setBytes(dataId, _permissions); /* Broadcast event. */ emit Permissions(_owner, _delegate, _permissions); /* Return success. */ return true; } /** * Set Respect */ function _setRespect( address _owner, address _peer, uint _respect ) private returns (bool success) { /* Validate respect. */ if (_respect == 0) { revert('Oops! Your respect is TOO LOW.'); } /* Validate respect. */ if (_respect > 5) { revert('Oops! Your respect is TOO MUCH.'); } /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _owner, '.respect.for.', _peer )); /* Save data to database. */ _zer0netDb.setUint(dataId, _respect); /* Broadcast event. */ emit Respect( _owner, _peer, _respect ); /* Return success. */ return true; } /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthBy0Admin external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * ZeroCache Interface * * Retrieves the current ZeroCache interface, * using the aname record from Zer0netDb. */ function _zeroCache() private view returns ( ZeroCacheInterface zeroCache ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.zerocache'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ zeroCache = ZeroCacheInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Validate Signature */ function _validateSignature( string _nametag, bytes32 _sigHash, bytes _signature ) private view returns (bool authorized) { /* Calculate owner hash. */ bytes32 ownerHash = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.owner' )); /* Retrieve nametag owner. */ address nametagOwner = _zer0netDb.getAddress(ownerHash); /* Calculate signature hash. */ bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', _sigHash)); /* Retrieve the authorized signer. */ address signer = _ecRecovery().recover(sigHash, _signature); /* Validate signer. */ authorized = (signer == nametagOwner); } /** * Is (Owner) Contract * * Tests if a specified account / address is a contract. */ function _ownerIsContract( address _owner ) private view returns (bool isContract) { /* Initialize code length. */ uint codeLength; /* Run assembly. */ assembly { /* Retrieve the size of the code on target address. */ codeLength := extcodesize(_owner) } /* Set test result. */ isContract = (codeLength > 0); } /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress( bytes _address ) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data, uint _offset ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i + _offset] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } /** * Transfer Any ERC20 Token * * @notice Owner can transfer out any accidentally sent ERC20 tokens. * * @dev Provides an ERC20 interface, which allows for the recover * of any accidentally sent ERC20 tokens. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _tokens); } }
contract Nametag is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'nametag'; event Update( string indexed nametag, string indexed field, bytes data ); event Permissions( address indexed owner, address indexed delegate, bytes permissions ); event Respect( address indexed owner, address indexed peer, uint respect ); /*************************************************************************** * * Constructor */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. // _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Nametag(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" nametag owner. */ modifier onlyNametagOwner( string _nametag ) { /* Calculate owner hash. */ bytes32 ownerHash = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.owner' )); /* Retrieve nametag owner. */ address nametagOwner = _zer0netDb.getAddress(ownerHash); /* Validate nametag owner. */ require(msg.sender == nametagOwner); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Give Respect (To Another Peer) */ function giveRespect( address _peer, uint _respect ) public returns (bool success) { /* Set respect. */ return _setRespect(msg.sender, _peer, _respect); } /** * Give Respect (To Another Peer by Relayer) */ function giveRespect( address _peer, uint _respect, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _peer, _respect, _expires, _nonce )); bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', hash)); /* Retrieve the authorized signer. */ address signer = _ecRecovery().recover(sigHash, _signature); /* Set respect. */ return _setRespect(signer, _peer, _respect); } /** * Show Respect (For Another Peer) */ function showRespectFor( address _peer ) external view returns (uint respect) { /* Show respect (value). */ return _getRespect(msg.sender, _peer); } /** * Show Respect (Between Two Peers) */ function showRespect( address _owner, address _peer ) external view returns ( uint respect, uint reciprocal ) { /* Retriieve respect (value). */ respect = _getRespect(_owner, _peer); /* Retriieve respect (value). */ reciprocal = _getRespect(_peer, _owner); } /*************************************************************************** * * GETTERS * */ /** * Get Data * * Retrieves the value for the given nametag id and data field. */ function getData( string _nametag, string _field ) external view returns (bytes data) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _field )); /* Retrieve data. */ data = _zer0netDb.getBytes(dataId); } /** * Get Permissions * * Owners can grant authority to delegated accounts with pre-determined * abilities for managing the primary account. * * This allows them to carry-out normal, everyday functions without * exposing the security of a more secure account. */ function getPermissions( string _nametag, address _owner, address _delegate ) external view returns (bytes permissions) { /* Set hash. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _owner, '.', _delegate, '.permissions' )); /* Save data to database. */ permissions = _zer0netDb.getBytes(dataId); } /** * Get Respect */ function _getRespect( address _owner, address _peer ) private view returns (uint respect) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _owner, '.respect.for.', _peer )); /* Retrieve data from database. */ respect = _zer0netDb.getUint(dataId); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /*************************************************************************** * * SETTERS * */ /** * Set (Nametag) Data * * NOTE: Nametags are NOT permanent, and WILL become vacated after an * extended period of inactivity. * * *** LIMIT OF ONE AUTHORIZED ACCOUNT / ADDRESS PER NAMETAG *** */ function setData( string _nametag, string _field, bytes _data ) external onlyNametagOwner(_nametag) returns (bool success) { /* Set data. */ return _setData( _nametag, _field, _data ); } /** * Set (Nametag) Data (by Relayer) */ function setData( string _nametag, string _field, bytes _data, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _nametag, _field, _data, _expires, _nonce )); /* Validate signature. */ if (!_validateSignature(_nametag, hash, _signature)) { revert('Oops! Your signature is INVALID.'); } /* Set data. */ return _setData( _nametag, _field, _data ); } /** * @notice Set nametag info. * * @dev Calculate the `_root` hash and use it to store a * definition string in the eternal database. * * NOTE: Markdown will be the default format for definitions. */ function _setData( string _nametag, string _field, bytes _data ) private returns (bool success) { /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _field )); /* Save data to database. */ _zer0netDb.setBytes(dataId, _data); /* Broadcast event. */ emit Update( _nametag, _field, _data ); /* Return success. */ return true; } /** * Set Permissions */ function setPermissions( string _nametag, address _delegate, bytes _permissions ) external returns (bool success) { /* Set permissions. */ return _setPermissions( _nametag, msg.sender, _delegate, _permissions ); } /** * Set Permissions */ function setPermissions( string _nametag, address _owner, address _delegate, bytes _permissions, uint _expires, uint _nonce, bytes _signature ) external returns (bool success) { /* Make sure the signature has not expired. */ if (block.number > _expires) { revert('Oops! That signature has already EXPIRED.'); } /* Calculate encoded data hash. */ bytes32 hash = keccak256(abi.encodePacked( address(this), _nametag, _owner, _delegate, _permissions, _expires, _nonce )); /* Validate signature. */ if (!_validateSignature(_nametag, hash, _signature)) { revert('Oops! Your signature is INVALID.'); } /* Set permissions. */ return _setPermissions( _nametag, _owner, _delegate, _permissions ); } /** * Set Permissions * * Allows owners to delegate another Ethereum account * to proxy commands as if they are the primary account. * * Permissions are encoded as TWO (2) bytes in a bytes array. ALL permissions * are assumed to be false, unless explicitly specified in this bytes array. * * Proposed Permissions List * ------------------------- * * TODO Review Web3 JSON api for best (data access) structure. * (see https://web3js.readthedocs.io/en/1.0/web3.html) * * Profile Management (0x10__) * 0x1001 => Modify Public Info * 0x1002 => Modify Private Info * 0x1003 => Modify Permissions * * HODL Management (0x20__) * 0x2001 => Deposit Tokens * 0x2002 => Withdraw Tokens * * SPEDN Management (0x30__) * 0x3001 => Transfer ANY ERC * 0x3002 => Transfer ERC-20 * 0x3003 => Transfer ERC-721 * * STAEK Management (0x40__) * 0x4001 => Increase Staek * 0x4002 => Decrease Staek * 0x4003 => Shift/Transfer Staek * * Exchange / Trade Execution (0x50__) * 0x5001 => Place Order (Maker) * 0x5002 => Place Order (Taker) * 0x5003 => Margin Account * * Voting & Governance (0x60__) * 0x6001 => Cast Vote * * (this specification is in active development and subject to change) * * NOTE: Permissions WILL NOT be transferred between owners. */ function _setPermissions( string _nametag, address _owner, address _delegate, bytes _permissions ) private returns (bool success) { /* Set data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.', _owner, '.', _delegate, '.permissions' )); /* Save data to database. */ _zer0netDb.setBytes(dataId, _permissions); /* Broadcast event. */ emit Permissions(_owner, _delegate, _permissions); /* Return success. */ return true; } /** * Set Respect */ function _setRespect( address _owner, address _peer, uint _respect ) private returns (bool success) { /* Validate respect. */ if (_respect == 0) { revert('Oops! Your respect is TOO LOW.'); } /* Validate respect. */ if (_respect > 5) { revert('Oops! Your respect is TOO MUCH.'); } /* Calculate the data id. */ bytes32 dataId = keccak256(abi.encodePacked( _namespace, '.', _owner, '.respect.for.', _peer )); /* Save data to database. */ _zer0netDb.setUint(dataId, _respect); /* Broadcast event. */ emit Respect( _owner, _peer, _respect ); /* Return success. */ return true; } /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthBy0Admin external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * ZeroCache Interface * * Retrieves the current ZeroCache interface, * using the aname record from Zer0netDb. */ function _zeroCache() private view returns ( ZeroCacheInterface zeroCache ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.zerocache'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ zeroCache = ZeroCacheInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Validate Signature */ function _validateSignature( string _nametag, bytes32 _sigHash, bytes _signature ) private view returns (bool authorized) { /* Calculate owner hash. */ bytes32 ownerHash = keccak256(abi.encodePacked( _namespace, '.', _nametag, '.owner' )); /* Retrieve nametag owner. */ address nametagOwner = _zer0netDb.getAddress(ownerHash); /* Calculate signature hash. */ bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', _sigHash)); /* Retrieve the authorized signer. */ address signer = _ecRecovery().recover(sigHash, _signature); /* Validate signer. */ authorized = (signer == nametagOwner); } /** * Is (Owner) Contract * * Tests if a specified account / address is a contract. */ function _ownerIsContract( address _owner ) private view returns (bool isContract) { /* Initialize code length. */ uint codeLength; /* Run assembly. */ assembly { /* Retrieve the size of the code on target address. */ codeLength := extcodesize(_owner) } /* Set test result. */ isContract = (codeLength > 0); } /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress( bytes _address ) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data, uint _offset ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i + _offset] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } /** * Transfer Any ERC20 Token * * @notice Owner can transfer out any accidentally sent ERC20 tokens. * * @dev Provides an ERC20 interface, which allows for the recover * of any accidentally sent ERC20 tokens. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _tokens); } }
28,391
39
// underlyingLiquidatedJuniors += jb.tokensjBondsAt.price / EXP_SCALE
underlyingLiquidatedJuniors = underlyingLiquidatedJuniors.add( jb.tokens.mul(jBondsAt.price).div(EXP_SCALE) ); _unaccountJuniorBond(jb);
underlyingLiquidatedJuniors = underlyingLiquidatedJuniors.add( jb.tokens.mul(jBondsAt.price).div(EXP_SCALE) ); _unaccountJuniorBond(jb);
75,257
68
// PRIVATE /
function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; }
function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; }
7,281
1
// Converts an unsigned uint256 into a unsigned uint96. Requirements: - input must be less than or equal to maxUint96./
function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn't fit in an uint96"); return uint96(value); }
function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn't fit in an uint96"); return uint96(value); }
14,528
11
// Yes: If the user is on the list, and under the cap Yes: If the user is not on the list, supplies a valid proof (thereby being added to the list), and is under the cap No: If the user is not on the list, does not supply a valid proof, or is over the cap
bool invited = guests[_guest];
bool invited = guests[_guest];
36,512
123
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`./
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount);
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount);
9,282
16
// Event emitted when an account has been revoked from being an approval delegate
event RevokeApprovalDelegate( address indexed approvalDelegate );
event RevokeApprovalDelegate( address indexed approvalDelegate );
8,496
22
// Function to freeze accounts/
function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); }
function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); }
78,762
86
// ERC20Symbol interfaceId: bytes4(keccak256("symbol()"))
_registerInterface(0x95d89b41);
_registerInterface(0x95d89b41);
10,447
35
// Add a new entry for the given subprotocol to the provided CID NFT/_cidNFTID ID of the CID NFT to add the data to/_subprotocolName Name of the subprotocol where the data will be added. Has to exist./_key Key to set. This value is only relevant for the AssociationType ORDERED (where a mapping int => nft ID is stored)/_nftIDToAdd The ID of the NFT to add/_type Association type (see AssociationType struct) to use for this data
function add( uint256 _cidNFTID, string calldata _subprotocolName, uint256 _key, uint256 _nftIDToAdd, AssociationType _type
function add( uint256 _cidNFTID, string calldata _subprotocolName, uint256 _key, uint256 _nftIDToAdd, AssociationType _type
9,722
12
// Creates a 'bytes memory' variable from the memory address 'addr', with the length 'len'. The function will allocate new memory for the bytes array, and the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint256 addr, uint256 len) internal pure returns (bytes memory bts)
function toBytes(uint256 addr, uint256 len) internal pure returns (bytes memory bts)
5,033
153
// Sets a sender address of the failed message that came from the other side._messageId id of the message from the other side that triggered a call._receiver address of the receiver./
function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal { addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver; }
function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal { addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver; }
8,594
95
// Modifier to make a function callable only when the contract is not paused. /
modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; }
modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; }
372
102
// `prevId` does not exist anymore or now has a smaller key than the given key
prevId = address(0);
prevId = address(0);
1,998
24
// Get the node at the end of a double linked list.self The list being used. return A address identifying the node at the end of the double linked list./
function end(List storage self) internal view returns (address) { return self.list[NULL].previous; }
function end(List storage self) internal view returns (address) { return self.list[NULL].previous; }
41,540
91
// Transfer to bankroll and div cards
if (toBankRoll != 0) { ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)(); }
if (toBankRoll != 0) { ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)(); }
16,577
26
// Returns true if the address is delegated to act on your behalf for a specific token, the token's contract or an entire vault delegate The hotwallet to act on your behalf contract_ The address for the contract you're delegating tokenId The token id for the token you're delegating vault The cold wallet who issued the delegation /
function checkDelegateForToken(address delegate, address vault, address contract_, uint256 tokenId)
function checkDelegateForToken(address delegate, address vault, address contract_, uint256 tokenId)
22,448
71
// The pool's fee in hundredths of a bip, i.e. 1e-6/ return The fee
function fee() external view returns (uint24);
function fee() external view returns (uint24);
29,766
44
// fulfillRequest - called by data provider to forward data to the Consumer _requestId the request the provider is sending data for _requestedData the data to send _signature data provider's signature of the _requestId, _requestedData and Consumer's addressthis will used to validate the data's origin in the Consumer's contractreturn success if the execution was successful. /
function fulfillRequest(bytes32 _requestId, uint256 _requestedData, bytes memory _signature) external returns (bool){ uint256 gasLeftStart = gasleft(); require(_signature.length > 0, "Router: must include signature"); require(dataRequests[_requestId].isSet, "Router: request does not exist"); require(tx.gasprice <= dataRequests[_requestId].gasPrice, "Router: tx.gasprice too high"); address dataConsumer = dataRequests[_requestId].dataConsumer; address payable dataProvider = dataRequests[_requestId].dataProvider; bytes4 callbackFunction = dataRequests[_requestId].callbackFunction; uint256 fee = dataRequests[_requestId].fee; // msg.sender is the address of the data provider require(msg.sender == dataProvider, "Router: msg.sender != requested dataProvider"); require(consumerAuthorisedProviders[dataConsumer][msg.sender], "Router: dataProvider not authorised for this dataConsumer"); // dataConsumer will see msg.sender as the Router's contract address // using functionCall from OZ's Address library dataConsumer.functionCall(abi.encodeWithSelector(callbackFunction, _requestedData, _requestId, _signature)); address gasPayer = dataProvider; if(!dataProviders[dataProvider].providerPaysGas) { gasPayer = dataConsumer; } emit RequestFulfilled( dataConsumer, msg.sender, _requestId, _requestedData, gasPayer ); // Pay dataProvider (msg.sender) from tokens held by the consumer's contract // dataConsumer (msg.sender) is the address of the Consumer smart contract // for which the provider is fulfilling the request. // It must have enough Tokens to pay for the dataProvider's fee. // Will return underlying ERC20 error "ERC20: transfer amount exceeds balance" // if the Consumer's contract does not have enough tokens to pay require(token.transferFrom(dataConsumer, msg.sender, fee)); uint256 gasUsedToCall = gasLeftStart - gasleft(); if(gasPayer != dataProvider) { // calculate how much should be refunded to the provider uint256 totalGasUsed = EXPECTED_GAS; if(gasUsedToCall > EXPECTED_GAS) { uint256 diff = gasUsedToCall.sub(EXPECTED_GAS); totalGasUsed = totalGasUsed.add(diff); } uint256 ethRefund = totalGasUsed.mul(tx.gasprice); // check there's enough require(totalGasDeposits >= ethRefund, "Router: not enough ETH held by Router to refund gas"); require(gasDepositsForConsumer[dataConsumer] >= ethRefund, "Router: dataConsumer does not have enough ETH to refund gas"); require(gasDepositsForConsumerProviders[dataConsumer][dataProvider] >= ethRefund, "Router: not have enough ETH for consumer/provider pair to refund gas"); // update total held by Router contract totalGasDeposits = totalGasDeposits.sub(ethRefund); // update total held for dataConsumer contract gasDepositsForConsumer[dataConsumer] = gasDepositsForConsumer[dataConsumer].sub(ethRefund); // update total held for dataConsumer contract/provider pair gasDepositsForConsumerProviders[dataConsumer][dataProvider] = gasDepositsForConsumerProviders[dataConsumer][dataProvider].sub(ethRefund); emit GasRefundedToProvider(dataConsumer, dataProvider, ethRefund); // refund the provider Address.sendValue(dataProvider, ethRefund); } delete dataRequests[_requestId]; return true; }
function fulfillRequest(bytes32 _requestId, uint256 _requestedData, bytes memory _signature) external returns (bool){ uint256 gasLeftStart = gasleft(); require(_signature.length > 0, "Router: must include signature"); require(dataRequests[_requestId].isSet, "Router: request does not exist"); require(tx.gasprice <= dataRequests[_requestId].gasPrice, "Router: tx.gasprice too high"); address dataConsumer = dataRequests[_requestId].dataConsumer; address payable dataProvider = dataRequests[_requestId].dataProvider; bytes4 callbackFunction = dataRequests[_requestId].callbackFunction; uint256 fee = dataRequests[_requestId].fee; // msg.sender is the address of the data provider require(msg.sender == dataProvider, "Router: msg.sender != requested dataProvider"); require(consumerAuthorisedProviders[dataConsumer][msg.sender], "Router: dataProvider not authorised for this dataConsumer"); // dataConsumer will see msg.sender as the Router's contract address // using functionCall from OZ's Address library dataConsumer.functionCall(abi.encodeWithSelector(callbackFunction, _requestedData, _requestId, _signature)); address gasPayer = dataProvider; if(!dataProviders[dataProvider].providerPaysGas) { gasPayer = dataConsumer; } emit RequestFulfilled( dataConsumer, msg.sender, _requestId, _requestedData, gasPayer ); // Pay dataProvider (msg.sender) from tokens held by the consumer's contract // dataConsumer (msg.sender) is the address of the Consumer smart contract // for which the provider is fulfilling the request. // It must have enough Tokens to pay for the dataProvider's fee. // Will return underlying ERC20 error "ERC20: transfer amount exceeds balance" // if the Consumer's contract does not have enough tokens to pay require(token.transferFrom(dataConsumer, msg.sender, fee)); uint256 gasUsedToCall = gasLeftStart - gasleft(); if(gasPayer != dataProvider) { // calculate how much should be refunded to the provider uint256 totalGasUsed = EXPECTED_GAS; if(gasUsedToCall > EXPECTED_GAS) { uint256 diff = gasUsedToCall.sub(EXPECTED_GAS); totalGasUsed = totalGasUsed.add(diff); } uint256 ethRefund = totalGasUsed.mul(tx.gasprice); // check there's enough require(totalGasDeposits >= ethRefund, "Router: not enough ETH held by Router to refund gas"); require(gasDepositsForConsumer[dataConsumer] >= ethRefund, "Router: dataConsumer does not have enough ETH to refund gas"); require(gasDepositsForConsumerProviders[dataConsumer][dataProvider] >= ethRefund, "Router: not have enough ETH for consumer/provider pair to refund gas"); // update total held by Router contract totalGasDeposits = totalGasDeposits.sub(ethRefund); // update total held for dataConsumer contract gasDepositsForConsumer[dataConsumer] = gasDepositsForConsumer[dataConsumer].sub(ethRefund); // update total held for dataConsumer contract/provider pair gasDepositsForConsumerProviders[dataConsumer][dataProvider] = gasDepositsForConsumerProviders[dataConsumer][dataProvider].sub(ethRefund); emit GasRefundedToProvider(dataConsumer, dataProvider, ethRefund); // refund the provider Address.sendValue(dataProvider, ethRefund); } delete dataRequests[_requestId]; return true; }
2,900
49
// ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)and `uint256` (`UintSet`) are supported. [WARNING]==== Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.==== /
library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
21,372
42
// Set Info by Hostname /
function setInfoByHostname( string _hostname, bytes _data
function setInfoByHostname( string _hostname, bytes _data
23,142
1
// Checks whether the loan is active and has been set or not Throws a require error if the loan is not active or has not been set loanID number of loan to check /
modifier loanActiveOrSet(uint256 loanID) { require(isActiveOrSet(loanID), "LOAN_NOT_ACTIVE_OR_SET"); _; }
modifier loanActiveOrSet(uint256 loanID) { require(isActiveOrSet(loanID), "LOAN_NOT_ACTIVE_OR_SET"); _; }
11,055
2
// YearnWrapping Allows users to wrap and unwrap Yearn tokens All functions must be payable so they can be called from a multicall involving ETH /
abstract contract YearnWrapping is IBaseRelayerLibrary { function wrapYearn( IYearnTokenVault wrappedToken, address sender, address recipient, uint256 amount, uint256 outputReference ) external payable { IERC20 underlying = IERC20(wrappedToken.token()); amount = _resolveAmountPullTokenAndApproveSpender(underlying, address(wrappedToken), amount, sender); uint256 receivedWrappedAmount = wrappedToken.deposit(amount, recipient); _setChainedReference(outputReference, receivedWrappedAmount); } function unwrapYearn( IYearnTokenVault wrappedToken, address sender, address recipient, uint256 amount, uint256 outputReference ) external payable { amount = _resolveAmountAndPullToken(IERC20(address(wrappedToken)), amount, sender); uint256 mainAmount = wrappedToken.withdraw(amount, recipient); _setChainedReference(outputReference, mainAmount); } }
abstract contract YearnWrapping is IBaseRelayerLibrary { function wrapYearn( IYearnTokenVault wrappedToken, address sender, address recipient, uint256 amount, uint256 outputReference ) external payable { IERC20 underlying = IERC20(wrappedToken.token()); amount = _resolveAmountPullTokenAndApproveSpender(underlying, address(wrappedToken), amount, sender); uint256 receivedWrappedAmount = wrappedToken.deposit(amount, recipient); _setChainedReference(outputReference, receivedWrappedAmount); } function unwrapYearn( IYearnTokenVault wrappedToken, address sender, address recipient, uint256 amount, uint256 outputReference ) external payable { amount = _resolveAmountAndPullToken(IERC20(address(wrappedToken)), amount, sender); uint256 mainAmount = wrappedToken.withdraw(amount, recipient); _setChainedReference(outputReference, mainAmount); } }
27,839
9
// Reinvest to get compound yield
invest();
invest();
41,253
217
// The TOKEN to buy lottery
IERC20 public atari;
IERC20 public atari;
14,854
133
// Extracts the order data and signing scheme for the specified trade.//trade The trade./tokens The list of tokens included in the settlement. The token/ indices in the trade parameters map to tokens in this array./order The memory location to extract the order data to.
function extractOrder( Data calldata trade, IERC20[] calldata tokens, GPv2Order.Data memory order
function extractOrder( Data calldata trade, IERC20[] calldata tokens, GPv2Order.Data memory order
54,717
19
// Cancels a tribute proposal which marks it as processed and initiates refund of the tribute tokens to the proposer. Proposal id must exist. Only proposals that have not already been sponsored can be cancelled. Only proposer can cancel a tribute proposal. dao The DAO address. proposalId The proposal id. /
function cancelProposal(DaoRegistry dao, bytes32 proposalId) external override
function cancelProposal(DaoRegistry dao, bytes32 proposalId) external override
31,937
13
// Returns the square root of the UBI balance of a particular submission of the ProofOfHumanity contract. Note that this function takes the expiration date into account._submissionID The address of the submission. return The balance of the submission. /
function balanceOf(address _submissionID) external view returns (uint256) { return isRegistered(_submissionID) ? sqrt(UBI.balanceOf(_submissionID)) : 0; }
function balanceOf(address _submissionID) external view returns (uint256) { return isRegistered(_submissionID) ? sqrt(UBI.balanceOf(_submissionID)) : 0; }
38,139
55
// Mapping from motion IDs to target addresses.
mapping(uint => address) public motionTarget;
mapping(uint => address) public motionTarget;
81,324
3
// The Owner will be able to create more supply.
function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); }
function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); }
25,473
14
// Returns an Ethereum Signed Typed Data, created from a`domainSeparator` and a `structHash`. This produces hash correspondingto the one signed with theJSON-RPC method as part of EIP-712.
* See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); }
* See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); }
19,100
52
// PROPOSAL PASSED
if (didPass) { proposal.flags[2] = 1; // didPass growGuild(proposal.applicant, proposal.sharesRequested, proposal.lootRequested);
if (didPass) { proposal.flags[2] = 1; // didPass growGuild(proposal.applicant, proposal.sharesRequested, proposal.lootRequested);
4,464
71
// 6500 blocks in average day --- decimalsNFY balance of rewardPool / blocks / 10000dailyReward (in hundredths of %) = rewardPerBlock
function getRewardPerBlock() public view returns(uint) { return NFYToken.balanceOf(rewardPool).mul(dailyReward).div(6500).div(10000); }
function getRewardPerBlock() public view returns(uint) { return NFYToken.balanceOf(rewardPool).mul(dailyReward).div(6500).div(10000); }
6,795
88
// full interface for router
interface IDMMRouter01 is IDMMExchangeRouter, IDMMLiquidityRouter { function factory() external pure returns (address); function weth() external pure returns (IWETH); }
interface IDMMRouter01 is IDMMExchangeRouter, IDMMLiquidityRouter { function factory() external pure returns (address); function weth() external pure returns (IWETH); }
23,342
116
// check for jackpot win
if (address(this).balance >= jackpotThreshold){ jackpotThreshold = address(this).balance + jackpotThreshIncrease; onJackpot(msg.sender, SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000), jackpotThreshold); ownerAccounts[msg.sender] = SafeMath.add(ownerAccounts[msg.sender], SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); jackpotAccount = SafeMath.sub(jackpotAccount,SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); } else {
if (address(this).balance >= jackpotThreshold){ jackpotThreshold = address(this).balance + jackpotThreshIncrease; onJackpot(msg.sender, SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000), jackpotThreshold); ownerAccounts[msg.sender] = SafeMath.add(ownerAccounts[msg.sender], SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); jackpotAccount = SafeMath.sub(jackpotAccount,SafeMath.div(SafeMath.mul(jackpotAccount,jackpotPayRate),1000)); } else {
33,895
14
// The user / client has to have the desire quantity of tokens to return
require(_tokens_number <= BalanceOf(msg.sender), "You don't have the tokens that you want to return"); token.transfer(msg.sender, contract_address, _tokens_number); msg.sender.transfer(TokensPrice(_tokens_number)); emit returned_tokens(_tokens_number, msg.sender);
require(_tokens_number <= BalanceOf(msg.sender), "You don't have the tokens that you want to return"); token.transfer(msg.sender, contract_address, _tokens_number); msg.sender.transfer(TokensPrice(_tokens_number)); emit returned_tokens(_tokens_number, msg.sender);
17,037
5
// user info mapping
mapping(address => UserInfo) internal users;
mapping(address => UserInfo) internal users;
12,550
8
// Function permise claim. /
function claimTokens() public nonReentrant { require(whitelist[msg.sender], "You must be on the whitelist."); require(block.timestamp > ending, "Presale must have finished."); require(claimReady[msg.sender] <= block.timestamp, "You can't claim now."); uint _contractBalance = token.balanceOf(address(this)); require(_contractBalance > 0, "Insufficient contract balance."); require(investorBalance[msg.sender] > 0, "Insufficient investor balance."); uint _withdrawableTokensBalance = mulScale(investorBalance[msg.sender], 2500, 10000); // 2500 basis points = 25%. // Balance whitdrawable. if(withdrawableBalance[msg.sender] <= _withdrawableTokensBalance) { token.transfer(msg.sender, withdrawableBalance[msg.sender]); investorBalance[msg.sender] = 0; withdrawableBalance[msg.sender] = 0; } else { claimReady[msg.sender] = block.timestamp + cooldownTime; // next claim. withdrawableBalance[msg.sender] -= _withdrawableTokensBalance; // balance del investor. token.transfer(msg.sender, _withdrawableTokensBalance); // Transfers tokens. } }
function claimTokens() public nonReentrant { require(whitelist[msg.sender], "You must be on the whitelist."); require(block.timestamp > ending, "Presale must have finished."); require(claimReady[msg.sender] <= block.timestamp, "You can't claim now."); uint _contractBalance = token.balanceOf(address(this)); require(_contractBalance > 0, "Insufficient contract balance."); require(investorBalance[msg.sender] > 0, "Insufficient investor balance."); uint _withdrawableTokensBalance = mulScale(investorBalance[msg.sender], 2500, 10000); // 2500 basis points = 25%. // Balance whitdrawable. if(withdrawableBalance[msg.sender] <= _withdrawableTokensBalance) { token.transfer(msg.sender, withdrawableBalance[msg.sender]); investorBalance[msg.sender] = 0; withdrawableBalance[msg.sender] = 0; } else { claimReady[msg.sender] = block.timestamp + cooldownTime; // next claim. withdrawableBalance[msg.sender] -= _withdrawableTokensBalance; // balance del investor. token.transfer(msg.sender, _withdrawableTokensBalance); // Transfers tokens. } }
21,002
212
// fire ERC721 transfer event
emit Transfer(address(0), _to, _tokenId + i);
emit Transfer(address(0), _to, _tokenId + i);
24,819
30
// Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled)
function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; }
function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; }
17,903
39
// Admin functions
function manualMapConfig( uint[] memory fnftIds, uint[] memory timePeriod, uint [] memory lockedFrom
function manualMapConfig( uint[] memory fnftIds, uint[] memory timePeriod, uint [] memory lockedFrom
30,244
44
// only owner address can selfdestruct - emergency /
{ PHXTKN.transfer(owner, contractBalance); selfdestruct(owner); }
{ PHXTKN.transfer(owner, contractBalance); selfdestruct(owner); }
38,139
130
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
interestRateModel = newInterestRateModel;
6,044
0
// VestingGrant is used to implement business rules regarding token vesting /
struct VestingGrant { bool isGranted; // Flag to indicate grant was issued address issuer; // Account that issued grant address beneficiary; // Beneficiary of grant uint256 grantJiffys; // Number of Jiffys granted uint256 startTimestamp; // Start date/time of vesting uint256 cliffTimestamp; // Cliff date/time for vesting uint256 endTimestamp; // End date/time of vesting bool isRevocable; // Whether issuer can revoke and reclaim Jiffys uint256 releasedJiffys; // Number of Jiffys already released }
struct VestingGrant { bool isGranted; // Flag to indicate grant was issued address issuer; // Account that issued grant address beneficiary; // Beneficiary of grant uint256 grantJiffys; // Number of Jiffys granted uint256 startTimestamp; // Start date/time of vesting uint256 cliffTimestamp; // Cliff date/time for vesting uint256 endTimestamp; // End date/time of vesting bool isRevocable; // Whether issuer can revoke and reclaim Jiffys uint256 releasedJiffys; // Number of Jiffys already released }
49,548
135
// allow user to stake payout automatically_stake bool_amount uint return uint /
function stakeOrSend( bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( OHM ).transfer( msg.sender, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( OHM ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, msg.sender ); } else { IERC20( OHM ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender ); } } return _amount; }
function stakeOrSend( bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( OHM ).transfer( msg.sender, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( OHM ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, msg.sender ); } else { IERC20( OHM ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender ); } } return _amount; }
33,288
154
// Make sure there's no change in governance NOTE: Also avoid bricking the wrapper from setting a bad registry
require(msg.sender == registry.governance());
require(msg.sender == registry.governance());
23,813
99
// IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. /
function _msgSender() internal view virtual override returns (address payable) { if (msg.sender != getHubAddr()) { return msg.sender; } else {
function _msgSender() internal view virtual override returns (address payable) { if (msg.sender != getHubAddr()) { return msg.sender; } else {
74,303
13
// set Token URI of that particular NFT
_setTokenURI(tokenId, houseTokenURIs[uint256(house)]); // takes tokenID and tokenURI s_minted[s_requestIdToSender[requestId]] = true; // Mark user as having minted an NFT s_tokenCounter += 1; // increment the token count
_setTokenURI(tokenId, houseTokenURIs[uint256(house)]); // takes tokenID and tokenURI s_minted[s_requestIdToSender[requestId]] = true; // Mark user as having minted an NFT s_tokenCounter += 1; // increment the token count
22,688
44
// Activates voting Clears projects
function enableVoting() public onlyAdmin returns(uint ballotId){ require(votingActive == false); require(frozen == false); curentBallotId++; votingActive = true; delete projects; emit VotingOn(curentBallotId); return curentBallotId; }
function enableVoting() public onlyAdmin returns(uint ballotId){ require(votingActive == false); require(frozen == false); curentBallotId++; votingActive = true; delete projects; emit VotingOn(curentBallotId); return curentBallotId; }
18,866
25
// update HE-3 contract address
function updateHe3TokenAddress(address _he3TokenAddress) public onlyOwner notAddress0(_he3TokenAddress) { he3TokenAddress = _he3TokenAddress; tokenHe3 = Token(he3TokenAddress); }
function updateHe3TokenAddress(address _he3TokenAddress) public onlyOwner notAddress0(_he3TokenAddress) { he3TokenAddress = _he3TokenAddress; tokenHe3 = Token(he3TokenAddress); }
41,823
8
// Update the reserve allocation. /
function updateMintReserve(uint256 reserve) external onlyOwner { mintReserve = reserve; }
function updateMintReserve(uint256 reserve) external onlyOwner { mintReserve = reserve; }
52,635
7
// If we reach this, the token is already released and we verify the transfer rules which enforce locking and vesting.
if(transferRules[from].tokens > 0) { uint lockedTokens = calcBalanceLocked(from); uint balanceUnlocked = super.balanceOf(from) - lockedTokens; require(amount <= balanceUnlocked, "transfer rule violation"); }
if(transferRules[from].tokens > 0) { uint lockedTokens = calcBalanceLocked(from); uint balanceUnlocked = super.balanceOf(from) - lockedTokens; require(amount <= balanceUnlocked, "transfer rule violation"); }
33,312
56
// Send the assets to the Strategy and call skim to invest them/ @inheritdoc IStrategy
function skim(uint256 amount) external override { sushi.approve(address(bar), amount); bar.enter(amount); }
function skim(uint256 amount) external override { sushi.approve(address(bar), amount); bar.enter(amount); }
1,590
2
// Track whether a depositor has claimed rewards for a given burn event epoch. tokenId_ ID of the staked `LP` `NFT`. epoch_ The burn epoch to track if rewards were claimed. return `True` if rewards were claimed for the given epoch, else false. /
function isEpochClaimed( uint256 tokenId_, uint256 epoch_ ) external view returns (bool);
function isEpochClaimed( uint256 tokenId_, uint256 epoch_ ) external view returns (bool);
35,441
0
// Implementation of the {IERC721Receiver} interface.Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}./ See {IERC721Receiver-onERC721Received}. Always returns `IERC721Receiver.onERC721Received.selector`. /
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; }
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; }
11,470
821
// Reads the uint56 at `mPtr` in memory.
function readUint56(MemoryPointer mPtr) internal pure returns (uint56 value) { assembly { value := mload(mPtr) } }
function readUint56(MemoryPointer mPtr) internal pure returns (uint56 value) { assembly { value := mload(mPtr) } }
40,472