comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @notice Withdraw the bounty after creation of conditional payment and finding counter party */
function withdrawBounty () public { // Creator needs to have permission require(bountyPermission[msg.sender]); bountyPermission[msg.sender] = false; // Only one withdraw per creator require(!gotBounty[msg.sender]); gotBounty[msg.sender] = true; ConditionalPayment conditionalPayment = ConditionalPayment(creatorsConditionalPaymentAddress[msg.sender]); // Conditional payment needs to have at least one counter party require(conditionalPayment.countCounterparties() > 0); msg.sender.transfer(bounty); }
0.5.8
/** * @notice Owner can withdraw bounty permission if creators did not succeed to find a taker before the deadline */
function withdrawPermission (address unsuccessfulCreator) public onlyByOwner deadlineExceeded { // Unsuccessful criterium ConditionalPayment conditionalPayment = ConditionalPayment(creatorsConditionalPaymentAddress[unsuccessfulCreator]); require(conditionalPayment.countCounterparties() == 0); // Disqualify creator from bounty bountyPermission[unsuccessfulCreator] = false; creatorsConditionalPaymentAddress[msg.sender] = 0x0000000000000000000000000000000000000000; numberOfGivenBounties -= 1; }
0.5.8
//Transfer functionality/// //transfer function, every transfer runs through this function
function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between uniswapV2Router and uniswapV2Pair are tax and lock free address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } }
0.8.9
//Feeless transfer only transfers and autostakes
function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); }
0.8.9
//Total shares equals circulating supply minus excluded Balances
function _getTotalShares() public view returns (uint256){ uint256 shares=_circulatingSupply; //substracts all excluded from shares, excluded list is limited to 30 // to avoid creating a Honeypot through OutOfGas exeption for(uint i=0; i<_excludedFromStaking.length(); i++){ shares-=_balances[_excludedFromStaking.at(i)]; } return shares; }
0.8.9
//adds Token to balances, adds new ETH to the toBePaid mapping and resets staking
function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } //gets the payout before the change uint256 payment=_newDividentsOf(addr); //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; //sets newBalance _balances[addr]=newAmount; }
0.8.9
/** * This function can help owner to add larger than one addresses cap. */
function setBuyerCapBatch(address[] memory buyers, uint256[] memory amount) public onlyOwner onlyOpened { require(buyers.length == amount.length, "Presale: buyers length and amount length not match"); require(buyers.length <= 100, "Presale: the max size of batch is 100."); for(uint256 i = 0; i < buyers.length; i ++) { _buyers_[buyers[i]].cap = amount[i]; } }
0.8.7
//gets the not dividents of a staker that aren't in the toBePaid mapping //returns wrong value for excluded accounts
function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; // if theres an overflow for some unexpected reason, return 0, instead of // an exeption to still make trades possible if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; }
0.8.9
//distributes ETH between marketing share and dividends
function _distributeStake(uint256 ETHAmount) private { // Deduct marketing Tax uint256 marketingSplit = (ETHAmount * StakingShare) / 100; uint256 amount = ETHAmount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); //when there are 0 shares, add everything to marketing budget if (totalShares == 0) { marketingBalance += amount; }else{ //Increases profit per share based on current total shares profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } }
0.8.9
//withdraws all dividents of address
function claimBTC(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); //WETH path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //WETH _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, path, addr, block.timestamp); emit OnWithdrawBTC(amount, addr); _isWithdrawing=false; }
0.8.9
//swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact
function _swapContractToken() private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_stakingTax; uint256 tokenToSwap = _setSellAmount; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance, so swap won't touch any staked ETH uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for Staking uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining ETH between stakers and Marketing _distributeStake(distributeETH); }
0.8.9
//Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot)
function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyOwner{ //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP require(newSellLimit<_circulatingSupply/100); //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; //Calculates the target Limits based on supply uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider; uint256 targetSellLimit=_circulatingSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; }
0.8.9
//Release Liquidity Tokens once unlock time is over
function TeamReleaseLiquidity() public onlyOwner { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); //Liquidity release if something goes wrong at start liquidityToken.transfer(TeamWallet, amount); }
0.8.9
//Removes Liquidity once unlock Time is over,
function TeamRemoveLiquidity(bool addToStaking) public onlyOwner{ //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); liquidityToken.approve(address(_uniswapV2Router),amount); //Removes Liquidity and either distributes liquidity ETH to stakers, or // adds them to marketing Balance //Token will be converted //to Liquidity and Staking ETH again uint256 initialETHBalance = address(this).balance; _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; if(addToStaking){ _distributeStake(newETHBalance); } else{ marketingBalance+=newETHBalance; } }
0.8.9
// main function which will make the investments
function LetsInvest() public payable returns(uint) { require (msg.value > 100000000000000); require (msg.sender != address(0)); uint invest_amt = msg.value; address payable investor = address(msg.sender); uint sBTCPortion = SafeMath.div(SafeMath.mul(invest_amt,sBTCPercentage),100); uint sETHPortion = SafeMath.sub(invest_amt, sBTCPortion); require (SafeMath.sub(invest_amt, SafeMath.add(sBTCPortion, sETHPortion)) ==0 ); Invest2_sBTCContract.LetsInvestin_sBTC.value(sBTCPortion)(investor); Invest2_sETHContract.LetsInvestin_sETH.value(sETHPortion)(investor); }
0.5.12
// Converts ETH to Tokens and sends new Tokens to the sender
receive () external payable { require(startDate > 0 && now.sub(startDate) <= 5 days); require(Token.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 60 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(20); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(35).div(2); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(15); } else if(now.sub(startDate) > 3 days) { amount = msg.value.mul(25).div(2); } require(amount <= Token.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // transfer the tokens. Token.transfer(msg.sender, amount); }
0.6.8
// Converts ETH to Tokens 1and sends new Tokens to the sender
function contribute() external payable { require(startDate > 0 && now.sub(startDate) <= 5 days); require(Token.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 60 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(20); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(35).div(2); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(15); } else if(now.sub(startDate) > 3 days) { amount = msg.value.mul(25).div(2); } require(amount <= Token.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // transfer the tokens. Token.transfer(msg.sender, amount); }
0.6.8
//event LogBool(uint8 id, bool value); //event LogAddress(uint8 id, address value); // Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_, address DmexOracleContract_, address poolAddress) { owner = msg.sender; feeAccount = feeAccount_; makerFee = makerFee_; takerFee = takerFee_; exchangeContract = exchangeContract_; DmexOracleContract = DmexOracleContract_; pools[poolAddress] = true; }
0.4.25
// public methods // public method to harvest all the unharvested epochs until current epoch - 1
function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _xfund.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; }
0.6.12
// internal methods
function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); }
0.6.12
/* @notice This claims your deevy bag in L2. */
function warpLoot( uint256 lootId, uint256 maxSubmissionCost, uint256 maxGas, uint256 gasPriceBid ) external payable returns (uint256) { require(msg.value > 0, "MSG_VALUE_IS_REQUIRED"); require( loot.ownerOf(lootId) == msg.sender, "SENDER_ISNT_LOOT_ID_OWNER" ); bytes memory data = abi.encodeWithSelector( IDeevyBridgeMinter.warpBag.selector, msg.sender, lootId ); uint256 ticketID = inbox.createRetryableTicket{value: msg.value}( l2Target, 0, maxSubmissionCost, msg.sender, msg.sender, maxGas, gasPriceBid, data ); lootsToTickets[lootId] = ticketID; emit RetryableTicketCreated(ticketID); return ticketID; }
0.6.12
// String helpers below were taken from Oraclize. // https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol
function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); }
0.4.24
// Called initially to bootstrap the game
function bootstrap( uint _bootstrapWinnings ) public onlyOwner returns (bool) { require(!isBootstrapped, "Game already bootstrapped"); bootstrapWinnings = _bootstrapWinnings; revenue += _bootstrapWinnings; isBootstrapped = true; startTime = block.timestamp; weth.safeTransferFrom(msg.sender, address(this), _bootstrapWinnings); return true; }
0.8.7
// Process random words from chainlink VRF2
function fulfillRandomWords( uint256 requestId, /* requestId */ uint256[] memory randomWords ) internal override { for (uint i = 0; i < randomWords.length; i++) { diceRolls[++rollCount].roll = getFormattedNumber(randomWords[i]); diceRolls[rollCount].roller = rollRequests[requestId]; // If the game was over between rolls - don't perform any of the below logic if (!isGameOver()) { if (diceRolls[rollCount].roll == winningNumber) { // User wins winner = diceRolls[rollCount]; // Transfer revenue to winner collectFees(); uint revenueSplit = getRevenueSplit(); uint winnings = revenue - feesCollected - revenueSplit; weth.safeTransfer(winner.roller, winnings); emit LogGameOver(winner.roller, winnings); } else if (diceRolls[rollCount].roll >= revenueSplitRollThreshold) { totalRevenueSplitShares += 1; revenueSplitSharesPerUser[diceRolls[rollCount].roller] += 1; } if (diceRolls[rollCount].roll != winningNumber) { int diff = getDiff(diceRolls[rollCount].roll, winningNumber); int currentWinnerDiff = getDiff(currentWinner.roll, winningNumber); if (diff <= currentWinnerDiff) { currentWinner = diceRolls[rollCount]; emit LogNewCurrentWinner(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller); } } } else emit LogDiscardedRollResult(requestId, rollCount, diceRolls[rollCount].roller); emit LogOnRollResult(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller); } }
0.8.7
// Ends a game that is past it's duration without a winner
function endGame() public returns (bool) { require( hasGameDurationElapsed() && winner.roller == address(0), "Game duration hasn't elapsed without a winner" ); winner = currentWinner; // Transfer revenue to winner collectFees(); uint revenueSplit = getRevenueSplit(); uint winnings = revenue - feesCollected - revenueSplit; weth.safeTransfer(winner.roller, winnings); emit LogGameOver(winner.roller, winnings); return true; }
0.8.7
// Allows users to collect their share of revenue split after a game is over
function collectRevenueSplit() external { require(isGameOver(), "Game isn't over"); require(revenueSplitSharesPerUser[msg.sender] > 0, "User does not have any revenue split shares"); require(revenueSplitCollectedPerUser[msg.sender] == 0, "User has already collected revenue split"); uint revenueSplit = getRevenueSplit(); uint userRevenueSplit = revenueSplit * revenueSplitSharesPerUser[msg.sender] / totalRevenueSplitShares; revenueSplitCollectedPerUser[msg.sender] = userRevenueSplit; weth.safeTransfer(msg.sender, userRevenueSplit); emit LogOnCollectRevenueSplit(msg.sender, userRevenueSplit); }
0.8.7
// Roll dice once
function rollDice() external { require(isSingleRollEnabled, "Single rolls are not currently enabled"); require(isBootstrapped, "Game is not bootstrapped"); require(!isGameOver(), "Game is over"); revenue += ticketSize; weth.safeTransferFrom(msg.sender, address(this), ticketSize); // Will revert if subscription is not set and funded. uint requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, 1 ); rollRequests[requestId] = msg.sender; emit LogNewRollRequest(requestId, msg.sender); }
0.8.7
// Approve WETH once and roll multiple times
function rollMultipleDice(uint32 times) external { require(isBootstrapped, "Game is not bootstrapped"); require(!isGameOver(), "Game is over"); require(times > 1 && times <= 5, "Should be >=1 and <=5 rolls in 1 txn"); uint total = ticketSize * times; revenue += total; weth.safeTransferFrom(msg.sender, address(this), total); // Will revert if subscription is not set and funded. uint requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, times ); rollRequests[requestId] = msg.sender; emit LogNewRollRequest(requestId, msg.sender); }
0.8.7
/** * @dev setAccessLevel for a user restricted to contract owner * @dev Ideally, check for whole number should be implemented (TODO) * @param _user address that access level is to be set for * @param _access uint256 level of access to give 0, 1, 2, 3. */
function setAccessLevel( address _user, uint256 _access ) public adminAccessLevelOnly { require( accessLevel[_user] < 4, "Cannot setAccessLevel for Admin Level Access User" ); /// owner access not allowed to be set if (_access < 0 || _access > 4) { revert("erroneous access level"); } else { accessLevel[_user] = _access; } emit AccessLevelSet(_user, _access, msg.sender); }
0.5.1
/// @dev External function to add a checklist item to our mystery set. /// Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8). /// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol) /// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner { require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first."); require(unreleasedCount() < 56, "You can't add any more checklist items."); require(_playerId < playerCount, "This player doesn't exist in our player list."); unreleasedChecklistItems.push(ChecklistItem({ playerId: _playerId, tier: _tier })); }
0.4.24
/// @dev Returns the mint limit for a given checklist item, based on its tier. /// @param _checklistId Which checklist item we need to get the limit for. /// @return How much of this checklist item we are allowed to mint.
function limitForChecklistId(uint8 _checklistId) external view returns (uint16) { RarityTier rarityTier; uint8 index; if (_checklistId < 100) { // Originals = #000 to #099 rarityTier = originalChecklistItems[_checklistId].tier; } else if (_checklistId < 200) { // Iconics = #100 to #131 index = _checklistId - 100; require(index < iconicsCount(), "This Iconics checklist item doesn't exist."); rarityTier = iconicChecklistItems[index].tier; } else { // Unreleased = #200 to max #255 index = _checklistId - 200; require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist."); rarityTier = unreleasedChecklistItems[index].tier; } return tierLimits[uint8(rarityTier)]; }
0.4.24
/// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned /// by this address. The second returns the corresponding checklist ID for each of these cards. /// There are a few places we need this info in the web app and short of being able to return an /// actual array of Cards, this is the best solution we could come up with...
function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) { uint256[] memory cardIds = ownedTokens[_owner]; uint256 cardCount = cardIds.length; uint8[] memory checklistIds = new uint8[](cardCount); for (uint256 i = 0; i < cardCount; i++) { uint256 cardId = cardIds[i]; checklistIds[i] = cards[cardId].checklistId; } return (cardIds, checklistIds); }
0.4.24
/// @dev An internal method that creates a new card and stores it. /// Emits both a CardMinted and a Transfer event. /// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol) /// @param _owner The card's first owner!
function _mintCard( uint8 _checklistId, address _owner ) internal returns (uint256) { uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId); require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!"); uint16 serialNumber = ++mintedCountForChecklistId[_checklistId]; Card memory newCard = Card({ mintTime: uint32(now), checklistId: _checklistId, serialNumber: serialNumber }); uint256 newCardId = cards.push(newCard) - 1; emit CardMinted(newCardId); _mint(_owner, newCardId); return newCardId; }
0.4.24
/// @dev Allows the contract at packSaleAddress to mint cards. /// @param _checklistId The checklist item represented by this new card. /// @param _owner The card's first owner! /// @return The new card's ID.
function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) { require(msg.sender == packSaleAddress, "Only the pack sale contract can mint here."); require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item..."); return _mintCard(_checklistId, _owner); }
0.4.24
/// @dev Allows the owner to mint cards from our Unreleased Set. /// @param _checklistId The checklist item represented by this new card. Must be >= 200. /// @param _owner The card's first owner!
function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner { require(_checklistId >= 200, "You can only use this to mint unreleased cards."); require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item..."); _mintCard(_checklistId, _owner); }
0.4.24
/// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again. /// @param _checklistId The Iconic or Unreleased card we want to remove from circulation.
function pullFromCirculation(uint8 _checklistId) external { bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress); require(ownerOrPackSale, "Only the owner or pack sale can take checklist items out of circulation."); require(_checklistId >= 100, "This function is reserved for Iconics and Unreleased sets."); outOfCirculation[_checklistId] = true; emit PulledFromCirculation(_checklistId); }
0.4.24
/// @dev Allows the maker to cancel a trade that hasn't been filled yet. /// @param _maker Address of the maker (i.e. trade creator). /// @param _makerCardId ID of the card the maker has agreed to give up. /// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) /// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi"). /// If not, then it's a card ID (e.g. "Lionel Messi #8/100"). /// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
function cancelTrade( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt) external { require(_maker == msg.sender, "Only the trade creator can cancel this trade."); bytes32 tradeHash = getTradeHash( _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt ); require(tradeStates[tradeHash] == TradeState.Valid, "This trade has already been cancelled or filled."); tradeStates[tradeHash] = TradeState.Cancelled; emit TradeCancelled(tradeHash, _maker); }
0.4.24
/// @dev Calculates Keccak-256 hash of a trade with specified parameters. /// @param _maker Address of the maker (i.e. trade creator). /// @param _makerCardId ID of the card the maker has agreed to give up. /// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) /// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi"). /// If not, then it's a card ID (e.g. "Lionel Messi #8/100"). /// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). /// @return Keccak-256 hash of trade.
function getTradeHash( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt) public view returns (bytes32) { // Hashing the contract address prevents a trade from being replayed on any new trade contract we deploy. bytes memory packed = abi.encodePacked(this, _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt); return keccak256(packed); }
0.4.24
/// @dev Verifies that a signed trade is valid. /// @param _signer Address of signer. /// @param _tradeHash Signed Keccak-256 hash. /// @param _v ECDSA signature parameter v. /// @param _r ECDSA signature parameters r. /// @param _s ECDSA signature parameters s. /// @return Validity of signature.
function isValidSignature( address _signer, bytes32 _tradeHash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (bool) { bytes memory packed = abi.encodePacked("\x19Ethereum Signed Message:\n32", _tradeHash); return _signer == ecrecover(keccak256(packed), _v, _r, _s); }
0.4.24
// Start of whitelist and free mint implementation
function FreeWhitelistMint (uint256 _beautyAmount, bytes32[] calldata _merkleProof) external payable callerIsUser { require(_beautyAmount > 0); require(saleState == SaleState.Presale, "Presale has not begun yet!"); require(whitelistMintsUsed[msg.sender] + _beautyAmount < 6, "Amount exceeds your allocation."); require(totalSupply() + _beautyAmount + amountForDevsRemaining <= collectionSize, "Exceeds max supply."); require(_verifyFreeMintStatus(msg.sender, _merkleProof), "Address not on Whitelist."); if (freeMintUsed[msg.sender] == false && freeRemaining != 0) { require(msg.value == mintPrice * (_beautyAmount - 1), "Incorrect ETH amount."); freeMintUsed[msg.sender] = true; freeRemaining -= 1; } else { require(msg.value == mintPrice * _beautyAmount, "Incorrect ETH amount."); } whitelistMintsUsed[msg.sender] += _beautyAmount; _safeMint(msg.sender, _beautyAmount); }
0.8.7
//Owner Mint function
function AllowOwnerMint(uint256 _beautyAmount) external onlyOwner { require(_beautyAmount > 0); require(_beautyAmount <= amountForDevsRemaining, "Not Enough Dev Tokens left"); amountForDevsRemaining -= _beautyAmount; require(totalSupply() + _beautyAmount <= collectionSize, "Reached Max Supply."); _safeMint(msg.sender, _beautyAmount); }
0.8.7
/** * @dev withdrawTokens allows the initial depositing user to withdraw tokens previously deposited * @param _user address of the user making the withdrawal * @param _amount uint256 of token to be withdrawn */
function withdrawTokens(address _user, uint256 _amount) public returns (bool) { // solium-ignore-next-line // require(tx.origin == _user, "tx origin does not match _user"); uint256 currentBalance = userTokenBalance[_user]; require(_amount <= currentBalance, "Withdraw amount greater than current balance"); uint256 newBalance = currentBalance.sub(_amount); require(StakeToken(token).transfer(_user, _amount), "error during token transfer"); /// Update user balance userTokenBalance[_user] = newBalance; /// update the total balance for the token totalTokenBalance = SafeMath.sub(totalTokenBalance, _amount); /// Fire event and return some goodies emit TokenWithdrawal(_user, _amount); emit UserBalanceChange(_user, currentBalance, newBalance); }
0.5.1
/** * @dev Gets current Cryptobud Price */
function getNFTPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint currentSupply = totalSupply(); if (currentSupply >= 9996) { return 10 ether; // 9996-10000 10 ETH } else if (currentSupply >= 9900) { return 2 ether; // 9900-9995 2 ETH } else if (currentSupply >= 9000) { return 0.5 ether; // 9000-9989 0.5 ETH } else if (currentSupply >= 7000) { return 0.19 ether; // 7000-8999 0.19 ETH } else if (currentSupply >= 4000) { return 0.1 ether; // 4000 - 6999 0.1 ETH } else if (currentSupply >= 2000) { return 0.05 ether; // 2000 - 3999 0.05 ETH } else if (currentSupply >= 1000) { return 0.02 ether; // 1000 - 1999 0.02 ETH } else { return 0.01 ether; // 0 - 999 0.01 ETH } }
0.7.0
/// @notice Initiates the atomic swap. /// /// @param _swapID The unique atomic swap id. /// @param _withdrawTrader The address of the withdrawing trader. /// @param _secretLock The hash of the secret (Hash Lock). /// @param _timelock The unix timestamp when the swap expires.
function initiate( bytes32 _swapID, address _withdrawTrader, bytes32 _secretLock, uint256 _timelock ) external onlyInvalidSwaps(_swapID) payable { // Store the details of the swap. Swap memory swap = Swap({ timelock: _timelock, value: msg.value, ethTrader: msg.sender, withdrawTrader: _withdrawTrader, secretLock: _secretLock, secretKey: 0x0 }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; // Logs open event emit LogOpen(_swapID, _withdrawTrader, _secretLock); }
0.4.24
/// @notice Redeems an atomic swap. /// /// @param _swapID The unique atomic swap id. /// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, bytes32 _secretKey) external onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) { // Close the swap. Swap memory swap = swaps[_swapID]; swaps[_swapID].secretKey = _secretKey; swapStates[_swapID] = States.CLOSED; /* solium-disable-next-line security/no-block-members */ redeemedAt[_swapID] = now; // Transfer the ETH funds from this contract to the withdrawing trader. swap.withdrawTrader.transfer(swap.value); // Logs close event emit LogClose(_swapID, _secretKey); }
0.4.24
/// @notice Refunds an atomic swap. /// /// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) external onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) { // Expire the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.EXPIRED; // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.value); // Logs expire event emit LogExpire(_swapID); }
0.4.24
/// @dev Withdraws ERC20 tokens from this contract /// (take care of reentrancy attack risk mitigation)
function _claimErc20( address token, address to, uint256 amount ) internal { // solhint-disable avoid-low-level-calls (bool success, bytes memory data) = token.call( abi.encodeWithSelector(SELECTOR_TRANSFER, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "claimErc20: TRANSFER_FAILED" ); }
0.8.4
/** * @dev Mints Masks */
function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
0.7.0
// Accept given `quantity` of an offer. Transfers funds from caller to // offer maker, and from market to caller.
function buy(uint id, uint quantity) public can_buy(id) synchronized returns (bool) { OfferInfo memory offer = offers[id]; uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt; require(uint128(spend) == spend); require(uint128(quantity) == quantity); // For backwards semantic compatibility. if (quantity == 0 || spend == 0 || quantity > offer.pay_amt || spend > offer.buy_amt) { return false; } offers[id].pay_amt = sub(offer.pay_amt, quantity); offers[id].buy_amt = sub(offer.buy_amt, spend); require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) ); require( offer.pay_gem.transfer(msg.sender, quantity) ); LogItemUpdate(id); LogTake( bytes32(id), keccak256(offer.pay_gem, offer.buy_gem), offer.owner, offer.pay_gem, offer.buy_gem, msg.sender, uint128(quantity), uint128(spend), uint64(now) ); LogTrade(quantity, offer.pay_gem, spend, offer.buy_gem); if (offers[id].pay_amt == 0) { delete offers[id]; } return true; }
0.4.25
// Cancel an offer. Refunds offer maker.
function cancel(uint id) public can_cancel(id) synchronized returns (bool success) { // read-only offer. Modify an offer by directly accessing offers[id] OfferInfo memory offer = offers[id]; delete offers[id]; require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) ); LogItemUpdate(id); LogKill( bytes32(id), keccak256(offer.pay_gem, offer.buy_gem), offer.owner, offer.pay_gem, offer.buy_gem, uint128(offer.pay_amt), uint128(offer.buy_amt), uint64(now) ); success = true; }
0.4.25
// Make a new offer. Takes funds from the caller into market escrow.
function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem) public can_offer synchronized returns (uint id) { require(uint128(pay_amt) == pay_amt); require(uint128(buy_amt) == buy_amt); require(pay_amt > 0); require(pay_gem != ERC20(0x0)); require(buy_amt > 0); require(buy_gem != ERC20(0x0)); require(pay_gem != buy_gem); OfferInfo memory info; info.pay_amt = pay_amt; info.pay_gem = pay_gem; info.buy_amt = buy_amt; info.buy_gem = buy_gem; info.owner = msg.sender; info.timestamp = uint64(now); id = _next_id(); offers[id] = info; require( pay_gem.transferFrom(msg.sender, this, pay_amt) ); LogItemUpdate(id); LogMake( bytes32(id), keccak256(pay_gem, buy_gem), msg.sender, pay_gem, buy_gem, uint128(pay_amt), uint128(buy_amt), uint64(now) ); }
0.4.25
// Make a new offer. Takes funds from the caller into market escrow. // // If matching is enabled: // * creates new offer without putting it in // the sorted list. // * available to authorized contracts only! // * keepers should call insert(id,pos) // to put offer in the sorted list. // // If matching is disabled: // * calls expiring market's offer(). // * available to everyone without authorization. // * no sorting is done. //
function offer( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //taker (ask) buy how much ERC20 buy_gem //taker (ask) buy which token ) public returns (uint) { require(!locked, "Reentrancy attempt"); var fn = matchingEnabled ? _offeru : super.offer; return fn(pay_amt, pay_gem, buy_amt, buy_gem); }
0.4.25
/** * @notice Deploys a new proxy instance that DELEGATECALLs this contract * @dev Must be called on the implementation (reverts if a proxy is called) */
function createProxy() external returns (address proxy) { _throwProxy(); // CREATE an EIP-1167 proxy instance with the target being this contract bytes20 target = bytes20(address(this)); assembly { let initCode := mload(0x40) mstore( initCode, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(initCode, 0x14), target) mstore( add(initCode, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) // note, 0x37 (55 bytes) is the init bytecode length // while the deployed bytecode length is 0x2d (45 bytes) only proxy := create(0, initCode, 0x37) } // Write this contract address into the proxy' "implementation" slot // (reentrancy attack impossible - this contract called) ProxyFactory(proxy).initProxy(address(this)); emit NewProxy(proxy); }
0.8.4
/// @dev Returns true if called on a proxy instance
function _isProxy() internal view virtual returns (bool) { // for a DELEGATECALLed contract, `this` and `extcodesize` // are the address and the code size of the calling contract // (for a CALLed contract, they are ones of that called contract) uint256 _size; address _this = address(this); assembly { _size := extcodesize(_this) } // shall be the same as the one the `createProxy` generates return _size == 45; }
0.8.4
// 20 *10^7 MH total
function Mohi() public { balances[msg.sender] = total * 50/100; Transfer(0x0, msg.sender, total); balances[0x7ae3AB28486B245A7Eae3A9e15c334B61690D4B9] = total * 5 / 100; balances[0xBd9E735e84695A825FB0051B02514BA36C57112E] = total * 5 / 100; balances[0x6a5C43220cE62A6A5D11e2D11Cc9Ee9660893407] = total * 5 / 100; }
0.4.24
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IChickenPlateStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IChickenPlateStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); earn(_want, _amount); } } }
0.6.12
//insert offer into the sorted list //keepers need to use this function
function insert( uint id, //maker (ask) id uint pos //position to insert into ) public returns (bool) { require(!locked, "Reentrancy attempt"); require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted require(isActive(id)); //make sure offers[id] is active _hide(id); //remove offer from unsorted offers list _sort(id, pos); //put offer into the sorted offers list LogInsert(msg.sender, id); return true; }
0.4.25
//set the minimum sell amount for a token // Function is used to avoid "dust offers" that have // very small amount of tokens to sell, and it would // cost more gas to accept the offer, than the value // of tokens received.
function setMinSell( ERC20 pay_gem, //token to assign minimum sell amount to uint dust //maker (ask) minimum sell amount ) public auth note returns (bool) { _dust[pay_gem] = dust; LogMinSell(pay_gem, dust); return true; }
0.4.25
//--Risk-parameter-config-------------------------------------------
function mold(bytes32 param, uint val) public note auth { if (param == 'cap') cap = val; else if (param == 'mat') { require(val >= RAY); mat = val; } else if (param == 'tax') { require(val >= RAY); drip(); tax = val; } else if (param == 'fee') { require(val >= RAY); drip(); fee = val; } else if (param == 'axe') { require(val >= RAY); axe = val; } else if (param == 'gap') { require(val >= WAD); gap = val; } else return; }
0.4.19
//find the id of the next higher offer after offers[id]
function _find(uint id) internal view returns (uint) { require( id > 0 ); address buy_gem = address(offers[id].buy_gem); address pay_gem = address(offers[id].pay_gem); uint top = _best[pay_gem][buy_gem]; uint old_top = 0; // Find the larger-than-id order whose successor is less-than-id. while (top != 0 && _isPricedLtOrEq(id, top)) { old_top = top; top = _rank[top].prev; } return old_top; }
0.4.25
// force settlement of the system at a given price (sai per gem). // This is nearly the equivalent of biting all cups at once. // Important consideration: the gems associated with free skr can // be tapped to make sai whole.
function cage(uint price) internal { require(!tub.off() && price != 0); caged = era(); tub.drip(); // collect remaining fees tap.heal(); // absorb any pending fees fit = rmul(wmul(price, vox.par()), tub.per()); // Most gems we can get per sai is the full balance of the tub. // If there is no sai issued, we should still be able to cage. if (sai.totalSupply() == 0) { fix = rdiv(WAD, price); } else { fix = min(rdiv(WAD, price), rdiv(tub.pie(), sai.totalSupply())); } tub.cage(fit, rmul(fix, sai.totalSupply())); tap.cage(fix); tap.vent(); // burn pending sale skr }
0.4.19
// Liquidation Ratio 150% // Liquidation Penalty 13% // Stability Fee 0.05% // PETH Fee 0% // Boom/Bust Spread -3% // Join/Exit Spread 0% // Debt Ceiling 0
function configParams() public auth { require(step == 3); tub.mold("cap", 0); tub.mold("mat", ray(1.5 ether)); tub.mold("axe", ray(1.13 ether)); tub.mold("fee", 1000000000158153903837946257); // 0.5% / year tub.mold("tax", ray(1 ether)); tub.mold("gap", 1 ether); tap.mold("gap", 0.97 ether); step += 1; }
0.4.19
// Make a new offer without putting it in the sorted list. // Takes funds from the caller into market escrow. // ****Available to authorized contracts only!********** // Keepers should call insert(id,pos) to put offer in the sorted list.
function _offeru( uint pay_amt, //maker (ask) sell how much ERC20 pay_gem, //maker (ask) sell which token uint buy_amt, //maker (ask) buy how much ERC20 buy_gem //maker (ask) buy which token ) internal returns (uint id) { require(_dust[pay_gem] <= pay_amt); id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem); _near[id] = _head; _head = id; LogUnsortedOffer(id); }
0.4.25
//put offer into the sorted list
function _sort( uint id, //maker (ask) id uint pos //position to insert into ) internal { require(isActive(id)); address buy_gem = address(offers[id].buy_gem); address pay_gem = address(offers[id].pay_gem); uint prev_id; //maker (ask) id pos = pos == 0 || offers[pos].pay_gem != pay_gem || offers[pos].buy_gem != buy_gem || !isOfferSorted(pos) ? _find(id) : _findpos(id, pos); if (pos != 0) { //offers[id] is not the highest offer //requirement below is satisfied by statements above //require(_isPricedLtOrEq(id, pos)); prev_id = _rank[pos].prev; _rank[pos].prev = id; _rank[id].next = pos; } else { //offers[id] is the highest offer prev_id = _best[pay_gem][buy_gem]; _best[pay_gem][buy_gem] = id; } if (prev_id != 0) { //if lower offer does exist //requirement below is satisfied by statements above //require(!_isPricedLtOrEq(id, prev_id)); _rank[prev_id].next = id; _rank[id].prev = prev_id; } _span[pay_gem][buy_gem]++; LogSortedOffer(id); }
0.4.25
// Remove offer from the sorted list (does not cancel offer)
function _unsort( uint id //id of maker (ask) offer to remove from sorted list ) internal returns (bool) { address buy_gem = address(offers[id].buy_gem); address pay_gem = address(offers[id].pay_gem); require(_span[pay_gem][buy_gem] > 0); require(_rank[id].delb == 0 && //assert id is in the sorted list isOfferSorted(id)); if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer require(_rank[_rank[id].next].prev == id); _rank[_rank[id].next].prev = _rank[id].prev; } else { //offers[id] is the highest offer _best[pay_gem][buy_gem] = _rank[id].prev; } if (_rank[id].prev != 0) { //offers[id] is not the lowest offer require(_rank[_rank[id].prev].next == id); _rank[_rank[id].prev].next = _rank[id].next; } _span[pay_gem][buy_gem]--; _rank[id].delb = block.number; //mark _rank[id] for deletion return true; }
0.4.25
/// @notice Backup function for activating token purchase /// requires sender to be a member of the group or CLevel /// @param _tokenId The ID of the Token group
function activatePurchase(uint256 _tokenId) external whenNotPaused { var group = tokenIndexToGroup[_tokenId]; require(group.addressToContribution[msg.sender] > 0 || msg.sender == ceoAddress || msg.sender == cooAddress1 || msg.sender == cooAddress2 || msg.sender == cooAddress3 || msg.sender == cfoAddress); // Safety check that enough money has been contributed to group var price = linkedContract.priceOf(_tokenId); require(group.contributedBalance >= price); // Safety check that token had not be purchased yet require(group.purchasePrice == 0); _purchase(_tokenId, price); }
0.4.18
/// @notice Allow user to leave purchase group; note that their contribution /// will be added to their withdrawable balance, and not directly refunded. /// User can call withdrawBalance to retrieve funds. /// @param _tokenId The ID of the Token purchase group to be left
function leaveTokenGroup(uint256 _tokenId) external whenNotPaused { address userAdd = msg.sender; var group = tokenIndexToGroup[_tokenId]; var contributor = userAddressToContributor[userAdd]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(userAdd)); // Safety check to make sure group exists; require(group.exists); // Safety check to make sure group hasn't purchased token already require(group.purchasePrice == 0); // Safety checks to ensure contributor has contributed to group require(group.addressToContributorArrIndex[userAdd] > 0); require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0); uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd); _clearGroupRecordInContributor(_tokenId, userAdd); userAddressToContributor[userAdd].withdrawableBalance += refundBalance; FundsDeposited(userAdd, refundBalance); LeaveGroup( _tokenId, userAdd, tokenIndexToGroup[_tokenId].contributedBalance, refundBalance ); }
0.4.18
/// @notice Allow user to leave purchase group; note that their contribution /// and any funds they have in their withdrawableBalance will transfered to them. /// @param _tokenId The ID of the Token purchase group to be left
function leaveTokenGroupAndWithdrawBalance(uint256 _tokenId) external whenNotPaused { address userAdd = msg.sender; var group = tokenIndexToGroup[_tokenId]; var contributor = userAddressToContributor[userAdd]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(userAdd)); // Safety check to make sure group exists; require(group.exists); // Safety check to make sure group hasn't purchased token already require(group.purchasePrice == 0); // Safety checks to ensure contributor has contributed to group require(group.addressToContributorArrIndex[userAdd] > 0); require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0); uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd); _clearGroupRecordInContributor(_tokenId, userAdd); userAddressToContributor[userAdd].withdrawableBalance += refundBalance; FundsDeposited(userAdd, refundBalance); _withdrawUserFunds(userAdd); LeaveGroup( _tokenId, userAdd, tokenIndexToGroup[_tokenId].contributedBalance, refundBalance ); }
0.4.18
/// @dev In the event of needing a fork, this function moves all /// of a group's contributors' contributions into their withdrawable balance. /// @notice Group is dissolved after fn call /// @param _tokenId The ID of the Token purchase group
function dissolveTokenGroup(uint256 _tokenId) external onlyCOO whenForking { var group = tokenIndexToGroup[_tokenId]; // Safety check to make sure group exists and had not purchased a token require(group.exists); require(group.purchasePrice == 0); for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) { address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i]; var userContribution = group.addressToContribution[userAdd]; _clearGroupRecordInContributor(_tokenId, userAdd); // clear contributor record on group tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0; tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0; // move contributor's contribution to their withdrawable balance userAddressToContributor[userAdd].withdrawableBalance += userContribution; ProceedsDeposited(_tokenId, userAdd, userContribution); } activeGroups -= 1; tokenIndexToGroup[_tokenId].exists = false; }
0.4.18
/// @dev Backup fn to allow distribution of funds after sale, /// for the special scenario where an alternate sale platform is used; /// @notice Group is dissolved after fn call /// @param _tokenId The ID of the Token purchase group /// @param _amount Funds to be distributed
function distributeCustomSaleProceeds(uint256 _tokenId, uint256 _amount) external onlyCOO { var group = tokenIndexToGroup[_tokenId]; // Safety check to make sure group exists and had purchased the token require(group.exists); require(group.purchasePrice > 0); require(_amount > 0); _distributeProceeds(_tokenId, _amount); }
0.4.18
/// @dev Distribute funds after a token is sold. /// Group is dissolved after fn call /// @param _tokenId The ID of the Token purchase group
function distributeSaleProceeds(uint256 _tokenId) external onlyCOO { var group = tokenIndexToGroup[_tokenId]; // Safety check to make sure group exists and had purchased the token require(group.exists); require(group.purchasePrice > 0); // Safety check to make sure token had been sold uint256 currPrice = linkedContract.priceOf(_tokenId); uint256 soldPrice = _newPrice(group.purchasePrice); require(currPrice > soldPrice); uint256 paymentIntoContract = uint256(SafeMath.div(SafeMath.mul(soldPrice, 94), 100)); _distributeProceeds(_tokenId, paymentIntoContract); }
0.4.18
/// @dev Backup fn to allow transfer of token out of /// contract, for use where a purchase group wants to use an alternate /// selling platform /// @param _tokenId The ID of the Token purchase group /// @param _to Address to transfer token to
function transferToken(uint256 _tokenId, address _to) external onlyCOO { var group = tokenIndexToGroup[_tokenId]; // Safety check to make sure group exists and had purchased the token require(group.exists); require(group.purchasePrice > 0); linkedContract.transfer(_to, _tokenId); }
0.4.18
/// @dev Withdraws sale commission, CFO-only functionality /// @param _to Address for commission to be sent to
function withdrawCommission(address _to) external onlyCFO { uint256 balance = commissionBalance; address transferee = (_to == address(0)) ? cfoAddress : _to; commissionBalance = 0; if (balance > 0) { transferee.transfer(balance); } FundsWithdrawn(transferee, balance); }
0.4.18
/// @dev Clears record of a Contributor from a Group's record /// @param _tokenId Token ID of Group to be cleared /// @param _userAdd Address of Contributor
function _clearContributorRecordInGroup(uint256 _tokenId, address _userAdd) private returns (uint256 refundBalance) { var group = tokenIndexToGroup[_tokenId]; // Index was saved is 1 + the array's index, b/c 0 is the default value // in a mapping. uint cIndex = group.addressToContributorArrIndex[_userAdd] - 1; uint lastCIndex = group.contributorArr.length - 1; refundBalance = group.addressToContribution[_userAdd]; // clear contribution record in group tokenIndexToGroup[_tokenId].addressToContributorArrIndex[_userAdd] = 0; tokenIndexToGroup[_tokenId].addressToContribution[_userAdd] = 0; // move address in last position to deleted contributor's spot if (lastCIndex > 0) { tokenIndexToGroup[_tokenId].addressToContributorArrIndex[group.contributorArr[lastCIndex]] = cIndex; tokenIndexToGroup[_tokenId].contributorArr[cIndex] = group.contributorArr[lastCIndex]; } tokenIndexToGroup[_tokenId].contributorArr.length -= 1; tokenIndexToGroup[_tokenId].contributedBalance -= refundBalance; }
0.4.18
/** * @notice Stake the staking token for the token to be paid as reward. */
function stake(address token, uint128 amount) external override nonReentrant updateTerm(token) updateReward(token, msg.sender) { if (_accountInfo[token][msg.sender].userTerm < _currentTerm[token]) { return; } require(amount != 0, "staking amount should be positive number"); _updVoteAdd(msg.sender, amount); _stake(msg.sender, token, amount); _stakingToken.safeTransferFrom(msg.sender, address(this), amount); }
0.7.1
/// @dev Redistribute proceeds from token purchase /// @param _tokenId Token ID of token to be purchased /// @param _amount Amount paid into contract for token
function _distributeProceeds(uint256 _tokenId, uint256 _amount) private { uint256 fundsForDistribution = uint256(SafeMath.div(SafeMath.mul(_amount, distributionNumerator), distributionDenominator)); uint256 commission = _amount; for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) { address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i]; // calculate contributor's sale proceeds and add to their withdrawable balance uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(fundsForDistribution, tokenIndexToGroup[_tokenId].addressToContribution[userAdd]), tokenIndexToGroup[_tokenId].contributedBalance)); _clearGroupRecordInContributor(_tokenId, userAdd); // clear contributor record on group tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0; tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0; commission -= userProceeds; userAddressToContributor[userAdd].withdrawableBalance += userProceeds; ProceedsDeposited(_tokenId, userAdd, userProceeds); } commissionBalance += commission; Commission(_tokenId, commission); activeGroups -= 1; tokenIndexToGroup[_tokenId].exists = false; tokenIndexToGroup[_tokenId].contributorArr.length = 0; tokenIndexToGroup[_tokenId].contributedBalance = 0; tokenIndexToGroup[_tokenId].purchasePrice = 0; }
0.4.18
/// @dev Calculates next price of celebrity token /// @param _oldPrice Previous price
function _newPrice(uint256 _oldPrice) private view returns (uint256 newPrice) { if (_oldPrice < firstStepLimit) { // first stage newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 200), 94); } else if (_oldPrice < secondStepLimit) { // second stage newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 120), 94); } else { // third stage newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 115), 94); } }
0.4.18
/** * @notice Withdraw the staking token for the token to be paid as reward. */
function withdraw(address token, uint128 amount) external override nonReentrant updateTerm(token) updateReward(token, msg.sender) { if (_accountInfo[token][msg.sender].userTerm < _currentTerm[token]) { return; } require(amount != 0, "withdrawing amount should be positive number"); _updVoteSub(msg.sender, amount); _withdraw(msg.sender, token, amount); _stakingToken.safeTransfer(msg.sender, amount); }
0.7.1
/** * @notice Receive the reward for your staking in the token. */
function receiveReward(address token) external override nonReentrant updateTerm(token) updateReward(token, msg.sender) returns (uint256 rewards) { rewards = _accountInfo[token][msg.sender].rewards; if (rewards != 0) { _totalRemainingRewards[token] = _totalRemainingRewards[token].sub(rewards); // subtract the total unpaid reward _accountInfo[token][msg.sender].rewards = 0; if (token == ETH_ADDRESS) { _transferETH(msg.sender, rewards); } else { IERC20(token).safeTransfer(msg.sender, rewards); } emit RewardPaid(token, msg.sender, rewards); } }
0.7.1
//THE ONLY ADMIN FUNCTIONS ^^^^
function sqrt(uint y) public pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } }
0.6.12
/// @notice Allots a new stake out of the stake of the message sender /// @dev Stakeholder only may call
function splitStake(address newHolder, uint256 newAmount) external { address holder = msg.sender; require(newHolder != holder, "PStakes: duplicated address"); Stake memory stake = _getStake(holder); require(newAmount <= stake.allocated, "PStakes: too large allocated"); uint256 updAmount = uint256(stake.allocated) - newAmount; uint256 updReleased = (uint256(stake.released) * updAmount) / uint256(stake.allocated); stakes[holder] = Stake(_safe96(updAmount), _safe96(updReleased)); emit StakeSplit(holder, updAmount, updReleased); uint256 newVested = uint256(stake.released) - updReleased; stakes[newHolder] = Stake(_safe96(newAmount), _safe96(newVested)); emit StakeSplit(newHolder, newAmount, newVested); }
0.8.4
////////////////// //// Owner //// ////////////////// /// @notice Inits the contract and adds stakes /// @dev Owner only may call on a proxy (but not on the implementation)
function addStakes( uint256 _poolId, address[] calldata holders, uint256[] calldata allocations, uint256 unallocated ) external onlyOwner { if (allocation == 0) { _init(_poolId); } else { require(_poolId == poolId, "PStakes: pool mismatch"); } uint256 nEntries = holders.length; require(nEntries == allocations.length, "PStakes: length mismatch"); uint256 updAllocated = uint256(allocated); for (uint256 i = 0; i < nEntries; i++) { _throwZeroHolderAddress(holders[i]); require( stakes[holders[i]].allocated == 0, "PStakes: holder exists" ); require(allocations[i] > 0, "PStakes: zero allocation"); updAllocated += allocations[i]; stakes[holders[i]] = Stake(_safe96(allocations[i]), 0); emit StakeAdded(holders[i], allocations[i]); } require( updAllocated + unallocated == allocation, "PStakes: invalid allocation" ); allocated = _safe96(updAllocated); }
0.8.4
/// @notice Withdraws accidentally sent token from this contract /// @dev Owner may call only
function claimErc20( address claimedToken, address to, uint256 amount ) external onlyOwner nonReentrant { IERC20 vestedToken = IERC20(address(_getToken())); if (claimedToken == address(vestedToken)) { uint256 balance = vestedToken.balanceOf(address(this)); require( balance - amount >= allocation - released, "PStakes: too big amount" ); } _claimErc20(claimedToken, to, amount); }
0.8.4
/// @notice Removes the contract from blockchain when tokens are released /// @dev Owner only may call on a proxy (but not on the implementation)
function removeContract() external onlyOwner { // avoid accidental removing of the implementation _throwImplementation(); require(allocation == released, "PStakes: unpaid stakes"); IERC20 vestedToken = IERC20(address(_getToken())); uint256 balance = vestedToken.balanceOf(address(this)); require(balance == 0, "PStakes: non-zero balance"); selfdestruct(payable(msg.sender)); }
0.8.4
/// @notice Initialize the contract /// @dev May be called on a proxy only (but not on the implementation)
function _init(uint256 _poolId) internal { _throwImplementation(); require(_poolId < 2**16, "PStakes:unsafePoolId"); IVestingPools pools = _getVestingPools(); address wallet = pools.getWallet(_poolId); require(wallet == address(this), "PStakes:invalidPool"); PoolParams memory pool = pools.getPool(_poolId); require(pool.sAllocation != 0, "PStakes:zeroPool"); poolId = uint16(_poolId); allocation = _safe96(uint256(pool.sAllocation) * SCALE); }
0.8.4
/// @dev Returns amount that may be released for the given stake and factor
function _releasableAmount(Stake memory stake, uint256 _factor) internal pure returns (uint256) { uint256 share = (_factor * uint256(stake.allocated)) / SCALE; if (share > stake.allocated) { // imprecise division safeguard share = uint256(stake.allocated); } return share - uint256(stake.released); }
0.8.4
/// @dev Sends the releasable amount of the specified placeholder
function _withdraw(address holder) internal { Stake memory stake = _getStake(holder); uint256 releasable = _releasableAmount(stake, uint256(factor)); require(releasable > 0, "PStakes: nothing to withdraw"); stakes[holder].released = _safe96(uint256(stake.released) + releasable); released = _safe96(uint256(released) + releasable); // (reentrancy attack impossible - known contract called) require(_getToken().transfer(holder, releasable), "PStakes:E1"); emit Released(holder, releasable); }
0.8.4
/// @dev Gets collateral balance deposited into Vesper Grow Pool
function _getCollateralBalance() internal view returns (uint256) { uint256 _totalSupply = vToken.totalSupply(); // avoids division by zero error when pool is empty return (_totalSupply != 0) ? (vToken.totalValue() * vToken.balanceOf(address(this))) / _totalSupply : 0; }
0.8.3
// When we add a shortable pynth, we need to know the iPynth as well // This is so we can get the proper skew for the short rate.
function addShortablePynths(bytes32[2][] calldata requiredPynthAndInverseNamesInResolver, bytes32[] calldata pynthKeys) external onlyOwner { require(requiredPynthAndInverseNamesInResolver.length == pynthKeys.length, "Input array length mismatch"); for (uint i = 0; i < requiredPynthAndInverseNamesInResolver.length; i++) { // setting these explicitly for clarity // Each entry in the array is [Pynth, iPynth] bytes32 pynth = requiredPynthAndInverseNamesInResolver[i][0]; bytes32 iPynth = requiredPynthAndInverseNamesInResolver[i][1]; if (!_shortablePynths.contains(pynth)) { // Add it to the address set lib. _shortablePynths.add(pynth); // store the mapping to the iPynth so we can get its total supply for the borrow rate. pynthToInversePynth[pynth] = iPynth; emit ShortablePynthAdded(pynth); // now the associated pynth key to the CollateralManagerState state.addShortCurrency(pynthKeys[i]); } } rebuildCache(); }
0.5.16
//A mapping to store the player pairs in private rooms based on keccak256 ids generated locally //constructor
function Lottery() public{ owner = msg.sender; player_count = 0; ante = 0.054 ether; required_number_players = 2; winner_percentage = 98; oraclize_setProof(proofType_Ledger); oracle_price = 0.003 ether; oraclize_gas = 285000; private_rooms_index=0; paused = false; ticket_price = ante + oracle_price; }
0.4.21
// function when someone gambles a.k.a sends ether to the contract
function buy() whenNotPaused payable public{ // No arguments are necessary, all // information is already part of // the transaction. The keyword payable // is required for the function to // be able to receive Ether. // If the bet is not equal to the ante + the oracle price, // send the money back. require (msg.value >= ante + oracle_price);//give it back, revert state changes, abnormal stop require (player_count <2); //make sure that the counter was reset if(msg.value > (ante+oracle_price)) { msg.sender.transfer(msg.value - ante - oracle_price); //If any extra eteher gets transferred return it back to the sender } player_count +=1; if (player_count == 1) { players.player1 = msg.sender; } if (player_count == 2) { players.player2 = msg.sender; ShowPlayers (players.player1,players.player2); update(); player_count =0; } }
0.4.21
/* Address => (productName => amount) */
function TestConf () { name = "TestConf"; totalSupply = 1000000; initialIssuance = totalSupply; owner = 0x443B9375536521127DBfABff21f770e4e684475d; currentEthPrice = 20000; /* TODO: Oracle */ currentTokenPrice = 100; /* In cents */ symbol = "TEST1"; balances[owner] = 100; }
0.4.14
/** * @dev Mint new quantity amount of nfts */
function mint(uint quantity) public payable isOpen notPaused { require(quantity > 0, "You can't mint 0"); require(quantity <= maxPurchaseSize, "Exceeds max per transaction"); require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough token left"); uint256 price = mintPrice.mul(quantity); require(msg.value >= price, "Value below order price"); for(uint i = 0; i < quantity; i++){ _safeMint(msg.sender, totalSupply().add(1)); } uint256 remaining = msg.value.sub(price); if (remaining > 0) { (bool success, ) = msg.sender.call{value: remaining}(""); require(success); } }
0.8.4
/** * @dev Returns all the token IDs owned by address who */
function tokensOfAddress(address who) external view returns(uint256[] memory) { uint tokenCount = balanceOf(who); uint256[] memory tokensId = new uint256[](tokenCount); for(uint i = 0; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(who, i); } return tokensId; }
0.8.4
/** * @dev Mint new quantity amount of nfts for specific address * Bypass pause modifier */
function ownerMint(uint quantity) public ownersOnly { require(quantity > 0, "You can't mint 0"); require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough token left"); for(uint i = 0; i < quantity; i++){ _safeMint(msg.sender, totalSupply().add(1)); } }
0.8.4
// Address of peg contract (to reject direct transfers)
function MinimalToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, address _peg ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; peg = _peg; }
0.4.19
//---------------------------------------------- // [public] tokenURI //----------------------------------------------
function tokenURI( uint256 tokenId ) public view override returns (string memory) { require( _exists( tokenId ), "nonexistent token" ); // 修復データがあれば string memory url = repairedUrl( tokenId ); if( bytes(url).length > 0 ){ return( url ); } uint256 at = ID_PHASE_MAX; for( uint256 i=0; i<ID_PHASE_MAX; i++ ){ if( tokenId >= _arr_id_offset[i] && tokenId < (_arr_id_offset[i]+_arr_num_mintable[i]) ){ at = i; break; } } require( at < ID_PHASE_MAX, "invalid phase" ); // ここまできたらリリース時のメタを返す string memory strId = LibString.toString( tokenId ); return( string( abi.encodePacked( _arr_base_url[at], strId ) ) ); }
0.8.7
// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, arbGasSpeedLimitPerBlock, baseStake ] // connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]
function initialize( bytes32 _machineHash, uint256[4] calldata _rollupParams, address _stakeToken, address _owner, bytes calldata _extraConfig, address[6] calldata connectedContracts, address[2] calldata _facets, uint256[2] calldata sequencerInboxParams ) public { require(confirmPeriodBlocks == 0, "ALREADY_INIT"); require(_rollupParams[0] != 0, "BAD_CONF_PERIOD"); delayedBridge = IBridge(connectedContracts[0]); sequencerBridge = ISequencerInbox(connectedContracts[1]); outbox = IOutbox(connectedContracts[2]); delayedBridge.setOutbox(connectedContracts[2], true); rollupEventBridge = RollupEventBridge(connectedContracts[3]); delayedBridge.setInbox(connectedContracts[3], true); rollupEventBridge.rollupInitialized( _rollupParams[0], _rollupParams[2], _rollupParams[3], _stakeToken, _owner, _extraConfig ); challengeFactory = IChallengeFactory(connectedContracts[4]); nodeFactory = INodeFactory(connectedContracts[5]); INode node = createInitialNode(_machineHash); initializeCore(node); confirmPeriodBlocks = _rollupParams[0]; extraChallengeTimeBlocks = _rollupParams[1]; arbGasSpeedLimitPerBlock = _rollupParams[2]; baseStake = _rollupParams[3]; owner = _owner; // A little over 15 minutes minimumAssertionPeriod = 75; challengeExecutionBisectionDegree = 400; sequencerInboxMaxDelayBlocks = sequencerInboxParams[0]; sequencerInboxMaxDelaySeconds = sequencerInboxParams[1]; // facets[0] == admin, facets[1] == user facets = _facets; (bool success, ) = _facets[1].delegatecall( abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken) ); require(success, "FAIL_INIT_FACET"); emit RollupCreated(_machineHash); }
0.6.11
/** ========== Internal Helpers ========== */
function _mint(address dst, uint256 rawAmount) internal virtual { require(dst != address(0), "mint to the zero address"); uint96 amount = safe96(rawAmount); _totalSupply = add96(_totalSupply, amount, "mint amount overflows"); balances[dst] += amount; // add96 not needed because totalSupply does not overflow emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); }
0.7.6
/* * Function to mint new NFTs when breeding */
function breed( uint256 idSecond ) public payable { require(NFTPrice == msg.value, "Ether value sent is not correct"); require(isActive, "Contract is not active"); require(BAYC.balanceOf(msg.sender)>=1,"You are not BAYC"); require(!hasBreed[idSecond],"1 MGDC can breed only once"); require(MGDCisBreeding[idSecond],"this MGDC is not listed"); mint(msg.sender,1); mint(MGDC.ownerOf(idSecond),1); hasBreed[idSecond]=true; }
0.8.4