lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.18
/**
 * @dev Purchase tokens for the amount of ether sent to this contract for custom address
 * @param _participant The address of the participant
 * @return A boolean that indicates if the operation was successful.
 */
function purchaseFor(address _participant) public payable onlyDuringICODates() returns(bool) {
        require(_participant != 0x0);
        require(paidEther[_participant].add(msg.value) >= minimumPurchaseAmount);

        selflleryManagerWallet.transfer(msg.value);

        uint currentBonusPercent = getCurrentBonusPercent();
        uint totalTokens = calcTotalTokens(msg.value, currentBonusPercent);
        require(currentCapTokens.add(totalTokens) <= saleTokensCents);
        require(token.transferFrom(owner, _participant, totalTokens));
        sentTokens[_participant] = sentTokens[_participant].add(totalTokens);
        currentCapTokens = currentCapTokens.add(totalTokens);
        currentCapEther = currentCapEther.add(msg.value);
        paidEther[_participant] = paidEther[_participant].add(msg.value);
        Purchase(_participant, totalTokens, msg.value);

        return true;
    }
// Solidity 0.4.18
/**
 * @dev Add pre-sale purchased tokens only owner
 * @param _participant The address of the participant
 * @param _totalTokens Total tokens amount for pre-sale participant
 * @return A boolean that indicates if the operation was successful.
 */
function addPreSalePurchaseTokens(address _participant, uint _totalTokens) public onlyOwner returns(bool) {
        require(_participant != 0x0);
        require(_totalTokens > 0);
        require(currentCapTokens.add(_totalTokens) <= saleTokensCents);

        require(token.transferFrom(owner, _participant, _totalTokens));
        sentTokens[_participant] = sentTokens[_participant].add(_totalTokens);
        preSaleParticipantTokens[_participant] = preSaleParticipantTokens[_participant].add(_totalTokens);
        currentCapTokens = currentCapTokens.add(_totalTokens);
        PreSalePurchase(_participant, _totalTokens);
        return true;
    }
// Solidity 0.5.8
/* actions */
function _collectPatronage() public {
        // determine patronage to pay
        if (state == StewardState.Owned) {
            uint256 collection = patronageOwed();
            
            // should foreclose and stake stewardship
            if (collection >= deposit) {
                // up to when was it actually paid for?
                timeLastCollected = timeLastCollected.add(((now.sub(timeLastCollected)).mul(deposit).div(collection)));
                collection = deposit; // take what's left.

                _foreclose();
            } else  {
                // just a normal collection
                timeLastCollected = now;
                currentCollected = currentCollected.add(collection);
            }
            
            deposit = deposit.sub(collection);
            totalCollected = totalCollected.add(collection);
            organizationFund = organizationFund.add(collection);
            emit LogCollection(collection);
        }
    }
// Solidity 0.4.22
/**
 * Change the upgrade master.
 *
 * This allows us to set a new owner for the upgrade mechanism.
 */
function setUpgradeMaster(address master) public {
        require(master != address(0), "The provided upgradeMaster is required to be a non-empty address when setting upgrade master.");

        require(msg.sender == upgradeMaster, "Message sender is required to be the original upgradeMaster when setting (new) upgrade master.");

        upgradeMaster = master;
    }
// Solidity 0.5.8
/**
 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Approve with a value of `MAX_UINT = 2 ** 256 - 1` will symbolize
 * an approval of infinite value.
 *
 * IMPORTANT:to prevent the risk that someone may use both the old and
 * the new allowance by unfortunate transaction ordering,
 * the approval must be set to 0 before it can be changed to any
 * different desired value.
 *
 * see: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 *
 * Emits an {Approval} event.
 */
function approve(address spender, uint256 value) public returns (bool) {
        require(
            value == 0 || _allowances[msg.sender][spender] == 0,
            "ERC20: approve only to or from 0 value"
        );
        _approve(msg.sender, spender, value);
        return true;
    }
// Solidity 0.6.12
///@dev Withdraws staked waTokens from the transmuter
///
/// This function reverts if you try to draw more tokens than you deposited
///
///@param amount the amount of waTokens to unstake
function unstake(uint256 amount) public updateAccount(msg.sender) {
        // by calling this function before transmuting you forfeit your gained allocation
        address sender = msg.sender;
        require(depositedWaTokens[sender] >= amount,"TransmuterD8: unstake amount exceeds deposited amount");
        depositedWaTokens[sender] = depositedWaTokens[sender].sub(amount);
        totalSupplyWaTokens = totalSupplyWaTokens.sub(amount);
        IERC20Burnable(WaToken).safeTransfer(sender, amount);
    }
