I am trying to write a function in my contract which swap ERC20 token to ETH. Tokens or ETH are in my contract, not my wallet. I am the one who triggers the swap action for my contract. Here is my function in my contract. It is swapping ERC20 to WETH, not to ETH. How should I design this functionality? Thanks..
function uniswapErc20ToEth(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) external {
callApprove(_tokenIn, UNISWAP_ROUTER, _amountIn);
uint24 poolFee = 3000;
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
.ExactInputSingleParams({
tokenIn: _tokenIn, //USDT_ADDR
tokenOut: _tokenOut, //WETH_ADDR
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
UNISWAP_ROUTER_CONTRACT.exactInputSingle{value: 0}(params);
// UNISWAP_ROUTER_CONTRACT.refundETH();
// refund leftover ETH to user
// (bool success, ) = msg.sender.call{value: address(this).balance}("");
// require(success, "refund failed");
}
Don't consider the comment lines please.