lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
// **** internal state changer ****
// for redeem supplied (unleveraged) DAI from compound
function _redeemDAI(uint256 _want) internal {
        uint256 maxRedeem = getSuppliedUnleveraged();
        _want = _want > maxRedeem? maxRedeem : _want;
        
        uint256 _redeem = _want;
        if (_redeem > 0) {
            // Make sure market can cover liquidity
            require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity");

            // How much borrowed amount do we need to free?
            uint256 borrowed = getBorrowed();
            uint256 supplied = getSupplied();
            uint256 curLeverage = getCurrentLeverage();
            uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18);

            // If the amount we need to free is > borrowed, Just free up all the borrowed amount
            if (borrowedToBeFree > borrowed) {
                _dlUntil(getSuppliedUnleveraged());
            } else {
                // Otherwise just keep freeing up borrowed amounts until we hit a safe number to redeem our underlying
                _dlUntil(supplied.sub(borrowedToBeFree));
            }

            // Redeems underlying
            require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem");
        }
    }
// Solidity 0.6.12
//dydx flashloan callback
function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override returns (bytes32) {
        require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), "!Flash");

        uint256 total = _amount.add(_loanFee);
        require(IERC20(dai).balanceOf(address(this)) >= _amount, '!balFlash');

        (Action action) = abi.decode(_data, (Action));

        if (action == Action.LEVERAGE){
            _leveraging(total, true);
            emit FlashLoanLeverage(_amount, _loanFee, _data, Action.LEVERAGE);
        } else{
            _deleveraging(_amount, total, true);
            emit FlashLoanDeleverage(_amount, _loanFee, _data, Action.DELEVERAGE);
        }

        require(IERC20(dai).balanceOf(address(this)) >= total, '!deficitFlashRepay');
        return 0x439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd9;
    }
// Solidity 0.4.24
/**
 * @notice Terminate contract and refund to owner
 * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to
 refund.
 * @notice The called token contracts could try to re-enter this contract. Only
 supply token contracts you trust.
 */
function destroy(address[] _tokens) public onlyOwner {

    // Transfer tokens to owner
    for (uint256 i = 0; i < _tokens.length; i++) {
      ERC20Basic token = ERC20Basic(_tokens[i]);
      uint256 balance = token.balanceOf(this);
      token.transfer(owner, balance);
    }

    // Transfer Eth to owner and terminate contract
    selfdestruct(owner);
  }
// Solidity 0.8.12
/**
 * @notice Validates the sale data for each phase per user
 *
 * @dev For each phase validates that the time is correct,
 * that the ether supplied is correct and that the purchase 
 * amount doesn't exceed the max amount
 *
 * @param amount. The amount the user want's to purchase
 * @param phase. The sale phase of the user
 */
function validatePhaseSpecificPurchase(uint256 amount, uint256 phase) internal {
        if (phase == 1) {                          
            require(msg.value >= pricePhaseOne * amount, "ETHER SENT NOT CORRECT");
            require(mintedPhases[1] + amount <= maxSupplyPhaseOne, "BUY AMOUNT GOES OVER MAX SUPPLY");
            require(block.timestamp >= startTimePhaseOne, "PHASE ONE SALE HASN'T STARTED YET");

        } else if (phase == 2) {                     
            require(msg.value >= pricePhaseTwo * amount, "ETHER SENT NOT CORRECT");
            require(mintedPhases[2] + amount <= maxSupplyPhaseTwo, "BUY AMOUNT GOES OVER MAX SUPPLY");
            require(block.timestamp >= startTimePhaseTwo, "PHASE TWO SALE HASN'T STARTED YET");

        } else {
            revert("INCORRECT PHASE");
        }
    }
// Solidity 0.8.12
/**
 * @notice Function to buy one or more NFTs.
 * @dev First the Merkle Proof is verified.
 * Then the buy is verified with the data embedded in the Merkle Proof.
 * Finally the NFTs are bought to the user's wallet.
 *
 * @param amount. The amount of NFTs to buy.     
 * @param buyMaxAmount. The max amount the user can buy.
 * @param phase. The permissioned sale phase.
 * @param proof. The Merkle Proof of the user.
 */
