Answer
web3.js does not provide a native mechanism to retrieve events that were emitted while the underlying provider was disconnected. When a web3.eth.Contract.subscribe subscription is created, it is bound to the provider instance at that moment; a provider reconnection does not transfer or resume the subscription, so any logs emitted during the downtime are lost.
Confirmed facts
- The subscription object returned by
Contract.subscribe is tied to the provider instance used at creation time (web3.js v1.x behavior).
- web3.js does not automatically re‑issue the subscription after a provider reconnect.
- No built‑in state‑sync or block‑range tracking exists for recovering missed logs.
Recommended pattern
- Detect provider lifecycle events. Most WebSocket providers expose
connect, end, or error events (e.g., via provider.on('connect', ...) and provider.on('end', ...)).
- When a disconnect is observed, unsubscribe the existing subscription:
await subscription.unsubscribe().
- After the provider emits a
connect event (or you confirm it is ready), create a fresh subscription with the same filter: const newSub = myContract.events.MyEvent({filter}, callback).
- Optionally, enable automatic reconnection in the WebSocket constructor (e.g.,
new WebSocket(url, { reconnect: { auto: true, maxAttempts: Infinity } })) so that the connect/end events fire reliably.
Verification steps
// 1. Log subscription ID before disconnect
console.log('sub id:', subscription.id);
// 2. Simulate provider disconnect (close WS or stop node)
// 3. Observe that no further events arrive
// 4. Reconnect provider, wait for 'connect' event
// 5. Unsubscribe old sub and create new one
await subscription.unsubscribe();
const newSub = myContract.events.MyEvent({filter}, handler);
console.log('new sub id:', newSub.id); // should differ
// 6. Confirm events resume after reconnection and none appear in the gap
Missing diagnostic detail
If your WebSocket provider library already exposes an automatic reconnection option that transparently restores the underlying socket without emitting disconnect/reconnect events, the manual unsubscribe/resubscribe step may be unnecessary. Please confirm whether your provider’s constructor or options include a reconnect flag that guarantees the same socket instance is reused after a network interruption.