[Ethereum] Uniswap V2 smart contract integration reverts attempt at swapping ETH for tokens

errorsoliditytransactions

I'm trying to integrate Uniswap V2 into my contract but my attempts at making a trade (ETH to Token) always gets reverted.

Here is my solidity code:

pragma solidity ^0.6.0;

// Included the interface found here: https://uniswap.org/docs/v2/smart-contracts/router/#interface
interface IUniswapV2Router01 {
...
}

contract MyContract {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0xcDbE04934d89e97a24BCc07c3562DC8CF17d8167; // Rinkeby

  IUniswapV2Router01 public uniswapRouter;

  constructor() public {
    uniswapRouter = IUniswapV2Router01(UNISWAP_ROUTER_ADDRESS);
  }

  function swapEthForTokenWithUniswap(uint ethAmount, address tokenAddress) public onlyOwner {
    // Verify we have enough funds
    require(ethAmount <= address(this).balance, "Not enough Eth in contract to perform swap.");

    // Build arguments for uniswap router call
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = tokenAddress;

    // Make the call and give it 15 seconds
    // Set amountOutMin to 0 but no success with larger amounts either
    uniswapRouter.swapExactETHForTokens.value(ethAmount)(0, path, address(this), now + 15);
  }

  function depositEth() external payable {
    // Nothing to do
  }
}

Before calling swapEthForTokenWithUniswap I deposit 1 ETH by calling depositEth.
I'm testing this on Rinkeby with the BAT token (0xda5b056cfb861282b4b59d29c9b395bcc238d29b). Unfortunately I don't have much information in terms of logs (still new to Solidity dev so may not know where to look).

Here's a link to a failed transaction I tried making:
https://rinkeby.etherscan.io/tx/0x465b095ee53ceff57850f7f1d6a1c0256f7bfc948563907d189d6bc4f9ad64c2

Best Answer

So I found the issue. I was testing with the BAT token (0xda5b056cfb861282b4b59d29c9b395bcc238d29b), but at this point in time the ETH/BAT trading pair had not been created yet.

I should have checked the pair, and liquidity of the pair before trying to make a swap.

My code works with the DAI token (0xc7ad46e0b8a400bb3c915120d284aafba8fc4735).

All addresses are on the rinkeby network.

Related Topic