Skip to content

webSocket

The webSocket Transport connects to a JSON-RPC API via a WebSocket. Wraps Viem's webSocket Transport.

Import

ts
import { webSocket } from '@wagmi/core'
import { webSocket } from '@wagmi/core'

Usage

ts
import { 
  createConfig, 
  webSocket 
} from '@wagmi/core'
import { mainnet, sepolia } from '@wagmi/core/chains'

export const config = createConfig({
  chains: [mainnet, sepolia],
  connectors: [injected()],
  transports: {
    [mainnet.id]: webSocket('wss://eth-mainnet.g.alchemy.com/v2/...'), 
    [sepolia.id]: webSocket('wss://eth-sepolia.g.alchemy.com/v2/...'), 
  },
})
import { 
  createConfig, 
  webSocket 
} from '@wagmi/core'
import { mainnet, sepolia } from '@wagmi/core/chains'

export const config = createConfig({
  chains: [mainnet, sepolia],
  connectors: [injected()],
  transports: {
    [mainnet.id]: webSocket('wss://eth-mainnet.g.alchemy.com/v2/...'), 
    [sepolia.id]: webSocket('wss://eth-sepolia.g.alchemy.com/v2/...'), 
  },
})

WARNING

If no URL is provided, then the transport will fall back to a public RPC URL on the chain. It is highly recommended to provide an authenticated RPC URL to prevent rate-limiting.

Parameters

url

string

URL of the JSON-RPC API.

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...')
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...')

key (optional)

string

A key for the Transport. Defaults to "webSocket".

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', { 
  key: 'alchemy',  
})
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', { 
  key: 'alchemy',  
})

name (optional)

string

A name for the Transport. Defaults to "WebSocket JSON-RPC".

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', { 
  name: 'Alchemy WebSocket Provider',  
})
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', { 
  name: 'Alchemy WebSocket Provider',  
})

retryCount (optional)

number

The max number of times to retry when a request fails. Defaults to 3.

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  retryCount: 5, 
})
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  retryCount: 5, 
})

retryDelay (optional)

number

The base delay (in ms) between retries. By default, the Transport will use exponential backoff (~~(1 << count) * retryDelay), which means the time between retries is not constant.

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  retryDelay: 100, 
})
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  retryDelay: 100, 
})

timeout (optional)

number

The timeout for async WebSocket requests. Defaults to 10_000.

ts
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  timeout: 60_000, 
})
const transport = webSocket('wss://eth-mainnet.g.alchemy.com/v2/...', {
  timeout: 60_000, 
})

Released under the MIT License.