MCPcopy Create free account
hub / github.com/CPChain/chain / subscribeBlocks

Function subscribeBlocks

api/rpc/client_example_test.go:64–88  ·  view source on GitHub ↗

subscribeBlocks runs in its own goroutine and maintains a subscription for new blocks.

(client *rpc.Client, subch chan Block)

Source from the content-addressed store, hash-verified

62// subscribeBlocks runs in its own goroutine and maintains
63// a subscription for new blocks.
64func subscribeBlocks(client *rpc.Client, subch chan Block) {
65 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
66 defer cancel()
67
68 // Subscribe to new blocks.
69 sub, err := client.EthSubscribe(ctx, subch, "newBlocks")
70 if err != nil {
71 fmt.Println("subscribe error:", err)
72 return
73 }
74
75 // The connection is established now.
76 // Update the channel with the current block.
77 var lastBlock Block
78 if err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest"); err != nil {
79 fmt.Println("can't get latest block:", err)
80 return
81 }
82 subch <- lastBlock
83
84 // The subscription will deliver events to the channel. Wait for the
85 // subscription to end for any reason, then loop around to re-establish
86 // the connection.
87 fmt.Println("connection lost: ", <-sub.Err())
88}

Callers 1

Calls 3

EthSubscribeMethod · 0.80
CallContextMethod · 0.80
ErrMethod · 0.65

Tested by

no test coverage detected