comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint bTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), bTokenBalance, borrowBalance, exchangeRateMantissa); }
0.5.16
/** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); }
0.5.16
/** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */
function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } }
0.5.16
/** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); }
0.5.16
/** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); }
0.5.16
/** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming bTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); }
0.5.16
/** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); }
0.5.16
/** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); }
0.5.16
/** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); }
0.5.16
/** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */
function liquidateBorrowInternal(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = bTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, bTokenCollateral); }
0.5.16
/** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); }
0.5.16
/** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); }
0.5.16
/** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setBController(BControllerInterface newBController) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK); } BControllerInterface oldBController = bController; // Ensure invoke bController.isBController() returns true require(newBController.isBController(), "marker method returned false"); // Set market's bController to newBController bController = newBController; // Emit NewBController(oldBController, newBController) emit NewBController(oldBController, newBController); return uint(Error.NO_ERROR); }
0.5.16
/** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); }
0.5.16
/** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewTokenReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); }
0.5.16
/** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; }
0.5.16
/** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom with multiple From and to Addresses * @param _tokenIds The asset identifiers * @param _fromB the address sending from * @param _toB the address sending to */
function multiBatchSafeTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } }
0.4.24
/** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); }
0.5.16
/** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); }
0.5.16
/** * @notice Batch Function to approve the spender * @dev Helps to approve a batch of collectibles * @param _tokenIds The asset identifiers * @param _spender The spender */
function batchApprove( uint256[] _tokenIds, address _spender ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _spender != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; approve(_spender, _id); } }
0.4.24
/** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */
function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract }
0.5.16
/** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */
function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); }
0.5.16
/** * @notice deposit token into the pool from the source * @param amount amount of token to deposit * @return true if success */
function depositAssetToken(uint256 amount) external virtual override returns (bool) { require(msg.sender == _poolSource, "Only designated source can deposit token"); require(amount > 0, "Amount must be greater than 0"); _wToken.transferFrom(_poolSource, address(this), amount); emit TokenDeposited(amount); return true; }
0.6.8
/** * @notice withdraw token from the pool back to the source * @param amount amount of token to withdraw * @return true if success */
function withdrawAssetToken(uint256 amount) external virtual override returns (bool) { require(msg.sender == _poolSource, "Only designated source can withdraw token"); require(amount > 0, "Amount must be greater than 0"); _wToken.transfer(_poolSource, amount); emit TokenWithdrawn(amount); return true; }
0.6.8
/** * @notice given an USD amount, calculate resulting wToken amount * @param usdAmount amount of USD for conversion * @return amount of resulting wTokens */
function usdToToken(uint256 usdAmount) public view returns (uint256) { (bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1); require(success, "Failed to fetch USD/CAD exchange rate"); require(granularity <= 36, "USD rate granularity too high"); // use mul before div return usdAmount.mul(USDToCADRate).mul(100).div(10 ** granularity).div(_fixedPriceCADCent); }
0.6.8
/** * @notice view max amount of USD deposit that can be accepted * @return max amount of USD deposit (18 decimal places) */
function availableTokenInUSD() external view returns (uint256) { (bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1); require(success, "Failed to fetch USD/CAD exchange rate"); require(granularity <= 36, "USD rate granularity too high"); uint256 tokenAmount = tokensAvailable(); return tokenAmount.mul(_fixedPriceCADCent).mul(10 ** granularity).div(100).div(USDToCADRate); }
0.6.8
/** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */
function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); }
0.8.4
/** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */
function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); }
0.5.8
// Calculate amount that needs to be paid
function totalPaymentRequired (uint amountMinted) internal returns (uint) { uint discountedMintsRemaining = discountedMints; uint totalPrice; if(discountedMintsRemaining == 0) { totalPrice = amountMinted * mintPrice; } else if (discountedMintsRemaining >= amountMinted) { totalPrice = amountMinted * discountedMintPrice; discountedMintsRemaining -= amountMinted; } else { totalPrice = (discountedMintsRemaining * discountedMintPrice) + ((amountMinted-discountedMintsRemaining) * mintPrice); discountedMintsRemaining = 0; } discountedMints = discountedMintsRemaining; return totalPrice; }
0.8.12
// promoMultiMint - this mint is for marketing ,etc, minted directly to the wallet of the recepient // for each item, a random character is chosen and minted. Max inclusing team mint is 200 (tracking reserved mint) // only approved wallets
function promoMultiMint (address receiver, uint quantity) public nonReentrant { require(approvedTeamMinters[msg.sender], "Minter not approved"); require(reservedMint > 0, "No reserved mint remaining"); uint16[10] memory characterTracker = divergentCharacters; uint[10] memory mintedCharacters; for (uint i= 0; i < quantity; i++ ){ bytes32 newRandomSelection = keccak256(abi.encodePacked(block.difficulty, block.coinbase, i)); uint pickCharacter = uint(newRandomSelection)%10; mintedCharacters[pickCharacter] += 1; characterTracker[pickCharacter] -= 1; } _safeMint(receiver, quantity); divergentCharacters = characterTracker; reservedMint -= quantity; emit Minted(mintedCharacters, receiver); }
0.8.12
/** * @param threshold exceed the threshold will get bonus */
function _setBonusConditions( uint256 threshold, uint256 t1BonusTime, uint256 t1BonusRate, uint256 t2BonusTime, uint256 t2BonusRate ) private onlyOwner { require(threshold > 0," threshold cannot be zero."); require(t1BonusTime < t2BonusTime, "invalid bonus time"); require(t1BonusRate >= t2BonusRate, "invalid bonus rate"); bonusThreshold = threshold; tierOneBonusTime = t1BonusTime; tierOneBonusRate = t1BonusRate; tierTwoBonusTime = t2BonusTime; tierTwoBonusRate = t2BonusRate; emit BonusConditionsSet( msg.sender, threshold, t1BonusTime, t1BonusRate, t2BonusTime, t2BonusRate ); }
0.5.8
/** * @dev buy tokens * @dev buyer must be in whitelist * @param exToken address of the exchangeable token * @param amount amount of the exchangeable token */
function buyTokens( address exToken, uint256 amount ) external { require(_exTokens[exToken].accepted, "token was not accepted"); require(amount != 0, "amount cannot 0"); require(whitelist[msg.sender], "buyer must be in whitelist"); // calculate token amount to sell uint256 tokens = _getTokenAmount(exToken, amount); require(tokens >= 10**19, "at least buy 10 tokens per purchase"); _forwardFunds(exToken, amount); _processPurchase(msg.sender, tokens); emit TokensPurchased(msg.sender, exToken, amount, tokens); }
0.5.8
/** * @dev calculated purchased sale token amount * @param exToken address of the exchangeable token * @param amount amount of the exchangeable token (how much to pay) * @return amount of purchased sale token */
function _getTokenAmount( address exToken, uint256 amount ) private view returns (uint256) { // round down value (v) by multiple (m) = (v / m) * m uint256 value = amount .div(100000000000000000) .mul(100000000000000000) .mul(_exTokens[exToken].rate); return _applyBonus(value); }
0.5.8
/* * fallback subscription logic */
function() public payable { /* * only when contract is active */ require(paused == 0, 'paused'); /* * smart contracts are not allowed to participate */ require(tx.origin == msg.sender, 'not allowed'); /* * only when contract is active */ require(msg.value >= price, 'low amount'); /* * subscribe the user */ users.push(msg.sender); /* * log the event */ emit NewBet(msg.sender); /* * collect the ETH */ owner.transfer(msg.value); }
0.4.24
/* * bet details */
function details() public view returns ( address _owner , bytes16 _name , uint _price , uint _total , uint _paused ) { return ( owner , name , price , users.length , paused ); }
0.4.24
// promoMint
function promoMint (address[] calldata receiver) public nonReentrant { require(approvedTeamMinters[msg.sender], "Minter not approved"); require(reservedMint > 0, "No reserved mint remaining"); uint16[10] memory characterTracker = divergentCharacters; for (uint i = 0; i < receiver.length; i++) { bytes32 newRandomSelection = keccak256(abi.encodePacked(block.difficulty, block.coinbase, i)); uint pickCharacter = uint(newRandomSelection)%10; uint[10] memory mintedCharacters; mintedCharacters[pickCharacter] += 1; characterTracker[pickCharacter] -= 1; _safeMint(receiver[i], 1); emit Minted(mintedCharacters, receiver[i]); } divergentCharacters = characterTracker; reservedMint -= receiver.length; }
0.8.12
//Guru minting
function guruMint(address receiver, uint quantity) public nonReentrant { require(approvedTeamMinters[msg.sender], "Minter not approved"); require(divergentGuru >= quantity, "Insufficient remaining Guru"); // Mint _safeMint(msg.sender, quantity); // Net off against guruminted divergentGuru -= quantity; // emit event emit GuruMinted(quantity, receiver); }
0.8.12
/** * @dev Allows entities to exchange their Ethereum for tokens representing * their tax credits. This function mints new tax credit tokens that are backed * by the ethereum sent to exchange for them. */
function exchange(string memory email) public payable { require(msg.value > minimumPurchase); require(keccak256(bytes(email)) != keccak256(bytes(""))); // require email parameter addresses.push(msg.sender); emails[msg.sender] = email; uint256 tokens = msg.value.mul(exchangeRate); tokens = tokens.mul(discountRate); tokens = tokens.div(1 ether).div(1 ether); // offset exchange rate & discount rate multiplications _handleMint(msg.sender, tokens); emit Exchange(email, msg.sender, tokens); }
0.5.1
/** * @dev Allows owner to change minimum purchase in order to keep minimum * tax credit exchange around a certain USD threshold * @param newMinimum The new minimum amount of ether required to purchase tax credit tokens */
function changeMinimumExchange(uint256 newMinimum) public onlyOwner { require(newMinimum > 0); // if minimum is 0 then division errors will occur for exchange and discount rates minimumPurchase = newMinimum * 1 ether; exchangeRate = 270000 ether / minimumPurchase; }
0.5.1
/* * @dev Return all addresses belonging to a certain email (it is possible that an * entity may purchase tax credit tokens multiple times with different Ethereum addresses). * * NOTE: This transaction may incur a significant gas cost as more participants purchase credits. */
function getAllAddresses(string memory email) public view onlyOwner returns (address[] memory) { address[] memory all = new address[](addresses.length); for (uint32 i = 0; i < addresses.length; i++) { if (keccak256(bytes(emails[addresses[i]])) == keccak256(bytes(email))) { all[i] = addresses[i]; } } return all; }
0.5.1
/** * @dev funtion that returns a callers staked position in a pool * using `_pid` as an argument. */
function accountPosition(address _account, uint256 _pid) public view returns ( address _accountAddress, uint256 _unlockHeight, uint256 _lockedAmount, uint256 _lockPeriodInDays, uint256 _userDPY, IERC20 _lpTokenAddress, uint256 _totalRewardsPaidFromPool ) { LiquidityProviders memory p = provider[_pid][_account]; PoolInfo memory pool = poolInfo[_pid]; return ( p.Provider, p.UnlockHeight, p.LockedAmount, p.Days, p.UserBP, pool.ContractAddress, pool.TotalRewardsPaidByPool ); }
0.7.4
/** * @dev allows accounts with the _ADMIN role to set new lock periods. */
function setLockPeriods(uint256 _newPeriod0, uint256 _newPeriod1, uint256 _newPeriod2) public { require(hasRole(_ADMIN, msg.sender),"LiquidityMining: Message Sender must be _ADMIN"); require(_newPeriod2 > _newPeriod1 && _newPeriod1 > _newPeriod0); lockPeriod0 = _newPeriod0; lockPeriod1 = _newPeriod1; lockPeriod2 = _newPeriod2; }
0.7.4
/** * @dev this function allows a user to add a liquidity Staking * position. The user will need to choose one of the three * configured lock Periods. Users may add to the position * only once per lock period. */
function addPosition(uint256 _lpTokenAmount, uint256 _lockPeriod, uint256 _pid) public addPositionNotDisabled unpaused{ LiquidityProviders storage p = provider[_pid][msg.sender]; PoolInfo storage pool = poolInfo[_pid]; address ca = address(this); require(p.LockedAmount == 0, "LiquidityMining: This account already has a position"); if(_lockPeriod == lockPeriod0) { pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount); uint _preYield = _lpTokenAmount.mul(lockPeriod0BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod); provider[_pid][msg.sender] = LiquidityProviders ( msg.sender, block.number.add(periodCalc.mul(lockPeriod0)), _lpTokenAmount, lockPeriod0, lockPeriod0BasisPoint, p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor)) ); fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor)); pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount); pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor)); } else if (_lockPeriod == lockPeriod1) { pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount); uint _preYield = _lpTokenAmount.mul(lockPeriod1BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod); provider[_pid][msg.sender] = LiquidityProviders ( msg.sender, block.number.add(periodCalc.mul(lockPeriod1)), _lpTokenAmount, lockPeriod1, lockPeriod1BasisPoint, p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor)) ); fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor)); pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount); pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor)); } else if (_lockPeriod == lockPeriod2) { pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount); uint _preYield = _lpTokenAmount.mul(lockPeriod2BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod); provider[_pid][msg.sender] = LiquidityProviders ( msg.sender, block.number.add(periodCalc.mul(lockPeriod2)), _lpTokenAmount, lockPeriod2, lockPeriod2BasisPoint, p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor)) ); fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor)); pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount); pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor)); }else revert("LiquidityMining: Incompatible Lock Period"); }
0.7.4
/** * @dev allows a user to remove a liquidity staking position * and will withdraw any pending rewards. User must withdraw * the entire position. */
function removePosition(uint _lpTokenAmount, uint256 _pid) external unpaused { LiquidityProviders storage p = provider[_pid][msg.sender]; PoolInfo storage pool = poolInfo[_pid]; require(_lpTokenAmount == p.LockedAmount, "LiquidyMining: Either you do not have a position or you must remove the entire amount."); require(p.UnlockHeight < block.number, "LiquidityMining: Not Long Enough"); pool.ContractAddress.safeTransfer(msg.sender, _lpTokenAmount); uint yield = calculateUserDailyYield(_pid); fundamenta.mintTo(msg.sender, yield); provider[_pid][msg.sender] = LiquidityProviders ( msg.sender, 0, p.LockedAmount.sub(_lpTokenAmount), 0, 0, p.TotalRewardsPaid.add(yield) ); pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(yield); pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.sub(_lpTokenAmount); }
0.7.4
/** * @dev funtion to forcibly remove a users position. This is required due to the fact that * the basis points and scales used to calculate user DPY will be constantly changing. We * will need to forceibly remove positions of lazy (or malicious) users who will try to take * advantage of DPY being lowered instead of raised and maintining thier current return levels. */
function forcePositionRemoval(uint256 _pid, address _account) public { require(hasRole(_REMOVAL, msg.sender)); LiquidityProviders storage p = provider[_pid][_account]; PoolInfo storage pool = poolInfo[_pid]; uint256 _lpTokenAmount = p.LockedAmount; pool.ContractAddress.safeTransfer(_account, _lpTokenAmount); uint256 _newLpTokenAmount = p.LockedAmount.sub(_lpTokenAmount); uint yield = calculateUserDailyYield(_pid); fundamenta.mintTo(msg.sender, yield); provider[_pid][_account] = LiquidityProviders ( _account, 0, _newLpTokenAmount, 0, 0, p.TotalRewardsPaid.add(yield) ); pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(yield); pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.sub(_lpTokenAmount); }
0.7.4
/** * @notice Create a new role. * @param _roleDescription The description of the role created. * @param _admin The role that is allowed to add and remove * bearers from the role being created. * @return The role id. */
function addRole(string memory _roleDescription, uint256 _admin) public returns(uint256) { require(_admin <= roles.length, "Admin role doesn't exist."); uint256 role = roles.push( Role({ description: _roleDescription, admin: _admin }) ) - 1; emit RoleCreated(role); return role; }
0.5.17
// Used by Blockbid admin to calculate amount of BIDL to deposit in the contract.
function admin_getBidlAmountToDeposit() public view returns (uint256) { uint256 weiBalance = address(this).balance; uint256 bidlAmountSupposedToLock = weiBalance / _weiPerBidl; uint256 bidlBalance = _bidlToken.balanceOf(address(this)); if (bidlAmountSupposedToLock < bidlBalance) { return 0; } return bidlAmountSupposedToLock - bidlBalance; }
0.5.11
// Process ETH coming from the pool participant address.
function () external payable { // Do not allow changing participant address after it has been set. if (_poolParticipant != address(0) && _poolParticipant != msg.sender) { revert(); } // Do not allow top-ups if the contract had been activated. if (_activated) { revert(); } uint256 weiBalance = address(this).balance; // Refund excessive ETH. if (weiBalance > _maxBalanceWei) { uint256 excessiveWei = weiBalance.sub(_maxBalanceWei); msg.sender.transfer(excessiveWei); weiBalance = _maxBalanceWei; } if (_poolParticipant != msg.sender) _poolParticipant = msg.sender; }
0.5.11
/** * @notice A method to remove a bearer from a role * @param _account The account to remove as a bearer. * @param _role The role to remove the bearer from. */
function removeBearer(address _account, uint256 _role) external { require( _role < roles.length, "Role doesn't exist." ); require( hasRole(msg.sender, roles[_role].admin), "User can't remove bearers." ); require( hasRole(_account, _role), "Account is not bearer of role." ); delete roles[_role].bearers[_account]; emit BearerRemoved(_account, _role); }
0.5.17
/** * @notice Create a new escrow * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _username The username of the user */
function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username ) public returns (uint escrowId) { address sender = getSender(); lastActivity[sender] = block.timestamp; escrowId = escrow.createEscrow_relayed( address(uint160(sender)), _offerId, _tokenAmount, _fiatAmount, _contactData, _location, _username ); }
0.5.10
/** * @notice Function returning if we accept or not the relayed call (do we pay or not for the gas) * @param from Address of the buyer getting a free transaction * @param encodedFunction Function that will be called on the Escrow contract * @param gasPrice Gas price * @dev relay and transaction_fee are useless in our relay workflow */
function acceptRelayedCall( address /* relay */, address from, bytes calldata encodedFunction, uint256 /* transactionFee */, uint256 gasPrice, uint256 /* gasLimit */, uint256 /* nonce */, bytes calldata /* approvalData */, uint256 /* maxPossibleCharge */ ) external view returns (uint256, bytes memory) { bytes memory abiEncodedFunc = encodedFunction; // Call data elements cannot be accessed directly bytes4 fSign; uint dataValue; assembly { fSign := mload(add(abiEncodedFunc, add(0x20, 0))) dataValue := mload(add(abiEncodedFunc, 36)) } return (_evaluateConditionsToRelay(from, gasPrice, fSign, dataValue), ""); }
0.5.10
/** * @dev Evaluates if the sender conditions are valid for relaying a escrow transaction * @param from Sender * @param gasPrice Gas Price * @param functionSignature Function Signature * @param dataValue Represents the escrowId or offerId depending on the function being called */
function _evaluateConditionsToRelay(address from, uint gasPrice, bytes4 functionSignature, uint dataValue) internal view returns (uint256) { address token; if(functionSignature == RATE_SIGNATURE && gasPrice < 20000000000){ return OK; } if(from.balance > 600000 * gasPrice) return ERROR_ENOUGH_BALANCE; if(gasPrice > 20000000000) return ERROR_GAS_PRICE; // 20Gwei if(functionSignature == PAY_SIGNATURE || functionSignature == CANCEL_SIGNATURE || functionSignature == OPEN_CASE_SIGNATURE){ address payable buyer; (buyer, , token, ) = escrow.getBasicTradeData(dataValue); if(buyer != from) return ERROR_INVALID_BUYER; if(token != snt && token != address(0)) return ERROR_INVALID_ASSET; if(functionSignature == CANCEL_SIGNATURE){ // Allow activity after 15min have passed if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON; } return OK; } else if(functionSignature == CREATE_SIGNATURE) { token = metadataStore.getAsset(dataValue); if(token != snt && token != address(0)) return ERROR_INVALID_ASSET; // Allow activity after 15 min have passed if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON; return OK; } return ERROR; }
0.5.10
// Write (n - 1) as 2^s * d
function getValues(uint256 n) public pure returns (uint256[2] memory) { uint256 s = 0; uint256 d = n - 1; while (d % 2 == 0) { d = d / 2; s++; } uint256[2] memory ret; ret[0] = s; ret[1] = d; return ret; }
0.8.7
/** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */
function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } }
0.4.21
/** * @dev Appends uint (in decimal) to a string * @param _str The prefix string * @param _value The uint to append * @return resulting string */
function _appendUintToString(string _str, uint _value) internal pure returns (string) { uint maxLength = 100; bytes memory reversed = new bytes(maxLength); uint i = 0; while (_value != 0) { uint remainder = _value % 10; _value = _value / 10; reversed[i++] = byte(48 + remainder); } i--; bytes memory inStrB = bytes(_str); bytes memory s = new bytes(inStrB.length + i + 1); uint j; for (j = 0; j < inStrB.length; j++) { s[j] = inStrB[j]; } for (j = 0; j <= i; j++) { s[j + inStrB.length] = reversed[i - j]; } return string(s); }
0.4.21
/** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */
function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; // If a hero is removed from its owner, it no longer can be their active hero if (activeHero[_from] == _tokenId) { activeHero[_from] = 0; emit ActiveHeroChanged(_from, 0); } }
0.4.21
/** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */
function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; // Clear genome data if (genome[_tokenId] != 0) { genome[_tokenId] = 0; } }
0.4.21
/** * @dev Allows setting hero data for a hero * @param _tokenId hero to set data for * @param _fieldA data to set * @param _fieldB data to set * @param _fieldC data to set * @param _fieldD data to set * @param _fieldE data to set * @param _fieldF data to set * @param _fieldG data to set */
function setHeroData( uint256 _tokenId, uint16 _fieldA, uint16 _fieldB, uint32 _fieldC, uint32 _fieldD, uint32 _fieldE, uint64 _fieldF, uint64 _fieldG ) external onlyLogicContract { heroData[_tokenId] = HeroData( _fieldA, _fieldB, _fieldC, _fieldD, _fieldE, _fieldF, _fieldG ); }
0.4.21
/** * @dev Release one of the payee's proportional payment. * @param account Whose payments will be released. */
function release(address account) public { require(_shares[account] > 0); uint256 totalReceived = address(this).balance.add(_totalReleased); uint256 payment = totalReceived.mul( _shares[account]).div( _totalShares).sub( _released[account] ); require(payment != 0); _released[account] = _released[account].add(payment); _totalReleased = _totalReleased.add(payment); account.transfer(payment); emit PaymentReleased(account, payment); }
0.4.24
// transfer _value tokens to _to from msg.sender
function transfer(address _to, uint256 _value) public returns (bool) { // if you want to destroy tokens, use burn replace transfer to address 0 require(_to != address(0)); // can not transfer to self require(_to != msg.sender); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
0.4.23
// decrease approval to _spender
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
0.4.23
/** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. */
function _mint(address _to, uint seed) internal returns (string) { require(_to != address(0)); require(numTokens < TOKEN_LIMIT); uint amount = 0; if (numTokens >= ARTIST_PRINTS) { amount = PRICE; require(msg.value >= amount); } require(seedToId[seed] == 0); uint id = numTokens + 1; idToCreator[id] = _to; idToSeed[id] = seed; seedToId[seed] = id; uint a = uint(uint160(keccak256(abi.encodePacked(seed)))); idToSymbolScheme[id] = getScheme(a); string memory uri = draw(id); emit Generated(id, _to, uri); numTokens = numTokens + 1; _addNFToken(_to, id); if (msg.value > amount) { msg.sender.transfer(msg.value - amount); } if (amount > 0) { BENEFICIARY.transfer(amount); } emit Transfer(address(0), _to, id); return uri; }
0.4.24
// Internal transfer function which includes the Fee
function _transfer(address _from, address _to, uint _value) private { require(_balances[_from] >= _value, 'Must not send more than balance'); require(_balances[_to] + _value >= _balances[_to], 'Balance overflow'); if(!mapHolder[_to]){holderArray.push(_to); holders+=1; mapHolder[_to]=true;} _balances[_from] =_balances[_from].sub(_value); uint _fee = _getFee(_from, _to, _value); // Get fee amount _balances[_to] += (_value.sub(_fee)); // Add to receiver _balances[address(this)] += _fee; // Add fee to self totalFees += _fee; // Track fees collected emit Transfer(_from, _to, (_value.sub(_fee))); // Transfer event if (!mapAddress_Excluded[_from] && !mapAddress_Excluded[_to]) { emit Transfer(_from, address(this), _fee); // Fee Transfer event } }
0.6.4
// Calculate Fee amount
function _getFee(address _from, address _to, uint _value) private view returns (uint) { if (mapAddress_Excluded[_from] || mapAddress_Excluded[_to]) { return 0; // No fee if excluded } else { return (_value / 1000); // Fee amount = 0.1% } }
0.6.4
/** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based }
0.6.12
// Allow to query for remaining upgrade amount
function getRemainingAmount() public view returns (uint amount){ uint maxEmissions = (upgradeHeight-1) * mapEra_Emission[1]; // Max Emission on Old Contract uint maxUpgradeAmount = (maxEmissions).sub(VETH(vether2).totalFees()); // Minus any collected fees if(maxUpgradeAmount >= upgradedAmount){ return maxUpgradeAmount.sub(upgradedAmount); // Return remaining } else { return 0; // Return 0 } }
0.6.4
// V1 upgrades by calling V2 snapshot
function upgradeV1() public { uint amount = ERC20(vether1).balanceOf(msg.sender); // Get Balance Vether1 if(amount > 0){ if(VETH(vether2).mapPreviousOwnership(msg.sender) < amount){ amount = VETH(vether2).mapPreviousOwnership(msg.sender); // Upgrade as much as possible } uint remainingAmount = getRemainingAmount(); if(remainingAmount < amount){amount = remainingAmount;} // Handle final amount upgradedAmount += amount; mapPreviousOwnership[msg.sender] = mapPreviousOwnership[msg.sender].sub(amount); // Update mappings ERC20(vether1).transferFrom(msg.sender, burnAddress, amount); // Must collect & burn tokens _transfer(address(this), msg.sender, amount); // Send to owner } }
0.6.4
// V2 upgrades by calling V3 internal snapshot
function upgradeV2() public { uint amount = ERC20(vether2).balanceOf(msg.sender); // Get Balance Vether2 if(amount > 0){ if(mapPreviousOwnership[msg.sender] < amount){ amount = mapPreviousOwnership[msg.sender]; // Upgrade as much as possible } uint remainingAmount = getRemainingAmount(); if(remainingAmount < amount){amount = remainingAmount;} // Handle final amount upgradedAmount += amount; mapPreviousOwnership[msg.sender] = mapPreviousOwnership[msg.sender].sub(amount); // Update mappings ERC20(vether2).transferFrom(msg.sender, burnAddress, amount); // Must collect & burn tokens _transfer(address(this), msg.sender, amount); // Send to owner } }
0.6.4
// Internal - Records burn
function _recordBurn(address _payer, address _member, uint _era, uint _day, uint _eth) private { require(VETH(vether1).currentDay() >= upgradeHeight || VETH(vether1).currentEra() > 1); // Prohibit until upgrade height if (mapEraDay_MemberUnits[_era][_day][_member] == 0){ // If hasn't contributed to this Day yet mapMemberEra_Days[_member][_era].push(_day); // Add it mapEraDay_MemberCount[_era][_day] += 1; // Count member mapEraDay_Members[_era][_day].push(_member); // Add member } mapEraDay_MemberUnits[_era][_day][_member] += _eth; // Add member's share mapEraDay_UnitsRemaining[_era][_day] += _eth; // Add to total historicals mapEraDay_Units[_era][_day] += _eth; // Add to total outstanding totalBurnt += _eth; // Add to total burnt emit Burn(_payer, _member, _era, _day, _eth, mapEraDay_Units[_era][_day]); // Burn event _updateEmission(); // Update emission Schedule }
0.6.4
// Allows changing an excluded address
function changeExcluded(address excluded) external { if(!mapAddress_Excluded[excluded]){ _transfer(msg.sender, address(this), mapEra_Emission[1]/16); // Pay fee of 128 Vether mapAddress_Excluded[excluded] = true; // Add desired address totalFees += mapEra_Emission[1]/16; } else { _transfer(msg.sender, address(this), mapEra_Emission[1]/32); // Pay fee of 64 Vether mapAddress_Excluded[excluded] = false; // Change desired address totalFees += mapEra_Emission[1]/32; } }
0.6.4
// Internal - withdraw function
function _withdrawShare (uint _era, uint _day, address _member) private returns (uint value) { _updateEmission(); if (_era < currentEra) { // Allow if in previous Era value = _processWithdrawal(_era, _day, _member); // Process Withdrawal } else if (_era == currentEra) { // Handle if in current Era if (_day < currentDay) { // Allow only if in previous Day value = _processWithdrawal(_era, _day, _member); // Process Withdrawal } } return value; }
0.6.4
// Internal - Withdrawal function
function _processWithdrawal (uint _era, uint _day, address _member) private returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[_era][_day][_member]; // Get Member Units if (memberUnits == 0) { value = 0; // Do nothing if 0 (prevents revert) } else { value = getEmissionShare(_era, _day, _member); // Get the emission Share for Member mapEraDay_MemberUnits[_era][_day][_member] = 0; // Set to 0 since it will be withdrawn mapEraDay_UnitsRemaining[_era][_day] = mapEraDay_UnitsRemaining[_era][_day].sub(memberUnits); // Decrement Member Units mapEraDay_EmissionRemaining[_era][_day] = mapEraDay_EmissionRemaining[_era][_day].sub(value); // Decrement emission totalEmitted += value; // Add to Total Emitted _transfer(address(this), _member, value); // ERC20 transfer function emit Withdrawal(msg.sender, _member, _era, _day, value, mapEraDay_EmissionRemaining[_era][_day]); } return value; }
0.6.4
// Get emission Share function
function getEmissionShare(uint era, uint day, address member) public view returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[era][day][member]; // Get Member Units if (memberUnits == 0) { return 0; // If 0, return 0 } else { uint totalUnits = mapEraDay_UnitsRemaining[era][day]; // Get Total Units uint emissionRemaining = mapEraDay_EmissionRemaining[era][day]; // Get emission remaining for Day uint balance = _balances[address(this)]; // Find remaining balance if (emissionRemaining > balance) { emissionRemaining = balance; } // In case less than required emission value = (emissionRemaining * memberUnits) / totalUnits; // Calculate share return value; } }
0.6.4
// Calculate Era emission
function getNextEraEmission() public view returns (uint) { if (emission > coin) { // Normal Emission Schedule return emission / 2; // Emissions: 2048 -> 1.0 } else{ // Enters Fee Era return coin; // Return 1.0 from fees } }
0.6.4
// Calculate Day emission
function getDayEmission() public view returns (uint) { uint balance = _balances[address(this)]; // Find remaining balance if (balance > emission) { // Balance is sufficient return emission; // Return emission } else { // Balance has dropped low return balance; // Return full balance } }
0.6.4
/** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
function transferFrom(address _from, address _to, uint256 _value) external returns(bool success) { // Check allowance require(_value <= _allowance[_from][msg.sender], "Not enough allowance!"); // Check balance require(_value <= _balanceOf[_from], "Not enough balance!"); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); emit Approval(_from, _to, _allowance[_from][_to]); return true; }
0.4.24
/** * @dev User registration */
function regUser(uint _referrerID, bytes32[3] calldata _mrs, uint8 _v) external payable { require(lockStatus == false, "Contract Locked"); require(users[msg.sender].isExist == false, "User exist"); require(_referrerID > 0 && _referrerID <= currentId, "Incorrect referrer Id"); require(msg.value == LEVEL_PRICE[1], "Incorrect Value"); if (users[userList[_referrerID]].referral.length >= referrer1Limit) _referrerID = users[findFreeReferrer(userList[_referrerID])].id; UserStruct memory userStruct; currentId++; userStruct = UserStruct({ isExist: true, id: currentId, referrerID: _referrerID, currentLevel: 1, totalEarningEth:0, referral: new address[](0) }); users[msg.sender] = userStruct; userList[currentId] = msg.sender; users[msg.sender].levelExpired[1] = now.add(PERIOD_LENGTH); users[userList[_referrerID]].referral.push(msg.sender); loopCheck[msg.sender] = 0; createdDate[msg.sender] = now; payForLevel(0, 1, msg.sender, ((LEVEL_PRICE[1].mul(adminFee)).div(10**20)), _mrs, _v, msg.value); emit regLevelEvent(msg.sender, userList[_referrerID], now); }
0.5.14
// // Logging // // This signature is intended for the categorical market creation. We use two signatures for the same event because of stack depth issues which can be circumvented by maintaining order of paramaters
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, bytes32[] _outcomes, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) { require(isKnownUniverse(_universe)); require(_universe == IUniverse(msg.sender)); MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, _outcomes, _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType); return true; }
0.4.20
// This signature is intended for yesNo and scalar market creation. See function comment above for explanation.
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) { require(isKnownUniverse(_universe)); require(_universe == IUniverse(msg.sender)); MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, new bytes32[](0), _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType); return true; }
0.4.20
// // Constructor // // No validation is needed here as it is simply a librarty function for organizing data
function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) { require(_outcome < _market.getNumberOfOutcomes()); require(_price < _market.getNumTicks()); IOrders _orders = IOrders(_controller.lookup("Orders")); IAugur _augur = _controller.getAugur(); return Data({ orders: _orders, market: _market, augur: _augur, id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); }
0.4.20
/** * @dev To buy the next level by User */
function buyLevel(uint256 _level, bytes32[3] calldata _mrs, uint8 _v) external payable { require(lockStatus == false, "Contract Locked"); require(users[msg.sender].isExist, "User not exist"); require(_level > 0 && _level <= 12, "Incorrect level"); if (_level == 1) { require(msg.value == LEVEL_PRICE[1], "Incorrect Value"); users[msg.sender].levelExpired[1] = users[msg.sender].levelExpired[1].add(PERIOD_LENGTH); users[msg.sender].currentLevel = 1; } else { require(msg.value == LEVEL_PRICE[_level], "Incorrect Value"); users[msg.sender].currentLevel = _level; for (uint i = _level - 1; i > 0; i--) require(users[msg.sender].levelExpired[i] >= now, "Buy the previous level"); if (users[msg.sender].levelExpired[_level] == 0) users[msg.sender].levelExpired[_level] = now + PERIOD_LENGTH; else users[msg.sender].levelExpired[_level] += PERIOD_LENGTH; } loopCheck[msg.sender] = 0; payForLevel(0, _level, msg.sender, ((LEVEL_PRICE[_level].mul(adminFee)).div(10**20)), _mrs, _v, msg.value); emit buyLevelEvent(msg.sender, _level, now); }
0.5.14
// // Private functions //
function escrowFundsForBid(Order.Data _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0); require(_orderData.sharesEscrowed == 0); uint256 _attosharesToCover = _orderData.amount; uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes(); // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has uint256 _attosharesHeld = 2**254; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator); _attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld); } } // Take shares into escrow if they have any almost-complete-sets if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; for (_i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { _orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed); } } } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price); require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed)); } return true; }
0.4.20
/** * @dev Update old contract data */
function oldAlexaSync(uint limit) public { require(address(oldAlexa) != address(0), "Initialize closed"); require(msg.sender == ownerAddress, "Access denied"); for (uint i = 0; i <= limit; i++) { UserStruct memory olduser; address oldusers = oldAlexa.userList(oldAlexaId); (olduser.isExist, olduser.id, olduser.referrerID, olduser.currentLevel, olduser.totalEarningEth) = oldAlexa.users(oldusers); address ref = oldAlexa.userList(olduser.referrerID); if (olduser.isExist) { if (!users[oldusers].isExist) { users[oldusers].isExist = true; users[oldusers].id = oldAlexaId; users[oldusers].referrerID = olduser.referrerID; users[oldusers].currentLevel = olduser.currentLevel; users[oldusers].totalEarningEth = olduser.totalEarningEth; userList[oldAlexaId] = oldusers; users[ref].referral.push(oldusers); createdDate[oldusers] = now; emit regLevelEvent(oldusers, ref, now); for (uint j = 1; j <= 12; j++) { users[oldusers].levelExpired[j] = oldAlexa.viewUserLevelExpired(oldusers, j); EarnedEth[oldusers][j] = oldAlexa.EarnedEth(oldusers, j); } } oldAlexaId++; } else { currentId = oldAlexaId.sub(1); break; } } }
0.5.14
/// @dev collectSwapFeesForBTC collects fees in the case of swap WBTC to BTC. /// @param _destToken The address of target token. /// @param _incomingAmount The spent amount. (WBTC) /// @param _minerFee The miner fees of BTC transaction. /// @param _rewardsAmount The fees that should be paid.
function collectSwapFeesForBTC( address _destToken, uint256 _incomingAmount, uint256 _minerFee, uint256 _rewardsAmount ) external override onlyOwner returns (bool) { require(_destToken == address(0), "_destToken should be address(0)"); address _feesToken = WBTC_ADDR; if (_incomingAmount > 0) { uint256 swapAmount = _incomingAmount.sub(_rewardsAmount).sub( _minerFee ); _swap(WBTC_ADDR, address(0), swapAmount.add(_minerFee)); } else if (_incomingAmount == 0) { _feesToken = address(0); } _rewardsCollection(_feesToken, _rewardsAmount); return true; }
0.7.5
/** * @dev register many users */
function registerManyUsersFullExternal( address[] calldata _addresses, uint256 _validUntilTime, uint256[] calldata _values) external onlyOperator returns (bool) { require(_values.length <= extendedKeys_.length, "UR08"); for (uint256 i = 0; i < _addresses.length; i++) { registerUserPrivate(_addresses[i], _validUntilTime); updateUserExtendedPrivate(userCount_, _values); } return true; }
0.5.12
/** * @dev attach many addresses to many users */
function attachManyAddressesExternal( uint256[] calldata _userIds, address[] calldata _addresses) external onlyOperator returns (bool) { require(_addresses.length == _userIds.length, "UR03"); for (uint256 i = 0; i < _addresses.length; i++) { attachAddress(_userIds[i], _addresses[i]); } return true; }
0.5.12
/** * @dev update many users */
function updateManyUsersExternal( uint256[] calldata _userIds, uint256 _validUntilTime, bool _suspended) external onlyOperator returns (bool) { for (uint256 i = 0; i < _userIds.length; i++) { updateUser(_userIds[i], _validUntilTime, _suspended); } return true; }
0.5.12
/** * @dev update many user extended informations */
function updateManyUsersExtendedExternal( uint256[] calldata _userIds, uint256 _key, uint256 _value) external onlyOperator returns (bool) { for (uint256 i = 0; i < _userIds.length; i++) { updateUserExtended(_userIds[i], _key, _value); } return true; }
0.5.12
/// @dev recordIncomingFloat mints LP token. /// @param _token The address of target token. /// @param _addressesAndAmountOfFloat The address of recipient and amount. /// @param _zerofee The flag to accept zero fees. /// @param _txid The txids which is for recording.
function recordIncomingFloat( address _token, bytes32 _addressesAndAmountOfFloat, bool _zerofee, bytes32 _txid ) external override onlyOwner priceCheck returns (bool) { require(whitelist[_token], "_token is invalid"); require( _issueLPTokensForFloat( _token, _addressesAndAmountOfFloat, _zerofee, _txid ) ); return true; }
0.7.5
/** * @dev update many users full */
function updateManyUsersFullExternal( uint256[] calldata _userIds, uint256 _validUntilTime, bool _suspended, uint256[] calldata _values) external onlyOperator returns (bool) { require(_values.length <= extendedKeys_.length, "UR08"); for (uint256 i = 0; i < _userIds.length; i++) { updateUser(_userIds[i], _validUntilTime, _suspended); updateUserExtendedPrivate(_userIds[i], _values); } return true; }
0.5.12
/** * @dev the user associated to the provided address if the user is valid */
function validUser(address _address, uint256[] memory _keys) public view returns (uint256, uint256[] memory) { uint256 addressUserId = walletOwners[_address]; if (isValidPrivate(users[addressUserId])) { uint256[] memory values = new uint256[](_keys.length); for (uint256 i=0; i < _keys.length; i++) { values[i] = users[addressUserId].extended[_keys[i]]; } return (addressUserId, values); } return (0, new uint256[](0)); }
0.5.12
/** * @dev attach an address with a user */
function attachAddress(uint256 _userId, address _address) public onlyOperator returns (bool) { require(_userId > 0 && _userId <= userCount_, "UR01"); require(walletOwners[_address] == 0, "UR02"); walletOwners[_address] = _userId; emit AddressAttached(_userId, _address); return true; }
0.5.12
/** * @dev update a user */
function updateUser( uint256 _userId, uint256 _validUntilTime, bool _suspended) public onlyOperator returns (bool) { require(_userId > 0 && _userId <= userCount_, "UR01"); if (users[_userId].validUntilTime != _validUntilTime) { users[_userId].validUntilTime = _validUntilTime; emit UserValidity(_userId, _validUntilTime); } if (users[_userId].suspended != _suspended) { users[_userId].suspended = _suspended; if (_suspended) { emit UserSuspended(_userId); } else { emit UserRestored(_userId); } } return true; }
0.5.12
/** * @dev update user extended private */
function updateUserExtendedPrivate(uint256 _userId, uint256[] memory _values) private { require(_userId > 0 && _userId <= userCount_, "UR01"); for (uint256 i = 0; i < _values.length; i++) { users[_userId].extended[extendedKeys_[i]] = _values[i]; } emit UserExtendedKeys(_userId, _values); }
0.5.12
/// @dev recordOutcomingFloat burns LP token. /// @param _token The address of target token. /// @param _addressesAndAmountOfLPtoken The address of recipient and amount. /// @param _minerFee The miner fees of BTC transaction. /// @param _txid The txid which is for recording.
function recordOutcomingFloat( address _token, bytes32 _addressesAndAmountOfLPtoken, uint256 _minerFee, bytes32 _txid ) external override onlyOwner priceCheck returns (bool) { require(whitelist[_token], "_token is invalid"); require( _burnLPTokensForFloat( _token, _addressesAndAmountOfLPtoken, _minerFee, _txid ) ); return true; }
0.7.5
/// @dev distributeNodeRewards sends rewards for Nodes.
function distributeNodeRewards() external override returns (bool) { // Reduce Gas uint256 rewardLPTsForNodes = lockedLPTokensForNode.add( feesLPTokensForNode ); require( rewardLPTsForNodes > 0, "totalRewardLPsForNode is not positive" ); bytes32[] memory nodeList = getActiveNodes(); uint256 totalStaked = 0; for (uint256 i = 0; i < nodeList.length; i++) { totalStaked = totalStaked.add( uint256(uint96(bytes12(nodeList[i]))) ); } IBurnableToken(lpToken).mint(address(this), lockedLPTokensForNode); for (uint256 i = 0; i < nodeList.length; i++) { IBurnableToken(lpToken).transfer( address(uint160(uint256(nodeList[i]))), rewardLPTsForNodes .mul(uint256(uint96(bytes12(nodeList[i])))) .div(totalStaked) ); } lockedLPTokensForNode = 0; feesLPTokensForNode = 0; return true; }
0.7.5
// View function to see pending tokens on frontend.
function pendingTokens(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokensPerShare = pool.accTokensPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 tokenReward = tokensPerBlock.mul(pool.allocPoint).div(totalAllocPoint); accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt); }
0.6.6
// Deposit LP tokens to contract for token allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); latestDepositBlockNumberForWallet[msg.sender] = block.number; emit Deposit(msg.sender, _pid, _amount); }
0.6.6
// Withdraw LP tokens from contract.
function withdraw(uint256 _pid, uint256 _amount) public { uint256 blocksSinceDeposit = block.number - latestDepositBlockNumberForWallet[msg.sender]; if(blocksSinceDeposit < maturationPeriod) { revert(); } PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
0.6.6
/// @dev churn transfers contract ownership and set variables of the next TSS validator set. /// @param _newOwner The address of new Owner. /// @param _rewardAddressAndAmounts The reward addresses and amounts. /// @param _isRemoved The flags to remove node. /// @param _churnedInCount The number of next party size of TSS group. /// @param _tssThreshold The number of next threshold. /// @param _nodeRewardsRatio The number of rewards ratio for node owners /// @param _withdrawalFeeBPS The amount of wthdrawal fees.
function churn( address _newOwner, bytes32[] memory _rewardAddressAndAmounts, bool[] memory _isRemoved, uint8 _churnedInCount, uint8 _tssThreshold, uint8 _nodeRewardsRatio, uint8 _withdrawalFeeBPS ) external override onlyOwner returns (bool) { require( _tssThreshold >= tssThreshold && _tssThreshold <= 2**8 - 1, "_tssThreshold should be >= tssThreshold" ); require( _churnedInCount >= _tssThreshold + uint8(1), "n should be >= t+1" ); require( _nodeRewardsRatio >= 0 && _nodeRewardsRatio <= 100, "_nodeRewardsRatio is not valid" ); require( _withdrawalFeeBPS >= 0 && _withdrawalFeeBPS <= 100, "_withdrawalFeeBPS is invalid" ); require( _rewardAddressAndAmounts.length == _isRemoved.length, "_rewardAddressAndAmounts and _isRemoved length is not match" ); transferOwnership(_newOwner); // Update active node list for (uint256 i = 0; i < _rewardAddressAndAmounts.length; i++) { (address newNode, ) = _splitToValues(_rewardAddressAndAmounts[i]); _addNode(newNode, _rewardAddressAndAmounts[i], _isRemoved[i]); } bytes32[] memory nodeList = getActiveNodes(); if (nodeList.length > 100) { revert("Stored node size should be <= 100"); } churnedInCount = _churnedInCount; tssThreshold = _tssThreshold; nodeRewardsRatio = _nodeRewardsRatio; withdrawalFeeBPS = _withdrawalFeeBPS; return true; }
0.7.5