Skip to content

Commit ca4c32f

Browse files
StephenButtolphDan Lainedhrubabasu
authored
Add example usage for the X-chain block indexer API (ava-labs#2778)
Co-authored-by: Dan Laine <daniel.laine@avalabs.org> Co-authored-by: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com>
1 parent 242b0f9 commit ca4c32f

File tree

1 file changed

+55
-0
lines changed
  • indexer/examples/x-chain-blocks

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
2+
// See the file LICENSE for licensing terms.
3+
4+
package main
5+
6+
import (
7+
"context"
8+
"fmt"
9+
"log"
10+
"time"
11+
12+
"github.com/ava-labs/avalanchego/indexer"
13+
"github.com/ava-labs/avalanchego/vms/proposervm/block"
14+
"github.com/ava-labs/avalanchego/wallet/chain/x"
15+
"github.com/ava-labs/avalanchego/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 = fmt.Sprintf("%s/ext/index/X/block", primary.LocalAPIURI)
23+
client = indexer.NewClient(uri)
24+
ctx = context.Background()
25+
nextIndex uint64
26+
)
27+
for {
28+
log.Printf("polling for next accepted block\n")
29+
container, err := client.GetContainerByIndex(ctx, nextIndex)
30+
if err != nil {
31+
time.Sleep(time.Second)
32+
continue
33+
}
34+
35+
proposerVMBlock, err := block.Parse(container.Bytes)
36+
if err != nil {
37+
log.Fatalf("failed to parse proposervm block: %s\n", err)
38+
}
39+
40+
avmBlockBytes := proposerVMBlock.Block()
41+
avmBlock, err := x.Parser.ParseBlock(avmBlockBytes)
42+
if err != nil {
43+
log.Fatalf("failed to parse avm block: %s\n", err)
44+
}
45+
46+
acceptedTxs := avmBlock.Txs()
47+
log.Printf("accepted block %s with %d transactions\n", avmBlock.ID(), len(acceptedTxs))
48+
49+
for _, tx := range acceptedTxs {
50+
log.Printf("accepted transaction %s\n", tx.ID())
51+
}
52+
53+
nextIndex++
54+
}
55+
}

0 commit comments

Comments
 (0)