watchBlockNumber
Watches and returns incoming block numbers
Watches and returns incoming block numbers
Import the public actions package so you can call this action.
import "github.com/ChefBingbong/viem-go/actions/public"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)}<-chan WatchBlockNumberEvent
A channel that emits WatchBlockNumberEvent structs containing:
BlockNumber uint64 - The current block numberPrevBlockNumber *uint64 - The previous block number (nil for first event)Error error - Any error that occurred while fetching the block numberConfiguration options accepted by this action.
boolfalseWhether or not to emit the latest block number immediately when the watcher starts.
events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{ EmitOnBegin: true,})boolfalseWhether 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,})*boolfalse for WebSocket Transports, true for non-WebSocket TransportsWhether 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 := trueevents := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{ Poll: &poll,})time.DurationPollingIntervalThe interval between polls when using polling mode.
import "time"
events := public.WatchBlockNumber(ctx, publicClient, public.WatchBlockNumberParameters{ PollingInterval: 5 * time.Second,})Underlying JSON-RPC methods used by this action.
eth_blockNumber on a polling intervaleth_subscribe with "newHeads" event