-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathinput.go
71 lines (59 loc) · 1.98 KB
/
input.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
package abiutil
import (
"fmt"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
)
const selectorLength = 4
// UnpackInputDataToInterface unpacks input data to interface.
func UnpackInputDataToInterface(v interface{}, input []byte, metadata *bind.MetaData) error {
abiData, err := metadata.GetAbi()
if err != nil {
return fmt.Errorf("failed to get abiData: %w", err)
}
method, err := getMethod(input, abiData)
if err != nil {
return fmt.Errorf("failed to get method by id: %w", err)
}
inputs, err := method.Inputs.Unpack(input[selectorLength:])
if err != nil {
return fmt.Errorf("failed to unpack inputs: %w", err)
}
err = method.Inputs.Copy(v, inputs)
if err != nil {
return fmt.Errorf("failed to copy inputs: %w", err)
}
return nil
}
// UnpackInputData takes a function name and a pointer to a `bind.MetaData` object,.
func UnpackInputData(input []byte, metadata *bind.MetaData) ([]interface{}, error) {
abiData, err := metadata.GetAbi()
if err != nil {
return nil, fmt.Errorf("failed to get abiData: %w", err)
}
method, err := getMethod(input, abiData)
if err != nil {
return nil, fmt.Errorf("failed to get method by id: %w", err)
}
res, err := method.Inputs.Unpack(input[selectorLength:])
if err != nil {
return nil, fmt.Errorf("failed to unpack inputs: %w", err)
}
return res, nil
}
// getMethod takes a function name and a pointer to a `bind.MetaData` object,
// and returns the `abi.Method` object for that function.
// If the function is not found, an error is returned.
func getMethod(input []byte, abiData *abi.ABI) (*abi.Method, error) {
if len(input) < selectorLength {
return nil, fmt.Errorf("input too short")
}
// get the selector from the input, this will be the first 4 bytes
selector := [selectorLength]byte{}
copy(selector[:], input[:selectorLength])
method, err := abiData.MethodById(selector[:])
if err != nil {
return nil, fmt.Errorf("failed to get method by id: %w", err)
}
return method, nil
}