Solidity

如何使用 uniswap v2 路由交換兩個自定義 ERC20 令牌?

  • April 20, 2022

嗨,我正在嘗試將我的自定義 ERC20 令牌與我的其他自定義創建的 ERC20 令牌交換,但我遇到了一個問題,除該swapTokens功能外,其他所有功能都執行良好。當我嘗試交換時,出現此錯誤:

執行恢復:UniswapV2Library:ZERO_ADDRESS

我的程式碼:-

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

在這種情況下,您的路徑必須是 2 長度而不是 3。更改有關您的智能合約程式碼的這三行:

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

用這些:

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

引用自:https://ethereum.stackexchange.com/questions/126569