lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
// ONLY-CITIZEN-CONTRACT FUNCTIONS
function bonusNewRank(address _investorAddress, uint _currentRank, uint _newRank) onlyCitizenContract public {
    require(_newRank > _currentRank, "Invalid ranks");
    Balance storage balance = userWallets[_investorAddress];
    for (uint8 i = uint8(_currentRank) + 1; i <= uint8(_newRank); i++) {
      uint rankBonusAmount = citizen.rankBonuses(i);
      balance.profitBalance = balance.profitBalance.add(rankBonusAmount);
      if (rankBonusAmount > 0) {
        emit RankBonusSent(_investorAddress, i, rankBonusAmount);
      }
    }
  }
// Solidity 0.4.10
//------------------------------------------------------
// check active game and valid player, return player index
//-------------------------------------------------------
function validPlayer(uint _hGame, address _addr)  internal returns( bool _valid, uint _pidx)
	{
		_valid = false;
		if (activeGame(_hGame)) {
			for (uint i = 0; i < games[_hGame].numPlayers; i++) {
				if (games[_hGame].players[i] == _addr) {
					_valid=true;
					_pidx = i;
					break;
				}
			}
		}			
	}
// Solidity 0.4.10
//------------------------------------------------------
// check valid player, return player index
//-------------------------------------------------------
function validPlayer2(uint _hGame, address _addr) internal  returns( bool _valid, uint _pidx)
	{
		_valid = false;
		for (uint i = 0; i < games[_hGame].numPlayers; i++) {
			if (games[_hGame].players[i] == _addr) {
				_valid=true;
				_pidx = i;
				break;
			}
		}
	}
// Solidity 0.4.10
//------------------------------------------------------
// register game arbiter, max players of 5, pass in exact registration fee
//------------------------------------------------------
function registerArbiter(uint _numPlayers, uint _arbToken) public payable 
	{

		if (msg.value != registrationFee) {
			throw;  //Insufficient Fee
		}

		if (_arbToken == 0) {
			throw; // invalid token
		}

		if (arbTokenExists(_arbToken & 0xffff)) {
			throw; // Token Already Exists
		}

		if (arbiters[msg.sender].registered) {
			throw; // Arb Already Registered
		}
		
		if (_numPlayers > MAX_PLAYERS) {
			throw; // Exceeds Max Players
		}

		arbiters[msg.sender].gamesStarted = 0;
		arbiters[msg.sender].gamesCompleted = 0;
		arbiters[msg.sender].gamesCanceled = 0; 
		arbiters[msg.sender].gamesTimedout = 0;
		arbiters[msg.sender].locked = false;
		arbiters[msg.sender].arbToken = _arbToken & 0xffff;
		arbiters[msg.sender].numPlayers = _numPlayers;
		arbiters[msg.sender].registered = true;

		arbiterTokens[(_arbToken & 0xffff)] = msg.sender;
		arbiterIndexes[numArbiters++] = msg.sender;
	

		if (!tokenPartner.call.gas(raGas).value(msg.value)()) {
			//Statvent("Send Error"); // event never registers
		        throw;
		}
		StatEventI("Arb Added", _arbToken);
	}
// Solidity 0.4.10
//------------------------------------------------------
// start game.  pass in valid hGame containing token in top two bytes
//------------------------------------------------------
function startGame(uint _hGame, int _hkMax, address[] _players) public 

	{
		uint ntok = ArbTokFromHGame(_hGame);
		if (!validArb(msg.sender, ntok )) {
			StatEvent("Invalid Arb");
			return;
		}


		if (arbLocked(msg.sender)) {
			StatEvent("Arb Locked");
			return; 
		}

		arbiter xarb = arbiters[msg.sender];
		if (_players.length != xarb.numPlayers) { 
			StatEvent("Incorrect num players");
			return; 
		}

		if (games[_hGame].active) {
			// guard-rail. just in case to return funds
			abortGame(msg.sender, _hGame, EndReason.erCancel);

		} else if (_hkMax > 0) {
			houseKeep(_hkMax, ntok); 
		}

		if (!games[_hGame].allocd) {
			games[_hGame].allocd = true;
			xarb.gameIndexes[xarb.gameSlots++] = _hGame;
		} 
		numGamesStarted++; // always inc this one
		xarb.gamesStarted++;

		games[_hGame].active = true;
		games[_hGame].started = now; 
		games[_hGame].lastMoved = now; 
		games[_hGame].payout = 0; 
		games[_hGame].winner = address(0);

		games[_hGame].numPlayers = _players.length; // we'll be the judge of how many unique players
		for (uint i = 0; i< _players.length && i < MAX_PLAYERS; i++) {
	            games[_hGame].players[i] = _players[i];
		    games[_hGame].playerPots[i] = 0;
		}

		StatEventI("Game Added", _hGame);
		

	}
