-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathorm.go
774 lines (712 loc) · 28.2 KB
/
orm.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
package logpoller
import (
"context"
"database/sql"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
// ORM represents the persistent data access layer used by the log poller. At this moment, it's a bit leaky abstraction, because
// it exposes some of the database implementation details (e.g. pg.Q). Ideally it should be agnostic and could be applied to any persistence layer.
// What is more, LogPoller should not be aware of the underlying database implementation and delegate all the queries to the ORM.
type ORM interface {
InsertLogs(logs []Log, qopts ...pg.QOpt) error
InsertLogsWithBlock(logs []Log, block LogPollerBlock, qopts ...pg.QOpt) error
InsertFilter(filter Filter, qopts ...pg.QOpt) error
LoadFilters(qopts ...pg.QOpt) (map[string]Filter, error)
DeleteFilter(name string, qopts ...pg.QOpt) error
DeleteBlocksBefore(end int64, qopts ...pg.QOpt) error
DeleteLogsAndBlocksAfter(start int64, qopts ...pg.QOpt) error
DeleteExpiredLogs(qopts ...pg.QOpt) error
GetBlocksRange(start int64, end int64, qopts ...pg.QOpt) ([]LogPollerBlock, error)
SelectBlockByNumber(blockNumber int64, qopts ...pg.QOpt) (*LogPollerBlock, error)
SelectLatestBlock(qopts ...pg.QOpt) (*LogPollerBlock, error)
SelectLogs(start, end int64, address common.Address, eventSig common.Hash, qopts ...pg.QOpt) ([]Log, error)
SelectLogsWithSigs(start, end int64, address common.Address, eventSigs []common.Hash, qopts ...pg.QOpt) ([]Log, error)
SelectLogsCreatedAfter(address common.Address, eventSig common.Hash, after time.Time, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectLatestLogByEventSigWithConfs(eventSig common.Hash, address common.Address, confs Confirmations, qopts ...pg.QOpt) (*Log, error)
SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresses []common.Address, eventSigs []common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectLatestBlockByEventSigsAddrsWithConfs(fromBlock int64, eventSigs []common.Hash, addresses []common.Address, confs Confirmations, qopts ...pg.QOpt) (int64, error)
SelectIndexedLogs(address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsByBlockRange(start, end int64, address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsCreatedAfter(address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, after time.Time, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsTopicGreaterThan(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsTopicRange(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin, topicValueMax common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsWithSigsExcluding(sigA, sigB common.Hash, topicIndex int, address common.Address, startBlock, endBlock int64, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectIndexedLogsByTxHash(address common.Address, eventSig common.Hash, txHash common.Hash, qopts ...pg.QOpt) ([]Log, error)
SelectLogsDataWordRange(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin, wordValueMax common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectLogsDataWordGreaterThan(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
SelectLogsDataWordBetween(address common.Address, eventSig common.Hash, wordIndexMin int, wordIndexMax int, wordValue common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error)
}
type DbORM struct {
chainID *big.Int
q pg.Q
lggr logger.Logger
}
// NewORM creates a DbORM scoped to chainID.
func NewORM(chainID *big.Int, db *sqlx.DB, lggr logger.Logger, cfg pg.QConfig) *DbORM {
namedLogger := logger.Named(lggr, "Configs")
q := pg.NewQ(db, namedLogger, cfg)
return &DbORM{
chainID: chainID,
q: q,
lggr: lggr,
}
}
// InsertBlock is idempotent to support replays.
func (o *DbORM) InsertBlock(blockHash common.Hash, blockNumber int64, blockTimestamp time.Time, finalizedBlock int64, qopts ...pg.QOpt) error {
args, err := newQueryArgs(o.chainID).
withCustomHashArg("block_hash", blockHash).
withCustomArg("block_number", blockNumber).
withCustomArg("block_timestamp", blockTimestamp).
withCustomArg("finalized_block_number", finalizedBlock).
toArgs()
if err != nil {
return err
}
return o.q.WithOpts(qopts...).ExecQNamed(`
INSERT INTO evm.log_poller_blocks
(evm_chain_id, block_hash, block_number, block_timestamp, finalized_block_number, created_at)
VALUES (:evm_chain_id, :block_hash, :block_number, :block_timestamp, :finalized_block_number, NOW())
ON CONFLICT DO NOTHING`, args)
}
// InsertFilter is idempotent.
//
// Each address/event pair must have a unique job id, so it may be removed when the job is deleted.
// If a second job tries to overwrite the same pair, this should fail.
func (o *DbORM) InsertFilter(filter Filter, qopts ...pg.QOpt) (err error) {
args, err := newQueryArgs(o.chainID).
withCustomArg("name", filter.Name).
withCustomArg("retention", filter.Retention).
withAddressArray(filter.Addresses).
withEventSigArray(filter.EventSigs).
toArgs()
if err != nil {
return err
}
// '::' has to be escaped in the query string
// https://github.com/jmoiron/sqlx/issues/91, https://github.com/jmoiron/sqlx/issues/428
return o.q.WithOpts(qopts...).ExecQNamed(`
INSERT INTO evm.log_poller_filters
(name, evm_chain_id, retention, created_at, address, event)
SELECT * FROM
(SELECT :name, :evm_chain_id ::::NUMERIC, :retention ::::BIGINT, NOW()) x,
(SELECT unnest(:address_array ::::BYTEA[]) addr) a,
(SELECT unnest(:event_sig_array ::::BYTEA[]) ev) e
ON CONFLICT (name, evm_chain_id, address, event)
DO UPDATE SET retention=:retention ::::BIGINT`, args)
}
// DeleteFilter removes all events,address pairs associated with the Filter
func (o *DbORM) DeleteFilter(name string, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
return q.ExecQ(`DELETE FROM evm.log_poller_filters WHERE name = $1 AND evm_chain_id = $2`, name, utils.NewBig(o.chainID))
}
// LoadFiltersForChain returns all filters for this chain
func (o *DbORM) LoadFilters(qopts ...pg.QOpt) (map[string]Filter, error) {
q := o.q.WithOpts(qopts...)
rows := make([]Filter, 0)
err := q.Select(&rows, `SELECT name,
ARRAY_AGG(DISTINCT address)::BYTEA[] AS addresses,
ARRAY_AGG(DISTINCT event)::BYTEA[] AS event_sigs,
MAX(retention) AS retention
FROM evm.log_poller_filters WHERE evm_chain_id = $1
GROUP BY name`, utils.NewBig(o.chainID))
filters := make(map[string]Filter)
for _, filter := range rows {
filters[filter.Name] = filter
}
return filters, err
}
func (o *DbORM) SelectBlockByHash(hash common.Hash, qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE block_hash = $1 AND evm_chain_id = $2`, hash, utils.NewBig(o.chainID)); err != nil {
return nil, err
}
return &b, nil
}
func (o *DbORM) SelectBlockByNumber(n int64, qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE block_number = $1 AND evm_chain_id = $2`, n, utils.NewBig(o.chainID)); err != nil {
return nil, err
}
return &b, nil
}
func (o *DbORM) SelectLatestBlock(qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1`, utils.NewBig(o.chainID)); err != nil {
return nil, err
}
return &b, nil
}
func (o *DbORM) SelectLatestLogByEventSigWithConfs(eventSig common.Hash, address common.Address, confs Confirmations, qopts ...pg.QOpt) (*Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND event_sig = :event_sig
AND address = :address
AND block_number <= %s
ORDER BY (block_number, log_index) DESC LIMIT 1`, nestedBlockNumberQuery(confs))
var l Log
if err := o.q.WithOpts(qopts...).GetNamed(query, &l, args); err != nil {
return nil, err
}
return &l, nil
}
// DeleteBlocksBefore delete all blocks before and including end.
func (o *DbORM) DeleteBlocksBefore(end int64, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
_, err := q.Exec(`DELETE FROM evm.log_poller_blocks WHERE block_number <= $1 AND evm_chain_id = $2`, end, utils.NewBig(o.chainID))
return err
}
func (o *DbORM) DeleteLogsAndBlocksAfter(start int64, qopts ...pg.QOpt) error {
// These deletes are bounded by reorg depth, so they are
// fast and should not slow down the log readers.
return o.q.WithOpts(qopts...).Transaction(func(tx pg.Queryer) error {
args, err := newQueryArgs(o.chainID).
withStartBlock(start).
toArgs()
if err != nil {
o.lggr.Error("Cant build args for DeleteLogsAndBlocksAfter queries", "err", err)
return err
}
_, err = tx.NamedExec(`DELETE FROM evm.log_poller_blocks WHERE block_number >= :start_block AND evm_chain_id = :evm_chain_id`, args)
if err != nil {
o.lggr.Warnw("Unable to clear reorged blocks, retrying", "err", err)
return err
}
_, err = tx.NamedExec(`DELETE FROM evm.logs WHERE block_number >= :start_block AND evm_chain_id = :evm_chain_id`, args)
if err != nil {
o.lggr.Warnw("Unable to clear reorged logs, retrying", "err", err)
return err
}
return nil
})
}
type Exp struct {
Address common.Address
EventSig common.Hash
Expiration time.Time
TimeNow time.Time
ShouldDelete bool
}
func (o *DbORM) DeleteExpiredLogs(qopts ...pg.QOpt) error {
qopts = append(qopts, pg.WithLongQueryTimeout())
q := o.q.WithOpts(qopts...)
return q.ExecQ(`WITH r AS
( SELECT address, event, MAX(retention) AS retention
FROM evm.log_poller_filters WHERE evm_chain_id=$1
GROUP BY evm_chain_id,address, event HAVING NOT 0 = ANY(ARRAY_AGG(retention))
) DELETE FROM evm.logs l USING r
WHERE l.evm_chain_id = $1 AND l.address=r.address AND l.event_sig=r.event
AND l.created_at <= STATEMENT_TIMESTAMP() - (r.retention / 10^9 * interval '1 second')`, // retention is in nanoseconds (time.Duration aka BIGINT)
utils.NewBig(o.chainID))
}
// InsertLogs is idempotent to support replays.
func (o *DbORM) InsertLogs(logs []Log, qopts ...pg.QOpt) error {
if err := o.validateLogs(logs); err != nil {
return err
}
return o.q.WithOpts(qopts...).Transaction(func(tx pg.Queryer) error {
return o.insertLogsWithinTx(logs, tx)
})
}
func (o *DbORM) InsertLogsWithBlock(logs []Log, block LogPollerBlock, qopts ...pg.QOpt) error {
// Optimization, don't open TX when there is only a block to be persisted
if len(logs) == 0 {
return o.InsertBlock(block.BlockHash, block.BlockNumber, block.BlockTimestamp, block.FinalizedBlockNumber, qopts...)
}
if err := o.validateLogs(logs); err != nil {
return err
}
// Block and logs goes with the same TX to ensure atomicity
return o.q.WithOpts(qopts...).Transaction(func(tx pg.Queryer) error {
if err := o.InsertBlock(block.BlockHash, block.BlockNumber, block.BlockTimestamp, block.FinalizedBlockNumber, pg.WithQueryer(tx)); err != nil {
return err
}
return o.insertLogsWithinTx(logs, tx)
})
}
func (o *DbORM) insertLogsWithinTx(logs []Log, tx pg.Queryer) error {
batchInsertSize := 4000
for i := 0; i < len(logs); i += batchInsertSize {
start, end := i, i+batchInsertSize
if end > len(logs) {
end = len(logs)
}
_, err := tx.NamedExec(`
INSERT INTO evm.logs
(evm_chain_id, log_index, block_hash, block_number, block_timestamp, address, event_sig, topics, tx_hash, data, created_at)
VALUES
(:evm_chain_id, :log_index, :block_hash, :block_number, :block_timestamp, :address, :event_sig, :topics, :tx_hash, :data, NOW())
ON CONFLICT DO NOTHING`,
logs[start:end],
)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 {
// In case of DB timeouts, try to insert again with a smaller batch upto a limit
batchInsertSize /= 2
i -= batchInsertSize // counteract +=batchInsertSize on next loop iteration
continue
}
return err
}
}
return nil
}
func (o *DbORM) validateLogs(logs []Log) error {
for _, log := range logs {
if o.chainID.Cmp(log.EvmChainId.ToInt()) != 0 {
return errors.Errorf("invalid chainID in log got %v want %v", log.EvmChainId.ToInt(), o.chainID)
}
}
return nil
}
func (o *DbORM) SelectLogsByBlockRange(start, end int64) ([]Log, error) {
args, err := newQueryArgs(o.chainID).
withStartBlock(start).
withEndBlock(end).
toArgs()
if err != nil {
return nil, err
}
var logs []Log
err = o.q.SelectNamed(&logs, `
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND block_number >= :start_block
AND block_number <= :end_block
ORDER BY (block_number, log_index, created_at)`, args)
if err != nil {
return nil, err
}
return logs, nil
}
// SelectLogsByBlockRangeFilter finds the logs in a given block range.
func (o *DbORM) SelectLogs(start, end int64, address common.Address, eventSig common.Hash, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withStartBlock(start).
withEndBlock(end).
toArgs()
if err != nil {
return nil, err
}
var logs []Log
err = o.q.WithOpts(qopts...).SelectNamed(&logs, `
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND block_number >= :start_block
AND block_number <= :end_block
ORDER BY (block_number, log_index)`, args)
if err != nil {
return nil, err
}
return logs, nil
}
// SelectLogsCreatedAfter finds logs created after some timestamp.
func (o *DbORM) SelectLogsCreatedAfter(address common.Address, eventSig common.Hash, after time.Time, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withBlockTimestampAfter(after).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND block_timestamp > :block_timestamp_after
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err = o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
// SelectLogsWithSigsByBlockRangeFilter finds the logs in the given block range with the given event signatures
// emitted from the given address.
func (o *DbORM) SelectLogsWithSigs(start, end int64, address common.Address, eventSigs []common.Hash, qopts ...pg.QOpt) (logs []Log, err error) {
args, err := newQueryArgs(o.chainID).
withAddress(address).
withEventSigArray(eventSigs).
withStartBlock(start).
withEndBlock(end).
toArgs()
if err != nil {
return nil, err
}
q := o.q.WithOpts(qopts...)
err = q.SelectNamed(&logs, `
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = ANY(:event_sig_array)
AND block_number BETWEEN :start_block AND :end_block
ORDER BY (block_number, log_index)`, args)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return logs, err
}
func (o *DbORM) GetBlocksRange(start int64, end int64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {
args, err := newQueryArgs(o.chainID).
withStartBlock(start).
withEndBlock(end).
toArgs()
if err != nil {
return nil, err
}
var blocks []LogPollerBlock
err = o.q.WithOpts(qopts...).SelectNamed(&blocks, `
SELECT * FROM evm.log_poller_blocks
WHERE block_number >= :start_block
AND block_number <= :end_block
AND evm_chain_id = :evm_chain_id
ORDER BY block_number ASC`, args)
if err != nil {
return nil, err
}
return blocks, nil
}
// SelectLatestLogEventSigsAddrsWithConfs finds the latest log by (address, event) combination that matches a list of Addresses and list of events
func (o *DbORM) SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresses []common.Address, eventSigs []common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgs(o.chainID).
withAddressArray(addresses).
withEventSigArray(eventSigs).
withStartBlock(fromBlock).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs WHERE (block_number, address, event_sig) IN (
SELECT MAX(block_number), address, event_sig FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND event_sig = ANY(:event_sig_array)
AND address = ANY(:address_array)
AND block_number > :start_block
AND block_number <= %s
GROUP BY event_sig, address
)
ORDER BY block_number ASC`, nestedBlockNumberQuery(confs))
var logs []Log
if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, errors.Wrap(err, "failed to execute query")
}
return logs, nil
}
// SelectLatestBlockNumberEventSigsAddrsWithConfs finds the latest block number that matches a list of Addresses and list of events. It returns 0 if there is no matching block
func (o *DbORM) SelectLatestBlockByEventSigsAddrsWithConfs(fromBlock int64, eventSigs []common.Hash, addresses []common.Address, confs Confirmations, qopts ...pg.QOpt) (int64, error) {
args, err := newQueryArgs(o.chainID).
withEventSigArray(eventSigs).
withAddressArray(addresses).
withStartBlock(fromBlock).
withConfs(confs).
toArgs()
if err != nil {
return 0, err
}
query := fmt.Sprintf(`
SELECT COALESCE(MAX(block_number), 0) FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND event_sig = ANY(:event_sig_array)
AND address = ANY(:address_array)
AND block_number > :start_block
AND block_number <= %s`, nestedBlockNumberQuery(confs))
var blockNumber int64
if err := o.q.WithOpts(qopts...).GetNamed(query, &blockNumber, args); err != nil {
return 0, err
}
return blockNumber, nil
}
func (o *DbORM) SelectLogsDataWordRange(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin, wordValueMax common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withWordIndex(wordIndex).
withWordValueMin(wordValueMin).
withWordValueMax(wordValueMax).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND substring(data from 32*:word_index+1 for 32) >= :word_value_min
AND substring(data from 32*:word_index+1 for 32) <= :word_value_max
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectLogsDataWordGreaterThan(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withWordIndex(wordIndex).
withWordValueMin(wordValueMin).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND substring(data from 32*:word_index+1 for 32) >= :word_value_min
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err = o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectLogsDataWordBetween(address common.Address, eventSig common.Hash, wordIndexMin int, wordIndexMax int, wordValue common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withWordIndexMin(wordIndexMin).
withWordIndexMax(wordIndexMax).
withWordValue(wordValue).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND substring(data from 32*:word_index_min+1 for 32) <= :word_value
AND substring(data from 32*:word_index_max+1 for 32) >= :word_value
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err = o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectIndexedLogsTopicGreaterThan(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withTopicIndex(topicIndex).
withTopicValueMin(topicValueMin).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND topics[:topic_index] >= :topic_value_min
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err = o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectIndexedLogsTopicRange(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin, topicValueMax common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withTopicIndex(topicIndex).
withTopicValueMin(topicValueMin).
withTopicValueMax(topicValueMax).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND topics[:topic_index] >= :topic_value_min
AND topics[:topic_index] <= :topic_value_max
AND block_number <= %s
ORDER BY (evm.logs.block_number, evm.logs.log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectIndexedLogs(address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withTopicIndex(topicIndex).
withTopicValues(topicValues).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND topics[:topic_index] = ANY(:topic_values)
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
// SelectIndexedLogsByBlockRangeFilter finds the indexed logs in a given block range.
func (o *DbORM) SelectIndexedLogsByBlockRange(start, end int64, address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withTopicIndex(topicIndex).
withTopicValues(topicValues).
withStartBlock(start).
withEndBlock(end).
toArgs()
if err != nil {
return nil, err
}
var logs []Log
err = o.q.WithOpts(qopts...).SelectNamed(&logs, `
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND topics[:topic_index] = ANY(:topic_values)
AND block_number >= :start_block
AND block_number <= :end_block
ORDER BY (block_number, log_index)`, args)
if err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectIndexedLogsCreatedAfter(address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, after time.Time, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgsForEvent(o.chainID, address, eventSig).
withBlockTimestampAfter(after).
withConfs(confs).
withTopicIndex(topicIndex).
withTopicValues(topicValues).
toArgs()
if err != nil {
return nil, err
}
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND topics[:topic_index] = ANY(:topic_values)
AND block_timestamp > :block_timestamp_after
AND block_number <= %s
ORDER BY (block_number, log_index)`, nestedBlockNumberQuery(confs))
var logs []Log
if err = o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func (o *DbORM) SelectIndexedLogsByTxHash(address common.Address, eventSig common.Hash, txHash common.Hash, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgs(o.chainID).
withTxHash(txHash).
withAddress(address).
withEventSig(eventSig).
toArgs()
if err != nil {
return nil, err
}
var logs []Log
err = o.q.WithOpts(qopts...).SelectNamed(&logs, `
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :event_sig
AND tx_hash = :tx_hash
ORDER BY (block_number, log_index)`, args)
if err != nil {
return nil, err
}
return logs, nil
}
// SelectIndexedLogsWithSigsExcluding query's for logs that have signature A and exclude logs that have a corresponding signature B, matching is done based on the topic index both logs should be inside the block range and have the minimum number of confirmations
func (o *DbORM) SelectIndexedLogsWithSigsExcluding(sigA, sigB common.Hash, topicIndex int, address common.Address, startBlock, endBlock int64, confs Confirmations, qopts ...pg.QOpt) ([]Log, error) {
args, err := newQueryArgs(o.chainID).
withAddress(address).
withTopicIndex(topicIndex).
withStartBlock(startBlock).
withEndBlock(endBlock).
withCustomHashArg("sigA", sigA).
withCustomHashArg("sigB", sigB).
withConfs(confs).
toArgs()
if err != nil {
return nil, err
}
nestedQuery := nestedBlockNumberQuery(confs)
query := fmt.Sprintf(`
SELECT * FROM evm.logs
WHERE evm_chain_id = :evm_chain_id
AND address = :address
AND event_sig = :sigA
AND block_number BETWEEN :start_block AND :end_block
AND block_number <= %s
EXCEPT
SELECT a.* FROM evm.logs AS a
INNER JOIN evm.logs B
ON a.evm_chain_id = b.evm_chain_id
AND a.address = b.address
AND a.topics[:topic_index] = b.topics[:topic_index]
AND a.event_sig = :sigA
AND b.event_sig = :sigB
AND b.block_number BETWEEN :start_block AND :end_block
AND b.block_number <= %s
ORDER BY block_number,log_index ASC`, nestedQuery, nestedQuery)
var logs []Log
if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil {
return nil, err
}
return logs, nil
}
func nestedBlockNumberQuery(confs Confirmations) string {
if confs == Finalized {
return `
(SELECT finalized_block_number
FROM evm.log_poller_blocks
WHERE evm_chain_id = :evm_chain_id
ORDER BY block_number DESC LIMIT 1) `
}
// Intentionally wrap with greatest() function and don't return negative block numbers when :confs > :block_number
// It doesn't impact logic of the outer query, because block numbers are never less or equal to 0 (guarded by log_poller_blocks_block_number_check)
return `
(SELECT greatest(block_number - :confs, 0)
FROM evm.log_poller_blocks
WHERE evm_chain_id = :evm_chain_id
ORDER BY block_number DESC LIMIT 1) `
}