viem-goviem-go

watchBlockNumber

Watches and returns incoming block numbers

Import

Import the public actions package so you can call this action.

import "github.com/ChefBingbong/viem-go/actions/public"

Usage

Watch actions return a channel of events. Cancel the context to stop watching.

import (
"context"
"fmt"
"log"
"github.com/ChefBingbong/viem-go/actions/public"
"github.com/ChefBingbong/viem-go/client"
"github.com/ChefBingbong/viem-go/client/transport"
"github.com/ChefBingbong/viem-go/chain/definitions"
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
publicClient, err := client.CreatePublicClient(client.PublicClientConfig{
Chain: definitions.Mainnet,
Transport: transport.HTTP("https://eth.llamarpc.com"),
})
if err != nil {
log.Fatal(err)
}
defer func() { _ = publicClient.Close() }()
events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{})
for event := range events {
if event.Error != nil {
log.Printf("error: %v", event.Error)
continue
}
fmt.Printf("Block: %d
", event.BlockNumber)
}

Returns

<-chan WatchBlockNumberEvent

A channel that emits WatchBlockNumberEvent structs containing:

  • BlockNumber uint64 - The current block number
  • PrevBlockNumber *uint64 - The previous block number (nil for first event)
  • Error error - Any error that occurred while fetching the block number

Parameters

Configuration options accepted by this action.

EmitOnBegin

  • Type: bool
  • Default: false
  • Optional

Whether or not to emit the latest block number immediately when the watcher starts.

events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{
EmitOnBegin: true,
})

EmitMissed

  • Type: bool
  • Default: false
  • Optional

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

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.

events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{
EmitMissed: true,
})

Poll

  • Type: *bool
  • Default: false for WebSocket Transports, true for non-WebSocket Transports
  • Optional

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.

poll := true
events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{
Poll: &poll,
})

PollingInterval

  • Type: time.Duration
  • Default: Client's PollingInterval
  • Optional

The interval between polls when using polling mode.

import "time"
events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{
PollingInterval: 5 * time.Second,
})

JSON-RPC Method

Underlying JSON-RPC methods used by this action.