Bsc

失敗並出現錯誤“TransferHelper:TRANSFER_FROM_FAILED”甚至在契約中獲得批准

  • January 7, 2022

我正在嘗試交換一些 BNB -> Token,然後將其交換回來,所有這些都在一個solidity 函式中。這是我的程式碼:

interface IERC20 {
   function approve(address spender, uint256 value) external returns (bool);
}

interface IPancakeSwapRouter {
   function swapExactETHForTokens(
       uint256 amountOutMin,
       address[] calldata path,
       address to,
       uint256 deadline
   ) external payable returns (uint256[] memory amounts);

   function swapExactTokensForETH(
       uint256 amountIn, 
       uint256 amountOutMin, 
       address[] calldata path, 
       address to, 
       uint256 deadline
   ) external returns (uint[] memory amounts);

   function WETH() external pure returns (address);
   function factory() external pure returns (address);
}

interface IPancakeFactory {
   function getPair(address tokenA, address tokenB) external view returns (address pair);
}

contract Test {

   receive() external payable { }
   fallback() external payable { }

   function BuySell(address token_out, uint value) public payable {

       address swap_router_addr = address(0x10ED43C718714eb63d5aA57B78B54704E256024E); //Pancake router
       IPancakeSwapRouter swap = IPancakeSwapRouter(swap_router_addr);

       uint deadline = block.timestamp + 1200;

       address[] memory path_buy = new address[](2);
       path_buy[0] = swap.WETH();
       path_buy[1] = token_out;

       // 1. try buy 0.001
       uint256[] memory amounts;

       amounts = swap.swapExactETHForTokens { value: msg.value } (
           0, path_buy, address(this), deadline
       );

       // 2. try to sell 
       // approve first
       IERC20 token_dest = IERC20(token_out);
       address pair = IPancakeFactory(swap.factory()).getPair(swap.WETH(), token_out);
       token_dest.approve(pair, amounts[1]); // approve WBNB/Token pair
       token_dest.approve(swap_router_addr, amounts[1]); // approve PancakeSwap Router

       // sell
       address[] memory path_sell = new address[](2);
       path_sell[0] = path_buy[1];
       path_sell[1] = path_buy[0];

       swap.swapExactTokensForETH(
           amounts[1], 0, path_sell, address(this), deadline);
   }
}

我可以確認錯誤發生在最後一行swapExactTokensForETH,它說“TRANSFER_FROM_FAILED”,我猜是關於approve(),但我已經在交換之前批准了 PancakeRoute 的令牌。

一些失敗的 tx 樣本:https ://bscscan.com/tx/0x3feaa9c746ee4458d073a0311b90fb8658d45ed7bac4877bc2934f7e05c4c538

為什麼會出錯?

問題是您需要批准這對而不是路由器。查看您連結的交易,您可以看到它在從0xa89C6f52Ce3Ce1BFF6CAac1E1c98b4f9b3AA5f63(您的契約)轉移到0x4a1a7f263b49dA21fBeD0907317233AA06AdF0dFPancakePair)時恢復。因此,這也是您需要批准的帳戶。

PancakePair可以PancakeFactory通過呼叫從 載入合約的地址getPair(tokenA, tokenB)。該factory地址可以通過從路由器載入factory()

編輯:

您使用的代幣會強制收取轉賬費用。對於這個你不能使用swapExactTokensForETH,你需要使用swapExactTokensForTokensSupportingFeeOnTransferTokens

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