I have an issue with processing new blocks through a WebSocket connection on a local node. Sometimes I receive multiple events with the same
blockNumber but different
I understood from some StackExchange threads that one of these blocks are just not part of the canonical chain. However, my question is: How do I determine which one of them is on the canonical chain? What would be the exact steps I need to take when I open a WebSocket connection and receive a new block after subscribing to
"newHeads" to ensure this block is canonical?
This is a shortened log of an application that stores some transactions from the newest blocks into an SQL db.
Added block #7665190 | hash 0x9ba66766f3835d5be9191e0ad7c79b741707e78dcf1f2a8898b7a7c2141d357c Added block #7665191 | hash 0xe550f98974b4b02fff709842f670e682fc90403ead36d6258927b38cd45a56bc Added block #7665191 | hash 0x068f5648b0509303640a1aa9c10764c89f33482148fde4ef94ce0ab4f21c25d1 Added block #7665192 | hash 0x36c2f7e9a4542a2311c91e8cd1560994ca14841086be86d0f6dbb1be9eae9d46 Added block #7665193 | hash 0x0cd7d6e0dac1c3288e574b454d7e4dee9123c4e1e94b6e87307aae32e812f1f1
Is using a
getBlockByNumber RPC call after receiving a new block number sufficient to determine that this is indeed the "right" block that I want to store transactions for in my DB?
I don't think so because if I would use
getBlockByNumber on the first
7665191 I would still receive the transactions in that block. Then after using it on the subsequent
7665191 I would receive another set of transactions that might include a bunch of the previous ones. Thus introducing redundancy and possible mismatches between the canonical transactions hashes / addresses in my SQL db.
Second option I could think of would be to wait until I receive just a single blockNumber after (e.g.
7665192 in this case) and then check it's
parentHash. If one of the
hash is equal to
parentHash I would take this one as the canonical block. However this just introduced a lot more questions:
- What if I would receive duplicate blockNumbers multiple times in a row?
7665191, 7665191, 7665192, 7665192, 7665193, 7665193 ...
- What if the parentHash wouldn't be one of the previous duplicates?
parentHashof 7665192 wouldn't be equal to hash of any
To reiterate my question: What is the recommended way to ensure that I only store the real transactions from the blocks that you can find on bscscan.