I am trying to do an autosell function like safemoon has, but I am getting always "insufficient output amount"
Steps to reproduce:
- Deploy my token
- Add liquidity v2 in uniswap with 1 T tokens, 1 ETH
- Try to buy my token
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
// Please notice that this is not the total of the tokens, only what I have received as part
// of the sale, since this is only for selling
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
//addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function getTokenPrice(address pairAddress, uint amount) public view returns(uint)
{
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
ERC20 token1 = ERC20(pair.token1());
(uint Res0, uint Res1,) = pair.getReserves();
// decimals
uint res0 = Res0*(10**token1.decimals());
return((amount*res0)/Res1); // return amount of token0 needed to buy token1
}
function swapTokensForEth(uint256 tokenAmount) public {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pancakeswap_router.WETH();
_approve(address(this), address(pancakeswap_router), tokenAmount);
uint256 minimumAccepted = getTokenPrice(uniswapV2Pair, tokenAmount).mul(90).div(100); //10% slippage
// make the swap
pancakeswap_router.swapExactTokensForETH(
tokenAmount,
minimumAccepted,
path,
address(this),
block.timestamp
);
}
Any clue why function swapExactTokensForETH is always failing? I have also tried to send minimum eth = 0 but I have the same issue
Edit: if I change the minimum to 0, I am getting the same error but in a different place: https://dashboard.tenderly.co/tx/rinkeby/0xb4f2f3c1bee3fb9ed9fbfda0fce42b2175ec935d3bd55b9bc7156b9e03f25ea0/debugger?trace=0.4.3.2