'PancackeswapV2Router swapExactETHForTokensSupportingFeeOnTransferTokens: 'Pancake: TRANSFER_FAILED' when "from" equals to "pancackeSwapV2pair"

PancakeSwap is driving me crazy!

I have this simple contract: when the token are transferred from someone different from the owner, instead of making the transer, swap the reveiced tokens with Bnb.

function _swapAsBnb(address from, address to, uint256 amount) private {    
    if(from != _owner && !lockSwap){
        // I tranfer tokens to the contract address in order to make it able to swap them
        _transfer(from, address(this), amount);

        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = _uniswapV2Router.WETH();

        _approve(address(this), address(_uniswapV2Router), tokenAmount);
         
        // use the lock to avoid cycles during the swap
        lockSwap = true;
        _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp);
        lockSwap = false;
    }
    else{
        _transfer(from, to, amount);
        emit Transfer(from, to, amount);
    }
}

function _transfer(address from, address to, uint256 amount) private {
    require(from != address(0), "BEP20: transfer from the zero address");
    require(balanceOf(from) >= amount, "BEP20: transfer amount exceeds balance");

    unchecked {
        _balances[from] -= amount;
    }

    _balances[to] += amount;
}

receive() external payable {}

The steps I made are:

  1. Deploy the contract on BSC Testnet
  2. Create a test pool at https://pancake.kiemtienonline360.com/ containing the pair WBNB:MyToken
  3. I use another wallet in order to buy the token (don't worry, there is enough liquidity)

What I expect is the new wallet has no token, instead the contract address is supposed to have the just swapped Bnb. However i receive the following error: 'Pancake: TRANSFER_FAILED'

I noticed this only happen when a wallet buy the token, not when it has been sold. So the problem occurs when the 'from' argument is the pancakeswap pair it self (in fact, I can avoid the problem by checking that from != uniswapV2Pair address).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source