Skip to content
LogoLogo

watchBlocks

Watches and returns information for incoming blocks.

Usage

Pass through your Public Client, along with a listener.

import {  } from './client'
 
const  = .( 
  { :  => .() }
)
 
}
}

Returns

UnwatchFn

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

Parameters

onBlock

  • Type: (block: Block) => void

The block information.

const  = .(
  { :  => .() } 
)

onError (optional)

  • Type: (error: Error) => void

Error thrown from getting a block.

const  = .(
  { 
    :  => .(),
    :  => .() 
  }
)

blockTag (optional)

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

Watch for new blocks on a given tag.

const  = .(
  { 
    : 'safe',
    :  => .(), 
  }
)

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.

const  = .(
  { 
    : true, 
    :  => .(),
  }
)

emitOnBegin (optional)

  • Type: boolean
  • Default: false

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

const  = .(
  { 
    : true, 
    :  => .(),
  }
)

includeTransactions (optional)

  • Type: boolean

Whether or not to include transactions (as a structured array of Transaction objects).

const  = .(
  { 
    : true,  
    :  => .(),
  }
)

poll (optional)

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

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

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

import { ,  } from 'viem'
import {  } from 'viem/chains'
 
const  = ({
  : ,
  : ()
})
 
const  = .(
  { 
    :  => .(),
    : true, 
  }
)

pollingInterval (optional)

  • Type: number

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

const  = .(
  { 
    :  => .(),
    : 1_000, 
  }
)

Example

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

JSON-RPC Methods

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