// Solidity 0.6.12
///@dev Deposits waTokens into the transmuter
///
///@param amount the amount of waTokens to stake
function stake(uint256 amount)
        public
        runPhasedDistribution()
        updateAccount(msg.sender)
        checkIfNewUser()
    {
        // requires approval of waToken first
        address sender = msg.sender;
        //require tokens transferred in;
        IERC20Burnable(WaToken).safeTransferFrom(sender, address(this), amount);
        totalSupplyWaTokens = totalSupplyWaTokens.add(amount);
        depositedWaTokens[sender] = depositedWaTokens[sender].add(amount);
    }
// Solidity 0.6.12
/// @dev Converts the staked waTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket
///
/// once the waToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim()
///
/// reverts if there are no pendingdivs or tokensInBucket
function transmute() public runPhasedDistribution() updateAccount(msg.sender) {
        address sender = msg.sender;
        uint256 pendingz = tokensInBucket[sender];
        uint256 diff;

        require(pendingz > 0, "need to have pending in bucket");

        tokensInBucket[sender] = 0;

        // check bucket overflow
        if (pendingz > depositedWaTokens[sender]) {
            diff = pendingz.sub(depositedWaTokens[sender]);

            // remove overflow
            pendingz = depositedWaTokens[sender];
        }

        // decrease watokens
        depositedWaTokens[sender] = depositedWaTokens[sender].sub(pendingz);

        // BURN WATOKENS
        IERC20Burnable(WaToken).burn(pendingz);

        // adjust total
        totalSupplyWaTokens = totalSupplyWaTokens.sub(pendingz);

        // reallocate overflow
        increaseAllocations(diff);

        // add payout
        realisedTokens[sender] = realisedTokens[sender].add(pendingz);
    }
// Solidity 0.6.12
/// @dev Executes transmute() on another account that has had more base tokens allocated to it than waTokens staked.
///
/// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action
///
/// This function reverts if the address to transmute is not over-filled.
///
/// @param toTransmute address of the account you will force transmute.
function forceTransmute(address toTransmute)
        public
        runPhasedDistribution()
        updateAccount(msg.sender)
        updateAccount(toTransmute)
    {
        //load into memory
        address sender = msg.sender;
        uint256 pendingz = tokensInBucket[toTransmute];
        // check restrictions
        require(
            pendingz > depositedWaTokens[toTransmute],
            "TransmuterD8: !overflow"
        );

        // empty bucket
        tokensInBucket[toTransmute] = 0;

        // calculaate diffrence
        uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);

        // remove overflow
        pendingz = depositedWaTokens[toTransmute];

        // decrease waTokens
        depositedWaTokens[toTransmute] = 0;

        // BURN WATOKENS
        IERC20Burnable(WaToken).burn(pendingz);

        // adjust total
        totalSupplyWaTokens = totalSupplyWaTokens.sub(pendingz);

        // reallocate overflow
        tokensInBucket[sender] = tokensInBucket[sender].add(diff);

        // add payout
        realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz);

        // force payout of realised tokens of the toTransmute address
        if (realisedTokens[toTransmute] > 0) {
            uint256 value = realisedTokens[toTransmute];
            realisedTokens[toTransmute] = 0;
            IERC20Burnable(Token).safeTransfer(toTransmute, value);
        }
    }
// Solidity 0.6.12
/// @dev Gets the status of a user's staking position.
///
/// The total amount allocated to a user is the sum of pendingdivs and inbucket.
///
/// @param user the address of the user you wish to query.
///
/// returns user status
function userInfo(address user)
        public
        view
        returns (
            uint256 depositedAl,
            uint256 pendingdivs,
            uint256 inbucket,
            uint256 realised
        )
    {
        uint256 _depositedAl = depositedWaTokens[user];
        uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD);
        if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){
            _toDistribute = buffer;
        }
        uint256 _pendingdivs = _toDistribute.mul(depositedWaTokens[user]).div(totalSupplyWaTokens);
        uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user));
        uint256 _realised = realisedTokens[user];
        return (_depositedAl, _pendingdivs, _inbucket, _realised);
    }
