lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.2
/**
 * Helper function to search for and delete an array element without leaving a gap.
 * Array size is also decremented.
 * DO NOT USE if ordering is important.
 * @param array array to be modified
 * @param element value to be removed
 */
function deleteElement(uint64[] storage array, uint64 element) internal {
        uint lastIndex = array.length.sub(1);
        for (uint i = 0; i < array.length; i++) {
            if (array[i] == element) {
                array[i] = array[lastIndex];
                delete(array[lastIndex]);
                array.length = lastIndex;
                break;
            }
        }
    }
// Solidity 0.5.2
/**
 * Calculates how many whole unpaid intervals (will) have elapsed since the last payment at a specific `time`.
 * DOES NOT check if subscriber account is funded.
 * @param sub Subscription object
 * @param time timestamp in seconds
 * @return number of unpaid intervals
 */
function calculateUnpaidIntervalsUntil(Subscription memory sub, uint time) internal view returns (uint) {
        require(time >= now, "don't use a time before now");

        if (time > sub.nextPaymentTime) {
            return ((time.sub(sub.nextPaymentTime)).div(sub.interval)).add(1);
        }

        return 0;
    }
// Solidity 0.8.9
/**
 * @notice buy weapon and add it to a token's weapon collection
 * @dev weaponId n can only be bought if the token owns weaponId - 1 (id 9 and up)
 * @param _tokenId - the token's id
 * @param _weaponId - the desired weapon's id
 */
function buyWeapon(uint256 _tokenId, uint256 _weaponId) public {
        require(
            msg.sender == raiders.ownerOf(_tokenId) ||
                hunt.isStaker(msg.sender, _tokenId),
            "Not allowed"
        );
        require(tokenToWeapon[_tokenId][_weaponId] == false, "Already owned");
        if (_weaponId > 8) {
            require(tokenToWeapon[_tokenId][_weaponId - 1], "Not unlocked");
        }
        require(rgo.balanceOf(msg.sender) >= weaponCost[_weaponId], "Too poor");
        rgo.adminBurn(msg.sender, weaponCost[_weaponId]);
        tokenToWeapon[_tokenId][_weaponId] = true;
    }
// Solidity 0.6.12
// 0 -> obtc, 1 -> renBTC, 2 -> wBTC
function trade(int128 token, uint amount, uint min_dy) public whenNotPaused nonReentrant {
        if(token == 1) {
            renBTC.safeTransferFrom(msg.sender, address(this), amount);
            renBTC.approve(address(sso), amount);
        } else if(token == 2) {
            wBTC.safeTransferFrom(msg.sender, address(this), amount);
            wBTC.approve(address(sso), amount);
        } else {
            revert("not support token");
        }

        uint dy = sso.exchange_underlying(token, 0, amount, min_dy);
        uint feeBor = calculateFeeBor(dy);
        if (feeBor != 0) {
            mintedAmount = mintedAmount.add(feeBor);
            bor.safeTransferFrom(distributor, msg.sender, feeBor);
        }
        oBTC.safeTransfer(msg.sender, dy);
    }
// Solidity 0.4.18
// Transfer funds.
function transfer(address _to, uint256 _amount) public returns (bool) {
        require(_to != address(0));
        require(_amount <= accounts[msg.sender].balance);
        // Enable the receiver if the sender is the exchange.
        if (msg.sender == owner && !accounts[_to].enabled) {
            accounts[_to].enabled = true;
        }
        if (
            // Check that the sender's account is enabled.
            accounts[msg.sender].enabled
            // Check that the receiver's account is enabled.
            && accounts[_to].enabled
            // Check that the sender has sufficient balance.
            && accounts[msg.sender].balance >= _amount
            // Check that the amount is valid.
            && _amount > 0
            // Check for overflow.
            && accounts[_to].balance + _amount > accounts[_to].balance) {
                // Credit the sender.
                accounts[msg.sender].balance -= _amount;
                // Debit the receiver.
                accounts[_to].balance += _amount;
                Transfer(msg.sender, _to, _amount);
                return true;
        }
        return false;
    }
// Solidity 0.7.6
/// @dev make any kind of request that may be answered with a file.This function is only called by Mage 
function submitNewRequest(
        string memory _orderTitle,
        string memory _description,
        string memory _zPaper,
        uint _tokenPerContributor,
        uint _tokenPerLaboratory,
        uint _totalContributors,
        string memory _zarelaCategory,
        uint _businessCategory,
        string memory _accessPublicKey
    )
        public
    {
        require(_balances[msg.sender] >= ((_tokenPerContributor + _tokenPerLaboratory) * _totalContributors), "Your Token Is Not Enough");
        ERC20.transfer(address(this),((_tokenPerContributor + _tokenPerLaboratory) * _totalContributors));
        uint orderId = orders.length;
        orders.push(
            Order(
                orderId,
                _orderTitle,
                msg.sender,
                _tokenPerContributor,
                _tokenPerLaboratory,
                _totalContributors,
                _zPaper,
                _description,
                _totalContributors,
                0,
                block.timestamp,
                _accessPublicKey
                )
            );
        userMap[msg.sender].ownedOrders.push(orderId);
        Categories.push(
            Category(
                    _zarelaCategory,
                    _businessCategory
                )
            );
        emit orderRegistered(msg.sender, orderId);
    }
// Solidity 0.7.6
/// @dev Confirm the signals sent by angels only by Requester (Mage) of that signal.
/// The selection of files is based on their index.
function confirmContributor(
        uint _orderId,
        uint[]memory _index
    )
        public 
        onlyRequester(_orderId)
        checkOrderId(_orderId)
    {
        Order storage myorder = orders[_orderId];
        require(_index.length >= 1,"You Should Select One At Least");
        require(_index.length <= myorder.totalContributorsRemain,"The number of entries is more than allowed");
        require(myorder.totalContributorsRemain != 0,"Your Order Is Done, And You Sent All of Rewards to Users");
        myorder.totalContributorsRemain = myorder.totalContributorsRemain - (_index.length);
        _balances[address(this)] = _balances[address(this)] - ( (myorder.tokenPerContributor + myorder.tokenPerLaboratory) *  _index.length);
        for (uint i;i < _index.length ; i++) {
            _balances[orderDataMap[_orderId].contributorAddresses[_index[i]]] = _balances[orderDataMap[_orderId].contributorAddresses[_index[i]]] + (myorder.tokenPerContributor);
            _balances[orderDataMap[_orderId].laboratoryAddresses[_index[i]]] = _balances[orderDataMap[_orderId].laboratoryAddresses[_index[i]]] + (myorder.tokenPerLaboratory);
            userMap[orderDataMap[_orderId].contributorAddresses[_index[i]]].tokenGainedFromMages+=(myorder.tokenPerContributor);
            userMap[orderDataMap[_orderId].laboratoryAddresses[_index[i]]].tokenGainedFromMages+=(myorder.tokenPerLaboratory);
            orderDataMap[_orderId].isConfirmedByMage[_index[i]] = true;
        }
        
        if (myorder.totalContributorsRemain == 0) {
            emit orderFinished(_orderId);
        }
        emit signalsApproved(_orderId,_index.length);
    }
// Solidity 0.7.6
/// @dev retrieves the value of each the specefic order by `_orderId`
/// @return the contributors addresses , the Laboratory addresses , Time to send that signal by the angel , Laboratory or angel gained reward? , Status (true , false) of confirmation , Zarela day sent that signal
function getOrderData(
        uint _orderId
    )
        public
        checkOrderId (_orderId)
        view returns (
            address[] memory,
            address[] memory,
            uint[]memory,
            bool[]memory,
            bool[] memory,
            uint[] memory)
    {
        return (
            orderDataMap[_orderId].contributorAddresses,
            orderDataMap[_orderId].laboratoryAddresses,
            orderDataMap[_orderId].dataRegistrationTime,
            orderDataMap[_orderId].whoGainedReward,
            orderDataMap[_orderId].isConfirmedByMage,
            orderDataMap[_orderId].zarelaDay
            );
    }
// Solidity 0.8.11
// swaps any combination of ERC-20/721/1155
// User needs to approve assets before invoking swap
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
function multiAssetSwap(
        ERC20Details memory erc20Details,
        SpecialTransferHelper.ERC721Details[] memory erc721Details,
        ERC1155Details[] memory erc1155Details,
        ConverstionDetails[] memory converstionDetails,
        MarketRegistry.TradeDetails[] memory tradeDetails,
        address[] memory dustTokens,
        uint256[2] memory feeDetails    // [affiliateIndex, ETH fee in Wei]
    ) payable external isOpenForTrades nonReentrant {
        // collect fees
        _collectFee(feeDetails);

        // transfer all tokens
        _transferFromHelper(
            erc20Details,
            erc721Details,
            erc1155Details
        );

        // Convert any assets if needed
        _conversionHelper(converstionDetails);

        // execute trades
        _trade(tradeDetails);

        // return dust tokens (if any)
        _returnDust(dustTokens);
    }
