问题描述
嗨,我正在使用 web3 和 react 做 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),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,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),getAddress(to))
const txZapResult = await txZap.wait()
if (txZapResult.status !== 1) {
throw new Error('Failed zap')
}
查看此doc的更多详情