/
contract_store.go
112 lines (99 loc) · 2.64 KB
/
contract_store.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
package seth
import (
"os"
"path/filepath"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
)
const (
ErrOpenABIFile = "failed to open ABI file"
ErrParseABI = "failed to parse ABI file"
ErrOpenBINFile = "failed to open BIN file"
)
// ContractStore contains all ABIs that are used in decoding. It might also contain contract bytecode for deployment
type ContractStore struct {
ABIs ABIStore
BINs map[string][]byte
}
type ABIStore map[string]abi.ABI
func (c *ContractStore) GetABI(name string) (*abi.ABI, bool) {
if !strings.HasSuffix(name, ".abi") {
name = name + ".abi"
}
abi, ok := c.ABIs[name]
return &abi, ok
}
func (c *ContractStore) AddABI(name string, abi abi.ABI) {
if !strings.HasSuffix(name, ".abi") {
name = name + ".abi"
}
c.ABIs[name] = abi
}
func (c *ContractStore) GetBIN(name string) ([]byte, bool) {
if !strings.HasSuffix(name, ".bin") {
name = name + ".bin"
}
bin, ok := c.BINs[name]
return bin, ok
}
func (c *ContractStore) AddBIN(name string, bin []byte) {
if !strings.HasSuffix(name, ".bin") {
name = name + ".bin"
}
c.BINs[name] = bin
}
// NewContractStore creates a new Contract store
func NewContractStore(abiPath, binPath string) (*ContractStore, error) {
cs := &ContractStore{ABIs: make(ABIStore), BINs: make(map[string][]byte)}
if abiPath != "" {
files, err := os.ReadDir(abiPath)
if err != nil {
return nil, err
}
var foundABI bool
for _, f := range files {
if strings.HasSuffix(f.Name(), ".abi") {
L.Debug().Str("File", f.Name()).Msg("ABI file loaded")
ff, err := os.Open(filepath.Join(abiPath, f.Name()))
if err != nil {
return nil, errors.Wrap(err, ErrOpenABIFile)
}
a, err := abi.JSON(ff)
if err != nil {
return nil, errors.Wrap(err, ErrParseABI)
}
cs.ABIs[f.Name()] = a
foundABI = true
}
}
if !foundABI {
L.Warn().Msg("No ABI files found")
L.Warn().Msg("You will need to provide the bytecode manually, when deploying contracts")
}
}
if binPath != "" {
files, err := os.ReadDir(binPath)
if err != nil {
return nil, err
}
var foundBIN bool
for _, f := range files {
if strings.HasSuffix(f.Name(), ".bin") {
L.Debug().Str("File", f.Name()).Msg("BIN file loaded")
bin, err := os.ReadFile(filepath.Join(binPath, f.Name()))
if err != nil {
return nil, errors.Wrap(err, ErrOpenBINFile)
}
cs.BINs[f.Name()] = common.FromHex(string(bin))
foundBIN = true
}
}
if !foundBIN {
L.Warn().Msg("No BIN files found")
L.Warn().Msg("You will need to provide the bytecode manually, when deploying contracts")
}
}
return cs, nil
}