lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.25
/// @notice Perform exchange-specific checks on the given order
/// @dev This should be called to check for payload errors
/// @param data LibOrder.Order struct containing order values
/// @return checksPassed value representing pass or fail
function staticExchangeChecks_(
        OrderData data
    )
        public
        view
        onlySelf
        returns (bool checksPassed)
    {

        // Make sure that:
        //  The order is not expired
        //  Both the maker and taker assets are ERC20 tokens
        //  The taker does not have to pay a fee (we don't support fees yet)
        //  We are permitted to take this order
        //  We are permitted to send this order
        // TODO: Should we check signatures here?
        return (block.timestamp <= data.expirationTimeSeconds &&
                toBytes4(data.takerAssetData, 0) == bytes4(0xf47261b0) &&
                toBytes4(data.makerAssetData, 0) == bytes4(0xf47261b0) &&
                data.takerFee == 0 &&
                (data.takerAddress == address(0x0) || data.takerAddress == address(this)) &&
                (data.senderAddress == address(0x0) || data.senderAddress == address(this))
        );
    }
// Solidity 0.4.25
/// @notice Perform a buy order at the exchange
/// @param data LibOrder.Order struct containing order values
/// @return amountSpentOnOrder the amount that would be spent on the order
/// @return amountReceivedFromOrder the amount that was received from this order
function performBuyOrder_(
        OrderData data
    )
        public
        payable
        onlySelf
        returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
    {
        uint256 amountToGiveForOrder = toUint(msg.data, msg.data.length - 32);

        approveAddress(ERC20_ASSET_PROXY, toAddress(data.takerAssetData, 16));

        weth.deposit.value(amountToGiveForOrder)();

        LibFillResults.FillResults memory results = exchange.fillOrder(
            getZeroExOrder(data),
            amountToGiveForOrder,
            data.signature
        );
        require(ERC20SafeTransfer.safeTransfer(toAddress(data.makerAssetData, 16), totlePrimary, results.makerAssetFilledAmount));

        amountSpentOnOrder = results.takerAssetFilledAmount;
        amountReceivedFromOrder = results.makerAssetFilledAmount;
        /* logger.log("Performed buy order on ZeroEx arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder); */
    }
// Solidity 0.8.4
// utility functions
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
		if (_i == 0) {
			return "0";
		}
		uint256 j = _i;
		uint256 len;
		while (j != 0) {
			len++;
			j /= 10;
		}
		bytes memory bstr = new bytes(len);
		uint256 k = len;
		while (_i != 0) {
			k = k - 1;
			uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
			bytes1 b1 = bytes1(temp);
			bstr[k] = b1;
			_i /= 10;
		}
		return string(bstr);
	}
// Solidity 0.4.19
/*
 Restricted functions (owner only)
 */
function reject(address applicant)
    public
    onlyOwner
    onlyPendingApplication(applicant)
    {
        applications[applicant].state = ApplicationState.Rejected;

        // protection against function reentry on an overriden transfer() function
        uint contribution = applications[applicant].contribution;
        applications[applicant].contribution = 0;
        applicant.transfer(contribution);

        contributionPending -= contribution;
        contributionRejected += contribution;

        RejectedApplication(applicant, contribution, applications[applicant].id);
    }
// Solidity 0.7.1
/// @notice Add/replace/remove any number of functions and optionally execute
///         a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
///                  _calldata is executed with delegatecall on _init
function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external override {
        LibDiamond.enforceIsContractOwner();
        LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
        uint256 originalSelectorCount = ds.selectorCount;
        uint256 selectorCount = originalSelectorCount;
        bytes32 selectorSlot;
        // Check if last selector slot is not full
        if (selectorCount % 8 > 0) {
            // get last selectorSlot
            selectorSlot = ds.selectorSlots[selectorCount / 8];
        }
        // loop through diamond cut
        for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
            (selectorCount, selectorSlot) = LibDiamond.addReplaceRemoveFacetSelectors(
                selectorCount,
                selectorSlot,
                _diamondCut[facetIndex].facetAddress,
                _diamondCut[facetIndex].action,
                _diamondCut[facetIndex].functionSelectors
            );
        }
        if (selectorCount != originalSelectorCount) {
            ds.selectorCount = uint16(selectorCount);
        }
        // If last selector slot is not full
        if (selectorCount % 8 > 0) {
            ds.selectorSlots[selectorCount / 8] = selectorSlot;
        }
        emit DiamondCut(_diamondCut, _init, _calldata);
        LibDiamond.initializeDiamondCut(_init, _calldata);
    }
