Ether

swapExactTokensForTokens 失敗

  • November 15, 2021

我一直在閱讀其他結果,但沒有一個符合我的情況*

我暫時無法解決這個問題。當我執行這個腳本時:

  • WBNB 到 DOGE - 有效。
  • DOGE 到 WBNB - 失敗。

我究竟做錯了什麼?

  1. 我用 (router.getAmountsOut()) 註冊了 amountIn
  2. 我正在批准帶有amountIn的令牌組合(Token.approve())
   const pair = [TOKENS.DOGE, TOKENS.WBNB]
   const amountIn = ethers.utils.parseUnits(val, 'ether')
   const amounts = await router.getAmountsOut(amountIn, pair);
   const amountOutMin = amounts[1].sub(amounts[1].div(15))

   const gasPrice = ethers.utils.parseUnits('5', 'gwei')
   const gasLimit = 2000000

   // Token = Token(TOKENS.DOGE)
   await Token.approve( pancakeRouter, amountIn, { gasLimit, gasPrice } )

   const buyTx = await router.swapExactTokensForTokens(
     amountIn,
     amountOutMin,
     pair,
     wallet.address,
     Math.floor(Date.now() / 1000) + 60 * 10,
     { gasLimit, gasPrice }
   )

錯誤:

 reason: 'transaction failed',
 code: 'CALL_EXCEPTION',
 transactionHash: '0xabd9862116711eacaa109d4a832c87e947af666745186b51cce7fe864a310c96',

第1步:

獲取代幣(合約)的 ABI,這是您可以使用該代幣的所有可用方法的介面。

在 bscscan 上,您可以註冊一個 api,然後您可以查詢每個令牌的 ABI。Api url 看起來類似於: https://api.bscscan.com/api?module=contract&action=getabi&address=[TOKEN ADDRESS HERE]&apikey=[YOUR API KEY HERE]並將其儲存到 varABI或其他東西。

// I use axios for HTTP get request
// Change [TOKENADDRESS] and [YOURAPIKEYHERE]

const ABI = await axios.get(`https://api.bscscan.com/api?module=contract&action=getabi&address=[TOKENADDRESS]&apikey=[YOURAPIKEYHERE]`);

第2步:

獲取該合約的小數點,我在 NodeJS 中這樣做:

var Contract = require('web3-eth-contract');

// This is the websocket url of a bsc node
Contract.setProvider('wss://bsc-ws-node.nariox.org:443');

var contractDecimals = new Contract(ABI, 'token address');
var decimals = await contractDecimals.methods.decimals().call();

第 3 步:準備批准出售的價值

// I use the ethers API here
const ethers = require('ethers');

// Get the balance of your wallet
// Change [YOUR WALLET ADDRESS HERE]
const balance = await contract.balanceOf([YOUR WALLET ADDRESS HERE]);

// approval with the decimals of the token
const valueToApprove = ethers.utils.parseUnits(balance.toString(), decimals);

第 4 步:批准銷售(您知道這是如何運作的)

第 5 步:出售!

router.swapExactTokensForETHSupportingFeeOnTransferTokens(
       balance,
       0,
       [TokenToSellHere, [WBNBAddress HERE]],
       recipient, // Your wallet
       Math.floor(Date.now() / 1000) + 60 * 2, // 2 minutes from the current Unix time
       {
           gasPrice: ethers.utils.parseUnits(5', 'gwei'),
           gasLimit: 450000
       }

就是這樣!

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