comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** @dev Release one tranche of the ecosystemSupply allocation to Yooba team,6.25% every tranche.About 4 years ecosystemSupply release over. @return true if successful, throws if not */
function releaseForEcosystem() public ownerOnly stoppable returns(bool success) { require(now >= createTime + 12 weeks); require(tokensReleasedToEcosystem < ecosystemSupply); uint256 temp = ecosystemSupply / 10000; uint256 allocAmount = safeMul(temp, 625); uint256 curren...
0.4.21
/** @dev Release one tranche of the teamSupply allocation to Yooba team,6.25% every tranche.About 4 years Yooba team will get teamSupply Tokens. @return true if successful, throws if not */
function releaseForYoobaTeam() public ownerOnly stoppable returns(bool success) { require(now >= createTime + 12 weeks); require(tokensReleasedToTeam < teamSupply); uint256 temp = teamSupply / 10000; uint256 allocAmount = safeMul(temp, 625); uint256 currentTranche = uint...
0.4.21
/** @dev release ico Tokens @return true if successful, throws if not */
function releaseForIco(address _icoAddress, uint256 _value) public ownerOnly stoppable returns(bool success) { require(_icoAddress != address(0x0) && _value > 0 && (tokensReleasedToIco + _value) <= icoReservedSupply && (currentSupply + _value) <= totalSupply); balanceOf[_icoAddress] = safeAdd(ba...
0.4.21
/** @dev release earlyInvestor Tokens @return true if successful, throws if not */
function releaseForEarlyInvestor(address _investorAddress, uint256 _value) public ownerOnly stoppable returns(bool success) { require(_investorAddress != address(0x0) && _value > 0 && (tokensReleasedToEarlyInvestor + _value) <= earlyInvestorSupply && (currentSupply + _value) <= totalSupply); b...
0.4.21
/** * add address to whitelist * @param _addresses wallet addresses to be whitelisted */
function addManyToWhitelist(address[] _addresses) external onlyOwner returns (bool) { require(_addresses.length <= 50); uint idx = 0; uint len = _addresses.length; for (; idx < len; idx++) { address _addr = _addresses[idx]; ...
0.4.18
/* Send Tokens tokens to a buyer: - and KYC is approved */
function sendTokens(address _user) public onlyOwner returns (bool) { require(_user != address(0)); require(_user != address(this)); require(purchaseLog[_user].kycApproved); require(purchaseLog[_user].vztValue > 0); require(!purchaseLog[_user].tokensDistributed); req...
0.4.18
// Deposit LP tokens to MasterChef for xLESS 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.accXLessPerSh...
0.6.12
/* For the convenience of presale interface to find current tier price. */
function getMinimumPurchaseVZTLimit() public view returns (uint256) { if (getTier() == 1) { return minimumPurchaseLimit.mul(PRESALE_RATE); //1250VZT/ether } else if (getTier() == 2) { return minimumPurchaseLimit.mul(SOFTCAP_RATE); //1150VZT/ether } return mi...
0.4.18
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. */
function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool success) { uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = safeSub(ol...
0.4.18
/** * @dev Bulk mint function to save gas. * @dev both arrays requires to have the same length */
function mint(address[] recipients, uint256[] tokens) public returns (bool) { require(msg.sender == owner); for (uint8 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 token = tokens[i]; totalSupply = safeAdd(totalSupply, toke...
0.4.18
/* For the convenience of presale interface to present status info. */
function getPresaleStatus() public view returns (uint256[3]) { // 0 - presale not started // 1 - presale started // 2 - presale ended if (now < startDate) return ([0, startDate, endDate]); else if (now <= endDate && !hasEnded()) return ([1, startDat...
0.4.18
/* Called after presale ends, to do some extra finalization work. */
function finalize() public onlyOwner { // do nothing if finalized require(!isFinalized); // presale must have ended require(hasEnded()); if (isMinimumGoalReached()) { // transfer to VectorZilla multisig wallet VZT_WALLET.transfer(this.balance); ...
0.4.18
/// @dev Internal function to process sale /// @param buyer The buyer address /// @param value The value of ether paid
function purchasePresale(address buyer, uint256 value) internal { require(value >= minimumPurchaseLimit); require(buyer != address(0)); uint256 tokens = 0; // still under soft cap if (!publicSoftCapReached) { // 1 ETH for 1,250 VZT tokens = value ...
0.4.18
/* Internal function to manage refunds */
function doRefund(address buyer) internal returns (bool) { require(tx.gasprice <= MAX_GAS_PRICE); require(buyer != address(0)); require(!purchaseLog[buyer].paidFiat); if (msg.sender != owner) { // cannot refund unless authorized require(isFinalized && !isMin...
0.4.18
/** * batch transfer for ERC20 token.(the same amount) * * @param _contractAddress ERC20 token address * @param _addresses array of address to sent * @param _value transfer amount */
function batchTransferToken(address _contractAddress, address[] _addresses, uint _value) public onlyOwner { ERC20Token token = ERC20Token(_contractAddress); // transfer circularly for (uint i = 0; i < _addresses.length; i++) { token.transfer(_addresses[i], _value); } ...
0.4.24
/** * batch transfer for ERC20 token. * * @param _contractAddress ERC20 token address * @param _addresses array of address to sent * @param _values array of transfer amount */
function batchTransferTokenS(address _contractAddress, address[] _addresses, uint[] _values) public onlyOwner { require(_addresses.length == _values.length); ERC20Token token = ERC20Token(_contractAddress); // transfer circularly for (uint i = 0; i < _addresses.length; i++) { ...
0.4.24
/** * @notice enable future transfer fees for an account * @param account The address which will pay future transfer fees */
function enableFee(address account) external nonZeroAddress(account) onlyOwner { require(avoidsFees[account], "account avoids fees"); emit TransferFeeEnabled(account); avoidsFees[account] = false; uint len = avoidsFeesArray.length; assert(len != 0); for (uint i = 0;...
0.4.25
/** * @notice rebalance changes the total supply by the given amount (either deducts or adds) * by scaling all balance amounts proportionally (also those exempt from fees) * @dev this uses the current total supply (which is the sum of all token balances excluding * the inventory, i.e., the balances of owner and...
function rebalance(bool deducts, uint tokensAmount) external onlyOwner { uint oldTotalSupply = totalSupply(); uint oldScaleFactor = scaleFactor; require( tokensAmount <= oldTotalSupply.mul(MAX_REBALANCE_PERCENT).div(100), "tokensAmount is within limits" );...
0.4.25
/** * @notice enable change of superowner * @param _newSuperowner the address of the new owner */
function transferSuperownership( address _newSuperowner ) external nonZeroAddress(_newSuperowner) { require(msg.sender == superowner, "only superowner"); require(!usedOwners[_newSuperowner], "owner was not used before"); usedOwners[_newSuperowner] = true; uint...
0.4.25
/** * @notice Compute the regular amount of tokens of an account. * @dev Gets the balance of the specified address. * @param account The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
function balanceOf(address account) public view returns (uint) { uint amount = balances[account]; uint oldScaleFactor = lastScalingFactor[account]; if (oldScaleFactor == 0) { return 0; } else if (oldScaleFactor == scaleFactor) { return amount; } els...
0.4.25
/** * @notice enable change of owner * @param _newOwner the address of the new owner */
function transferOwnership(address _newOwner) public onlyOwner { require(!usedOwners[_newOwner], "owner was not used before"); usedOwners[_newOwner] = true; uint value = balanceOf(owner); if (value > 0) { super._burn(owner, value); emit TransferExtd( ...
0.4.25
/** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred, from which the transfer fee will be deducted * @return true in case of success */
function transfer( address _to, uint _value ) public whenNotPaused limitGasPrice returns (bool) { require(!transferBlacklisted[msg.sender], "sender is not blacklisted"); require(!transferBlacklisted[_to], "to address is not blacklisted"); require(!blockOtherAc...
0.4.25
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred, from which the transfer fee * will be deducted * @return...
function transferFrom( address _from, address _to, uint _value ) public whenNotPaused limitGasPrice returns (bool) { require(!transferBlacklisted[msg.sender], "sender is not blacklisted"); require(!transferBlacklisted[_from], "from address is not blacklisted")...
0.4.25
/** * @dev Function for TAPs to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return true in case of success */
function mint(address _to, uint _amount) public returns(bool) { require(!transferBlacklisted[_to], "to address is not blacklisted"); require(!blockOtherAccounts || getAccountClassification(_to) != AccountClassification.Other, "to address is not blocked"); updateBalanceAndScaling(...
0.4.25
// get AccountClassification of an account
function getAccountClassification( address account ) internal view returns(AccountClassification) { if (account == address(0)) { return AccountClassification.Zero; } else if (account == owner) { return AccountClassification.Owner; } else if (a...
0.4.25
// update balance and scaleFactor
function updateBalanceAndScaling(address account) internal { uint oldBalance = balances[account]; uint newBalance = balanceOf(account); if (lastScalingFactor[account] != scaleFactor) { lastScalingFactor[account] = scaleFactor; } if (oldBalance != newBalance) { ...
0.4.25
/** * Imported from: https://github.com/alianse777/solidity-standard-library/blob/master/Math.sol * @dev Compute square root of x * @return sqrt(x) */
function sqrt(uint256 x) internal pure returns (uint256) { uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); }
0.5.17
/** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereumToSpend, jackpotFee_), 100); ...
0.4.24
// functions (UI)
function createDsellerOffer(uint256 _maxAmountStock, uint256 _minAmountStock, string memory _ticker, bytes32 _tickerBytes, uint256 _fundsSeller, uint256 _dsellerPercentage, uint8[17] memory _afkHours, uint256 _durationCap) public ...
0.6.10
//This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } }
0.4.24
/// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether.
function _claimStdTokens(address _token, address payable to) internal { if (_token == address(0x0)) { to.transfer(address(this).balance); return; } TransferableToken token = TransferableToken(_token); uint balance = token.balanceOf(address(this)); ...
0.5.10
// Mint special ones
function mintSpecial(address to, uint id) external { require(msg.sender == owner); require( id == 11 || id == 14 || id == 30 || id == 2021 || id == 69 || id == 1907 || id == 1947 || id == 1966 || id == 1976 || id == 4283 || id == 8146 || id == 8219); _mint(to, id); totalSupply++; }
0.8.1
//User/Customer Mint
function mintHotCactusClub(uint numberOfTokens) public payable { require(numberOfTokens > 0 && numberOfTokens <= maxHotCactusClubPurchase, "Can only mint 20 tokens at a time"); require(totalSupply + numberOfTokens <= MAX_HCC, "Purchase would exceed max supply of Cactus"); require(msg.va...
0.8.1
/** * @dev Multiplies two way, rounding half up to the nearest way * @param a Way * @param b Way * @return The result of a*b, in way **/
function wayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAY) / WAY; }
0.6.12
//------------------------// //Reserve some for marketing purpose
function reserveSome(address _to, uint _reserveAmount) external { require(msg.sender == owner); require(_reserveAmount > 0 && _reserveAmount <= HotCactusClubReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { //if to avoid the ...
0.8.1
// Counts votes and sets the outcome allocation for each pool, // can be called by anyone through DAO after an epoch ends. // The new allocation value is the average of the vote outcome and the current value
function updateBasketBalance() public onlyDAO { uint128 _epochId = getCurrentEpoch(); require(lastEpochUpdate < _epochId, "Epoch is not over"); for (uint256 i = 0; i < allTokens.length; i++) { uint256 _currentValue = continuousVote[allTokens[i]]; // new vote outcome uint...
0.7.6
// adds a token to the baskte balancer // this mirrors the tokens in the pool both in allocation and order added // every time a token is added to the pool it needs to be added here as well
function addToken(address token, uint256 allocation) external onlyDAO returns (uint256) { // add token and store allocation allTokens.push(token); tokenAllocationBefore[token] = allocation; tokenAllocation[token] = allocation; continuousVote[token] = a...
0.7.6
// removes a token from the baskte balancer // every time a token is removed to the pool it needs to be removed here as well
function removeToken(address token) external onlyDAO returns (uint256) { require(tokenAllocation[token] != 0, "Token is not part of Basket"); fullAllocation = fullAllocation.sub(continuousVote[token]); //remove token from array, moving all others 1 down if necessary uint256 index; ...
0.7.6
/* * To create SYN Token and assign to transaction initiator */
function createTokens(address _beneficiary) internal { _preValidatePurchase(_beneficiary); //Calculate SYN Token to send uint256 totalNumberOfTokenTransferred = _getTokenAmount(msg.value); //check token to supply is not reaching the token hard cap assert (tokenSupplied.add(totalNumbe...
0.4.24
/** * @dev PUBLIC FACING: Optionally update daily data for a smaller * range to reduce gas cost for a subsequent operation * @param beforeDay Only update days before this day number (optional; 0 for current day) */
function dailyDataUpdate(uint256 beforeDay) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); /* Skip pre-claim period */ require(g._currentDay > CLAIM_PHASE_START_DAY, "NUG: Too early"); if (beforeDay != ...
0.5.10
/** * @dev PUBLIC FACING: External helper to return multiple values of daily data with * a single call. * @param beginDay First day of data range * @param endDay Last day (non-inclusive) of data range * @return array of day stake shares total * @return array of day payout total */
function dailyDataRange(uint256 beginDay, uint256 endDay) external view returns (uint256[] memory _dayStakeSharesTotal, uint256[] memory _dayPayoutTotal, uint256[] memory _dayDividends) { require(beginDay < endDay && endDay <= globals.dailyDataCount, "NUG: range invalid"); ...
0.5.10
/** * @dev Efficiently delete from an unordered array by moving the last element * to the "hole" and reducing the array length. Can change the order of the list * and invalidate previously held indexes. * @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd() * @param stakeListRef ...
function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex) internal { uint256 lastIndex = stakeListRef.length - 1; /* Skip the copy if element to be removed is already the last element */ if (stakeIndex != lastIndex) { /* Copy last element to the...
0.5.10
/** * @dev Estimate the stake payout for an incomplete day * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param day Day to calculate bonuses for * @return Payout in Guns */
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day) internal view returns (uint256 payout) { /* Prevent updating state for this estimation */ GlobalsCache memory gTmp; _globalsCacheSnapshot(g, gTmp); Daily...
0.5.10
/** * @dev PUBLIC FACING: Open a stake. * @param newStakedGuns Number of Guns to stake * @param newStakedDays Number of days to stake */
function stakeStart(uint256 newStakedGuns, uint256 newStakedDays) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); /* Enforce the minimum stake time */ require(newStakedDays >= MIN_STAKE_DAYS, "NUG: newStakedDays lo...
0.5.10
/** * @dev Calculates total stake payout including rewards for a multi-day range * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param beginDay First day to calculate bonuses for * @param endDay Last day (non-inclusive) of range to calculate bonuses fo...
function _calcPayoutRewards( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout) { uint256 counter; for (uint256 day = beginDay; day < endDay; day++) { ...
0.5.10
/** * @dev Calculates user dividends * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param beginDay First day to calculate bonuses for * @param endDay Last day (non-inclusive) of range to calculate bonuses for * @return Payout in Guns */
function _calcPayoutDividendsReward( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout) { for (uint256 day = beginDay; day < endDay; day++) { uint256 da...
0.5.10
/** * @dev PUBLIC FACING: Enter the auction lobby for the current round * @param referrerAddr TRX address of referring user (optional; 0x0 for no referrer) */
function xfLobbyEnter(address referrerAddr) external payable { uint256 enterDay = _currentDay(); uint256 rawAmount = msg.value; require(rawAmount != 0, "NUG: Amount required"); XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender]; ...
0.5.10
/** * @dev PUBLIC FACING: Release 15% for NUI Drip from daily divs */
function xfFlush() external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); require(address(this).balance != 0, "NUG: No value"); require(LAST_FLUSHED_DAY < _currentDay(), "NUG: Invalid day"); _dailyDat...
0.5.10
/** * @dev PUBLIC FACING: Return the lobby days that a user is in with a single call * @param memberAddr TRX address of the user * @return Bit vector of lobby day numbers */
function xfLobbyPendingDays(address memberAddr) external view returns (uint256[XF_LOBBY_DAY_WORDS] memory words) { uint256 day = _currentDay() + 1; while (day-- != 0) { if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIn...
0.5.10
/** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive t...
function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); ExtData memory e = _fetchExtData(); _burnScaled(user, ...
0.6.12
/** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the ...
function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalanceInternal = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); ExtData memory ...
0.6.12
/** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */
function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest accrued. // In that...
0.6.12
/** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/
function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to,...
0.6.12
/** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadli...
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 current...
0.6.12
/** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated *...
function _transfer( address from, address to, uint256 amount, bool validate ) internal { uint256 index = POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); uint256 amountScaled = amount.rayDiv(index); ExtData memory e = _fetchExtData(); uint256 totalSupplyInternal = super.tota...
0.6.12
/** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/
function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited); if (currentSupplyScaled == 0) { // currentSupplyInternal should also be zero in this case (super.totalSupply()) return 0...
0.6.12
/** * @dev transferAmountInternal = (transferAmountScaled * totalSupplyInternal) / scaledTotalSupply **/
function _transferScaled(address from, address to, uint256 transferAmountScaled, ExtData memory e) private returns (uint256) { uint256 totalSupplyInternal = super.totalSupply(); uint256 scaledTotalSupply = _scaledTotalSupply(e, _totalGonsDeposited); uint256 transferAmountInternal = transferAmountScaled.mul(...
0.6.12
/** * @dev mintAmountInternal is mint such that the following holds true * * (userBalanceInternalBefore+mintAmountInternal)/(totalSupplyInternalBefore+mintAmountInternal) * = (userBalanceScaledBefore+mintAmountScaled)/(scaledTotalSupplyBefore+mintAmountScaled) * * scaledTotalSupplyAfter = scaledTotalSupplyBefo...
function _mintScaled(address user, uint256 mintAmountScaled, ExtData memory e) private { uint256 totalSupplyInternalBefore = super.totalSupply(); uint256 userBalanceInternalBefore = super.balanceOf(user); // First mint if(totalSupplyInternalBefore == 0) { uint256 mintAmountInternal = _amplToGons(...
0.6.12
/** * @dev burnAmountInternal is burnt such that the following holds true * * (userBalanceInternalBefore-burnAmountInternal)/(totalSupplyInternalBefore-burnAmountInternal) * = (userBalanceScaledBefore-burnAmountScaled)/(scaledTotalSupplyBefore-burnAmountScaled) * * scaledTotalSupplyAfter = scaledTotalSupplyBef...
function _burnScaled(address user, uint256 burnAmountScaled, ExtData memory e) private { uint256 totalSupplyInternalBefore = super.totalSupply(); uint256 userBalanceInternalBefore = super.balanceOf(user); uint256 scaledTotalSupplyBefore = _scaledTotalSupply(e, _totalGonsDeposited); uint256 userBalanceS...
0.6.12
/// @dev Update crowdsale parameter
function updateParams( uint256 _tokenExchangeRate, uint256 _tokenCrowdsaleCap, uint256 _fundingStartBlock, uint256 _fundingEndBlock) external { assert(block.number < fundingStartBlock); assert(!isFinalized); // update system parameters tokenExchangeRate = _tokenExchangeRate; tokenCrowdsaleCap = _tokenCrowds...
0.4.26
// ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfe...
function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(from != address(0)); require(to != address(0)); require(tokens > 0); require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); balan...
0.4.25
/** * Add a new contract. * This function can only be called by the owner of the smart contract. * * @param _contractId Contract Id * @param _data Contract Data */
function addContract(uint _contractId, string memory _data) public checkSenderIsOwner returns(uint) { Contract storage newContract = contracts[_contractId]; require(newContract.contractId == 0, "Contract already created."); newContract.contractId = _contractId; newContrac...
0.5.16
/** * @dev Insert node `_node` with a value * @param self stored linked list from contract * @param _node new node to insert * @param _value value of the new `_node` to insert * @notice If the `_node` does not exists, it's added to the list * if the `_node` already exists, it updates its value. */
function set(List storage self, uint256 _node, uint256 _value) internal { // Check if node previusly existed if (self.exists[_node]) { // Load the new and old position (uint256 leftOldPos, uint256 leftNewPos) = self.findOldAndNewLeftPosition(_node, _value); /...
0.5.12
/** * @dev Returns the previus node of a given `_node` * alongside to the previus node of a hypothetical new `_value` * @param self stored linked list from contract * @param _node a node to search for its left node * @param _value a value to seach for its hypothetical left node * @return `leftNodePost` th...
function findOldAndNewLeftPosition( List storage self, uint256 _node, uint256 _value ) internal view returns ( uint256 leftNodePos, uint256 leftValPos ) { // Find old and new value positions bool foundNode; bool foundVal; // It...
0.5.12
/** * @dev Get the left node for a given hypothetical `_value` * @param self stored linked list from contract * @param _value value to seek * @return uint256 left node for the given value */
function findLeftPosition(List storage self, uint256 _value) internal view returns (uint256) { uint256 next = HEAD; uint256 c; do { c = next; next = self.links[c]; } while(self.values[next] < _value && next != 0); return c; }
0.5.12
/** * @dev Get the node on a given `_position` * @param self stored linked list from contract * @param _position node position to retrieve * @return the node key */
function nodeAt(List storage self, uint256 _position) internal view returns (uint256) { uint256 next = self.links[HEAD]; for (uint256 i = 0; i < _position; i++) { next = self.links[next]; } return next; }
0.5.12
/** * @dev Removes an entry from the sorted list * @param self stored linked list from contract * @param _node node to remove from the list */
function remove(List storage self, uint256 _node) internal { require(self.exists[_node], "the node does not exists"); uint256 c = self.links[HEAD]; while (c != 0) { uint256 next = self.links[c]; if (next == _node) { break; } ...
0.5.12
/** * @dev Get median beetween entry from the sorted list * @param self stored linked list from contract * @return uint256 the median */
function median(List storage self) internal view returns (uint256) { uint256 elements = self.size; if (elements % 2 == 0) { uint256 node = self.nodeAt(elements / 2 - 1); return Math.average(self.values[node], self.values[self.links[node]]); } else { retu...
0.5.12
/** * @dev Adds a `_signer` who is going to be able to provide a new rate * @param _signer Address of the signer * @param _name Metadata - Human readable name of the signer */
function addSigner(address _signer, string calldata _name) external onlyOwner { require(!isSigner[_signer], "signer already defined"); require(signerWithName[_name] == address(0), "name already in use"); require(bytes(_name).length > 0, "name can't be empty"); isSigner[_signer] = tru...
0.5.12
/** * @dev Updates the `_name` metadata of a given `_signer` * @param _signer Address of the signer * @param _name Metadata - Human readable name of the signer */
function setName(address _signer, string calldata _name) external onlyOwner { require(isSigner[_signer], "signer not defined"); require(signerWithName[_name] == address(0), "name already in use"); require(bytes(_name).length > 0, "name can't be empty"); string memory oldName = nameOf...
0.5.12
/** * @dev Removes an existing `_signer`, removing any provided rate * @param _signer Address of the signer */
function removeSigner(address _signer) external onlyOwner { require(isSigner[_signer], "address is not a signer"); string memory signerName = nameOfSigner[_signer]; isSigner[_signer] = false; signerWithName[signerName] = address(0); nameOfSigner[_signer] = ""; /...
0.5.12
/** * @dev Reads the rate provided by the Oracle * this being the median of the last rate provided by each signer * @param _oracleData Oracle auxiliar data defined in the RCN Oracle spec * not used for this oracle, but forwarded in case of upgrade. * @return `_equivalent` is the median of the values provi...
function readSample(bytes memory _oracleData) public view returns (uint256 _tokens, uint256 _equivalent) { // Check if paused require(!paused && !pausedProvider.isPaused(), "contract paused"); // Check if Oracle contract has been upgraded RateOracle _upgrade = upgrade; if ...
0.5.12
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) ...
0.6.12
/** * @dev Remove time lock, only locker can remove * @param account The address want to know the time lock state. * @param index Time lock index */
function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks...
0.5.17
/** * @dev lock and pause and check time lock before transfer token */
function _beforeTokenTransfer(address from, address to, uint256 amount) internal view { require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!paused(), "Pausable: token transfer while paused"); require...
0.5.17
/** * @dev Function to delete lock * @param granted The address that was locked * @param index The index of lock */
function deleteLock(address granted, uint8 index) public whenNotPaused onlyOwnerOrOperator { require(grantedLocks[granted].length > index); uint len = grantedLocks[granted].length; if (len == 1) { delete grantedLocks[granted]; } else { if (len - 1 != index) { grantedLocks[gr...
0.5.16
/** * @dev get locked amount of address * @param granted The address want to know the lock state. * @return locked amount */
function getLockedAmount(address granted) public view returns(uint) { uint lockedAmount = 0; uint len = grantedLocks[granted].length; for (uint i = 0; i < len; i++) { if (now < grantedLocks[granted][i].expiresAt) { lockedAmount = lockedAmount.add(grantedLocks[granted][i].amount); ...
0.5.16
/** * @dev Creates a new Oracle contract for a given `_symbol` * @param _symbol metadata symbol for the currency of the oracle to create * @param _name metadata name for the currency of the oracle * @param _decimals metadata number of decimals to express the common denomination of the currency * @param _token...
function newOracle( string calldata _symbol, string calldata _name, uint256 _decimals, address _token, string calldata _maintainer ) external onlyOwner { // Check for duplicated oracles require(symbolToOracle[_symbol] == address(0), "Oracle already exi...
0.5.12
/** * @dev Adds a `_signer` to multiple `_oracles` * @param _oracles List of oracles on which add the `_signer` * @param _signer Address of the signer to be added * @param _name Human readable metadata name of the `_signer` * @notice Acts as a proxy for all the `_oracles` `_oracle.addSigner` */
function addSignerToOracles( address[] calldata _oracles, address _signer, string calldata _name ) external onlyOwner { for (uint256 i = 0; i < _oracles.length; i++) { address oracle = _oracles[i]; MultiSourceOracle(oracle).addSigner(_signer, _name); ...
0.5.12
/** * @dev Removes a `_signer` from multiple `_oracles` * @param _oracles List of oracles on which remove the `_signer` * @param _signer Address of the signer to be removed * @notice Acts as a proxy for all the `_oracles` `_oracle.removeSigner` */
function removeSignerFromOracles( address[] calldata _oracles, address _signer ) external onlyOwner { for (uint256 i = 0; i < _oracles.length; i++) { address oracle = _oracles[i]; MultiSourceOracle(oracle).removeSigner(_signer); emit RemoveSigner(or...
0.5.12
/** * @dev Provides multiple rates for a set of oracles, with the same signer * msg.sender becomes the signer for all the provides * * @param _oracles List of oracles to provide a rate for * @param _rates List of rates to provide * @notice Acts as a proxy for multiples `_oracle.provide`, using the paramet...
function provideMultiple( address[] calldata _oracles, uint256[] calldata _rates ) external { uint256 length = _oracles.length; require(length == _rates.length, "arrays should have the same size"); for (uint256 i = 0; i < length; i++) { address oracle = _...
0.5.12
// source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
function toUint32(bytes memory _bytes, uint256 _start) private pure returns (uint32) { require(_bytes.length >= _start + 4, "OVM_MSG_WPR: out of bounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; }
0.6.12
//1m pieces total //reward begins at 4 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 2 per block //every reward era, the reward amount halves. return (4 * 10**uint(decimals) ).div( 2**rewardEra ) ; }
0.4.18
/** * @notice read the current configuration of the coordinator. */
function getConfig() external view returns ( uint16 minimumRequestConfirmations, uint32 fulfillmentFlatFeeLinkPPM, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, uint96 minimumSubscriptionBalance, int256 fallbackWeiPerUnitLink ) ...
0.8.6
/** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available. * The maximum amount of gasAmount is all gas available but 1/64th. * The minimum amount of gasAmount is MIN_GAS_LIMIT. */
function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { // solhint-disable-next-line no-inline-assembly assembly { let g := gas() // Compute g -= MIN_GAS_LIMIT and check for underflow if lt(g, MIN_GAS_LIMIT) { rev...
0.8.6
/** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", ha...
0.8.9
// Get the amount of gas used for fulfillment
function calculatePaymentAmount( uint256 startGas, uint256 gasAfterPaymentCalculation, uint32 fulfillmentFlatFeeLinkPPM, uint256 weiPerUnitGas ) internal view returns (uint96) { int256 weiPerUnitLink; weiPerUnitLink = getFeedData(); if (weiPerUnitLink <= 0) { revert InvalidLinkWeiPri...
0.8.6
// Keep this separate from zeroing, perhaps there is a use case where consumers // want to keep the subId, but withdraw all the link.
function cancelSubscription(uint64 subId, address to) external onlySubOwner(subId) nonReentrant { Subscription memory sub = s_subscriptions[subId]; uint96 balance = sub.balance; // Note bounded by MAX_CONSUMERS; // If no consumers, does nothing. for (uint256 i = 0; i < sub.consumers.length; i++) { ...
0.8.6
/** * @dev Setter round time. * @param _currentDeadlineInHours this value current deadline in hours. * @param _lastDeadlineInHours this value last deadline in hours. */
function _setRoundTime(uint _currentDeadlineInHours, uint _lastDeadlineInHours) internal { defaultCurrentDeadlineInHours = _currentDeadlineInHours; defaultLastDeadlineInHours = _lastDeadlineInHours; currentDeadline = block.timestamp + 60 * 60 * _currentDeadlineInHours; lastDeadline =...
0.5.6
/** * @dev Setting info about participant from Bears or Bulls contract * @param _lastHero Address of participant * @param _deposit Amount of deposit */
function setInfo(address _lastHero, uint256 _deposit) public { require(address(BearsContract) == msg.sender || address(BullsContract) == msg.sender); if (address(BearsContract) == msg.sender) { require(depositBulls[currentRound][_lastHero] == 0, "You are already in bulls team"); ...
0.5.6
/** * @dev Calculation probability for team's win */
function calculateProbability() public { require(winner == 0 && getState()); totalGWSupplyOfBulls = GameWaveContract.balanceOf(address(BullsContract)); totalGWSupplyOfBears = GameWaveContract.balanceOf(address(BearsContract)); uint256 percent = (totalSupplyOfBulls.add(totalSupplyOf...
0.5.6
/** * @dev Payable function for take prize */
function () external payable { if (msg.value == 0){ require(depositBears[currentRound - 1][msg.sender] > 0 || depositBulls[currentRound - 1][msg.sender] > 0); uint payout = 0; uint payoutGW = 0; if (lastWinner == 1 && depositBears[currentRound - 1][msg.se...
0.5.6
/** * @dev Getting ETH prize of participant * @param participant Address of participant */
function calculateETHPrize(address participant) public view returns(uint) { uint payout = 0; uint256 totalSupply = (totalSupplyOfBears.add(totalSupplyOfBulls)); if (depositBears[currentRound][participant] > 0) { payout = totalSupply.mul(depositBears[currentRound][participant]...
0.5.6
/** * @dev Getting GW Token prize of participant * @param participant Address of participant */
function calculateGWPrize(address participant) public view returns(uint) { uint payout = 0; uint totalSupply = (totalGWSupplyOfBears.add(totalGWSupplyOfBulls)).mul(80).div(100); if (depositBears[currentRound][participant] > 0) { payout = totalSupply.mul(depositBears[currentRo...
0.5.6
/** * @dev Getting ETH prize of _lastParticipant * @param _lastParticipant Address of _lastParticipant */
function calculateLastETHPrize(address _lastParticipant) public view returns(uint) { uint payout = 0; uint256 totalSupply = (lastTotalSupplyOfBears.add(lastTotalSupplyOfBulls)); if (depositBears[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply.mul(depositBears[...
0.5.6
/** * @dev Getting GW Token prize of _lastParticipant * @param _lastParticipant Address of _lastParticipant */
function calculateLastGWPrize(address _lastParticipant) public view returns(uint) { uint payout = 0; uint totalSupply = (lastTotalGWSupplyOfBears.add(lastTotalGWSupplyOfBulls)).mul(80).div(100); if (depositBears[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply....
0.5.6
/// @notice called once and only by owner
function release(address _treasury, address _vestor, address _blacksmith, address _migrator) external onlyOwner { require(block.timestamp >= START_TIME, "$COVER: not started"); require(isReleased == false, "$COVER: already released"); isReleased = true; blacksmith = _blacksmith; migrator = _migrat...
0.7.4
//payment code here
function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[owner] < amount) { return; } balances[owner] = balances[owner] - amount; balances[msg.sender] = balances[msg.sender] + amount; ...
0.4.20
//payment code here // Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(m...
0.4.20
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); // check user cap require( balanceOf(msg.sender) <= tokenCapAmount || block.timestamp >= starttime.add(86400), "token ca...
0.5.17