function buyPhases(uint256 amount, uint256 buyMaxAmount, uint256 phase, bytes32[] calldata proof) 
        external 
        payable {

        /// @dev Verifies Merkle Proof submitted by user.
        /// @dev All mint data is embedded in the merkle proof.

        bytes32 leaf = keccak256(abi.encodePacked(msg.sender, buyMaxAmount, phase));
        require(MerkleProof.verify(proof, merkleRoot, leaf), "INVALID PROOF");

        /// @dev Verify that user can perform permissioned sale based on the provided parameters.

        require(address(nft) != address(0), "NFT SMART CONTRACT NOT SET");
        require(merkleRoot != "", "PERMISSIONED SALE CLOSED");
        
        require(amount > 0, "HAVE TO BUY AT LEAST 1");
        require(addressToMints[msg.sender][phase] + amount <= buyMaxAmount, "BUY AMOUNT EXCEEDS MAX FOR USER");            

        /// @dev Verify that user can perform permissioned sale based on phase of user

        validatePhaseSpecificPurchase(amount, phase);

        /// @dev Permissioned sale closes as soon as public sale starts
        require(block.timestamp < startTimeOpen, "PERMISSIONED SALE CLOSED");

        /// @dev Update mint values

        mintedPhases[phase] += amount;
        addressToMints[msg.sender][phase] += amount;
        nft.mintTo(amount, msg.sender);

        emit Purchase(msg.sender, amount, phase);
    }
// Solidity 0.8.12
/**
 * @notice Function to buy one or more NFTs.
 *
 * @param amount. The amount of NFTs to buy.
 */
function buyOpen(uint256 amount) 
        external 
        payable {
        
        /// @dev Verifies that user can perform open mint based on the provided parameters.

        require(address(nft) != address(0), "NFT SMART CONTRACT NOT SET");
        require(block.timestamp >= startTimeOpen, "OPEN SALE CLOSED");

        require(amount > 0, "HAVE TO BUY AT LEAST 1");

        require(addressToMints[msg.sender][3] + amount <= limitOpen, "MINT AMOUNT EXCEEDS MAX FOR USER");
        require(mintedOpen + amount <= maxSupplyOpen(), "MINT AMOUNT GOES OVER MAX SUPPLY");
        require(msg.value >= priceOpen * amount, "ETHER SENT NOT CORRECT");

        /// @dev Updates contract variables and mints `amount` NFTs to users wallet
        
        mintedOpen += amount;
        addressToMints[msg.sender][3] += amount;
        nft.mintTo(amount, msg.sender);

        emit Purchase(msg.sender, amount, 3);
    }
// Solidity 0.8.12
/**
 * @notice Set recipients for funds collected in smart contract.
 *
 * @dev Overrides old recipients and shares
 *
 * @param _addresses. The addresses of the new recipients.
 * @param _shares. The shares corresponding to the recipients.
 */
function setRecipients(address[] calldata _addresses, uint256[] calldata _shares) external onlyOwner {
        require(_addresses.length > 0, "HAVE TO PROVIDE AT LEAST ONE RECIPIENT");
        require(_addresses.length == _shares.length, "PAYMENT SPLIT NOT CONFIGURED CORRECTLY");

        delete recipients;
        delete shares;

        for (uint i = 0; i < _addresses.length; i++) {
            recipients.push(_addresses[i]);
            shares.push(_shares[i]);
        }

        emit setRecipientsEvent(_addresses, _shares);
    }
// Solidity 0.8.12
/**
 * @notice Allows owner to withdraw funds generated from sale to the specified recipients.
 *
 */
function withdrawAll() external {
        bool senderIsRecipient = false;
        for (uint i = 0; i < recipients.length; i++) {
            senderIsRecipient = senderIsRecipient || (msg.sender == recipients[i]);
        }
        require(senderIsRecipient, "CAN ONLY BE CALLED BY RECIPIENT");
        require(recipients.length > 0, "CANNOT WITHDRAW TO ZERO ADDRESS");
        require(recipients.length == shares.length, "PAYMENT SPLIT NOT CONFIGURED CORRECTLY");

        uint256 contractBalance = address(this).balance;

        require(contractBalance > 0, "NO ETHER TO WITHDRAW");

        for (uint i = 0; i < recipients.length; i++) {
            address _to = recipients[i];
            uint256 _amount = contractBalance * shares[i] / 1000;
            payable(_to).transfer(_amount);
            emit WithdrawAllEvent(_to, _amount);
        }        
    }
// Solidity 0.7.5
/**
 * @notice logic for claiming OHM
 * @param _amount uint256
 * @return toSend_ uint256
 */
