首页 > 解决方案 > 批准是否需要时间来确认,在 BSC 中如何处理?

问题描述

嗨,我正在使用 web3 和 react 做 BSC DApp。我对这个领域很陌生。

我在 call 之后发现approvetransfer(或我的例子中的 zapInToken)不会因为抱怨没有足够的津贴而成功。所以我添加wait allowance了在场 10 秒,但似乎在 10 秒后多次(50% 的机会)津贴仍然不存在。请检查以下代码以获取更多信息。

从理论上讲,approve将产生一个交易,并且存在的时间取决于。如果是这种情况,它是标准模式approve吗?wait 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.')
}

标签: ethereumweb3jserc20

解决方案


我想通了,我需要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')
}

从更多详细信息中检查此文档


推荐阅读