github.com/MetalBlockchain/metalgo@v1.11.9/indexer/examples/x-chain-blocks/main.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"log"
     9  	"time"
    10  
    11  	"github.com/MetalBlockchain/metalgo/ids"
    12  	"github.com/MetalBlockchain/metalgo/indexer"
    13  	"github.com/MetalBlockchain/metalgo/vms/proposervm/block"
    14  	"github.com/MetalBlockchain/metalgo/wallet/chain/x/builder"
    15  	"github.com/MetalBlockchain/metalgo/wallet/subnet/primary"
    16  )
    17  
    18  // This example program continuously polls for the next X-Chain block
    19  // and prints the ID of the block and its transactions.
    20  func main() {
    21  	var (
    22  		uri       = primary.LocalAPIURI + "/ext/index/X/block"
    23  		xChainID  = ids.FromStringOrPanic("2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed")
    24  		client    = indexer.NewClient(uri)
    25  		ctx       = context.Background()
    26  		nextIndex uint64
    27  	)
    28  	for {
    29  		container, err := client.GetContainerByIndex(ctx, nextIndex)
    30  		if err != nil {
    31  			time.Sleep(time.Second)
    32  			log.Println("polling for next accepted block")
    33  			continue
    34  		}
    35  
    36  		proposerVMBlock, err := block.Parse(container.Bytes, xChainID)
    37  		if err != nil {
    38  			log.Fatalf("failed to parse proposervm block: %s\n", err)
    39  		}
    40  
    41  		avmBlockBytes := proposerVMBlock.Block()
    42  		avmBlock, err := builder.Parser.ParseBlock(avmBlockBytes)
    43  		if err != nil {
    44  			log.Fatalf("failed to parse avm block: %s\n", err)
    45  		}
    46  
    47  		acceptedTxs := avmBlock.Txs()
    48  		log.Printf("accepted block %s with %d transactions\n", avmBlock.ID(), len(acceptedTxs))
    49  
    50  		for _, tx := range acceptedTxs {
    51  			log.Printf("accepted transaction %s\n", tx.ID())
    52  		}
    53  
    54  		nextIndex++
    55  	}
    56  }