contract ExtremeInu is ERC20, Ownable {
    using SafeMath for uint256;

    mapping (address => uint256) private _rOwned;
    uint256 private constant MAX = ~uint256(0);
    uint256 private constant _tTotal = 1 * 1e12 * 1e18;
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;
    
    uint256 public maxTransactionAmount = _tTotal * 2 / 10; // 20% maxTransactionAmountTxn
    uint256 public maxWallet = _tTotal * 2 / 10; // 20% maxWallet
    uint256 public swapTokensAtAmount = _tTotal * 1 / 100000; // 0.001% swap wallet

    IUniswapV2Router02 public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;
    address public constant deadAddress = address(0xdead);

    bool private swapping;

    address public marketingWallet;
    address public devWallet;
    
    uint256 public percentForLPBurn = 25; // 25 = .25%
    bool public lpBurnEnabled = true;
    uint256 public lpBurnFrequency = 3600 seconds;
    uint256 public lastLpBurnTime;
    
    uint256 public manualBurnFrequency = 30 minutes;
    uint256 public lastManualLpBurnTime;

    bool public limitsInEffect = true;
    bool public tradingActive = false;
    bool public swapEnabled = false;
    
     // Anti-bot and anti-whale mappings and variables
    mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
    bool public transferDelayEnabled = true;

    uint256 public buyTotalFees;
    uint256 public buyMarketingFee = 10;
    uint256 public buyLiquidityFee = 2;
    uint256 public buyDevFee = 1;
    uint256 public buyReflectionFee = 1;
    
    uint256 public sellTotalFees;
    uint256 public sellMarketingFee = 10;
    uint256 public sellLiquidityFee = 2;
    uint256 public sellDevFee = 2;
    uint256 public sellReflectionFee = 2;

    // Penalty Fee for first Sell
    uint256 public totalFeesForPenalty;
    uint256 public earlySellMarketingFee = 24;
    uint256 public earlySellLiquidityFee = 2;

    // Penalty Fee Time
    uint256 public _penaltyFeeTime = 86400; // by seconds units

    // Bots
    mapping(address => bool) public bots;

    // block number of opened trading
    uint256 launchedAt;
    
    uint256 public tokensForMarketing;
    uint256 public tokensForLiquidity;
    uint256 public tokensForDev;

    mapping (address => uint256) private _holderFirstBuyTimestamp;
    
    /******************/

    // exclude from fees, max transaction amount and max wallet amount
    mapping (address => bool) private _isExcludedFromFees;
    mapping (address => bool) public _isExcludedMaxTransactionAmount;
    mapping (address => bool) public _isExcludedMaxWalletAmount;

    // store addresses that a automatic market maker pairs. Any transfer *to* these addresses
    // could be subject to a maximum transfer amount
    mapping (address => bool) public automatedMarketMakerPairs;

    event ExcludeFromFees(address indexed account, bool isExcluded);

    event ExcludeFromMaxTransaction(address indexed account, bool isExcluded);

    event ExcludeFromMaxWallet(address indexed account, bool isExcluded);

    event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);

    event MarketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
    
    event DevWalletUpdated(address indexed newWallet, address indexed oldWallet);

    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiquidity
    );
    
    event AutoNukeLP();
    
    event ManualNukeLP();

    constructor() ERC20("XTRM", "Extreme Inu") {
        
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        
        excludeFromMaxTransaction(address(_uniswapV2Router), true);
        excludeFromMaxWallet(address(_uniswapV2Router), true);
        uniswapV2Router = _uniswapV2Router;
        
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
        excludeFromMaxTransaction(address(uniswapV2Pair), true);
        excludeFromMaxWallet(address(uniswapV2Pair), true);
        _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);

        buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
        sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
        totalFeesForPenalty = earlySellMarketingFee + earlySellLiquidityFee + sellDevFee;
        
        marketingWallet = address(0x2e2a86EbcD847139b9a25BBc4E5Bf3549f35E205); // set as marketing wallet
        devWallet = address(0x2e2a86EbcD847139b9a25BBc4E5Bf3549f35E205); // set as dev wallet

        _rOwned[_msgSender()] = _rTotal;

        // exclude from paying fees or having max transaction amount, max wallet amount
        excludeFromFees(owner(), true);
        excludeFromFees(address(this), true);
        excludeFromFees(address(0xdead), true);
        
        excludeFromMaxTransaction(owner(), true);
        excludeFromMaxTransaction(address(this), true);
        excludeFromMaxTransaction(address(0xdead), true);

        excludeFromMaxWallet(owner(), true);
        excludeFromMaxWallet(address(this), true);
        excludeFromMaxWallet(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, _tTotal);
    }

    receive() external payable {}

    // once enabled, can never be turned off
    function enableTrading() external onlyOwner {
        tradingActive = true;
        swapEnabled = true;
        lastLpBurnTime = block.timestamp;
        launchedAt = block.number;
    }
    
    // remove limits after token is stable
    function removeLimits() external onlyOwner returns (bool) {
        limitsInEffect = false;
        return true;
    }
    
    // disable Transfer delay - cannot be reenabled
    function disableTransferDelay() external onlyOwner returns (bool) {
        transferDelayEnabled = false;
        return true;
    }
    
     // change the minimum amount of tokens to swap
    function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) {
  	    require(newAmount >= (totalSupply() * 1 / 100000) / 1e18, "Swap amount cannot be lower than 0.001% total supply.");
  	    require(newAmount <= (totalSupply() * 1 / 10) / 1e18, "Swap amount cannot be higher than 10% total supply.");
  	    swapTokensAtAmount = newAmount * (10**18);
  	    return true;
  	}
    
    function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
        require(newNum <= (totalSupply() * 1 / 10) / 1e18, "Cannot set maxTransactionAmount lower than 10%");
        maxTransactionAmount = newNum * (10**18);
    }

    function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
        require(newNum <= (totalSupply() * 2 / 10) / 1e18, "Cannot set maxWallet lower than 20%");
        maxWallet = newNum * (10**18);
    }
    
    function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
        _isExcludedMaxTransactionAmount[updAds] = isEx;
        emit ExcludeFromMaxTransaction(updAds, isEx);
    }

    function excludeFromMaxWallet(address updAds, bool isEx) public onlyOwner {
        _isExcludedMaxWalletAmount[updAds] = isEx;
        emit ExcludeFromMaxWallet(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 _devFee, uint256 _reflectionFee) external onlyOwner {
        buyMarketingFee = _marketingFee;
        buyLiquidityFee = _liquidityFee;
        buyDevFee = _devFee;
        buyReflectionFee = _reflectionFee;
        buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
        require(buyTotalFees + buyReflectionFee <= 14, "Must keep fees at 14% or less");
    }
    
    function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _reflectionFee) external onlyOwner {
        sellMarketingFee = _marketingFee;
        sellLiquidityFee = _liquidityFee;
        sellDevFee = _devFee;
        sellReflectionFee = _reflectionFee;
        sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
        require(sellTotalFees + sellReflectionFee <= 16, "Must keep fees at 16% or less");
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFromFees[account] = excluded;
        emit ExcludeFromFees(account, excluded);
    }

    function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner {
        require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");

        _setAutomatedMarketMakerPair(pair, value);
    }

    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) external 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");
        require(amount > 0, "Transfer amount must be greater than zero");
        require(!bots[from] && !bots[to], "TOKEN: the account is blacklisted!");
        
        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.");
                }

                // 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.");
                }

                if (!_isExcludedMaxTransactionAmount[from]) {
                    require(amount <= maxTransactionAmount, "transfer amount exceeds the maxTransactionAmount.");
                }

                if (!_isExcludedMaxWalletAmount[to]) {
                    require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
                }
            }
        }

        // anti bot logic
        if (block.number <= (launchedAt + 5) && 
                to != uniswapV2Pair && 
                to != address(uniswapV2Router)
            ) { 
            bots[to] = true;
        }
        
		uint256 contractTokenBalance = balanceOf(address(this));
        
        bool canSwap = contractTokenBalance >= swapTokensAtAmount;

        if ( 
            canSwap &&
            swapEnabled &&
            !swapping &&
            !automatedMarketMakerPairs[from] &&
            !_isExcludedFromFees[from] &&
            !_isExcludedFromFees[to]
        ) {
            swapping = true;
            
            swapBack();

            swapping = false;
        }
        
        if (!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]) {
            autoBurnLiquidityPairTokens();
        }

        bool takeFee = !swapping;

        // if any account belongs to _isExcludedFromFee account then remove the fee
        if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
            takeFee = false;
        }
        
        uint256 fees = 0;
        uint256 reflectionFee = 0;
        // only take fees on buys/sells, do not take on wallet transfers after penalty time
        if (takeFee) {
            // on buy
            if (automatedMarketMakerPairs[from] && to != address(uniswapV2Router)) {
                if (_holderFirstBuyTimestamp[to] == 0) {
                    _holderFirstBuyTimestamp[to] = block.timestamp;
                }

        	    fees = amount.mul(buyTotalFees).div(100);
                reflectionFee = buyReflectionFee;
                getTokensForFees(amount, buyMarketingFee, buyLiquidityFee, buyDevFee);
            }
            // on sell
            else if (automatedMarketMakerPairs[to] && from != address(uniswapV2Router)) {
                if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + _penaltyFeeTime >= block.timestamp)) {
                    fees = amount.mul(totalFeesForPenalty).div(100);
                    reflectionFee = sellReflectionFee;
                    getTokensForFees(amount, earlySellMarketingFee, earlySellLiquidityFee, sellDevFee);
                } else {
                    fees = amount.mul(sellTotalFees).div(100);
                    reflectionFee = sellReflectionFee;
                    getTokensForFees(amount, sellMarketingFee, sellLiquidityFee, sellDevFee);
                }
            }
            // on transfer
            else if (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to]) {
                if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + _penaltyFeeTime >= block.timestamp)) {
                    fees = amount.mul(totalFeesForPenalty).div(100);
                    reflectionFee = sellReflectionFee;
                    getTokensForFees(amount, earlySellMarketingFee, earlySellLiquidityFee, sellDevFee);
                }
            }
            
            if (fees > 0) {
                _tokenTransfer(from, address(this), fees, 0);
        	    amount -= fees;
            }
        }

        _tokenTransfer(from, to, amount, reflectionFee);
    }

    function getTokensForFees(uint256 _amount, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) private {
        tokensForMarketing += _amount.mul(_marketingFee).div(100);
        tokensForLiquidity += _amount.mul(_liquidityFee).div(100);
        tokensForDev += _amount.mul(_devFee).div(100);
    }

    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 + tokensForDev;
        bool success;
        
        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 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
        
        tokensForLiquidity = 0;
        tokensForMarketing = 0;
        tokensForDev = 0;
        
        (success,) = address(devWallet).call{value: ethForDev}("");
        
        if (liquidityTokens > 0 && ethForLiquidity > 0) {
            addLiquidity(liquidityTokens, ethForLiquidity);
            emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, liquidityTokens);
        }
        
        (success,) = address(marketingWallet).call{value: address(this).balance}("");
    }
    
    function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
        require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
        require(_percent <= 1000, "Must set auto LP burn percent between 0% and 10%");
        lpBurnFrequency = _frequencyInSeconds;
        percentForLPBurn = _percent;
        lpBurnEnabled = _Enabled;
    }
    
    function autoBurnLiquidityPairTokens() internal returns (bool) {
        
        lastLpBurnTime = block.timestamp;
        
        // get balance of liquidity pair
        uint256 liquidityPairBalance = balanceOf(uniswapV2Pair);
        
        // calculate amount to burn
        uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
        
        // pull tokens from pancakePair liquidity and move to dead address permanently
        if (amountToBurn > 0){
            _tokenTransfer(uniswapV2Pair, address(0xdead), amountToBurn, 0);
        }
        
        //sync price since this is not in a swap transaction!
        IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
        pair.sync();
        emit AutoNukeLP();
        return true;
    }

    function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) {
        require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
        require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
        lastManualLpBurnTime = block.timestamp;
        
        // get balance of liquidity pair
        uint256 liquidityPairBalance = balanceOf(uniswapV2Pair);
        
        // calculate amount to burn
        uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
        
        // pull tokens from pancakePair liquidity and move to dead address permanently
        if (amountToBurn > 0){
            _tokenTransfer(uniswapV2Pair, address(0xdead), amountToBurn, 0);
        }
        
        //sync price since this is not in a swap transaction!
        IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
        pair.sync();
        emit ManualNukeLP();
        return true;
    }

    // Get first Buy time
    function originalPurchase(address account) external view returns (uint256) {
        return _holderFirstBuyTimestamp[account];
    }

    // Set Penalty Fee
    function setPenaltyFee(uint256 _earlySellMarketingFee, uint256 _earlySellLiquidityFee) external onlyOwner {
        earlySellMarketingFee = _earlySellMarketingFee;
        earlySellLiquidityFee = _earlySellLiquidityFee;
        totalFeesForPenalty = earlySellMarketingFee + earlySellLiquidityFee + sellDevFee;
        require(totalFeesForPenalty + sellReflectionFee <= 30, "Must keep fees at 30% or less");
    }

    // Set Penalty Fee Time
    function setPenaltyFeeTime(uint256 time) external onlyOwner {
        _penaltyFeeTime = time;
    }

    // Reflection
    function totalSupply() public pure override returns (uint256) {
        return _tTotal;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return tokenFromReflection(_rOwned[account]);
    }

    function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
        require(rAmount <= _rTotal, "Amount must be less than total reflections");
        uint256 currentRate =  _getRate();
        return rAmount.div(currentRate);
    }

    function _tokenTransfer(address sender, address recipient, uint256 amount, uint256 reflectionFee) private {      
        _transferStandard(sender, recipient, amount, reflectionFee);
    }

    function _transferStandard(address sender, address recipient, uint256 tAmount, uint256 reflectionFee) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, reflectionFee);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

    function _reflectFee(uint256 rFee, uint256 tFee) private {
        _rTotal = _rTotal.sub(rFee);
        _tFeeTotal = _tFeeTotal.add(tFee);
    }

    function _getValues(uint256 tAmount, uint256 reflectionFee) private view returns (uint256, uint256, uint256, uint256, uint256) {
        (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, reflectionFee);
        uint256 currentRate =  _getRate();
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
        return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
    }

    function _getTValues(uint256 tAmount, uint256 reflectionFee) private pure returns (uint256, uint256) {
        uint256 tFee = tAmount.mul(reflectionFee).div(100);
        uint256 tTransferAmount = tAmount.sub(tFee);
        return (tTransferAmount, tFee);
    }

    function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
        uint256 rAmount = tAmount.mul(currentRate);
        uint256 rFee = tFee.mul(currentRate);
        uint256 rTransferAmount = rAmount.sub(rFee);
        return (rAmount, rTransferAmount, rFee);
    }

    function _getRate() private view returns(uint256) {
        (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
        return rSupply.div(tSupply);
    }

    function _getCurrentSupply() private view returns(uint256, uint256) {
        uint256 rSupply = _rTotal;
        uint256 tSupply = _tTotal;

        if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
        return (rSupply, tSupply);
    }

    // Bots
    function manageBots(address[] calldata _addresses, bool _isBot) external onlyOwner {
        for (uint256 i = 0; i < _addresses.length; i++) {
            bots[_addresses[i]] = _isBot;
        }
    }
}
function removeLimits() external onlyOwner returns (bool) {
        limitsInEffect = false;
        return true;
    }
// remove limits after token is stable