lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.16
/// @dev Re-invest whatever this worker has earned back to staked LP tokens.
function reinvest() public onlyEOA nonReentrant {
        // 1. Withdraw all the rewards.
        staking.getReward();
        uint256 reward = uni.myBalance();
        if (reward == 0) return;
        // 2. Send the reward bounty to the caller.
        uint256 bounty = reward.mul(reinvestBountyBps) / 10000;
        uni.safeTransfer(msg.sender, bounty);
        // 3. Convert all the remaining rewards to ETH.
        address[] memory path = new address[](2);
        path[0] = address(uni);
        path[1] = address(weth);
        router.swapExactTokensForETH(reward.sub(bounty), 0, path, address(this), now);
        // 4. Use add ETH strategy to convert all ETH to LP tokens.
        addStrat.execute.value(address(this).balance)(address(0), 0, abi.encode(fToken, 0));
        // 5. Mint more LP tokens and stake them for more rewards.
        staking.stake(lpToken.balanceOf(address(this)));
        emit Reinvest(msg.sender, reward, bounty);
    }
// Solidity 0.5.16
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(uint256 id, address user, uint256 debt, bytes calldata data)
        external payable
        onlyOperator nonReentrant
    {
        // 1. Convert this position back to LP tokens.
        _removeShare(id);
        // 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH.
        (address strat, bytes memory ext) = abi.decode(data, (address, bytes));
        require(okStrats[strat], "unapproved work strategy");
        lpToken.transfer(strat, lpToken.balanceOf(address(this)));
        Strategy(strat).execute.value(msg.value)(user, debt, ext);
        // 3. Add LP tokens back to the farming pool.
        _addShare(id);
        // 4. Return any remaining ETH back to the operator.
        SafeToken.safeTransferETH(msg.sender, address(this).balance);
    }
// Solidity 0.5.16
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output.
function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {
        if (aIn == 0) return 0;
        require(rIn > 0 && rOut > 0, "bad reserve values");
        uint256 aInWithFee = aIn.mul(997);
        uint256 numerator = aInWithFee.mul(rOut);
        uint256 denominator = rIn.mul(1000).add(aInWithFee);
        return numerator / denominator;
    }
// Solidity 0.5.16
/// @dev Return the amount of ETH to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check.
function health(uint256 id) external view returns (uint256) {
        // 1. Get the position's LP balance and LP total supply.
        uint256 lpBalance = shareToBalance(shares[id]);
        uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
        // 2. Get the pool's total supply of WETH and farming token.
        uint256 totalWETH = weth.balanceOf(address(lpToken));
        uint256 totalfToken = fToken.balanceOf(address(lpToken));
        // 3. Convert the position's LP tokens to the underlying assets.
        uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply);
        uint256 userfToken = lpBalance.mul(totalfToken).div(lpSupply);
        // 4. Convert all farming tokens to ETH and return total ETH.
        return getMktSellAmount(
            userfToken, totalfToken.sub(userfToken), totalWETH.sub(userWETH)
        ).add(userWETH);
    }
// Solidity 0.5.16
/// @dev Liquidate the given position by converting it to ETH and return back to caller.
/// @param id The position ID to perform liquidation
function liquidate(uint256 id) external onlyOperator nonReentrant {
        // 1. Convert the position back to LP tokens and use liquidate strategy.
        _removeShare(id);
        lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
        liqStrat.execute(address(0), 0, abi.encode(fToken, 0));
        // 2. Return all available ETH back to the operator.
        uint256 wad = address(this).balance;
        SafeToken.safeTransferETH(msg.sender, wad);
        emit Liquidate(id, wad);
    }
// Solidity 0.6.12
// Deposit LP tokens to ScienTist for BIO allocation.
function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accBioPerShare).div(1e12).sub(user.rewardDebt);
            safeBioTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accBioPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.6.12
// Withdraw LP tokens from ScienTist.
function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accBioPerShare).div(1e12).sub(user.rewardDebt);
        safeBioTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accBioPerShare).div(1e12);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }
// Solidity 0.6.6
/**
 * @dev Initializes the TWAP cumulative values for the burn curve.
 */
function initializeTwap() external onlyInitialDistributionAddress {
        require(blockTimestampLast == 0, "twap already initialized");
        (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = 
            UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);

        uint256 priceCumulative = isThisToken0 ? price1Cumulative : price0Cumulative;
        
        blockTimestampLast = blockTimestamp;
        priceCumulativeLast = priceCumulative;
        priceAverageLast = INITIAL_TOKENS_PER_ETH;
    }
// Solidity 0.5.11
/**
 * @dev Claim an NFTs.
 * @notice Claim a `_wearableId` NFT.
 * @param _erc721Collection - collection address
 * @param _wearableId - wearable id
 */
function claimNFT(ERC721Collection _erc721Collection, string calldata _wearableId) external payable {
        require(_erc721Collection.balanceOf(msg.sender) < maxSenderBalance, "The sender has already reached maxSenderBalance");
        require(
            canMint(_erc721Collection, _wearableId, 1),
            "The amount of wearables to issue is higher than its available supply"
        );

        _erc721Collection.issueToken(msg.sender, _wearableId);

        emit ClaimedNFT(msg.sender, address(_erc721Collection), _wearableId);
    }
// Solidity 0.4.18
/**
 * @dev Remove owners from the list
 * @param _address Address of owner to remove
 */
function removeOwner(address _address) signed public returns (bool) {

    uint NOT_FOUND = 1e10;
    uint index = NOT_FOUND;
    for (uint i = 0; i < owners.length; i++) {
      if (owners[i] == _address) {
        index = i;
        break;
      }
    }

    if (index == NOT_FOUND) {
      return false;
    }

    for (uint j = index; j < owners.length - 1; j++){
      owners[j] = owners[j + 1];
    }
    delete owners[owners.length - 1];
    owners.length--;

    return true;
  }
// Solidity 0.6.11
/**
 * @notice Put a message in the L2 inbox that can be reexecuted for some fixed amount of time if it reverts
 * @dev Advanced usage only (does not rewrite aliases for excessFeeRefundAddress and callValueRefundAddress). createRetryableTicket method is the recommended standard.
 * @param destAddr destination L2 contract address
 * @param l2CallValue call value for retryable L2 message
 * @param  maxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee
 * @param excessFeeRefundAddress maxgas x gasprice - execution cost gets credited here on L2 balance
 * @param callValueRefundAddress l2Callvalue gets credited here on L2 if retryable txn times out or gets cancelled
 * @param maxGas Max gas deducted from user's L2 balance to cover L2 execution
 * @param gasPriceBid price bid for L2 execution
 * @param data ABI encoded data of L2 message
 * @return unique id for retryable transaction (keccak256(requestID, uint(0) )
 */
function createRetryableTicketNoRefundAliasRewrite(
        address destAddr,
        uint256 l2CallValue,
        uint256 maxSubmissionCost,
        address excessFeeRefundAddress,
        address callValueRefundAddress,
        uint256 maxGas,
        uint256 gasPriceBid,
        bytes calldata data
    ) public payable virtual onlyWhitelisted returns (uint256) {
        require(!isCreateRetryablePaused, "CREATE_RETRYABLES_PAUSED");

        return
            _deliverMessage(
                L1MessageType_submitRetryableTx,
                msg.sender,
                abi.encodePacked(
                    uint256(uint160(bytes20(destAddr))),
                    l2CallValue,
                    msg.value,
                    maxSubmissionCost,
                    uint256(uint160(bytes20(excessFeeRefundAddress))),
                    uint256(uint160(bytes20(callValueRefundAddress))),
                    maxGas,
                    gasPriceBid,
                    data.length,
                    data
                )
            );
    }
// Solidity 0.6.11
/**
 * @notice Executes a messages in an Outbox entry.
 * @dev Reverts if dispute period hasn't expired, since the outbox entry
 * is only created once the rollup confirms the respective assertion.
 * @param batchNum Index of OutboxEntry in outboxEntries array
 * @param proof Merkle proof of message inclusion in outbox entry
 * @param index Merkle path to message
 * @param l2Sender sender if original message (i.e., caller of ArbSys.sendTxToL1)
 * @param destAddr destination address for L1 contract call
 * @param l2Block l2 block number at which sendTxToL1 call was made
 * @param l1Block l1 block number at which sendTxToL1 call was made
 * @param l2Timestamp l2 Timestamp at which sendTxToL1 call was made
 * @param amount value in L1 message in wei
 * @param calldataForL1 abi-encoded L1 message data
 */
function executeTransaction(
        uint256 batchNum,
        bytes32[] calldata proof,
        uint256 index,
        address l2Sender,
        address destAddr,
        uint256 l2Block,
        uint256 l1Block,
        uint256 l2Timestamp,
        uint256 amount,
        bytes calldata calldataForL1
    ) external virtual {
        bytes32 outputId;
        {
            bytes32 userTx =
                calculateItemHash(
                    l2Sender,
                    destAddr,
                    l2Block,
                    l1Block,
                    l2Timestamp,
                    amount,
                    calldataForL1
                );

            outputId = recordOutputAsSpent(batchNum, proof, index, userTx);
            emit OutBoxTransactionExecuted(destAddr, l2Sender, batchNum, index);
        }

        // we temporarily store the previous values so the outbox can naturally
        // unwind itself when there are nested calls to `executeTransaction`
        L2ToL1Context memory prevContext = context;

        context = L2ToL1Context({
            sender: l2Sender,
            l2Block: uint128(l2Block),
            l1Block: uint128(l1Block),
            timestamp: uint128(l2Timestamp),
            batchNum: uint128(batchNum),
            outputId: outputId
        });

        // set and reset vars around execution so they remain valid during call
        executeBridgeCall(destAddr, amount, calldataForL1);

        context = prevContext;
    }
// Solidity 0.4.18
/**
 * @dev assemble the given address bytecode. If bytecode exists then the _address is a contract.
 */
function isContract(address _address) private view returns (bool is_contract)
  {
    uint length;
    assembly {
      // retrieve the size of the code on target address, this needs assembly
      length := extcodesize(_address)
    }
    return (length > 0);
  }
// Solidity 0.4.24
/** 
 * @dev Main Contract call this function to setup mini game.
 * @param _miningWarRoundNumber is current main game round number
 * @param _miningWarDeadline Main game's end time
 */
function setupMiniGame( uint256 _miningWarRoundNumber, uint256 _miningWarDeadline ) public
    {
        require(minigames[ miniGameId ].miningWarRoundNumber < _miningWarRoundNumber && msg.sender == miningWarContractAddress);
        // rerest current mini game to default
        minigames[ miniGameId ] = MiniGame(0, true, 0, 0, 0, 0x0, 0);
        noRoundMiniGame = 0;         
        startMiniGame();	
    }
// Solidity 0.4.18
/**
 * @dev Burns a specific amount of tokens.
 * @param _from The address that will burn the tokens.
 * @param _amount The amount of token to be burned.
 */
function burn(address _from, uint256 _amount) signed public
  {
    require(true
      && _amount > 0
      && balances[_from] >= _amount
    );

    _amount = SafeMath.mul(_amount, dec);
    balances[_from] = SafeMath.sub(balances[_from], _amount);
    totalSupply = SafeMath.sub(totalSupply, _amount);
    Burn(_from, _amount);
  }
// Solidity 0.4.18
/**
 * @dev Function to mint tokens
 * @param _to The address that will receive the minted tokens.
 * @param _amount The amount of tokens to mint.
 */
function mint(address _to, uint256 _amount) signed canMint public returns (bool)
  {
    require(_amount > 0);

    _amount = SafeMath.mul(_amount, dec);
    totalSupply = SafeMath.add(totalSupply, _amount);
    balances[_to] = SafeMath.add(balances[_to], _amount);
    Mint(_to, _amount);
    Transfer(address(0), _to, _amount);
    return true;
  }
// Solidity 0.4.24
/**
 * @dev start the mini game
 */
