-
Notifications
You must be signed in to change notification settings - Fork 88
/
abi_wrapper.go
78 lines (69 loc) · 1.64 KB
/
abi_wrapper.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
package web3
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/gochain/gochain/v4/accounts/abi"
"github.com/gochain/web3/assets"
)
// GetABI accepts either built in contracts (erc20, erc721), a file location or a URL
func GetABI(abiFile string) (*abi.ABI, error) {
abi, err := ABIBuiltIn(abiFile)
if err != nil {
return nil, fmt.Errorf("Cannot get ABI from the bundled storage: %v", err)
}
if abi != nil {
return abi, nil
}
abi, err = ABIOpenFile(abiFile)
if err == nil {
return abi, nil
}
// else most likely just not found, log it?
abi, err = ABIOpenURL(abiFile)
if err == nil {
return abi, nil
}
return nil, err
}
func ABIBuiltIn(abiFile string) (*abi.ABI, error) {
if val, ok := bundledContracts[abiFile]; ok {
return readAbi(strings.NewReader(val))
}
return nil, nil
}
func ABIOpenFile(abiFile string) (*abi.ABI, error) {
jsonReader, err := os.Open(abiFile)
if err != nil {
return nil, err
}
return readAbi(jsonReader)
}
func ABIOpenURL(abiFile string) (*abi.ABI, error) {
resp, err := http.Get(abiFile)
if err != nil {
return nil, fmt.Errorf("error getting ABI: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("error getting ABI %v: %v", resp.StatusCode, string(bodyBytes))
}
return readAbi(resp.Body)
}
func readAbi(reader io.Reader) (*abi.ABI, error) {
abi, err := abi.JSON(reader)
if err != nil {
return nil, err
}
return &abi, nil
}
var bundledContracts = map[string]string{
"erc20": assets.ERC20ABI,
"erc721": assets.ERC721ABI}