-
Notifications
You must be signed in to change notification settings - Fork 0
/
restake_manager.go
469 lines (390 loc) · 12.6 KB
/
restake_manager.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package restake
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
"github.com/tessellated-io/healthchecks/health"
"github.com/tessellated-io/pickaxe/arrays"
chainregistry "github.com/tessellated-io/pickaxe/cosmos/chain-registry"
"github.com/tessellated-io/pickaxe/cosmos/rpc"
"github.com/tessellated-io/pickaxe/cosmos/tx"
"github.com/tessellated-io/pickaxe/crypto"
"github.com/tessellated-io/pickaxe/log"
"github.com/tessellated-io/pickaxe/util"
routertypes "github.com/tessellated-io/router/types"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
txauth "github.com/cosmos/cosmos-sdk/x/auth/tx"
)
var (
wg sync.WaitGroup
results RestakeResults = []*RestakeResult{}
)
// A restake client runs restake clients based on configurations in the Restake registry.
type RestakeManager struct {
version string
// Core services
cdc *codec.ProtoCodec
chainRouter routertypes.Router
gasManager tx.GasManager
logger *log.Logger
// Restake services
configurationLoader *configurationLoader
debug_runSync bool
}
func NewRestakeManager(
version string,
configurationLoader *configurationLoader,
logger *log.Logger,
// NOTE: Chain router is injected from cmd so that we can hot swap if needed.
chainRouter routertypes.Router,
// If `true`, run restake synchronously across networks to aid in debugging.
gasManager tx.GasManager,
debug_runSync bool,
) (*RestakeManager, error) {
cdc := getCodec()
restakeManager := &RestakeManager{
version: version,
cdc: cdc,
chainRouter: chainRouter,
gasManager: gasManager,
logger: logger,
configurationLoader: configurationLoader,
debug_runSync: debug_runSync,
}
return restakeManager, nil
}
func (rm *RestakeManager) Start(ctx context.Context) {
rm.logger.Debug().Msg("starting restake")
// Run immediately, initially.
nextRunTime := time.Now()
for {
// Sleep until the next run time.
timeToNextRun := time.Until(nextRunTime)
rm.logger.Info().Time("next_run_time", nextRunTime).Str("time_to_next_run", timeToNextRun.String()).Msg("waiting for next run")
time.Sleep(timeToNextRun)
// Reload the config
localConfiguration := rm.mustLoadConfig()
// Calculate the run deadline
nextRunTime = time.Now().Add(localConfiguration.RunInterval())
deadlineContext, cancelFunc := context.WithDeadline(ctx, nextRunTime)
// Monitor balances
rm.runOnce(deadlineContext, localConfiguration)
// Cancel the context.
cancelFunc()
}
}
func (rm *RestakeManager) runOnce(ctx context.Context, localConfiguration *Configuration) {
var err error
defer func() {
// Log errors, if one has been populated
if err != nil {
rm.logger.Error().Err(err).Msg("encountered error in restaking run.")
} else {
rm.logger.Info().Msg("finished a monitoring run.")
}
}()
rm.logger.Debug().Msg("starting core restake loop")
// Retryable chain registry client
rawChainClient := chainregistry.NewChainRegistryClient(rm.logger, localConfiguration.ChainRegistryBaseUrl, localConfiguration.ValidatorRegistryBaseUrl)
chainRegistryClient, err := chainregistry.NewRetryableChainRegistryClient(
localConfiguration.NetworkRetryAttempts,
localConfiguration.NetworkRetryDelay(),
rawChainClient,
rm.logger,
)
if err != nil {
rm.logger.Error().Err(err).Msg("unable to create a chain registry client")
return
}
rm.logger.Debug().Msg("created chain registry client")
// Load Restake Configuration from registry
registryConfiguration, err := chainRegistryClient.Validator(ctx, localConfiguration.TargetValidator)
if err != nil {
rm.logger.Error().Err(err).Msg("failed to load configuration from Restake's validator registry")
return
}
rm.logger.Debug().Int("registry_count", len(registryConfiguration.Chains)).Msg("loaded restake registry data")
// Filter networks marked to ignore
ignoreChainNames := localConfiguration.Ignores
restakeChains := []chainregistry.RestakeInfo{}
for _, chain := range registryConfiguration.Chains {
shouldIgnore := false
for _, ignore := range ignoreChainNames {
if strings.EqualFold(chain.Name, ignore) {
rm.logger.Info().Str("chain_id", chain.Name).Msg("ignoring chain due to configuration file")
shouldIgnore = true
}
}
if !shouldIgnore {
restakeChains = append(restakeChains, chain)
}
}
rm.logger.Debug().Int("chain_count", len(restakeChains)).Msg("determined chains to restake")
// Run for each network
results = []*RestakeResult{}
for _, restakeChain := range restakeChains {
wg.Add(1)
// Print results whenever they all finish
// Do this async so that the time.sleep() below tracks time correctly
if rm.debug_runSync {
rm.logger.Debug().Msg("running restake synchronously for debugging")
rm.runRestakeForNetwork(
ctx,
localConfiguration,
restakeChain,
chainRegistryClient,
)
rm.logger.Debug().Msg("synchronously running runRestakeForNetwork has finished")
} else {
go rm.runRestakeForNetwork(
ctx,
localConfiguration,
restakeChain,
chainRegistryClient,
)
}
}
// Wait until all jobs time out, or finish
rm.logger.Debug().Msg("all jobs kicked off")
wg.Wait()
rm.logger.Debug().Msg("all jobs finished")
rm.waitForAndPrintResults()
}
// NOTE: This thread should be run from a goroutine, unless in debug mode.
func (rm *RestakeManager) waitForAndPrintResults() {
wg.Wait()
printResults(results, rm.logger)
}
// NOTE: This thread should be run from a goroutine, unless in debug mode.
func (rm *RestakeManager) runRestakeForNetwork(
ctx context.Context,
localConfiguration *Configuration,
restakeChain chainregistry.RestakeInfo,
chainRegistryClient chainregistry.ChainRegistryClient,
) {
// Results from the run
var txHashes []string
var err error
defer func() {
// Ensure we didn't crash from panic
recoveredErr := recover()
if recoveredErr != nil {
err = util.InterfaceToError(recoveredErr)
}
if err != nil {
rm.logger.Error().Err(err).Str("chain_id", restakeChain.Name).Msg("restake failed with error")
}
// Add results
result := &RestakeResult{
network: restakeChain.Name,
txHashes: txHashes,
err: err,
}
results = append(results, result)
// Send health check if enabled
if !strings.EqualFold(localConfiguration.HealthChecksPingKey, "") {
healthClient := health.NewHealthClient(rm.logger, localConfiguration.HealthChecksPingKey, true)
if err == nil {
err = healthClient.SendSuccess(restakeChain.Name)
} else {
err = healthClient.SendFailure(restakeChain.Name)
}
if err != nil {
rm.logger.Error().Err(err).Str("chain_id", restakeChain.Name).Msg("unable to send healthchecks ping")
}
} else {
rm.logger.Info().Str("chain_id", restakeChain.Name).Msg("not sending healthchecks.io pings as they are disabled in config.")
}
// Leave wait group
defer wg.Done()
}()
prefixedLogger := rm.logger.ApplyPrefix(fmt.Sprintf("[%s]", restakeChain.Name))
prefixedLogger.Info().Str("chain_name", restakeChain.Name).Msg("starting restake for network")
// Get the chain info
prefixedLogger.Info().Str("chain_name", restakeChain.Name).Msg("fetching chain registry data for chain...")
var chainInfo *chainregistry.ChainInfo
chainInfo, err = chainRegistryClient.ChainInfo(ctx, restakeChain.Name)
if err != nil {
return
}
// Derive info needed about the chain
chainID := chainInfo.ChainID
var stakingDenom string
stakingDenom, err = chainInfo.StakingDenom()
if err != nil {
prefixedLogger.Error().Err(err).Str("chain_name", restakeChain.Name).Msg("failed to get staking denom")
return
}
var minimumRequiredReward math.LegacyDec
minimumRequiredReward, err = math.LegacyNewDecFromStr(restakeChain.Restake.MinimumReward.String())
if err != nil {
prefixedLogger.Error().Err(err).Str("chain_name", restakeChain.Name).Str("minimum_reward", restakeChain.Restake.MinimumReward.String()).Msg("failed to parse minimum reward")
return
}
var feeDenom string
feeDenom, err = chainInfo.FeeDenom()
if err != nil {
return
}
// Derive info needed about Restake
validatorAddress := restakeChain.Address
botAddress := restakeChain.Restake.Address
// Fetch the asset list for the chain
var assetList *chainregistry.AssetList
assetList, err = chainRegistryClient.AssetList(ctx, restakeChain.Name)
if err != nil {
return
}
// Set minimum bot balance to be 1 fee token.
var minimumRequiredBotBalance *sdk.Coin
minimumRequiredBotBalance, err = assetList.OneToken(feeDenom)
if err != nil {
return
}
prefixedLogger.Info().Str("chain_name", restakeChain.Name).Msg("finished fetching chain registry data")
// Get an endpoint from the Router
var grpcEndpoint string
grpcEndpoint, err = rm.chainRouter.GrpcEndpoint(chainInfo.ChainID)
if err != nil {
return
}
// Bind up an RPC Client with some retries
var rawRpcClient rpc.RpcClient
rawRpcClient, err = rpc.NewGrpcClient(grpcEndpoint, cdc, prefixedLogger)
if err != nil {
return
}
var rpcClient rpc.RpcClient
rpcClient, err = rpc.NewRetryableRpcClient(
localConfiguration.NetworkRetryAttempts,
localConfiguration.NetworkRetryDelay(),
rawRpcClient,
prefixedLogger,
)
if err != nil {
return
}
// Create a Grant manager
var grantManager *grantManager
grantManager, err = NewGrantManager(restakeChain.Restake.Address, chainID, prefixedLogger, rpcClient, stakingDenom, validatorAddress)
if err != nil {
return
}
// Create a tx provider
slip44 := uint(chainInfo.Slip44)
var signer crypto.BytesSigner
signer, err = tx.GetSoftSigner(slip44, localConfiguration.BotMnemonic)
if err != nil {
return
}
txConfig := txauth.NewTxConfig(cdc, txauth.DefaultSignModes)
var simulationManager tx.SimulationManager
simulationManager, err = tx.NewSimulationManager(rpcClient, txConfig)
if err != nil {
return
}
var txProvider tx.TxProvider
txProvider, err = tx.NewTxProvider(signer, chainID, feeDenom, localConfiguration.VersionedMemo(rm.version), prefixedLogger, simulationManager, txConfig)
if err != nil {
return
}
// Create a signing metadata provider
var signingMetadataProvider *tx.SigningMetadataProvider
signingMetadataProvider, err = tx.NewSigningMetadataProvider(chainID, rpcClient)
if err != nil {
return
}
// Create the tx broadcaster
var broadcaster *tx.Broadcaster
broadcaster, err = tx.NewDefaultBroadcaster(
restakeChain.Name,
chainInfo.Bech32Prefix,
signer,
rm.gasManager,
prefixedLogger,
rpcClient,
signingMetadataProvider,
txProvider,
localConfiguration.TxPollAttempts,
localConfiguration.TxPollDelay(),
localConfiguration.NetworkRetryAttempts,
localConfiguration.NetworkRetryDelay(),
)
if err != nil {
return
}
var restakeClient *restakeClient
restakeClient, err = NewRestakeClient(
chainInfo.Bech32Prefix,
chainID,
feeDenom,
stakingDenom,
localConfiguration.BatchSize,
validatorAddress,
botAddress,
minimumRequiredReward,
minimumRequiredBotBalance,
broadcaster,
grantManager,
prefixedLogger,
rpcClient,
signer,
)
if err != nil {
return
}
txHashes, err = restakeClient.restake(ctx)
prefixedLogger.Info().Str("chain_name", restakeChain.Name).Msg("finished restaking")
stringifiedTxHashes := ""
if txHashes != nil {
stringifiedTxHashes = arrays.Reduce(txHashes, func(accumulated, next string) string {
return fmt.Sprintf("%s%s, ", accumulated, next)
}, "")
}
prefixedLogger.Debug().Str("chain_name", restakeChain.Name).Str("tx_hashes", stringifiedTxHashes).Err(err).Msg("verbose restake results")
}
// Results of running Restake on a given network
type RestakeResult struct {
network string
txHashes []string
err error
}
type RestakeResults []*RestakeResult
func (rr RestakeResults) Len() int { return len(rr) }
func (rr RestakeResults) Swap(i, j int) { rr[i], rr[j] = rr[j], rr[i] }
func (rr RestakeResults) Less(i, j int) bool { return rr[i].network < rr[j].network }
func printResults(results RestakeResults, log *log.Logger) {
sort.Sort(results)
log.Info().Msg("Restake Results:")
for _, result := range results {
if result.err == nil {
txHashes := zerolog.Arr()
for _, txHash := range result.txHashes {
txHashes.Str(txHash)
}
msg := fmt.Sprintf("✅ %s: Success", result.network)
if len(result.txHashes) == 0 {
msg = fmt.Sprintf("%s | 😬 No transactions sent. The restake website may mark you as offline.", msg)
}
log.Info().Array("tx_hashes", txHashes).Msg(msg)
} else {
log.Error().Err(result.err).Msg(fmt.Sprintf("❌ %s: Failure", result.network))
}
}
}
func (rm *RestakeManager) mustLoadConfig() *Configuration {
for {
config, err := rm.configurationLoader.LoadConfiguration()
if err == nil {
return config
}
rm.logger.Error().Err(err).Msg("error reloading config. trying again...")
time.Sleep(30 * time.Second)
}
}