【发布时间】:2021-07-26 08:42:03
【问题描述】:
您好,我正在使用带有 react 的 web3 做 BSC DApp。我对这个领域很陌生。
我在致电approve 后发现,transfer(或我的情况下是 zapInToken)不会成功,因为抱怨没有足够的津贴。所以我添加了wait allowance 存在 10 秒,但似乎在 10 秒后多次(50% 的机会)津贴仍然不存在。请查看以下代码以获取更多信息。
理论上,approve 将生成一个事务,并且出现的时间取决于。如果是这样,是approve、wait for allowance和transfer的标准模式吗?
谢谢!
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.')
}
【问题讨论】: