-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_number.go
66 lines (57 loc) · 1.32 KB
/
block_number.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ethereum
import (
"fmt"
"strconv"
"github.com/goccy/go-json"
log "github.com/sirupsen/logrus"
c "github.com/verity-team/dws/internal/common"
)
func MostRecentBlockNumber(ctxt c.Context) (uint64, error) {
label := "finalized"
if ctxt.CrawlerType == c.Latest {
label = "latest"
}
request := EthGetBlockByNumberRequest{
JsonRPC: "2.0",
Method: "eth_getBlockByNumber",
Params: []interface{}{label, false},
ID: 1,
}
requestBytes, err := json.Marshal(request)
if err != nil {
return 0, err
}
params := c.HTTPParams{
URL: ctxt.ETHRPCURL,
RequestBody: requestBytes,
MaxWaitInSeconds: ctxt.MaxWaitInSeconds,
}
body, err := c.HTTPPost(params)
if err != nil {
return 0, err
}
blockNumber, err := parseMostRecentBlockNumber(body)
if err != nil {
return 0, err
}
return blockNumber, nil
}
func parseMostRecentBlockNumber(body []byte) (uint64, error) {
type Response struct {
Result struct {
Number string `json:"number"`
} `json:"result"`
}
var resp Response
err := json.Unmarshal(body, &resp)
if err != nil {
return 0, err
}
blockNumber, err := strconv.ParseUint(resp.Result.Number, 0, 64)
if err != nil {
err = fmt.Errorf("failed to parse block number ('%s'), %w", resp.Result.Number, err)
log.Error(err)
return 0, err
}
return blockNumber, nil
}