// Solidity 0.6.12
/// @dev Gets the status of multiple users in one call
///
/// This function is used to query the contract to check for
/// accounts that have overfilled positions in order to check
/// who can be force transmuted.
///
/// @param from the first index of the userList
/// @param to the last index of the userList
///
/// returns the userList with their staking status in paginated form.
function getMultipleUserInfo(uint256 from, uint256 to)
        public
        view
        returns (address[] memory theUserList, uint256[] memory theUserData)
    {
        uint256 i = from;
        uint256 delta = to - from;
        address[] memory _theUserList = new address[](delta); //user
        uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket
        uint256 y = 0;
        uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD);
        if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){
            _toDistribute = buffer;
        }
        for (uint256 x = 0; x < delta; x += 1) {
            _theUserList[x] = userList[i];
            _theUserData[y] = depositedWaTokens[userList[i]];
            _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedWaTokens[userList[i]]).div(totalSupplyWaTokens));
            y += 2;
            i += 1;
        }
        return (_theUserList, _theUserData);
    }
// Solidity 0.4.24
// Note: Order creation happens off-chain but the orders are signed by creators,
// we validate the contents and the creator address in the logic below
function trade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive,
      uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount) {
    bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce);
    // Check order signatures and expiration, also check if not fulfilled yet
		if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) != _user ||
      block.number > _expires ||
      safeAdd(orderFills[_user][hash], _amount) > _amountGet) {
      revert();
    }
    tradeBalances(_tokenGet, _amountGet, _tokenGive, _amountGive, _user, msg.sender, _amount);
    orderFills[_user][hash] = safeAdd(orderFills[_user][hash], _amount);
    Trade(_tokenGet, _amount, _tokenGive, _amountGive * _amount / _amountGet, _user, msg.sender, _nonce);
  }
// Solidity 0.4.24
// User-triggered (!) fund migrations in case contract got updated
// Similar to withdraw but we use a successor account instead
// As we don't store user tokens list on chain, it has to be passed from the outside
function migrateFunds(address[] _tokens) {

    // Get the latest successor in the chain
    require(successor != address(0));
    TokenStore newExchange = TokenStore(successor);
    for (uint16 n = 0; n < 20; n++) {  // We will look past 20 contracts in the future
      address nextSuccessor = newExchange.successor();
      if (nextSuccessor == address(this)) {  // Circular succession
        revert();
      }
      if (nextSuccessor == address(0)) { // We reached the newest, stop
        break;
      }
      newExchange = TokenStore(nextSuccessor);
    }

    // Ether
    uint etherAmount = tokens[0][msg.sender];
    if (etherAmount > 0) {
      tokens[0][msg.sender] = 0;
      newExchange.depositForUser.value(etherAmount)(msg.sender);
    }

    // Tokens
    for (n = 0; n < _tokens.length; n++) {
      address token = _tokens[n];
      require(token != address(0)); // 0 = Ether, we handle it above
      uint tokenAmount = tokens[token][msg.sender];
      if (tokenAmount == 0) {
        continue;
      }
      if (!Token(token).approve(newExchange, tokenAmount)) {
        revert();
      }
      tokens[token][msg.sender] = 0;
      newExchange.depositTokenForUser(token, tokenAmount, msg.sender);
    }

    FundsMigrated(msg.sender);
  }
// Solidity 0.4.24
// This is used for migrations only. To be called by previous exchange only,
// user-triggered, on behalf of the user called the migrateFunds method.
// Note that it does exactly the same as depositToken, but as this is called
// by a previous generation of exchange itself, we credit internally not the
// previous exchange, but the user it was called for.
function depositForUser(address _user) payable deprecable {
    require(_user != address(0));
    require(msg.value > 0);
    TokenStore caller = TokenStore(msg.sender);
    require(caller.version() > 0); // Make sure it's an exchange account
    tokens[0][_user] = safeAdd(tokens[0][_user], msg.value);
  }
// Solidity 0.5.1
// Have that someone else spend your tokens
function transferFrom(address payable from, address payable to, uint value) public returns(bool success) {
		uint256 allowance = allowances[from][msg.sender];
		require(allowance > 0, "Not approved");
		require(allowance >= value, "Over spending limit");
		allowances[from][msg.sender] = allowance.sub(value);
		actualTransfer(from, to, value, "", "", false);
		return true;
	}