// Solidity 0.8.11
// Utility function that is used for free swaps for sponsored markets
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! 
function multiAssetSwapWithoutFee(
        ERC20Details memory erc20Details,
        SpecialTransferHelper.ERC721Details[] memory erc721Details,
        ERC1155Details[] memory erc1155Details,
        ConverstionDetails[] memory converstionDetails,
        MarketRegistry.TradeDetails[] memory tradeDetails,
        address[] memory dustTokens,
        uint256 sponsoredMarketIndex
    ) payable external isOpenForFreeTrades nonReentrant {
        // fetch the marketId of the sponsored market
        SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];
        // check if the market is active
        require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market");

        // transfer all tokens
        _transferFromHelper(
            erc20Details,
            erc721Details,
            erc1155Details
        );

        // Convert any assets if needed
        _conversionHelper(converstionDetails);

        // execute trades
        bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);

        // check if the trades include the sponsored market
        require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market");

        // return dust tokens (if any)
        _returnDust(dustTokens);
    }
// Solidity 0.8.9
// Generic function to determine winner. Aim to be called any number of times
function drawTicket (uint randomiserNumber, bytes32 randomHash) internal view returns(uint pickedTicket, bytes32 newGeneratedRandomHash) {
        bytes32 newRandomHash;
        uint pickTicket;
        
        for (int i = 0; i < 10; i++) {
            newRandomHash = keccak256(abi.encodePacked(randomHash, block.difficulty, block.coinbase, randomiserNumber, i));
            pickTicket = uint(newRandomHash)%ticketsSold;
            
            if (selectedTickets[pickTicket] == false && pickTicket != 0) {
                return (pickTicket, newRandomHash);
            } else if (pickTicket == 0 && selectedTickets[ticketsSold]) {
                return (ticketsSold, newRandomHash);
            }
        } 
        
        return (pickTicket, newRandomHash);
    }
// Solidity 0.4.24
// ------------------------------------------------------------------------
// CrowdSale Function 1,800,000 RCALLS Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
        require(now >= startDate && now <= endDate);
        uint tokens;
        if (now <= bonusEnds) {
            tokens = msg.value * 2400000;
        } else {
            tokens = msg.value * 1800000;
        }
        balances[owner] = safeSub(balances[owner], tokens);
        balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
        emit Transfer(owner, msg.sender, tokens);
        owner.transfer(msg.value);
    }
// Solidity 0.7.0
/*
 * Allows the owner to change the return rate for a given bracket
 * NOTE: changes to this rate will only affect those that stake AFTER this change.
 * Will not affect the currently staked amounts.
 */
function changeReturnRateForBracket(uint256 _percentage, uint256 _stakeBracket) public onlyOwner {
        require(_stakeBracket <= 4);
        // TAKE NOTE OF FORMATTING:
        // stakeReward[0] = 25;
        // stakeReward[1] = 55;
        // stakeReward[2] = 190;
        // stakeReward[3] = 450;
        // stakeReward[4] = 1200;

        stakeReward[_stakeBracket] = _percentage;
        emit stakeRewardUpdated(_stakeBracket,_percentage);
    }
// Solidity 0.6.12
/***********************************|
 |          Only Controller          |
 |__________________________________*/
function energize(
    address contractAddress,
    uint256 tokenId,
    address assetToken,
    uint256 assetAmount
  )
    external
    override
    onlyController
    returns (uint256 yieldTokensAmount)
  {
    uint256 uuid = contractAddress.getTokenUUID(tokenId);
    address wallet = _wallets[uuid];

    // Deposit into Smart-Wallet
    yieldTokensAmount = AaveSmartWallet(wallet).deposit(assetToken, assetAmount, _referralCode);

    // Log Event
    emit WalletEnergized(contractAddress, tokenId, assetToken, assetAmount, yieldTokensAmount);
  }
// Solidity 0.5.6
/**
 * @dev Create an order for your NFT and other people can pairing their NFT to exchange
 * @notice You must call receiveErc721Token method first to send your NFT to exchange contract,
 * if your NFT have matchorder pair with other order, then they will become Invalid until you
 * delete this order.
 * @param contractAddress NFT's contract address
 * @param tokenId NFT's id
 */
