subscribeBlocks runs in its own goroutine and maintains a subscription for new blocks.
(client *rpc.Client, subch chan Block)
| 62 | // subscribeBlocks runs in its own goroutine and maintains |
| 63 | // a subscription for new blocks. |
| 64 | func 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 | } |
no test coverage detected