3

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?

2
  • Thankyou for this answer, it was exactly what I needed.
    – Johan
    May 12, 2021 at 7:11
  • Did you find the solution? function swapEthforTokens(uint amountOut) external returns (uint amountOut) { address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = usdt; } this is my code Sep 25 at 9:08

2 Answers 2

1

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).

4

We have to type {value: msg.value} before calling a function which is using msg.value.

        uniswap.swapExactETHForTokens{value: msg.value}(
            amountOut,
            path,
            msg.sender,
            deadline
        );

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