function _claim(uint256 _amount) internal returns (uint256 toSend_) {
        Term memory info = terms[msg.sender];

        dai.safeTransferFrom(msg.sender, address(this), _amount);
        toSend_ = treasury.deposit(_amount, address(dai), 0);

        require(redeemableFor(msg.sender).div(1e9) >= toSend_, "Claim more than vested");
        require(info.max.sub(claimed(msg.sender)) >= toSend_, "Claim more than max");

        if(useStatic) {
            terms[msg.sender].gClaimed = info.gClaimed.add(gOHM.balanceTo(toSend_.mul(9).div(10)));
            terms[msg.sender].claimed = info.claimed.add(toSend_.div(10));
        } else terms[msg.sender].gClaimed = info.gClaimed.add(gOHM.balanceTo(toSend_));
    }
// Solidity 0.7.5
/**
 * @notice bulk migrate users from previous contract
 * @param _addresses address[] memory
 */
function migrate(address[] memory _addresses) external onlyOwner {
        for (uint256 i = 0; i < _addresses.length; i++) {
            IClaim.Term memory term = previous.terms(_addresses[i]);
            setTerms(
                _addresses[i], 
                term.max,
                term.percent,
                term.claimed,
                term.wClaimed
            );
        }
    }
// Solidity 0.7.5
/**
 *  @notice set terms for new address
 *  @notice cannot lower for address or exceed maximum total allocation
 *  @param _address address
 *  @param _percent uint256
 *  @param _claimed uint256
 *  @param _gClaimed uint256
 *  @param _max uint256
 */
function setTerms(
        address _address, 
        uint256 _percent, 
        uint256 _claimed, 
        uint256 _gClaimed, 
        uint256 _max
    ) public onlyOwner {
        require(terms[_address].max == 0, "address already exists");
        terms[_address] = Term({
            percent: _percent,
            claimed: _claimed,
            gClaimed: _gClaimed,
            max: _max
        });
        require(totalAllocated.add(_percent) <= maximumAllocated, "Cannot allocate more");
        totalAllocated = totalAllocated.add(_percent);
    }
// Solidity 0.5.16
// https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV4_Chai.sol#L1591
function rpow(
       uint256 x,
       uint256 n,
       uint256 base)
       public
       pure
       returns (uint256 z)
   {
       assembly {
           switch x case 0 {switch n case 0 {z := base} default {z := 0}}
           default {
               switch mod(n, 2) case 0 { z := base } default { z := x }
               let half := div(base, 2)  // for rounding.
               for { n := div(n, 2) } n { n := div(n,2) } {
                   let xx := mul(x, x)
                   if iszero(eq(div(xx, x), x)) { revert(0,0) }
                   let xxRound := add(xx, half)
                   if lt(xxRound, xx) { revert(0,0) }
                   x := div(xxRound, base)
                   if mod(n,2) {
                       let zx := mul(z, x)
                       if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
                       let zxRound := add(zx, half)
                       if lt(zxRound, zx) { revert(0,0) }
                       z := div(zxRound, base)
                   }
               }
           }
       }
   }
// Solidity 0.6.10
/// @param _conditionData The encoded data from getConditionData()
function ok(uint256, bytes calldata _conditionData, uint256)
        public
        view
        virtual
        override
        returns(string memory)
    {
        (address sendToken,
         uint256 sendAmount,
         address buyToken,
         uint256 currentRefRate,
         bool greaterElseSmaller
        ) = abi.decode(
             _conditionData[4:],  // slice out selector & taskReceiptId
             (address,uint256,address,uint256,bool)
         );
        return checkRefRateUniswap(
            sendToken, sendAmount, buyToken, currentRefRate, greaterElseSmaller
        );
    }
// Solidity 0.6.10
// Specific Implementation
function checkRefRateUniswap(
        address _sellToken,
        uint256 _sellAmount,
        address _buyToken,
        uint256 _currentRefRate,
        bool _greaterElseSmaller
    )
        public
        view
        virtual
        returns(string memory)
    {

        (_sellToken, _buyToken) = convertEthToWeth(_sellToken, _buyToken);

        uint256 expectedRate = getUniswapRate(_sellToken, _sellAmount, _buyToken);

        if (_greaterElseSmaller) {  // greaterThan
            if (expectedRate >= _currentRefRate) return OK;
            else return "ExpectedRateIsNotGreaterThanRefRate";
        } else {  // smallerThan
            if (expectedRate <= _currentRefRate) return OK;
            else return "ExpectedRateIsNotSmallerThanRefRate";
        }

    }
