Take an example of a voting DApp. A user clicks on a vote button, then behind the scenes a transaction gets mined on the blockchain, and finally the DApp tells the user their vote has been recorded.
Now for some reason, there is a chain reorganization (maybe the user's node lost and regained network connectivity).
How can a DApp use web3.js to detect this, so that it can check if the user's transaction has been undone and if the user needs to submit their vote again? Does web3.js fire an event to notify the DApp? Are there any code snippets, such as what event to listen on and how? Or are there any libraries with examples of their use?
Best Answer
Here's code that waits specified number of blocks and verifies the transaction receipt is still valid. If a fork occurs and the replay fails, the receipt check should fail and the callback will call with Error set.
I've only tested this for success and timeout failures, I've not tested it on an actual fork of the blockchain, because I haven't figured out how to reliably cause that to happen yet in a test framework. Appreciate any hints on how to do that.
Per the question, it only uses web3.js calls, and no libraries. I have to tell you using callbacks instead of promises is very painful for me ;-P
I haven't implemented validating the transaction multiple RPC nodes, but there's a note in the code on where to do that. You will probably want to use at least Async.join to do that, which would be an external library.
[EDIT 1] - out of gas is greater than or equal, not greater...