// Solidity 0.4.10
//------------------------------------------------------
// clean up game, set to inactive, refund any balances
// called by housekeep ONLY
//------------------------------------------------------
function abortGame(address _arb, uint  _hGame, EndReason _reason) private returns(bool _success)
	{
	     gameInstance nGame = games[_hGame];
	     
		// find game in game id, 
		if (nGame.active) {
			_success = true;
			for (uint i = 0; i < nGame.numPlayers; i++) {
				if (nGame.playerPots[i] > 0) {
					address a = nGame.players[i];
					uint nsend = nGame.playerPots[i];
					nGame.playerPots[i] = 0;
					if (!a.call.gas(rfGas).value(nsend)()) {
						houseFeeHoldover += nsend; // cannot refund due to error, give to the house
					        StatEventA("Cannot Refund Address", a);
					}
				}
			}
			nGame.active = false;
			nGame.reasonEnded = _reason;
			if (_reason == EndReason.erCancel) {
				numGamesCanceled++;
				arbiters[_arb].gamesCanceled++;
				StatEvent("Game canceled");
			} else if (_reason == EndReason.erTimeOut) {
				numGamesTimedOut++;
				arbiters[_arb].gamesTimedout++;
				StatEvent("Game timed out");
			} else 
				StatEvent("Game aborted");
		}
	}
// Solidity 0.4.10
//------------------------------------------------------
// handle a bet made by a player, validate the player and game
// add to players balance
//------------------------------------------------------
function handleBet(uint _hGame) public payable 
	{
		address narb = arbiterTokens[ArbTokFromHGame(_hGame)];
		if (narb == address(0)) {
			throw; // "Invalid hGame"
		}

		var (valid, pidx) = validPlayer(_hGame, msg.sender);
		if (!valid) {
			throw; // "Invalid Player"
		}

		games[_hGame].playerPots[pidx] += msg.value;
		games[_hGame].lastMoved = now;

		StatEventI("Bet Added", _hGame);

	}
// Solidity 0.4.10
//------------------------------------------------------
// return arbiter game stats
//------------------------------------------------------
function getArbInfo(uint _idx) constant  returns (address _addr, uint _started, uint _completed, uint _canceled, uint _timedOut) 
	{
		if (_idx >= numArbiters) {
			StatEvent("Invalid Arb");
			return;
		}
		_addr = arbiterIndexes[_idx];
		if ((_addr == address(0))
			|| (!arbiters[_addr].registered)) {
			StatEvent("Invalid Arb");
			return;
		}
		arbiter xarb = arbiters[_addr];
		_started = xarb.gamesStarted;
		_completed = xarb.gamesCompleted;
		_timedOut = xarb.gamesTimedout;
		_canceled = xarb.gamesCanceled;
	}
// Solidity 0.4.10
//------------------------------------------------------
// scan for a game 10 minutes old
// if found abort the game, causing funds to be returned
//------------------------------------------------------
function houseKeep(int _max, uint _arbToken) public
	{	
		uint gi;
		address a;
		int aborted = 0;
		
		arbiter xarb = arbiters[msg.sender];// have to set it to something
	        
         
		if (msg.sender == owner) {
			for (uint ar = 0; (ar < numArbiters) && (aborted < _max) ; ar++) {
			    a = arbiterIndexes[ar];
			    xarb = arbiters[a];    

			    for ( gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
				gameInstance ngame0 = games[xarb.gameIndexes[gi]];
				if ((ngame0.active)
				    && ((now - ngame0.lastMoved) > gameTimeOut)) {
					abortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);
					++aborted;
				}
			    }
			}

		} else {
			if (!validArb(msg.sender, _arbToken))
				StatEvent("Housekeep invalid arbiter");
			else {
			    a = msg.sender;
			    xarb = arbiters[a];    
			    for (gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
				gameInstance ngame1 = games[xarb.gameIndexes[gi]];
				if ((ngame1.active)
				    && ((now - ngame1.lastMoved) > gameTimeOut)) {
					abortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);
					++aborted;
				}
			    }

			}	
		}
	}
// Solidity 0.4.10
//------------------------------------------------------
// return game info
//------------------------------------------------------
function getGameInfo(uint _hGame)  constant  returns (EndReason _reason, uint _players, uint _payout, bool _active, address _winner )
	{
		gameInstance ngame = games[_hGame];
		_active = ngame.active;
		_players = ngame.numPlayers;
		_winner = ngame.winner;
		_payout = ngame.payout;
		_reason = ngame.reasonEnded;

	}
// Solidity 0.4.10
//------------------------------------------------------
// get operation gas amounts
//------------------------------------------------------
function getOpGas() constant returns (uint _ra, uint _sg, uint _wp, uint _rf, uint _fg) 
	{
		_ra = raGas; // register arb
		_sg = sgGas; // start game
		_wp = wpGas; // winner paid
		_rf = rfGas; // refund
		_fg = feeGas; // rake fee gas
	}
// Solidity 0.4.10
//------------------------------------------------------
// set operation gas amounts for forwading operations
//------------------------------------------------------
function setOpGas(uint _ra, uint _sg, uint _wp, uint _rf, uint _fg) 
	{
		if (msg.sender != owner)
			throw;

		raGas = _ra;
		sgGas = _sg;
		wpGas = _wp;
		rfGas = _rf;
		feeGas = _fg;
	}
// Solidity 0.4.10
//------------------------------------------------------
// flush the house fees whenever commanded to.
// ignore the threshold and the last payout time
// but this time only reset lastpayouttime upon success
//------------------------------------------------------
function flushHouseFees()
	{
		if (msg.sender != owner) {
			StatEvent("only owner calls this function");
		} else if (houseFeeHoldover > 0) {
			uint ntmpho = houseFeeHoldover;
			houseFeeHoldover = 0;
			if (!tokenPartner.call.gas(feeGas).value(ntmpho)()) {
				houseFeeHoldover = ntmpho; // put it back
				StatEvent("House-Fee Error2"); 
			} else {
				lastPayoutTime = now;
 				StatEvent("House-Fee Paid");
	 		}
		}

	}
// Solidity 0.4.10
//------------------------------------------------------
// set the token partner
//------------------------------------------------------
function setTokenPartner(address _addr) public
	{
		if (msg.sender != owner) {
			throw;
		} 

		if ((settingsState == SettingStateValue.lockedRelease) 
			&& (tokenPartner == address(0))) {
			tokenPartner = _addr;
			StatEvent("Token Partner Final!");
		} else if (settingsState != SettingStateValue.lockedRelease) {
			tokenPartner = _addr;
			StatEvent("Token Partner Assigned!");
		}
			
	}
// Solidity 0.4.24
/**
 * @dev public function that is used to determine the current rate for token / ETH conversion
 * @dev there exists a case where rate cant be set to 0, which is fine.
 * @return The current token rate
 */
function getRate() public view returns(uint256) {
        require( priceOfEMLTokenInUSDPenny !=0 );
        require( priceOfEthInUSD !=0 );
        uint256 rate;

        if(overridenBonusValue > 0){
            rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
        } else {
            if (now <= (startTime + 1 days)) {
                rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
            } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
                rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
            } else {
                rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
            }
        }
        return rate;
    }
// Solidity 0.4.24
/** @dev Function for buying EML tokens using ether
 * @param _investorAddr The address that should receive bought tokens
 */
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
        require(_investorAddr != address(0));
        require(validPurchase());

        uint256 weiAmount = msg.value;
        uint256 returnToSender = 0;

        // final rate after including rate value and bonus amount.
        uint256 finalConversionRate = getRate();

        // Calculate EML token amount to be transferred
        uint256 tokens = weiAmount.mul(finalConversionRate);

        // Distribute only the remaining tokens if final contribution exceeds hard cap
        if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
            tokens = hardCap.sub(totalTokensSoldandAllocated);
            weiAmount = tokens.div(finalConversionRate);
            returnToSender = msg.value.sub(weiAmount);
        }

        // update state and balances
        etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
        tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
        totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
        totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
        totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);


        // assert implies it should never fail
        assert(token.transferFrom(owner, _investorAddr, tokens));
        emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);

        // Forward funds
        multisigWallet.transfer(weiAmount);

        // Update token contract.
        _postValidationUpdateTokenContract();

        // Return funds that are over hard cap
        if (returnToSender > 0) {
            msg.sender.transfer(returnToSender);
        }
    }
