While I'm able to successfully swap ETH for DAI, I'm running into an INSUFFICIENT_OUTPUT_AMOUNT
error when trying to swap DAI for ETH using swapExactTokensForETH
, even with amountOutMin set to 0. I also tried with LINK with the same result: ETH => LINK works fine, LINK => ETH gives INSUFFICIENT_OUTPUT_AMOUNT
.
I've tried both on Kovan and using Hardhat's forked mainnet. This is the function I'm trying to call:
function swapTokensForEth(address token, uint amountIn, uint deadline) external payable {
IERC20(token).transferFrom(msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = token;
path[1] = uniswap.WETH();
IERC20(token).approve(address(uniswap), amountIn);
// https://uniswap.org/docs/v2/smart-contracts/library/#getamountout
uint[] memory amountOutMin = getEstimatedTokenForETH(amountIn, path); // Fails even when this is 0.
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uniswap.swapExactTokensForETH(
amountIn,
amountOutMin[1],
path,
msg.sender,
deadline
);
}
function getEstimatedTokenForETH(uint amountIn , address[] memory path) public view returns (uint[] memory) {
return uniswap.getAmountsOut(amountIn, path);
}