lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.6
/// @notice This function does all calculations to find trade dest amount without accounting 
///        for maxDestAmount. Part of this process includes:
///        - Call kyberMatchingEngine to parse hint and get an optional reserve list to trade.
///        - Query reserve rates and call kyberMatchingEngine to use best reserve.
///        - Calculate trade values and fee values.
///     This function should set all TradeData information so that it can be later used without 
///         any ambiguity
/// @param tradeData Main trade data object for trade info to be stored
/// @param hint Advanced user instructions for the trade 
function calcRatesAndAmounts(TradeData memory tradeData, bytes memory hint)
        internal
        view
        returns (uint256 destAmount, uint256 rateWithNetworkFee)
    {
        validateFeeInput(tradeData.input, tradeData.networkFeeBps);

        // token -> eth: find best reserves match and calculate wei amount
        tradeData.tradeWei = calcDestQtyAndMatchReserves(
            tradeData.input.src,
            ETH_TOKEN_ADDRESS,
            tradeData.input.srcAmount,
            tradeData,
            tradeData.tokenToEth,
            hint
        );

        require(tradeData.tradeWei <= MAX_QTY, "Trade wei > MAX_QTY");
        if (tradeData.tradeWei == 0) {
            return (0, 0);
        }

        // calculate fees
        tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;
        tradeData.networkFeeWei =
            (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
            BPS;

        assert(tradeData.tradeWei >= (tradeData.networkFeeWei + tradeData.platformFeeWei));

        // eth -> token: find best reserves match and calculate trade dest amount
        uint256 actualSrcWei = tradeData.tradeWei -
            tradeData.networkFeeWei -
            tradeData.platformFeeWei;

        destAmount = calcDestQtyAndMatchReserves(
            ETH_TOKEN_ADDRESS,
            tradeData.input.dest,
            actualSrcWei,
            tradeData,
            tradeData.ethToToken,
            hint
        );

        tradeData.networkFeeWei =
            (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
            BPS;

        rateWithNetworkFee = calcRateFromQty(
            tradeData.input.srcAmount * (BPS - tradeData.input.platformFeeBps) / BPS,
            destAmount,
            tradeData.tokenToEth.decimals,
            tradeData.ethToToken.decimals
        );
    }
// Solidity 0.6.6
/// @dev Checks a trade input validity, including correct src amounts
/// @param input Trade input structure
function validateTradeInput(TradeInput memory input) internal view
    {
        require(isEnabled, "network disabled");
        require(kyberProxyContracts[msg.sender], "bad sender");
        require(tx.gasprice <= maxGasPriceValue, "gas price");
        require(input.srcAmount <= MAX_QTY, "srcAmt > MAX_QTY");
        require(input.srcAmount != 0, "0 srcAmt");
        require(input.destAddress != address(0), "dest add 0");
        require(input.src != input.dest, "src = dest");

        if (input.src == ETH_TOKEN_ADDRESS) {
            require(msg.value == input.srcAmount); // kyberProxy issues message here
        } else {
            require(msg.value == 0); // kyberProxy issues message here
            // funds should have been moved to this contract already.
            require(input.src.balanceOf(address(this)) >= input.srcAmount, "no tokens");
        }
    }
// Solidity 0.6.6
/// @notice Update reserve data with selected reserves from kyberMatchingEngine
function updateReservesList(ReservesData memory reservesData, uint256[] memory selectedIndexes)
        internal
        pure
    {
        uint256 numReserves = selectedIndexes.length;

        require(numReserves <= reservesData.addresses.length, "doMatch: too many reserves");

        IKyberReserve[] memory reserveAddresses = new IKyberReserve[](numReserves);
        bytes32[] memory reserveIds = new bytes32[](numReserves);
        uint256[] memory splitsBps = new uint256[](numReserves);
        bool[] memory isFeeAccountedFlags = new bool[](numReserves);
        bool[] memory isEntitledRebateFlags = new bool[](numReserves);
        uint256[] memory srcAmounts = new uint256[](numReserves);
        uint256[] memory rates = new uint256[](numReserves);

        // update participating resevres and all data (rates, srcAmounts, feeAcounted etc.)
        for (uint256 i = 0; i < numReserves; i++) {
            reserveAddresses[i] = reservesData.addresses[selectedIndexes[i]];
            reserveIds[i] = reservesData.ids[selectedIndexes[i]];
            splitsBps[i] = reservesData.splitsBps[selectedIndexes[i]];
            isFeeAccountedFlags[i] = reservesData.isFeeAccountedFlags[selectedIndexes[i]];
            isEntitledRebateFlags[i] = reservesData.isEntitledRebateFlags[selectedIndexes[i]];
            srcAmounts[i] = reservesData.srcAmounts[selectedIndexes[i]];
            rates[i] = reservesData.rates[selectedIndexes[i]];
        }

        // update values
        reservesData.addresses = reserveAddresses;
        reservesData.ids = reserveIds;
        reservesData.splitsBps = splitsBps;
        reservesData.isFeeAccountedFlags = isFeeAccountedFlags;
        reservesData.isEntitledRebateFlags = isEntitledRebateFlags;
        reservesData.rates = rates;
        reservesData.srcAmounts = srcAmounts;
    }
// Solidity 0.6.6
/// @notice Verify split values bps and reserve ids,
///     then calculate the destQty from srcAmounts and rates
/// @dev Each split bps must be in range (0, BPS]
/// @dev Total split bps must be 100%
/// @dev Reserve ids must be increasing
function validateTradeCalcDestQtyAndFeeData(
        IERC20 src,
        ReservesData memory reservesData,
        TradeData memory tradeData
    ) internal pure returns (uint256 totalDestAmount) {
        uint256 totalBps;
        uint256 srcDecimals = (src == ETH_TOKEN_ADDRESS) ? ETH_DECIMALS : reservesData.decimals;
        uint256 destDecimals = (src == ETH_TOKEN_ADDRESS) ? reservesData.decimals : ETH_DECIMALS;
        
        for (uint256 i = 0; i < reservesData.addresses.length; i++) {
            if (i > 0 && (uint256(reservesData.ids[i]) <= uint256(reservesData.ids[i - 1]))) {
                return 0; // ids are not in increasing order
            }
            totalBps += reservesData.splitsBps[i];

            uint256 destAmount = calcDstQty(
                reservesData.srcAmounts[i],
                srcDecimals,
                destDecimals,
                reservesData.rates[i]
            );
            if (destAmount == 0) {
                return 0;
            }
            totalDestAmount += destAmount;

            if (reservesData.isFeeAccountedFlags[i]) {
                tradeData.feeAccountedBps += reservesData.splitsBps[i];

                if (reservesData.isEntitledRebateFlags[i]) {
                    tradeData.numEntitledRebateReserves++;
                }
            }
        }

        if (totalBps != BPS) {
            return 0;
        }
    }
// Solidity 0.6.6
/// @notice Recalculates tradeWei, network and platform fees, and actual source amount needed for the trade
/// in the event actualDestAmount > maxDestAmount
function calcTradeSrcAmountFromDest(TradeData memory tradeData)
        internal
        pure
        virtual
        returns (uint256 actualSrcAmount)
    {
        uint256 weiAfterDeductingFees;
        if (tradeData.input.dest != ETH_TOKEN_ADDRESS) {
            weiAfterDeductingFees = calcTradeSrcAmount(
                tradeData.tradeWei - tradeData.platformFeeWei - tradeData.networkFeeWei,
                ETH_DECIMALS,
                tradeData.ethToToken.decimals,
                tradeData.input.maxDestAmount,
                tradeData.ethToToken
            );
        } else {
            weiAfterDeductingFees = tradeData.input.maxDestAmount;
        }

        // reverse calculation, because we are working backwards
        uint256 newTradeWei =
            (weiAfterDeductingFees * BPS * BPS) /
            ((BPS * BPS) -
                (tradeData.networkFeeBps *
                tradeData.feeAccountedBps +
                tradeData.input.platformFeeBps *
                BPS));
        tradeData.tradeWei = minOf(newTradeWei, tradeData.tradeWei);
        // recalculate network and platform fees based on tradeWei
        tradeData.networkFeeWei =
            (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /
            BPS;
        tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;

        if (tradeData.input.src != ETH_TOKEN_ADDRESS) {
            actualSrcAmount = calcTradeSrcAmount(
                tradeData.input.srcAmount,
                tradeData.tokenToEth.decimals,
                ETH_DECIMALS,
                tradeData.tradeWei,
                tradeData.tokenToEth
            );
        } else {
            actualSrcAmount = tradeData.tradeWei;
        }

        assert(actualSrcAmount <= tradeData.input.srcAmount);
    }
// Solidity 0.6.6
/// @notice Recalculates srcAmounts and stores into tradingReserves, given the new destAmount.
///     Uses the original proportion of srcAmounts and rates to determine new split destAmounts,
///     then calculate the respective srcAmounts
/// @dev Due to small rounding errors, will fallback to current src amounts if new src amount is greater
function calcTradeSrcAmount(
        uint256 srcAmount,
        uint256 srcDecimals,
        uint256 destDecimals,
        uint256 destAmount,
        ReservesData memory reservesData
    ) internal pure returns (uint256 newSrcAmount) {
        uint256 totalWeightedDestAmount;
        for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {
            totalWeightedDestAmount += reservesData.srcAmounts[i] * reservesData.rates[i];
        }

        uint256[] memory newSrcAmounts = new uint256[](reservesData.srcAmounts.length);
        uint256 destAmountSoFar;
        uint256 currentSrcAmount;
        uint256 destAmountSplit;

        for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {
            currentSrcAmount = reservesData.srcAmounts[i];
            require(destAmount * currentSrcAmount * reservesData.rates[i] / destAmount == 
                    currentSrcAmount * reservesData.rates[i], 
                "multiplication overflow");
            destAmountSplit = i == (reservesData.srcAmounts.length - 1)
                ? (destAmount - destAmountSoFar)
                : (destAmount * currentSrcAmount * reservesData.rates[i]) /
                    totalWeightedDestAmount;
            destAmountSoFar += destAmountSplit;

            newSrcAmounts[i] = calcSrcQty(
                destAmountSplit,
                srcDecimals,
                destDecimals,
                reservesData.rates[i]
            );
            if (newSrcAmounts[i] > currentSrcAmount) {
                // revert back to use current src amounts
                return srcAmount;
            }

            newSrcAmount += newSrcAmounts[i];
        }
        // new src amounts are used only when all of them aren't greater then current srcAmounts
        reservesData.srcAmounts = newSrcAmounts;
    }
// Solidity 0.4.18
/*
 * Buy in function to be called mostly from the fallback function
 * @dev kept public in order to buy for someone else
 * @param beneficiary address
 */
function buyTokens(address beneficiary) private {
        require(beneficiary != 0x0);
        require(validPurchase());

        // Check the register if the investor was approved
        require(register.approved(beneficiary));

        uint256 weiAmount = msg.value;

        // calculate token amount to be created
        uint256 toGet = howMany(msg.value);

        require((toGet > 0) && (toGet.add(tokensSold) <= toBeSold));

        // update state
        weiRaised = weiRaised.add(weiAmount);
        tokensSold = tokensSold.add(toGet);

        token.mint(beneficiary, toGet);
        TokenPurchase(msg.sender, beneficiary, weiAmount, toGet);

        forwardFunds();

    }
// Solidity 0.4.24
/**
 * @dev        Batch Function to mark spender for approved for all. Does a check
 * for address(0) and throws if true
 * @notice     Facilitates batch approveAll
 * @param      _spenders  The spenders
 * @param      _approved  The approved
 */
function batchSetApprovalForAll(
        address[] _spenders,
        bool _approved
        )
        public
    {   
        require (isBatchSupported);

        require (_spenders.length > 0);

        address _spender;
        for (uint256 i = 0; i < _spenders.length; ++i) {        

            require (address(_spenders[i]) != address(0));
                
            _spender = _spenders[i];
            setApprovalForAll(_spender, _approved);
        }
    }
// Solidity 0.6.12
/**
 * @dev Only gov. Will revert if the destinationToken isn't on the allowed list
 *
 * @param _integrationName             The name of the integration to interact with
 * @param _sourceToken                 The address of the token to spend
 * @param _sourceAmount                The source amount to trade
 * @param _destinationToken            The token to get
 * @param _minimumDestinationAmount    The minimum amount to get
 * @param _data                        Calldata needed for the integration
 */
function trade(
        address, // Left here purely so that ABI is exactly the same as the trade module /* unused */
        string memory _integrationName,
        address _sourceToken,
        uint256 _sourceAmount,
        address _destinationToken,
        uint256 _minimumDestinationAmount,
        bytes memory _data
    ) external onlyGovOrSubGov {
        require(
            manager.isTokenAllowed(_destinationToken),
            "TradeAdapter::trade: _destinationToken is not on the allowed list"
        );

        bytes memory encoded = abi.encodeWithSelector(
            module.trade.selector,
            setToken,
            _integrationName,
            _sourceToken,
            _sourceAmount,
            _destinationToken,
            _minimumDestinationAmount,
            _data
        );

        manager.interactModule(address(module), encoded);
    }
// Solidity 0.4.26
// send ETH to the fund collection wallet(s)
function forwardFunds(uint256 partnerTokenAmount, uint256 weiMinusfee) internal {
      for (uint i=0;i<owners.length;i++)
      {
         uint percent = ownerAddresses[owners[i]];
         uint amountToBeSent = weiMinusfee.mul(percent);
         amountToBeSent = amountToBeSent.div(100);
         owners[i].transfer(amountToBeSent);
         
         if (owners[i]!=owner &&  ownerAddresses[owners[i]]>0)
         {
             token.transfer(owners[i],partnerTokenAmount);
         }
      }
    }
// Solidity 0.4.24
/**
 * @dev        Function to request Detachment from our Contract
 * @notice     a wallet can request to detach it collectible, so, that it can be used in other third-party contracts.
 * @param      _tokenId  The token identifier
 */
function requestDetachment(
        uint256 _tokenId
    )
        public
    {
        //Request can only be made by owner or approved address
        require (isApprovedOrOwner(msg.sender, _tokenId));

        uint256 isAttached = checkIsAttached(_tokenId);

        //If collectible is on a gamecard prevent detachment
        require(getGameCardId(_tokenId) == 0);

        require (isAttached >= 1);

        if(attachedSystemActive == true) {
            //Checks to see if request was made and if time elapsed
            if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
                isAttached = 0;
            } else if(isAttached > 1) {
                //Forces Tx Fail if time is already set for attachment and not less than detachmentTime
                require (isAttached == 1);
            } else {
                //Is attached, set detachment time and make request to detach
                // emit AssetUpdated(_tokenId);
                isAttached = block.timestamp;
            }
        } else {
            isAttached = 0;
        }

        updateIsAttached(_tokenId, isAttached);
    }
// Solidity 0.8.6
/**
 * Set some Dorkis aside for giveaways.
 */
function reserveTokens() public onlyOwner {    
        require(totalSupply().add(MAX_RESERVE) <= MAX_SLOTHS, "Reserve would exceed max supply of Dorkis");
        uint supply = totalSupply();
        for (uint i = 0; i < MAX_RESERVE; i++) {
            _safeMint(msg.sender, supply + i);
        }
    }
// Solidity 0.8.6
/**
 * Mints Sloths
 */
function mintSloths(uint numberOfTokens) public payable {
        require(numberOfTokens > 0, "numberOfNfts cannot be 0");
        require(saleIsActive, "Sale must be active to mint tokens");
        require(numberOfTokens <= MAX_PURCHASE, "Can only mint 20 tokens at a time");
        require(totalSupply().add(numberOfTokens) <= MAX_SLOTHS, "Purchase would exceed max supply of tokens");
        require(tokenPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
        for(uint i = 0; i < numberOfTokens; i++) {
            uint mintIndex = totalSupply();
            if (totalSupply() < MAX_SLOTHS) {
                _safeMint(msg.sender, mintIndex);
            }
        }
    }
// Solidity 0.8.6
/**
 * Get all tokens for a specific wallet
 *
 */
function getTokensForAddress(address fromAddress) external view returns (uint256 [] memory){
        uint tokenCount = balanceOf(fromAddress);
        uint256[] memory tokensId = new uint256[](tokenCount);
        for(uint i = 0; i < tokenCount; i++){
            tokensId[i] = tokenOfOwnerByIndex(fromAddress, i);
        }
        return tokensId;
    }
// Solidity 0.4.24
/**
 * @dev   Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check
 * @notice Helps a wallet to create a sale using our Sale Contract
 * @param      _tokenId        The token identifier
 * @param      _startingPrice  The starting price
 * @param      _endingPrice    The ending price
 * @param      _duration       The duration
 */
function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external {
        require (_tokenId != 0);
        
        // If DodgersNFT is already on any sale, this will throw
        // because it will be owned by the sale contract.
        address owner = ownerOf(_tokenId);
        require (owner == msg.sender);

        // Sale contract checks input sizes
        require (_startingPrice == _startingPrice);
        require (_endingPrice == _endingPrice);
        require (_duration == _duration);

        require (checkIsAttached(_tokenId) == 0);
        
        // One time approval for the tokenID
        _approveForSale(msg.sender, address(saleManagerAddress), _tokenId);

        saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);
    }
// Solidity 0.4.24
/**
 * @dev        Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration.
 * @notice     Batch function to put 10 or less collectibles on sale
 * @param      _tokenIds        The token identifier
 * @param      _startingPrices  The starting price
 * @param      _endingPrices    The ending price
 * @param      _durations       The duration
 */
function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused {

        require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0);
        
        // Sale contract checks input sizes
        for(uint ii = 0; ii < _tokenIds.length; ii++){

            // Do not process for tokenId 0
            require (_tokenIds[ii] != 0);
            
            require (_startingPrices[ii] == _startingPrices[ii]);
            require (_endingPrices[ii] == _endingPrices[ii]);
            require (_durations[ii] == _durations[ii]);

            // If DodgersNFT is already on any sale, this will throw
            // because it will be owned by the sale contract.
            address _owner = ownerOf(_tokenIds[ii]);
            address _msgSender = msg.sender;
            require (_owner == _msgSender);

            // Check whether the collectible is inPlay. If inPlay cant put it on Sale
            require (checkIsAttached(_tokenIds[ii]) == 0);
            
            // approve token to for Sale creation
            _approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]);
            
            saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender);
        }
    }
