github.com/0xsequence/ethkit@v1.25.0/cmd/chain-newheads/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 "time" 9 10 "github.com/0xsequence/ethkit/go-ethereum/common/hexutil" 11 "github.com/0xsequence/ethkit/go-ethereum/rpc" 12 "github.com/0xsequence/ethkit/util" 13 ) 14 15 var ( 16 ETH_NODE_URL = "" 17 ETH_NODE_WSS_URL = "" 18 ) 19 20 func init() { 21 testConfig, err := util.ReadTestConfig("../../ethkit-test.json") 22 if err != nil { 23 panic(err) 24 } 25 26 if testConfig["POLYGON_MAINNET_WSS_URL"] != "" { 27 ETH_NODE_URL = testConfig["POLYGON_MAINNET_URL"] 28 ETH_NODE_WSS_URL = testConfig["POLYGON_MAINNET_WSS_URL"] 29 } 30 // if testConfig["MAINNET_URL"] != "" { 31 // ETH_NODE_URL = testConfig["MAINNET_URL"] 32 // ETH_NODE_WSS_URL = testConfig["MAINNET_WSS_URL"] 33 // } 34 if testConfig["ARB_NOVA_WSS_URL"] != "" { 35 ETH_NODE_URL = testConfig["ARB_NOVA_URL"] 36 ETH_NODE_WSS_URL = testConfig["ARB_NOVA_WSS_URL"] 37 } 38 // if testConfig["AVAX_MAINNET_WSS_URL"] != "" { 39 // // ETH_NODE_URL = testConfig["ARB_NOVA_URL"] 40 // ETH_NODE_WSS_URL = testConfig["AVAX_MAINNET_WSS_URL"] 41 // } 42 } 43 44 func main() { 45 client, err := rpc.Dial(ETH_NODE_WSS_URL) 46 if err != nil { 47 log.Fatal(err) 48 } 49 50 ch := make(chan map[string]interface{}) 51 52 sub, err := client.EthSubscribe(context.Background(), ch, "newHeads") 53 if err != nil { 54 log.Fatal(err) 55 } 56 57 var prevHash string 58 go func() { 59 for { 60 select { 61 62 case err := <-sub.Err(): 63 fmt.Println("sub err!", err) 64 os.Exit(1) 65 66 case out := <-ch: 67 // fmt.Println("===> out:", out) 68 // spew.Dump(out) 69 70 hash, ok := out["hash"].(string) 71 if !ok { 72 panic(ok) 73 } 74 parentHash, ok := out["parentHash"].(string) 75 if !ok { 76 panic(ok) 77 } 78 if prevHash != "" { 79 if prevHash != parentHash { 80 fmt.Println("REORG!") 81 } 82 } 83 prevHash = hash 84 num, ok := out["number"].(string) 85 if !ok { 86 panic("hmm") 87 } 88 blockNumber := hexutil.MustDecodeBig(num) 89 fmt.Println("hash", hash, "num", blockNumber.String()) 90 } 91 } 92 }() 93 94 time.Sleep(20 * time.Minute) 95 sub.Unsubscribe() 96 97 // os.Exit(1) 98 99 // filter := map[string]interface{}{ 100 // "topics": []string{}, 101 // // "fromBlock": "latest", 102 // } 103 104 // sub, err = client.EthSubscribe(context.Background(), ch, "logs", filter) 105 // if err != nil { 106 // log.Fatal(err) 107 // } 108 109 // go func() { 110 // for { 111 // select { 112 113 // case err := <-sub.Err(): 114 // fmt.Println("sub err!", err) 115 // os.Exit(1) 116 117 // case out := <-ch: 118 // // fmt.Println("===> out:", out) 119 // spew.Dump(out) 120 121 // removed, ok := out["removed"].(bool) 122 // if !ok { 123 // panic("no") 124 // } 125 // if removed { 126 // panic("removed!!!") 127 // } 128 // } 129 // } 130 // }() 131 132 // time.Sleep(2 * time.Minute) 133 // sub.Unsubscribe() 134 }