viem icon indicating copy to clipboard operation
viem copied to clipboard

Unwatching and then rewatching block numbers causes duplication of numbers if the connection has failed before

Open oskarlh opened this issue 4 months ago • 0 comments

Check existing issues

Viem Version

2.37.6

Current Behavior

If you start watching for new block numbers, using a WebSocket transport, a PublicClient, and watchBlockNumber, and there is a connection failure and then the connection is restored, and after that you stop watching and then start watching again, you will receive duplicate numbers

Expected Behavior

The onBlockNumber callback receives the same number only once

Steps To Reproduce

  1. createPublicClient using webSocket
  2. const unwatch = watchBlockNumber({ onBlockNumber: someCallback });
  3. Disconnect from the Internet
  4. Wait a couple of minutes
  5. Reconnect to the Internet and wait for a new block number to be received
  6. unwatch()
  7. watchBlockNumber({ onBlockNumber: someOtherCallback });
  8. someOtherCallback will now (incorrectly) be called twice for the same block numbers

Link to Minimal Reproducible Example

https://github.com/oskarlh/viemwatchbug

Anything else?

Node v22.17 on MacOS 15.6.1.

In an application I have observed more than just duplication, with the same number being received three or even four times. It seemed to happen more frequently when I connected through a VPN.

oskarlh avatar Sep 16 '25 14:09 oskarlh