// Solidity 0.5.8
/**
 * @param tokenAmount Amount of tokens to swap with bep2
 * @param BNB_Address address of Binance Chain to which to receive the bep2 tokens
 */
function swap(uint tokenAmount, string memory BNB_Address) public returns(bool) {
        
        bool success = token.transferFrom(msg.sender, owner, tokenAmount);
        
        if(!success) {
            revert("Transfer of tokens to Swap contract failed.");
        }
        
        emit Swaped(tokenAmount, BNB_Address);
        
        return true;
        
    }
// Solidity 0.4.24
/**
 	* @dev Moves specified amount of tokens from main balance to mining balance 
 	* @param _amount An uint256 representing the amount of tokens to transfer to main balance
 	*/
function depositToMiningBalance(uint _amount) public {
		require(balances[msg.sender] >= _amount, "not enough tokens");
		require(getCurrentDayDeposited().add(_amount) <= DAY_MINING_DEPOSIT_LIMIT,
			"Day mining deposit exceeded");
		require(miningTotalDeposited.add(_amount) <= TOTAL_MINING_DEPOSIT_LIMIT,
			"Total mining deposit exceeded");

		balances[msg.sender] = balances[msg.sender].sub(_amount);
		miningBalances[msg.sender] = miningBalances[msg.sender].add(_amount);
		miningTotalDeposited = miningTotalDeposited.add(_amount);
		updateCurrentDayDeposited(_amount);
		lastMiningBalanceUpdateTime[msg.sender] = now;
		emit MiningBalanceUpdated(msg.sender, _amount, true);
	}
// Solidity 0.4.24
/**
 	* @dev Get number of days for reward on mining. Maximum 100 days.
 	* @return An uint256 representing number of days user will get reward for.
 	*/
function getDaysForReward() public view returns (uint rewardDaysNum){
		if(lastMiningBalanceUpdateTime[msg.sender] == 0) {
			return 0;
		} else {
			uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days);
			if(value > 100) {
				return 100;
			} else {
				return value;
			}
		}
	}
// Solidity 0.4.24
/**
 	* @dev Calculate current mining reward based on total supply of tokens
 	* @return An uint256 representing reward in percents multiplied by 1000000000
 	*/
function getReward(uint _totalSupply) public pure returns (uint rewardPercent){
		uint rewardFactor = 1000000 * (10 ** uint256(decimals));
		uint decreaseFactor = 41666666;

		if(_totalSupply < 23 * rewardFactor) {
			return 2000000000 - (decreaseFactor.mul(_totalSupply.div(rewardFactor)));
		}

		if(_totalSupply < MAX_SUPPLY) {
			return 1041666666;
		} else {
			return 1000000000;
		} 
	}
// Solidity 0.5.11
/**
 * @dev Receive payment in ether and return tokens.
 */
function buyTokens() payable public {
        require(msg.value>=getPrice(),'Tx value cannot be lower than price of 1 token');
        uint256 amount = msg.value.div(getPrice());
        ERC20 erc20 = ERC20(token);
        require(erc20.balanceOf(address(this))>=amount,"Sorry, token vendor does not possess enough tokens for this purchase");
        erc20.transfer(msg.sender,amount);
        emit TokensBought(msg.sender,amount);
    }
// Solidity 0.5.11
/**
 * @dev Receive payment in tokens and return ether. 
 * Only usable by accounts which allowed the smart contract to transfer tokens from their account.
 */
function sellTokens(uint256 _amount) public {
        require(_amount>0,'You cannot sell 0 tokens');
        uint256 ethToSend = _amount.mul(getPrice());
        require(address(this).balance>=ethToSend,'Sorry, vendor does not possess enough Ether to trade for your tokens');
        ERC20 erc20 = ERC20(token);
        require(erc20.balanceOf(msg.sender)>=_amount,"You cannot sell more tokens than you own on your balance");
        require(erc20.allowance(msg.sender,address(this))>=_amount,"You need to allow this contract to transfer enough tokens from your account");
        erc20.transferFrom(msg.sender,address(this),_amount);
        msg.sender.transfer(ethToSend);
        emit TokensSold(msg.sender,_amount);
    }
// Solidity 0.8.7
/**
 * @notice Update royalty info for collection
 * @param collection address of the NFT contract
 * @param setter address that sets the receiver
 * @param receiver receiver for the royalty fee
 * @param fee fee (500 = 5%, 1,000 = 10%)
 */
function updateRoyaltyInfoForCollection(
        address collection,
        address setter,
        address receiver,
        uint256 fee
    ) external override onlyOwner {
        require(fee <= royaltyFeeLimit, "Registry: Royalty fee too high");
        _royaltyFeeInfoCollection[collection] = FeeInfo({
            setter: setter,
            receiver: receiver,
            fee: fee
        });

        emit RoyaltyFeeUpdate(collection, setter, receiver, fee);
    }
// Solidity 0.4.24
/**
 * @dev Get random number.
 * @dev Random number calculation depends on block timestamp,
 * @dev difficulty, number and hash.
 *
 * @param min Minimal number.
 * @param max Maximum number.
 * @param time Timestamp.
 * @param difficulty Block difficulty.
 * @param number Block number.
 * @param bHash Block hash.
 */
function randomNumber(
        uint min,
        uint max,
        uint time,
        uint difficulty,
        uint number,
        bytes32 bHash
    ) 
        public 
        pure 
        returns (uint) 
    {
        min ++;
        max ++;

        uint random = uint(keccak256(
            time * 
            difficulty * 
            number *
            uint(bHash)
        ))%10 + 1;
       
        uint result = uint(keccak256(random))%(min+max)-min;
        
        if (result > max) {
            result = max;
        }
        
        if (result < min) {
            result = min;
        }
        
        result--;

        return result;
    }
// Solidity 0.4.24
/**
 * @dev Start the new game.
 * @dev Checks ticket price changes, if exists new ticket price the price will be changed.
 * @dev Checks game status changes, if exists request for changing game status game status 
 * @dev will be changed.
 */
function startGame() internal {
        require(isActive);

        game = block.number;
        if (newPrice != 0) {
            ticketPrice = newPrice;
            newPrice = 0;
        }
        if (toogleStatus) {
            isActive = !isActive;
            toogleStatus = false;
        }
        emit Game(game, now);
    }
// Solidity 0.4.24
/**
 * @dev Pick the winner.
 * @dev Check game players, depends on player count provides next logic:
 * @dev - if in the game is only one player, by game rules the whole jackpot 
 * @dev without commission returns to him.
 * @dev - if more than one player smart contract randomly selects one player, 
 * @dev calculates commission and after that jackpot transfers to the winner,
 * @dev commision to founders.
 */
function pickTheWinner() internal {
        uint winner;
        uint toPlayer;
        if (players[game].length == 1) {
            toPlayer = jackpot[game];
            players[game][0].transfer(jackpot[game]);
            winner = 0;
        } else {
            winner = randomNumber(
                0,
                players[game].length - 1,
                block.timestamp,
                block.difficulty,
                block.number,
                blockhash(block.number - 1)
            );
        
            uint distribute = jackpot[game] * fee / 100;
            toPlayer = jackpot[game] - distribute;
            players[game][winner].transfer(toPlayer);

            transferToPartner(players[game][winner]);
            
            distribute -= paidToPartners;
            bool result = address(fundsDistributor).call.gas(30000).value(distribute)();
            if (!result) {
                revert();
            }
        }
    
        paidToPartners = 0;
        stats.newWinner(
            players[game][winner],
            game,
            players[game].length,
            toPlayer,
            gType,
            winner
        );
        
        allTimeJackpot += toPlayer;
        allTimePlayers += players[game].length;
    }
// Solidity 0.4.24
/**
 * @dev Checks if the player is in referral system.
 * @dev Sending earned ether to partners.
 *
 * @param partner Partner address.
 * @param referral Player address.
 */
function processReferralSystem(address partner, address referral) 
        internal 
    {
        address partnerRef = referralInstance.getPartnerByReferral(referral);
        if (partner != address(0) || partnerRef != address(0)) {
            if (partnerRef == address(0)) {
                referralInstance.addReferral(partner, referral);
                partnerRef = partner;
            }

            if (players[game].length > 1) {
                transferToPartner(referral);
            }
        }
    }
// Solidity 0.4.24
/**
 * @dev Sending earned ether to partners.
 *
 * @param referral Player address.
 */
function transferToPartner(address referral) internal {
        address partner = referralInstance.getPartnerByReferral(referral);
        if (partner != address(0)) {
            uint sum = getPartnerAmount(partner);
            if (sum != 0) {
                partner.transfer(sum);
                paidToPartners += sum;

                emit ToPartner(partner, referral, sum, now);

                transferToSalesPartner(partner);
            }
        }
    }
