Skip to content

webSocket auto reconnect doesn't work if socket is closed #2325

Closed
@yivlad

Description

@yivlad

Check existing issues

Viem Version

2.13.1

Current Behavior

We use webSocket transport in our frontend app. After some period of inactivity browsers automatically close the web socket connections. When a user leaves the tab open and gets back after a while, webSocket transport is unable to recover from the socket CLOSED state and requests keep failing.

Expected Behavior

webSocket transport creates new connection in place of the closed one.

Steps To Reproduce

Minimal reproducible example using only viem:

import { createPublicClient, parseAbi, webSocket } from "viem";

const client = createPublicClient({
  transport: webSocket(
    "wss://mainnet.infura.io/ws/v3/84842078b09946638c03157f83405213"
  ),
});

const blockNumber = await client.readContract({
  abi: parseAbi(["function getBlockNumber() view returns (uint256)"]),
  address: "0xca11bde05977b3631167028862be2a173976ca11",
  functionName: "getBlockNumber",
});

console.log({
  blockNumber
});

(await client.transport.getRpcClient()).socket.close(); // simulate closing by browser

await client.readContract({
  abi: parseAbi(["function getBlockNumber() view returns (uint256)"]),
  address: "0xca11bde05977b3631167028862be2a173976ca11",
  functionName: "getBlockNumber",
});

In the provided code the second request fails because the web socket connection is closed.

Link to Minimal Reproducible Example

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions