Solidity Uniswap – How to Use SwapExactETHForTokens in Smart Contract

solidityuniswap

I want to use use swapExactETHForTokens in my smart contract, always fails transaction with error which is "execution reverted: UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT".

This is my code.

pragma solidity ^0.6.2;

interface IUniswap {
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function WETH() external pure returns (address);
}

contract MyDefi{
    
    IUniswap uniswap;
    
    constructor(address _uniswap) public {
        uniswap = IUniswap(_uniswap);
    }

    function tastSwapExactETHForTokens(
        uint amountOut,
        address token,
        uint deadline
    ) external payable {
        address[] memory path = new address[](2);
        path[0] = uniswap.WETH();
        path[1] = token;
        uniswap.swapExactETHForTokens(
            amountOut,
            path,
            msg.sender,
            deadline
        );
    }
  
}

I tried to swap DAI token in rinkeby network and I got an amountOut argument from the etherscan website.
https://rinkeby.etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D#readContract

Does anyone help to solve my problem?

Best Answer

https://uniswap.org/docs/v2/smart-contracts/router02/ Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).

Related Topic