// Solidity 0.4.24
/**
 * @dev Sending earned ether to sales partners.
 *
 * @param partner Partner address.
 */
function transferToSalesPartner(address partner) internal {
        address salesPartner = referralInstance.getSalesPartner(partner);
        if (salesPartner != address(0)) {
            uint sum = getSalesPartnerAmount(partner);
            if (sum != 0) {
                salesPartner.transfer(sum);
                paidToPartners += sum;

                emit ToSalesPartner(salesPartner, partner, sum, now);
            } 
        }
    }
// Solidity 0.5.16
/**
 * Uses the Curve protocol to convert the wbtc asset into to mixed renwbtc token.
 */
function mixFromWBTC() internal {
    uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));
    if (wbtcBalance > 0) {
      IERC20(wbtc).safeApprove(curve, 0);
      IERC20(wbtc).safeApprove(curve, wbtcBalance);
      // we can accept 0 as minimum because this is called only by a trusted role
      uint256 minimum = 0;
      uint256[2] memory coinAmounts = wrapCoinAmount(wbtcBalance);
      ICurveFiWbtc(curve).add_liquidity(
        coinAmounts, minimum
      );
    }
    // now we have the mixed token
  }
// Solidity 0.5.16
/**
 * Uses the Curve protocol to convert the mixed token back into the wbtc asset. If it cannot
 * acquire the limit amount, it will acquire the maximum it can.
 */
function mixToWBTC(uint256 wbtcLimit) internal {
    uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));

    // this is the maximum number of wbtc we can get for our mixed token
    uint256 wbtcMaximumAmount = wbtcValueFromMixToken(mixTokenBalance);
    if (wbtcMaximumAmount == 0) {
      return;
    }

    if (wbtcLimit < wbtcMaximumAmount) {
      // we want less than what we can get, we ask for the exact amount
      // now we can remove the liquidity
      uint256[2] memory tokenAmounts = wrapCoinAmount(wbtcLimit);
      IERC20(mixToken).safeApprove(curve, 0);
      IERC20(mixToken).safeApprove(curve, mixTokenBalance);
      ICurveFiWbtc(curve).remove_liquidity_imbalance(
        tokenAmounts, mixTokenBalance
      );
    } else {
      // we want more than we can get, so we withdraw everything
      IERC20(mixToken).safeApprove(curve, 0);
      IERC20(mixToken).safeApprove(curve, mixTokenBalance);
      ICurveFiWbtc(curve).remove_liquidity_one_coin(mixTokenBalance, int128(tokenIndex), 0);
    }
    // now we have wbtc asset
  }
// Solidity 0.5.16
/**
 * Withdraws an wbtc asset from the strategy to the vault in the specified amount by asking
 * by removing imbalanced liquidity from the Curve protocol. The rest is deposited back to the
 * Curve protocol pool. If the amount requested cannot be obtained, the method will get as much
 * as we have.
 */
function withdrawToVault(uint256 amountWbtc) external restricted {
    // withdraw all from gauge
    Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
    // convert the mix to WBTC, but get at most amountWbtc
    mixToWBTC(amountWbtc);
    // we can transfer the asset to the vault
    uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));
    if (actualBalance > 0) {
      IERC20(wbtc).safeTransfer(vault, Math.min(amountWbtc, actualBalance));
    }

    // invest back the rest
    investAllUnderlying();
  }
// Solidity 0.5.16
/**
 * Withdraws all assets from the vault.
 */
function withdrawAllToVault() external restricted {
    // withdraw all from gauge
    Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
    // convert the mix to WBTC, we want the entire balance
    mixToWBTC(uint256(~0));
    // we can transfer the asset to the vault
    uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));
    if (actualBalance > 0) {
      IERC20(wbtc).safeTransfer(vault, actualBalance);
    }
  }
// Solidity 0.5.16
/**
 * Invests all wbtc assets into our mixToken vault.
 */
function investAllUnderlying() internal {
    // convert the entire balance not yet invested into mixToken first
    mixFromWBTC();

    // then deposit into the mixToken vault
    uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));
    if (mixTokenBalance > 0) {
      IERC20(mixToken).safeApprove(gauge, 0);
      IERC20(mixToken).safeApprove(gauge, mixTokenBalance);
      Gauge(gauge).deposit(mixTokenBalance);
    }
  }
