代码之家  ›  专栏  ›  技术社区  ›  Ron

批准需要时间确认吗?在BSC中如何处理?

  •  0
  • Ron  · 技术社区  · 5 年前

    大家好,我正在使用web3和react进行BSC DApp。我对这个领域很陌生。

    打电话后我发现 approve 这个 transfer (或者在我的例子中是zapInToken)抱怨没有足够的津贴是不会成功的。于是我又加了一句 wait allowance 出现10秒,但在很多情况下(50%的几率)10秒后,津贴仍然不存在。请查看下面的代码以了解更多信息。

    理论上, 批准 将生成一个事务,出现的时间取决于。如果是这样的话,这是一种标准模式吗 批准 , wait for allowance ?

    非常感谢。

    const bepContract = getContract(getAddress(from), erc20ABI, library, account)
    const tx = await bepContract.approve(getAddress(contracts.zap), weiAmount)
    if (!tx) {
        throw new Error('Failed to approve transaction')
    }
    await waitAllowance(bepContract, account, getAddress(contracts.zap), weiAmount, 10) // <-- and it will stuck here in most time, the code waits for the allowance is present
    await getZapContract().zapInToken(getAddress(from), weiAmount, getAddress(to)).then(logInfo).catch(logError)
    

    比如说低于零用钱

    const waitAllowance = async (
      contract: Contract,
      account: string,
      to: string,
      allowanceNeeded: string,
      timesLeft: number
    ): Promise<void> => {
      if (timesLeft > 1) {
        const currentAllowance = await contract.allowance(account, to)
        // console.log(`I want ${allowanceNeeded}, and current is ${currentAllowance} `)
        const needed = new BigNumber(allowanceNeeded)
        const current = new BigNumber(currentAllowance.toString())
        if (current.isGreaterThanOrEqualTo(needed)) {
          return
        }
        await new Promise((res) => setTimeout(res, 1000))
        await waitAllowance(contract, account, to, allowanceNeeded, timesLeft - 1)
      }
      throw new Error('wait allowance failed for many times.')
    }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Ron    5 年前

    我明白了,我需要 tx.wait ,因此工作代码如下所示:

    const bepContract = getContract(getAddress(from), erc20ABI, library, account)
    const tx = await bepContract.approve(getAddress(contracts.zap), weiAmount)
    if (!tx) {
        throw new Error('Failed to approve transaction')
    }
    const tx = await waitAllowance(bepContract, account, getAddress(contracts.zap), weiAmount, 10)
    const txResult = await tx.wait()
    if (txResult.status !== 1) {
        throw new Error('Failed approve')
    }
    const txZap = await getZapContract().zapInToken(getAddress(from), weiAmount, getAddress(to))
    const txZapResult = await txZap.wait()
    if (txZapResult.status !== 1) {
        throw new Error('Failed zap')
    }
    

    看看这个 doc 从更多细节

        2
  •  0
  •   Nagibaba    4 年前

    经过数小时的调试,我意识到这是由于我使用的节点。从 getblock Moralis 而且成功了