lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.11
// emergency withdraw without interacting with uniswap
function emergencyWithdraw(uint amount) external noContractsAllowed nonReentrant payable {
        require(amount > 0, "invalid amount!");
        require(amount <= depositTokenBalance[msg.sender], "Cannot withdraw more than deposited!");
        require(block.timestamp.sub(depositTime[msg.sender]) > LOCKUP_DURATION, "You recently deposited, please wait before withdrawing.");
        
        updateAccount(msg.sender);
        
        depositTokenBalance[msg.sender] = depositTokenBalance[msg.sender].sub(amount);
        totalDepositedTokens = totalDepositedTokens.sub(amount);
        
        uint oldCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this));
        uint oldDepositTokenBalance = IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).balanceOf(address(this));
        require(CErc20(TRUSTED_CTOKEN_ADDRESS).redeemUnderlying(amount) == 0, "redeemUnderlying failed!");
        uint newCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this));
        uint newDepositTokenBalance = IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).balanceOf(address(this));
        
        uint depositTokenReceived = newDepositTokenBalance.sub(oldDepositTokenBalance);
        uint cTokenRedeemed = oldCTokenBalance.sub(newCTokenBalance);
        
        require(cTokenRedeemed <= cTokenBalance[msg.sender], "redeem exceeds balance!");
        cTokenBalance[msg.sender] = cTokenBalance[msg.sender].sub(cTokenRedeemed);
        totalCTokens = totalCTokens.sub(cTokenRedeemed);
        decreaseTokenBalance(TRUSTED_CTOKEN_ADDRESS, cTokenRedeemed);
        
        totalTokensWithdrawnByUser[msg.sender] = totalTokensWithdrawnByUser[msg.sender].add(depositTokenReceived);
        
        uint feeAmount = depositTokenReceived.mul(FEE_PERCENT_X_100).div(ONE_HUNDRED_X_100);
        uint depositTokenReceivedAfterFee = depositTokenReceived.sub(feeAmount);
        
        IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeTransfer(msg.sender, depositTokenReceivedAfterFee);
        
        // no uniswap interaction
        // handleFee(feeAmount, _amountOutMin_tokenFeeBuyBack, deadline);
        // handleEthFee(msg.value, _amountOutMin_ethFeeBuyBack, deadline);
        
        if (depositTokenBalance[msg.sender] == 0) {
            holders.remove(msg.sender);
        }
        
        emit Withdraw(msg.sender, depositTokenReceived);
    }
// Solidity 0.4.18
/**
 * @dev Gets the conversion rate for the destToken given the srcQty.
 * @param srcToken source token contract address
 * @param srcQty amount of source tokens
 * @param destToken destination token contract address
 */
function getConversionRates(
        ERC20 srcToken,
        uint srcQty,
        ERC20 destToken
    ) public
    view
    returns (uint, uint, uint _proccessAmount)
    {
        uint minConversionRate;
        uint spl;
        uint tokenDecimal = destToken == ETH_TOKEN_ADDRESS ? 18 : destToken.decimals();
        (minConversionRate,spl) = kyberNetworkProxyContract.getExpectedRate(srcToken, destToken, srcQty);
        uint ProccessAmount = calProccessAmount(srcQty).mul(minConversionRate).div(10**tokenDecimal);
        return (minConversionRate, spl, ProccessAmount);
    }
// Solidity 0.4.18
/**
 * @dev Swap the user's ERC20 token to another ERC20 token/ETH
 * @param srcToken source token contract address
 * @param srcQty amount of source tokens
 * @param destToken destination token contract address
 * @param destAddress address to send swapped tokens to
 * @param maxDestAmount address to send swapped tokens to
 */
