Solidity

在 BSC 測試網上交換代幣

  • July 21, 2021

我在 BSC 測試網上交換兩個令牌時遇到問題,現在我知道這段程式碼可能會在主網上執行,但我正試圖讓它先在測試網上執行,這可能看起來微不足道,但如果有人可以,我將不勝感激協助

address private constant WN = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;

function swap(uint _amountIn, address to_) external {
   // generate the uniswap pair path of token -> weth
   _approve(address(this), address(uniswapV2Router), _amountIn);
  
   transferFrom(0x5dbe1daA8A1CFE11b2F5330E39D3F466DB592bC5, address(this), _amountIn);
  
   address[] memory path = new address[](2);
   path[0] = WN; 
   path[1] = address(this);

   uint onePercent = _amountIn.div(100).mul(2);
   uint tenPercent = _amountIn.div(10);
   
   uint _slippage = _amountIn.add(onePercent.add(tenPercent));

   // make the swap
   uniswapV2Router.swapTokensForExactTokens(
       _amountIn,
       _slippage, // accept any amount of ETH
       path,
       to_,
       now + 60
   );
}


function getAmountOutMin(uint _amountIn) external view returns (uint) {
 //path is an array of addresses.
 //this path array will have 3 addresses [tokenIn, WETH, tokenOut]
 //the if statement below takes into account if token in or token out is WETH.  then the path is only 2 addresses
 address[] memory path = new address[](2);
 path[0] = address(this);
 path[1] = WN; 

 uint[] memory amountOutMins = uniswapV2Router.getAmountsOut(_amountIn, path);
 return amountOutMins[path.length -1];
}   

我不斷收到錯誤

call to MelaCoin.getAmountOutMin errored: Error: Internal JSON-RPC error.
{
 "code": 3,
 "message": "execution reverted: PancakeLibrary: INSUFFICIENT_LIQUIDITY",
 "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002650616e63616b654c6962726172793a20494e53554646494349454e545f4c49515549444954590000000000000000000000000000000000000000000000000000"
} 

我已經批准了契約,並且我想花費的錢包有足夠的 WBNB,是否因為我是所有者並且我試圖在我自己的錢包之間進行交換而失敗?

謝謝

首先是你,因為solidity不喜歡小數。計算百分比時,您必須始終乘以然後除,onePercent 計算 2% 而不是 1%,因此將 2 更改為 1

uint onePercent = _amountIn.mul(1).div(100)

這也不是您在將確切代幣交換為代幣的情況下計算滑點的方式,滑點是將 amountOut 乘以 (100-(your slippage))%

在交換確切代幣的情況下,您將金額乘以 (100 + (您的滑點))%

現在,由於您使用的是 getAmountsOut ,因此您想根據滑點將已知數量的代幣交換為不斷變化的代幣數量,然後在交換方法中您應該使用 swapExactTokensForTokens。

   uniswapV2Router.swapExactTokensForTokens(
   _amountIn,
   _amountOutMin, // Get that from the method GetAmountsOutMin
   path,
   to_,
   now + 60
);

}

現在我們以防萬一將精確換成非精確,您可以計算滑點,滑點是將金額乘以 (100-(您的滑點))% 所以您想要 11% 的滑點 滑點的程式碼是

_amountOut = getAmountOutMin(_amountIn)
_AmountOutMin = _amountOut.mul(89).div(100) //this is the second paramater in the swap function

最後,與在測試網和主網上使用相同地址的 uniswap 不同,pancakeswap 路由器對測試網使用 0xD99D1c33F9fC3444f8101754aBC46c52416550D1

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