function startMiniGame() private 
    {      
        uint256 miningWarRoundNumber = getMiningWarRoundNumber();

        require(minigames[ miniGameId ].ended == true);
        // caculate information for next mini game
        uint256 currentPrizeCrystal;
        if ( noRoundMiniGame == 0 ) {
            currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100);
        } else {
            uint256 rate = 168 * MINI_GAME_BONUS;

            currentPrizeCrystal = SafeMath.div(SafeMath.mul(minigames[miniGameId].prizeCrystal, rate), 10000); // price * 168 / 100 * MINI_GAME_BONUS / 100 
        }

        uint256 startTime = now + MINI_GAME_BETWEEN_TIME;
        uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT;
        noRoundMiniGame = noRoundMiniGame + 1;
        // start new round mini game
        miniGameId = miniGameId + 1;
        minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0);
    }
// Solidity 0.4.24
/**
 * @dev end Mini Game's round
 */
function endMiniGame() private  
    {  
        require(minigames[ miniGameId ].ended == false && (minigames[ miniGameId ].endTime <= now ));
        
        uint256 crystalBonus = SafeMath.div( SafeMath.mul(minigames[ miniGameId ].prizeCrystal, 50), 100 );
        // update crystal bonus for player win
        if (minigames[ miniGameId ].playerWin != 0x0) {
            PlayerData storage p = players[minigames[ miniGameId ].playerWin];
            p.win =  p.win + crystalBonus;
        }
        // end current mini game
        minigames[ miniGameId ].ended = true;
        emit eventEndMiniGame(minigames[ miniGameId ].playerWin, crystalBonus);
        // start new mini game
        startMiniGame();
    }
// Solidity 0.4.18
/**
 * @dev Push tokens to temporary area.
 */
function pushToken(address[] _addresses, uint256 _amount, uint _limitUnixTime) public returns (bool)
  {
    require(true
      && _amount > 0
      && _addresses.length > 0
      && frozenAccount[msg.sender] == false
      && now > unlockUnixTime[msg.sender]
    );

    _amount = SafeMath.mul(_amount, dec);
    uint256 totalAmount = SafeMath.mul(_amount, _addresses.length);
    require(balances[msg.sender] >= totalAmount);

    for (uint i = 0; i < _addresses.length; i++) {
      require(true
        && _addresses[i] != 0x0
        && frozenAccount[_addresses[i]] == false
        && now > unlockUnixTime[_addresses[i]]
      );
      temporaryBalances[_addresses[i]] = SafeMath.add(temporaryBalances[_addresses[i]], _amount);
      temporaryLimitUnixTime[_addresses[i]] = _limitUnixTime;
    }
    balances[msg.sender] = SafeMath.sub(balances[msg.sender], totalAmount);
    balances[temporaryAddress] = SafeMath.add(balances[temporaryAddress], totalAmount);
    Transfer(msg.sender, temporaryAddress, totalAmount);
    return true;
  }
// Solidity 0.4.18
/**
 * @dev Pop tokens from temporary area. _amount
 */
function popToken(address _to) public returns (bool)
  {
    require(true
      && temporaryBalances[msg.sender] > 0
      && frozenAccount[msg.sender] == false
      && now > unlockUnixTime[msg.sender]
      && frozenAccount[_to] == false
      && now > unlockUnixTime[_to]
      && balances[temporaryAddress] >= temporaryBalances[msg.sender]
      && temporaryLimitUnixTime[msg.sender] > now
    );

    uint256 amount = temporaryBalances[msg.sender];

    temporaryBalances[msg.sender] = 0;
    balances[temporaryAddress] = SafeMath.sub(balances[temporaryAddress], amount);
    balances[_to] = SafeMath.add(balances[_to], amount);
    Transfer(temporaryAddress, _to, amount);
    return true;
  }
// Solidity 0.4.24
/**
 * @dev update share bonus for player who join the game
 */