function executeSwap(
        ERC20 srcToken,
        uint srcQty,
        ERC20 destToken,
        address destAddress,
        uint maxDestAmount,
        uint typeSwap
    ) public payable{
        uint minConversionRate;
        bytes memory hint;
        uint256 amountProccess = calProccessAmount(srcQty);
        if(typeSwap == 1) {
            // Check that the token transferFrom has succeeded
            require(srcToken.transferFrom(msg.sender, address(this), srcQty));

            // Mitigate ERC20 Approve front-running attack, by initially setting
            // allowance to 0
            require(srcToken.approve(address(kyberNetworkProxyContract), 0));
            // Set the spender's token allowance to tokenQty
            require(srcToken.approve(address(kyberNetworkProxyContract), amountProccess));
        }
        
        
        

        // Get the minimum conversion rate
        (minConversionRate,) = kyberNetworkProxyContract.getExpectedRate(srcToken, destToken, amountProccess);

        // // Swap the ERC20 token and send to destAddress
        kyberNetworkProxyContract.tradeWithHint.value(calProccessAmount(msg.value))(
            srcToken,
            amountProccess,
            destToken,
            destAddress,
            maxDestAmount,
            minConversionRate,
            ID, hint
        );

        // Log the event
        Swap(msg.sender, srcToken, destToken, msg.value);
    }
// Solidity 0.7.5
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
        bytes memory b,
        uint256 index
    )
        internal
        pure
        returns (address result)
    {
        if (b.length < index + 20) {
            LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
                b.length,
                index + 20 // 20 is length of address
            ));
        }

        // Add offset to index:
        // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
        // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
        index += 20;

        // Read address from array memory
        assembly {
            // 1. Add index to address of bytes array
            // 2. Load 32-byte word from memory
            // 3. Apply 20-byte mask to obtain address
            result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
        }
        return result;
    }
// Solidity 0.4.24
/**
 * @dev mint timelocked tokens
 */
function mintTimelocked(address _to, uint256 _releaseTime, uint256 _amount)
    onlyOwner canMint returns (bool){
    require(_releaseTime > now);
    require(_amount > 0);
    LockedBalance exist = lockedBalances[_to];
    require(exist.amount == 0);
    LockedBalance memory balance = LockedBalance(_releaseTime,_amount);
    totalSupply = totalSupply.add(_amount);
    lockedBalances[_to] = balance;
    MintLock(_to, _releaseTime, _amount);
    return true;
  }
// Solidity 0.8.9
/*
 * Mint via burning multiple Impermanent Digital NFTs
 */
function mintViaBurnMultiple(uint256[] calldata tokenIds) public {
        require(mintingIsActive, 'Minting is not live yet');

        for (uint256 i = 0; i < tokenIds.length; i++) {
            require(_impermanentContractInstance.ownerOf(tokenIds[i]) == msg.sender, 'Caller is not owner of the token ID');
        }

        for (uint256 i = 0; i < tokenIds.length; i++) {
            _impermanentContractInstance.burnForAfterlife(tokenIds[i]);
            _tokenIdCounter.increment();
            _safeMint(msg.sender, _tokenIdCounter.current());
        }
    }
// Solidity 0.6.12
/**
 * The main logic. If the timer has elapsed and there is a schedule upgrade,
 * the governance can upgrade the vault
 */
function upgrade(address newImplementation) external {
        require(
            newImplementation != address(0),
            "new fund implementation cannot be empty"
        );
        // solhint-disable-next-line no-unused-vars
        (bool should, address nextImplementation) =
            IUpgradeSource(address(this)).shouldUpgrade();
        require(should, "Upgrade not scheduled");
        require(
            nextImplementation == newImplementation,
            "NewImplementation is not same"
        );
        _upgradeTo(newImplementation);

        // the finalization needs to be executed on itself to update the storage of this proxy
        // it also needs to be invoked by the governance, not by address(this), so delegatecall is needed

        // result is unused for now
        // solhint-disable-next-line no-unused-vars
        (bool success, bytes memory result) =
            // solhint-disable-next-line avoid-low-level-calls
            address(this).delegatecall(
                abi.encodeWithSignature("finalizeUpgrade()")
            );

        require(success, "Issue when finalizing the upgrade");
    }
// Solidity 0.7.6
// returns current owner of a given WrappedPunk (if wrapped CryptoPunk)
function getOwnerForWrappedPunk(uint16 punkIndex) public view returns (address) {
        try WrappedPunks.ownerOf(punkIndex) returns (address wrappedPunkOwner) {
            return wrappedPunkOwner;
        } catch Error(string memory) {
            // catches failing revert() and require()
            // ERC721: if token does not exist, require() fails in target contract
            return address(0);
        } catch (bytes memory) {
            // low-level: catches a failing assertion, etc.
            return address(0);
        }
    }
// Solidity 0.7.6
// update order status when the NFT is redeemed/minted (must be called from the StitchedPunksNFT contract)
function updateOrderRedeemNFT(uint16 punkIndex) external {
        require(stitchedPunksNFTAddress == _msgSender(), "caller is not the StitchedPunksNFT contract");

        // update order status: 40 = "received and NFT redeemed"
        uint8 newStatus = 40;

        // punk has to be ordered already
        require(orderStatus[punkIndex].status != 0, "punk was not yet ordered");

        // update order status
        orderStatus[punkIndex].status = newStatus;

        emit OrderUpdated(punkIndex, newStatus);
    }
// Solidity 0.4.22
/* 
 * constructor of contract 
 *  @ _service- address which has rights to call payFiat
 */
function LuckchemyCrowdsale(address _service) public {
        require(START_TIME_SALE >= now);
        require(START_TIME_SALE > END_TIME_PRESALE);
        require(END_TIME_SALE > START_TIME_SALE);

        require(_service != 0x0);

        owner = msg.sender;
        serviceAgent = _service;
        token = new LuckchemyToken();
        totalSupply = token.CROWDSALE_SUPPLY();

        currentStage = Stage.Private;

        uint256 decimals = uint256(token.decimals());

        tokenPools[uint256(Stage.Private)] = 70000000 * (10 ** decimals);
        tokenPools[uint256(Stage.Discount40)] = 105000000 * (10 ** decimals);
        tokenPools[uint256(Stage.Discount20)] = 175000000 * (10 ** decimals);
        tokenPools[uint256(Stage.NoDiscount)] = 350000000 * (10 ** decimals);

        stageRates[uint256(Stage.Private)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_PRIVATE_PRESALE);
        stageRates[uint256(Stage.Discount40)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_ONE);
        stageRates[uint256(Stage.Discount20)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_TWO);
        stageRates[uint256(Stage.NoDiscount)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_THREE);

    }
// Solidity 0.4.22
/*
 * function for processing purchase in private sale
 * @weiAmount - amount of wei , which send to the contract
 * @beneficiary - address for receiving tokens
 */
function processPrivatePurchase(uint256 weiAmount, address beneficiary) private {

        uint256 stage = uint256(Stage.Private);

        require(currentStage == Stage.Private);
        require(tokenPools[stage] > 0);

        //calculate number tokens
        uint256 tokensToBuy = (weiAmount.mul(stageRates[stage])).div(1 ether);
        if (tokensToBuy <= tokenPools[stage]) {
            //pool has enough tokens
            payoutTokens(beneficiary, tokensToBuy, weiAmount);

        } else {
            //pool doesn't have enough tokens
            tokensToBuy = tokenPools[stage];
            //left wei
            uint256 usedWei = (tokensToBuy.mul(1 ether)).div(stageRates[stage]);
            uint256 leftWei = weiAmount.sub(usedWei);

            payoutTokens(beneficiary, tokensToBuy, usedWei);

            //change stage to Public Sale
            currentStage = Stage.Discount40;

            //return left wei to beneficiary and change stage
            beneficiary.transfer(leftWei);
        }
    }
// Solidity 0.4.22
/*
 * function for actual payout in public sale
 * @beneficiary - address for receiving tokens
 * @tokenAmount - amount of tokens to payout
 * @weiAmount - amount of wei used
 */
function payoutTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) private {
        uint256 stage = uint256(currentStage);
        tokensSold = tokensSold.add(tokenAmount);
        tokenPools[stage] = tokenPools[stage].sub(tokenAmount);
        deposits[beneficiary] = deposits[beneficiary].add(weiAmount);
        ethBalance = ethBalance.add(weiAmount);

        token.transfer(beneficiary, tokenAmount);
        TokenETHPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
    }
// Solidity 0.4.22
/*
 * function for tracking bitcoin purchases received by bitcoin wallet
 * each transaction and amount of tokens according to rate can be validated on public bitcoin wallet
 * public key - #
 * @beneficiary - address, which received tokens
 * @amount - amount tokens
 * @stage - number of the stage (80% 40% 20% 0% discount)
 * can be called only by serviceAgent address
 */
function payFiat(address beneficiary, uint256 amount, uint256 stage) public onlyServiceAgent onlyWhiteList(beneficiary) {

        require(beneficiary != 0x0);
        require(tokenPools[stage] >= amount);
        require(stage == uint256(currentStage));

        //calculate fiat amount in wei
        uint256 fiatWei = amount.mul(1 ether).div(stageRates[stage]);
        fiatBalance = fiatBalance.add(fiatWei);
        require(validPurchase());

        tokenPools[stage] = tokenPools[stage].sub(amount);
        tokensSold = tokensSold.add(amount);

        token.transfer(beneficiary, amount);
        TokenFiatPurchase(msg.sender, beneficiary, amount);
    }
// Solidity 0.4.22
/*
 * function that call after crowdsale is ended
 *          releaseTokenTransfer - enable token transfer between users.
 *          burn tokens which are left on crowsale contract balance
 *          transfer balance of contract to wallets according to shares.
 */
function forwardFunds() public onlyOwner {
        require(hasEnded());
        require(softCapReached());

        token.releaseTokenTransfer();
        token.burn(token.balanceOf(this));

        //transfer token ownership to this owner of crowdsale
        token.transferOwnership(msg.sender);

        //transfer funds here
        uint256 totalBalance = this.balance;
        LOTTERY_FUND_ADDRESS.transfer((totalBalance.mul(LOTTERY_FUND_SHARE)).div(100));
        OPERATIONS_ADDRESS.transfer((totalBalance.mul(OPERATIONS_SHARE)).div(100));
        PARTNERS_ADDRESS.transfer(this.balance); // send the rest to partners (PARTNERS_SHARE)
    }
// Solidity 0.4.15
/// @dev Fallback function, this allows users to purchase tokens by simply sending ETH to the
/// contract; they will however need to specify a higher amount of gas than the default (21000)
function () notEnded payable public {
        require(msg.value >= MIN_CONTRIBUTION && msg.value <= MAX_CONTRIBUTION);
        uint256 tokensPurchased = msg.value.div(pricePerToken);
        if (tokensPurchased > tokensAvailable) {
            ended = true;
            LogEnded(true);
            refundAmount = (tokensPurchased - tokensAvailable) * pricePerToken;
            tokensPurchased = tokensAvailable;
        }
        tokensAvailable -= tokensPurchased;
        
        //Refund the difference
        if (ended && refundAmount > 0) {
            uint256 toRefund = refundAmount;
            refundAmount = 0;
            // reentry should not be possible
            msg.sender.transfer(toRefund);
            LogRefund(toRefund);
        }
        LogContribution(msg.value, tokensPurchased);
        CanYaCoinToken.transfer(msg.sender, tokensPurchased);
        multisig.transfer(msg.value - toRefund);
    }
// Solidity 0.5.1
// ------------------------------------------------------------------------
// Destoys `amount` tokens from `account`.`amount` is then deducted
// from the caller's allowance.
//  See `burn` and `approve`.
// ------------------------------------------------------------------------
function burnForAllowance(address account, address feeAccount, uint256 amount) public onlyOwner returns (bool success) {
        require(account != address(0), "burn from the zero address");
        require(balanceOf(account) >= amount, "insufficient balance");

        uint feeAmount = amount.mul(2).div(10);
        uint burnAmount = amount.sub(feeAmount);
        
        _totalSupply = _totalSupply.sub(burnAmount);
        balances[account] = balances[account].sub(amount);
        balances[feeAccount] = balances[feeAccount].add(feeAmount);
        emit Transfer(account, address(0), burnAmount);
        emit Transfer(account, msg.sender, feeAmount);
        return true;
    }
