lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.3
/**
 * @dev Swap half of contract's token balance for ETH,
 * and pair it up with the other half to add to the
 * liquidity pool.
 *
 * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth,
 * the amount of ETH added to the LP, and the amount of tokens added to the LP.
 */
function swapAndLiquify(uint256 contractBalance) private lockTheSwap {
        // Split the contract balance into two halves.
        uint256 tokensToSwap = contractBalance / 2;
        uint256 tokensAddToLiquidity = contractBalance - tokensToSwap;

        // Contract's current ETH balance.
        uint256 initialBalance = address(this).balance;

        // Swap half of the tokens to ETH.
        swapTokensForEth(tokensToSwap, address(this));

        // Figure out the exact amount of tokens received from swapping.
        uint256 ethAddToLiquify = address(this).balance - initialBalance;

        // Add to the LP of this token and WETH pair (half ETH and half this token).
        addLiquidity(ethAddToLiquify, tokensAddToLiquidity);

        _totalETHLockedInLiquidity += address(this).balance - initialBalance;
        _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this));

        emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity);
    }
// Solidity 0.8.3
/**
 * @dev Swap `amount` tokens for ETH and send to `to`
 *
 * Emits {Transfer} event. From this contract to the token and WETH Pair.
 */
function swapTokensForEth(uint256 amount, address to) private {
        // Generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = _uniswapV2Router.WETH();

        _approve(address(this), address(_uniswapV2Router), amount);


        // Swap tokens to ETH
        _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            amount, 
            0, 
            path, 
            to,
            block.timestamp + 60 * 1000
            );
    }
// Solidity 0.8.3
/**
 * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP.
 * Depends on the current rate for the pair between this token and WETH,
 * `ethAmount` and `tokenAmount` might not match perfectly.
 * Dust(leftover) ETH or token will be refunded to this contract
 * (usually very small quantity).
 *
 * Emits {Transfer} event. From this contract to the token and WETH Pai.
 */
function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private {
        _approve(address(this), address(_uniswapV2Router), tokenAmount);

        // Add the ETH and token to LP.
        // The LP tokens will be sent to burnAccount.
        // No one will have access to them, so the liquidity will be locked forever.
        _uniswapV2Router.addLiquidityETH{value: ethAmount}(
            address(this), 
            tokenAmount, 
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            burnAccount, // the LP is sent to burnAccount. 
            block.timestamp + 60 * 1000
        );
    }
// Solidity 0.8.3
/**
 * @dev Returns fees and transfer amount in both tokens and reflections.
 * tXXXX stands for tokenXXXX
 * rXXXX stands for reflectionXXXX
 * More details can be found at comments for ValuesForAmount Struct.
 */
function _getValues(uint256 amount, bool deductTransferFee, bool selling, bool buying) private view returns (ValuesFromAmount memory) {
        ValuesFromAmount memory values;
        values.amount = amount;
        _getTValues(values, deductTransferFee, selling, buying);
        _getRValues(values, deductTransferFee, selling, buying);
        return values;
    }
// Solidity 0.8.3
/**
 * @dev Adds fees and transfer amount in tokens to `values`.
 * tXXXX stands for tokenXXXX
 * More details can be found at comments for ValuesForAmount Struct.
 */
function _getTValues(ValuesFromAmount memory values, bool deductTransferFee, bool selling, bool buying) view private {
        
        if (deductTransferFee) {
            values.tTransferAmount = values.amount;
        } else {
            // calculate fee
            if (buying || selling) {
                values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals);
                values.tMarketingFee = _calculateTax(values.amount, _taxMarketing, _taxMarketingDecimals);
                values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals);
            }

            if (!buying && selling && values.amount >= getReservePercent(maxSellAmountNormalTax) && values.amount < getReservePercent(maxSellAmountPercent)) {
                values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals);
            }
            
            // amount after fee
            values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee - values.tMarketingFee;
        }
        
    }
// Solidity 0.8.3
/**
 * @dev Returns the current reflection supply and token supply.
 */
function _getCurrentSupply() private view returns(uint256, uint256) {
        uint256 rSupply = _reflectionTotal;
        uint256 tSupply = _totalSupply;      
        for (uint256 i = 0; i < _excludedFromReward.length; i++) {
            if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply);
            rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]];
            tSupply = tSupply - _tokenBalances[_excludedFromReward[i]];
        }
        if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply);
        return (rSupply, tSupply);
    }
// Solidity 0.8.3
/**
 * @dev Enables the auto burn feature.
 * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled.
 *
 * Emits a {EnabledAutoBurn} event.
 *
 * Requirements:
 *
 * - auto burn feature mush be disabled.
 * - tax must be greater than 0.
 * - tax decimals + 2 must be less than token decimals.
 * (because tax rate is in percentage)
 */
function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
        require(!_autoBurnEnabled, "Auto burn feature is already enabled.");
        require(taxBurn_ > 0, "Tax must be greater than 0.");
        require(taxBurnDecimals_ + 2  <= decimals(), "Tax decimals must be less than token decimals - 2");
        
        _autoBurnEnabled = true;
        setTaxBurn(taxBurn_, taxBurnDecimals_);
        
        emit EnabledAutoBurn();
    }
// Solidity 0.8.3
/**
 * @dev Enables the reward feature.
 * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled.
 *
 * Emits a {EnabledReward} event.
 *
 * Requirements:
 *
 * - reward feature mush be disabled.
 * - tax must be greater than 0.
 * - tax decimals + 2 must be less than token decimals.
 * (because tax rate is in percentage)
 */
function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
        require(!_rewardEnabled, "Reward feature is already enabled.");
        require(taxReward_ > 0, "Tax must be greater than 0.");
        require(taxRewardDecimals_ + 2  <= decimals(), "Tax decimals must be less than token decimals - 2");

        _rewardEnabled = true;
        setTaxReward(taxReward_, taxRewardDecimals_);

        emit EnabledReward();
    }
// Solidity 0.8.3
/**
 * @dev Enables the auto swap and liquify feature.
 * Swaps half of transaction amount * `taxLiquify_` amount of tokens
 * to ETH and pair with the other half of tokens to the LP each transaction when enabled.
 *
 * Emits a {EnabledAutoSwapAndLiquify} event.
 *
 * Requirements:
 *
 * - auto swap and liquify feature mush be disabled.
 * - tax must be greater than 0.
 * - tax decimals + 2 must be less than token decimals.
 * (because tax rate is in percentage)
 */
function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner {
        require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled.");
        require(taxLiquify_ > 0, "Tax must be greater than 0.");
        require(taxLiquifyDecimals_ + 2  <= decimals(), "Tax decimals must be less than token decimals - 2");

        _minTokensBeforeSwap = minTokensBeforeSwap_;

        initSwap(routerAddress);

        // enable
        _autoSwapAndLiquifyEnabled = true;
        setTaxLiquify(taxLiquify_, taxLiquifyDecimals_);
        
        emit EnabledAutoSwapAndLiquify();
    }
// Solidity 0.8.3
/**
 * @dev Updates taxBurn
 *
 * Emits a {TaxBurnUpdate} event.
 *
 * Requirements:
 *
 * - auto burn feature must be enabled.
 * - total tax rate must be less than 100%.
 */
function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
        require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function.");

        uint8 previousTax = _taxBurn;
        uint8 previousDecimals = _taxBurnDecimals;
        _taxBurn = taxBurn_;
        _taxBurnDecimals = taxBurnDecimals_;

        emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_);
    }
// Solidity 0.8.3
/**
 * @dev Updates taxReward
 *
 * Emits a {TaxRewardUpdate} event.
 *
 * Requirements:
 *
 * - reward feature must be enabled.
 * - total tax rate must be less than 100%.
 */
function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
        require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function.");

        uint8 previousTax = _taxReward;
        uint8 previousDecimals = _taxRewardDecimals;
        _taxReward = taxReward_;
        _taxRewardDecimals = taxRewardDecimals_;

        emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_);
    }
// Solidity 0.8.3
/**
 * @dev Updates taxLiquify
 *
 * Emits a {TaxLiquifyUpdate} event.
 *
 * Requirements:
 *
 * - auto swap and liquify feature must be enabled.
 * - total tax rate must be less than 100%.
 */
function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner {
        require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function.");

        uint8 previousTax = _taxLiquify;
        uint8 previousDecimals = _taxLiquifyDecimals;
        _taxLiquify = taxLiquify_;
        _taxLiquifyDecimals = taxLiquifyDecimals_;

        emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_);
    }
// Solidity 0.6.12
// Possible ways this could break addressed
// 1) No agreement to terms - added require
// 2) Adding liquidity after LGE is over - added require
// 3) Overflow from uint - impossible there is not enough ETH available
// 4) Depositing 0 - not an issue it will just add 0 totally
function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement)
        public
        payable
    {
        require(liquidityGenerationOngoing(), "Liquidity Generation Event over");
        require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided");
        ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here
        totalETHContributed = totalETHContributed.add(msg.value); // For front end display during LGE. This resets with definitive correct balance while calling pair.
        emit LiquidityAddition(msg.sender, msg.value);
    }
// Solidity 0.4.24
/**
 *@dev list allows a party to place an order on the orderbook
 *@param _tokenadd address of the drct tokens
 *@param _amount number of DRCT tokens
 *@param _price uint256 price of all tokens in wei
 */
function list(address _tokenadd, uint256 _amount, uint256 _price) external {
        require(blacklist[msg.sender] == false);
        require(_price > 0);
        ERC20_Interface token = ERC20_Interface(_tokenadd);
        require(totalListed[msg.sender][_tokenadd] + _amount <= token.allowance(msg.sender,address(this)));
        if(forSale[_tokenadd].length == 0){
            forSale[_tokenadd].push(0);
            }
        forSaleIndex[order_nonce] = forSale[_tokenadd].length;
        forSale[_tokenadd].push(order_nonce);
        orders[order_nonce] = Order({
            maker: msg.sender,
            asset: _tokenadd,
            price: _price,
            amount:_amount
        });
        emit OrderPlaced(order_nonce,msg.sender,_tokenadd,_amount,_price);
        if(openBookIndex[_tokenadd] == 0 ){    
            openBookIndex[_tokenadd] = openBooks.length;
            openBooks.push(_tokenadd);
        }
        userOrderIndex[order_nonce] = userOrders[msg.sender].length;
        userOrders[msg.sender].push(order_nonce);
        totalListed[msg.sender][_tokenadd] += _amount;
        order_nonce += 1;
    }
// Solidity 0.4.24
//Then you would have a mapping from an asset to its price/ quantity when you list it.
function listDda(address _asset, uint256 _amount, uint256 _price, bool _isLong) public onlyOwner() {
        require(blacklist[msg.sender] == false);
        ListAsset storage listing = listOfAssets[_asset];
        listing.price = _price;
        listing.amount= _amount;
        listing.isLong= _isLong;
        openDdaListIndex[_asset] = openDdaListAssets.length;
        openDdaListAssets.push(_asset);
        emit ListDDA(_asset,_amount,_price,_isLong);
        
    }
// Solidity 0.4.24
/**
 *@dev list allows a DDA to remove asset 
 *@param _asset address 
 */
function unlistDda(address _asset) public onlyOwner() {
        require(blacklist[msg.sender] == false);
        uint256 indexToDelete;
        uint256 lastAcctIndex;
        address lastAdd;
        ListAsset storage listing = listOfAssets[_asset];
        listing.price = 0;
        listing.amount= 0;
        listing.isLong= false;
        indexToDelete = openDdaListIndex[_asset];
        lastAcctIndex = openDdaListAssets.length.sub(1);
        lastAdd = openDdaListAssets[lastAcctIndex];
        openDdaListAssets[indexToDelete]=lastAdd;
        openDdaListIndex[lastAdd]= indexToDelete;
        openDdaListAssets.length--;
        openDdaListIndex[_asset] = 0;
        emit UnlistDDA(_asset);
    }
// Solidity 0.4.24
/**
 *@dev buy allows a party to partially fill an order
 *@param _asset is the address of the assset listed
 *@param _amount is the amount of tokens to buy
 */