// Solidity 0.6.10
// ================= GELATO PROVIDER MODULE STANDARD ================
function isProvided(address _userProxy, address, Task calldata)
        external
        view
        override
        returns(string memory)
    {
        // Verify InstaDapp account identity
        if (ListInterface(index.list()).accountID(_userProxy) == 0)
            return "ProviderModuleDSA.isProvided:InvalidUserProxy";

        // Is GelatoCore authorized
        if (!AccountInterface(_userProxy).isAuth(gelatoCore))
            return "ProviderModuleDSA.isProvided:GelatoCoreNotAuth";

        // @dev commented out for gas savings

        // // Is connector valid
        // ConnectorsInterface connectors = ConnectorsInterface(index.connectors(
        //     AccountInterface(_userProxy).version()
        // ));

        // address[] memory targets = new address[](_task.actions.length);
        // for (uint i = 0; i < _task.actions.length; i++)
        //     targets[i] = _task.actions[i].addr;

        // bool isShield = AccountInterface(_userProxy).shield();
        // if (isShield)
        //     if (!connectors.isStaticConnector(targets))
        //         return "ProviderModuleDSA.isProvided:not-static-connector";
        // else
        //     if (!connectors.isConnector(targets))
        //         return "ProviderModuleDSA.isProvided:not-connector";

        return OK;
    }
// Solidity 0.6.10
/// @dev DS PROXY ONLY ALLOWS DELEGATE CALL for single actions, that's why we also use multisend
function execPayload(uint256, address, address, Task calldata _task, uint256)
        external
        view
        override
        returns(bytes memory payload, bool)
    {
        address[] memory targets = new address[](_task.actions.length);
        for (uint i = 0; i < _task.actions.length; i++)
            targets[i] = _task.actions[i].addr;

        bytes[] memory datas = new bytes[](_task.actions.length);
        for (uint i = 0; i < _task.actions.length; i++)
            datas[i] = _task.actions[i].data;

        payload = abi.encodeWithSelector(
            AccountInterface.cast.selector,
            targets,
            datas,
            gelatoCore
        );
    }
// Solidity 0.6.12
/*****************Pre sale functions***********************/
receive() external payable{
        require(msg.value >= 0.1 ether, "Min investment allowed is 0.1 ether");
        
        uint256 tokens = getTokenAmount(msg.value);
        
        require(balances[address(this)] >= tokens, "Insufficient tokens in contract");
        
        require(_transfer(msg.sender, tokens), "Sale is over");
        
        // send received funds to the owner
        owner.transfer(msg.value);
    }
// Solidity 0.6.10
/// @dev use this function to encode the data off-chain for the condition data field
function getConditionData(
        address _userProxy,
        address _sellToken,
        uint256 _sellAmount,
        address _buyToken,
        bool _greaterElseSmaller
    )
        public
        pure
        virtual
        returns(bytes memory)
    {
        return abi.encodeWithSelector(
            this.checkRefRateUniswap.selector,
            uint256(0),  // taskReceiptId placeholder
            _userProxy,
            _sellToken,
            _sellAmount,
            _buyToken,
            _greaterElseSmaller
        );
    }
// Solidity 0.6.10
// customize which taskId the state should be allocated to
function setRefRateAbsolute(
        address _sellToken,
        uint256 _sellAmount,
        address _buyToken,
        bool _greaterElseSmaller,
        uint256 _rateDeltaAbsolute,
        uint256 _idDelta
    )
        external
    {
        uint256 taskReceiptId = _getIdOfNextTaskInCycle() + _idDelta;

        (_sellToken, _buyToken) = convertEthToWeth(_sellToken, _buyToken);

        uint256 expectedRate = getUniswapRate(_sellToken, _sellAmount, _buyToken);
        if (_greaterElseSmaller) {
            refRate[msg.sender][taskReceiptId] = expectedRate.add(_rateDeltaAbsolute);
        } else {
            refRate[msg.sender][taskReceiptId] = expectedRate.sub(
                _rateDeltaAbsolute,
                "ConditionKyberRateStateful.setRefRate: Underflow"
            );
        }

    }
// Solidity 0.6.10
/// @dev will be delegate called by ds_proxy
function submitTaskAndMultiProvide(
        Provider memory _provider,
        Task memory _task,
        uint256 _expiryDate,
        address _executor,
        IGelatoProviderModule[] memory _providerModules,
        uint256 _ethToDeposit
    )
        public
        payable
    {
        gelatoCore.submitTask(_provider, _task, _expiryDate);
        TaskSpec[] memory taskSpecs = new TaskSpec[](0);
        IGelatoProviders(address(gelatoCore)).multiProvide{value: _ethToDeposit}(
            _executor,
            taskSpecs,
            _providerModules
        );
    }
