This repository has been archived by the owner on Aug 21, 2021. It is now read-only.
/
misc.go
86 lines (70 loc) · 1.88 KB
/
misc.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
package types
import (
"encoding/hex"
"math/big"
"database/sql/driver"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"errors"
"fmt"
"bytes"
)
type Address [20]byte
func (addr *Address) Value() (driver.Value, error) {
return addr[:], nil
}
func (addr *Address) Scan(src interface{}) error {
switch v := src.(type) {
case []byte:
copy(addr[:], v)
return nil
default:
return errors.New("Address scanner src should be []byte")
}
}
func (addr *Address) String() string {
return fmt.Sprintf("%#x", addr[:])
}
func (addr *Address) UnmarshalJSON(data []byte) error {
length, err := hex.Decode(addr[:], bytes.TrimPrefix(bytes.Trim(data, "\""), []byte("0x")))
if err != nil { return err }
if length != 20 {
return errors.New("Invalid address length")
}
return nil
}
func (data *Address) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%v\"", data)), nil
}
func (data *Address) ToGethAddress() (common.Address) {
return common.HexToAddress(hex.EncodeToString(data[:]))
}
type Uint256 [32]byte
func (data *Uint256) Value() (driver.Value, error) {
return data[:], nil
}
func (data *Uint256) Scan(src interface{}) error {
switch v := src.(type) {
case []byte:
copy(data[:], v)
return nil
default:
return errors.New("Uint256 scanner src should be []byte")
}
}
func (data *Uint256) String() (string) {
return data.Big().String()
}
func (data *Uint256) Big() (*big.Int) {
return new(big.Int).SetBytes(data[:])
}
func (data *Uint256) UnmarshalJSON(jsonData []byte) error {
numberBytes := bytes.Trim(jsonData, "\"")
numberBig, ok := new(big.Int).SetString(string(numberBytes), 10)
if !ok { return fmt.Errorf("Failed to convert number to integer: %v", string(jsonData)) }
copy(data[:], abi.U256(numberBig))
return nil
}
func (data *Uint256) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%v\"", data)), nil
}