Solidity – How to Swap Two Custom ERC20 Tokens Using Uniswap V2 Routes

erc-20solidityswapsuniswap

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);
}

Best Answer

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;
...
Related Topic