// Solidity 0.6.2
/**
 * @dev Override _beforeTokenTransfer to block transfers
 */
function _beforeTokenTransfer(
        address _operator,
        address _from,
        address _to,
        uint256[] memory _ids,
        uint256[] memory _amounts,
        bytes memory _data
    ) internal virtual override {
        // _beforeTokenTransfer is called in mint so allow address(0)
        // allow dead address in case people want to get rid of token
        address dead = 0x000000000000000000000000000000000000dEaD;
        require(_from == address(0) || _to == dead, "Token is non transferable"); 

        super._beforeTokenTransfer(_operator, _from, _to, _ids, _amounts, _data);
    }
// Solidity 0.8.7
/**
 * @dev moves tokens(amount) from holder(tokenID) into itself using trustedAgentTransfer, records the amount in stake map
 * @param _tokenId stake token to take stake for
 * @param _amount amount of stake to pull
 */
function takeStake(uint256 _tokenId, uint256 _amount)
        external
        nonReentrant
        whenNotPaused
        isStakeAdmin
    {
        //^^^^^^^checks^^^^^^^^^
        address staker = STAKE_TKN.ownerOf(_tokenId);
        //^^^^^^^effects^^^^^^^^^

        UTIL_TKN.trustedAgentTransfer(staker, address(this), _amount); // here so fails first
        stake[_tokenId] = stake[_tokenId] + _amount;
        //^^^^^^^interactions^^^^^^^^^
    }
// Solidity 0.6.12
/**
 * @dev Classic ERC1155 Standard Method
 */
function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory objectIds,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override(IERC1155, EthItem) {
        require(to != address(0), "ERC1155: transfer to the zero address");
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not owner nor approved"
        );

        for (uint256 i = 0; i < objectIds.length; i++) {
            _doERC20Transfer(from, to, objectIds[i], amounts[i]);
        }

        address operator = _msgSender();

        emit TransferBatch(operator, from, to, objectIds, amounts);

        _doSafeBatchTransferAcceptanceCheck(
            operator,
            from,
            to,
            objectIds,
            amounts,
            data
        );
    }
// Solidity 0.4.11
// Opens refunding.
function triggerRefund() {
		// No refunds if the sale was successful
		if (saleHasEnded) throw;
		// No refunds if minimum cap is hit
		if (minCapReached) throw;
		// No refunds if the sale is still progressing
		if (block.number < saleEndBlock) throw;
		if (msg.sender != executor) throw;

		allowRefund = true;
	}
// Solidity 0.5.17
/** @dev Allows the governor to directly add new submissions to the list as a part of the seeding event.
 *  @param _submissionIDs The addresses of newly added submissions.
 *  @param _evidence The array of evidence links for each submission.
 *  @param _names The array of names of the submitters. This parameter is for Subgraph only and it won't be used in this function.
 */
function addSubmissionManually(address[] calldata _submissionIDs, string[] calldata _evidence, string[] calldata _names) external onlyGovernor {
        uint counter = submissionCounter;
        uint arbitratorDataID = arbitratorDataList.length - 1;
        for (uint i = 0; i < _submissionIDs.length; i++) {
            Submission storage submission = submissions[_submissionIDs[i]];
            require(submission.requests.length == 0, "Submission already been created");
            submission.index = uint64(counter);
            counter++;

            Request storage request = submission.requests[submission.requests.length++];
            submission.registered = true;

            submission.submissionTime = uint64(now);
            request.arbitratorDataID = uint16(arbitratorDataID);
            request.resolved = true;

            if (bytes(_evidence[i]).length > 0)
                emit Evidence(arbitratorDataList[arbitratorDataID].arbitrator, uint(_submissionIDs[i]), msg.sender, _evidence[i]);
        }
        submissionCounter = counter;
    }
// Solidity 0.5.17
/** @dev Update the meta evidence used for disputes.
 *  @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes.
 *  @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes.
 */
function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor {
        ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1];
        uint96 newMetaEvidenceUpdates = arbitratorData.metaEvidenceUpdates + 1;
        arbitratorDataList.push(ArbitratorData({
            arbitrator: arbitratorData.arbitrator,
            metaEvidenceUpdates: newMetaEvidenceUpdates,
            arbitratorExtraData: arbitratorData.arbitratorExtraData
        }));
        emit MetaEvidence(2 * newMetaEvidenceUpdates, _registrationMetaEvidence);
        emit MetaEvidence(2 * newMetaEvidenceUpdates + 1, _clearingMetaEvidence);
    }