function createOrder(
        address contractAddress, 
        uint256 tokenId
    ) 
    external 
    onlySenderIsOriginalOwner(
        contractAddress, 
        tokenId
    ) 
    {
        bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));
        require(OrderToOwner[orderHash] != msg.sender, "Order already exist");
        _addOrder(msg.sender, orderHash);
        emit CreateOrder(msg.sender, orderHash, contractAddress, tokenId);
    }
// Solidity 0.5.6
/**
 * @dev Remove order information on exchange contract 
 * @param sender order's owner
 * @param orderHash order's hash
 */
function _removeOrder(
        address sender,
        bytes32 orderHash
    )
    internal
    {
        OrderToExist[orderHash] = false;
        delete OrderToOwner[orderHash];
        uint256 orderIndex = OrderToIndex[orderHash];
        uint256 lastOrderIndex = OwnerToOrders[sender].length.sub(1);
        if (lastOrderIndex != orderIndex){
            bytes32 lastOwnerOrder = OwnerToOrders[sender][lastOrderIndex];
            OwnerToOrders[sender][orderIndex] = lastOwnerOrder;
            OrderToIndex[lastOwnerOrder] = orderIndex;
        }
        OwnerToOrders[sender].length--;
    }
// Solidity 0.5.6
/**
 * @dev If your are interested in specfic order's NFT, create a matchorder and pair with it so order's owner
 * can know and choose to exchange with you
 * @notice You must call receiveErc721Token method first to send your NFT to exchange contract,
 * if your NFT already create order, then you will be prohibit create matchorder until you delete this NFT's 
 * order.
 * @param contractAddress NFT's contract address
 * @param tokenId NFT's id
 * @param orderHash order's hash which matchorder want to pair with 
 */
function createMatchOrder(
        address contractAddress,
        uint256 tokenId, 
        bytes32 orderHash
    ) 
    external 
    onlySenderIsOriginalOwner(
        contractAddress, 
        tokenId
    ) 
    {
        bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));
        require(OrderToOwner[matchOrderHash] != msg.sender, "Order already exist");
        _addMatchOrder(matchOrderHash, orderHash);
        emit CreateMatchOrder(msg.sender, orderHash, matchOrderHash, contractAddress, tokenId);
    }
// Solidity 0.5.6
/**
 * @dev delete matchorder information on exchange contract 
 * @param matchOrderHash matchorder's hash
 * @param orderHash order's hash which matchorder pair with 
 */
function deleteMatchOrder(
        bytes32 matchOrderHash,
        bytes32 orderHash
    )
    external
    {
        require(MatchOrderToOwner[matchOrderHash] == msg.sender, "match order doens't belong to this address" );
        require(OrderToExist[orderHash] == true, "this order is not exist");
        _removeMatchOrder(orderHash, matchOrderHash);
        emit DeleteMatchOrder(msg.sender, orderHash, matchOrderHash);
    }
// Solidity 0.5.6
/**
 * @dev order's owner can choose NFT to exchange from it's match order array, when function 
 * execute, order will be deleted, both NFT will be exchanged and send to corresponding address.
 * @param order order's hash which matchorder pair with 
 * @param matchOrder matchorder's hash
 */
function exchangeToken(
        bytes32 order,
        bytes32 matchOrder
    ) 
    external 
    {
        require(OrderToOwner[order] == msg.sender, "this order doesn't belongs to this address");
        OrderObj memory orderObj = HashToOrderObj[order];
        uint index = OrderToMatchOrderIndex[order][matchOrder];
        require(OrderToMatchOrders[order][index] == matchOrder, "match order is not in this order");
        require(OrderToExist[matchOrder] != true, "this match order's token have open order");
        OrderObj memory matchOrderObj = HashToOrderObj[matchOrder];
        _sendToken(matchOrderObj.owner, orderObj.contractAddress, orderObj.tokenId);
        _sendToken(orderObj.owner, matchOrderObj.contractAddress, matchOrderObj.tokenId);
        _removeMatchOrder(order, matchOrder);
        _removeOrder(msg.sender, order);
    }
