I am trying to buy DAI tokens from my smart contract using IUniswapV2Router02:

contract BuyToken {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //  Uniswap Router Address
  address private multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI Kovan Address, Mainet: 0x6B175474E89094C44Da98b954EedeAC495271d0F
  IUniswapV2Router02 public uniswapRouter;

  constructor() {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);

  function getPathForETHtoToken() private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = multiDaiKovan;

    return path;

  function getEstimatedETHforToken(uint daiAmount) public view returns (uint[] memory) {
    return uniswapRouter.getAmountsIn(daiAmount, getPathForETHtoToken());

  event Debug(
    uint256 ethAmountDerivable

  function buy(uint tokenAmount) public payable {
    uint deadline = block.timestamp + 15; 
    uint ethAmountDerivable = getEstimatedETHforToken(tokenAmount)[0];

    // Swap ETH for DAI
    uniswapRouter.swapETHForExactTokens{ value: ethAmountDerivable }(daiAmount, getPathForETHtoToken(), address(this), deadline);

    IERC20 token = IERC20(multiDaiKovan);
    require(token.transferFrom(msg.sender, address(this), tokenAmount), 'transferFrom failed.');
    require(token.approve(address(uniswapRouter), tokenAmount), 'approve failed.');

    emit Debug(ethAmountDerivable);

  // important to receive ETH
  receive() payable external {}

If I try on Remix to call the getAmountsIn and paste the value for swapETHForExactTokens it works fine, but directly using the variable to supply into the swap function causes Gas Estimation Error. I looked into the value of ethAmountDerivable the result is just exactly the same as the one I am pasting.

Why do I get gas estimation error even if the value I used manually and thru variable is exactly the same? And how do I resolve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.