[Ethereum] Can’t call “addLiquidityETH” Uniswap function from the contract

remixsolidityuniswap

I'm a newbie, have been learning Solidity for 6 months now. I have been trying to fix this problem for couple of months but still got no hope.

I'm trying to learn how to add liquidity to Uniswap by using my contract.
The problem is when I'm trying to call addLiquidityETH from Uniswap on my contract with Remix it always failed and show the following errors.

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted: UniswapV2Library: INSUFFICIENT_AMOUNT { "originalError": { "code": 3, "data": "0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000025556e697377617056324c6962726172793a20494e53554646494349454e545f414d4f554e54000000000000000000000000000000000000000000000000000000", "message": "execution reverted: UniswapV2Library: INSUFFICIENT_AMOUNT" } }`.

Can anybody help me understand what's wrong with my code?

pragma solidity ^0.6.6;

interface IUniswap {
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);

}

interface IERC20 {
    function approve(address spender, uint256 amount) external returns (bool);
}

contract TestAddLiquidity {

    address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Ropsten

    IUniswap public uniswap;

    constructor() public {
        uniswap = IUniswap(UNISWAP_ROUTER_ADDRESS);
    }
    
    function addLiq(address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline) external payable {
     
        IERC20(token).approve(UNISWAP_ROUTER_ADDRESS, amountTokenDesired);
        uniswap.addLiquidityETH(token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline);
    }
      
}

It would appreciate it if you could give me some advice.

Thank you

Best Answer

Just for the others who might be facing the same issue (it took me quite a while to fix it).

The problem I faced was that I was calling function addLiquidityETH() without sending the ethers to Uniswap smart contract, so {value: msg.value} has to be added to the call:

uniswap.addLiquidityETH{ value: msg.value }(
    token,
    amountTokenDesired,
    amountTokenMin,
    amountETHMin,
    msg.sender,
    deadline
);