-
Notifications
You must be signed in to change notification settings - Fork 40
/
contract_map.go
119 lines (97 loc) · 2.19 KB
/
contract_map.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
package seth
import (
"io"
"os"
"strings"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/pelletier/go-toml/v2"
)
type ContractMap struct {
mu *sync.RWMutex
addressMap map[string]string
}
func NewEmptyContractMap() ContractMap {
return ContractMap{
mu: &sync.RWMutex{},
addressMap: map[string]string{},
}
}
func NewContractMap(contracts map[string]string) ContractMap {
return ContractMap{
mu: &sync.RWMutex{},
addressMap: contracts,
}
}
func (c ContractMap) GetContractMap() map[string]string {
return c.addressMap
}
func (c ContractMap) IsKnownAddress(addr string) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.addressMap[strings.ToLower(addr)] != ""
}
func (c ContractMap) GetContractName(addr string) string {
c.mu.Lock()
defer c.mu.Unlock()
return c.addressMap[strings.ToLower(addr)]
}
func (c ContractMap) GetContractAddress(addr string) string {
if addr == UNKNOWN {
return UNKNOWN
}
c.mu.Lock()
defer c.mu.Unlock()
for k, v := range c.addressMap {
if v == addr {
return k
}
}
return UNKNOWN
}
func (c ContractMap) AddContract(addr, name string) {
if addr == UNKNOWN {
return
}
name = strings.TrimSuffix(name, ".abi")
c.mu.Lock()
defer c.mu.Unlock()
c.addressMap[strings.ToLower(addr)] = name
}
func (c ContractMap) Size() int {
return len(c.addressMap)
}
func SaveDeployedContract(filename, contractName, address string) error {
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer file.Close()
v := map[string]string{
address: contractName,
}
marhalled, err := toml.Marshal(v)
if err != nil {
return err
}
_, err = file.WriteString(string(marhalled))
return err
}
func LoadDeployedContracts(filename string) (map[string]string, error) {
tomlFile, err := os.Open(filename)
if err != nil {
return map[string]string{}, nil
}
defer tomlFile.Close()
b, _ := io.ReadAll(tomlFile)
rawContracts := map[common.Address]string{}
err = toml.Unmarshal(b, &rawContracts)
if err != nil {
return map[string]string{}, err
}
contracts := map[string]string{}
for k, v := range rawContracts {
contracts[k.Hex()] = v
}
return contracts, nil
}