comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * A Scribe is a contract that is allowed to write Lore *if* the transaction * originated from the token owner. For example, The Great Burning may write * the death of a Wizard and the inception of their Soul */
function addLoreWithScribe( address tokenContract, uint256 tokenId, uint256 parentLoreId, bool nsfw, string memory loreMetadataURI ) public onlyAllowedTokenContract(tokenContract) { require(scribeAllowlist[_msgSender()], 'sender is not a Scribe'); address tokenOwner = IERC721(tokenContract).ownerOf(tokenId); require( tokenOwner == tx.origin, // ! - note that msg.sender must be a Scribe for this to work 'Owner: tx.origin is not the token owner' ); tokenLore[tokenContract][tokenId].push( // we credit this lore to the Scribe, not the token owner Lore(_msgSender(), parentLoreId, nsfw, false, loreMetadataURI) ); emit LoreAdded( tokenContract, tokenId, tokenLore[tokenContract][tokenId].length - 1 ); }
0.8.0
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
function finishMinting() onlyOwner canMint public returns (bool) { require(foundationAddress != address(0) && teamAddress != address(0) && bountyAddress != address(0)); require(SHARE_PURCHASERS + SHARE_FOUNDATION + SHARE_TEAM + SHARE_BOUNTY == 1000); require(totalSupply_ != 0); // before calling this method totalSupply includes only purchased tokens uint256 onePerThousand = totalSupply_ / SHARE_PURCHASERS; //ignore (totalSupply mod 617) ~= 616e-8, uint256 foundationTokens = onePerThousand * SHARE_FOUNDATION; uint256 teamTokens = onePerThousand * SHARE_TEAM; uint256 bountyTokens = onePerThousand * SHARE_BOUNTY; mint(foundationAddress, foundationTokens); mint(teamAddress, teamTokens); mint(bountyAddress, bountyTokens); mintingFinished = true; emit MintFinished(); return true; }
0.4.24
/** * @dev Returns the data about a token. */
function getDataForTokenId(uint256 _tokenId) public view returns ( uint, string, uint, uint, address, address, uint ) { metaData storage meta = tokenToMetaData[_tokenId]; return ( _tokenId, meta.seed, meta.parent1, meta.parent2, ownerOf(_tokenId), getApproved(_tokenId), meta.remixCount ); }
0.4.25
// Converts uint to a string
function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); }
0.4.25
// Vesting Issue Function -----
function issue_Vesting_RND(address _to, uint _time) onlyOwner_creator public { require(saleTime == false); require(vestingReleaseRound_RND >= _time); uint time = now; require( ( ( endSaleTime + (_time * vestingReleaseTime_RND) ) < time ) && ( vestingRelease_RND[_time] > 0 ) ); uint tokens = vestingRelease_RND[_time]; require(maxSupply_RND >= issueToken_RND.add(tokens)); balances[_to] = balances[_to].add(tokens); vestingRelease_RND[_time] = 0; issueToken_Total = issueToken_Total.add(tokens); issueToken_RND = issueToken_RND.add(tokens); emit Issue_RND(_to, tokens); }
0.5.0
// accept ether subscription payments // only one time per address // msg.value = ticketPriceWei + expected future price format in wei // Example // 1. ticketPrice is 0.01 Ether // 2. Your future price prediction is 9588.25 // 3. You send 0.1 + 0.0000000000958825 // 4. The contract registers your prediction of 958825 // 5. The contract pays you back get back 0.0000000000958825 Ether
function() payable external { require(status == 0, 'closed'); require(msg.value > ticketPriceWei && msg.value < ticketPriceWei + 10000000, 'invalid ticket price'); require(futures[msg.sender] == 0, 'already in'); uint future = msg.value - ticketPriceWei; futures[msg.sender] = future; subscribers.push(msg.sender); msg.sender.transfer(future); emit PriceBet(msg.sender, future, now); }
0.5.17
// close subscription doors
function closeSubscriptions() public { require(msg.sender == factory, 'only factory'); require(status == 0, 'wrong transition'); status = 1; // in case of one+ subscribers // lunch the next solution timer if(subscribers.length == 0) { status = 2; distributeRewards(); } emit RoundClose(); }
0.5.17
// if the execution did not happen after 24 hours // the beneficiary can withdraw total amount same share // equally with the subscribers
function rollback() public { // should be not distributed require(status < 3, 'already distributed'); // only the beneficiary can do it require(msg.sender == beneficiary, 'only beneficiary'); // at least 24H passed without execution uint unlockTime = created.add(executionDelay).add(24*3600); require(now >= unlockTime, 'still early'); // the balance is normally distributed uint perShareWei = address(this).balance.div(subscribers.length); for(uint i = 0; i < subscribers.length; i++) { subscribers[i].transfer(perShareWei); } }
0.5.17
// set the solution and alarm the distribution // pay the factory and tell about the gas Limit
function executeResult(uint solution) public returns (uint gasLimit) { require(msg.sender == factory, 'only factory'); require(status == 1, 'wrong transition'); status = 2; winSolution = solution; emit RoundExecuted(winSolution); // default provable 20 GWei per Gas and 200 000 GAS uint PROVABLE_GAS_PRICE = 20e9 wei; // estimation for the factory uint estGas = subscribers.length*7000 + 300000; uint estWei = estGas.mul(PROVABLE_GAS_PRICE); // check up the available cost if(address(this).balance >= estWei) { // defaulting extras back to factory factory.transfer((estGas.sub(200000)).mul(PROVABLE_GAS_PRICE)); return estGas; } else { // The factory covers DEFAULT PROVABLE GAS COST: 20GWEI * 200 000 GAS return 200000; } }
0.5.17
// Blacklist Lock & Unlock functions. // Unlocking the blacklist requires a minimum of 3 days notice.
function unlockBlacklist(bool _limitedBlacklist, uint _daysUntilUnlock) external onlyOwner { require(_daysUntilUnlock > 2, "Unlocking blacklist functionality requires a minimum of 3 days notice."); blacklistUnlockTimestamp = now + (_daysUntilUnlock * 60 * 60 * 24); limitedBlacklist = _limitedBlacklist; blacklistPossible = true; emit BlacklistUnlockCalled(blacklistUnlockTimestamp, _daysUntilUnlock, limitedBlacklist); }
0.6.12
//lock LOCK tokens to contract
function LockTokens(uint amt) public { require(amt > 0, "zero input"); require(tokenBalance() >= amt, "Error: insufficient balance");//ensure user has enough funds tokenLockedBalances[msg.sender] = tokenLockedBalances[msg.sender].add(amt); totalLocked = totalLocked.add(amt); _transfer(msg.sender, address(this), amt);//make transfer emit TokenLock(msg.sender, amt); }
0.6.4
//unlock LOCK tokens from contract
function UnlockTokens(uint amt) public { require(amt > 0, "zero input"); require(tokenLockedBalances[msg.sender] >= amt,"Error: unsufficient frozen balance");//ensure user has enough locked funds tokenLockedBalances[msg.sender] = tokenLockedBalances[msg.sender].sub(amt);//update balances totalLocked = totalLocked.sub(amt); _transfer(address(this), msg.sender, amt);//make transfer emit TokenUnlock(msg.sender, amt); }
0.6.4
//stakes hex - transfers HEX from user to contract - approval needed
function stakeHex(uint hearts, uint dayLength, address payable ref) internal returns(bool) { //send require(hexInterface.transferFrom(msg.sender, address(this), hearts), "Transfer failed");//send hex from user to contract //user info updateUserData(hearts); //stake HEX hexInterface.stakeStart(hearts, dayLength); //get the most recent stakeIndex uint hexStakeIndex = hexInterface.stakeCount(address(this)).sub(1); //update stake info updateStakeData(hearts, dayLength, ref, hexStakeIndex); //mint bonus LOCK tokens relative to HEX amount and stake length (stake for more than 20 days and get larger bonus) if(dayLength < 10){ dayLength = 10; } require(mintLock(hearts * (dayLength / 100)), "Error: could not mint tokens"); return true; }
0.6.4
//updates user data
function updateUserData(uint hearts) internal { UserInfo storage user = users[msg.sender]; lifetimeHeartsStaked += hearts; if(user.totalHeartsStaked == 0){ userCount++; } user.totalHeartsStaked = user.totalHeartsStaked.add(hearts);//total amount of hearts staked by this user after fees user.userAddress = msg.sender; }
0.6.4
//updates stake data
function updateStakeData(uint hearts, uint dayLength, address payable ref, uint index) internal { uint _stakeId = _next_stake_id();//new stake id userStakeIds[msg.sender].push(_stakeId);//update userStakeIds StakeInfo memory stake; stake.heartValue = hearts;//amount of hearts staked stake.dayLength = dayLength;//length of days staked stake.userAddress = msg.sender;//staker stake.refferer = ref;//referrer stake.hexStakeIndex = index;//hex contract stakeIndex SStore memory _stake = getStakeByIndex(address(this), stake.hexStakeIndex); //get stake from address and stakeindex stake.hexStakeId = _stake.stakeId;//hex contract stake id stake.stakeId = _stakeId;//hexlock contract stake id stake.stakeStartTimestamp = now;//timestamp stake started stake.isStaking = true;//stake is now staking stakes[_stakeId] = stake;//update data emit StakeStarted( hearts, dayLength, stake.hexStakeId ); }
0.6.4
//general stake info
function getStakeInfo(uint stakeId) public view returns( uint heartValue, uint stakeDayLength, uint hexStakeId, uint hexStakeIndex, address payable userAddress, address payable refferer, uint stakeStartTimestamp ) { return(stakes[stakeId].heartValue, stakes[stakeId].dayLength, stakes[stakeId].hexStakeId, stakes[stakeId].hexStakeIndex, stakes[stakeId].userAddress, stakes[stakeId].refferer, stakes[stakeId].stakeStartTimestamp); }
0.6.4
/** * @dev Add wallet that received pre-minted tokens to the list in the Governance contract. * The contract owner should be GovernanceProxy contract. * This Escrow contract address should be added to Governance contract (setEscrowContract). * @param wallet The address of wallet. */
function _addPremintedWallet(address wallet, uint256 groupId) internal { require(groupId < groups.length, "Wrong group"); IGovernance(governanceContract).addPremintedWallet(wallet); inGroup[wallet] = groupId + 1; // groupId + 1 (0 - mean that wallet not added) groups[groupId].wallets.add(wallet); // add to the group }
0.6.12
/** * @dev whitelist buy */
function whitelistBuy( uint256 qty, uint256 tokenId, bytes32[] calldata proof ) external payable whenNotPaused { require(qty <= 2, "max 2"); require(tokenPrice * qty == msg.value, "exact amount needed"); require(usedAddresses[msg.sender] + qty <= 2, "max per wallet reached"); require(block.timestamp > whitelistStartTime, "not live"); require(isTokenValid(msg.sender, tokenId, proof), "invalid merkle proof"); usedAddresses[msg.sender] += qty; _safeMint(msg.sender, qty); }
0.8.11
/** * @dev everyone can mint freely */
function buy(uint256 qty) external payable whenNotPaused { require(tokenPrice * qty == msg.value, "exact amount needed"); require(qty < 6, "max 5 at once"); require(totalSupply() + qty <= maxSupply, "out of stock"); require(block.timestamp > publicSaleStartTime, "not live"); _safeMint(msg.sender, qty); }
0.8.11
/** * @dev verification function for merkle root */
function isTokenValid( address _to, uint256 _tokenId, bytes32[] memory _proof ) public view returns (bool) { // construct Merkle tree leaf from the inputs supplied bytes32 leaf = keccak256(abi.encodePacked(_to, _tokenId)); // verify the proof supplied, and return the verification result return _proof.verify(root, leaf); }
0.8.11
//---------------------------------- //----------- other code ----------- //----------------------------------
function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
0.8.11
// earnings withdrawal
function withdraw() public payable onlyOwner { uint256 _total_owner = address(this).balance; (bool all1, ) = payable(0xed6f9E7d3A94141E28cA5D1905d2EA9F085D00FA).call{ value: (_total_owner * 1) / 3 }(""); //l require(all1); (bool all2, ) = payable(0x318cbB40Fdaf1A2Ab545B957518cb95D7c18ED32).call{ value: (_total_owner * 1) / 3 }(""); //sc require(all2); (bool all3, ) = payable(0x831C6bF9562791480802055Eb51311f6EedCA783).call{ value: (_total_owner * 1) / 3 }(""); //sp require(all3); }
0.8.11
/** * @dev internal function of `trade`. * It verifies user signature, transfer tokens from user and store tx hash to prevent replay attack. */
function _prepare( bool fromEth, IWETH weth, address _makerAddr, address _takerAssetAddr, address _makerAssetAddr, uint256 _takerAssetAmount, uint256 _makerAssetAmount, address _userAddr, address _receiverAddr, uint256 _salt, uint256 _deadline, bytes memory _sig ) internal returns (bytes32 transactionHash) { // Verify user signature // TRADE_WITH_PERMIT_TYPEHASH = keccak256("tradeWithPermit(address makerAddr,address takerAssetAddr,address makerAssetAddr,uint256 takerAssetAmount,uint256 makerAssetAmount,address userAddr,address receiverAddr,uint256 salt,uint256 deadline)"); transactionHash = keccak256( abi.encode( TRADE_WITH_PERMIT_TYPEHASH, _makerAddr, _takerAssetAddr, _makerAssetAddr, _takerAssetAmount, _makerAssetAmount, _userAddr, _receiverAddr, _salt, _deadline ) ); bytes32 EIP712SignDigest = keccak256( abi.encodePacked( EIP191_HEADER, EIP712_DOMAIN_SEPARATOR, transactionHash ) ); require(isValidSignature(_userAddr, EIP712SignDigest, bytes(""), _sig), "AMMWrapper: invalid user signature"); // Transfer asset from user and deposit to weth if needed if (fromEth) { require(msg.value > 0, "AMMWrapper: msg.value is zero"); require(_takerAssetAmount == msg.value, "AMMWrapper: msg.value doesn't match"); // Deposit ETH to weth weth.deposit{value: msg.value}(); } else { spender.spendFromUser(_userAddr, _takerAssetAddr, _takerAssetAmount); } // Validate that the transaction is not seen before require(! permStorage.isTransactionSeen(transactionHash), "AMMWrapper: transaction seen before"); // Set transaction as seen permStorage.setTransactionSeen(transactionHash); }
0.6.12
/** * @dev internal function of `trade`. * It executes the swap on chosen AMM. */
function _swap( bool makerIsUniV2, address _makerAddr, address _takerAssetAddr, address _makerAssetAddr, uint256 _takerAssetAmount, uint256 _makerAssetAmount, uint256 _deadline, uint256 _subsidyFactor ) internal returns (string memory source, uint256 receivedAmount) { // Approve IERC20(_takerAssetAddr).safeApprove(_makerAddr, _takerAssetAmount); // Swap // minAmount = makerAssetAmount * (10000 - subsidyFactor) / 10000 uint256 minAmount = _makerAssetAmount.mul((BPS_MAX.sub(_subsidyFactor))).div(BPS_MAX); if (makerIsUniV2) { source = "Uniswap V2"; receivedAmount = _tradeUniswapV2TokenToToken(_takerAssetAddr, _makerAssetAddr, _takerAssetAmount, minAmount, _deadline); } else { int128 fromTokenCurveIndex = permStorage.getCurveTokenIndex(_makerAddr, _takerAssetAddr); int128 toTokenCurveIndex = permStorage.getCurveTokenIndex(_makerAddr, _makerAssetAddr); if (! (fromTokenCurveIndex == 0 && toTokenCurveIndex == 0)) { source = "Curve"; uint256 balanceBeforeTrade = IERC20(_makerAssetAddr).balanceOf(address(this)); _tradeCurveTokenToToken(_makerAddr, fromTokenCurveIndex, toTokenCurveIndex, _takerAssetAmount, minAmount); uint256 balanceAfterTrade = IERC20(_makerAssetAddr).balanceOf(address(this)); receivedAmount = balanceAfterTrade.sub(balanceBeforeTrade); } else { revert("AMMWrapper: Unsupported makerAddr"); } } // Close allowance IERC20(_takerAssetAddr).safeApprove(_makerAddr, 0); }
0.6.12
/** * @dev gets total ether claimed for characters in account. */
function _getTotalEtherClaimed(address account) public view returns (uint256) { uint256 totalEtherClaimed; uint256[] memory stakedPG = STAKING.getStakerTokens(account, address(PG)); uint256[] memory stakedAP = STAKING.getStakerTokens(account, address(AP)); for (uint256 i; i < PG.balanceOf(account); i++) { totalEtherClaimed += _etherClaimedByPG[PG.tokenOfOwnerByIndex(account, i)]; } for (uint256 i; i < stakedPG.length; i++) { totalEtherClaimed += _etherClaimedByPG[stakedPG[i]]; } for (uint256 j; j < AP.balanceOf(account); j++) { totalEtherClaimed += _etherClaimedByAP[AP.tokenOfOwnerByIndex(account, j)]; } for (uint256 j; j < stakedAP.length; j++) { totalEtherClaimed += _etherClaimedByAP[stakedAP[j]]; } return totalEtherClaimed; }
0.8.0
/** * @dev Deposit interest (add to savings) and update exchange rate of contract. * Exchange rate is calculated as the ratio between new savings q and credits: * exchange rate = savings / credits * * @param _amount Units of underlying to add to the savings vault */
function depositInterest(uint256 _amount) external onlySavingsManager { require(_amount > 0, "Must deposit something"); // Transfer the interest from sender to here require(mUSD.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); totalSavings = totalSavings.add(_amount); // Calc new exchange rate, protect against initialisation case if(totalCredits > 0) { // new exchange rate is relationship between totalCredits & totalSavings // exchangeRate = totalSavings/totalCredits exchangeRate = totalSavings.divPrecisely(totalCredits); emit ExchangeRateUpdated(exchangeRate, _amount); } }
0.5.16
/** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * If automation is enabled, we will first update the internal exchange rate by * collecting any interest generated on the underlying. * @param _amount Units of underlying to deposit into savings vault * @return creditsIssued Units of credits issued internally */
function depositSavings(uint256 _amount) external returns (uint256 creditsIssued) { require(_amount > 0, "Must deposit something"); if(automateInterestCollection) { // Collect recent interest generated by basket and update exchange rate ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mUSD)); } // Transfer tokens from sender to here require(mUSD.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); totalSavings = totalSavings.add(_amount); // Calc how many credits they receive based on currentRatio creditsIssued = _massetToCredit(_amount); totalCredits = totalCredits.add(creditsIssued); // add credits to balances creditBalances[msg.sender] = creditBalances[msg.sender].add(creditsIssued); emit SavingsDeposited(msg.sender, _amount, creditsIssued); }
0.5.16
/** * @dev Redeem specific number of the senders "credits" in exchange for underlying. * Payout amount is calculated as a ratio of credits and exchange rate: * payout = credits * exchangeRate * @param _credits Amount of credits to redeem * @return massetReturned Units of underlying mAsset paid out */
function redeem(uint256 _credits) external returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); uint256 saverCredits = creditBalances[msg.sender]; require(saverCredits >= _credits, "Saver has no credits"); creditBalances[msg.sender] = saverCredits.sub(_credits); totalCredits = totalCredits.sub(_credits); // Calc payout based on currentRatio massetReturned = _creditToMasset(_credits); totalSavings = totalSavings.sub(massetReturned); // Transfer tokens from here to sender require(mUSD.transfer(msg.sender, massetReturned), "Must send tokens"); emit CreditsRedeemed(msg.sender, _credits, massetReturned); }
0.5.16
//return (or revert) with a string in the given length
function checkReturnValues(uint len, bool doRevert) public view returns (string memory) { (this); string memory mesg = "this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself."; require( bytes(mesg).length>=len, "invalid len: too large"); /* solhint-disable no-inline-assembly */ //cut the msg at that length assembly { mstore(mesg, len) } require(!doRevert, mesg); return mesg; }
0.6.10
/* * @param rawTransaction RLP encoded ethereum transaction * @return tuple (nonce,gasPrice,gasLimit,to,value,data) */
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){ RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first! return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes()); }
0.6.10
// Getter and Setter for ledger
function setLedger(uint8 _index, int _value) public { require(FD_AC.checkPermission(101, msg.sender)); int previous = ledger[_index]; ledger[_index] += _value; // --> debug-mode // LogInt("previous", previous); // LogInt("ledger[_index]", ledger[_index]); // LogInt("_value", _value); // <-- debug-mode // check for int overflow if (_value < 0) { assert(ledger[_index] < previous); } else if (_value > 0) { assert(ledger[_index] > previous); } }
0.4.18
/** * @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data) */
function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure { bytes memory data = abi.encode(status, ret); GsnEip712Library.truncateInPlace(data); assembly { let dataSize := mload(data) let dataPtr := add(data, 32) revert(dataPtr, dataSize) } }
0.6.10
// updates the count for this player
function updatePlayCount() internal{ // first time playing this share cycle? if(allPlayers[msg.sender].shareCycle!=shareCycle){ allPlayers[msg.sender].playCount=0; allPlayers[msg.sender].shareCycle=shareCycle; insertCyclePlayer(); } allPlayers[msg.sender].playCount++; // note we don't touch profitShare or winnings because they need to roll over cycles if unclaimed }
0.4.19
// buy into syndicate
function buyIntoSyndicate() public payable { if(msg.value==0 || availableBuyInShares==0) revert(); if(msg.value < minimumBuyIn*buyInSharePrice) revert(); uint256 value = (msg.value/precision)*precision; // ensure precision uint256 allocation = value/buyInSharePrice; if (allocation >= availableBuyInShares){ allocation = availableBuyInShares; // limit hit } availableBuyInShares-=allocation; addMember(msg.sender); // possibly add this member to the syndicate members[msg.sender].numShares+=allocation; }
0.4.19
// main entry point for investors/players
function invest(uint256 optionNumber) public payable { // Check that the number is within the range (uints are always>=0 anyway) assert(optionNumber <= 9); uint256 amount = roundIt(msg.value); // round to precision assert(amount >= minimumStake); // check for zero tie-breaker transaction // in this case nobody wins and investment goes into next session. if (block.number >= endingBlock && currentLowestCount>1 && marketOptions[currentLowest]==0){ endSession(); // auto invest them in the lowest market option - reward for optionNumber = currentLowest; } uint256 holding = playerPortfolio[msg.sender][optionNumber]; holding = SafeMath.add(holding, amount); playerPortfolio[msg.sender][optionNumber] = holding; marketOptions[optionNumber] = SafeMath.add(marketOptions[optionNumber],amount); numberOfInvestments += 1; totalInvested += amount; if (!activePlayers[msg.sender]){ insertPlayer(msg.sender); activePlayers[msg.sender]=true; } Invest(msg.sender, optionNumber, amount, marketOptions, block.number); updatePlayCount(); // rank the player in leaderboard currentLowest = findCurrentLowest(); // overtime and there's a winner if (block.number >= endingBlock && currentLowestCount==1){ // somebody wins here. endSession(); } }
0.4.19
// end invest // find lowest option sets currentLowestCount>1 if there are more than 1 lowest
function findCurrentLowest() internal returns (uint lowestOption) { uint winner = 0; uint lowestTotal = marketOptions[0]; currentLowestCount = 0; for(uint i=0;i<10;i++) { if (marketOptions [i]<lowestTotal){ winner = i; lowestTotal = marketOptions [i]; currentLowestCount = 0; } if (marketOptions [i]==lowestTotal){currentLowestCount+=1;} } return winner; }
0.4.19
// distribute winnings at the end of a session
function endSession() internal { uint256 sessionWinnings = 0; if (currentLowestCount>1){ numberWinner = 10; // no winner }else{ numberWinner = currentLowest; } // record the end of session for(uint j=1;j<numPlayers;j++) { if (numberWinner<10 && playerPortfolio[players[j]][numberWinner]>0){ uint256 winningAmount = playerPortfolio[players[j]][numberWinner]; uint256 winnings = SafeMath.mul(winningMultiplier,winningAmount); // n times the invested amount. sessionWinnings+=winnings; allocateWinnings(players[j],winnings); // allocate winnings Winning(players[j], winnings, sessionNumber, numberWinner,block.number); // we can pick this up on gui } playerPortfolio[players[j]] = [0,0,0,0,0,0,0,0,0,0]; activePlayers[players[j]]=false; } EndSession(msg.sender, sessionNumber, numberWinner, marketOptions , block.number); uint256 playerInvestments = totalInvested-seedInvestment; if (sessionWinnings>playerInvestments){ uint256 loss = sessionWinnings-playerInvestments; // this is a loss if (currentSyndicateValue>=loss){ currentSyndicateValue-=loss; }else{ currentSyndicateValue = 0; } } if (playerInvestments>sessionWinnings){ currentSyndicateValue+=playerInvestments-sessionWinnings; // this is a gain } resetMarket(); }
0.4.19
// This Function is used to do Batch Mint.
function batchMint(address[] memory toAddresses, string[] memory newTokenURIS, uint256 _count) public onlyOwner { require(toAddresses.length > 0,"To Addresses Cant Be null."); require(newTokenURIS.length > 0,"Token URIs Cant Be null"); require(_count > 0,"Count Cant be Zero"); require(_tokenIdCounter.current() < MAX_RATS,"All Tokens Have been minted."); require(_tokenIdCounter.current() + _count <= MAX_RATS,"Token count exceeds with available NFT's."); require(_count <= maxMint,"You have exceeded max mint count."); require(newTokenURIS.length == _count, "Token URI's & count does not match."); for (uint256 i = 0; i < _count; i++) { _tokenIdCounter.increment(); uint256 tokenId = _tokenIdCounter.current(); _safeMint(toAddresses[i], tokenId); _setTokenURI(tokenId, newTokenURIS[i]); } }
0.8.11
/* * @dev Used to get the tokensOfOwner. * @return uint256[] for tokensOfOwner. */
function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all Rats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 tokensId; for (tokensId = 1; tokensId <= totalTokens; tokensId++) { if (ownerOf(tokensId) == _owner) { result[resultIndex] = tokensId; resultIndex++; } } return result; } }
0.8.11
// return a list of bool, true means unstake
function unstakeCheck(address contractAddr, uint256[] calldata tokenIds) external view returns (bool[] memory) { require(tokenIds.length <= maxLoopSize,"Staking: check stake size exceed"); uint256 contractId = whiteList[contractAddr]; require(contractId > 0, "Staking: contract not on whitelist"); bool[] memory stakeResult = new bool[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; i++) { if(tokenStorage[contractId][tokenIds[i]] == 0){ stakeResult[i] = true; } } return stakeResult; }
0.8.4
// ------------------------------------------------------------------------ // YES! Accept ETH // ------------------------------------------------------------------------
function () public payable { require(msg.value > 0); require(balances[address(this)] > msg.value * token_price); amount_eth += msg.value; uint tokens = msg.value * token_price; balances[address(this)] -= tokens; balances[msg.sender] += tokens; //SEND TO CONTRACT Transfer(address(this), msg.sender, address(this).balance); //SEND TO OWNER //owner.transfer(address(this).balance); }
0.4.18
/** * @dev x to the power of y power(base, exponent) */
function pow(uint256 base, uint256 exponent) public pure returns (uint256) { if (exponent == 0) { return 1; } else if (exponent == 1) { return base; } else if (base == 0 && exponent != 0) { return 0; } else { uint256 z = base; for (uint256 i = 1; i < exponent; i++) z = mul(z, base); return z; } }
0.5.2
/** * Add a historically significant event (i.e. maintenance, damage * repair or new owner). */
function addEvent(uint256 _mileage, uint256 _repairOrderNumber, EventType _eventType, string _description, string _vin) onlyAuthorized { events[sha3(_vin)].push(LedgerEvent({ creationTime: now, mileage: _mileage, repairOrderNumber: _repairOrderNumber, verifier: msg.sender, eventType: _eventType, description: _description })); EventLogged(_vin, _eventType, _mileage, msg.sender); }
0.4.10
/** * Returns the details of a specific event. To be used together with the function * getEventsCount(). */
function getEvent(string _vin, uint256 _index) constant returns (uint256 mileage, address verifier, EventType eventType, string description) { LedgerEvent memory e = events[sha3(_vin)][_index]; mileage = e.mileage; verifier = e.verifier; eventType = e.eventType; description = e.description; }
0.4.10
/** * @dev To invest on shares * @param _noOfShares No of shares */
function investOnShare(uint _noOfShares) public payable returns(bool){ require( lockStatus == false, "Contract is locked" ); require( msg.value == invest.mul(_noOfShares), "Incorrect Value" ); require(users[msg.sender].isExist || syncIsExist1(msg.sender) || syncIsExist2(msg.sender),"User not exist"); require(msg.sender != oldEEEMoney1.ownerWallet(), "old ownerWallet"); uint32 size; address useraddress = msg.sender; assembly { size := extcodesize(useraddress) } require(size == 0, "cannot be a contract"); uint _value = (msg.value).div(2); address _referer; uint referrerID = users[msg.sender].referrerID; if(referrerID == 0) referrerID = syncReferrerID2(msg.sender); if(referrerID == 0) referrerID = syncReferrerID1(msg.sender); _referer = userList[referrerID]; if(_referer == address(0)) _referer = oldEEEMoney2.userList(referrerID); if(_referer == address(0)) _referer = oldEEEMoney1.userList(referrerID); if((_referer == address(0)) || (_referer == oldEEEMoney1.ownerWallet())) _referer = ownerWallet; require( address(uint160(_referer)).send(_value), "Transaction failed" ); users[_referer].totalEarnedETH = users[_referer].totalEarnedETH.add(_value); users[msg.sender].directShare = users[msg.sender].directShare.add(_noOfShares); users[msg.sender].sharesHoldings = users[msg.sender].sharesHoldings.add(_noOfShares); poolMoney = poolMoney.add(_value); emit poolMoneyEvent( msg.sender, _value, now); emit userInversement( msg.sender, _noOfShares, msg.value, now, 1); return true; }
0.5.16
// Performs payout based on launch outcome, // triggered by bookies.
function performPayout() public canPerformPayout onlyBookieLevel { // Calculate total pool of ETH // betted for the two outcomes uint losingChunk = this.balance - totalAmountsBet[launchOutcome]; uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot // Equal weight payout to the bookies BOOKIES[0].transfer(bookiePayout / 2); BOOKIES[1].transfer(bookiePayout / 2); // Weighted payout to betters based on // their contribution to the winning pool for (uint k = 0; k < betters.length; k++) { uint betOnWinner = betterInfo[betters[k]].amountsBet[launchOutcome]; uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[launchOutcome]); if (payout > 0) betters[k].transfer(payout); } payoutCompleted = true; }
0.4.19
// Release all the bets back to the betters // if, for any reason, payouts cannot be // completed. Triggered by bookies.
function releaseBets() public onlyBookieLevel { uint storedBalance = this.balance; for (uint k = 0; k < betters.length; k++) { uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1]; betters[k].transfer(totalBet * storedBalance / totalBetAmount); } }
0.4.19
// generic minting function :)
function _handleMinting(address _to, uint256 _index, uint8 _type, bool useECType) private { // Attempt to mint. _safeMint(_to, _index); localTotalSupply.increment(); // Removed for now. if (useECType && _type == 0) { companionBalance[_to]++; companionList.push(_index); noundleOffsetCount[_index] = mintCountCompanions; mintCountCompanions++; } else if (useECType && _type == 1) { evilBalance[_to]++; evilList.push(_index); noundleOffsetCount[_index] = mintCountEvil; mintCountEvil++; } else if (_type == 2) { lowLandBalance[_to]++; lowLandList.push(_index); noundleOffsetCount[_index] = mintCountLandLow; mintCountLandLow++; } else if (_type == 3) { midLandBalance[_to]++; midLandList.push(_index); noundleOffsetCount[_index] = mintCountLandMid; mintCountLandMid++; } else if (_type == 4) { highLandBalance[_to]++; highLandList.push(_index); noundleOffsetCount[_index] = mintCountLandHigh; mintCountLandHigh++; } // Set it's type in place. noundleType[_index] = _type; }
0.8.7
// Reserves some of the supply of the noundles for giveaways & the community
function reserveNoundles(uint256 _amount, uint8 _type) public onlyOwner { // enforce reserve limits based on type claimed if (_type == 0) { require(reservedComp + _amount <= MAX_RESERVED_COMP, "Cannot reserve more companions!"); } else if (_type == 1) { require(reservedEvil + _amount <= MAX_RESERVED_EVIL, "Cannot reserve more evil noundles!"); } else { require(reservedLand + _amount <= MAX_RESERVED_LAND, "Cannot reserve more land!"); } uint256 _ts = localTotalSupply.current(); // totalSupply(); // Mint the reserves. for (uint256 i; i < _amount; i++) { _handleMinting(msg.sender, _ts + i, _type, true); if (_type == 0) { reservedComp++; } else if (_type == 1) { reservedEvil++; } else { reservedLand++; } } }
0.8.7
// Mint your evil noundle.
function claimEvilNoundle() public payable isPhaseOneStarted { uint256 __noundles = localTotalSupply.current(); // totalSupply(); // Verify request. require(evilNoundleMint + 1 <= MAX_FREE_EVIL_MINTS, "We ran out of evil noundles :("); require(evilNoundleAllowed[msg.sender], "You are not on whitelist"); require(evilNoundleMinted[msg.sender] == false, "You already minted your free noundle."); // Make sure that the wallet is holding at least 1 noundle. // require(Originals.getNoundlesFromWallet(msg.sender).length > 0, "You must hold at least one Noundle to mint"); // Burn the rainbows. Rainbows.burn(msg.sender, evilMintPriceRainbow); // Mark it as they already got theirs. evilNoundleMinted[msg.sender] = true; // Add to our free mint count. evilNoundleMint += 1; // Mint it. _handleMinting(msg.sender, __noundles, 1, true); }
0.8.7
// Mint your free companion.
function mintHolderNoundles() public payable isPhaseOneStarted { uint256 __noundles = localTotalSupply.current(); // totalSupply(); // Verify request. require(freeCompanionMint + 1 <= MAX_FREE_COMPANION_MINTS, "We ran out of evil noundles :("); require(freeCompanionAllowed[msg.sender], "You are not on whitelist"); require(freeCompanionMinted[msg.sender] == false, "You already minted your free companion."); // Make sure that the wallet is holding at least 1 noundle. require(Originals.getNoundlesFromWallet(msg.sender).length > 0, "You must hold at least one Noundle to mint"); // Mark it as they already got theirs. freeCompanionMinted[msg.sender] = true; // Add to our free mint count. freeCompanionMint += 1; // Mint it. _handleMinting(msg.sender, __noundles, 0, true); }
0.8.7
// migrate the old contract over
function migrateOldNoundles(uint256[] memory tokens) public payable { require(migrationEnabled, "Migration is not enabled"); uint256 __noundles = localTotalSupply.current(); // totalSupply(); // Look up the types for each. uint8[] memory foundTypes = BetaTheory.getTypeByTokenIds(tokens); uint256 offset = 0; // Claim each token they ask to migrate. for(uint256 i = 0; i < tokens.length; i += 1){ // Verify it has not already been migrated. if(alreadyClaimedMigration[tokens[i]]){ continue; } // Verify the owner if the sender. if(BetaTheory.ownerOf(tokens[i]) != msg.sender){ continue; } // Mark it as already migrated. alreadyClaimedMigration[tokens[i]] = true; // Mint it. _handleMinting(msg.sender, __noundles + offset, foundTypes[i], true); if(foundTypes[i] == 1){ MigrationMapToMap[__noundles + offset] = tokens[i]; if(percentChance(__noundles + offset, 100, 15)){ MigrationValue[tokens[i]] = 6; }else { MigrationValue[tokens[i]] = 3; } } offset++; } }
0.8.7
// Handle consuming rainbow to mint a new NFT with random chance.
function mintWithRainbows(uint256 _noundles) public payable isRainbowMintingEnabled { if (overrideContractMintBlock == false) { require(msg.sender == tx.origin, "No contract minting allowed!"); } uint256 __noundles = localTotalSupply.current(); // totalSupply(); require(_noundles > 0 && _noundles <= 10, "Your amount needs to be greater then 0 and can't exceed 10"); require(_noundles + (mintCountCompanions + mintCountEvil + OG_TOTAL_SUPPLY) <= MAX_EVIL_NOUNDLES, "We ran out of noundles! Try minting with less!"); for (uint256 ___noundles; ___noundles < _noundles; ___noundles++) { _handleRainbowMinting(msg.sender, __noundles + ___noundles); } }
0.8.7
// Get a evil out of jail.
function getOutOfJailByTokenId(uint256 _tokenId) public payable isRainbowMintingEnabled { // Check that it is a evil noundle. require(noundleType[_tokenId] == 1, "Only evil noundles can go to jail."); // Burn the rainbows to get out of jail. Rainbows.burn(msg.sender, getOutOfJail); // Reset the jail time. jailHouse[_tokenId] = 1; // Stat track. counterBail += 1; }
0.8.7
// Pick a evil noundle randomly from our list.
function getRandomEvilNoundle(uint256 index, uint256 depth) public returns(uint256) { // If we have no evil noundles, return. if(evilList.length == 0){ return 0; } uint256 selectedIndex = RandomNumber.getRandomNumber(index) % evilList.length; // If it's not in jail. if(jailHouse[evilList[selectedIndex]] + jailLength < block.timestamp){ return evilList[selectedIndex]; } // If we can't find one in 100 attempts, select none. if(depth > 99){ return 0; } // If it's in jail, it can't steal so try again. return getRandomEvilNoundle(index, depth + 1); }
0.8.7
// Gets the noundle theory tokens and returns a array with all the tokens owned
function getNoundlesFromWallet(address _noundles) external view returns (uint256[] memory) { uint256 __noundles = balanceOf(_noundles); uint256[] memory ___noundles = new uint256[](__noundles); uint256 offset = 0; for (uint256 i; (offset < __noundles) && i < localTotalSupply.current(); i++) { if(ownerOf(i) == _noundles){ // ___noundles[i] = tokenOfOwnerByIndex(_noundles, i); ___noundles[offset] = i; offset += 1; } } return ___noundles; }
0.8.7
// Returns the addresses that own any evil noundle - seems rare :eyes:
function getEvilNoundleOwners() external view returns (address[] memory) { address[] memory result = new address[](evilList.length); for(uint256 index; index < evilList.length; index += 1){ if(jailHouse[evilList[index]] + jailLength <= block.timestamp){ result[index] = ownerOf(evilList[index]); } } return result; }
0.8.7
// Helper to convert int to string (thanks stack overflow).
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); }
0.8.7
//Pool UniSwap pair creation method (called by initialSetup() )
function POOL_CreateUniswapPair(address router, address factory) internal returns (address) { require(contractInitialized > 0, "Requires intialization 1st"); uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); require(UniswapPair == address(0), "Token: pool already created"); UniswapPair = uniswapFactory.createPair(address(uniswapRouterV2.WETH()),address(this)); return UniswapPair; }
0.6.6
/* Once initialSetup has been invoked * Team will create the Vault and the LP wrapper token * * Only AFTER these 2 addresses have been created the users * can start contributing in ETH */
function secondarySetup(address _Vault, address _wUNIv2) public governanceLevel(2) { require(contractInitialized > 0 && contractStart_Timestamp == 0, "Requires Initialization and Start"); setVault(_Vault); //also adds the Vault to noFeeList wUNIv2 = _wUNIv2; require(Vault != address(0) && wUNIv2 != address(0), "Wrapper Token and Vault not Setup"); contractStart_Timestamp = block.timestamp; }
0.6.6
//========================================================================================================================================= // Emergency drain in case of a bug
function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public governanceLevel(2) { require(contractStart_Timestamp > 0, "Requires contractTimestamp > 0"); require(contractStart_Timestamp.add(emergencyPeriod) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens (bool success, ) = msg.sender.call{value:(address(this).balance)}(""); require(success, "ETH Transfer failed... we are cucked"); ERC20._transfer(address(this), msg.sender, balanceOf(address(this))); }
0.6.6
//During ETH_ContributionPhase: Users deposit funds //funds sent to TOKEN contract.
function USER_PledgeLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable ETH_ContributionPhase { require(ethContributed[msg.sender].add(msg.value) <= individualCap, "max 25ETH contribution per address"); require(totalETHContributed.add(msg.value) <= totalCap, "500 ETH Hard cap"); require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); ethContributed[msg.sender] = ethContributed[msg.sender].add(msg.value); totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE emit LiquidityAddition(msg.sender, msg.value); }
0.6.6
// After ETH_ContributionPhase: Pool can create liquidity. // Vault and wrapped UNIv2 contracts need to be setup in advance.
function POOL_CreateLiquidity() public LGE_Possible { totalETHContributed = address(this).balance; IUniswapV2Pair pair = IUniswapV2Pair(UniswapPair); //Wrap eth address WETH = uniswapRouterV2.WETH(); //Send to UniSwap IWETH(WETH).deposit{value : totalETHContributed}(); require(address(this).balance == 0 , "Transfer Failed"); IWETH(WETH).transfer(address(pair),totalETHContributed); emit Transfer(address(this), address(pair), balanceOf(address(this))); //UniCore balances transfer ERC20._transfer(address(this), address(pair), balanceOf(address(this))); pair.mint(address(this)); //mint LP tokens. lock method in UniSwapPairV2 PREVENTS FROM DOING IT TWICE totalLPTokensMinted = pair.balanceOf(address(this)); require(totalLPTokensMinted != 0 , "LP creation failed"); LPperETHUnit = totalLPTokensMinted.mul(1e18).div(totalETHContributed); // 1e18x for change require(LPperETHUnit != 0 , "LP creation failed"); LGECompleted_Timestamp = block.timestamp; }
0.6.6
//After ETH_ContributionPhase: Pool can create liquidity.
function USER_ClaimWrappedLiquidity() public LGE_happened { require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); IReactor(wUNIv2).wTransfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); }
0.6.6
//========================================================================================================================================= //overriden _transfer to take Fees
function _transfer(address sender, address recipient, uint256 amount) internal override Trading_Possible { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); //updates _balances setBalance(sender, balanceOf(sender).sub(amount, "ERC20: transfer amount exceeds balance")); //calculate net amounts and fee (uint256 toAmount, uint256 toFee) = calculateAmountAndFee(sender, amount); //Send Reward to Vault 1st if(toFee > 0 && Vault != address(0)){ setBalance(Vault, balanceOf(Vault).add(toFee)); IVault(Vault).updateRewards(); //updating the vault with rewards sent. emit Transfer(sender, Vault, toFee); } //transfer to recipient setBalance(recipient, balanceOf(recipient).add(toAmount)); emit Transfer(sender, recipient, toAmount); }
0.6.6
/** * Bid on rebalancing a given quantity of sets held by a rebalancing token wrapping or unwrapping * any ETH involved. The tokens are returned to the user. * * @param _rebalancingSetToken Instance of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity is greater than currentRemainingSets */
function bidAndWithdrawWithEther( IRebalancingSetToken _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) external payable nonReentrant { // Wrap all Ether sent to the contract weth.deposit.value(msg.value)(); // Get token addresses address[] memory combinedTokenArray = _rebalancingSetToken.getCombinedTokenArray(); // Get inflow and outflow arrays for the given bid quantity uint256[] memory inflowArray; uint256[] memory outflowArray; ( inflowArray, outflowArray ) = _rebalancingSetToken.getBidPrice(_quantity); // Ensure allowances and transfer non-weth tokens from user depositNonWethComponents( combinedTokenArray, inflowArray ); // Bid in auction rebalanceAuctionModule.bidAndWithdraw( address(_rebalancingSetToken), _quantity, _allowPartialFill ); // Withdraw non-weth tokens to user withdrawNonWethComponentsToSender( combinedTokenArray ); // Unwrap all remaining Ether and transfer to user uint256 wethBalance = ERC20Wrapper.balanceOf(address(weth), address(this)); if (wethBalance > 0) { weth.withdraw(wethBalance); msg.sender.transfer(wethBalance); } // Log bid placed with Eth event emit BidPlacedWithEth( address(_rebalancingSetToken), msg.sender ); }
0.5.7
/** * Before bidding, calculate the required amount of inflow tokens and deposit token components * into this helper contract. * * @param _combinedTokenArray Array of token addresses * @param _inflowArray Array of inflow token units */
function depositNonWethComponents( address[] memory _combinedTokenArray, uint256[] memory _inflowArray ) private { // Loop through the combined token addresses array and deposit inflow amounts for (uint256 i = 0; i < _combinedTokenArray.length; i++) { address currentComponent = _combinedTokenArray[i]; uint256 currentComponentQuantity = _inflowArray[i]; // Check component inflow is greater than 0 if (currentComponentQuantity > 0) { // Ensure allowance for components to transferProxy ERC20Wrapper.ensureAllowance( address(currentComponent), address(this), address(transferProxy), currentComponentQuantity ); // If not WETH, transfer tokens from user to contract if (currentComponent != address(weth)) { // Transfer tokens to contract ERC20Wrapper.transferFrom( address(currentComponent), msg.sender, address(this), currentComponentQuantity ); } } } }
0.5.7
/** * After bidding, loop through token address array and transfer * token components except wrapped ether to the sender * * @param _combinedTokenArray Array of token addresses */
function withdrawNonWethComponentsToSender( address[] memory _combinedTokenArray ) private { // Loop through the combined token addresses array and withdraw leftover amounts for (uint256 i = 0; i < _combinedTokenArray.length; i++) { address currentComponent = _combinedTokenArray[i]; // Get balance of tokens in contract uint256 currentComponentBalance = ERC20Wrapper.balanceOf( currentComponent, address(this) ); // Check component balance is greater than 0 if (currentComponentBalance > 0 && currentComponent != address(weth)) { // Withdraw tokens from the contract and send to the user ERC20Wrapper.transfer( address(currentComponent), msg.sender, currentComponentBalance ); } } }
0.5.7
// modified Transfer Function to log times @ accts balances exceed minReqBal, for Sublimation Pool // modified Transfer Function to safeguard Uniswap liquidity during token sale
function _transfer(address sender, address recipient, uint256 amount) internal virtual { if(allowUniswap == false && sender != _owner && recipient == UniswapPair ){ revert("UNI_LIQ_PLAY_NOT_YET"); } else { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); bool isOverReq = false; if(_balances[recipient] >= _minBalReq){ isOverReq = true; } _balances[recipient] = _balances[recipient].add(amount); if(_balances[recipient] >= _minBalReq && isOverReq == false){ _timeExceeded[recipient] = uint32(block.timestamp); } emit Transfer(sender, recipient, amount); } }
0.7.6
/** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */
function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); }
0.7.6
/** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */
function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); }
0.7.6
/** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */
function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; }
0.7.6
// n form 1 <= to <= 32
function getBetValue(bytes32 values, uint8 n) private constant returns (uint256) { // bet in credits (1..256) uint256 bet = uint256(values[32-n])+1; // check min bet uint8 minCredits = minCreditsOnBet[n]; if (minCredits == 0) minCredits = defaultMinCreditsOnBet; if (bet < minCredits) throw; // bet in wei bet = currentMaxBet*bet/256; if (bet > currentMaxBet) throw; return bet; }
0.4.8
/** * @dev Private implementation of staking methods. * @param staker User address who deposits tokens to stake. * @param beneficiary User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. */
function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'SeigniorageMining: stake amount is zero'); require(beneficiary != address(0), 'SeigniorageMining: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'SeigniorageMining: Invalid state. Staking shares exist, but no staking tokens do'); uint256 mintedStakingShares = (totalStakingShares > 0) ? totalStakingShares.mul(amount).div(totalStaked()) : amount.mul(_initialSharesPerToken); require(mintedStakingShares > 0, 'SeigniorageMining: Stake amount is too small'); updateAccounting(); // 1. User Accounting UserTotals storage totals = _userTotals[beneficiary]; totals.stakingShares = totals.stakingShares.add(mintedStakingShares); totals.lastAccountingTimestampSec = now; Stake memory newStake = Stake(mintedStakingShares, now); _userStakes[beneficiary].push(newStake); // 2. Global Accounting totalStakingShares = totalStakingShares.add(mintedStakingShares); // Already set in updateAccounting() // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount), 'SeigniorageMining: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); }
0.5.0
/** * @dev A globally callable function to update the accounting state of the system. * Global state and state for the caller are updated. * @return [0] balance of the locked pool * @return [1] balance of the unlocked pool * @return [2] caller's staking share seconds * @return [3] global staking share seconds * @return [4] Rewards caller has accumulated * @return [5] Dollar Rewards caller has accumulated * @return [6] block timestamp */
function updateAccounting() public returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256) { unlockTokens(); // Global accounting uint256 newStakingShareSeconds = now .sub(_lastAccountingTimestampSec) .mul(totalStakingShares); _totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds); _lastAccountingTimestampSec = now; // User Accounting UserTotals storage totals = _userTotals[msg.sender]; uint256 newUserStakingShareSeconds = now .sub(totals.lastAccountingTimestampSec) .mul(totals.stakingShares); totals.stakingShareSeconds = totals.stakingShareSeconds .add(newUserStakingShareSeconds); totals.lastAccountingTimestampSec = now; uint256 totalUserShareRewards = (_totalStakingShareSeconds > 0) ? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds) : 0; uint256 totalUserDollarRewards = (_totalStakingShareSeconds > 0) ? totalLockedDollars().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds) : 0; return ( totalLocked(), totalUnlocked(), totals.stakingShareSeconds, _totalStakingShareSeconds, totalUserShareRewards, totalUserDollarRewards, now ); }
0.5.0
/** * @dev This funcion allows the contract owner to add more locked distribution tokens, along * with the associated "unlock schedule". These locked tokens immediately begin unlocking * linearly over the duraction of durationSec timeframe. * @param amount Number of distribution tokens to lock. These are transferred from the caller. * @param durationSec Length of time to linear unlock the tokens. */
function lockTokens(uint256 amount, uint256 startTimeSec, uint256 durationSec) external onlyOwner { require(unlockSchedules.length < _maxUnlockSchedules, 'SeigniorageMining: reached maximum unlock schedules'); // Update lockedTokens amount before using it in computations after. updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now; schedule.startAtSec = startTimeSec; schedule.endAtSec = startTimeSec.add(durationSec); schedule.durationSec = durationSec; unlockSchedules.push(schedule); totalLockedShares = totalLockedShares.add(mintedLockedShares); require(_lockedPool.shareToken().transferFrom(msg.sender, address(_lockedPool), amount), 'SeigniorageMining: transfer into locked pool failed'); emit TokensLocked(amount, durationSec, totalLocked()); }
0.5.0
/** * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the * previously defined unlock schedules. Publicly callable. * @return Number of newly unlocked distribution tokens. */
function unlockTokens() public returns (uint256) { uint256 unlockedShareTokens = 0; uint256 lockedShareTokens = totalLocked(); uint256 unlockedDollars = 0; uint256 lockedDollars = totalLockedDollars(); if (totalLockedShares == 0) { unlockedShareTokens = lockedShareTokens; unlockedDollars = lockedDollars; } else { uint256 unlockedShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockedShares = unlockedShares.add(unlockScheduleShares(s)); } unlockedShareTokens = unlockedShares.mul(lockedShareTokens).div(totalLockedShares); unlockedDollars = unlockedShares.mul(lockedDollars).div(totalLockedShares); totalLockedShares = totalLockedShares.sub(unlockedShares); } if (unlockedShareTokens > 0) { require(_lockedPool.shareTransfer(address(_unlockedPool), unlockedShareTokens), 'SeigniorageMining: shareTransfer out of locked pool failed'); require(_lockedPool.dollarTransfer(address(_unlockedPool), unlockedDollars), 'SeigniorageMining: dollarTransfer out of locked pool failed'); emit TokensUnlocked(unlockedShareTokens, totalLocked()); emit DollarsUnlocked(unlockedDollars, totalLocked()); } return unlockedShareTokens; }
0.5.0
/** * @dev Returns the number of unlockable shares from a given schedule. The returned value * depends on the time since the last unlock. This function updates schedule accounting, * but does not actually transfer any tokens. * @param s Index of the unlock schedule. * @return The number of unlocked shares. */
function unlockScheduleShares(uint256 s) private returns (uint256) { UnlockSchedule storage schedule = unlockSchedules[s]; if(schedule.unlockedShares >= schedule.initialLockedShares) { return 0; } uint256 sharesToUnlock = 0; if (now < schedule.startAtSec) { // do nothing } else if (now >= schedule.endAtSec) { // Special case to handle any leftover dust from integer division sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else { sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec) .mul(schedule.initialLockedShares) .div(schedule.durationSec); schedule.lastUnlockTimestampSec = now; } schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock); return sharesToUnlock; }
0.5.0
// Get token creation rate
function getTokenCreationRate() constant returns (uint256) { require(!presaleFinalized || !saleFinalized); uint256 creationRate; if (!presaleFinalized) { //The rate on presales is constant creationRate = presaleTokenCreationRate; } else { //The rate on sale is changing lineral while time is passing. On sales start it is 1.66 and on end 1.0 uint256 rateRange = saleStartTokenCreationRate - saleEndTokenCreationRate; uint256 timeRange = saleEndTime - saleStartTime; creationRate = saleStartTokenCreationRate.sub(rateRange.mul(now.sub(saleStartTime)).div(timeRange)); } return creationRate; }
0.4.13
// Buy presale tokens
function buyPresaleTokens(address _beneficiary) payable { require(!presaleFinalized); require(msg.value != 0); require(now <= presaleEndTime); require(now >= presaleStartTime); uint256 bbdTokens = msg.value.mul(getTokenCreationRate()).div(divisor); uint256 checkedSupply = totalSupply.add(bbdTokens); require(presaleTokenCreationCap >= checkedSupply); totalSupply = totalSupply.add(bbdTokens); balances[_beneficiary] = balances[_beneficiary].add(bbdTokens); raised += msg.value; TokenPurchase(msg.sender, _beneficiary, msg.value, bbdTokens); }
0.4.13
// Finalize presale
function finalizePresale() onlyOwner external { require(!presaleFinalized); require(now >= presaleEndTime || totalSupply == presaleTokenCreationCap); presaleFinalized = true; uint256 ethForCoreMember = this.balance.mul(500).div(divisor); coreTeamMemberOne.transfer(ethForCoreMember); // 5% coreTeamMemberTwo.transfer(ethForCoreMember); // 5% qtAccount.transfer(this.balance); // Quant Technology 90% }
0.4.13
// Buy sale tokens
function buySaleTokens(address _beneficiary) payable { require(!saleFinalized); require(msg.value != 0); require(now <= saleEndTime); require(now >= saleStartTime); uint256 bbdTokens = msg.value.mul(getTokenCreationRate()).div(divisor); uint256 checkedSupply = totalSupply.add(bbdTokens); require(totalTokenCreationCap >= checkedSupply); totalSupply = totalSupply.add(bbdTokens); balances[_beneficiary] = balances[_beneficiary].add(bbdTokens); raised += msg.value; TokenPurchase(msg.sender, _beneficiary, msg.value, bbdTokens); }
0.4.13
// Finalize sale
function finalizeSale() onlyOwner external { require(!saleFinalized); require(now >= saleEndTime || totalSupply == totalTokenCreationCap); saleFinalized = true; //Add aditional 25% tokens to the Quant Technology and development team uint256 additionalBBDTokensForQTAccount = totalSupply.mul(2250).div(divisor); // 22.5% totalSupply = totalSupply.add(additionalBBDTokensForQTAccount); balances[qtAccount] = balances[qtAccount].add(additionalBBDTokensForQTAccount); uint256 additionalBBDTokensForCoreTeamMember = totalSupply.mul(125).div(divisor); // 1.25% totalSupply = totalSupply.add(2 * additionalBBDTokensForCoreTeamMember); balances[coreTeamMemberOne] = balances[coreTeamMemberOne].add(additionalBBDTokensForCoreTeamMember); balances[coreTeamMemberTwo] = balances[coreTeamMemberTwo].add(additionalBBDTokensForCoreTeamMember); uint256 ethForCoreMember = this.balance.mul(500).div(divisor); coreTeamMemberOne.transfer(ethForCoreMember); // 5% coreTeamMemberTwo.transfer(ethForCoreMember); // 5% qtAccount.transfer(this.balance); // Quant Technology 90% }
0.4.13
// freeze system' balance
function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal { uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day); balances[owner] = balances[owner].sub(_value); frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex}); frozenBalance = frozenBalance.add(_value); emit SystemFreeze(owner, _value, _unfreezeTime); }
0.4.21
// update release amount for single day // according to dividend rule in https://coincoolotc.com
function updateReleaseAmount() internal { if (releaseCount <= 180) { releaseAmountPerDay = standardReleaseAmount; } else if (releaseCount <= 360) { releaseAmountPerDay = standardReleaseAmount.div(2); } else if (releaseCount <= 540) { releaseAmountPerDay = standardReleaseAmount.div(4); } }
0.4.21
// Verifies that the higher level count is correct, and that the last uint256 is left packed with 0's
function initStruct(uint256[] memory _arr, uint256 _len) internal pure returns (PackedArray memory) { uint256 actualLength = _arr.length; uint256 len0 = _len / 16; require(actualLength == len0 + 1, "Invalid arr length"); uint256 len1 = _len % 16; uint256 leftPacked = uint256(_arr[len0] >> (len1 * 16)); require(leftPacked == 0, "Invalid uint256 packing"); return PackedArray(_arr, _len); }
0.8.7
/*************************************** BREEDING ****************************************/
function breedPrimes( uint16 _parent1, uint16 _parent2, uint256 _attributes, bytes32[] memory _merkleProof ) external nonReentrant { BreedInput memory input1 = _getInput(_parent1); BreedInput memory input2 = _getInput(_parent2); require(input1.owns && input2.owns, "Breeder must own input token"); _breed(input1, input2, _attributes, _merkleProof); }
0.8.7
// After each batch has begun, the DAO can mint to ensure no bottleneck
function rescueSale() external onlyOwner nonReentrant { (bool active, uint256 batchId, uint256 remaining, ) = batchCheck(); require(active, "Batch not active"); require( block.timestamp > batchStartTime + RESCUE_SALE_GRACE_PERIOD, "Must wait for sale to elapse" ); uint256 rescueCount = remaining < 20 ? remaining : 20; for (uint256 i = 0; i < rescueCount; i++) { _getPrime(batchId); } }
0.8.7
/*************************************** MINTING - INTERNAL ****************************************/
function _getPrime(uint256 _batchId) internal { uint256 seed = _rand(); uint16 primeIndex; if (_batchId == 0) { uint256 idx = seed % batch0.length; primeIndex = batch0.getValue(idx); batch0.extractIndex(idx); _triggerTimestamp(_batchId, batch0.length); } else if (_batchId == 1) { uint256 idx = seed % batch1.length; primeIndex = batch1.getValue(idx); batch1.extractIndex(idx); _triggerTimestamp(_batchId, batch1.length); } else { revert("Invalid batchId"); } _mintLocal(msg.sender, primeIndex); }
0.8.7
/** * @notice Checks whether or not a trade should be approved * * @dev This method calls back to the token contract specified by `_token` for * information needed to enforce trade approval if needed * * @param _token The address of the token to be transfered * @param _spender The address of the spender of the token (unused in this implementation) * @param _from The address of the sender account * @param _to The address of the receiver account * @param _amount The quantity of the token to trade * * @return `true` if the trade should be approved and `false` if the trade should not be approved */
function check(address _token, address _spender, address _from, address _to, uint256 _amount) public returns (uint8) { if (settings[_token].locked) { return CHECK_ELOCKED; } if (participants[_token][_from] & PERM_SEND == 0) { return CHECK_ESEND; } if (participants[_token][_to] & PERM_RECEIVE == 0) { return CHECK_ERECV; } if (!settings[_token].partialTransfers && _amount % _wholeToken(_token) != 0) { return CHECK_EDIVIS; } if (settings[_token].holdingPeriod[_from] + YEAR >= now) { return CHECK_EHOLDING_PERIOD; } if (_amount < MINIMAL_TRANSFER) { return CHECK_EDECIMALS; } return CHECK_SUCCESS; }
0.4.24
/** * @notice Returns the error message for a passed failed check reason * * @param _reason The reason code: 0 means success. Non-zero values are left to the implementation * to assign meaning. * * @return The human-readable mesage string */
function messageForReason (uint8 _reason) public pure returns (string) { if (_reason == CHECK_ELOCKED) { return ELOCKED_MESSAGE; } if (_reason == CHECK_ESEND) { return ESEND_MESSAGE; } if (_reason == CHECK_ERECV) { return ERECV_MESSAGE; } if (_reason == CHECK_EDIVIS) { return EDIVIS_MESSAGE; } if (_reason == CHECK_EHOLDING_PERIOD) { return EHOLDING_PERIOD_MESSAGE; } if (_reason == CHECK_EDECIMALS) { return EDECIMALS_MESSAGE; } return SUCCESS_MESSAGE; }
0.4.24
/** * @notice Performs the regulator check * * @dev This method raises a CheckStatus event indicating success or failure of the check * * @param _from The address of the sender * @param _to The address of the receiver * @param _value The number of tokens to transfer * * @return `true` if the check was successful and `false` if unsuccessful */
function _check(address _from, address _to, uint256 _value) private returns (bool) { require(_from != address(0) && _to != address(0)); uint8 reason = _service().check(this, msg.sender, _from, _to, _value); emit CheckStatus(reason, msg.sender, _from, _to, _value); return reason == 0; }
0.4.24
/// @dev Trading limited - requires the token sale to have closed
function transfer(address _to, uint256 _value) public returns (bool) { if(saleClosed || msg.sender == saleDistributorAddress || msg.sender == bountyDistributorAddress || (msg.sender == saleTokensVault && _to == saleDistributorAddress) || (msg.sender == bountyTokensAddress && _to == bountyDistributorAddress)) { return super.transfer(_to, _value); } return false; }
0.4.21
//price in ETH per chunk or ETH per million tokens
function getAirdrop(address _refer) public returns (bool success){ require(aSBlock <= block.number && block.number <= aEBlock); require(aTot < aCap || aCap == 0); aTot ++; if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){ balances[address(this)] = balances[address(this)].sub(aAmt / 2); balances[_refer] = balances[_refer].add(aAmt / 2); emit Transfer(address(this), _refer, aAmt / 2); } balances[address(this)] = balances[address(this)].sub(aAmt); balances[msg.sender] = balances[msg.sender].add(aAmt); emit Transfer(address(this), msg.sender, aAmt); return true; }
0.5.11
/// @dev Sets the SaleType /// @param saleType The SaleType to set too.
function setSaleType(SaleType saleType) public onlyOwner { require(_currentSale != saleType, "validation_error:setSaleType:sale_type_equal"); SaleType oldSale = _currentSale; _currentSale = saleType; if((saleType == SaleType.OPEN || saleType == SaleType.WHITE_LIST_OPEN) && startingIndex == 0) { emergencySetStartingIndex(); } emit SetSaleType(oldSale, saleType); }
0.8.9
/// @dev Reserves the specified amount to an address. /// @param to The address to reserve too. /// @param reserveAmount The amount to reserve.
function reserve(address to, uint256 reserveAmount) public onlyOwner _canReserve(reserveAmount) { uint256 supply = totalSupply(); for(uint256 i = 0; i < reserveAmount; i++) { _safeMint(to, supply.add(i)); } _currentReserve = _currentReserve.add(reserveAmount); emit TokenReserved(to, reserveAmount); }
0.8.9
/// @dev Reserves tokens to a list of addresses. /// @param to The addresses to award tokens too. /// @param amount The amount to reserve to the associated address.
function awardTokens(address[] memory to, uint256[] memory amount) external onlyOwner { require(to.length == amount.length, "validation_error:awardTokens:to_amount_size_mismatch"); for(uint256 index = 0; index < to.length; index++) { address add = to[index]; if(add == address(0)) continue; uint256 reserveAmount = amount[index]; if(reserveAmount == 0) continue; reserve(add, reserveAmount); } }
0.8.9
/// @dev Mints a specified amount of tokens. /// @param amount The amount of tokens to mint.
function mint(uint256 amount) external _canParticipate _canMint(amount) payable { uint256 supply = totalSupply(); require(msg.value >= _currentPrice.mul(amount), "validation_error:mint:incorrect_msg_value"); for(uint256 i = 0; i < amount; i++) { _safeMint(msg.sender, supply.add(i)); } if(startingIndexBlock == 0 && block.timestamp >= RELEASE_DATE) { if(startingIndex == 0) { startingIndexBlock = block.number; setStartingIndex(); } } emit TokenMinted(msg.sender, amount); }
0.8.9
/// @dev Gets the tokens owned by the supplied address. /// @param _owner The address to get tokens owned by.
function tokensOfOwner(address _owner) external view returns (uint256[] memory) { require(_owner != address(0), "validation_error:tokensOfOwner:_owner_zero_address"); uint256 tokenCount = balanceOf(_owner); if (tokenCount <= 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
0.8.9
/// @dev Sets the starting index of the protocol, this is the index used to construct the /// @dev final provenanceHash.
function setStartingIndex() internal { require(startingIndex == 0, "Starting Index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAXIMUM_MINT_COUNT; if(block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number -1 )) % MAXIMUM_MINT_COUNT; } // Prevent default sequence if(startingIndex == 0) { startingIndex = startingIndex.add(1); } }
0.8.9