watchBlocks
Watches and returns information for incoming blocks
Loading...
Watches and returns information for incoming blocks
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.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{})
for event := range events { if event.Error != nil { log.Printf("error: %v", event.Error) continue } fmt.Printf("Block %d: %d transactions", event.Block.Number, len(event.Block.Transactions))}<-chan WatchBlocksEvent
A channel that emits WatchBlocksEvent structs containing:
Block *types.Block - The current blockPrevBlock *types.Block - The previous block (nil for first event)Error error - Any error that occurred while fetching the blockConfiguration options accepted by this action.
BlockTag"latest"The block tag to watch.
events := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ BlockTag: public.BlockTagSafe,})boolfalseWhether or not to emit the current block immediately when the watcher starts.
events := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ EmitOnBegin: true,})boolfalseWhether or not to emit missed blocks to the channel.
events := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ EmitMissed: true,})boolfalseWhether or not to include full transaction objects in the block data.
events := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ IncludeTransactions: true,})*boolfalse for WebSocket Transports, true for non-WebSocket TransportsWhether or not to use a polling mechanism instead of a WebSocket subscription.
poll := trueevents := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ Poll: &poll,})time.DurationPollingIntervalThe interval between polls when using polling mode.
import "time"
events := public.WatchBlocks(ctx, publicClient, public.WatchBlocksParameters{ PollingInterval: 5 * time.Second,})Underlying JSON-RPC methods used by this action.
eth_getBlockByNumber on a polling intervaleth_subscribe with "newHeads" event, then fetches full block