// Solidity 0.5.16
/**
 * Salvages a token. We cannot salvage mixToken tokens, CRV, or wbtc assets.
 */
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
    // To make sure that governance cannot come in and take away the coins
    require(!unsalvagableTokens[token], "token is defined as not salvageable");
    IERC20(token).safeTransfer(recipient, amount);
  }
// Solidity 0.5.16
/**
 * Returns the wbtc invested balance. The is the wbtc amount in this stragey, plus the gauge
 * amount of the mixed token converted back to wbtc.
 */
function investedUnderlyingBalance() public view returns (uint256) {
    uint256 gaugeBalance = Gauge(gauge).balanceOf(address(this));
    uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));
    if (gaugeBalance == 0) {
      // !!! if we have 0 balance in gauge, the conversion to wbtc reverts in Curve
      // !!! this if-statement is necessary to avoid transaction reverts
      return wbtcBalance;
    }
    uint256 investedBalance = wbtcValueFromMixToken(gaugeBalance);
    return investedBalance.add(wbtcBalance);
  }
// Solidity 0.5.16
/**
 * Claims the CRV crop, converts it to WBTC/renWBTC on Uniswap
 */
function claimAndLiquidateCrv() internal {
    if (!sell) {
      // Profits can be disabled for possible simplified and rapid exit
      emit ProfitsNotCollected();
      return;
    }
    Mintr(mintr).mint(gauge);
    // claiming rewards and liquidating them
    uint256 crvBalance = IERC20(crv).balanceOf(address(this));
    emit Liquidating(crvBalance);
    if (crvBalance > sellFloor) {
      uint256 wbtcBalanceBefore = IERC20(wbtc).balanceOf(address(this));
      IERC20(crv).safeApprove(uni, 0);
      IERC20(crv).safeApprove(uni, crvBalance);
      // we can accept 1 as the minimum because this will be called only by a trusted worker
      IUniswapV2Router02(uni).swapExactTokensForTokens(
        crvBalance, 1, uniswap_CRV2WBTC, address(this), block.timestamp
      );

      // now we have WBTC
      notifyProfit(wbtcBalanceBefore, IERC20(wbtc).balanceOf(address(this)));
    }
  }
// Solidity 0.5.7
/**
 * Allows user to destroy a specified token
 * This would allow a user to claim his prize for the destroyed token
 * @param _tokenId uint256 ID of the token
 */
function claimReward(uint256 _tokenId) public {
        require(winningTokenId > 0, "The is not winner yet!");
        require(_tokenId == winningTokenId, "This token is not the winner!");
        
        ensureAddressIsTokenOwner(msg.sender, _tokenId);
        
        winnerAddress = msg.sender;
        
        emit RewardIsClaimed(msg.sender, _tokenId);
    }
// Solidity 0.5.7
/**
 * Allows the buyer of at least the number of WLC tokens, specified in WLCRewardAmount
 * to receive a DCC as a bonus.
 * This can only be called by the deployed WLC contract, by the address specified in WLCAdress
 * @param _boughtWLCAmount uint256 the number of bought WLC tokens
 * @param _owner address the address of the buyer
 */
function getWLCReward(uint256 _boughtWLCAmount, address _owner) public returns (uint256 _remaining) {
        if (WLCAdress != address(0) && WLCRewardAmount > 0 && _boughtWLCAmount >= WLCRewardAmount) {
            require(WLCAdress == msg.sender, "You cannot invoke this function directly!");
            
            uint256 DCCAmount = scalePurchaseTokenAmountToMatchRemainingTokens(_boughtWLCAmount / WLCRewardAmount);
            
            if (DCCAmount > 0) {
                _addTokensToAddress(_owner, DCCAmount);
                
                emit Buy(_owner, DCCAmount, nextTokenId - DCCAmount, nextTokenId - 1);
                
                chooseWinner();
                
                return _boughtWLCAmount - (DCCAmount * WLCRewardAmount);
            }
        }
        
        return _boughtWLCAmount;
    }
// Solidity 0.5.7
/**
 * Allows an onwer of WLC token to excange it for DCC token
 * This can only be called by the deployed WLC contract, by the address specified in WLCAdress
 * @param _owner address the address of the exchanger
 */
function getForWLC(address _owner) public {
        require(WLCAdress == msg.sender, "You cannot invoke this function directly!");
        
        require(nextTokenId <= totalTokenSupply, "Not enough tokens are available for purchase!");
        
        _addTokensToAddress(_owner, 1);
        
        emit Buy(_owner, 1, nextTokenId - 1, nextTokenId - 1);
        
        chooseWinner();
    }