// Solidity 0.5.6
/**
 * @dev if you want to create order and matchorder on exchange contract, you must call this function
 * to send your NFT to exchange contract, if your NFT is followed erc165 and erc721 standard, exchange
 * contract will checked and execute sucessfully, then contract will record your information so you 
 * don't need worried about NFT lost.
 * @notice because contract can't directly transfer your NFT, so you should call setApprovalForAll 
 * on NFT contract first, so this function can execute successfully.
 * @param contractAddress NFT's Contract address
 * @param tokenId NFT's id 
 */
function receiveErc721Token(
        address contractAddress, 
        uint256 tokenId
    ) 
    external  
    {
        bool checkSupportErc165Interface = false;
        if(contractAddress != CryptoKittiesAddress){
            for(uint i = 0; i < SupportNFTInterface.length; i++){
                if(contractAddress._supportsInterface(SupportNFTInterface[i]) == true){
                    checkSupportErc165Interface = true;
                }
            }
            require(checkSupportErc165Interface == true, "not supported Erc165 Interface");
            Erc721Interface erc721Contract = Erc721Interface(contractAddress);
            require(erc721Contract.isApprovedForAll(msg.sender,address(this)) == true, "contract doesn't have power to control this token id");
            erc721Contract.transferFrom(msg.sender, address(this), tokenId);
        }else {
            KittyInterface kittyContract = KittyInterface(contractAddress);
            require(kittyContract.kittyIndexToApproved(tokenId) == address(this), "contract doesn't have power to control this cryptoKitties's id");
            kittyContract.transferFrom(msg.sender, address(this), tokenId);
        }
        _addToken(msg.sender, contractAddress, tokenId);
        emit ReceiveToken(msg.sender, contractAddress, tokenId);

    }
// Solidity 0.5.6
/**
 * @dev add token and OrderObj information on exchange contract, because order hash and matchorder
 * hash are same, so one NFT have mapping to one OrderObj
 * @param sender NFT's owner
 * @param contractAddress NFT's contract address
 * @param tokenId NFT's id
 */
function _addToken(
        address sender, 
        address contractAddress, 
        uint256 tokenId
    ) 
    internal 
    {   
        bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, sender));
        MatchOrderToOwner[matchOrderHash] = sender;
        HashToOrderObj[matchOrderHash] = OrderObj(sender,contractAddress,tokenId);
        TokenToOwner[contractAddress][tokenId] = sender;
        uint index = OwnerToTokens[sender][contractAddress].push(tokenId).sub(1);
        TokenToIndex[contractAddress][tokenId] = index;
        emit CreateOrderObj(matchOrderHash, sender, contractAddress, tokenId);
    }
// Solidity 0.5.6
/**
 * @dev send your NFT back to address which you send token in, if your NFT still have open order,
 * then order will be deleted
 * @notice matchorder will not be deleted because cost too high, but they will be useless and other
 * people can't choose your match order to exchange
 * @param contractAddress NFT's Contract address
 * @param tokenId NFT's id 
 */
function sendBackToken(
        address contractAddress, 
        uint256 tokenId
    ) 
    external 
    onlySenderIsOriginalOwner(
        contractAddress, 
        tokenId
    ) 
    {
        bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));
        if(OrderToExist[orderHash] == true) {
            _removeOrder(msg.sender, orderHash);
        }
        _sendToken(msg.sender, contractAddress, tokenId);
        emit SendBackToken(msg.sender, contractAddress, tokenId);
    }
// Solidity 0.5.6
/**
 * @dev Drive NFT contract to send NFT to corresponding address
 * @notice because cryptokittes contract method are not the same as general NFT contract, so 
 * need treat it individually
 * @param sendAddress NFT's owner
 * @param contractAddress NFT's contract address
 * @param tokenId NFT's id
 */
function _sendToken(
        address sendAddress,
        address contractAddress, 
        uint256 tokenId
    )
    internal
    {   
        if(contractAddress != CryptoKittiesAddress){
            Erc721Interface erc721Contract = Erc721Interface(contractAddress);
            require(erc721Contract.ownerOf(tokenId) == address(this), "exchange contract should have this token");
            erc721Contract.transferFrom(address(this), sendAddress, tokenId);
        }else{
            KittyInterface kittyContract = KittyInterface(contractAddress);
            require(kittyContract.ownerOf(tokenId) == address(this), "exchange contract should have this token");
            kittyContract.transfer(sendAddress, tokenId);
        }
        _removeToken(contractAddress, tokenId);
        emit SendToken(sendAddress, contractAddress, tokenId);
    }