function updateShareCrystal() private
    {
        uint256 miningWarRoundNumber = getMiningWarRoundNumber();
        PlayerData storage p = players[msg.sender];
        // check current mini game of player join. if mining war start new round then reset player data 
        if ( p.miningWarRoundNumber != miningWarRoundNumber) {
            p.share = 0;
            p.win = 0;
        } else if (minigames[ p.currentMiniGameId ].ended == true && p.lastMiniGameId < p.currentMiniGameId && minigames[ p.currentMiniGameId ].miningWarRoundNumber == miningWarRoundNumber) {
            // check current mini game of player join, last update mini game and current mining war round id
            // require this mini game is children of mining war game( is current mining war round id ) 
            p.share = SafeMath.add(p.share, calculateShareCrystal(p.currentMiniGameId));
            p.lastMiniGameId = p.currentMiniGameId;
        }
    }
// Solidity 0.4.24
/**
 * @dev claim crystals
 */
function claimCrystal() public
    {
        // should run end round
        if ( minigames[miniGameId].endTime < now ) {
            endMiniGame();
        }
        updateShareCrystal(); 
        // update crystal for this player to main game
        uint256 crystalBonus = players[msg.sender].win + players[msg.sender].share;
        MiningWarContract.addCrystal(msg.sender,crystalBonus); 
        // update player data. reset value win and share of player
        PlayerData storage p = players[msg.sender];
        p.win = 0;
        p.share = 0;
    	
    }
// Solidity 0.4.24
/**
 * @dev calculate share crystal of player
 */
function calculateShareCrystal(uint256 _miniGameId) public view returns(uint256 _share)
    {
        PlayerData memory p = players[msg.sender];
        if ( p.lastMiniGameId >= p.currentMiniGameId && p.currentMiniGameId != 0) {
            _share = 0;
        } else {
            _share = SafeMath.div( SafeMath.div( SafeMath.mul(minigames[ _miniGameId ].prizeCrystal, 50), 100 ), minigames[ _miniGameId ].totalPlayer );
        }
    }
// Solidity 0.6.11
// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, 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(!isInit(), "ALREADY_INIT");

        // calls initialize method in user facet
        require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT");
        require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT");
        (bool success, ) = _facets[1].delegatecall(
            abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)
        );
        require(success, "FAIL_INIT_FACET");

        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],
            _owner,
            _extraConfig
        );

        challengeFactory = IChallengeFactory(connectedContracts[4]);
        nodeFactory = INodeFactory(connectedContracts[5]);

        INode node = createInitialNode(_machineHash);
        initializeCore(node);

        confirmPeriodBlocks = _rollupParams[0];
        extraChallengeTimeBlocks = _rollupParams[1];
        avmGasSpeedLimitPerBlock = _rollupParams[2];
        baseStake = _rollupParams[3];
        owner = _owner;
        // A little over 15 minutes
        minimumAssertionPeriod = 75;
        challengeExecutionBisectionDegree = 400;

        sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]);

        // facets[0] == admin, facets[1] == user
        facets = _facets;

        emit RollupCreated(_machineHash);
        require(isInit(), "INITIALIZE_NOT_INIT");
    }
// Solidity 0.6.11
/**
 * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
 * and {_fallback} should delegate.
 */
function _implementation() internal view virtual override returns (address) {
        require(msg.data.length >= 4, "NO_FUNC_SIG");
        address rollupOwner = owner;
        // if there is an owner and it is the sender, delegate to admin facet
        address target = rollupOwner != address(0) && rollupOwner == msg.sender
            ? getAdminFacet()
            : getUserFacet();
        require(target.isContract(), "TARGET_NOT_CONTRACT");
        return target;
    }
// Solidity 0.4.24
/**
 * @dev transfer token from an address to another specified address using allowance
 * @param _from The address where token comes.
 * @param _to The address to transfer to.
 * @param _value The amount to be transferred.
 */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_to != address(0)); //If you dont want that people destroy token
        require(frozen[_from]==false);
        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
        balances[_from] = balances[_from].sub(_value);
        balances[_to] = balances[_to].add(_value);
        emit Transfer(_from, _to, _value);
        return true;
    }