Skip to content

Commit bd9925d

Browse files
Add P-chain indexer API example (#1271)
1 parent e5567ec commit bd9925d

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

indexer/examples/p-chain/main.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright (C) 2019-2023, 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/platformvm/blocks"
14+
"github.com/ava-labs/avalanchego/vms/proposervm/block"
15+
"github.com/ava-labs/avalanchego/wallet/subnet/primary"
16+
)
17+
18+
// This example program continuously polls for the next P-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/P/block", primary.LocalAPIURI)
23+
client = indexer.NewClient(uri)
24+
ctx = context.Background()
25+
nextIndex uint64
26+
)
27+
for {
28+
container, err := client.GetContainerByIndex(ctx, nextIndex)
29+
if err != nil {
30+
time.Sleep(time.Second)
31+
log.Printf("polling for next accepted block\n")
32+
continue
33+
}
34+
35+
platformvmBlockBytes := container.Bytes
36+
proposerVMBlock, err := block.Parse(container.Bytes)
37+
if err == nil {
38+
platformvmBlockBytes = proposerVMBlock.Block()
39+
}
40+
41+
platformvmBlock, err := blocks.Parse(blocks.Codec, platformvmBlockBytes)
42+
if err != nil {
43+
log.Fatalf("failed to parse platformvm block: %s\n", err)
44+
}
45+
46+
acceptedTxs := platformvmBlock.Txs()
47+
log.Printf("accepted block %s with %d transactions\n", platformvmBlock.ID(), len(acceptedTxs))
48+
49+
for _, tx := range acceptedTxs {
50+
log.Printf("accepted transaction %s\n", tx.ID())
51+
}
52+
53+
nextIndex++
54+
}
55+
}

indexer/examples/x-chain-blocks/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ func main() {
2525
nextIndex uint64
2626
)
2727
for {
28-
log.Printf("polling for next accepted block\n")
2928
container, err := client.GetContainerByIndex(ctx, nextIndex)
3029
if err != nil {
3130
time.Sleep(time.Second)
31+
log.Printf("polling for next accepted block\n")
3232
continue
3333
}
3434

0 commit comments

Comments
 (0)