-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathabi.go
More file actions
373 lines (328 loc) · 10.3 KB
/
abi.go
File metadata and controls
373 lines (328 loc) · 10.3 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package ethcoder
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"github.com/0xsequence/ethkit/go-ethereum/accounts/abi"
"github.com/0xsequence/ethkit/go-ethereum/common"
"github.com/0xsequence/ethkit/go-ethereum/common/hexutil"
)
func AbiCoder(argTypes []string, argValues []interface{}) ([]byte, error) {
if len(argTypes) != len(argValues) {
return nil, errors.New("invalid arguments - types and values do not match")
}
args, err := buildArgumentsFromTypes(argTypes)
if err != nil {
return nil, fmt.Errorf("failed to build abi: %v", err)
}
return args.Pack(argValues...)
}
func AbiCoderHex(argTypes []string, argValues []interface{}) (string, error) {
b, err := AbiCoder(argTypes, argValues)
if err != nil {
return "", err
}
h := hexutil.Encode(b)
return h, nil
}
func AbiDecoder(argTypes []string, input []byte, argValues []interface{}) error {
if len(argTypes) != len(argValues) {
return errors.New("invalid arguments - types and values do not match")
}
args, err := buildArgumentsFromTypes(argTypes)
if err != nil {
return fmt.Errorf("failed to build abi: %v", err)
}
values, err := args.Unpack(input)
if err != nil {
return err
}
if len(args) > 1 {
return args.Copy(&argValues, values)
} else {
return args.Copy(&argValues[0], values)
}
}
func AbiDecoderWithReturnedValues(argTypes []string, input []byte) ([]interface{}, error) {
args, err := buildArgumentsFromTypes(argTypes)
if err != nil {
return nil, fmt.Errorf("failed to build abi: %v", err)
}
return args.UnpackValues(input)
}
func AbiEncodeMethodCalldata(methodExpr string, argValues []interface{}) ([]byte, error) {
mabi, methodName, err := ParseMethodABI(methodExpr, "")
if err != nil {
return nil, err
}
data, err := mabi.Pack(methodName, argValues...)
if err != nil {
return nil, err
}
return data, nil
}
func AbiEncodeMethodCalldataFromStringValues(methodExpr string, argStringValues []string) ([]byte, error) {
_, argsList, err := parseMethodExpr(methodExpr)
if err != nil {
return nil, err
}
argTypes := []string{}
for _, v := range argsList {
argTypes = append(argTypes, v.Type)
}
argValues, err := AbiUnmarshalStringValues(argTypes, argStringValues)
if err != nil {
return nil, err
}
return AbiEncodeMethodCalldata(methodExpr, argValues)
}
func AbiDecodeExpr(expr string, input []byte, argValues []interface{}) error {
argsList := parseArgumentExpr(expr)
argTypes := []string{}
for _, v := range argsList {
argTypes = append(argTypes, v.Type)
}
return AbiDecoder(argTypes, input, argValues)
}
func AbiDecodeExprAndStringify(expr string, input []byte) ([]string, error) {
argsList := parseArgumentExpr(expr)
argTypes := []string{}
for _, v := range argsList {
argTypes = append(argTypes, v.Type)
}
return AbiMarshalStringValues(argTypes, input)
}
func AbiDecodeExprToInterfaces(expr string, input []byte) ([]interface{}, error) {
argsList := parseArgumentExpr(expr)
argTypes := []string{}
for _, v := range argsList {
argTypes = append(argTypes, v.Type)
}
return AbiDecoderWithReturnedValues(argTypes, input)
}
func AbiMarshalStringValues(argTypes []string, input []byte) ([]string, error) {
values, err := AbiDecoderWithReturnedValues(argTypes, input)
if err != nil {
return nil, err
}
return StringifyValues(values)
}
// AbiDecodeStringValues will take an array of ethereum types and string values, and decode
// the string values to runtime objects.
func AbiUnmarshalStringValues(argTypes []string, stringValues []string) ([]interface{}, error) {
if len(argTypes) != len(stringValues) {
return nil, fmt.Errorf("ethcoder: argTypes and stringValues must be of equal length")
}
values := []interface{}{}
for i, typ := range argTypes {
s := stringValues[i]
switch typ {
case "address":
// expected "0xabcde......"
if !strings.HasPrefix(s, "0x") {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting address in hex", i)
}
values = append(values, common.HexToAddress(s))
continue
case "string":
// expected: string value
values = append(values, s)
continue
case "bytes":
// expected: bytes in hex encoding with 0x prefix
if strings.HasPrefix(s, "0x") {
values = append(values, common.Hex2Bytes(s[2:]))
continue
} else {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting bytes in hex", i)
}
case "bool":
// expected: "true" | "false"
if s == "true" {
values = append(values, true)
} else if s == "false" {
values = append(values, false)
} else {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting bool as 'true' or 'false'", i)
}
continue
}
// numbers
if match := regexArgNumber.FindStringSubmatch(typ); len(match) > 0 {
size, err := strconv.ParseInt(match[2], 10, 64)
if err != nil {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting %s. reason: %w", i, typ, err)
}
if (size%8 != 0) || size == 0 || size > 256 {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. invalid number type '%s'", i, typ)
}
num := big.NewInt(0)
num, ok := num.SetString(s, 10)
if !ok {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting number. unable to set value of '%s'", i, s)
}
values = append(values, num)
continue
}
// bytesXX (fixed)
if match := regexArgBytes.FindStringSubmatch(typ); len(match) > 0 {
if !strings.HasPrefix(s, "0x") {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting bytes in hex", i)
}
size, err := strconv.ParseInt(match[1], 10, 64)
if err != nil {
return nil, err
}
if size == 0 || size > 32 {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. bytes type '%s' is invalid", i, typ)
}
val := common.Hex2Bytes(s[2:])
if int64(len(val)) != size {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. %s type expects a %d byte value but received %d", i, typ, size, len(val))
}
values = append(values, val)
continue
}
// arrays
if match := regexArgArray.FindStringSubmatch(typ); len(match) > 0 {
baseTyp := match[1]
if match[2] == "" {
match[2] = "0"
}
count, err := strconv.ParseInt(match[2], 10, 64)
if err != nil {
return nil, err
}
if baseTyp != "address" {
submatch := regexArgNumber.FindStringSubmatch(baseTyp)
if len(submatch) == 0 {
return nil, fmt.Errorf("ethcoder: value at position %d of type %s is unsupported. Only number string arrays are presently supported.", i, typ)
}
}
var stringValues []string
err = json.Unmarshal([]byte(s), &stringValues)
if err != nil {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. failed to unmarshal json string array '%s'", i, s)
}
if count > 0 && len(stringValues) != int(count) {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. array size does not match required size of %d", i, count)
}
var arrayArgs []string
for i := 0; i < len(stringValues); i++ {
arrayArgs = append(arrayArgs, baseTyp)
}
arrayValues, err := AbiUnmarshalStringValues(arrayArgs, stringValues)
if err != nil {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. failed to get string values for array - %w", i, err)
}
if baseTyp == "address" {
var addresses []common.Address
for _, element := range arrayValues {
address, ok := element.(common.Address)
if !ok {
return nil, fmt.Errorf("ethcoder: expected common.Address, got %v", element)
}
addresses = append(addresses, address)
}
values = append(values, addresses)
} else {
var bnArray []*big.Int
for _, n := range arrayValues {
bn, ok := n.(*big.Int)
if !ok {
return nil, fmt.Errorf("ethcoder: value at position %d is invalid. expecting array element to be *big.Int", i)
}
bnArray = append(bnArray, bn)
}
values = append(values, bnArray)
}
}
}
return values, nil
}
// ParseMethodABI will return an `abi.ABI` object from the short-hand method string expression,
// for example, methodExpr: `balanceOf(address)` returnsExpr: `uint256`
func ParseMethodABI(methodExpr, returnsExpr string) (*abi.ABI, string, error) {
var methodName string
var inputArgs, outputArgs []abiArgument
var err error
methodName, inputArgs, err = parseMethodExpr(methodExpr)
if err != nil {
return nil, "", err
}
if returnsExpr != "" {
outputArgs = parseArgumentExpr(returnsExpr)
}
// generate method abi json for parsing
methodABI := abiJSON{
Name: methodName,
Type: "function",
Inputs: inputArgs,
Outputs: outputArgs,
}
abiJSON, err := json.Marshal(methodABI)
if err != nil {
return nil, methodName, err
}
mabi, err := abi.JSON(strings.NewReader(fmt.Sprintf("[%s]", string(abiJSON))))
if err != nil {
return nil, methodName, err
}
return &mabi, methodName, nil
}
func buildArgumentsFromTypes(argTypes []string) (abi.Arguments, error) {
args := abi.Arguments{}
for _, argType := range argTypes {
abiType, err := abi.NewType(argType, "", nil)
if err != nil {
return nil, err
}
args = append(args, abi.Argument{Type: abiType})
}
return args, nil
}
func parseMethodExpr(expr string) (string, []abiArgument, error) {
expr = strings.Trim(expr, " ")
idx := strings.Index(expr, "(")
if idx < 0 {
return "", nil, errors.New("ethcoder: invalid input expr. expected format is: methodName(arg1Type, arg2Type)")
}
methodName := expr[0:idx]
expr = expr[idx:]
if expr[0] != '(' || expr[len(expr)-1] != ')' {
return "", nil, errors.New("ethcoder: invalid input expr. expected format is: methodName(arg1Type, arg2Type)")
}
argsList := parseArgumentExpr(expr)
return methodName, argsList, nil
}
func parseArgumentExpr(expr string) []abiArgument {
args := []abiArgument{}
expr = strings.Trim(expr, "() ")
p := strings.Split(expr, ",")
if expr == "" {
return args
}
for _, v := range p {
v = strings.Trim(v, " ")
n := strings.Split(v, " ")
arg := abiArgument{Type: n[0]}
if len(n) > 1 {
arg.Name = n[1]
}
args = append(args, arg)
}
return args
}
type abiJSON struct {
Name string `json:"name"`
Inputs []abiArgument `json:"inputs"`
Outputs []abiArgument `json:"outputs"`
Type string `json:"type"`
}
type abiArgument struct {
Name string `json:"name,omitempty"`
Type string `json:"type"`
}