Skip to content
On this page

watchBlocks

Watches and returns information for incoming blocks.

Usage

Pass through your Public Client, along with a listener.

ts
import { publicClient } from './client'

const unwatch = publicClient.watchBlocks( 
  { onBlock: block => console.log(block) }
)
/**
 * > {
 *  baseFeePerGas: 10789405161n,
 *  difficulty: 11569232145203128n,
 *  extraData: '0x75732d656173742d38',
 *  ...
 * }
 * 
 * > {
 *  baseFeePerGas: 12394051511n,
 *  difficulty: 11512315412421123n,
 *  extraData: '0x5123ab1512dd14aa',
 *  ...
 * }
 */
ts
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'

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

Returns

UnwatchFn

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

Parameters

onBlock

  • Type: (block: Block) => void

The block information.

ts
const unwatch = publicClient.watchBlocks(
  { onBlock: block => console.log(block) } 
)

onError (optional)

  • Type: (error: Error) => void

Error thrown from getting a block.

ts
const unwatch = publicClient.watchBlocks(
  { 
    onBlock: block => console.log(block),
    onError: error => console.log(error) 
  }
)

blockTag (optional)

  • Type: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'
  • Default: 'latest'

Watch for new blocks on a given tag.

ts
const unwatch = publicClient.watchBlocks(
  { 
    blockTag: 'safe',
    onBlock: block => console.log(block), 
  }
)

emitMissed (optional)

  • Type: boolean
  • Default: false

Whether or not to emit missed blocks to the callback.

Missed blocks 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.watchBlocks(
  { 
    emitMissed: true, 
    onBlock: block => console.log(block),
  }
)

emitOnBegin (optional)

  • Type: boolean
  • Default: false

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

ts
const unwatch = publicClient.watchBlocks(
  { 
    emitOnBegin: true, 
    onBlock: block => console.log(block),
  }
)

pollingInterval (optional)

  • Type: number

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

ts
const unwatch = publicClient.watchBlocks(
  { 
    onBlock: block => console.log(block),
    pollingInterval: true, 
  }
)

Example

Check out the usage of watchBlocks in the live Watch Blocks Example below.

JSON-RPC Methods

Calls eth_getBlockByNumber on a polling interval.

Real-time subscriptions (eth_subscribe) coming shortly.

Released under the MIT License.