-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.go
96 lines (77 loc) · 2.09 KB
/
blockchain.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
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
93
94
95
96
package types
import (
"errors"
"fmt"
"io"
"math/big"
"strconv"
"github.com/99designs/gqlgen/graphql"
"github.com/ericlagergren/decimal"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
var zeroAddress common.Address
func MarshalAddress(addr common.Address) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, strconv.Quote(addr.Hex()))
})
}
func UnmarshalAddress(v interface{}) (common.Address, error) {
s, ok := v.(string)
if !ok {
return zeroAddress, fmt.Errorf("type %T not a string", v)
}
if !common.IsHexAddress(s) {
return zeroAddress, errors.New("not a valid hex address")
}
return common.HexToAddress(s), nil
}
func MarshalBytes(b []byte) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, strconv.Quote(hexutil.Encode(b)))
})
}
func UnmarshalBytes(v interface{}) ([]byte, error) {
s, ok := v.(string)
if !ok {
return nil, fmt.Errorf("type %T not a string", v)
}
// TODO(elffjs): A bit hacky. We want the nice feedback from hexutil, but
// we don't want to require the prefix, so we add it if we think we need it.
if len(s) < 2 || s[0] != '0' || s[1] != 'x' && s[1] != 'X' {
s = "0x" + s
}
return hexutil.Decode(s)
}
func MarshalBigInt(x *big.Int) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, strconv.Quote(x.String()))
})
}
func UnmarshalBigInt(v any) (*big.Int, error) {
s, ok := v.(string)
if !ok {
return nil, fmt.Errorf("type %T not a string", v)
}
x, ok := new(big.Int).SetString(s, 10)
if !ok {
return nil, errors.New("not a valid decimal integer")
}
return x, nil
}
func MarshalBigDecimal(x *decimal.Big) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = fmt.Fprintf(w, `"%.2f"`, x)
})
}
func UnmarshalBigDecimal(v any) (*decimal.Big, error) {
s, ok := v.(string)
if !ok {
return nil, fmt.Errorf("type %T not a string", v)
}
x, ok := new(decimal.Big).SetString(s)
if !ok {
return nil, errors.New("not a valid decimal number")
}
return x, nil
}