4

I'm trying to swap tokens on uniswap unsing hardhat's mainnet fork but I'm getting this error: Error: Transaction reverted without a reason string. And I don't really know why.

Here is my swap function:

    function swap(address router, address _tokenIn, address _tokenOut, uint _amount) public {
        IERC20(router).approve(router, _amount);
        address[] memory path;
        path = new address[](2);
        path[0] = _tokenIn;
        path[1] = _tokenOut;
        uint deadline = block.timestamp + 300;  
        IUniswapV2Router(router).swapExactTokensForTokens(_amount, 1, path, address(this), deadline);  
}

It is a simple function and it should work. This is how I'm calling it:

await arb.swap(
    uniAddress,
    wethAddress,
    daiAddress,
    ethers.utils.parseEther('0.5')
);

Thanks for answers!

Also here are the addresses I'm calling just to verify if they are the right ones but I'm pretty sure they are:

const wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const daiAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const uniAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';
Kuly14
  • 496
  • 3
  • 12

2 Answers2

5

Weth is different from other token, you're not able to use swapTokensForTokens. We must use the swapEthForTokens function instead, and you have to declare the data option separately.

so in your case we need to do:

Solidity code:

function swapEth(address router, address _tokenIn, address _tokenOut, uint _amount) public {
    IERC20(router).approve(router, _amount);
    address[] memory path;
    path = new address[](2);
    path[0] = _tokenIn;
    path[1] = _tokenOut;
    uint deadline = block.timestamp + 300;
    IUniswapV2Router(router). swapExactETHForTokens(... parameters);  
}

JSCode

const dataOption = { gasPrice: ethers.getDefaultProvider().getGasPrice(), gasLimit: 310000, value: ethers.utils.parseEther('0.5') }

await arb.swap(`enter code here`
    uniAddress,
    wethAddress,
    daiAddress,
    ethers.utils.parseEther('0.5'), // this parameter should be remove from the function declaration as well as in this Javascript
    dataOption
);

PySoL
  • 566
  • 3
  • 9
  • Ohh ok I thought those functions were for native eth but I didin't realize that uniswap v2 doesn't take the native token. You saved me hours of debugging thanks a lot! – Kuly14 Feb 17 '22 at 08:45
  • I am facing similar problem here: https://stackoverflow.com/questions/75960250/nonfungiblepositionmanager-contract-interaction-error-transaction-reverted-with – jayyyo Apr 07 '23 at 16:48
0

Just adding for reffernce but you can also get this error from provider/hardhat if the gas price you set is too high or too low. at the time of writing 5 gwei seems about right

Alex_Nabu
  • 311
  • 3
  • 11