0

Hi I am trying to swap my custom ERC20 token with my other custom-created ERC20 token but I am facing an issue, Every other function is working fine except the swapTokens function. When I am trying to swap I am getting this error:

execution reverted: UniswapV2Library: ZERO_ADDRESS

My code:-

function swapTokens(uint256 _tokenAmount, address _tokenIn, address _tokenOut) external payable {
    address[] memory path;
    path = new address[](3);
    path[0] = _tokenIn;
    path[1] = _tokenOut;

    ERC20(_tokenIn).transferFrom(msg.sender, address(this), _tokenAmount);
    ERC20(_tokenIn).approve(uniswapRouter, _tokenAmount);
    
    uint amountOut = IUniswapV2Router(uniswapRouter).getAmountsOut(
        _tokenAmount,
        path
    )[1];
    
    (uint[] memory amounts) = IUniswapV2Router(uniswapRouter).swapTokensForExactTokens(
        _tokenAmount, 
        amountOut,
        path, 
        msg.sender, 
        block.timestamp
        );
    emit TokenSwapEvent(amounts);
}

1 Answer 1

1

Your path in this case must be 2 length and not 3. Change these three lines about your smart contract code:

...
path = new address[](3);
path[0] = _tokenIn;
path[1] = _tokenOut;
...

with these:

...
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
...
1
  • Thanks that worked but I am having another. error : - Error Message: invalid opcode: INVALID amountIn = (numerator / denominator).add(1); But the weird thing is this is running fine in hardhat tests
    – Mohit
    Apr 20, 2022 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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