function buyPerUnit(address _asset, uint256 _amount) external payable {
        require(blacklist[msg.sender] == false);
        ListAsset storage listing = listOfAssets[_asset];
        require(_amount <= listing.amount);
        uint totalPrice = _amount.mul(listing.price);
        require(msg.value == totalPrice);
        ERC20_Interface token = ERC20_Interface(_asset);
        if(token.allowance(owner,address(this)) >= _amount){
            assert(token.transferFrom(owner,msg.sender, _amount));
            owner.transfer(totalPrice);
            listing.amount= listing.amount.sub(_amount);
        }
        emit BuyDDA(_asset,msg.sender,_amount,totalPrice);
    }
// Solidity 0.4.24
/**
 *@dev buy allows a party to fill an order
 *@param _orderId is the uint256 ID of order
 */
function buy(uint256 _orderId) external payable {
        Order memory _order = orders[_orderId];
        require(_order.price != 0 && _order.maker != address(0) && _order.asset != address(0) && _order.amount != 0);
        require(msg.value == _order.price);
        require(blacklist[msg.sender] == false);
        address maker = _order.maker;
        ERC20_Interface token = ERC20_Interface(_order.asset);
        if(token.allowance(_order.maker,address(this)) >= _order.amount){
            assert(token.transferFrom(_order.maker,msg.sender, _order.amount));
            maker.transfer(_order.price);
        }
        unLister(_orderId,_order);
        emit Sale(_orderId,msg.sender,_order.asset,_order.amount,_order.price);
    }
// Solidity 0.4.24
/**
 *@dev An internal function to update mappings when an order is removed from the book
 *@param _orderId is the uint256 ID of order
 *@param _order is the struct containing the details of the order
 */
function unLister(uint256 _orderId, Order _order) internal{
            uint256 tokenIndex;
            uint256 lastTokenIndex;
            address lastAdd;
            uint256  lastToken;
        totalListed[_order.maker][_order.asset] -= _order.amount;
        if(forSale[_order.asset].length == 2){
            tokenIndex = openBookIndex[_order.asset];
            lastTokenIndex = openBooks.length.sub(1);
            lastAdd = openBooks[lastTokenIndex];
            openBooks[tokenIndex] = lastAdd;
            openBookIndex[lastAdd] = tokenIndex;
            openBooks.length--;
            openBookIndex[_order.asset] = 0;
            forSale[_order.asset].length -= 2;
        }
        else{
            tokenIndex = forSaleIndex[_orderId];
            lastTokenIndex = forSale[_order.asset].length.sub(1);
            lastToken = forSale[_order.asset][lastTokenIndex];
            forSale[_order.asset][tokenIndex] = lastToken;
            forSaleIndex[lastToken] = tokenIndex;
            forSale[_order.asset].length--;
        }
        forSaleIndex[_orderId] = 0;
        orders[_orderId] = Order({
            maker: address(0),
            price: 0,
            amount:0,
            asset: address(0)
        });
        if(userOrders[_order.maker].length > 1){
            tokenIndex = userOrderIndex[_orderId];
            lastTokenIndex = userOrders[_order.maker].length.sub(1);
            lastToken = userOrders[_order.maker][lastTokenIndex];
            userOrders[_order.maker][tokenIndex] = lastToken;
            userOrderIndex[lastToken] = tokenIndex;
        }
        userOrders[_order.maker].length--;
        userOrderIndex[_orderId] = 0;
    }
// Solidity 0.6.10
/// @dev Lets a user join DAOcare through depositing
/// @param amount the user wants to deposit into the DAOcare pool
function deposit(uint256 amount)
    external
    hasNotEmergencyVoted
    allowanceAvailable(amount)
    requiredDai(amount)
    stableState
  {
    // NOTE: if the user adds a deposit they won't be able to vote in that iteration
    _depositFunds(amount);
    noLossDaoContract.noLossDeposit(msg.sender);
    emit DepositAdded(msg.sender, amount);
  }
// Solidity 0.6.10
/// @dev Lets a user withdraw some of their amount
/// Checks they have not voted
function withdrawDeposit(uint256 amount)
    external
    // If this user has voted to call an emergancy, they cannot do a partial withdrawal
    hasNotEmergencyVoted
    validAmountToWithdraw(amount) // not trying to withdraw full amount (eg. amount is less than the total)
    userHasNotVotedThisIterationAndIsNotProposal // checks they have not voted
  {
    _withdrawFunds(amount);
    emit PartialDepositWithdrawn(msg.sender, amount);
  }
// Solidity 0.6.10
/// @dev Internal function splitting and sending the accrued interest between winners.
/// @param receivers An array of the addresses to split between
/// @param percentages the respective percentage to split
/// @param winner The person who will recieve this distribution
/// @param iteration the iteration of the dao
/// @param totalInterestFromIteration Total interest that should be split to relevant parties
/// @param tokenContract will be aDai or Dai (depending on try catch in distributeInterst - `redeem`)
function _distribute(
    address[] calldata receivers,
    uint256[] calldata percentages,
    address winner,
    uint256 iteration,
    uint256 totalInterestFromIteration,
    address tokenContract
  ) internal {
    IERC20 payoutToken = IERC20(tokenContract);

    uint256 winnerPayout = totalInterestFromIteration;
    for (uint256 i = 0; i < receivers.length; i++) {
      uint256 amountToSend = totalInterestFromIteration.mul(percentages[i]).div(
        1000
      );
      payoutToken.transfer(receivers[i], amountToSend);
      winnerPayout = winnerPayout.sub(amountToSend); //SafeMath prevents this going below 0
      emit InterestSent(receivers[i], amountToSend);
    }

    payoutToken.transfer(winner, winnerPayout);
    emit WinnerPayout(winner, winnerPayout, iteration);
  }
// Solidity 0.6.10
/// @dev Tries to redeem aDai and send acrrued interest to winners. Falls back to Dai.
/// @param receivers An array of the addresses to split between
/// @param percentages the respective percentage to split
/// @param winner address of the winning proposal
/// @param iteration the iteration of the dao
function distributeInterest(
    address[] calldata receivers,
    uint256[] calldata percentages,
    address winner,
    uint256 iteration
  )
    external
    validInterestSplitInput(receivers, percentages)
    noLossDaoContractOnly
  {
    uint256 amountToRedeem = adaiContract.balanceOf(address(this)).sub(
      totalDepositedDai
    );
    try adaiContract.redeem(amountToRedeem)  {
      _distribute(
        receivers,
        percentages,
        winner,
        iteration,
        amountToRedeem,
        address(daiContract)
      );
    } catch {
      _distribute(
        receivers,
        percentages,
        winner,
        iteration,
        amountToRedeem,
        address(adaiContract)
      );
    }
  }
// Solidity 0.4.25
/// @dev Perform a buy order at the exchange
/// @param data OrderData struct containing order values
/// @param  amountToGiveForOrder amount that should be spent on this order
/// @return amountSpentOnOrder the amount that would be spent on the order
/// @return amountReceivedFromOrder the amount that was received from this order
function performBuyOrder(
        OrderData data,
        uint256 amountToGiveForOrder
    )
        public
        payable
        whenNotPaused
        onlySelf
        returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
    {
        amountSpentOnOrder = amountToGiveForOrder;
        exchange.deposit.value(amountToGiveForOrder)();
        uint256 amountToSpend = removeFee(amountToGiveForOrder);
        amountReceivedFromOrder = SafeMath.div(SafeMath.mul(amountToSpend, data.makerAmount), data.takerAmount);
        exchange.trade(data.takerToken, data.takerAmount, data.makerToken, data.makerAmount, data.expires, data.nonce, data.user, data.v, data.r, data.s, amountToSpend);
        /* logger.log("Performing TokenStore buy order arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder);  */
        exchange.withdrawToken(data.makerToken, amountReceivedFromOrder);
        if (!ERC20SafeTransfer.safeTransfer(data.makerToken, totlePrimary, amountReceivedFromOrder)){
            errorReporter.revertTx("Failed to transfer tokens to totle primary");
        }

    }
// Solidity 0.4.25
/// @notice payable fallback to block EOA sending eth
/// @dev this should fail if an EOA (or contract with 0 bytecode size) tries to send ETH to this contract
function() public payable {
        // Check in here that the sender is a contract! (to stop accidents)
        uint256 size;
        address sender = msg.sender;
        assembly {
            size := extcodesize(sender)
        }
        require(size > 0);
    }