Skip to content

Commit 0806d3d

Browse files
committed
fix(lib/contracts): add mutex to caches
1 parent 58ef5e2 commit 0806d3d

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

lib/contracts/address.go

+22-6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package contracts
33
import (
44
"context"
55
"math/big"
6+
"sync"
67

78
"github.com/omni-network/omni/e2e/app/eoa"
89
"github.com/omni-network/omni/lib/create3"
@@ -94,17 +95,29 @@ type Salts struct {
9495
Token string
9596
}
9697

98+
type cache[T any] struct {
99+
mu sync.Mutex
100+
cache T
101+
}
102+
97103
var (
98104
// cached addresses by network.
99-
addrsCache = map[netconf.ID]Addresses{}
105+
addrsCache = cache[map[netconf.ID]Addresses]{
106+
cache: map[netconf.ID]Addresses{},
107+
}
100108

101109
// cached salts by network.
102-
saltsCache = map[netconf.ID]Salts{}
110+
saltsCache = cache[map[netconf.ID]Salts]{
111+
cache: map[netconf.ID]Salts{},
112+
}
103113
)
104114

105115
// GetAddresses returns the contract addresses for the given network.
106116
func GetAddresses(ctx context.Context, network netconf.ID) (Addresses, error) {
107-
addrs, ok := addrsCache[network]
117+
addrsCache.mu.Lock()
118+
defer addrsCache.mu.Unlock()
119+
120+
addrs, ok := addrsCache.cache[network]
108121
if ok {
109122
return addrs, nil
110123
}
@@ -124,14 +137,17 @@ func GetAddresses(ctx context.Context, network netconf.ID) (Addresses, error) {
124137
GasStation: gasStation(network, ver),
125138
}
126139

127-
addrsCache[network] = addrs
140+
addrsCache.cache[network] = addrs
128141

129142
return addrs, nil
130143
}
131144

132145
// GetSalts returns the contract salts for the given network.
133146
func GetSalts(ctx context.Context, network netconf.ID) (Salts, error) {
134-
salts, ok := saltsCache[network]
147+
saltsCache.mu.Lock()
148+
defer saltsCache.mu.Unlock()
149+
150+
salts, ok := saltsCache.cache[network]
135151
if ok {
136152
return salts, nil
137153
}
@@ -150,7 +166,7 @@ func GetSalts(ctx context.Context, network netconf.ID) (Salts, error) {
150166
GasStation: gasStationSalt(network, ver),
151167
}
152168

153-
saltsCache[network] = salts
169+
saltsCache.cache[network] = salts
154170

155171
return salts, nil
156172
}

0 commit comments

Comments
 (0)