Not reseting after 3 transactions

pls im having issues trying to make my contract reset the transaction count to 0 and sending fees to my wallet
so basicall i want my contract to swap and send fee to my wallet after 3 transactions and reset the count to zero but it keeps counting beyond 3 and the swapback function is not called.

bool canSwap = txCount == swapTrigger;
    if(canSwap && from != uniswapV2Pair && swapEnabled){
        txCount = 0;
        swapBack();
    }

      bool takeFee = true;
      bool isBuy;

    if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){
       takeFee = false;
    }else{
        if(from == uniswapV2Pair){
            isBuy = true;
        }
        txCount ++;
    } 
      _transferTokens(from, to, amount, takeFee, isBuy);
      emit Transfer(from, to, amount);
   }

so this is the full code below

// SPDX-License-Identifier: MIT
  pragma solidity 0.8.0;

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

    abstract 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);
        }
        
        modifier onlyOwner() {
        require(_owner == msg.sender, "Not Owner");
        _;
        }

        /**
        * @dev Returns the address of the current owner.
        */
        function owner() public view virtual 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), "Invalid address");
            _transferOwnership(newOwner);
        }

        /**
        * @dev Transfers ownership of the contract to a new account (`newOwner`).
        * Internal function without access restriction.
        */
        function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }

library SafeMath {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }
}

    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 IUniswapV2Factory {
        event PairCreated(address indexed token0, address indexed token1, address pair, uint);
        function feeTo() external view returns (address);
        function feeToSetter() external view returns (address);
        function getPair(address tokenA, address tokenB) external view returns (address pair);
        function allPairs(uint) external view returns (address pair);
        function allPairsLength() external view returns (uint);
        function createPair(address tokenA, address tokenB) external returns (address pair);
        function setFeeTo(address) external;
        function setFeeToSetter(address) external;
    }
    interface IUniswapV2Pair {
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
        function name() external pure returns (string memory);
        function symbol() external pure returns (string memory);
        function decimals() external pure returns (uint8);
        function totalSupply() external view returns (uint);
        function balanceOf(address owner) external view returns (uint);
        function allowance(address owner, address spender) external view returns (uint);
        function approve(address spender, uint value) external returns (bool);
        function transfer(address to, uint value) external returns (bool);
        function transferFrom(address from, address to, uint value) external returns (bool);
        function DOMAIN_SEPARATOR() external view returns (bytes32);
        function PERMIT_TYPEHASH() external pure returns (bytes32);
        function nonces(address owner) external view returns (uint);
        function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
        event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
        event Swap(
            address indexed sender,
            uint amount0In,
            uint amount1In,
            uint amount0Out,
            uint amount1Out,
            address indexed to
        );
        event Sync(uint112 reserve0, uint112 reserve1);
        function MINIMUM_LIQUIDITY() external pure returns (uint);
        function factory() external view returns (address);
        function token0() external view returns (address);
        function token1() external view returns (address);
        function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
        function price0CumulativeLast() external view returns (uint);
        function price1CumulativeLast() external view returns (uint);
        function kLast() external view returns (uint);
        function burn(address to) external returns (uint amount0, uint amount1);
        function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
        function skim(address to) external;
        function sync() external;
        function initialize(address, address) external;
    }
    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 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 Auto is Context, Ownable, IERC20{

   using SafeMath for uint256;

   address payable taxVault = payable(0x2989EE486770365a53E71A3c17f9A476b456e915);
   address public uniswapV2Pair;
   IUniswapV2Router02 public uniswapV2Router;

   string constant private _name = "My Auto";
   string constant private _symbol = "MAU";
     
    //supply

   uint8 constant private _decimals = 9;
   uint256 constant private _totalSupply = 1000000 * 10**_decimals;
   uint256 public maxTransaction = _totalSupply * 1000/1000; // // 1% = 10, 10% = 100, 100% = 1000  of totalSupply; 
   uint256 public maxTransfer = _totalSupply * 1000/1000; // // 1% = 10, 10% = 100, 100% = 1000  of totalSupply; 

    //for buys

   uint256 public buyFee = 5;
   uint256 public sellFee = 5;
   uint256 public percentLiquidity = 50;
   uint256 public percentMarketing = 50;
   uint256 public tokensForLiquidity;
   uint256 public tokensForMarketing;
   
   uint256 public swapTrigger = 3;
   uint256 public txCount = 0;

   bool inSwapAndLiquify;
   bool swapEnabled = true;

   modifier lockSwap{
    require(!inSwapAndLiquify);

    inSwapAndLiquify = true;
    _;
    inSwapAndLiquify = false;
   }
                      //MAPPINGS
   mapping(address => uint256) private _balanceOf;
   mapping(address => mapping(address => uint256)) private _allowances;
   mapping(address => bool) private _isExcludedFromFees;
   mapping(address => bool) private _isExcludedFromMaxTransactions;
   mapping(address => bool) private _isBot;

                      //EVENTS
    event Excluded(
        address indexed account,
        bool state
    );

    event feesUpdated(
        uint256 newBuyFee,
        uint256 newSellFee
    );

   constructor(){
    _balanceOf[owner()] = _totalSupply;
    emit Transfer(address(0), owner(), _totalSupply);
    uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);
    uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
    .createPair(address(this), uniswapV2Router.WETH());
     _isExcludedFromFees[owner()] = true;
     _isExcludedFromFees[address(this)] = true;
     _isExcludedFromFees[address(0)] = true;

     _isExcludedFromMaxTransactions[owner()] = true;
     _isExcludedFromMaxTransactions[address(this)] = true;
     _isExcludedFromMaxTransactions[address(0)] = true;
   }

    function name() public pure returns(string memory){
      return _name;
    }

    function symbol() public pure returns(string memory){
      return _symbol;
    }

    function decimals() public pure returns(uint8){
      return _decimals;
    }

    function totalSupply() public pure override  returns (uint256){
       return _totalSupply;
    }

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

    function excludeFromFee(address account, bool state) external onlyOwner returns(bool){
        _isExcludedFromFees[account] = state;
        emit Excluded(account, state);
        return true;
    }

    function excludeFromMaxTransaction(address account, bool state) external onlyOwner returns(bool){
        _isExcludedFromMaxTransactions[account] = state;
         emit Excluded(account, state);
        return true;
    }

    function updateMaxTransaction(uint256 _perc) external onlyOwner returns(bool){
      // 1% = 10, 10% = 100, 100% = 1000 
      require(_perc >= 10 && _perc <= 1000, "Must be within the range of 1% to 100%");
      maxTransaction = _totalSupply .mul(_perc).div(1000);
      return true;
   }
    function updateMaxTransfer(uint256 _perc) external onlyOwner returns(bool){
      // 1% = 10, 10% = 100, 100% = 1000 
      require(_perc >= 10 && _perc <= 1000, "Must be within the range of 1% to 100%");
      maxTransfer = _totalSupply .mul(_perc).div(1000);
      return true;
   }

    function antiBot(address account, bool state) external onlyOwner returns(bool){
        _isBot[account] = state;
        return true;
    }

    function bulkAntiBot(address[] memory account, bool state) external onlyOwner returns(bool){
       for(uint256 i; i < account.length; i ++){
         _isBot[account[i]] = state;
       }
        return true;
    }

    function enableSwap(bool state) external onlyOwner returns(bool){
        swapEnabled = state;
        return true;
    }

   function transfer(address to, uint256 amount) public override returns(bool){
       require(_balanceOf[msg.sender] >= amount, "Insufficient balance");
          _transfer(msg.sender, to, amount);
          return true;
   }

   function _transfer(address from, address to, uint256 amount) private lockSwap{
    if(
        to != owner() && //if receiver is owner skip the code inside the if statement, if its any other address apart from the owner run the code
        to != uniswapV2Pair && //if receiver is uniswapV2Pair skip the code inside the if statement, if its any other address apart from the uniwapV2Pair run the code
        to != address(this) && //if receiver is the contract skip the code inside the if statement, if its any other address apart from the contract address run the code
        from != owner() //if sender is owner skip the code inside the if statement, if its any other address apart from the owner run the code
    ){
        uint256 heldToken = balanceOf(to);
        require(heldToken.add(amount) <= maxTransfer, "Over wallet limits");
    }

    if(from != owner()){
        require(amount <= maxTransaction, "Over transaction Limit");
        require(amount > 0, "Invalid amount");
        require(!_isBot[from] && !_isBot[to], "Youre a bot!!");
        require(to != address(0) && from != address(0), "Cannot send to a dead address");
    }

    bool canSwap = txCount == swapTrigger;
    if(canSwap && from != uniswapV2Pair && swapEnabled){
        txCount = 0;
        swapBack();
    }

      bool takeFee = true;
      bool isBuy;

    if(_isExcludedFromFees[from] || _isExcludedFromFees[to]){
       takeFee = false;
    }else{
        if(from == uniswapV2Pair){
            isBuy = true;
        }
        txCount ++;
    } 
      _transferTokens(from, to, amount, takeFee, isBuy);
      emit Transfer(from, to, amount);
   }

    function _sendToWallet(uint256 _amount) private{
        payable(taxVault).transfer(_amount);
    }

  function _transferTokens(address from, address to, uint256 amount, bool takeFee, bool isBuy) private{
      if(!takeFee){
          _balanceOf[from] = _balanceOf[from].sub(amount);
          _balanceOf[to] = _balanceOf[to].add(amount);
          emit Transfer(from, to, amount);
      }else if(isBuy){
        // Transfer from UniswapV2 pair (buy)
            uint256 bTotalFees;
            bTotalFees += amount.mul(buyFee).div(100);
            tokensForLiquidity += bTotalFees * percentLiquidity/100;
            tokensForMarketing += bTotalFees * percentMarketing/100;
            uint256 bTransferAmount = amount - bTotalFees;
        _balanceOf[from] -= amount;
        _balanceOf[to] += bTransferAmount;
        _balanceOf[address(this)] += bTotalFees;
        emit Transfer(from, to, bTransferAmount);
        }else {
        // Transfer to UniswapV2 pair (sell)
            uint256 sTotalFees;
            sTotalFees += amount.mul(sellFee).div(100);
            tokensForLiquidity += sTotalFees * percentLiquidity/100;
            tokensForMarketing += sTotalFees * percentMarketing/100;
            uint256 sTransferAmount = amount - sTotalFees;
        _balanceOf[from] -= amount;
        _balanceOf[to] += sTransferAmount;
        _balanceOf[address(this)] += sTotalFees;
        emit Transfer(from, to, sTransferAmount);
        }
      
  }

  function swapBack() private  {
     uint256 contractTokenBalance = balanceOf(address(this));
        if(contractTokenBalance > 0){
           _swapTokensForEth(contractTokenBalance);
        }
        uint256 contractEthBalance = address(this).balance;
        if(contractTokenBalance > 0){
           _sendToWallet(contractEthBalance);
        }
        tokensForLiquidity = 0;
        tokensForMarketing = 0;
  }

   function transferFrom(address from, address to, uint256 amount) public override  returns (bool){
    require(_allowances[from][msg.sender] >= amount, "Insufficient allowance");
    require(_balanceOf[from] >= amount, "Insufficient balance");
     _transfer(from, to, amount);
     _approve(from, msg.sender, _allowances[from][msg.sender].sub(amount));
    return true;
   }

   function approve(address spender, uint256 amount) public override  returns(bool){
      _approve(msg.sender, spender, amount);
      return true;
   }
   function _approve(address theOwner, address theSpender, uint256 amount) private{
      _allowances[theOwner][theSpender] = amount;
      emit Approval(theOwner, theSpender, amount);
   }
   function allowance(address theOwner, address spender) public view override  returns (uint256){
       return _allowances[theOwner][spender];
   }

   function _swapTokensForEth(uint256 _amount) private returns(bool) {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = uniswapV2Router.WETH();

        _approve(address(this), address(uniswapV2Router), _amount);

        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            _amount,
            0,
            path,
            address(this),
            block.timestamp
        );
        return true;
    }

     function _addLiquidity(uint256 _amount, uint256 _ethAmount) private {
        _approve(address(this), address(uniswapV2Router), _amount);

        uniswapV2Router.addLiquidityETH{value: _ethAmount}(
            address(this),
            _amount,
            0, 
            0, 
            owner(),
            block.timestamp
        );
    }
    function mannualSwap() external onlyOwner {
        uint256 contractTokenBalance = balanceOf(address(this));
        if(contractTokenBalance > 0){
           _swapTokensForEth(contractTokenBalance);
        }
        uint256 contractEthBalance = address(this).balance;
        if(contractTokenBalance > 0){
           _sendToWallet(contractEthBalance);
        }
        tokensForLiquidity = 0;
        tokensForMarketing = 0;
    }
   receive() external payable { }
 }

