【问题标题】:Does approve take time to be confirmed, and how to deal with this in BSC?批准是否需要时间来确认,在 BSC 中如何处理?
【发布时间】:2021-07-26 08:42:03
【问题描述】:

您好,我正在使用带有 react 的 web3 做 BSC DApp。我对这个领域很陌生。

我在致电approve 后发现,transfer(或我的情况下是 zapInToken)不会成功,因为抱怨没有足够的津贴。所以我添加了wait allowance 存在 10 秒,但似乎在 10 秒后多次(50% 的机会)津贴仍然不存在。请查看以下代码以获取更多信息。

理论上,approve 将生成一个事务,并且出现的时间取决于。如果是这样,是approvewait for allowancetransfer的标准模式吗?

谢谢!

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)

waitAllowance 如下所示

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.')
}

【问题讨论】:

    标签: ethereum web3js erc20


    【解决方案1】:

    我想通了,我需要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 了解更多详情

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 2011-08-01
      • 2017-06-03
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多