ethers.js swapExactETHForTokens 和 swapExactTokensForTokens on pancake swap

Posted

技术标签:

【中文标题】ethers.js swapExactETHForTokens 和 swapExactTokensForTokens on pancake swap【英文标题】:ethers.js swapExactETHForTokens and swapExactTokensForTokens on pancake swap 【发布时间】:2021-10-12 18:23:39 【问题描述】:

我在使用以下代码时遇到了问题,我无法在 pancake swap 上购买。根据我调用swapExactETHForTokensswapExactTokensForTokens 的函数,我会收到以下错误: https://bscscan.com/tx/0x18285588819662c93543dba5650d4471e62a504900b9a089f09dea4970698352 https://bscscan.com/tx/0x38ae19f6b677f072a82ac7c5528d445d3fc45288b1004f205d479edffee97b2f

这是我正在使用的代码:

const ethers = require('ethers')
require('dotenv').config( path: __dirname + '/./../../.env' )

const config = 
  wbnb: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
  safemoon: '0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3',
  pancakeSwapRouter: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
  slippage: 12,


const provider = new ethers.providers.WebSocketProvider(
  'wss://bsc-ws-node.nariox.org:443'
)

const wallet = new ethers.Wallet.fromMnemonic(process.env.MNEMONIC)
const account = wallet.connect(provider)

const pancakeswap = new ethers.Contract(
  config.pancakeSwapRouter,
  [
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
    'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)',
    'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)',
  ],
  account
)

const wbnb = new ethers.Contract(
  config.wbnb,
  ['function approve(address spender, uint amount) public returns(bool)'],
  account
)

const buyToken = async () => 
  try 
    const deadline = Math.floor(Date.now() / 1000) + 60 * 20
    const tokenIn = config.wbnb
    const tokenOut = config.safemoon
    const amountIn = ethers.utils.parseUnits('0.001', 'ether')

    const amounts = await pancakeswap.getAmountsOut(amountIn, [
      tokenIn,
      tokenOut,
    ])
    const amountOutMin = amounts[1].sub(amounts[1].div(`$config.slippage`))

    console.log(`
Buying new token
tokenIn: $amountIn $tokenIn (WBNB)
tokenOut: $amountOutMin $tokenOut
    `)

    // const tx = await pancakeswap.swapExactTokensForTokens(
    //   amountIn,
    //   amountOutMin,
    //   [tokenIn, tokenOut],
    //   account.address,
    //   deadline,
    //   
    //     gasPrice: provider.getGasPrice(),
    //     gasLimit: 100000,
    //   
    // )

    const tx = await pancakeswap.swapExactETHForTokens(
      amountOutMin,
      [tokenIn, tokenOut],
      account.address,
      deadline,
      
        gasPrice: provider.getGasPrice(),
        gasLimit: 100000,
      
    )

    const receipt = await tx.wait()
    console.log('buyToken receipt')
    console.log(receipt)
   catch (error) 
    console.log(error)
  


const approve = async () => 
  const valueToapprove = ethers.utils.parseUnits('0.01', 'ether')
  const tx = await wbnb.approve(pancakeswap.address, valueToapprove, 
    gasPrice: provider.getGasPrice(),
    gasLimit: 100000,
  )
  console.log('Approving...')
  const receipt = await tx.wait()
  console.log('Approve receipt')
  console.log(receipt)


const main = async () => 
  await approve()
  await buyToken()
  process.exit()


main()

批准有效,但我不知道swapExactTokensForTokensswapExactETHForTokens 出了什么问题。需要打电话批准吗?似乎对任何一种方式都没有帮助。感谢您的意见。

【问题讨论】:

嗨。我有同样的问题。你找到解决办法了吗? 【参考方案1】:

只需使用swapExactETHForTokens 并尝试在选项中添加一些value

        const token = "Your token";
        const amountIn = ethers.utils.parseUnits("0.0001", 'ether');

        await approve(amountIn);


        const amounts = await router.getAmountsOut(amountIn, [
            addresses.WBNB,
            token
            
          ])

          const amountOutMin = amounts[1].sub(amounts[1].div(12))

            const tx = await router.swapExactETHForTokens(
            0,
            [addresses.WBNB, token],
            addresses.recipient,
            Date.now() + 1000 * 60 * 10, 
            
                gasPrice: provider.getGasPrice(),
                gasLimit: 310000,
                value: amountIn
            
        );

如果有效,请不要忘记标记为已接受的答案。谢谢(-:

【讨论】:

非支付方式不能覆盖值

以上是关于ethers.js swapExactETHForTokens 和 swapExactTokensForTokens on pancake swap的主要内容,如果未能解决你的问题,请参考以下文章

ethers.js:provider.getGasPrice()

如何将 ethers.js 与元掩码连接起来?

区块链-前端交互第四篇:认识 ethers.js并运行测试代码

区块链-前端交互第四篇:认识 ethers.js并运行测试代码

如何以编程方式将 ethers.js 库与 Rinkeby 连接?

Ethers.js,向智能合约汇款(接收功能)