Solidity – How swapExactETHForTokens Works with Example Code in Uniswap

solidityuniswap


receive() external payable {}
    function swapEthForTokens(uint256 ethAmount) public payable returns (uint256) {
        address[] memory path = new address[](2);
        path[0] = uniswapV2Router.WETH();
        path[1] = address(this);

        uint[] memory tokenAmount_ ; 

        // make the swap
        tokenAmount_ = uniswapV2Router.swapExactETHForTokens{ value: ethAmount }(
            0,
            path,
            address(this), // The contract
            block.timestamp
        );
        uint256 outputTokenCount = uint256(tokenAmount_[tokenAmount_.length - 1]);
        return outputTokenCount;
    }

exmple

if inside my contract have remain ETH
I would like my contract to use all remaining ETH to token

after i add liquidity and swap token no problem but when i deposit eth to my contract and swap i got error
" The transaction cannot succeed due to error: undefined. This is probably an issue with one of the tokens you are swapping. "

Best Answer

The general method I use for my contracts is as such:

function swapETHForTokens(uint256 amount) private {
        address[] memory path = new address[](2);
        path[0] = uniswapV2Router.WETH();
        path[1] = address(this);

        uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(0, path, deadAddress, block.timestamp.add(300));
        
        emit SwapETHForTokens(amount, path);
}

This function simply swaps amount of inputted WETH in the contract for tokens (assuming an ERC20 contract). If we wanted to swap everything I suggest writing a separate function:

function swapAllEthForTokens() external {
        swapETHForTokens(address(this).balance);
}

Also, it is generally good practice to keep functions like this private.

Related Topic