// Solidity 0.4.21
// Tests for uppercase characters in a given string
function allLower(string memory _string) internal pure returns (bool) {
        bytes memory bytesString = bytes(_string);
        for (uint i = 0; i < bytesString.length; i++) {
            if ((bytesString[i] >= 65) && (bytesString[i] <= 90)) {  // Uppercase characters
                return false;
            }
        }
        return true;
    }
// Solidity 0.4.21
// Allows the Hydro API to delete official users iff they've signed keccak256("Delete") with their private key
function deleteUserForUser(string userName, uint8 v, bytes32 r, bytes32 s) public onlyOwner {
        bytes32 userNameHash = keccak256(userName);
        require(userNameHashTaken(userNameHash));
        address userAddress = userDirectory[userNameHash].userAddress;
        require(isSigned(userAddress, keccak256("Delete"), v, r, s));

        delete userDirectory[userNameHash];

        emit UserDeleted(userName, userAddress, true);
    }
// Solidity 0.4.21
// Allows anyone to sign up as an unofficial application
function unofficialApplicationSignUp(string applicationName) public payable {
        require(bytes(applicationName).length < 100);
        require(msg.value >= unofficialApplicationSignUpFee);
        require(applicationName.allLower());

        HydroToken hydro = HydroToken(hydroTokenAddress);
        uint256 hydroBalance = hydro.balanceOf(msg.sender);
        require(hydroBalance >= hydroStakingMinimum);

        bytes32 applicationNameHash = keccak256(applicationName);
        require(!applicationNameHashTaken(applicationNameHash, false));
        unofficialApplicationDirectory[applicationNameHash] = Application(applicationName, false, true);

        emit ApplicationSignUp(applicationName, false);
    }
// Solidity 0.4.8
/// @dev Mints a new token.
/// @param _to Address of token owner.
function mint(address _to) minterOnly returns (bool success) {
        // ensure that the token owner doesn't already own a token.
        if (balances[_to] != 0x0) return false;

        balances[_to] = 1;

        // log the minting of this token.
        Mint(_to);
        Transfer(0x0, _to, 1);
        TokenEventLib._Transfer(0x0, _to);

        // increase the supply.
        numTokens += 1;

        return true;
    }
// Solidity 0.4.8
// @dev Mint many new tokens
function mint(address[] _to) minterOnly returns (bool success) {
        for(uint i = 0; i < _to.length; i++) {
            if(balances[_to[i]] != 0x0) return false;
            balances[_to[i]] = 1;
            Mint(_to[i]);
            Transfer(0x0, _to[i], 1);
            TokenEventLib._Transfer(0x0, _to[i]);
        }
        numTokens += _to.length;
        return true;
    }