Skip to content
On this page

watchBlockNumber โ€‹

Watches and returns incoming block numbers.

Usage โ€‹

Pass through your Public Client, along with a listener.

ts
import { publicClient } from './client'

const unwatch = publicClient.watchBlockNumber( 
  { onBlockNumber: blockNumber => console.log(blockNumber) }
)
/**
 * > 69420n
 * > 69421n
 * > 69422n
 */
ts
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'

export const publicClient = createPublicClient({
  chain: mainnet,
  transport: http()
})

Listener โ€‹

(blockNumber: bigint) => void

The block number.

Returns โ€‹

UnwatchFn

A function that can be invoked to stop watching for new block numbers.

Parameters โ€‹

emitMissed (optional) โ€‹

  • Type: boolean
  • Default: false

Whether or not to emit missed block numbers to the callback.

Missed block numbers may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client.

ts
const unwatch = publicClient.watchBlockNumber(
  { 
    emitMissed: true, 
    onBlockNumber: blockNumber => console.log(blockNumber),
  }
)

emitOnBegin (optional) โ€‹

  • Type: boolean
  • Default: false

Whether or not to emit the latest block number to the callback when the subscription opens.

ts
const unwatch = publicClient.watchBlockNumber(
  { 
    emitOnBegin: true, 
    onBlockNumber: blockNumber => console.log(blockNumber),
  }
)

poll (optional) โ€‹

  • Type: boolean
  • Default: false for WebSocket Transports, true for non-WebSocket Transports

Whether or not to use a polling mechanism to check for new block numbers instead of a WebSocket subscription.

This option is only configurable for Clients with a WebSocket Transport.

ts
import { createPublicClient, webSocket } from 'viem'
import { mainnet } from 'viem/chains'

const publicClient = createPublicClient({
  chain: mainnet,
  transport: webSocket()
})

const unwatch = publicClient.watchBlockNumber(
  { 
    onBlockNumber: blockNumber => console.log(blockNumber),
    poll: true, 
  }
)

pollingInterval (optional) โ€‹

  • Type: number

Polling frequency (in ms). Defaults to Client's pollingInterval config.

ts
const unwatch = publicClient.watchBlockNumber(
  { 
    onBlockNumber: blockNumber => console.log(blockNumber),
    pollingInterval: 12_000, 
  }
)

Example โ€‹

Check out the usage of watchBlockNumber in the live Watch Block Numbers Example below.

JSON-RPC Methods โ€‹

  • When poll: true, calls eth_blockNumber on a polling interval.
  • When poll: false & WebSocket Transport, uses a WebSocket subscription via eth_subscribe and the "newHeads" event.

Released under the MIT License.