-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
orm.go
324 lines (294 loc) · 11.8 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
package logpoller
import (
"database/sql"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/lib/pq"
"github.com/pkg/errors"
"github.com/smartcontractkit/sqlx"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/utils"
)
type ORM struct {
chainID *big.Int
q pg.Q
}
// NewORM creates an ORM scoped to chainID.
func NewORM(chainID *big.Int, db *sqlx.DB, lggr logger.Logger, cfg pg.QConfig) *ORM {
namedLogger := lggr.Named("ORM")
q := pg.NewQ(db, namedLogger, cfg)
return &ORM{
chainID: chainID,
q: q,
}
}
// InsertBlock is idempotent to support replays.
func (o *ORM) InsertBlock(h common.Hash, n int64, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
err := q.ExecQ(`INSERT INTO log_poller_blocks (evm_chain_id, block_hash, block_number, created_at)
VALUES ($1, $2, $3, NOW()) ON CONFLICT DO NOTHING`, utils.NewBig(o.chainID), h[:], n)
return err
}
func (o *ORM) SelectBlockByHash(h common.Hash, qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM log_poller_blocks WHERE block_hash = $1 AND evm_chain_id = $2`, h, utils.NewBig(o.chainID)); err != nil {
return nil, err
}
return &b, nil
}
func (o *ORM) SelectBlockByNumber(n int64, qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM 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 *ORM) SelectLatestBlock(qopts ...pg.QOpt) (*LogPollerBlock, error) {
q := o.q.WithOpts(qopts...)
var b LogPollerBlock
if err := q.Get(&b, `SELECT * FROM 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 *ORM) SelectLatestLogEventSigWithConfs(eventSig common.Hash, address common.Address, confs int, qopts ...pg.QOpt) (*Log, error) {
q := o.q.WithOpts(qopts...)
var l Log
if err := q.Get(&l, `SELECT * FROM logs
WHERE evm_chain_id = $1
AND event_sig = $2
AND address = $3
AND (block_number + $4) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (block_number, log_index) DESC LIMIT 1`, utils.NewBig(o.chainID), eventSig, address, confs); err != nil {
return nil, err
}
return &l, nil
}
// DeleteBlocksAfter delete all blocks after and including start.
func (o *ORM) DeleteBlocksAfter(start int64, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
return q.ExecQ(`DELETE FROM log_poller_blocks WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID))
}
// DeleteBlocksBefore delete all blocks before and including end.
func (o *ORM) DeleteBlocksBefore(end int64, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
_, err := q.Exec(`DELETE FROM log_poller_blocks WHERE block_number <= $1 AND evm_chain_id = $2`, end, utils.NewBig(o.chainID))
return err
}
func (o *ORM) DeleteLogsAfter(start int64, qopts ...pg.QOpt) error {
q := o.q.WithOpts(qopts...)
return q.ExecQ(`DELETE FROM logs WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID))
}
// InsertLogs is idempotent to support replays.
func (o *ORM) InsertLogs(logs []Log, qopts ...pg.QOpt) 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)
}
}
q := o.q.WithOpts(qopts...)
batchInsertSize := 4000
for i := 0; i < len(logs); i += batchInsertSize {
start, end := i, i+batchInsertSize
if end > len(logs) {
end = len(logs)
}
err := q.ExecQNamed(`INSERT INTO logs
(evm_chain_id, log_index, block_hash, block_number, address, event_sig, topics, tx_hash, data, created_at) VALUES
(:evm_chain_id, :log_index, :block_hash, :block_number, :address, :event_sig, :topics, :tx_hash, :data, NOW()) ON CONFLICT DO NOTHING`, logs[start:end])
if err != nil {
return err
}
}
return nil
}
func (o *ORM) selectLogsByBlockRange(start, end int64) ([]Log, error) {
var logs []Log
err := o.q.Select(&logs, `
SELECT * FROM logs
WHERE block_number >= $1 AND block_number <= $2 AND evm_chain_id = $3
ORDER BY (block_number, log_index, created_at)`, start, end, utils.NewBig(o.chainID))
if err != nil {
return nil, err
}
return logs, nil
}
// SelectLogsByBlockRangeFilter finds the logs in a given block range.
func (o *ORM) SelectLogsByBlockRangeFilter(start, end int64, address common.Address, eventSig common.Hash, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
q := o.q.WithOpts(qopts...)
err := q.Select(&logs, `
SELECT * FROM logs
WHERE logs.block_number >= $1 AND logs.block_number <= $2 AND logs.evm_chain_id = $3
AND address = $4 AND event_sig = $5
ORDER BY (logs.block_number, logs.log_index)`, start, end, utils.NewBig(o.chainID), address, eventSig.Bytes())
if 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 *ORM) SelectLogsWithSigsByBlockRangeFilter(start, end int64, address common.Address, eventSigs []common.Hash, qopts ...pg.QOpt) (logs []Log, err error) {
q := o.q.WithOpts(qopts...)
sigs := make([][]byte, 0, len(eventSigs))
for _, sig := range eventSigs {
sigs = append(sigs, sig.Bytes())
}
a := map[string]any{
"start": start,
"end": end,
"chainid": utils.NewBig(o.chainID),
"address": address,
"EventSigs": sigs,
}
query, args, err := sqlx.Named(
`
SELECT
*
FROM logs
WHERE logs.block_number BETWEEN :start AND :end
AND logs.evm_chain_id = :chainid
AND logs.address = :address
AND logs.event_sig IN (:EventSigs)
ORDER BY (logs.block_number, logs.log_index)`, a)
if err != nil {
return nil, errors.Wrap(err, "sqlx Named")
}
query, args, err = sqlx.In(query, args...)
if err != nil {
return nil, errors.Wrap(err, "sqlx In")
}
query = q.Rebind(query)
err = q.Select(&logs, query, args...)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return logs, err
}
func (o *ORM) GetBlocksRange(start uint64, end uint64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {
var blocks []LogPollerBlock
q := o.q.WithOpts(qopts...)
err := q.Select(&blocks, `
SELECT * FROM log_poller_blocks
WHERE block_number >= $1 AND block_number <= $2 AND evm_chain_id = $3
ORDER BY block_number ASC`, start, end, utils.NewBig(o.chainID))
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 *ORM) SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresses []common.Address, eventSigs []common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
var sigs [][]byte
for _, sig := range eventSigs {
sigs = append(sigs, sig.Bytes())
}
var addrs [][]byte
for _, addr := range addresses {
addrs = append(addrs, addr.Bytes())
}
q := o.q.WithOpts(qopts...)
err := q.Select(&logs, `
SELECT * FROM logs WHERE (block_number, address, event_sig) IN (
SELECT MAX(block_number), address, event_sig FROM logs
WHERE evm_chain_id = $1 AND
event_sig = ANY($2) AND
address = ANY($3) AND
block_number > $4 AND
(block_number + $5) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
GROUP BY event_sig, address
)
ORDER BY block_number ASC
`, o.chainID.Int64(), pq.ByteaArray(sigs), pq.ByteaArray(addrs), fromBlock, confs)
if err != nil {
return nil, errors.Wrap(err, "failed to execute query")
}
return logs, nil
}
func (o *ORM) SelectDataWordRange(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin, wordValueMax common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
q := o.q.WithOpts(qopts...)
err := q.Select(&logs,
`SELECT * FROM logs
WHERE logs.evm_chain_id = $1
AND address = $2 AND event_sig = $3
AND substring(data from 32*$4+1 for 32) >= $5
AND substring(data from 32*$4+1 for 32) <= $6
AND (block_number + $7) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (logs.block_number, logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), wordValueMax.Bytes(), confs)
if err != nil {
return nil, err
}
return logs, nil
}
func (o *ORM) SelectDataWordGreaterThan(address common.Address, eventSig common.Hash, wordIndex int, wordValueMin common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
q := o.q.WithOpts(qopts...)
err := q.Select(&logs,
`SELECT * FROM logs
WHERE logs.evm_chain_id = $1
AND address = $2 AND event_sig = $3
AND substring(data from 32*$4+1 for 32) >= $5
AND (block_number + $6) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (logs.block_number, logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), confs)
if err != nil {
return nil, err
}
return logs, nil
}
func (o *ORM) SelectIndexLogsTopicGreaterThan(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
q := o.q.WithOpts(qopts...)
err := q.Select(&logs,
`SELECT * FROM logs
WHERE logs.evm_chain_id = $1
AND address = $2 AND event_sig = $3
AND topics[$4] >= $5
AND (block_number + $6) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (logs.block_number, logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), confs)
if err != nil {
return nil, err
}
return logs, nil
}
func (o *ORM) SelectIndexLogsTopicRange(address common.Address, eventSig common.Hash, topicIndex int, topicValueMin, topicValueMax common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
var logs []Log
q := o.q.WithOpts(qopts...)
err := q.Select(&logs,
`SELECT * FROM logs
WHERE logs.evm_chain_id = $1
AND address = $2 AND event_sig = $3
AND topics[$4] >= $5
AND topics[$4] <= $6
AND (block_number + $7) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (logs.block_number, logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), topicValueMax.Bytes(), confs)
if err != nil {
return nil, err
}
return logs, nil
}
func (o *ORM) SelectIndexedLogs(address common.Address, eventSig common.Hash, topicIndex int, topicValues []common.Hash, confs int, qopts ...pg.QOpt) ([]Log, error) {
q := o.q.WithOpts(qopts...)
var logs []Log
var topicValuesBytes [][]byte
for _, topicValue := range topicValues {
topicValuesBytes = append(topicValuesBytes, topicValue.Bytes())
}
// Add 1 since postgresql arrays are 1-indexed.
err := q.Select(&logs, `
SELECT * FROM logs
WHERE logs.evm_chain_id = $1
AND address = $2 AND event_sig = $3
AND topics[$4] = ANY($5)
AND (block_number + $6) <= (SELECT COALESCE(block_number, 0) FROM log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1)
ORDER BY (logs.block_number, logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, pq.ByteaArray(topicValuesBytes), confs)
if err != nil {
return nil, err
}
return logs, nil
}