forked from streamingfast/eth-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method.go
607 lines (495 loc) · 16 KB
/
method.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// Copyright 2021 dfuse Platform Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package eth
import (
"encoding/json"
"fmt"
"math"
"math/big"
"regexp"
"strings"
"go.uber.org/zap"
)
//go:generate go-enum -f=$GOFILE --lower --marshal --names
//
// ENUM(
// Pure
// View
// NonPayable
// Payable
// )
//
type StateMutability int
type MethodParameter struct {
// Name represents the name of the parameter as defined by the
// developer in the Solidity code of the contract.
Name string
// TypeName represents the type of the parameter, this is standard
// types known to Solidity. Array have a suffix `[]` (can be nested)
// and struct type is always `tuple` with an filled up `Components`
// defining the struct.
TypeName string
// TypeMutability is unclear, requires more investigation, I don't recall
// to which Solidity concept it refers to.
TypeMutability string
// Payable determines if the parameter is a payable value so an
// Ether value.
Payable bool
// InternalType is the internal type to the contract, usually equal
// to `TypeName` but can be different for example if a type `uint`
// was defined, in this case `TypeName` will be `uint256` and internal
// type will be `uint`. Tuple which have `TypeName` `tuple` but internal
// type is `struct <Contract>.<Struct>` is another exceptions.
InternalType string
// Components represents that struct fields of a particular tuple. Only
// filled up when `TypeName` is equal to `tuple` (or array of tuples).
Components []*StructComponent
}
func newMethodParameter(mStr string) (*MethodParameter, error) {
mStr = strings.TrimLeft(mStr, " ")
mStr = strings.TrimRight(mStr, " ")
if mStr == "" {
return nil, fmt.Errorf("invalid method parameter")
}
chunks := strings.Split(mStr, " ")
// TODO: we should check the type
m := &MethodParameter{TypeName: chunks[0]}
if len(chunks) > 1 {
m.Name = chunks[len(chunks)-1]
}
return m, nil
}
func (p *MethodParameter) Signature() string {
typeName := p.TypeName
if strings.HasPrefix(typeName, "tuple") {
// FIXME: Need to be recursive, let's add only once someone request it
componentTypeNames := make([]string, len(p.Components))
for i, component := range p.Components {
componentTypeNames[i] = component.Type
}
typeName = strings.Replace(typeName, "tuple", fmt.Sprintf("(%s)", strings.Join(componentTypeNames, ",")), 1)
}
return typeName
}
type MethodDef struct {
Name string
Parameters []*MethodParameter
ReturnParameters []*MethodParameter
StateMutability StateMutability
}
func MustNewMethodDef(signature string) *MethodDef {
def, err := NewMethodDef(signature)
if err != nil {
panic(fmt.Errorf("invalid method definition %q: %w", signature, err))
}
return def
}
func NewMethodDef(signature string) (*MethodDef, error) {
method, inputs, outputs, err := parseSignature(signature)
if err != nil {
return nil, fmt.Errorf("invalid signature %q: %w", signature, err)
}
return &MethodDef{
Name: method,
Parameters: inputs,
ReturnParameters: outputs,
}, nil
}
// NewCall instantiate a new call from the method definition and uses
// the received arguments as elements used to resolve the parameters
// values.
//
// A call is a particular instance of a Method where ultimately the
// parameters's value will be resolved. A method call in opposition
// to a method definition can be encoded according to Ethereum rules
// or decode data returned for this call against the definition.
func (f *MethodDef) NewCall(args ...interface{}) *MethodCall {
call := &MethodCall{MethodDef: f}
if len(args) > 0 {
call.Data = make([]interface{}, len(args))
}
for i, arg := range args {
call.Data[i] = arg
}
return call
}
// NewCallFromString works exactly like `NewCall`` except that it
// actually assumes all arguments are string version of the actual
// Ethereum types defined by the method and append them to the Data
// slice by calling `AppendArgFromString` which converts the string
// representation to the correct type.
func (f *MethodDef) NewCallFromString(args ...string) *MethodCall {
call := &MethodCall{MethodDef: f}
for _, arg := range args {
call.AppendArgFromString(arg)
}
return call
}
func (f *MethodDef) MethodID() []byte {
return Keccak256([]byte(f.Signature()))[0:4]
}
func (f *MethodDef) Signature() string {
var args []string
for _, parameter := range f.Parameters {
args = append(args, parameter.Signature())
}
return fmt.Sprintf("%s(%s)", f.Name, strings.Join(args, ","))
}
func (f *MethodDef) String() string {
var args []string
for _, parameter := range f.Parameters {
args = append(args, fmt.Sprintf("%s %s", parameter.TypeName, parameter.Name))
}
return fmt.Sprintf("%s(%s)", f.Name, strings.Join(args, ","))
}
func (f *MethodDef) DecodeOutput(data []byte) ([]interface{}, error) {
if len(f.ReturnParameters) == 0 {
return nil, fmt.Errorf("no return parameters defined for method")
}
return NewDecoder(data).ReadOutput(f.ReturnParameters)
}
func (f *MethodDef) DecodeOutputFromString(data string) ([]interface{}, error) {
if len(f.ReturnParameters) == 0 {
return nil, fmt.Errorf("no return parameters defined for method")
}
decoder, err := NewDecoderFromString(data)
if err != nil {
return nil, fmt.Errorf("data is not a valid hexadecimal value")
}
return decoder.ReadOutput(f.ReturnParameters)
}
func (f *MethodDef) DecodeToObjectFromString(data string) (out map[string]interface{}, err error) {
if len(f.ReturnParameters) == 0 {
return nil, fmt.Errorf("no return parameters defined for method")
}
decoder, err := NewDecoderFromString(data)
if err != nil {
return nil, fmt.Errorf("data is not a valid hexadecimal value")
}
values, err := decoder.ReadOutput(f.ReturnParameters)
if err != nil {
return nil, fmt.Errorf("unable to read output")
}
out = make(map[string]interface{})
for i, returnParm := range f.ReturnParameters {
fieldName := returnParm.Name
if fieldName == "" {
if len(f.ReturnParameters) == 1 {
fieldName = f.Name
} else {
fieldName = fmt.Sprintf("%s%d", f.Name, i)
}
}
zlog.Debug("object decoding assigning new field", zap.String("field_name", fieldName), zap.Reflect("value", values[i]))
out[fieldName] = values[i]
}
return out, nil
}
type MethodCall struct {
MethodDef *MethodDef
Data []interface{}
err []error
}
func (f *MethodCall) AppendArgFromString(v string) {
i := len(f.Data)
if i >= len(f.MethodDef.Parameters) {
f.err = append(f.err, fmt.Errorf("args exceeds method definition parameter count %d", len(f.MethodDef.Parameters)))
return
}
param := f.MethodDef.Parameters[i]
out, err := argToDataType(v, param.TypeName, param.Components)
if err != nil {
f.err = append(f.err, fmt.Errorf("invalid string argument %q for parameter %s: %w", param.Name, v, err))
return
}
f.Data = append(f.Data, out)
}
func argToDataType(in interface{}, typeName string, components []*StructComponent) (interface{}, error) {
switch typeName {
case "string":
if v, ok := in.(string); ok {
return v, nil
}
case "bytes":
switch v := in.(type) {
case string:
data, err := NewHex(v)
if err != nil {
return nil, fmt.Errorf("invalid hex: %w", err)
}
return data, nil
case []byte:
return v, nil
}
case "bytes32":
switch v := in.(type) {
case string:
data, err := NewHash(v)
if err != nil {
return nil, fmt.Errorf("invalid bytes32: %w", err)
}
return data, nil
case []byte:
return v, nil
}
case "address[]":
if v, ok := in.(string); ok {
var addrs []Address
err := json.Unmarshal([]byte(v), &addrs)
if err != nil {
return nil, fmt.Errorf("invalid JSON address array: %w", err)
}
return addrs, nil
}
case "address":
switch v := in.(type) {
case string:
addr, err := NewAddress(v)
if err != nil {
return nil, fmt.Errorf("invalid address: %w", err)
}
return addr, nil
case []byte:
return Address(v), nil
}
case "uint8":
switch v := in.(type) {
case string:
var value Uint8
if err := value.UnmarshalText([]byte(v)); err != nil {
return nil, fmt.Errorf("invalid uint8: %w", err)
}
return value, nil
// Type float64 arise when parsing JSON numbers
case float64:
return Uint8(v), nil
}
case "uint16":
switch v := in.(type) {
case string:
var value Uint16
if err := value.UnmarshalText([]byte(v)); err != nil {
return nil, fmt.Errorf("invalid uint16: %w", err)
}
return value, nil
// Type float64 arise when parsing JSON numbers
case float64:
return Uint16(v), nil
}
case "uint24", "uint32":
switch v := in.(type) {
case string:
var value Uint32
if err := value.UnmarshalText([]byte(v)); err != nil {
return nil, fmt.Errorf("invalid %s: %w", typeName, err)
}
return value, nil
// Type float64 arise when parsing JSON numbers
case float64:
return Uint32(v), nil
}
case "uint40", "uint48", "uint56", "uint64":
switch v := in.(type) {
case string:
var value Uint64
if err := value.UnmarshalText([]byte(v)); err != nil {
return nil, fmt.Errorf("invalid %s: %w", typeName, err)
}
return value, nil
// Type float64 arise when parsing JSON numbers
case float64:
return Uint64(v), nil
}
case "uint72", "uint80", "uint88", "uint96", "uint104", "uint112", "uint120", "uint128", "uint136", "uint144", "uint152", "uint160", "uint168", "uint176", "uint184", "uint192", "uint200", "uint208", "uint216", "uint224", "uint232", "uint240", "uint248", "uint256":
switch v := in.(type) {
case string:
out, ok := new(big.Int).SetString(v, 0)
if !ok {
return nil, fmt.Errorf("invalid %s", typeName)
}
return out, nil
// Type float64 arise when parsing JSON numbers
case float64:
return new(big.Int).SetUint64(uint64(v)), nil
}
case "tuple":
switch v := in.(type) {
case string:
var t interface{}
if err := json.Unmarshal([]byte(v), &t); err != nil {
return nil, fmt.Errorf("invalid JSON %w", err)
}
switch vt := t.(type) {
case []interface{}:
return tupleInterfaceSliceToDataType(vt, components)
case map[string]interface{}:
return tupleMapSliceToDataType(vt, components)
default:
return nil, fmt.Errorf("accepting only JSON array or JSON object, got %T", vt)
}
case []interface{}:
return tupleInterfaceSliceToDataType(v, components)
case map[string]interface{}:
return tupleMapSliceToDataType(v, components)
}
case "tuple[]":
switch v := in.(type) {
case string:
var t interface{}
if err := json.Unmarshal([]byte(v), &t); err != nil {
return nil, fmt.Errorf("invalid JSON %w", err)
}
switch vt := t.(type) {
case []interface{}:
return tupleArrayInterfaceSliceToDataType(vt, components)
default:
return nil, fmt.Errorf("accepting only JSON array, got %T", vt)
}
case []interface{}:
return tupleArrayInterfaceSliceToDataType(v, components)
}
case "bool":
return in == "true", nil
default:
return nil, fmt.Errorf("unsupported type %s", typeName)
}
return nil, fmt.Errorf("converting %T to type %s is unsupported", in, typeName)
}
func tupleInterfaceSliceToDataType(in []interface{}, components []*StructComponent) (out interface{}, err error) {
if len(in) != len(components) {
return nil, fmt.Errorf(`input "[]interface{}" value has %d elements, but there is %d struct components`, len(in), len(components))
}
elements := make([]interface{}, len(components))
for i, component := range components {
elements[i], err = argToDataType(in[i], component.Type, nil)
if err != nil {
return nil, fmt.Errorf("unable to transfrom struct component %s from input type %T: %w", component.Name, in[i], err)
}
}
return elements, nil
}
func tupleArrayInterfaceSliceToDataType(in []interface{}, components []*StructComponent) (out interface{}, err error) {
elements := make([]interface{}, len(in))
for i := range in {
elements[i], err = argToDataType(in[i], "tuple", components)
if err != nil {
return nil, fmt.Errorf("unable to transfrom index %d of tuple array from input type %T: %w", i, in[i], err)
}
}
return elements, nil
}
func tupleMapSliceToDataType(in map[string]interface{}, components []*StructComponent) (out interface{}, err error) {
if len(in) != len(components) {
return nil, fmt.Errorf(`input "map[string]interface{}" value has %d elements, but there is %d struct components`, len(in), len(components))
}
i := 0
elements := make([]interface{}, len(components))
for _, component := range components {
fieldIn, found := in[component.Name]
if !found {
return fmt.Errorf(`struct component %s was not found in input "map[string]interface{}" (keys %q)`, component.Name, strings.Join(mapStringInterfaceKeys(in), ", ")), nil
}
elements[i], err = argToDataType(fieldIn, component.Type, nil)
if err != nil {
return nil, fmt.Errorf("unable to transfrom struct component %s from input type %T: %w", component.Name, fieldIn, err)
}
i++
}
return elements, nil
}
func (f *MethodCall) AppendArg(v interface{}) {
f.Data = append(f.Data, v)
}
func (f *MethodCall) MustEncode() []byte {
out, err := f.Encode()
if err != nil {
panic(fmt.Errorf("unable to encode method call: %w", err))
}
return out
}
func (f *MethodCall) Encode() ([]byte, error) {
if len(f.err) > 0 {
return nil, fmt.Errorf("%s", f.err)
}
enc := NewEncoder()
err := enc.WriteMethodCall(f)
if err != nil {
return nil, err
}
return enc.Buffer(), nil
}
func (f *MethodCall) MarshalJSONRPC() ([]byte, error) {
if len(f.err) > 0 {
return nil, fmt.Errorf("%s", f.err)
}
enc := Encoder{}
err := enc.WriteMethodCall(f)
if err != nil {
return nil, err
}
return []byte(`"0x` + enc.String() + `"`), nil
}
var identifierPart = `([a-zA-Z$_][a-zA-Z0-9$_]*)`
var methodRegex = regexp.MustCompile(identifierPart + `\(` + `([^\)]*)` + `\)` + `\s*(returns)?\s*` + `(\(` + `([^\)]*)` + `\))?`)
var methodRegexGroupCount = 6
func parseSignature(signature string) (method string, inputs []*MethodParameter, outputs []*MethodParameter, err error) {
matches := methodRegex.FindAllStringSubmatch(signature, 1)
if len(matches) == 0 {
return "", nil, nil, fmt.Errorf("invalid signature: %s", signature)
}
match := matches[0]
if tracer.Enabled() {
zlog.Debug("got a match for signature", zap.Int("count", len(match)), zap.Strings("groups", match))
}
if len(match) != methodRegexGroupCount {
panic(fmt.Errorf("method regex was modified without updating code, expected %d groups, got %d", methodRegexGroupCount, len(match)))
}
method = match[1]
inputList := match[2]
if inputList != "" {
inputs = parseParameterList(inputList)
}
returnsList := match[5]
if returnsList != "" {
outputs = parseParameterList(returnsList)
}
return
}
var typeNamePart = `(([a-z0-9]+)(\s+(payable|calldata|memory|storage))?(\[\])?)`
var parameterRegex = regexp.MustCompile(typeNamePart + `(\s+` + identifierPart + `)?`)
var parameterRegexGroupCount = 8
func parseParameterList(list string) (out []*MethodParameter) {
matches := parameterRegex.FindAllStringSubmatch(list, math.MaxInt64)
if len(matches) <= 0 {
return nil
}
out = make([]*MethodParameter, len(matches))
for i, match := range matches {
if tracer.Enabled() {
zlog.Debug("got a match for parameter", zap.Int("count", len(match)), zap.Strings("groups", match))
}
if len(match) != parameterRegexGroupCount {
panic(fmt.Errorf("parameter regex was modified without updating code, expected %d groups, got %d", parameterRegexGroupCount, len(match)))
}
parameter := &MethodParameter{TypeName: match[2], Payable: match[4] == "payable"}
if match[5] != "" {
parameter.TypeName += "[]"
}
if match[7] != "" {
parameter.Name = match[7]
}
out[i] = parameter
}
return
}