forked from chenzhijie/go-web3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abi.go
85 lines (72 loc) · 1.87 KB
/
abi.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
package utils
import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
func (u *Utils) EncodeFunctionSignature(funcName string) []byte {
return crypto.Keccak256([]byte(funcName))[:4]
}
func (u *Utils) DecodeParameters(parameters []string, data []byte) ([]interface{}, error) {
args := make(abi.Arguments, 0)
for _, p := range parameters {
arg := abi.Argument{}
var err error
arg.Type, err = abi.NewType(p, "", nil)
if err != nil {
return nil, err
}
args = append(args, arg)
}
return args.Unpack(data)
}
func (u *Utils) EncodeParameters(parameters []string, data []interface{}) ([]byte, error) {
args := make(abi.Arguments, 0)
for _, p := range parameters {
arg := abi.Argument{}
var err error
arg.Type, err = abi.NewType(p, "", nil)
if err != nil {
return nil, err
}
args = append(args, arg)
}
return args.Pack(data...)
}
func (u *Utils) PackCode(signature string, args []string, params []interface{}) []byte {
methodSig := u.EncodeFunctionSignature(signature)
if len(args) == 0 {
return methodSig
}
inputCode, err := u.EncodeParameters(args, params)
if err != nil {
panic(err)
}
code := append(methodSig, inputCode...)
return code
}
// Equal to solidity `abi.encodePacked(args)`
func (u *Utils) AbiEncodePacked(args ...interface{}) ([]byte, error) {
bytes := make([]byte, 0)
for _, arg := range args {
switch val := arg.(type) {
case *big.Int:
bytes = append(bytes, common.LeftPadBytes(val.Bytes(), 32)...)
case bool:
if val {
bytes = append(bytes, []byte{0x0, 0x1}...)
}
case common.Hash:
bytes = append(bytes, val[:]...)
case []byte:
bytes = append(bytes, val...)
case common.Address:
bytes = append(bytes, val[:]...)
default:
return nil, fmt.Errorf("unsupport type %T", arg)
}
}
return bytes, nil
}