// Solidity 0.5.1
// The fallback function
function() payable external{
		// Only accept free ETH from the bitx and from our child slave.
		if (msg.sender != address(bitx) && msg.sender != address(refHandler)) {
			// Now, sending ETH increases the balance _before_ the transaction has been fully processed.
			// We don't want to distribute the entire purchase order as dividends.
			if (msg.value > 0) {
				lastTotalBalance += msg.value;
				distributeDividends(0, NULL_ADDRESS);
				lastTotalBalance -= msg.value;
			}
			createTokens(msg.sender, msg.value, NULL_ADDRESS, false);
		}
	}
// Solidity 0.5.1
// Throw your money at this thing with a referrer specified by their Ethereum address.
// Returns the amount of tokens created.
function buy(address referrerAddress) payable public returns(uint256) {
		// Now, sending ETH increases the balance _before_ the transaction has been fully processed.
		// We don't want to distribute the entire purchase order as dividends.
		if (msg.value > 0) {
			lastTotalBalance += msg.value;
			distributeDividends(0, NULL_ADDRESS);
			lastTotalBalance -= msg.value;
		}
		return createTokens(msg.sender, msg.value, referrerAddress, false);
	}
// Solidity 0.5.1
// Use all the ETH you earned hodling BXTG to buy more BXTG.
// Returns the amount of tokens created.
function reinvest() public returns(uint256) {
		address accountHolder = msg.sender;
		distributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.
		uint256 payout;
		uint256 bonusPayout;
		(payout, bonusPayout) = clearDividends(accountHolder);
		emit onWithdraw(accountHolder, payout, bonusPayout, true);
		return createTokens(accountHolder, payout + bonusPayout, NULL_ADDRESS, true);
	}
// Solidity 0.5.1
// Use some of the ETH you earned hodling BXTG to buy more BXTG.
// You can withdraw the rest or keep it in here allocated for you.
// Returns the amount of tokens created.
function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) public returns(uint256 tokensCreated) {
		address payable accountHolder = msg.sender;
		distributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.

		uint256 payout = dividendsOf(accountHolder, false);
		uint256 bonusPayout = bonuses[accountHolder];

		uint256 payoutReinvested = 0;
		uint256 bonusReinvested;

		require((payout + bonusPayout) >= ethToReinvest, "Insufficient balance for reinvestment");
		// We're going to take ETH out of the masternode bonus first, then the outstanding divs.
		if (ethToReinvest > bonusPayout){
			payoutReinvested = ethToReinvest - bonusPayout;
			bonusReinvested = bonusPayout;
			// Take ETH out from outstanding dividends.
			payouts[accountHolder] += int256(payoutReinvested * ROUNDING_MAGNITUDE);
		}else{
			bonusReinvested = ethToReinvest;
		}
		// Take ETH from the masternode bonus.
		bonuses[accountHolder] -= bonusReinvested;

		emit onWithdraw(accountHolder, payoutReinvested, bonusReinvested, true);
		// Do the buy thing!
		tokensCreated = createTokens(accountHolder, ethToReinvest, NULL_ADDRESS, true);

		if (withdrawAfter && dividendsOf(msg.sender, true) > 0) {
			withdrawDividends(msg.sender);
		}
		return tokensCreated;
	}
// Solidity 0.5.1
// There's literally no reason to call this function
function sell(uint256 amount, bool withdrawAfter) public returns(uint256) {
		require(amount > 0, "You have to sell something");
		uint256 sellAmount = destroyTokens(msg.sender, amount);
		if (withdrawAfter && dividendsOf(msg.sender, true) > 0) {
			withdrawDividends(msg.sender);
		}
		return sellAmount;
	}
// Solidity 0.5.1
// --Public read-only functions--
// Internal functions
// Returns true if the gauntlet has expired. Otherwise, false.
function isGauntletExpired(address holder) internal view returns(bool) {
		if (gauntletType[holder] != 0) {
			if (gauntletType[holder] == 1) {
				return (block.timestamp >= gauntletEnd[holder]);
			} else if (gauntletType[holder] == 2) {
				return (bitx.totalSupply() >= gauntletEnd[holder]);
			} else if (gauntletType[holder] == 3) {
				return ExternalGauntletInterface(gauntletEnd[holder]).gauntletRemovable(holder);
			}
		}
		return false;
	}
