I am deploying a smart contract using web3js and it works perfectly. But i was made aware of my incorrect use of callbacks. I got some basic understanding of promievents from https://web3js.readthedocs.io/en/v1.2.1/callbacks-promises-events.html and rewrote my code as below based on the samples here : 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)
}
})
I did this based on the principle that the callback in getTransactionCount() might execute at any future time, so i should use the return value txCount only within the callback. That is why the entire code is inside the callback function.
But i am not sure about the sendsignedtransaction part. I am assuming that the ".on('transactionHash')" function will execute whenever a transactionHash event is emitted by the sendsignedtransaction function. Similarly the ".on('receipt')" function will execute whenever a receipt event is emitted by the sendsignedtransaction function. And the ".on('error')" function will execute whenever a error event is emitted by the sendsignedtransaction function. So everything works asynchronously without blocking my thread.
If my understanding is correct, then i am confused why this code just hangs in node when i intentionally put in an bug(by removing the "{common: customCommon}" parameter). Shouldn't it return immediately and do "console.error" ?