github.com/MetalBlockchain/metalgo@v1.11.9/indexer/examples/p-chain/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/indexer"
    12  	"github.com/MetalBlockchain/metalgo/utils/constants"
    13  	"github.com/MetalBlockchain/metalgo/wallet/subnet/primary"
    14  
    15  	platformvmblock "github.com/MetalBlockchain/metalgo/vms/platformvm/block"
    16  	proposervmblock "github.com/MetalBlockchain/metalgo/vms/proposervm/block"
    17  )
    18  
    19  // This example program continuously polls for the next P-Chain block
    20  // and prints the ID of the block and its transactions.
    21  func main() {
    22  	var (
    23  		uri       = primary.LocalAPIURI + "/ext/index/P/block"
    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  		platformvmBlockBytes := container.Bytes
    37  		proposerVMBlock, err := proposervmblock.Parse(container.Bytes, constants.PlatformChainID)
    38  		if err == nil {
    39  			platformvmBlockBytes = proposerVMBlock.Block()
    40  		}
    41  
    42  		platformvmBlock, err := platformvmblock.Parse(platformvmblock.Codec, platformvmBlockBytes)
    43  		if err != nil {
    44  			log.Fatalf("failed to parse platformvm block: %s\n", err)
    45  		}
    46  
    47  		acceptedTxs := platformvmBlock.Txs()
    48  		log.Printf("accepted block %s with %d transactions\n", platformvmBlock.ID(), len(acceptedTxs))
    49  
    50  		for _, tx := range acceptedTxs {
    51  			log.Printf("accepted transaction %s\n", tx.ID())
    52  		}
    53  
    54  		nextIndex++
    55  	}
    56  }