// Solidity 0.5.1
// Same as usableBalanceOf, except the gauntlet is lifted when it's expired.
function updateUsableBalanceOf(address holder) internal returns(uint256) {
		// isGauntletExpired is a _view_ function, with uses STATICCALL in solidity 0.5.0 or later.
		// Since STATICCALLs can't modifiy the state, re-entry attacks aren't possible here.
		if (isGauntletExpired(holder)) {
			if (gauntletType[holder] == 3){
				emit onExternalGauntletAcquired(holder, 0, NULL_ADDRESS);
			}else{
				emit onGauntletAcquired(holder, 0, 0, 0);
			}
			gauntletType[holder] = 0;
			gauntletBalance[holder] = 0;

			return balances[holder];
		}
		return balances[holder] - gauntletBalance[holder];
	}
// Solidity 0.5.1
// sends ETH to the specified account, using all the ETH BXTG has access to.
function sendETH(address payable to, uint256 amount) internal {
		uint256 childTotalBalance = refHandler.totalBalance();
		uint256 thisBalance = address(this).balance;
		uint256 thisTotalBalance = thisBalance + bitx.myDividends(true);
		if (childTotalBalance >= amount) {
			// the refHanlder has enough of its own ETH to send, so it should do that.
			refHandler.sendETH(to, amount);
		} else if (thisTotalBalance >= amount) {
			// We have enough ETH of our own to send.
			if (thisBalance < amount) {
				bitx.withdraw();
			}
			to.transfer(amount);
		} else {
			// Neither we nor the refHandler has enough ETH to send individually, so both contracts have to send ETH.
			refHandler.sendETH(to, childTotalBalance);
			if (bitx.myDividends(true) > 0) {
				bitx.withdraw();
			}
			to.transfer(amount - childTotalBalance);
		}
		// keep the dividend tracker in check.
		lastTotalBalance = lastTotalBalance.sub(amount);
	}
// Solidity 0.5.1
// Take the ETH we've got and distribute it among our token holders.
function distributeDividends(uint256 bonus, address bonuser) internal{
		// Prevents "HELP I WAS THE LAST PERSON WHO SOLD AND I CAN'T WITHDRAW MY ETH WHAT DO????" (dividing by 0 results in a crash)
		if (totalSupply > 0) {
			uint256 tb = totalBalance();
			uint256 delta = tb - lastTotalBalance;
			if (delta > 0) {
				// We have more ETH than before, so we'll just distribute those dividends among our token holders.
				if (bonus != 0) {
					bonuses[bonuser] += bonus;
				}
				profitPerShare = profitPerShare.add(((delta - bonus) * ROUNDING_MAGNITUDE) / totalSupply);
				lastTotalBalance += delta;
			}
		}
	}
// Solidity 0.5.1
// Clear out someone's dividends.
function clearDividends(address accountHolder) internal returns(uint256, uint256) {
		uint256 payout = dividendsOf(accountHolder, false);
		uint256 bonusPayout = bonuses[accountHolder];

		payouts[accountHolder] += int256(payout * ROUNDING_MAGNITUDE);
		bonuses[accountHolder] = 0;

		// External apps can now get reliable masternode statistics
		return (payout, bonusPayout);
	}
// Solidity 0.5.1
// Withdraw 100% of someone's dividends
function withdrawDividends(address payable accountHolder) internal {
		distributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.
		uint256 payout;
		uint256 bonusPayout;
		(payout, bonusPayout) = clearDividends(accountHolder);
		emit onWithdraw(accountHolder, payout, bonusPayout, false);
		sendETH(accountHolder, payout + bonusPayout);
	}
// Solidity 0.6.10
/**
 * Settle the pool, the winners are selected randomly and fee is transfer to the manager.
 */
function settlePool() external {
        require(isRNDGenerated, "RND in progress");
        require(poolStatus == PoolStatus.INPROGRESS, "pool in progress");

        // generate winnerIndexes until the numOfWinners reach
        uint256 newRandom = randomResult;
        uint256 offset = 0;
        while(winnerIndexes.length < poolConfig.numOfWinners) {
            uint256 winningIndex = newRandom.mod(poolConfig.participantLimit);
            if (!winnerIndexes.contains(winningIndex)) {
                winnerIndexes.push(winningIndex);
            }
            offset = offset.add(1);
            newRandom = _getRandomNumberBlockchain(offset, newRandom);
        }
        areWinnersGenerated = true;
        emit WinnersGenerated(winnerIndexes);

        // set pool CLOSED status
        poolStatus = PoolStatus.CLOSED;

        // transfer fees
        uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100);
        rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners);
        _transferEnterToken(feeRecipient, feeAmount);

        // collectRewards();
        emit PoolSettled();
    }