comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev accessory functions to fetch data from the lendingPoolCore **/
function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool bo...
0.5.14
/** * @dev mints token in the event of users depositing the underlying asset into the lending pool * only lending pools can call this function * @param _account the address receiving the minted tokens * @param _amount the amount of tokens to mint */
function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool { //cumulates the balance of the user (, , uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(_account); //if the user is redirecting his interest towards someone ...
0.5.14
/** * @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset * Transfer of the liquidated asset is executed by the lending pool contract. * only lending pools can call this function * @param _account the address from which burn the aTokens * @param _v...
function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool { //cumulates the balance of the user being liquidated (,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account); //adds the accrued interest and substracts the ...
0.5.14
/** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * only lending pools can call this function * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/
function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool { //being a normal transfer, the Transfer() and BalanceTransfer() are emitted //so no need to emit a specific event here executeTransferInternal(_from, _to, _value); }
0.5.14
/** * @dev calculates the balance of the user, which is the * principal balance + interest generated by the principal balance + interest generated by the redirected balance * @param _user the user for which the balance is being calculated * @return the total balance of the user **/
function balanceOf(address _user) public view returns(uint256) { //current principal balance of the user uint256 currentPrincipalBalance = super.balanceOf(_user); //balance redirected by other users to _user for interest rate accrual uint256 redirectedBalance = redirectedBalances[_...
0.5.14
/** * @dev accumulates the accrued interest of the user to the principal balance * @param _user the address of the user for which the interest is being accumulated * @return the previous principal balance, the new principal balance, the balance increase * and the new user index **/
function cumulateBalanceInternal(address _user) internal returns(uint256, uint256, uint256, uint256) { uint256 previousPrincipalBalance = super.balanceOf(_user); //calculate the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(_user).sub(p...
0.5.14
/** * @dev updates the redirected balance of the user. If the user is not redirecting his * interest, nothing is executed. * @param _user the address of the user for which the interest is being accumulated * @param _balanceToAdd the amount to add to the redirected balance * @param _balanceToRemove the amount ...
function updateRedirectedBalanceOfRedirectionAddressInternal( address _user, uint256 _balanceToAdd, uint256 _balanceToRemove ) internal { address redirectionAddress = interestRedirectionAddresses[_user]; //if there isn't any redirection, nothing to be done if...
0.5.14
/** * @dev executes the transfer of aTokens, invoked by both _transfer() and * transferOnLiquidation() * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/
function executeTransferInternal( address _from, address _to, uint256 _value ) internal { require(_value > 0, "Transferred amount needs to be greater than zero"); //cumulate the balance of the sender (, uint256 fromBalance, uint256 fromBal...
0.5.14
/** * @dev function to reset the interest stream redirection and the user index, if the * user has no balance left. * @param _user the address of the user * @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value **/
function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) { //if the user has 0 principal balance, the interest stream redirection gets reset interestRedirectionAddresses[_user] = address(0); //emits a InterestStreamRedirected event to notify that the redirection has b...
0.5.14
/** * @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 ...
function updateStateOnDeposit( address _reserve, address _user, uint256 _amount, bool _isFirstDeposit ) external onlyLendingPool { reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0); if ...
0.5.14
/** * @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 red...
function updateStateOnRedeem( address _reserve, address _user, uint256 _amountRedeemed, bool _userRedeemedEverything ) external onlyLendingPool { //compound liquidity and variable borrow interests reserves[_reserve].updateCumulativeIndexes(); updateRes...
0.5.14
/** * @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 _r...
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 (...
0.5.14
/** * @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 th...
function updateStateOnRepay( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) external onlyLendingPool { updateReserveStateOnRepayInternal( _...
0.5.14
/** * @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 b...
function updateStateOnSwapRate( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) external onlyLendingPool returns (CoreLibrary.InterestR...
0.5.14
/** * @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...
function updateStateOnLiquidation( address _principalReserve, address _collateralReserve, address _user, uint256 _amountToLiquidate, uint256 _collateralToLiquidate, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _balanceIncrea...
0.5.14
/** * @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...
function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease) external onlyLendingPool returns (uint256) { updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); //update user data and rebalance the rate updateU...
0.5.14
/** * @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 (bo...
0.5.14
/** * @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 != EthAddr...
0.5.14
/** * @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 liquidati...
0.5.14
/** * @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(_r...
0.5.14
/** * @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...
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]; ...
0.5.14
/** * @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]; ...
0.5.14
/** * @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) { ...
0.5.14
/** * @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 l...
function getReserveConfiguration(address _reserve) external view returns (uint256, uint256, uint256, bool) { uint256 decimals; uint256 baseLTVasCollateral; uint256 liquidationThreshold; bool usageAsCollateralEnabled; CoreLibrary.ReserveData ...
0.5.14
/** * @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 availableLiqui...
0.5.14
/** * @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 CoreLi...
0.5.14
/** * @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; ...
0.5.14
/** * @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); ...
0.5.14
/** * @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 chec...
0.5.14
/** * @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 _balance...
function updateReserveStateOnBorrowInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _rateMode ) internal { reserves[_reserve].updateCumulativeInd...
0.5.14
/** * @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 int...
function updateReserveStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersRes...
0.5.14
/** * @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 _balanc...
function updatePrincipalReserveStateOnLiquidationInternal( address _principalReserve, address _user, uint256 _amountToLiquidate, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_principalReserve]; CoreLibrary.UserReserve...
0.5.14
/** * @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 _liquidit...
function updateReserveInterestRatesAndTimestampInternal( address _reserve, uint256 _liquidityAdded, uint256 _liquidityTaken ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRa...
0.5.14
/** * @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 { ...
0.5.14
/** * @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...
0.5.14
/** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param _reserve the address of the reserve * @param _amount the amount to be deposited * @param _referralCode integrators are assigned a referral code and can potentially receive r...
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) onlyAmountGreaterThanZero(_amount) { AToken aToken = AToken(core.getReserveATokenAddress(...
0.5.14
/** * @dev Redeems the underlying amount of assets requested by _user. * This function is executed by the overlying aToken contract in response to a redeem action. * @param _reserve the address of the reserve * @param _user the address of the user performing the action * @param _amount the underlying amount t...
function redeemUnderlying( address _reserve, address payable _user, uint256 _amount, uint256 _aTokenBalanceAfterRedeem ) external nonReentrant onlyOverlyingAToken(_reserve) onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount...
0.5.14
/** * @dev borrowers can user this function to swap between stable and variable borrow rate modes. * @param _reserve the address of the reserve on which the user borrowed **/
function swapBorrowRateMode(address _reserve) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { (uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core .getUserBorrowBalances(_...
0.5.14
/** * @dev allows depositors to enable or disable a specific deposit as collateral. * @param _reserve the address of the reserve * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender); require(un...
0.5.14
/** * @dev users can invoke this function to liquidate an undercollateralized position. * @param _reserve the address of the collateral to liquidated * @param _reserve the address of the principal reserve * @param _user the address of the borrower * @param _purchaseAmount the amount of principal that the liqu...
function liquidationCall( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) { address liquidationManager = addressesProvi...
0.5.14
/** * @dev calculates how much of a specific collateral can be liquidated, given * a certain amount of principal currency. This function needs to be called after * all the checks to validate the liquidation have been performed, otherwise it might fail. * @param _collateral the collateral to be liquidated * @p...
function calculateAvailableCollateralToLiquidate( address _collateral, address _principal, uint256 _purchaseAmount, uint256 _userCollateralBalance ) internal view returns (uint256 collateralAmount, uint256 principalAmountNeeded) { collateralAmount = 0; principa...
0.5.14
/** @dev Increase a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to increase in DAI (ex. 10m DAI amount == 10000000) @param _global If true, increases the global debt ceiling by _amount */
function increaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" address _vat = vat(); (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); Fileable(_vat).file(_ilk, "line", add(line_, _amount * RAD)...
0.6.12
/** @dev Set the debt ceiling for an ilk in the "MCD_IAM_AUTO_LINE" auto-line without updating the time values @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) */
function setIlkAutoLineDebtCeiling(bytes32 _ilk, uint256 _amount) public { address _autoLine = autoLine(); (, uint256 gap, uint48 ttl,,) = IAMLike(_autoLine).ilks(_ilk); require(gap != 0 && ttl != 0); // "LibDssExec/auto-line-not-configured" IAMLike(_autoLine).setIlk(_ilk, _amount *...
0.6.12
/** @dev Set a collateral liquidation ratio. Amount will be converted to the correct internal precision. @dev Equation used for conversion is pct * RAY / 10,000 @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 150% = 150 * 1...
function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 10 * BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-mat-precision" // Fails if pct >= 1000% require(_pct_bps >= BPS_ONE_HUNDRED_PCT); // the liquidation ratio has to be bigger or equal to 100% File...
0.6.12
/** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/
function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external override { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInpu...
0.7.5
/** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of st...
function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestam...
0.7.5
/** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribut...
function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _up...
0.7.5
/** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/
function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, ...
0.7.5
/** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/
function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256...
0.7.5
/** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this dist...
function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdate...
0.7.5
/** * @dev returns the current delegated power of a user. The current power is the * power delegated at the time of the last snapshot * @param user the user **/
function getPowerCurrent(address user, DelegationType delegationType) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, ) = _getDelegationDataByType(delega...
0.7.5
/** * @dev returns the delegated power of a user at a certain block * @param user the user **/
function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, ) = _getDelegatio...
0.7.5
/** * @dev delegates the specific power to a delegatee * @param delegatee the user which delegated power has changed * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) **/
function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require(delegatee != address(0), 'INVALID_DELEGATEE'); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance ...
0.7.5
/** * @dev moves delegated power from one user to another * @param from the user from which delegated power is moved * @param to the user that will receive the delegated power * @param amount the amount of delegated power to be moved * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_PO...
function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshots...
0.7.5
/** * @dev searches a snapshot by block number. Uses binary search. * @param snapshots the snapshots mapping * @param snapshotsCounts the number of snapshots * @param user the user for which the snapshot is being searched * @param blockNumber the block number being searched **/
function _searchByBlockNumber( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address user, uint256 blockNumber ) internal view returns (uint256) { require(blockNumber <= block.number, 'INVALID_BLOCK_NUMBER'); u...
0.7.5
/** * @dev Writes a snapshot for an owner of tokens * @param owner The owner of the tokens * @param oldValue The value before the operation that is gonna be executed after the snapshot * @param newValue The value after the operation */
function _writeSnapshot( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address owner, uint128 oldValue, uint128 newValue ) internal { uint128 currentBlock = uint128(block.number); uint256 ownerSnapshotsCou...
0.7.5
/** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/
function redeem(address to, uint256 amount) external override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); //solium-disable-next-line uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender]; require( block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_...
0.7.5
/** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param to Address to stake for * @param amount Amount to stake **/
function claimRewards(address to, uint256 amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[msg.sender] = newTotalR...
0.7.5
/** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param from Address to transfer from * @param to Address to transfer to * @param amount Amount to transfer **/
function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); // Sender _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); // Recipient if (from != to) { uint256 balanceOfTo = balanceOf(to); ...
0.7.5
/** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total ...
function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(user, address(this), userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[user].add(a...
0.7.5
/** * @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation * - If the timestamp of the sender is "better" or the timestamp of the recipient is 0, we take the one of the recipient * - Weighted average of from/to cooldown timestamps if: * # The sender doesn'...
function getNextCooldownTimestamp( uint256 fromCooldownTimestamp, uint256 amountToReceive, address toAddress, uint256 toBalance ) public returns (uint256) { uint256 toCooldownTimestamp = stakersCooldowns[toAddress]; if (toCooldownTimestamp == 0) { return 0; } uint256 ...
0.7.5
/** * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn * - On _transfer, it writes snapshots for both "from" and "to" * - On _mint, only for _to * - On _burn, only for _from * @param from the from address * @param to the to address * @param amount the amo...
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { address votingFromDelegatee = _votingDelegates[from]; address votingToDelegatee = _votingDelegates[to]; if (votingFromDelegatee == address(0)) { votingFromDelegatee = from; } ...
0.7.5
// Transfer the balance from token owner account to receiver account
function transfer(address to, uint tokens) public returns (bool success) { require(to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(!transactionLock); // Check for transaction lock require(!frozenAccount[to]);// Check if recipient is frozen balances[msg.sen...
0.4.25
// Transfer token from spender account to receiver account
function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(!transactionLock); // Check for transaction lock require(!frozenAccount[from]); // Check if sender is fro...
0.4.25
/** * @dev stakeNft allows a user to submit their NFT to the contract and begin getting returns. * @param _nftIds The ID of the NFT being staked. **/
function batchStakeNft(uint256[] memory _nftIds) public // doKeep { // Loop through all submitted NFT IDs and stake them. for (uint256 i = 0; i < _nftIds.length; i++) { _stake(_nftIds[i], msg.sender); } }
0.6.12
/** * @dev Internal function for staking--this allows us to skip updating stake multiple times during a batch stake. * @param _nftId The ID of the NFT being staked. == coverId * @param _user The user who is staking the NFT. **/
function _stake(uint256 _nftId, address _user) internal { (/*coverId*/, uint8 coverStatus, uint256 sumAssured, uint16 coverPeriod, uint256 validUntil, address scAddress, bytes4 coverCurrency, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT( getModule("ARNFT") ).getToken(_nftId...
0.6.12
/** * @dev Internal main removal functionality. **/
function _removeNft(uint256 _nftId) internal { (/*coverId*/, /*status*/, uint256 sumAssured, uint16 coverPeriod, /*uint256 validuntil*/, address scAddress, /*coverCurrency*/, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT(getModule("ARNFT")).getToken(_nftId); address ...
0.6.12
/** * @dev Need a force remove--at least temporarily--where owner can remove data relating to an NFT. * This necessity came about when updating the contracts and some users started withdrawal when _removeNFT * was in the second step of withdrawal, then executed the second step of withdrawal after _remov...
function forceRemoveNft(address[] calldata _users, uint256[] calldata _nftIds) external onlyOwner { require(_users.length == _nftIds.length, "Array lengths must match."); for (uint256 i = 0; i < _users.length; i++) { uint256 nftId = _nftIds[i]; address user...
0.6.12
/** * @dev Some NFT expiries used a different bucket step upon update and must be reset. **/
function forceResetExpires(uint256[] calldata _nftIds) external onlyOwner { uint64[] memory validUntils = new uint64[](_nftIds.length); for (uint256 i = 0; i < _nftIds.length; i++) { (/*coverId*/, /*status*/, /*uint256 sumAssured*/, /*uint16 coverPeriod*/, uint256 valid...
0.6.12
/** * @dev Subtract from the cover amount for the user and contract overall. * @param _user The user who is having the token removed. * @param _nftId ID of the NFT being used--must check if it has been submitted. * @param _coverAmount The amount of cover being removed. * @param _coverPrice Price that the user...
function _subtractCovers(address _user, uint256 _nftId, uint256 _coverAmount, uint256 _coverPrice, address _protocol) internal { if (coverMigrated[_nftId]) { IRewardManagerV2(getModule("REWARDV2")).withdraw(_user, _protocol, _coverPrice, _nftId); } else { IRewardM...
0.6.12
/** * @dev Migrate reward to V2 * @param _nftIds Nft ids **/
function migrateCovers(uint256[] calldata _nftIds) external { for (uint256 i = 0; i < _nftIds.length; i += 1) { address user = nftOwners[_nftIds[i]]; require(user != address(0), "NFT not staked."); require(coverMigrated[_nftIds[i]] == false, "Already migrated....
0.6.12
/** * @dev Check that the NFT should be allowed to be added. We check expiry and claimInProgress. * @param _validUntil The expiration time of this NFT. * @param _scAddress The smart contract protocol that the NFt is protecting. * @param _coverCurrency The currency that this NFT is protected in (must be ETH_SIG)...
function _checkNftValid(uint256 _validUntil, address _scAddress, bytes4 _coverCurrency, uint8 _coverStatus) internal view { require(_validUntil > now + 20 days, "NFT is expired or within 20 days of expiry."); require(_coverStatus == 0, "arNFT claim is already in progress."); ...
0.6.12
/** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i ++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freez...
0.4.20
/** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in ...
function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings...
0.4.20
/** * @dev release first available freezing tokens. */
function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amou...
0.4.20
/** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */
function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreez...
0.4.20
/** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token...
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBal...
0.4.20
/* Admin function for transfer coins */
function transferFromAdmin(address _from, address _to, uint256 _value) public onlyOwner returns(bool success) { if (_to == 0x0) revert(); if (balanceOf[_from] < _value) revert(); // Check if the sender has enough if ((balanceOf[_to] + _value) < balanceOf[_to]) revert(); // Check for overflows...
0.4.18
/* Set params of ICO _auctionsStartBlock, _auctionsStopBlock - block number of start and stop of Ico _auctionsMinTran - minimum transaction amount for Ico in wei */
function setICOParams(uint256 _gracePeriodPrice, uint32 _gracePeriodStartBlock, uint32 _gracePeriodStopBlock, uint256 _gracePeriodMaxTarget, uint256 _gracePeriodMinTran, bool _resetAmount) public onlyOwner { gracePeriodStartBlock = _gracePeriodStartBlock; gracePeriodStopBlock = _gracePeriodStopBlock; ...
0.4.18
// Initiate dividends round ( owner can transfer ETH to contract and initiate dividends round ) // aDividendsRound - is integer value of dividends period such as YYYYMM example 201712 (year 2017, month 12)
function setDividends(uint32 _dividendsRound) public payable onlyOwner { if (_dividendsRound > 0) { if (msg.value < 1000000000000000) revert(); dividendsSum = msg.value; dividendsBuffer = msg.value; } else { dividendsSum = 0; dividendsBu...
0.4.18
// Get dividends
function getDividends() public { if (dividendsBuffer == 0) revert(); if (balanceOf[msg.sender] == 0) revert(); if (paidDividends[msg.sender][dividendsRound] != 0) revert(); uint256 divAmount = calcDividendsSum(msg.sender); if (divAmount >= 100000000000000) { if ...
0.4.18
// Stop ICO
function stopICO() public onlyOwner { if ( gracePeriodStopBlock > block.number ) gracePeriodStopBlock = block.number; icoFinished = true; weiToPresalersFromICO = icoRaisedETH * percentToPresalersFromICO / 10000; if (soldedSupply >= (burnAfterSoldAmount * 100000000)) { ...
0.4.18
// Withdraw ETH to founders
function withdrawToFounders(uint256 amount) public onlyOwner { uint256 amount_to_withdraw = amount * 1000000000000000; // 0.001 ETH if ((this.balance - weiToPresalersFromICO) < amount_to_withdraw) revert(); amount_to_withdraw = amount_to_withdraw / foundersAddresses.length; uint8 i = 0;...
0.4.18
/** * @dev Swaps funds to another token. * @param outputToken The output ERC20SwappableOutput token contract address. * @param payee The address to which the output funds will be sent. * @param inputAmount The amount of input tokens to be burned. */
function swap(address outputToken, address payee, uint256 inputAmount) external returns (bool) { require(_outputSwapTokens[outputToken] != 0, "Output token is not a registered output swap token."); require(inputAmount > 0, "No funds inputted to swap."); require(inputAmount <= this.balanceOf(p...
0.5.16
// GET Membership OF A WALLET AS STRING.
function manokengNameOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCou...
0.7.6
// Note: // This method should have been called issue(address _receiver), but will remain this for meme value
function squanderMyEthForWorthlessBeans(address _receiver) payable public { // Goals: // 1. deposit eth into the vault // 2. give the holder a claim on the vault for later withdrawal to the address they choose // 3. pay the protocol require(getExc...
0.5.17
// note: all values used by defisaver are in WAD format // we do not need that level of precision on this method // so for simplicity and readability they are all set in discrete percentages here
function automate( uint _repaymentRatio, uint _targetRatio, uint _boostRatio, uint _minRedemptionRatio, uint _automationFeePerc, uint _riskLimit) public auth { // for reference - this function is called on the ...
0.5.17
/** * @notice Stake tokens to earn rewards * @param tokenAddress Staking token address * @param amount Amount of tokens to be staked */
function stake( address referrerAddress, address tokenAddress, uint256 amount ) external whenNotPaused { // checks require( _msgSender() != referrerAddress, "STAKE: invalid referrer address" ); require( tokenDetai...
0.7.6
/** * @notice Claim accumulated rewards * @param stakeId Stake ID of the user * @param stakedAmount Staked amount of the user */
function claimRewards( address userAddress, uint256 stakeId, uint256 stakedAmount, uint256 totalStake ) internal { // Local variables uint256 interval; uint256 endOfProfit; interval = poolStartTime.add(stakeDuration); // Interval ...
0.7.6
/** * @notice Get rewards for one day * @param stakedAmount Stake amount of the user * @param stakedToken Staked token address of the user * @param rewardToken Reward token address * @return reward One dayh reward for the user */
function getOneDayReward( uint256 stakedAmount, address stakedToken, address rewardToken, uint256 totalStake ) public view returns (uint256 reward) { uint256 lockBenefit; if (tokenDetails[stakedToken].optionableStatus) { stakedAmount = stakedAmou...
0.7.6
/** * @notice Get rewards for one day * @param stakedToken Stake amount of the user * @param tokenAddress Reward token address * @param amount Amount to be transferred as reward */
function sendToken( address userAddress, address stakedToken, address tokenAddress, uint256 amount ) internal { // Checks if (tokenAddress != address(0)) { require( rewardCap[tokenAddress] >= amount, "SEND : Insuff...
0.7.6
/** * @notice Unstake and claim rewards * @param stakeId Stake ID of the user */
function unStake(address userAddress, uint256 stakeId) external whenNotPaused returns (bool) { require( _msgSender() == userAddress || _msgSender() == _owner, "UNSTAKE: Invalid User Entry" ); address stakedToken = stakingDetails[user...
0.7.6
/** * @notice View staking details * @param _user User address */
function viewStakingDetails(address _user) public view returns ( address[] memory, address[] memory, bool[] memory, uint256[] memory, uint256[] memory, uint256[] memory ) { return ( ...
0.7.6
/** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */
function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, ...
0.8.7
/** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */
function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == a...
0.8.7
///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// /////////////////////////////////////////////////////////////////////
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tok...
0.8.7
/** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */
function mint(address account, uint256 amount, bool shouldPause) public onlyMinter returns (bool) { _mint(account, amount); // First time being minted? Then let's ensure // the token will remain paused for now if (shouldPause && !_isPaused(account)) { _pauseAccount(acc...
0.5.0
// To stake token user will call this method // user can stake only once while
function stake(uint256 amount) nonReentrant external returns (bool) { require(enabled == true); require(amount <= 115792089237316195423570985008687907853269984665640564039457584007913129639935, "Overflow"); if (stakedAmount[msg.sender] == 0) { bool isOk = IERC20(StakingToken)...
0.7.5
// To unstake token user will call this method // user get daily rewards according to calulation // for first 28 days we give 1.0% rewards per day // after 31 day reward is 1.5% per day
function unStake() nonReentrant external returns (bool) { require(stakedAmount[msg.sender] != 0, "ERR_NOT_STACKED"); uint256 lastStackTime = lastStack[msg.sender]; uint256 amount = stakedAmount[msg.sender]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); ...
0.7.5
// user can check balance if they unstake now
function balanceOf(address _whom) external view returns (uint256) { uint256 lastStackTime = lastStack[_whom]; uint256 amount = stakedAmount[_whom]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); uint256 totalReward = 0; if (_days > rewardBreakin...
0.7.5