-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
registry.go
625 lines (544 loc) · 20.7 KB
/
registry.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package evm
import (
"context"
goerrors "errors"
"fmt"
"math/big"
"net/http"
"sync"
"time"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
coreTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/smartcontractkit/chainlink-common/pkg/services"
ocr2keepers "github.com/smartcontractkit/chainlink-automation/pkg/v3/types"
"github.com/smartcontractkit/chainlink/v2/core/chains/evm/client"
"github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller"
"github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm"
"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated"
iregistry21 "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/i_keeper_registry_master_wrapper_2_1"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/models"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/core"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/mercury/streams"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
const (
defaultPluginRetryExpiration = 30 * time.Minute
// defaultAllowListExpiration decides how long an upkeep's allow list info will be valid for.
defaultAllowListExpiration = 10 * time.Minute
// cleanupInterval decides when the expired items in cache will be deleted.
cleanupInterval = 5 * time.Minute
logTriggerRefreshBatchSize = 32
)
var (
RegistryServiceName = "AutomationRegistry"
ErrLogReadFailure = fmt.Errorf("failure reading logs")
ErrHeadNotAvailable = fmt.Errorf("head not available")
ErrInitializationFailure = fmt.Errorf("failed to initialize registry")
ErrContextCancelled = fmt.Errorf("context was cancelled")
ErrABINotParsable = fmt.Errorf("error parsing abi")
ActiveUpkeepIDBatchSize int64 = 1000
// This is the interval at which active upkeep list is fully refreshed from chain
refreshInterval = 15 * time.Minute
// This is the lookback for polling upkeep state event logs from latest block
logEventLookback int64 = 250
)
//go:generate mockery --quiet --name Registry --output ./mocks/ --case=underscore
type Registry interface {
GetUpkeep(opts *bind.CallOpts, id *big.Int) (encoding.UpkeepInfo, error)
GetState(opts *bind.CallOpts) (iregistry21.GetState, error)
GetActiveUpkeepIDs(opts *bind.CallOpts, startIndex *big.Int, maxCount *big.Int) ([]*big.Int, error)
GetUpkeepPrivilegeConfig(opts *bind.CallOpts, upkeepId *big.Int) ([]byte, error)
GetUpkeepTriggerConfig(opts *bind.CallOpts, upkeepId *big.Int) ([]byte, error)
CheckCallback(opts *bind.CallOpts, id *big.Int, values [][]byte, extraData []byte) (iregistry21.CheckCallback, error)
ParseLog(log coreTypes.Log) (generated.AbigenLog, error)
}
//go:generate mockery --quiet --name HttpClient --output ./mocks/ --case=underscore
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
func NewEvmRegistry(
lggr logger.Logger,
addr common.Address,
client legacyevm.Chain,
registry *iregistry21.IKeeperRegistryMaster,
mc *models.MercuryCredentials,
al ActiveUpkeepList,
logEventProvider logprovider.LogEventProvider,
packer encoding.Packer,
blockSub *BlockSubscriber,
finalityDepth uint32,
) *EvmRegistry {
mercuryConfig := &MercuryConfig{
cred: mc,
Abi: core.StreamsCompatibleABI,
AllowListCache: cache.New(defaultAllowListExpiration, cleanupInterval),
pluginRetryCache: cache.New(defaultPluginRetryExpiration, cleanupInterval),
}
hc := http.DefaultClient
return &EvmRegistry{
ctx: context.Background(),
threadCtrl: utils.NewThreadControl(),
lggr: lggr.Named(RegistryServiceName),
poller: client.LogPoller(),
addr: addr,
client: client.Client(),
logProcessed: make(map[string]bool),
registry: registry,
abi: core.RegistryABI,
active: al,
packer: packer,
headFunc: func(ocr2keepers.BlockKey) {},
chLog: make(chan logpoller.Log, 1000),
hc: hc,
logEventProvider: logEventProvider,
bs: blockSub,
finalityDepth: finalityDepth,
streams: streams.NewStreamsLookup(packer, mercuryConfig, blockSub, client.Client(), registry, lggr),
}
}
var upkeepStateEvents = []common.Hash{
iregistry21.IKeeperRegistryMasterUpkeepRegistered{}.Topic(), // adds new upkeep id to registry
iregistry21.IKeeperRegistryMasterUpkeepReceived{}.Topic(), // adds new upkeep id to registry via migration
iregistry21.IKeeperRegistryMasterUpkeepUnpaused{}.Topic(), // unpauses an upkeep
iregistry21.IKeeperRegistryMasterUpkeepPaused{}.Topic(), // pauses an upkeep
iregistry21.IKeeperRegistryMasterUpkeepMigrated{}.Topic(), // migrated an upkeep, equivalent to cancel from this registry's perspective
iregistry21.IKeeperRegistryMasterUpkeepCanceled{}.Topic(), // cancels an upkeep
iregistry21.IKeeperRegistryMasterUpkeepTriggerConfigSet{}.Topic(), // trigger config was changed
}
type MercuryConfig struct {
cred *models.MercuryCredentials
Abi abi.ABI
// AllowListCache stores the upkeeps privileges. In 2.1, this only includes a JSON bytes for allowed to use mercury
AllowListCache *cache.Cache
pluginRetryCache *cache.Cache
}
func NewMercuryConfig(credentials *models.MercuryCredentials, abi abi.ABI) *MercuryConfig {
return &MercuryConfig{
cred: credentials,
Abi: abi,
AllowListCache: cache.New(defaultPluginRetryExpiration, cleanupInterval),
pluginRetryCache: cache.New(defaultPluginRetryExpiration, cleanupInterval),
}
}
func (c *MercuryConfig) Credentials() *models.MercuryCredentials {
return c.cred
}
func (c *MercuryConfig) IsUpkeepAllowed(k string) (interface{}, bool) {
return c.AllowListCache.Get(k)
}
func (c *MercuryConfig) SetUpkeepAllowed(k string, v interface{}, d time.Duration) {
c.AllowListCache.Set(k, v, d)
}
func (c *MercuryConfig) GetPluginRetry(k string) (interface{}, bool) {
return c.pluginRetryCache.Get(k)
}
func (c *MercuryConfig) SetPluginRetry(k string, v interface{}, d time.Duration) {
c.pluginRetryCache.Set(k, v, d)
}
type EvmRegistry struct {
services.StateMachine
threadCtrl utils.ThreadControl
lggr logger.Logger
poller logpoller.LogPoller
addr common.Address
client client.Client
chainID uint64
registry Registry
abi abi.ABI
packer encoding.Packer
chLog chan logpoller.Log
mu sync.RWMutex
logProcessed map[string]bool
active ActiveUpkeepList
lastPollBlock int64
ctx context.Context
headFunc func(ocr2keepers.BlockKey)
mercury *MercuryConfig
hc HttpClient
bs *BlockSubscriber
logEventProvider logprovider.LogEventProvider
finalityDepth uint32
streams streams.Lookup
}
func (r *EvmRegistry) Name() string {
return r.lggr.Name()
}
func (r *EvmRegistry) Start(ctx context.Context) error {
return r.StartOnce(RegistryServiceName, func() error {
if err := r.registerEvents(r.chainID, r.addr); err != nil {
return fmt.Errorf("logPoller error while registering automation events: %w", err)
}
r.threadCtrl.Go(func(ctx context.Context) {
lggr := r.lggr.With("where", "upkeeps_referesh")
err := r.refreshActiveUpkeeps()
if err != nil {
lggr.Errorf("failed to initialize upkeeps", err)
}
ticker := time.NewTicker(refreshInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
err = r.refreshActiveUpkeeps()
if err != nil {
lggr.Errorf("failed to refresh upkeeps", err)
}
case <-ctx.Done():
return
}
}
})
r.threadCtrl.Go(func(ctx context.Context) {
lggr := r.lggr.With("where", "logs_polling")
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := r.pollUpkeepStateLogs()
if err != nil {
lggr.Errorf("failed to poll logs for upkeeps", err)
}
case <-ctx.Done():
return
}
}
})
r.threadCtrl.Go(func(ctx context.Context) {
lggr := r.lggr.With("where", "logs_processing")
ch := r.chLog
for {
select {
case l := <-ch:
err := r.processUpkeepStateLog(l)
if err != nil {
lggr.Errorf("failed to process log for upkeep", err)
}
case <-ctx.Done():
return
}
}
})
return nil
})
}
func (r *EvmRegistry) Close() error {
return r.StopOnce(RegistryServiceName, func() error {
r.threadCtrl.Close()
return nil
})
}
func (r *EvmRegistry) HealthReport() map[string]error {
return map[string]error{RegistryServiceName: r.Healthy()}
}
func (r *EvmRegistry) refreshActiveUpkeeps() error {
// Allow for max timeout of refreshInterval
ctx, cancel := context.WithTimeout(r.ctx, refreshInterval)
defer cancel()
r.lggr.Debugf("Refreshing active upkeeps list")
// get active upkeep ids from contract
ids, err := r.getLatestIDsFromContract(ctx)
if err != nil {
return fmt.Errorf("failed to get active upkeep ids from contract during refresh: %s", err)
}
r.active.Reset(ids...)
var logTriggerIDs []*big.Int
for _, id := range ids {
uid := &ocr2keepers.UpkeepIdentifier{}
if ok := uid.FromBigInt(id); !ok {
r.lggr.Warnf("failed to parse upkeep id %s", id.String())
continue
}
switch core.GetUpkeepType(*uid) {
case ocr2keepers.LogTrigger:
logTriggerIDs = append(logTriggerIDs, id)
default:
}
}
_, err = r.logEventProvider.RefreshActiveUpkeeps(logTriggerIDs...)
if err != nil {
return fmt.Errorf("failed to refresh active upkeep ids in log event provider: %w", err)
}
// Try to refersh log trigger config for all log upkeeps
return r.refreshLogTriggerUpkeeps(logTriggerIDs)
}
// refreshLogTriggerUpkeeps refreshes the active upkeep ids for log trigger upkeeps
func (r *EvmRegistry) refreshLogTriggerUpkeeps(ids []*big.Int) error {
var err error
for i := 0; i < len(ids); i += logTriggerRefreshBatchSize {
end := i + logTriggerRefreshBatchSize
if end > len(ids) {
end = len(ids)
}
idBatch := ids[i:end]
if batchErr := r.refreshLogTriggerUpkeepsBatch(idBatch); batchErr != nil {
multierr.AppendInto(&err, batchErr)
}
time.Sleep(500 * time.Millisecond)
}
return err
}
func (r *EvmRegistry) refreshLogTriggerUpkeepsBatch(logTriggerIDs []*big.Int) error {
var logTriggerHashes []common.Hash
for _, id := range logTriggerIDs {
logTriggerHashes = append(logTriggerHashes, common.BigToHash(id))
}
unpausedLogs, err := r.poller.IndexedLogs(iregistry21.IKeeperRegistryMasterUpkeepUnpaused{}.Topic(), r.addr, 1, logTriggerHashes, logpoller.Confirmations(r.finalityDepth), pg.WithParentCtx(r.ctx))
if err != nil {
return err
}
configSetLogs, err := r.poller.IndexedLogs(iregistry21.IKeeperRegistryMasterUpkeepTriggerConfigSet{}.Topic(), r.addr, 1, logTriggerHashes, logpoller.Confirmations(r.finalityDepth), pg.WithParentCtx(r.ctx))
if err != nil {
return err
}
logs := append(unpausedLogs, configSetLogs...)
configSetBlockNumbers := map[string]uint64{}
unpausedBlockNumbers := map[string]uint64{}
perUpkeepConfig := map[string][]byte{}
for _, log := range logs {
rawLog := log.ToGethLog()
abilog, err := r.registry.ParseLog(rawLog)
if err != nil {
return err
}
switch l := abilog.(type) {
case *iregistry21.IKeeperRegistryMasterUpkeepTriggerConfigSet:
if rawLog.BlockNumber > configSetBlockNumbers[l.Id.String()] {
configSetBlockNumbers[l.Id.String()] = rawLog.BlockNumber
perUpkeepConfig[l.Id.String()] = l.TriggerConfig
}
case *iregistry21.IKeeperRegistryMasterUpkeepUnpaused:
if rawLog.BlockNumber > unpausedBlockNumbers[l.Id.String()] {
unpausedBlockNumbers[l.Id.String()] = rawLog.BlockNumber
}
}
}
var merr error
for _, id := range logTriggerIDs {
logBlock, ok := configSetBlockNumbers[id.String()]
if !ok {
r.lggr.Warnf("unable to find finalized config set block number for %s, using 0 as config start block", id.String())
// Use zero as config update block so it can be updated if an actual event is found later
logBlock = 0
}
config, ok := perUpkeepConfig[id.String()]
if !ok {
r.lggr.Warnf("unable to find per finalized log config for %s, will fetch latest config from chain", id.String())
// Set it to empty bytes so that latest config is fetched within r.updateTriggerConfig
config = []byte{}
}
// In case an upkeep was paused then unpaused after a config set event, start the config from the unpaused block number
if unpausedBlockNumbers[id.String()] > logBlock {
logBlock = unpausedBlockNumbers[id.String()]
}
if err := r.updateTriggerConfig(id, config, logBlock); err != nil {
merr = goerrors.Join(merr, fmt.Errorf("failed to update trigger config for upkeep id %s: %w", id.String(), err))
}
}
return merr
}
func (r *EvmRegistry) pollUpkeepStateLogs() error {
var latest int64
var end logpoller.LogPollerBlock
var err error
if end, err = r.poller.LatestBlock(pg.WithParentCtx(r.ctx)); err != nil {
return fmt.Errorf("%w: %s", ErrHeadNotAvailable, err)
}
r.mu.Lock()
latest = r.lastPollBlock
r.lastPollBlock = end.BlockNumber
r.mu.Unlock()
// if start and end are the same, no polling needs to be done
if latest == 0 || latest == end.BlockNumber {
return nil
}
var logs []logpoller.Log
if logs, err = r.poller.LogsWithSigs(
end.BlockNumber-logEventLookback,
end.BlockNumber,
upkeepStateEvents,
r.addr,
pg.WithParentCtx(r.ctx),
); err != nil {
return fmt.Errorf("%w: %s", ErrLogReadFailure, err)
}
for _, log := range logs {
r.chLog <- log
}
return nil
}
func (r *EvmRegistry) processUpkeepStateLog(l logpoller.Log) error {
lid := fmt.Sprintf("%s%d", l.TxHash.String(), l.LogIndex)
r.mu.Lock()
if _, ok := r.logProcessed[lid]; ok {
r.mu.Unlock()
return nil
}
r.logProcessed[lid] = true
r.mu.Unlock()
txHash := l.TxHash.String()
rawLog := l.ToGethLog()
abilog, err := r.registry.ParseLog(rawLog)
if err != nil {
return err
}
switch l := abilog.(type) {
case *iregistry21.IKeeperRegistryMasterUpkeepPaused:
r.lggr.Debugf("KeeperRegistryUpkeepPaused log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
r.removeFromActive(l.Id)
case *iregistry21.IKeeperRegistryMasterUpkeepCanceled:
r.lggr.Debugf("KeeperRegistryUpkeepCanceled log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
r.removeFromActive(l.Id)
case *iregistry21.IKeeperRegistryMasterUpkeepMigrated:
r.lggr.Debugf("KeeperRegistryMasterUpkeepMigrated log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
r.removeFromActive(l.Id)
case *iregistry21.IKeeperRegistryMasterUpkeepTriggerConfigSet:
r.lggr.Debugf("KeeperRegistryUpkeepTriggerConfigSet log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
if err := r.updateTriggerConfig(l.Id, l.TriggerConfig, rawLog.BlockNumber); err != nil {
r.lggr.Warnf("failed to update trigger config upon KeeperRegistryMasterUpkeepTriggerConfigSet for upkeep ID %s: %s", l.Id.String(), err)
}
case *iregistry21.IKeeperRegistryMasterUpkeepRegistered:
uid := &ocr2keepers.UpkeepIdentifier{}
uid.FromBigInt(l.Id)
trigger := core.GetUpkeepType(*uid)
r.lggr.Debugf("KeeperRegistryUpkeepRegistered log detected for upkeep ID %s (trigger=%d) in transaction %s", l.Id.String(), trigger, txHash)
r.active.Add(l.Id)
if err := r.updateTriggerConfig(l.Id, nil, rawLog.BlockNumber); err != nil {
r.lggr.Warnf("failed to update trigger config upon KeeperRegistryMasterUpkeepRegistered for upkeep ID %s: %s", err)
}
case *iregistry21.IKeeperRegistryMasterUpkeepReceived:
r.lggr.Debugf("KeeperRegistryUpkeepReceived log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
r.active.Add(l.Id)
if err := r.updateTriggerConfig(l.Id, nil, rawLog.BlockNumber); err != nil {
r.lggr.Warnf("failed to update trigger config upon KeeperRegistryMasterUpkeepReceived for upkeep ID %s: %s", err)
}
case *iregistry21.IKeeperRegistryMasterUpkeepUnpaused:
r.lggr.Debugf("KeeperRegistryUpkeepUnpaused log detected for upkeep ID %s in transaction %s", l.Id.String(), txHash)
r.active.Add(l.Id)
if err := r.updateTriggerConfig(l.Id, nil, rawLog.BlockNumber); err != nil {
r.lggr.Warnf("failed to update trigger config upon KeeperRegistryMasterUpkeepUnpaused for upkeep ID %s: %s", err)
}
default:
r.lggr.Debugf("Unknown log detected for log %+v in transaction %s", l, txHash)
}
return nil
}
func RegistryUpkeepFilterName(addr common.Address) string {
return logpoller.FilterName("KeeperRegistry Events", addr.String())
}
// registerEvents registers upkeep state events from keeper registry on log poller
func (r *EvmRegistry) registerEvents(_ uint64, addr common.Address) error {
// Add log filters for the log poller so that it can poll and find the logs that we need
return r.poller.RegisterFilter(logpoller.Filter{
Name: RegistryUpkeepFilterName(addr),
EventSigs: upkeepStateEvents,
Addresses: []common.Address{addr},
})
}
// removeFromActive removes an upkeepID from active list and unregisters the log filter for log upkeeps
func (r *EvmRegistry) removeFromActive(id *big.Int) {
r.active.Remove(id)
uid := &ocr2keepers.UpkeepIdentifier{}
uid.FromBigInt(id)
trigger := core.GetUpkeepType(*uid)
switch trigger {
case ocr2keepers.LogTrigger:
if err := r.logEventProvider.UnregisterFilter(id); err != nil {
r.lggr.Warnw("failed to unregister log filter", "upkeepID", id.String())
}
r.lggr.Debugw("unregistered log filter", "upkeepID", id.String())
default:
}
}
func (r *EvmRegistry) buildCallOpts(ctx context.Context, block *big.Int) *bind.CallOpts {
opts := bind.CallOpts{
Context: ctx,
}
if block == nil || block.Int64() == 0 {
l := r.bs.latestBlock.Load()
if l != nil && l.Number != 0 {
opts.BlockNumber = big.NewInt(int64(l.Number))
}
} else {
opts.BlockNumber = block
}
return &opts
}
func (r *EvmRegistry) getLatestIDsFromContract(ctx context.Context) ([]*big.Int, error) {
opts := r.buildCallOpts(ctx, nil)
state, err := r.registry.GetState(opts)
if err != nil {
n := "latest"
if opts.BlockNumber != nil {
n = fmt.Sprintf("%d", opts.BlockNumber.Int64())
}
return nil, fmt.Errorf("%w: failed to get contract state at block number '%s'", err, n)
}
ids := make([]*big.Int, 0, int(state.State.NumUpkeeps.Int64()))
for int64(len(ids)) < state.State.NumUpkeeps.Int64() {
startIndex := int64(len(ids))
maxCount := state.State.NumUpkeeps.Int64() - startIndex
if maxCount == 0 {
break
}
if maxCount > ActiveUpkeepIDBatchSize {
maxCount = ActiveUpkeepIDBatchSize
}
batchIDs, err := r.registry.GetActiveUpkeepIDs(opts, big.NewInt(startIndex), big.NewInt(maxCount))
if err != nil {
return nil, fmt.Errorf("%w: failed to get active upkeep IDs from index %d to %d (both inclusive)", err, startIndex, startIndex+maxCount-1)
}
ids = append(ids, batchIDs...)
}
return ids, nil
}
// updateTriggerConfig updates the trigger config for an upkeep. it will re-register a filter for this upkeep.
func (r *EvmRegistry) updateTriggerConfig(id *big.Int, cfg []byte, logBlock uint64) error {
uid := &ocr2keepers.UpkeepIdentifier{}
uid.FromBigInt(id)
switch core.GetUpkeepType(*uid) {
case ocr2keepers.LogTrigger:
if len(cfg) == 0 {
fetched, err := r.fetchTriggerConfig(id)
if err != nil {
return errors.Wrap(err, "failed to fetch log upkeep config")
}
cfg = fetched
}
parsed, err := r.packer.UnpackLogTriggerConfig(cfg)
if err != nil {
// Upkeep has been setup with improper config. Log a warning and ignore the upkeep.
r.lggr.Warnw("failed to unpack log upkeep config", "upkeepID", id.String(), "err", err)
return nil
}
if err := r.logEventProvider.RegisterFilter(r.ctx, logprovider.FilterOptions{
TriggerConfig: logprovider.LogTriggerConfig(parsed),
UpkeepID: id,
UpdateBlock: logBlock,
}); err != nil {
return errors.Wrap(err, "failed to register log filter")
}
r.lggr.Debugw("registered log filter", "upkeepID", id.String(), "cfg", parsed)
default:
}
return nil
}
// fetchTriggerConfig fetches trigger config in raw bytes for an upkeep.
func (r *EvmRegistry) fetchTriggerConfig(id *big.Int) ([]byte, error) {
opts := r.buildCallOpts(r.ctx, nil)
cfg, err := r.registry.GetUpkeepTriggerConfig(opts, id)
if err != nil {
r.lggr.Warnw("failed to get trigger config", "err", err)
return nil, err
}
return cfg, nil
}