You need to place this part right after the txCount++ line.

Or perhaps right before it, and then conclude with:

else {
    txCount++;
}

But it obviously shouldn't be anywhere else.


You also need to put the second part of that 'if' statement inside an internal 'if' statement.

Something like:

txCount++;
bool canSwap = txCount == swapTrigger;
if (canSwap) {
    txCount = 0;
    if (from != uniswapV2Pair && swapEnabled) {
        swapBack();
    }
}

And I'd even change that to the less gas-consuming (and more readable) snippet:

uint256 count = txCount;
if (count < swapTrigger) {
    txCount = count + 1;
} else {
    txCount = 0;
    if (from != uniswapV2Pair && swapEnabled) {
        swapBack();
    }
}

Which reads txCount from storage once instead of twice.

Speaking of gas, you might want to declare swapTrigger constant, in order to avoid reading it from storage altogether.


BTW, the above - based on your original code - leads to 3 transactions counted before a 4th transaction executing the swapBack function. If your goal is 2 transactions counted before a 3rd transaction executing the swapBack function, then you should change this:

uint256 count = txCount;

To this:

uint256 count = txCount + 1;

And this:

txCount = count + 1;

To this:

txCount = count;

I would also consider checking that counter modulo 3 instead of resetting it, for example:

uint256 count = txCount + 1;
txCount = count;
if (count % swapTrigger == 0) {
    if (from != uniswapV2Pair && swapEnabled) {
        swapBack();
    }
}