-
Notifications
You must be signed in to change notification settings - Fork 0
/
gas.go
342 lines (267 loc) · 8.85 KB
/
gas.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package tx
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"sync"
"github.com/tessellated-io/pickaxe/log"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
)
// GasManager interprets tx results and associated outcomes.
type GasManager interface {
InitializePrice(chainName string, gasPrice float64) error
// Get a suggested gas price for the chainName
GetGasPrice(chainName string) (float64, error)
// Get a gas factor for the chain name
GetGasFactor(chainName string) (float64, error)
// Given a broadcast result for a chainName, update gas prices. Calling with a successful broadcast result is a no-op. Tally successes
// using ManageTransactionStatus.
ManageFailingBroadcastResult(chainName string, broadcastResult *txtypes.BroadcastTxResponse) error
// Manage a transaction status once it has settled on chain. Statuses could be positive or negative.
ManageIncludedTransactionStatus(chainName string, txStatus *txtypes.GetTxResponse) error
// Manage a failure in the case a tx was successfully broadcasted, but never landed on chain and we thus are unable to provide a tx status
ManageInclusionFailure(chainName string) error
}
// GasPriceProvider is a simple KV store for gas.
type GasPriceProvider interface {
HasGasPrice(chainName string) (bool, error)
GetGasPrice(chainName string) (float64, error)
SetGasPrice(chainName string, gasPrice float64) error
HasGasFactor(chainName string) (bool, error)
GetGasFactor(chainName string) (float64, error)
SetGasFactor(chainName string, gasFactor float64) error
getGasData() (*GasData, error)
}
// InMemoryGasPriceProvider stores gas prices in memory.
type InMemoryGasPriceProvider struct {
prices map[string]float64
factors map[string]float64
lock *sync.Mutex
}
var _ GasPriceProvider = (*InMemoryGasPriceProvider)(nil)
func NewInMemoryGasPriceProvider() (GasPriceProvider, error) {
provider := &InMemoryGasPriceProvider{
prices: make(map[string]float64),
factors: make(map[string]float64),
lock: &sync.Mutex{},
}
return provider, nil
}
func (gp *InMemoryGasPriceProvider) HasGasPrice(chainName string) (bool, error) {
gp.lock.Lock()
defer gp.lock.Unlock()
_, found := gp.prices[chainName]
return found, nil
}
func (gp *InMemoryGasPriceProvider) GetGasPrice(chainName string) (float64, error) {
gp.lock.Lock()
defer gp.lock.Unlock()
gasPrice, found := gp.prices[chainName]
if !found {
return 0, ErrNoGasPrice
}
return gasPrice, nil
}
func (gp *InMemoryGasPriceProvider) SetGasPrice(chainName string, gasPrice float64) error {
gp.lock.Lock()
defer gp.lock.Unlock()
gp.prices[chainName] = gasPrice
return nil
}
func (gp *InMemoryGasPriceProvider) HasGasFactor(chainName string) (bool, error) {
gp.lock.Lock()
defer gp.lock.Unlock()
_, found := gp.factors[chainName]
return found, nil
}
func (gp *InMemoryGasPriceProvider) GetGasFactor(chainName string) (float64, error) {
gp.lock.Lock()
defer gp.lock.Unlock()
gasFactor, found := gp.factors[chainName]
if !found {
return 0, ErrNoGasFactor
}
return gasFactor, nil
}
func (gp *InMemoryGasPriceProvider) SetGasFactor(chainName string, gasFactor float64) error {
gp.lock.Lock()
defer gp.lock.Unlock()
gp.factors[chainName] = gasFactor
return nil
}
func (gp *InMemoryGasPriceProvider) getGasData() (*GasData, error) {
gp.lock.Lock()
defer gp.lock.Unlock()
gasPrices := make(map[string]float64)
for chainName, price := range gp.prices {
gasPrices[chainName] = price
}
gasFactors := make(map[string]float64)
for chainName, factor := range gp.factors {
gasFactors[chainName] = factor
}
gasData := &GasData{
GasPrices: gasPrices,
GasFactors: gasFactors,
}
return gasData, nil
}
// Helper function to know if an error had to do with gas.
func IsGasRelatedError(codespace string, code uint32) bool {
return IsGasPriceError(codespace, code) || isGasAmountError(codespace, code)
}
// Helper function to determine if an error is related to too small of a gas price
func IsGasPriceError(codespace string, code uint32) bool {
return (codespace == "sdk" && code == 13) || (codespace == "gaia" && code == 4)
}
// Helper function to determine if an error is related to to few gas units
func isGasAmountError(codespace string, code uint32) bool {
return (codespace == "sdk" && code == 11)
}
// extractMinGlobalFee is basically a kludge for Evmos, and EIP-1559.
func extractMinGlobalFee(errMsg string) (float64, error) {
// Regular expression to match the desired number
pattern := `(\d+)\w+\)\. Please increase`
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(errMsg)
if len(matches) > 1 {
converted, err := strconv.Atoi(matches[1])
if err != nil {
return 0, err
}
return float64(converted), nil
}
return 0, fmt.Errorf("unrecognized error format")
}
// FileGasPriceProvider writes gas prices to a file by internally wrapping calls to an InMemoryGasPriceProvider.
type FileGasPriceProvider struct {
wrapped GasPriceProvider
logger *log.Logger
gasDataFile string
lock *sync.Mutex
}
// gasDataFile is the file name inside the data directory
const gasDataFile = "gas_prices.json"
// Assert all FileGasPriceProvider are GasPriceProviders
var _ GasPriceProvider = (*FileGasPriceProvider)(nil)
// Data format for gas file.
type GasData struct {
GasFactors map[string]float64 `json:"gas_factors"`
GasPrices map[string]float64 `json:"gas_prices"`
}
// Create a new FileGasProvider which will wrap an in-memory gas price provider
func NewFileGasPriceProvider(logger *log.Logger, dataDirectory string) (GasPriceProvider, error) {
// Wrap an in memory provider, so that the logic is reused
// TODO: InMemoryGasPriceProvider should probably be renamed to BaseGasPriceProvider
wrapped, err := NewInMemoryGasPriceProvider()
if err != nil {
return nil, err
}
// Create a provider
gasDataFile := fmt.Sprintf("%s/%s", dataDirectory, gasDataFile)
provider := &FileGasPriceProvider{
wrapped: wrapped,
logger: logger,
gasDataFile: gasDataFile,
lock: &sync.Mutex{},
}
// Initialize the wrapped provider.
err = provider.initialize()
if err != nil {
return nil, err
}
return provider, nil
}
func (p *FileGasPriceProvider) HasGasPrice(chainName string) (bool, error) {
return p.wrapped.HasGasPrice(chainName)
}
func (p *FileGasPriceProvider) GetGasPrice(chainName string) (float64, error) {
return p.wrapped.GetGasPrice(chainName)
}
func (p *FileGasPriceProvider) SetGasPrice(chainName string, gasPrice float64) error {
p.lock.Lock()
defer p.lock.Unlock()
err := p.wrapped.SetGasPrice(chainName, gasPrice)
if err != nil {
return err
}
return p.writeToFile()
}
func (p *FileGasPriceProvider) HasGasFactor(chainName string) (bool, error) {
return p.wrapped.HasGasFactor(chainName)
}
func (p *FileGasPriceProvider) GetGasFactor(chainName string) (float64, error) {
return p.wrapped.GetGasFactor(chainName)
}
func (p *FileGasPriceProvider) SetGasFactor(chainName string, gasFactor float64) error {
p.lock.Lock()
defer p.lock.Unlock()
err := p.wrapped.SetGasFactor(chainName, gasFactor)
if err != nil {
return err
}
return p.writeToFile()
}
func (p *FileGasPriceProvider) getGasData() (*GasData, error) {
return p.wrapped.getGasData()
}
func (p *FileGasPriceProvider) writeToFile() error {
gasData, err := p.getGasData()
if err != nil {
return err
}
jsonBytes, err := json.MarshalIndent(gasData, "", " ")
if err != nil {
return err
}
err = os.WriteFile(p.gasDataFile, jsonBytes, 0o600)
if err != nil {
return err
}
p.logger.Info().Str("file", p.gasDataFile).Msg("💾 saved gas prices to disk")
return nil
}
// Initialize the wrapped provider with data from a file.
func (p *FileGasPriceProvider) initialize() error {
p.logger.Info().Str("file", p.gasDataFile).Msg("💾 initializing gas prices from disk")
gasData, err := p.loadData()
if err != nil {
return err
}
for chainName, gasFactor := range gasData.GasFactors {
err := p.wrapped.SetGasFactor(chainName, gasFactor)
if err != nil {
return err
}
p.logger.Info().Str("chain_name", chainName).Float64("gas_factor", gasFactor).Msg("💾 initialized gas factor")
}
for chainName, gasPrice := range gasData.GasPrices {
err := p.wrapped.SetGasPrice(chainName, gasPrice)
if err != nil {
return err
}
p.logger.Info().Str("chain_name", chainName).Float64("gas_price", gasPrice).Msg("💾 initialized gas price")
}
p.logger.Info().Str("file", p.gasDataFile).Msg("gas price state initialization complete")
return nil
}
// Load data from the file
func (p *FileGasPriceProvider) loadData() (*GasData, error) {
_, err := os.Stat(p.gasDataFile)
if os.IsNotExist(err) {
p.logger.Info().Str("file", p.gasDataFile).Msg("💾 no gas price cache found on disk. will not initialize.")
return &GasData{}, nil
}
file, err := os.Open(p.gasDataFile)
if err != nil {
return nil, err
}
defer file.Close()
gasData := &GasData{}
if err := json.NewDecoder(file).Decode(gasData); err != nil {
return nil, err
}
return gasData, nil
}