Skip to content

Instantly share code, notes, and snippets.

@arberiii
Created December 18, 2019 07:25
Show Gist options
  • Save arberiii/aa10b0c8d4d60f97a1e002e3f0df76c5 to your computer and use it in GitHub Desktop.
Save arberiii/aa10b0c8d4d60f97a1e002e3f0df76c5 to your computer and use it in GitHub Desktop.
ethereum rpc client
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
client, err := rpc.Dial("ws://127.0.0.1:8546")
if err != nil {
log.Fatal(err)
}
subch := make(chan interface{})
if client == nil {
log.Fatal("hey")
}
// Ensure that subch receives the latest block.
go func() {
for i := 0; ; i++ {
if i > 0 {
time.Sleep(2 * time.Second)
}
subscribeBlocks(client, subch)
}
}()
// Print events from the subscription as they arrive.
for block := range subch {
fmt.Println("latest block:", block)
}
}
// subscribeBlocks runs in its own goroutine and maintains
// a subscription for new blocks.
func subscribeBlocks(client *rpc.Client, subch chan interface{}) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Subscribe to new blocks.
sub, err := client.EthSubscribe(ctx, subch, "newHeads")
if err != nil {
fmt.Println("subscribe error:", err)
return
}
// The connection is established now.
// Update the channel with the current block.
var lastBlock interface{}
if err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest", false); err != nil {
fmt.Println("can't get latest block:", err)
return
}
subch <- lastBlock
// The subscription will deliver events to the channel. Wait for the
// subscription to end for any reason, then loop around to re-establish
// the connection.
fmt.Println("connection lost: ", <-sub.Err())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment