我在BSC上交换两个令牌时遇到了问题,现在我知道这段代码可能会在mainnet上工作,但是我正在尝试让它首先在Testnet上工作,这看起来很简单,但是如果有人能提供帮助,我会很感激
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,是不是因为我是我的所有者和我试图在我自己的钱包之间交换?
谢谢
发布于 2021-07-21 19:45:42
首先,你,因为坚实不喜欢小数。在计算百分比时,您必须始终乘然后再除以,onePercent也计算2%而不是1%,因此将2改为1
uint onePercent = _amountIn.mul(1).div(100)而且,在将确切的令牌替换为令牌的情况下,不是这样计算滑动的,而是将amountOut乘以(100-(您的滑动)%)。
在这种情况下,可以用(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最后,与在testnet和mainnet上使用相同地址的uniswap不同,pancakeswap路由器在testnet上使用0xD99D1c33F9fC3444f8101754aBC46c52416550D1。
https://ethereum.stackexchange.com/questions/103881
复制相似问题