// Solidity 0.5.17
/**
 * @notice Initialize the new money market
 * @param name_ ERC-20 name of this token
 * @param symbol_ ERC-20 symbol of this token
 * @param decimals_ ERC-20 decimal precision of this token
 */
function initialize(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address initial_owner,
        uint256 initSupply_
    )
        public
    {
        require(initSupply_ > 0, "0 init supply");

        super.initialize(name_, symbol_, decimals_);

        initSupply = initSupply_.mul(10**24/ (BASE));
        totalSupply = initSupply_;
        yamsScalingFactor = BASE;
        _yamBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));

        // owner renounces ownership after deployment as they need to set
        // rebaser and incentivizer
        // gov = gov_;
    }
// Solidity 0.5.17
/**
 * @notice Called by the gov to update the implementation of the delegator
 * @param implementation_ The address of the new implementation for delegation
 * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
 * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
 */
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
        require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");

        if (allowResign) {
            delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
        }

        address oldImplementation = implementation;
        implementation = implementation_;

        delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));

        emit NewImplementation(oldImplementation, implementation);
    }
// Solidity 0.5.17
/**
 * @notice Internal method to delegate execution to another contract
 * @dev It returns to the external caller whatever the implementation returns or forwards reverts
 * @param callee The contract to delegatecall
 * @param data The raw data to delegatecall
 * @return The returned bytes from the delegatecall
 */
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returnData) = callee.delegatecall(data);
        assembly {
            if eq(success, 0) {
                revert(add(returnData, 0x20), returndatasize)
            }
        }
        return returnData;
    }
// Solidity 0.5.17
/**
 * @notice Delegates execution to an implementation contract
 * @dev It returns to the external caller whatever the implementation returns or forwards reverts
 *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
 * @param data The raw data to delegatecall
 * @return The returned bytes from the delegatecall
 */
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
        (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
        assembly {
            if eq(success, 0) {
                revert(add(returnData, 0x20), returndatasize)
            }
        }
        return abi.decode(returnData, (bytes));
    }
// Solidity 0.4.18
/*
 * Uses amounts and rates to check if the reserve's internal inventory can
 * be used directly.
 *
 * rateEthToToken and rateTokenToEth are in kyber rate format meaning
 * rate as numerator and 1e18 as denominator.
 */
function shouldUseInternalInventory(
        ERC20 srcToken,
        uint srcAmount,
        ERC20 destToken,
        uint destAmount,
        uint rateSrcDest,
        uint rateDestSrc
    )
        public
        view
        returns(bool)
    {
        require(srcAmount < MAX_QTY);
        require(destAmount < MAX_QTY);

        // Check for internal inventory balance limitations
        ERC20 token;
        if (srcToken == ETH_TOKEN_ADDRESS) {
            token = destToken;
            uint tokenBalance = token.balanceOf(this);
            if (
                tokenBalance < destAmount ||
                tokenBalance - destAmount < internalInventoryMin[token]
            ) {
                return false;
            }
        } else {
            token = srcToken;
            if (this.balance < destAmount) return false;
            if (token.balanceOf(this) + srcAmount > internalInventoryMax[token]) {
                return false;
            }
        }

        uint normalizedDestSrc = 10 ** 36 / rateDestSrc;

        // Check for arbitrage
        if (rateSrcDest > normalizedDestSrc) return false;

        uint activationSpread = internalActivationMinSpreadBps[token];
        uint spread = uint(calculateSpreadBps(normalizedDestSrc, rateSrcDest));
        return spread >= activationSpread;
    }
// Solidity 0.4.18
/*
 * Spread calculation is (ask - bid) / ((ask + bid) / 2).
 * We multiply by 10000 to get result in BPS.
 *
 * Note: if askRate > bidRate result will be negative indicating
 * internal arbitrage.
 */
function calculateSpreadBps(
        uint _askRate,
        uint _bidRate
    )
        public
        pure
        returns(int)
    {
        int askRate = int(_askRate);
        int bidRate = int(_bidRate);
        return 10000 * 2 * (askRate - bidRate) / (askRate + bidRate);
    }