watchBlockNumber
Watches and returns incoming block numbers.
Usage
Pass through your Public Client, along with a listener.
import { publicClient } from './client'
const unwatch = publicClient.watchBlockNumber(
{ onBlockNumber: blockNumber => console.log(blockNumber) }
)
/**
* > 69420n
* > 69421n
* > 69422n
*/
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.
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.
const unwatch = publicClient.watchBlockNumber(
{
emitOnBegin: true,
onBlockNumber: blockNumber => console.log(blockNumber),
}
)
pollingInterval (optional)
- Type:
number
Polling frequency (in ms). Defaults to Client's pollingInterval
config.
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
Calls eth_blockNumber
on a polling interval.
Real-time subscriptions (eth_subscribe
) coming shortly.