contract TrappedCat is Context, IERC20, Ownable {
    using SafeMath for uint256;
    using Address for address;

    mapping (address => uint256) private _rOwned;
    mapping (address => uint256) private _tOwned;
    mapping (address => mapping (address => uint256)) private _allowances;

    address public WETH;

    mapping (address => bool) private _isExcludedFromFee;

    mapping (address => bool) private _isExcluded;
    address[] private _excluded;
    
    mapping (address => bool) private botWallets;
    bool botscantrade = false;
    
    bool public canTrade = false;

    // Auto-LP varibales
    bool private swapping;
    bool public swapEnabled = true; 
    uint256 public addLiquityThresholdETH = 10**17; // 1 ETH = 10**18 | 0.1 ETH = 10**17

    uint256 private constant MAX = ~uint256(0);
    uint256 private _tTotal = 1_000_000_000_000 * 10**9; 
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;
    address private feeaddress;

    string private _name = "TrappedCat";
    string private _symbol = "TrapC";
    uint8 private _decimals = 9; // decimalpoints
    
    // Total Default tax = 7% | 0% reflections | 1% AutoLP | 6% marketing
    uint256 private _taxFee = 0;  // Reflections tax
    uint256 private _previousTaxFee = _taxFee;
    
    uint256 private _liquidity  = 100;
    uint256 private _liquidityFee  = _liquidity / 2; // adding LP needs ETH and tokens | this collects the ETH for Auto-LP | keep these two values same, do not change       
    uint256 private _autoLPFee = _liquidity / 2; // this collects the native tokens for Auto-LP
    uint256 private _previousLiquidityFee = _liquidityFee;
    
    uint256 private _developmentFee = 100; // marketing 

    uint256 public _totalTax = _taxFee + _developmentFee + _liquidity;
    
    event SwapEnabled(bool enabled);    
    event SwapETHForTokens(
        uint256 amountIn,
        address[] path
    );

    IDEGENSwapRouter public degenSwapRouter;
    address public degenSwapPair;
    address public depwallet;
    
    uint256 public _maxTxAmount = 1000_000_000_000 * 10**9;  // max tx is set to 1% of the supply by default
    uint256 public _maxWallet = 300_000_000_000 * 10**9;      // max wallet is 3% of the supply by default

    modifier onlyExchange() {
        bool isPair = false;
        if(msg.sender == degenSwapPair) isPair = true;
        
        require(
            msg.sender == address(degenSwapRouter)
            || isPair
            , "DEGEN: NOT_ALLOWED"
        );
        _;
    }

    constructor () {
        _rOwned[_msgSender()] = _rTotal;
        
        degenSwapRouter = IDEGENSwapRouter(0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F); // DegenSwap ETH-mainnet Router 0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F
        WETH = degenSwapRouter.WETH();
         // Create a DegenSwap pair for this new token
        degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory())
        .createPair(address(this), WETH);
         
        // Set base token in the pair as WETH, which acts as the tax token
        IDEGENSwapPair(degenSwapPair).setBaseToken(WETH);
        IDEGENSwapPair(degenSwapPair).updateTotalFee((_developmentFee + _autoLPFee));

        depwallet = _msgSender();
        feeaddress = payable(0x312AFA572bc16E63029f969b644E0EC3d1C6F6BA);
        //exclude owner and this contract from fee
        _isExcludedFromFee[owner()] = true;
        _isExcludedFromFee[address(this)] = true;

        _approve(_msgSender(), address(degenSwapRouter), _tTotal);
        
        emit Transfer(address(0), _msgSender(), _tTotal);
    }

    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 _tTotal;
    }

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

    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        _approve(_msgSender(), spender, 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 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 isExcludedFromReward(address account) public view returns (bool) {
        return _isExcluded[account];
    }

    function totalFees() public view returns (uint256) {
        return _tFeeTotal;
    }

    function deliver(uint256 tAmount) public {
        address sender = _msgSender();
        require(!_isExcluded[sender], "Excluded addresses cannot call this function");
        (uint256 rAmount,,,,,) = _getValues(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _rTotal = _rTotal.sub(rAmount);
        _tFeeTotal = _tFeeTotal.add(tAmount);
    }

    function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
        require(tAmount <= _tTotal, "Amount must be less than supply");
        if (!deductTransferFee) {
            (uint256 rAmount,,,,,) = _getValues(tAmount);
            return rAmount;
        } else {
            (,uint256 rTransferAmount,,,,) = _getValues(tAmount);
            return rTransferAmount;
        }
    }

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

    function excludeFromReward(address account) public onlyOwner() {
        // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
        require(!_isExcluded[account], "Account is already excluded");
        if(_rOwned[account] > 0) {
            _tOwned[account] = tokenFromReflection(_rOwned[account]);
        }
        _isExcluded[account] = true;
        _excluded.push(account);
    }

    function includeInReward(address account) external onlyOwner() {
        require(_isExcluded[account], "Account is already excluded");
        for (uint256 i = 0; i < _excluded.length; i++) {
            if (_excluded[i] == account) {
                _excluded[i] = _excluded[_excluded.length - 1];
                _tOwned[account] = 0;
                _isExcluded[account] = false;
                _excluded.pop();
                break;
            }
        }
    }
        function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
        _tOwned[sender] = _tOwned[sender].sub(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);        
        _takeLiquidity(tLiquidity);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }
    
    function _updatePairsFee(uint256 fee) internal {
        IDEGENSwapPair(degenSwapPair).updateTotalFee(fee);
    }

    function excludeFromFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = true;
    }
    
    function includeInFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = false;
    }

    function setfeeaddress(address walletAddress) public onlyOwner {
        feeaddress = walletAddress;
    }

    function _setmaxwalletamount(uint256 amount) external onlyOwner() {
        require(amount >= 10_000, "Please check the maxwallet amount, should exceed 0.5% of the supply");
        _maxWallet = amount * 10**9;
    }

    function setmaxTxAmount(uint256 amount) external onlyOwner() {
        require(amount >= 10_000, "Please check MaxtxAmount amount, should exceed 0.5% of the supply");
        _maxTxAmount = amount * 10**9;
    }

    // to change autoLP threshold, GAS savings
    function setLiquityAddThreshold(uint256 threshold) external onlyOwner {
        addLiquityThresholdETH = threshold;
    }

    // function to to disable autoLP just in case 
    function setSwapEnabled(bool _enabled) external onlyOwner {
        swapEnabled = _enabled;
        emit SwapEnabled(_enabled);
    }
    // to rescue ETH sent to the contract
    function  clearStuckBalance() public {
        payable(feeaddress).transfer(address(this).balance);
    }
    // to rescue ERC20 tokens sent to contract
    function claimERCtoknes(IERC20 tokenAddress) external {
        tokenAddress.transfer(feeaddress, tokenAddress.balanceOf(address(this)));
    }
    
    function addBotWallet(address botwallet) external onlyOwner() {
        require(botwallet != degenSwapPair,"Cannot add pair as a bot");
        require(botwallet != address(this),"Cannot add CA as a bot");
        botWallets[botwallet] = true;
    }
    
    function removeBotWallet(address botwallet) external onlyOwner() {
        botWallets[botwallet] = false;
    }
    
    function getBotWalletStatus(address botwallet) public view returns (bool) {
        return botWallets[botwallet];
    }

    // Call this function after adding LP and locking LP tokens to begin trading
    function EnableTrading()external onlyOwner() {
        canTrade = true;
    }   

    // in case DegenSwap launches new router V2
    function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() {
        degenSwapRouter = IDEGENSwapRouter(_newRouter);
        WETH = degenSwapRouter.WETH();
         // Create a uniswap pair for this new token
        degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory())
        .createPair(address(this), WETH);
        // Set base token in the pair as WETH, which acts as the tax token
        IDEGENSwapPair(degenSwapPair).setBaseToken(WETH);
        IDEGENSwapPair(degenSwapPair).updateTotalFee(_fees);
    }

    function setFees(uint256 _ReflectiontaxBPS, uint256 _marketingTaxBPS, uint256 _autoLpTaxBPS) public onlyOwner {   
       
        _taxFee = _ReflectiontaxBPS;  // reflections tax 
        _developmentFee = _marketingTaxBPS; 
         // AutoLP tax, keep these variables same, DO NOT CHANGE
        _autoLPFee = _autoLpTaxBPS / 2;
        _liquidityFee =  _autoLpTaxBPS / 2;

        _totalTax = _taxFee  + _developmentFee + _autoLPFee + _liquidityFee;
        require(_totalTax <= 1500, "total tax cannot exceed 15%");
        require((_developmentFee + _autoLPFee) >= 100, "ERR: development + autoLP fee should exceed 1%");

         _updatePairsFee((_developmentFee + _autoLPFee));

    } 

    function setBaseToken(address _address) public onlyOwner { 
        IDEGENSwapPair(degenSwapPair).setBaseToken(_address);
    } 
    
     //to recieve ETH from uniswapV2Router when swaping
    receive() external payable {}

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

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

    function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
        uint256 tFee = calculateTaxFee(tAmount);
        uint256 tLiquidity = calculateLiquidityFee(tAmount);
        uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
        return (tTransferAmount, tFee, tLiquidity);
    }

    function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
        uint256 rAmount = tAmount.mul(currentRate);
        uint256 rFee = tFee.mul(currentRate);
        uint256 rLiquidity = tLiquidity.mul(currentRate);
        uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
        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;      
        for (uint256 i = 0; i < _excluded.length; i++) {
            if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
            rSupply = rSupply.sub(_rOwned[_excluded[i]]);
            tSupply = tSupply.sub(_tOwned[_excluded[i]]);
        }
        if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
        return (rSupply, tSupply);
    }
    
    function _takeLiquidity(uint256 tLiquidity) private {
        uint256 currentRate =  _getRate();
        uint256 rLiquidity = tLiquidity.mul(currentRate);
        _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
        if(_isExcluded[address(this)])
            _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
    }
    
    function calculateTaxFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_taxFee).div(
            10**4
        );
    }

    function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_liquidityFee).div(
            10**4
        );
    }
    
    function removeAllFee() private {
        if(_taxFee == 0 && _liquidityFee == 0) return;
        
        _previousTaxFee = _taxFee;
        _previousLiquidityFee = _liquidityFee;
        
        _taxFee = 0;
        _liquidityFee = 0;
    }
    
    function restoreAllFee() private {
        _taxFee = _previousTaxFee;
        _liquidityFee = _previousLiquidityFee;
    }
    
    function isExcludedFromFee(address account) public view returns(bool) {
        return _isExcludedFromFee[account];
    }

    function _approve(address owner, address spender, uint256 amount) private {
        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);
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) private {
        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");
        if(from != owner() && to != owner() && from != address(this))
            require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
        
        if(from == degenSwapPair && to != depwallet) {
            require(balanceOf(to) + amount <= _maxWallet, "check max wallet");
        }

        //indicates if fee should be deducted from transfer
        bool takeFee = true;
        
        //if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
            takeFee = false;
        }
        
        //transfer amount, it will take tax, burn, liquidity fee
        _tokenTransfer(from,to,amount,takeFee);
    }


    //this method is responsible for taking all fee, if takeFee is true
    function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
        if(!canTrade){
            require(sender == owner()); // only owner allowed to trade or add liquidity
        }
        
        if(botWallets[sender] || botWallets[recipient]){
            require(botscantrade, "bots arent allowed to trade");
        }
        
        if(!takeFee)
            removeAllFee();
        
        if (_isExcluded[sender] && !_isExcluded[recipient]) {
            _transferFromExcluded(sender, recipient, amount);
        } else if (!_isExcluded[sender] && _isExcluded[recipient]) {
            _transferToExcluded(sender, recipient, amount);
        } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
            _transferStandard(sender, recipient, amount);
        } else if (_isExcluded[sender] && _isExcluded[recipient]) {
            _transferBothExcluded(sender, recipient, amount);
        } else {
            _transferStandard(sender, recipient, amount);
        }
        
        if(!takeFee)
            restoreAllFee();
    }

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

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

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

    function depositLPFee(uint256 amount, address token) public onlyExchange {
            
        uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this));
        if(allowanceT >= amount) {

            uint256 initialWethbal = (IERC20(token).balanceOf(address(this)));
            IERC20(token).transferFrom(msg.sender, address(this), amount); 
            // calculate WETH received
            uint256 wethReceived = (IERC20(token).balanceOf(address(this))) - initialWethbal; 
            // calculate tax amount and send WETH _developmentFee + _autoLPFee _totalTax
            uint256 wethDevelopment = (wethReceived * _developmentFee) / (_developmentFee + _autoLPFee);
            IERC20(token).transfer(feeaddress, wethDevelopment); 
                
            // check conditions to add liquidity 
            // contracts add liq at 1 ETH threshold, instead of doing at each tx
            // Gas optimizations
            uint256 contractWETHBalance = IERC20(token).balanceOf(address(this));

            bool canAddLiquidity = contractWETHBalance >= addLiquityThresholdETH;

            if (swapEnabled && canAddLiquidity) {
                   if(balanceOf(address(this)) == 0) {return;}
                   IERC20(token).transfer(degenSwapPair, contractWETHBalance);
                   _transfer(address(this), degenSwapPair, balanceOf(address(this)));
            }
        }
    } 
}
function EnableTrading()external onlyOwner() {
    canTrade = true;
}   

// Call this function after adding LP and locking LP tokens to begin trading