Solidity
執行恢復:PancakeRouter:INVALID_PATH - 交換令牌時
所以我有一個合約,在呼叫時將特定令牌交換到 BNB,它只使用簡單的 uniswap 路由器介面。
它在使用以下程式碼將代幣交換到 BNB 時起作用,(tokenToSwap) 是我正在交換的代幣的地址
address[] memory path = new address[](2); path[0] = address(tokenToSwap); path[1] = uniswap.WETH();
但是當我更改程式碼時,將以下程式碼換成 BUSD:
address[] memory path = new address[](3); path[0] = address(tokenToSwap); path[1] = uniswap.WETH(); path[2] = address(tokenOut);
此程式碼失敗,我收到以下錯誤消息:
execution reverted: PancakeRouter: INVALID_PATH
我使用的路徑是 BUSD 測試網路徑
address tokenOut = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
我錯過了什麼,為什麼我會收到錯誤消息
– 編輯包含所有程式碼(介面已被省略)
contract ACT_SWAP is Context, Ownable { IUniswapV2Router02 uniswap; address tokenToSwap; address SwaptokenOut; function SetTokenIn(address TokenIn) public onlyOwner() { tokenToSwap = TokenIn; } function SetTokenOut(address TokenOut) public onlyOwner() { SwaptokenOut = TokenOut; } constructor() { uniswap = IUniswapV2Router02(address(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3)); } receive() external payable {} function swapTokensForETH(uint amountIn) external { // need to have called approve on this contract first IERC20(tokenToSwap).transferFrom(msg.sender, address(this), amountIn); address[] memory path = new address[](3); path[0] = address(tokenToSwap); path[1] = uniswap.WETH(); // returns address of Wrapped Ether path[2] = address(SwaptokenOut); // returns address of Wrapped Ether IERC20(tokenToSwap).approve(address(uniswap), amountIn); uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( amountIn, 0, path, address(this), block.timestamp ); } }
你的錯誤是在這一行:
uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( amountIn, 0, path, address(this), block.timestamp );
當您將代幣兌換成ETH/WETH/BNB/WBNB
swapExactTokensForETHSupportingFeeOnTransferTokens(...)
時,必須使用該功能。事實上,這個函式的邏輯檢查你是否從該區塊鏈的本機硬幣(或其掛鉤)交換傳遞。您可以在此連結後的第 391 行看到這些條件。要解決此問題,您必須使用呼叫的函式,該函式允許您將通過 thorw 的代幣與原生硬幣或其掛鉤交換。有關更多資訊,請查看我修改的這段程式碼:swapExactTokensForTokensSupportingFeeOnTransferTokens()
function swapTokensForETH(uint amountIn) external { // need to have called approve on this contract first IERC20(tokenToSwap).transferFrom(msg.sender, address(this), amountIn); address[] memory path = new address[](3); path[0] = tokenToSwap; path[1] = uniswap.WETH(); // returns address of Wrapped BNB path[2] = SwaptokenOut; IERC20(tokenToSwap).approve(address(uniswap), amountIn); uniswap.swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn, 0, path, address(this), block.timestamp ); }