-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
92 lines (80 loc) · 1.95 KB
/
Copy pathdecode.go
File metadata and controls
92 lines (80 loc) · 1.95 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package ethrpc
import (
"encoding/json"
"errors"
"math/big"
"strconv"
)
// ReadUint64 decodes the return value and passes it as a uint64.
//
// This can be used as: res, err := ReadUint64(target.Do("eth_blockNumber"))
func ReadUint64(v json.RawMessage, e error) (uint64, error) {
if e != nil {
return 0, e
}
if len(v) > 0 && v[0] == '"' {
// string
var v2 string
err := json.Unmarshal(v, &v2)
if err != nil {
return 0, err
}
return strconv.ParseUint(v2, 0, 64)
}
var v2 uint64
err := json.Unmarshal(v, &v2)
return v2, err
}
// ReadBigInt can decode a json-encoded bigint in various ways, including
// if it is a number literal or a string.
func ReadBigInt(v json.RawMessage, e error) (*big.Int, error) {
if e != nil {
return nil, e
}
if len(v) > 0 && v[0] == '"' {
// string
var v2 string
err := json.Unmarshal(v, &v2)
if err != nil {
return nil, err
}
res, ok := new(big.Int).SetString(v2, 0)
if !ok {
return nil, errors.New("invalid integer value")
}
return res, nil
}
res := new(big.Int)
err := json.Unmarshal(v, &res)
return res, err
}
// ReadString decodes the return value as a string and returns it
func ReadString(v json.RawMessage, e error) (string, error) {
if e != nil {
return "", e
}
var v2 string
err := json.Unmarshal(v, &v2)
return v2, err
}
// ReadTo returns a setter function that will return an error if an error happens. This is
// a bit convoluted because of limitation in Go's syntax, but this could be used as:
//
// err = ReadTo(&block)(target.Do("eth_getBlockByNumber", "0x1b4", true))
func ReadTo(target any) func(v json.RawMessage, e error) error {
return func(v json.RawMessage, e error) error {
if e != nil {
return e
}
return json.Unmarshal(v, target)
}
}
// ReadAs decodes the return value into the specified generic type T.
func ReadAs[T any](v json.RawMessage, e error) (T, error) {
var v2 T
if e != nil {
return v2, e
}
err := json.Unmarshal(v, &v2)
return v2, err
}