ethereum - 批准是否需要时间来确认,在 BSC 中如何处理?
问题描述
嗨,我正在使用 web3 和 react 做 BSC DApp。我对这个领域很陌生。
我在 call 之后发现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.')
}
解决方案
我想通了,我需要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')
}
从更多详细信息中检查此文档
推荐阅读
- html - ReactBootstrap flexbox 不会拉伸到内容高度
- kubernetes - 如何在 Kubernetes 中每 10 秒运行一次 cronjob?
- azure - 在浏览器中显示 Azure blob 图像文件并且不要强制下载
- html - 如何制作这个 Facebook SVG 图标?
- google-maps - Flutter Google Maps:如何在运行后更改地图类型?
- flutter - 来自 Firestore 的 DropDownMenuItem
- r - Shiny:用一些文本描述或默认绘图替换 renderPlotly 错误
- json - 如何使用spring boot rest api获取关系数据?
- cloudflare - 如何删除尚未激活的网站?
- android - OnTextChangedListener 中的 MutableLIst 错误