1

When using Uniswap function swapExactTokensForETH() I get the following error:

'TransferHelper: ETH_TRANSFER_FAILED'

Contract code:

pragma solidity 0.8.0;

import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";


contract test {

address internal owner;
address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ;
IUniswapV2Router02 private uniswapRouter;

constructor() {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
    owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
    }

//owner
modifier isOwner(){
    require(msg.sender == owner, "Caller is not owner");
    _;
    }
    
    
function EthToTokens(address tokenAddress, uint EthInAmount, uint TokenOutAmountMin, uint deadline) public payable {
    uniswapRouter.swapExactETHForTokens{ value: EthInAmount }(TokenOutAmountMin, getPathForEthToToken(tokenAddress), address(this), deadline);
    }

function TokensToEth(address tokenAddress, uint EthOutAmount, uint TokenInAmount, uint deadline) public payable {
    IERC20 token = IERC20(tokenAddress);
    token.approve(UNISWAP_ROUTER_ADDRESS, TokenInAmount);
    uniswapRouter.swapExactTokensForETH(TokenInAmount, EthOutAmount, getPathForTokenToEth(tokenAddress), address(this), deadline);
    }

function getPathForEthToToken(address tokenAddress) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = tokenAddress;
    return path;
    }    
    
function getPathForTokenToEth(address tokenAddress) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = tokenAddress;
    path[1] = uniswapRouter.WETH();
    return path;
    }

function sendEther() public payable{
}

function withdraw(address payable _address, uint withdrawAmount) public payable isOwner{
    _address.transfer(withdrawAmount);
}

}

1 Answer 1

1

The code uses address(this) as target.

uniswapRouter.swapExactTokensForETH(TokenInAmount, EthOutAmount, getPathForTokenToEth(tokenAddress), address(this), deadline);

For a contract to accept ether it has to implement the receive function.

event Received(address sender, uint amount);

receive() external payable {
    emit Received(msg.sender, msg.value);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.