/**



 ..  ..  ..  :~?Y5GGGGGGGGGGGPPY7~:.   ..  ..  ..
..  ..    .~JPP5Y?!~^::::::::^~!?YPPPJ!.  ..  ..  
  ..   .^YGPYY57...:::::::::::...JG5YYPGY~  ..  ..
..   .~PBYJP#@@@?.:::::::::::::.Y@@@@#PJYBG!  ..  
  . :P#JJB@@@@@@@J.:::::::::::.J@@@@@@@@BJJ#G^  ..
.. 7&57G@@@@@@@@@@Y.:::::::::.?@@@@@@@@@@@B75&?   
  J@?J@@@@@@@@@@@@@5:.::::::.?@@@@@@@@@@@@@@J?@Y .
 ?@7J@@@@@@@@@@@@@@@P::::::.?@@@@@@@@@@@@@@@@J7@? 
^@Y!@@@@@@@@@@@@@@@@@?.....^B@@@@@@@@@@@@@@@@@!Y@~
P&^B@@@@@@@@@@@@@@@G~.:!??!^.!P@@@@@@@@@@@@@@@B^&P
&G~@@@@@@@@@@@@@@@P:.7#@@@@&J..J@@@@@@@@@@@@@@@~G@
@5~GGGGBBBBBBBBBBB~.:#@@@@@@@^..J555YYYYYYJJJJJ^P@
@G:...::::::::::::::.?&@@@@@Y:::...............:G&
P&^:::::::::::::::::..:7JJ7^.:.::::::::::::::::^@P
~@5::::::::::::::::.^PGYJJY5B#?.:::::::::::::::5@^
 ?@7::::::::::::::.7&@@@@@@@@@@5:.::::::::::::?@? 
  Y@?:::::::::::.:Y@@@@@@@@@@@@@B~.::::::::::?@J  
.  ?&5:::::::::.~B@@@@@@@@@@@@@@@&?..::::::^P&7  .
..  ^G#?::.:::.?&@@@@@@@@@@@@@@@@@@P^.:.::J#P^ .. 
  ..  !GBY~:.:5@@@@@@@@@@@@@@@@@@@@@#~:~YBP~    ..
..  ..  ~5BGJ?5G#&@@@@@@@@@@@@@@&#G5YYGBY^    ..  
  ..  ..  .!JPPP5YY55PPGGGGPP55YY5PPPJ~.    ..  ..
..  ..  ..    :~7Y5PPGGGGGGGGPP5J7~:     ...  .. 


Bull or Bear the question on everyones mind is 

░██╗░░░░░░░██╗███████╗███╗░░██╗  ███╗░░██╗██╗░░░██╗██╗░░██╗███████╗
░██║░░██╗░░██║██╔════╝████╗░██║  ████╗░██║██║░░░██║██║░██╔╝██╔════╝
░╚██╗████╗██╔╝█████╗░░██╔██╗██║  ██╔██╗██║██║░░░██║█████═╝░█████╗░░
░░████╔═████║░██╔══╝░░██║╚████║  ██║╚████║██║░░░██║██╔═██╗░██╔══╝░░
░░╚██╔╝░╚██╔╝░███████╗██║░╚███║  ██║░╚███║╚██████╔╝██║░╚██╗███████╗
░░░╚═╝░░░╚═╝░░╚══════╝╚═╝░░╚══╝  ╚═╝░░╚══╝░╚═════╝░╚═╝░░╚═╝╚══════╝

Telegram: https://t.me/NUKEPORTAL
website: http://wennuke.site/
Twitter: https://twitter.com/NukeERC20

**/


// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

library Address {
    function isContract(address account) internal view returns (bool) {
        return account.code.length > 0;
    }

    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

interface IERC20Metadata is IERC20 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
}

contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    constructor(string memory name_, string memory symbol_, uint8 decimals_) {
        _name = name_;
        _symbol = symbol_;
        _decimals = decimals_;
    }

    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        if(currentAllowance != type(uint256).max){
            require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
            unchecked {
                _approve(sender, _msgSender(), currentAllowance - amount);
            }
        }

        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);
    }

    function _createInitialSupply(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);
    }

    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }
}

contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    function owner() public view returns (address) {
        return _owner;
    }

    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    function renounceOwnership() external virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

interface ILpPair {
    function sync() external;
}

interface IDexRouter {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);
    function swapExactTokensForETHSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable;
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external;
    function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    function addLiquidity(address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB, uint liquidity);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
}

interface IDexFactory {
    function createPair(address tokenA, address tokenB) external returns (address pair);
}


contract WenNuke is ERC20, Ownable {

    uint256 public maxBuyAmount;
    uint256 public maxWalletAmount; 



    IDexRouter public immutable dexRouter;
    address public immutable lpPair;

    bool private swapping;
    uint256 public swapTokensAtAmount;

    address public marketingAddress;

    uint256 public tradingActiveBlock = 0; // 0 means trading is not active

    bool public limitsInEffect = true;
    bool public tradingActive = false;
    bool public swapEnabled = false;
    
     // Anti-bot and anti-whale mappings and variables
    mapping(address => uint256) private _holderLastTransferBlock; // to hold last Transfers temporarily during launch
    bool public transferDelayEnabled = true;

    uint256 public buyTotalFees;
    uint256 public buyTaxFee;
    uint256 public buyLiquidityFee;

    uint256 public sellTotalFees;
    uint256 public sellTaxFee;
    uint256 public sellLiquidityFee;

    uint256 public tokensForMarket;
    uint256 public tokensForLiquidity;
    
    mapping (address => bool) private _isExcludedFromFees;
    mapping (address => bool) public _isExcludedMaxTransactionAmount;

    mapping (address => bool) public automatedMarketMakerPairs;

    event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
    event EnabledTrading();
    event RemovedLimits();
    event ExcludeFromFees(address indexed account, bool isExcluded);
    event UpdatedMaxBuyAmount(uint256 newAmount);
    event UpdateMaxWalletAmount(uint256 newAmount);
    event UpdatedBuyFee(uint256 newAmount);
    event UpdatedSellFee(uint256 newAmount);
    event UpdatedMarketAddress(address indexed newWallet);
    event MaxTransactionExclusion(address _address, bool excluded);
    event OwnerForcedSwapBack(uint256 timestamp);
    event TransferForeignToken(address token, uint256 amount);
    event RemovedTokenHoldingsRequiredToBuy();
    event TransferDelayDisabled();
    event ReuppedApprovals();
    event SwapTokensAtAmountUpdated(uint256 newAmount);

    constructor() ERC20("Wen", "Nuke", 18){
        address newOwner = msg.sender; // can leave alone if owner is deployer.

        address _dexRouter;

        // automatically detect router/desired stablecoin
        if(block.chainid == 1){
            _dexRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // ETH: Uniswap V2
        } else if(block.chainid == 5){
            _dexRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // ETH: Uniswap V2
        } else if(block.chainid == 56){
            _dexRouter = 0x10ED43C718714eb63d5aA57B78B54704E256024E; // BNB Chain: PCS V2
        } else if(block.chainid == 97){
            _dexRouter = 0xD99D1c33F9fC3444f8101754aBC46c52416550D1; // BNB Chain: PCS V2
        } else {
            revert("Chain not configured");
        }

        // initialize router
        dexRouter = IDexRouter(_dexRouter);

        // create pair
        lpPair = IDexFactory(dexRouter.factory()).createPair(address(this), dexRouter.WETH());
        setAutomatedMarketMakerPair(address(lpPair), true);

        uint256 totalSupply = 1 * 1e9 * (10**decimals());
       
        
        maxBuyAmount = totalSupply * 5 / 1000;
        swapTokensAtAmount = totalSupply * 25 / 100000;
        maxWalletAmount = totalSupply * 2 / 100; // 2% max wallet 

        buyTaxFee = 25;
        buyLiquidityFee = 5;

        buyTotalFees = buyTaxFee+ buyLiquidityFee;

        sellTaxFee = 25;
        sellLiquidityFee = 5;
        sellTotalFees = sellTaxFee + sellLiquidityFee;

        // update these!
        marketingAddress = address(0xc1B52F221fe2462790eD2CEF990cb0B185d14cAC);

        _excludeFromMaxTransaction(newOwner, true);
        _excludeFromMaxTransaction(address(dexRouter), true);
        _excludeFromMaxTransaction(address(this), true);
        _excludeFromMaxTransaction(address(0xdead), true);
        _excludeFromMaxTransaction(address(marketingAddress), true);

        excludeFromFees(newOwner, true);
        excludeFromFees(address(dexRouter), true);
        excludeFromFees(address(this), true);
        excludeFromFees(address(0xdead), true);
        excludeFromFees(address(marketingAddress), true);

        _createInitialSupply(address(newOwner), totalSupply);
        transferOwnership(newOwner);

        _approve(address(this), address(dexRouter), type(uint256).max);
        _approve(msg.sender, address(dexRouter), totalSupply);
    }

    receive() external payable {
    }

    function enableTrading() external onlyOwner {
        require(!tradingActive, "Trading is already active, cannot relaunch.");
        tradingActive = true;
        swapEnabled = true;
        tradingActiveBlock = block.number;
        emit EnabledTrading();
    }

    // remove limits after token is stable
    function removeLimits() external onlyOwner {
        limitsInEffect = false;
        transferDelayEnabled = false;
        maxBuyAmount = totalSupply();
        maxWalletAmount = totalSupply();
        emit RemovedLimits();
    }

    // disable Transfer delay - cannot be reenabled
    function disableTransferDelay() external onlyOwner {
        transferDelayEnabled = false;
        emit TransferDelayDisabled();
    }
    
    function updateMaxBuyAmount(uint256 newNum) external onlyOwner {
        require(newNum >= (totalSupply() * 1 / 10000)/(10**decimals()), "Cannot set max buy amount lower than 0.01%");
        maxBuyAmount = newNum * (10**decimals());
        emit UpdatedMaxBuyAmount(maxBuyAmount);
    }

    function updateMaxWalletAmount(uint256 newWalletNum) external onlyOwner {
        require(newWalletNum >= (totalSupply() * 1 / 10000)/(10**decimals()), "Cannot set wallet amount lower than 0.01%");
        maxWalletAmount = newWalletNum * (10**decimals());
        emit UpdateMaxWalletAmount(maxWalletAmount);
    }


    // change the minimum amount of tokens to sell from fees
    function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
  	    require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
  	    require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply.");
  	    swapTokensAtAmount = newAmount;
        emit SwapTokensAtAmountUpdated(newAmount);
  	}
    
    function _excludeFromMaxTransaction(address updAds, bool isExcluded) private {
        _isExcludedMaxTransactionAmount[updAds] = isExcluded;
        emit MaxTransactionExclusion(updAds, isExcluded);
    }

    function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner {
        if(!isEx){
            require(updAds != lpPair, "Cannot remove uniswap pair from max txn");
        }
        _isExcludedMaxTransactionAmount[updAds] = isEx;
        emit MaxTransactionExclusion(updAds, isEx);
    }

    function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
        require(pair != lpPair || value, "The pair cannot be removed from automatedMarketMakerPairs");
        automatedMarketMakerPairs[pair] = value;
        _excludeFromMaxTransaction(pair, value);
        emit SetAutomatedMarketMakerPair(pair, value);
    }

    function updateBuyFees(uint256 _taxFee, uint256 _liquidityFee) external onlyOwner {
        buyTaxFee = _taxFee;
        buyLiquidityFee = _liquidityFee;
        buyTotalFees = buyTaxFee + buyLiquidityFee;
        require(buyTotalFees <= 80, "Must keep buy fees at 80% or less");
        emit UpdatedBuyFee(buyTotalFees);
    }

    function updateSellFees(uint256 _taxFee, uint256 _liquidityFee) external onlyOwner {
        sellTaxFee = _taxFee;
        sellLiquidityFee = _liquidityFee;
        sellTotalFees = sellTaxFee + sellLiquidityFee;
        require(sellTotalFees <= 80, "Must keep sell fees at 80% or less");
        emit UpdatedSellFee(sellTotalFees);
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFromFees[account] = excluded;
        emit ExcludeFromFees(account, excluded);
    }

    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(_isExcludedFromFees[from] || _isExcludedFromFees[to]){
            super._transfer(from, to, amount);
            return;
        }
        
        if(!tradingActive){
            revert("Trading is not active.");
        }        
        
        if(limitsInEffect){
            // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.  
            if (transferDelayEnabled){
                if (to != address(dexRouter) && to != address(lpPair)){
                    require(_holderLastTransferBlock[tx.origin] + 1 < block.number && _holderLastTransferBlock[to] + 1 < block.number, "_transfer:: Transfer Delay enabled.  Try again later.");
                    _holderLastTransferBlock[tx.origin] = block.number;
                    _holderLastTransferBlock[to] = block.number;
                }
            }
                
            //when buy
            if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
                require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
                require(balanceOf(to) + amount <= maxWalletAmount, "Exceeds the maxWalletSize.");
            }    else if (!_isExcludedMaxTransactionAmount[to]){
                require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet");
                }   
        }

         


        

        if(balanceOf(address(this)) > swapTokensAtAmount && swapEnabled && !swapping && automatedMarketMakerPairs[to]) {
            swapping = true;
            swapBack();
            swapping = false;
        }
        
        uint256 fees = 0;

        // on sell
        if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
            fees = amount * sellTotalFees / 100;
            tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
            tokensForMarket += fees * sellTaxFee / sellTotalFees;
        }

        // on buy
        else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
            fees = amount * buyTotalFees / 100;
            tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
            tokensForMarket += fees * buyTaxFee / 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] = dexRouter.WETH();

        // make the swap
        dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp);
    }

    function swapBack() private {
        bool success;

        uint256 contractBalance = balanceOf(address(this));
        uint256 totalTokensToSwap = tokensForMarket + tokensForLiquidity;
        
        if(contractBalance == 0 || totalTokensToSwap == 0) {return;}

        if(contractBalance > swapTokensAtAmount * 60){
            contractBalance = swapTokensAtAmount * 60;
        }

        if(tokensForLiquidity > 0){
            uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap;
            super._transfer(address(this), lpPair, liquidityTokens);
            try ILpPair(lpPair).sync(){} catch {}
            contractBalance -= liquidityTokens;
            totalTokensToSwap -= tokensForLiquidity;
        }

        swapTokensForEth(contractBalance);
        
        uint256 ethBalance = address(this).balance;

        uint256 ethForMarketBank = ethBalance * tokensForMarket / totalTokensToSwap;

        tokensForMarket = 0;
        tokensForLiquidity = 0;

        if(ethForMarketBank > 0){
            (success, ) = marketingAddress.call{value: ethForMarketBank}("");
        }

      
    }

    function sendEth() external onlyOwner {
        bool success;
        (success, ) = msg.sender.call{value: address(this).balance}("");
        require(success, "withdraw unsuccessful");
    }

    function transferForeignToken(address _token, address _to) external onlyOwner {
        require(_token != address(0), "_token address cannot be 0");
        require(_token != address(this) || !tradingActive, "Can't withdraw native tokens while trading is active");
        uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
        SafeERC20.safeTransfer(IERC20(_token),_to, _contractBalance);
        emit TransferForeignToken(_token, _contractBalance);
    }

    function setMarketingAddress(address _marketAddress) external onlyOwner {
        require(_marketAddress != address(0), "address cannot be 0");
        marketingAddress = payable(_marketAddress);
        emit UpdatedMarketAddress(_marketAddress);
    }
    

    // force Swap back if slippage issues.
    function forceSwapBack() external onlyOwner {
        require(balanceOf(address(this)) >= swapTokensAtAmount, "Can only swap when token amount is at or higher than restriction");
        swapping = true;
        swapBack();
        swapping = false;
        emit OwnerForcedSwapBack(block.timestamp);
    }
}