我正在使用web3js部署一个智能契约,它工作得非常完美。但我意识到我对回调的错误使用。我从https://web3js.readthedocs.io/en/v1.2.1/callbacks-promises-events.html获得了对promievents的一些基本理解,并根据下面的示例重写了代码:https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html#sendsignedtransaction:
web3.eth.getTransactionCount(account, (err, txCount) => {
if (err!=null) {console.log('error executing web3.eth.getTransactionCount: ', err)}
else{
console.log('txCount: ',txCount)
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(web3.utils.toWei('0', 'gWei')),
data: contractByteCode
}
const tx = new EthereumTx(txObject,{common: customCommon})
tx.sign(privateKey)
const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')
web3.eth.sendSignedTransaction(raw)
.on('transactionHash',(hash) => {
console.log('txHash:', hash)
})
.on('receipt',(receipt) => {
console.log('receipt', receipt)
})
.on('error', console.error)
}
})我这样做是基于一个原则,即getTransactionCount()中的回调可以在将来的任何时候执行,所以我应该只在回调中使用返回值txCount。这就是为什么整个代码都在回调函数中。
但我不确定发送交易部分。我假设".on(' transactionHash ')“函数将在sendsignedtransaction函数发出transactionHash事件时执行。类似地,“.on(‘接收’)”函数将在sendsignedtransaction函数发出接收事件时执行。每当sendsignedtransaction函数发出错误事件时,".on(' error ')“函数就会执行。所以所有东西都异步工作,而不阻塞我的线程。
如果我的理解是正确的,那么当我故意放进一个bug时,为什么这段代码只挂在节点中(通过删除“{ put : customCommon}”参数)。它不应该立即返回并执行"console.error“吗?
发布于 2020-01-21 06:48:29
以下是一般计划:
transactionHash (几乎立即)receipt。error。confirmation。请注意,等待的确认次数越多,事务永远保持在块链中的概率就越高。
有关更多细节,请参见正式文件 (web3.jsv1.2.0)。
https://ethereum.stackexchange.com/questions/79148
复制相似问题