// Solidity 0.4.24
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
 * @return True if the transaction can buy tokens
 */
function validPurchase() internal view returns(bool) {
        bool withinPeriod = now >= startTime && now <= endTime;
        bool minimumPurchase = msg.value >= 1*(10**18);
        bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
        return withinPeriod && hardCapNotReached && minimumPurchase;
    }
// Solidity 0.4.24
/** @dev Returns ether to token holders in case soft cap is not reached.
 */
function claimRefund() public whenNotPaused onlyOwner {
        require(now>endTime);
        require(totalTokensSoldandAllocated<soft_cap);
        uint256 amount = etherInvestments[msg.sender];

        if (address(this).balance >= amount) {
            etherInvestments[msg.sender] = 0;
            if (amount > 0) {
                msg.sender.transfer(amount);
                emit Refund(msg.sender, amount);
            }
        }
      }
// Solidity 0.4.24
/** @dev Allocates EML tokens to an investor address called automatically
 * after receiving fiat or btc investments from KYC whitelisted investors.
 * @param beneficiary The address of the investor
 * @param tokenCount The number of tokens to be allocated to this address
 */
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
        require(beneficiary != address(0));
        require(validAllocation(tokenCount));

        uint256 tokens = tokenCount;

        /* Allocate only the remaining tokens if final contribution exceeds hard cap */
        if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
            tokens = hardCap.sub(totalTokensSoldandAllocated);
        }

        /* Update state and balances */
        allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
        totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
        totalTokensAllocated = totalTokensAllocated.add(tokens);

        // assert implies it should never fail
        assert(token.transferFrom(owner, beneficiary, tokens));
        emit TokensAllocated(beneficiary, tokens);

        /* Update token contract. */
        _postValidationUpdateTokenContract();
        return true;
    }
// Solidity 0.4.24
/** @dev public function that is used to determine the current rate for ETH to EML conversion
 * @return The current token rate
 */
function getRate() public view returns(uint256) {
        require(priceOfEMLTokenInUSDPenny > 0 );
        require(priceOfEthInUSD > 0 );
        uint256 rate;

        if(overridenBonusValue > 0){
            rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
        } else {
            rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
        }
        return rate;
    }
// Solidity 0.4.25
/*
 * Declaring the customized details of the token. The token will be called Tratok, with a total supply of 100 billion tokens.
 * It will feature five decimal places and have the symbol TRAT.
 */
function Tratok() {

        //we will create 100 Billion Coins and send them to the creating wallet.
        balances[msg.sender] = 10000000000000000;
        totalSupply = 10000000000000000;
        name = "Tratok";
        decimals = 5;
        symbol = "TRAT";
    }
// Solidity 0.4.25
/*
 *Approve and enact the contract.
 *
 */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns(bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);

        //If the call fails, result to "vanilla" approval.
        if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) {
            throw;
        }
        return true;
    }
// Solidity 0.8.11
//Checks staked amount
function depositsOf(address account)
        external
        view
        returns (uint256[] memory)
    {
        EnumerableSet.UintSet storage depositSet = _deposits[account];
        uint256[] memory tokenIds = new uint256[](depositSet.length());

        for (uint256 i; i < depositSet.length(); i++) {
            tokenIds[i] = depositSet.at(i);
        }

        return tokenIds;
    }
// Solidity 0.8.11
//Calculate rewards amount by address/tokenIds[]
function calculateRewards(address account, uint256[] memory tokenIds)
        public
        view
        returns (uint256[] memory rewards)
    {
        rewards = new uint256[](tokenIds.length);

        for (uint256 i; i < tokenIds.length; i++) {
            uint256 tokenId = tokenIds[i];
            rewards[i] =
                rate *
                (_deposits[account].contains(tokenId) ? 1 : 0) *
                (block.number - _depositBlocks[account][tokenId]);
        }

        return rewards;
    }
// Solidity 0.8.11
//Staking function
function stake(uint256[] calldata tokenIds) external whenNotPaused {
        require(msg.sender != nftAddress, "Invalid address");
        require(
            nft.isApprovedForAll(msg.sender, address(this)),
            "This contract is not approved to transfer your NFT."
        );
        for (uint256 i = 0; i < tokenIds.length; i++) {
            require(
                nft.ownerOf(tokenIds[i]) == msg.sender,
                "You do not own this NFT."
            );
        }

        claimRewards(tokenIds);
        for (uint256 i; i < tokenIds.length; i++) {
            IERC721(nftAddress).safeTransferFrom(
                msg.sender,
                address(this),
                tokenIds[i],
                ""
            );
            _deposits[msg.sender].add(tokenIds[i]);
        }
    }
// Solidity 0.4.12
// end Uniswap stuff
function rebase(uint256 epoch, int256 supplyDelta)
        external
        returns (uint256)
    {
        require(msg.sender == info.chef);
        if (supplyDelta == 0) {
             LogRebase(epoch, info.totalFrozen);
            return info.totalFrozen;
        }

        if (supplyDelta < 0) {
            info.totalFrozen = info.totalFrozen.sub(uint256(supplyDelta));
        }

         LogRebase(epoch, info.totalFrozen);
        return info.totalFrozen;
    }
// Solidity 0.6.4
//==================================================================================//
// Unstaking functions
// Unstake % for self
function unstake(uint basisPoints, address pool) public returns (bool success) {
        require((basisPoints > 0 && basisPoints <= 10000), "Must be valid BasisPoints");
        uint _units = math.calcPart(basisPoints, memberData[msg.sender].stakeData[pool].stakeUnits);
        unstakeExact(_units, pool);
        return true;
    }
// Solidity 0.6.4
// Unstake an exact qty of units
function unstakeExact(uint units, address pool) public returns (bool success) {
        require(units <= memberData[msg.sender].stakeData[pool].stakeUnits, "Must own the units");
        uint _outputVether = math.calcShare(units, poolData[pool].poolUnits, poolData[pool].vether);
        uint _outputAsset = math.calcShare(units, poolData[pool].poolUnits, poolData[pool].asset);
        _handleUnstake(units, _outputVether, _outputAsset, msg.sender, pool);
        return true;
    }
// Solidity 0.6.4
// Unstake Exact Asymmetrically
function unstakeExactAsymmetric(uint units, address pool, bool toVether) public returns (uint outputAmount){
        require(units <= memberData[msg.sender].stakeData[pool].stakeUnits, "Must own the units");
        uint _poolUnits = poolData[pool].poolUnits;
        require(units < _poolUnits, "Must not be last staker");
        uint _outputVether; uint _outputAsset; 
        if(toVether){
            _outputVether = math.calcAsymmetricShare(units, _poolUnits, poolData[pool].vether);
            _outputAsset = 0;
            outputAmount = _outputVether;
        } else {
            _outputVether = 0;
            _outputAsset = math.calcAsymmetricShare(units, _poolUnits, poolData[pool].asset);
            outputAmount = _outputAsset;
        }
        _handleUnstake(units, _outputVether, _outputAsset, msg.sender, pool);
        return outputAmount;
    }
// Solidity 0.6.4
// Internal - handle Unstake
function _handleUnstake(uint _units, uint _outputVether, uint _outputAsset, address payable _member, address _pool) internal {
        _decrementPoolBalances(_units, _outputVether, _outputAsset, _pool);
        _removeDataForMember(_member, _units, _pool);
        emit Unstaked(_pool, _member, _outputAsset, _outputVether, _units);
        _handleTransferOut(_pool, _outputAsset, _member);
        _handleTransferOut(VETHER, _outputVether, _member);
    }
// Solidity 0.6.4
//==================================================================================//
// Upgrade functions
// Upgrade from this contract to a new one - opt in
function upgrade(address payable newContract, address pool) public {
        uint _units = memberData[msg.sender].stakeData[pool].stakeUnits;
        uint _outputVether = math.calcShare(_units, poolData[pool].poolUnits, poolData[pool].vether);
        uint _outputAsset = math.calcShare(_units, poolData[pool].poolUnits, poolData[pool].asset);
        _decrementPoolBalances(_units, _outputVether, _outputAsset, pool);
        _removeDataForMember(msg.sender, _units, pool);
        emit Unstaked(pool, msg.sender, _outputAsset, _outputVether, _units);
        ERC20(VETHER).approve(newContract, _outputVether);
        if(pool == address(0)){
            POOLS(newContract).stakeForMember{value:_outputAsset}(_outputVether, _outputAsset, pool, msg.sender);
        } else {
            ERC20(pool).approve(newContract, _outputAsset);
            POOLS(newContract).stakeForMember(_outputVether, _outputAsset, pool, msg.sender);
        }
    }