hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
1package historydb
2
3import (
4 "errors"
5 "fmt"
6 "math"
7 "math/big"
8 "strings"
9
10 ethCommon "github.com/ethereum/go-ethereum/common"
11 "github.com/hermeznetwork/hermez-node/common"
12 "github.com/hermeznetwork/hermez-node/db"
13 "github.com/hermeznetwork/tracerr"
14 "github.com/iden3/go-iden3-crypto/babyjub"
15 "github.com/jmoiron/sqlx"
16
17 //nolint:errcheck // driver for postgres DB
18 _ "github.com/lib/pq"
19 "github.com/russross/meddler"
20)
21
22const (
23 // OrderAsc indicates ascending order when using pagination
24 OrderAsc = "ASC"
25 // OrderDesc indicates descending order when using pagination
26 OrderDesc = "DESC"
27)
28
29// TODO(Edu): Document here how HistoryDB is kept consistent
30
31// HistoryDB persist the historic of the rollup
32type HistoryDB struct {
33 db *sqlx.DB
34}
35
36// NewHistoryDB initialize the DB
37func NewHistoryDB(db *sqlx.DB) *HistoryDB {
38 return &HistoryDB{db: db}
39}
40
41// DB returns a pointer to the L2DB.db. This method should be used only for
42// internal testing purposes.
43func (hdb *HistoryDB) DB() *sqlx.DB {
44 return hdb.db
45}
46
47// AddBlock insert a block into the DB
48func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
49func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
50 return tracerr.Wrap(meddler.Insert(d, "block", block))
51}
52
53// AddBlocks inserts blocks into the DB
54func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
55 return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
56}
57
58func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
59 return tracerr.Wrap(db.BulkInsert(
60 d,
61 `INSERT INTO block (
62 eth_block_num,
63 timestamp,
64 hash
65 ) VALUES %s;`,
66 blocks[:],
67 ))
68}
69
70// GetBlock retrieve a block from the DB, given a block number
71func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
72 block := &common.Block{}
73 err := meddler.QueryRow(
74 hdb.db, block,
75 "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
76 )
77 return block, tracerr.Wrap(err)
78}
79
80// GetAllBlocks retrieve all blocks from the DB
81func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
82 var blocks []*common.Block
83 err := meddler.QueryAll(
84 hdb.db, &blocks,
85 "SELECT * FROM block ORDER BY eth_block_num;",
86 )
87 return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
88}
89
90// GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
91func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
92 var blocks []*common.Block
93 err := meddler.QueryAll(
94 hdb.db, &blocks,
95 "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
96 from, to,
97 )
98 return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
99}
100
101// GetLastBlock retrieve the block with the highest block number from the DB
102func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
103 block := &common.Block{}
104 err := meddler.QueryRow(
105 hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
106 )
107 return block, tracerr.Wrap(err)
108}
109
110// AddBatch insert a Batch into the DB
111func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
112func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
113 // Calculate total collected fees in USD
114 // Get IDs of collected tokens for fees
115 tokenIDs := []common.TokenID{}
116 for id := range batch.CollectedFees {
117 tokenIDs = append(tokenIDs, id)
118 }
119 // Get USD value of the tokens
120 type tokenPrice struct {
121 ID common.TokenID `meddler:"token_id"`
122 USD *float64 `meddler:"usd"`
123 Decimals int `meddler:"decimals"`
124 }
125 var tokenPrices []*tokenPrice
126 if len(tokenIDs) > 0 {
127 query, args, err := sqlx.In(
128 "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
129 tokenIDs,
130 )
131 if err != nil {
132 return tracerr.Wrap(err)
133 }
134 query = hdb.db.Rebind(query)
135 if err := meddler.QueryAll(
136 hdb.db, &tokenPrices, query, args...,
137 ); err != nil {
138 return tracerr.Wrap(err)
139 }
140 }
141 // Calculate total collected
142 var total float64
143 for _, tokenPrice := range tokenPrices {
144 if tokenPrice.USD == nil {
145 continue
146 }
147 f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
148 amount, _ := f.Float64()
149 total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
150 }
151 batch.TotalFeesUSD = &total
152 // Insert to DB
153 return tracerr.Wrap(meddler.Insert(d, "batch", batch))
154}
155
156// AddBatches insert Bids into the DB
157func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
158 return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
159}
160func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
161 for i := 0; i < len(batches); i++ {
162 if err := hdb.addBatch(d, &batches[i]); err != nil {
163 return tracerr.Wrap(err)
164 }
165 }
166 return nil
167}
168
169// GetBatchAPI return the batch with the given batchNum
170func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
171 batch := &BatchAPI{}
172 return batch, tracerr.Wrap(meddler.QueryRow(
173 hdb.db, batch,
174 `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
175 batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
176 batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
177 block.timestamp, block.hash,
178 COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs
179 FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
180 WHERE batch_num = $1;`, batchNum,
181 ))
182}
183
184// GetBatchesAPI return the batches applying the given filters
185func (hdb *HistoryDB) GetBatchesAPI(
186 minBatchNum, maxBatchNum, slotNum *uint,
187 forgerAddr *ethCommon.Address,
188 fromItem, limit *uint, order string,
189) ([]BatchAPI, uint64, error) {
190 var query string
191 var args []interface{}
192 queryStr := `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
193 batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
194 batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
195 block.timestamp, block.hash,
196 COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs,
197 count(*) OVER() AS total_items
198 FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
199 // Apply filters
200 nextIsAnd := false
201 // minBatchNum filter
202 if minBatchNum != nil {
203 if nextIsAnd {
204 queryStr += "AND "
205 } else {
206 queryStr += "WHERE "
207 }
208 queryStr += "batch.batch_num > ? "
209 args = append(args, minBatchNum)
210 nextIsAnd = true
211 }
212 // maxBatchNum filter
213 if maxBatchNum != nil {
214 if nextIsAnd {
215 queryStr += "AND "
216 } else {
217 queryStr += "WHERE "
218 }
219 queryStr += "batch.batch_num < ? "
220 args = append(args, maxBatchNum)
221 nextIsAnd = true
222 }
223 // slotNum filter
224 if slotNum != nil {
225 if nextIsAnd {
226 queryStr += "AND "
227 } else {
228 queryStr += "WHERE "
229 }
230 queryStr += "batch.slot_num = ? "
231 args = append(args, slotNum)
232 nextIsAnd = true
233 }
234 // forgerAddr filter
235 if forgerAddr != nil {
236 if nextIsAnd {
237 queryStr += "AND "
238 } else {
239 queryStr += "WHERE "
240 }
241 queryStr += "batch.forger_addr = ? "
242 args = append(args, forgerAddr)
243 nextIsAnd = true
244 }
245 // pagination
246 if fromItem != nil {
247 if nextIsAnd {
248 queryStr += "AND "
249 } else {
250 queryStr += "WHERE "
251 }
252 if order == OrderAsc {
253 queryStr += "batch.item_id >= ? "
254 } else {
255 queryStr += "batch.item_id <= ? "
256 }
257 args = append(args, fromItem)
258 }
259 queryStr += "ORDER BY batch.item_id "
260 if order == OrderAsc {
261 queryStr += " ASC "
262 } else {
263 queryStr += " DESC "
264 }
265 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
266 query = hdb.db.Rebind(queryStr)
267 // log.Debug(query)
268 batchPtrs := []*BatchAPI{}
269 if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
270 return nil, 0, tracerr.Wrap(err)
271 }
272 batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
273 if len(batches) == 0 {
274 return batches, 0, nil
275 }
276 return batches, batches[0].TotalItems - uint64(len(batches)), nil
277}
278
279// GetAllBatches retrieve all batches from the DB
280func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
281 var batches []*common.Batch
282 err := meddler.QueryAll(
283 hdb.db, &batches,
284 `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
285 batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
286 batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
287 ORDER BY item_id;`,
288 )
289 return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
290}
291
292// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
293func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
294 var batches []*common.Batch
295 err := meddler.QueryAll(
296 hdb.db, &batches,
297 `SELECT batch_num, eth_block_num, forger_addr, fees_collected, fee_idxs_coordinator,
298 state_root, num_accounts, last_idx, exit_root, forge_l1_txs_num, slot_num, total_fees_usd
299 FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;`,
300 from, to,
301 )
302 return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
303}
304
305// GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
306// batch within a slot
307func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
308 row := hdb.db.QueryRow(
309 `SELECT eth_block_num FROM batch
310 WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
311 )
312 var blockNum int64
313 return blockNum, tracerr.Wrap(row.Scan(&blockNum))
314}
315
316// GetLastBatchNum returns the BatchNum of the latest forged batch
317func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
318 row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
319 var batchNum common.BatchNum
320 return batchNum, tracerr.Wrap(row.Scan(&batchNum))
321}
322
323// GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
324func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
325 row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
326 WHERE forge_l1_txs_num IS NOT NULL
327 ORDER BY batch_num DESC LIMIT 1;`)
328 var blockNum int64
329 return blockNum, tracerr.Wrap(row.Scan(&blockNum))
330}
331
332// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
333// batches. If there's no batch in the DB (nil, nil) is returned.
334func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
335 row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
336 lastL1TxsNum := new(int64)
337 return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
338}
339
340// Reorg deletes all the information that was added into the DB after the
341// lastValidBlock. If lastValidBlock is negative, all block information is
342// deleted.
343func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
344 var err error
345 if lastValidBlock < 0 {
346 _, err = hdb.db.Exec("DELETE FROM block;")
347 } else {
348 _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
349 }
350 return tracerr.Wrap(err)
351}
352
353// AddBids insert Bids into the DB
354func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
355func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
356 if len(bids) == 0 {
357 return nil
358 }
359 // TODO: check the coordinator info
360 return tracerr.Wrap(db.BulkInsert(
361 d,
362 "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
363 bids[:],
364 ))
365}
366
367// GetAllBids retrieve all bids from the DB
368func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
369 var bids []*common.Bid
370 err := meddler.QueryAll(
371 hdb.db, &bids,
372 `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
373 ORDER BY item_id;`,
374 )
375 return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
376}
377
378// GetBestBidAPI returns the best bid in specific slot by slotNum
379func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
380 bid := &BidAPI{}
381 err := meddler.QueryRow(
382 hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
383 FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
384 INNER JOIN (
385 SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
386 GROUP BY bidder_addr
387 ) c ON bid.bidder_addr = c.bidder_addr
388 INNER JOIN coordinator ON c.item_id = coordinator.item_id
389 WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
390 )
391 return *bid, tracerr.Wrap(err)
392}
393
394// GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
395func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
396 bidCoord := &common.BidCoordinator{}
397 err := meddler.QueryRow(
398 hdb.db, bidCoord,
399 `SELECT (
400 SELECT default_slot_set_bid
401 FROM auction_vars
402 WHERE default_slot_set_bid_slot_num <= $1
403 ORDER BY eth_block_num DESC LIMIT 1
404 ),
405 bid.slot_num, bid.bid_value, bid.bidder_addr,
406 coordinator.forger_addr, coordinator.url
407 FROM bid
408 INNER JOIN (
409 SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
410 GROUP BY bidder_addr
411 ) c ON bid.bidder_addr = c.bidder_addr
412 INNER JOIN coordinator ON c.item_id = coordinator.item_id
413 WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
414 slotNum)
415
416 return bidCoord, tracerr.Wrap(err)
417}
418
419// GetBestBidsAPI returns the best bid in specific slot by slotNum
420func (hdb *HistoryDB) GetBestBidsAPI(
421 minSlotNum, maxSlotNum *int64,
422 bidderAddr *ethCommon.Address,
423 limit *uint, order string,
424) ([]BidAPI, uint64, error) {
425 var query string
426 var args []interface{}
427 // JOIN the best bid of each slot with the latest update of each coordinator
428 queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
429 COUNT(*) OVER() AS total_items FROM (
430 SELECT slot_num, MAX(item_id) as maxitem
431 FROM bid GROUP BY slot_num
432 )
433 AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
434 INNER JOIN block ON b.eth_block_num = block.eth_block_num
435 INNER JOIN (
436 SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
437 GROUP BY bidder_addr
438 ) c ON b.bidder_addr = c.bidder_addr
439 INNER JOIN coordinator ON c.item_id = coordinator.item_id
440 WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
441 args = append(args, minSlotNum)
442 args = append(args, maxSlotNum)
443 // Apply filters
444 if bidderAddr != nil {
445 queryStr += " AND b.bidder_addr = ? "
446 args = append(args, bidderAddr)
447 }
448 queryStr += " ORDER BY b.slot_num "
449 if order == OrderAsc {
450 queryStr += "ASC "
451 } else {
452 queryStr += "DESC "
453 }
454 if limit != nil {
455 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
456 }
457 query = hdb.db.Rebind(queryStr)
458 bidPtrs := []*BidAPI{}
459 if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
460 return nil, 0, tracerr.Wrap(err)
461 }
462 // log.Debug(query)
463 bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
464 if len(bids) == 0 {
465 return bids, 0, nil
466 }
467 return bids, bids[0].TotalItems - uint64(len(bids)), nil
468}
469
470// GetBidsAPI return the bids applying the given filters
471func (hdb *HistoryDB) GetBidsAPI(
472 slotNum *int64, bidderAddr *ethCommon.Address,
473 fromItem, limit *uint, order string,
474) ([]BidAPI, uint64, error) {
475 var query string
476 var args []interface{}
477 // JOIN each bid with the latest update of each coordinator
478 queryStr := `SELECT bid.*, block.timestamp, coord.forger_addr, coord.url,
479 COUNT(*) OVER() AS total_items
480 FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
481 INNER JOIN (
482 SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
483 GROUP BY bidder_addr
484 ) c ON bid.bidder_addr = c.bidder_addr
485 INNER JOIN coordinator coord ON c.item_id = coord.item_id `
486 // Apply filters
487 nextIsAnd := false
488 // slotNum filter
489 if slotNum != nil {
490 if nextIsAnd {
491 queryStr += "AND "
492 } else {
493 queryStr += "WHERE "
494 }
495 queryStr += "bid.slot_num = ? "
496 args = append(args, slotNum)
497 nextIsAnd = true
498 }
499 // bidder filter
500 if bidderAddr != nil {
501 if nextIsAnd {
502 queryStr += "AND "
503 } else {
504 queryStr += "WHERE "
505 }
506 queryStr += "bid.bidder_addr = ? "
507 args = append(args, bidderAddr)
508 nextIsAnd = true
509 }
510 if fromItem != nil {
511 if nextIsAnd {
512 queryStr += "AND "
513 } else {
514 queryStr += "WHERE "
515 }
516 if order == OrderAsc {
517 queryStr += "bid.item_id >= ? "
518 } else {
519 queryStr += "bid.item_id <= ? "
520 }
521 args = append(args, fromItem)
522 }
523 // pagination
524 queryStr += "ORDER BY bid.item_id "
525 if order == OrderAsc {
526 queryStr += "ASC "
527 } else {
528 queryStr += "DESC "
529 }
530 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
531 query, argsQ, err := sqlx.In(queryStr, args...)
532 if err != nil {
533 return nil, 0, tracerr.Wrap(err)
534 }
535 query = hdb.db.Rebind(query)
536 bids := []*BidAPI{}
537 if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
538 return nil, 0, tracerr.Wrap(err)
539 }
540 if len(bids) == 0 {
541 return []BidAPI{}, 0, nil
542 }
543 return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
544}
545
546// AddCoordinators insert Coordinators into the DB
547func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
548 return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
549}
550func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
551 if len(coordinators) == 0 {
552 return nil
553 }
554 return tracerr.Wrap(db.BulkInsert(
555 d,
556 "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
557 coordinators[:],
558 ))
559}
560
561// AddExitTree insert Exit tree into the DB
562func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
563 return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
564}
565func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
566 if len(exitTree) == 0 {
567 return nil
568 }
569 return tracerr.Wrap(db.BulkInsert(
570 d,
571 "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
572 "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
573 exitTree[:],
574 ))
575}
576
577func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
578 rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
579 if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
580 return nil
581 }
582 type withdrawal struct {
583 BatchNum int64 `db:"batch_num"`
584 AccountIdx int64 `db:"account_idx"`
585 InstantWithdrawn *int64 `db:"instant_withdrawn"`
586 DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
587 DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
588 Owner *ethCommon.Address `db:"owner"`
589 Token *ethCommon.Address `db:"token"`
590 }
591 withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
592 for i := range rollupWithdrawals {
593 info := &rollupWithdrawals[i]
594 withdrawals[i] = withdrawal{
595 BatchNum: int64(info.NumExitRoot),
596 AccountIdx: int64(info.Idx),
597 }
598 if info.InstantWithdraw {
599 withdrawals[i].InstantWithdrawn = &blockNum
600 } else {
601 withdrawals[i].DelayedWithdrawRequest = &blockNum
602 withdrawals[i].Owner = &info.Owner
603 withdrawals[i].Token = &info.Token
604 }
605 }
606 for i := range wDelayerWithdrawals {
607 info := &wDelayerWithdrawals[i]
608 withdrawals[len(rollupWithdrawals)+i] = withdrawal{
609 DelayedWithdrawn: &blockNum,
610 Owner: &info.Owner,
611 Token: &info.Token,
612 }
613 }
614 // In VALUES we set an initial row of NULLs to set the types of each
615 // variable passed as argument
616 const query string = `
617 UPDATE exit_tree e SET
618 instant_withdrawn = d.instant_withdrawn,
619 delayed_withdraw_request = CASE
620 WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
621 ELSE d.delayed_withdraw_request
622 END,
623 delayed_withdrawn = d.delayed_withdrawn,
624 owner = d.owner,
625 token = d.token
626 FROM (VALUES
627 (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
628 (:batch_num,
629 :account_idx,
630 :instant_withdrawn,
631 :delayed_withdraw_request,
632 :delayed_withdrawn,
633 :owner,
634 :token)
635 ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
636 WHERE
637 (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
638 (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
639 `
640 if len(withdrawals) > 0 {
641 if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
642 return tracerr.Wrap(err)
643 }
644 }
645
646 return nil
647}
648
649// AddToken insert a token into the DB
650func (hdb *HistoryDB) AddToken(token *common.Token) error {
651 return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
652}
653
654// AddTokens insert tokens into the DB
655func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
656func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
657 if len(tokens) == 0 {
658 return nil
659 }
660 // Sanitize name and symbol
661 for i, token := range tokens {
662 token.Name = strings.ToValidUTF8(token.Name, " ")
663 token.Symbol = strings.ToValidUTF8(token.Symbol, " ")
664 tokens[i] = token
665 }
666 return tracerr.Wrap(db.BulkInsert(
667 d,
668 `INSERT INTO token (
669 token_id,
670 eth_block_num,
671 eth_addr,
672 name,
673 symbol,
674 decimals
675 ) VALUES %s;`,
676 tokens[:],
677 ))
678}
679
680// UpdateTokenValue updates the USD value of a token
681func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
682 // Sanitize symbol
683 tokenSymbol = strings.ToValidUTF8(tokenSymbol, " ")
684
685 _, err := hdb.db.Exec(
686 "UPDATE token SET usd = $1 WHERE symbol = $2;",
687 value, tokenSymbol,
688 )
689 return tracerr.Wrap(err)
690}
691
692// GetToken returns a token from the DB given a TokenID
693func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
694 token := &TokenWithUSD{}
695 err := meddler.QueryRow(
696 hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
697 )
698 return token, tracerr.Wrap(err)
699}
700
701// GetAllTokens returns all tokens from the DB
702func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
703 var tokens []*TokenWithUSD
704 err := meddler.QueryAll(
705 hdb.db, &tokens,
706 "SELECT * FROM token ORDER BY token_id;",
707 )
708 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
709}
710
711// GetTokens returns a list of tokens from the DB
712func (hdb *HistoryDB) GetTokens(
713 ids []common.TokenID, symbols []string, name string, fromItem,
714 limit *uint, order string,
715) ([]TokenWithUSD, uint64, error) {
716 var query string
717 var args []interface{}
718 queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
719 // Apply filters
720 nextIsAnd := false
721 if len(ids) > 0 {
722 queryStr += "WHERE token_id IN (?) "
723 nextIsAnd = true
724 args = append(args, ids)
725 }
726 if len(symbols) > 0 {
727 if nextIsAnd {
728 queryStr += "AND "
729 } else {
730 queryStr += "WHERE "
731 }
732 queryStr += "symbol IN (?) "
733 args = append(args, symbols)
734 nextIsAnd = true
735 }
736 if name != "" {
737 if nextIsAnd {
738 queryStr += "AND "
739 } else {
740 queryStr += "WHERE "
741 }
742 queryStr += "name ~ ? "
743 args = append(args, name)
744 nextIsAnd = true
745 }
746 if fromItem != nil {
747 if nextIsAnd {
748 queryStr += "AND "
749 } else {
750 queryStr += "WHERE "
751 }
752 if order == OrderAsc {
753 queryStr += "item_id >= ? "
754 } else {
755 queryStr += "item_id <= ? "
756 }
757 args = append(args, fromItem)
758 }
759 // pagination
760 queryStr += "ORDER BY item_id "
761 if order == OrderAsc {
762 queryStr += "ASC "
763 } else {
764 queryStr += "DESC "
765 }
766 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
767 query, argsQ, err := sqlx.In(queryStr, args...)
768 if err != nil {
769 return nil, 0, tracerr.Wrap(err)
770 }
771 query = hdb.db.Rebind(query)
772 tokens := []*TokenWithUSD{}
773 if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
774 return nil, 0, tracerr.Wrap(err)
775 }
776 if len(tokens) == 0 {
777 return []TokenWithUSD{}, 0, nil
778 }
779 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
780}
781
782// GetTokenSymbols returns all the token symbols from the DB
783func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
784 var tokenSymbols []string
785 rows, err := hdb.db.Query("SELECT symbol FROM token;")
786 if err != nil {
787 return nil, tracerr.Wrap(err)
788 }
789 defer db.RowsClose(rows)
790 sym := new(string)
791 for rows.Next() {
792 err = rows.Scan(sym)
793 if err != nil {
794 return nil, tracerr.Wrap(err)
795 }
796 tokenSymbols = append(tokenSymbols, *sym)
797 }
798 return tokenSymbols, nil
799}
800
801// AddAccounts insert accounts into the DB
802func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
803 return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
804}
805func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
806 if len(accounts) == 0 {
807 return nil
808 }
809 return tracerr.Wrap(db.BulkInsert(
810 d,
811 `INSERT INTO account (
812 idx,
813 token_id,
814 batch_num,
815 bjj,
816 eth_addr
817 ) VALUES %s;`,
818 accounts[:],
819 ))
820}
821
822// GetAllAccounts returns a list of accounts from the DB
823func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
824 var accs []*common.Account
825 err := meddler.QueryAll(
826 hdb.db, &accs,
827 "SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
828 )
829 return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
830}
831
832// AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
833// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
834// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
835// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
836func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
837 return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
838}
839
840// addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
841// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
842// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
843// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
844func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
845 if len(l1txs) == 0 {
846 return nil
847 }
848 txs := []txWrite{}
849 for i := 0; i < len(l1txs); i++ {
850 af := new(big.Float).SetInt(l1txs[i].Amount)
851 amountFloat, _ := af.Float64()
852 laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
853 depositAmountFloat, _ := laf.Float64()
854 txs = append(txs, txWrite{
855 // Generic
856 IsL1: true,
857 TxID: l1txs[i].TxID,
858 Type: l1txs[i].Type,
859 Position: l1txs[i].Position,
860 FromIdx: &l1txs[i].FromIdx,
861 ToIdx: l1txs[i].ToIdx,
862 Amount: l1txs[i].Amount,
863 AmountFloat: amountFloat,
864 TokenID: l1txs[i].TokenID,
865 BatchNum: l1txs[i].BatchNum,
866 EthBlockNum: l1txs[i].EthBlockNum,
867 // L1
868 ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
869 UserOrigin: &l1txs[i].UserOrigin,
870 FromEthAddr: &l1txs[i].FromEthAddr,
871 FromBJJ: &l1txs[i].FromBJJ,
872 DepositAmount: l1txs[i].DepositAmount,
873 DepositAmountFloat: &depositAmountFloat,
874 })
875 }
876 return tracerr.Wrap(hdb.addTxs(d, txs))
877}
878
879// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
880func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
881 return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
882}
883
884// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
885func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
886 txs := []txWrite{}
887 for i := 0; i < len(l2txs); i++ {
888 f := new(big.Float).SetInt(l2txs[i].Amount)
889 amountFloat, _ := f.Float64()
890 txs = append(txs, txWrite{
891 // Generic
892 IsL1: false,
893 TxID: l2txs[i].TxID,
894 Type: l2txs[i].Type,
895 Position: l2txs[i].Position,
896 FromIdx: &l2txs[i].FromIdx,
897 ToIdx: l2txs[i].ToIdx,
898 Amount: l2txs[i].Amount,
899 AmountFloat: amountFloat,
900 BatchNum: &l2txs[i].BatchNum,
901 EthBlockNum: l2txs[i].EthBlockNum,
902 // L2
903 Fee: &l2txs[i].Fee,
904 Nonce: &l2txs[i].Nonce,
905 })
906 }
907 return tracerr.Wrap(hdb.addTxs(d, txs))
908}
909
910func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
911 if len(txs) == 0 {
912 return nil
913 }
914 return tracerr.Wrap(db.BulkInsert(
915 d,
916 `INSERT INTO tx (
917 is_l1,
918 id,
919 type,
920 position,
921 from_idx,
922 to_idx,
923 amount,
924 amount_f,
925 token_id,
926 batch_num,
927 eth_block_num,
928 to_forge_l1_txs_num,
929 user_origin,
930 from_eth_addr,
931 from_bjj,
932 deposit_amount,
933 deposit_amount_f,
934 fee,
935 nonce
936 ) VALUES %s;`,
937 txs[:],
938 ))
939}
940
941// // GetTxs returns a list of txs from the DB
942// func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
943// var txs []*common.Tx
944// err := meddler.QueryAll(
945// hdb.db, &txs,
946// `SELECT * FROM tx
947// ORDER BY (batch_num, position) ASC`,
948// )
949// return db.SlicePtrsToSlice(txs).([]common.Tx), err
950// }
951
952// GetHistoryTx returns a tx from the DB given a TxID
953func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
954 // Warning: amount_success and deposit_amount_success have true as default for
955 // performance reasons. The expected default value is false (when txs are unforged)
956 // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
957 tx := &TxAPI{}
958 err := meddler.QueryRow(
959 hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
960 hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
961 hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
962 tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
963 tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
964 tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
965 token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
966 token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
967 token.usd_update, block.timestamp
968 FROM tx INNER JOIN token ON tx.token_id = token.token_id
969 INNER JOIN block ON tx.eth_block_num = block.eth_block_num
970 WHERE tx.id = $1;`, txID,
971 )
972 return tx, tracerr.Wrap(err)
973}
974
975// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
976// and pagination info
977func (hdb *HistoryDB) GetHistoryTxs(
978 ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
979 tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
980 fromItem, limit *uint, order string,
981) ([]TxAPI, uint64, error) {
982 // Warning: amount_success and deposit_amount_success have true as default for
983 // performance reasons. The expected default value is false (when txs are unforged)
984 // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
985 if ethAddr != nil && bjj != nil {
986 return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
987 }
988 var query string
989 var args []interface{}
990 queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
991 hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
992 hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
993 tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
994 tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
995 tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
996 token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
997 token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
998 token.usd_update, block.timestamp, count(*) OVER() AS total_items
999 FROM tx INNER JOIN token ON tx.token_id = token.token_id
1000 INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
1001 // Apply filters
1002 nextIsAnd := false
1003 // ethAddr filter
1004 if ethAddr != nil {
1005 queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
1006 nextIsAnd = true
1007 args = append(args, ethAddr, ethAddr)
1008 } else if bjj != nil { // bjj filter
1009 queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
1010 nextIsAnd = true
1011 args = append(args, bjj, bjj)
1012 }
1013 // tokenID filter
1014 if tokenID != nil {
1015 if nextIsAnd {
1016 queryStr += "AND "
1017 } else {
1018 queryStr += "WHERE "
1019 }
1020 queryStr += "tx.token_id = ? "
1021 args = append(args, tokenID)
1022 nextIsAnd = true
1023 }
1024 // idx filter
1025 if idx != nil {
1026 if nextIsAnd {
1027 queryStr += "AND "
1028 } else {
1029 queryStr += "WHERE "
1030 }
1031 queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
1032 args = append(args, idx, idx)
1033 nextIsAnd = true
1034 }
1035 // batchNum filter
1036 if batchNum != nil {
1037 if nextIsAnd {
1038 queryStr += "AND "
1039 } else {
1040 queryStr += "WHERE "
1041 }
1042 queryStr += "tx.batch_num = ? "
1043 args = append(args, batchNum)
1044 nextIsAnd = true
1045 }
1046 // txType filter
1047 if txType != nil {
1048 if nextIsAnd {
1049 queryStr += "AND "
1050 } else {
1051 queryStr += "WHERE "
1052 }
1053 queryStr += "tx.type = ? "
1054 args = append(args, txType)
1055 nextIsAnd = true
1056 }
1057 if fromItem != nil {
1058 if nextIsAnd {
1059 queryStr += "AND "
1060 } else {
1061 queryStr += "WHERE "
1062 }
1063 if order == OrderAsc {
1064 queryStr += "tx.item_id >= ? "
1065 } else {
1066 queryStr += "tx.item_id <= ? "
1067 }
1068 args = append(args, fromItem)
1069 nextIsAnd = true
1070 }
1071 if nextIsAnd {
1072 queryStr += "AND "
1073 } else {
1074 queryStr += "WHERE "
1075 }
1076 queryStr += "tx.batch_num IS NOT NULL "
1077
1078 // pagination
1079 queryStr += "ORDER BY tx.item_id "
1080 if order == OrderAsc {
1081 queryStr += " ASC "
1082 } else {
1083 queryStr += " DESC "
1084 }
1085 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1086 query = hdb.db.Rebind(queryStr)
1087 // log.Debug(query)
1088 txsPtrs := []*TxAPI{}
1089 if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
1090 return nil, 0, tracerr.Wrap(err)
1091 }
1092 txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
1093 if len(txs) == 0 {
1094 return txs, 0, nil
1095 }
1096 return txs, txs[0].TotalItems - uint64(len(txs)), nil
1097}
1098
1099// GetAllExits returns all exit from the DB
1100func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
1101 var exits []*common.ExitInfo
1102 err := meddler.QueryAll(
1103 hdb.db, &exits,
1104 `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
1105 exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
1106 exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
1107 )
1108 return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
1109}
1110
1111// GetExitAPI returns a exit from the DB
1112func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
1113 exit := &ExitAPI{}
1114 err := meddler.QueryRow(
1115 hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
1116 hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
1117 account.bjj, account.eth_addr,
1118 exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
1119 exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
1120 token.token_id, token.item_id AS token_item_id,
1121 token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
1122 token.decimals, token.usd, token.usd_update
1123 FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
1124 INNER JOIN token ON account.token_id = token.token_id
1125 WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
1126 )
1127 return exit, tracerr.Wrap(err)
1128}
1129
1130// GetExitsAPI returns a list of exits from the DB and pagination info
1131func (hdb *HistoryDB) GetExitsAPI(
1132 ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
1133 idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
1134 fromItem, limit *uint, order string,
1135) ([]ExitAPI, uint64, error) {
1136 if ethAddr != nil && bjj != nil {
1137 return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
1138 }
1139 var query string
1140 var args []interface{}
1141 queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
1142 hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
1143 account.bjj, account.eth_addr,
1144 exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
1145 exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
1146 token.token_id, token.item_id AS token_item_id,
1147 token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
1148 token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
1149 FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
1150 INNER JOIN token ON account.token_id = token.token_id `
1151 // Apply filters
1152 nextIsAnd := false
1153 // ethAddr filter
1154 if ethAddr != nil {
1155 queryStr += "WHERE account.eth_addr = ? "
1156 nextIsAnd = true
1157 args = append(args, ethAddr)
1158 } else if bjj != nil { // bjj filter
1159 queryStr += "WHERE account.bjj = ? "
1160 nextIsAnd = true
1161 args = append(args, bjj)
1162 }
1163 // tokenID filter
1164 if tokenID != nil {
1165 if nextIsAnd {
1166 queryStr += "AND "
1167 } else {
1168 queryStr += "WHERE "
1169 }
1170 queryStr += "account.token_id = ? "
1171 args = append(args, tokenID)
1172 nextIsAnd = true
1173 }
1174 // idx filter
1175 if idx != nil {
1176 if nextIsAnd {
1177 queryStr += "AND "
1178 } else {
1179 queryStr += "WHERE "
1180 }
1181 queryStr += "exit_tree.account_idx = ? "
1182 args = append(args, idx)
1183 nextIsAnd = true
1184 }
1185 // batchNum filter
1186 if batchNum != nil {
1187 if nextIsAnd {
1188 queryStr += "AND "
1189 } else {
1190 queryStr += "WHERE "
1191 }
1192 queryStr += "exit_tree.batch_num = ? "
1193 args = append(args, batchNum)
1194 nextIsAnd = true
1195 }
1196 // onlyPendingWithdraws
1197 if onlyPendingWithdraws != nil {
1198 if *onlyPendingWithdraws {
1199 if nextIsAnd {
1200 queryStr += "AND "
1201 } else {
1202 queryStr += "WHERE "
1203 }
1204 queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
1205 nextIsAnd = true
1206 }
1207 }
1208 if fromItem != nil {
1209 if nextIsAnd {
1210 queryStr += "AND "
1211 } else {
1212 queryStr += "WHERE "
1213 }
1214 if order == OrderAsc {
1215 queryStr += "exit_tree.item_id >= ? "
1216 } else {
1217 queryStr += "exit_tree.item_id <= ? "
1218 }
1219 args = append(args, fromItem)
1220 // nextIsAnd = true
1221 }
1222 // pagination
1223 queryStr += "ORDER BY exit_tree.item_id "
1224 if order == OrderAsc {
1225 queryStr += " ASC "
1226 } else {
1227 queryStr += " DESC "
1228 }
1229 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1230 query = hdb.db.Rebind(queryStr)
1231 // log.Debug(query)
1232 exits := []*ExitAPI{}
1233 if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
1234 return nil, 0, tracerr.Wrap(err)
1235 }
1236 if len(exits) == 0 {
1237 return []ExitAPI{}, 0, nil
1238 }
1239 return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
1240}
1241
1242// GetAllL1UserTxs returns all L1UserTxs from the DB
1243func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
1244 var txs []*common.L1Tx
1245 err := meddler.QueryAll(
1246 hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
1247 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1248 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
1249 tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
1250 tx.deposit_amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.deposit_amount_success THEN tx.deposit_amount ELSE '\x' END) AS effective_deposit_amount,
1251 tx.eth_block_num, tx.type, tx.batch_num
1252 FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
1253 )
1254 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
1255}
1256
1257// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
1258func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
1259 var txs []*common.L1Tx
1260 // Since the query specifies that only coordinator txs are returned, it's safe to assume
1261 // that returned txs will always have effective amounts
1262 err := meddler.QueryAll(
1263 hdb.db, &txs,
1264 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1265 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
1266 tx.amount, tx.amount AS effective_amount,
1267 tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
1268 tx.eth_block_num, tx.type, tx.batch_num
1269 FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
1270 )
1271 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
1272}
1273
1274// GetAllL2Txs returns all L2Txs from the DB
1275func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
1276 var txs []*common.L2Tx
1277 err := meddler.QueryAll(
1278 hdb.db, &txs,
1279 `SELECT tx.id, tx.batch_num, tx.position,
1280 tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
1281 tx.type, tx.eth_block_num
1282 FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
1283 )
1284 return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
1285}
1286
1287// GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
1288func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
1289 var txs []*common.L1Tx
1290 err := meddler.QueryAll(
1291 hdb.db, &txs, // only L1 user txs can have batch_num set to null
1292 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1293 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
1294 tx.amount, NULL AS effective_amount,
1295 tx.deposit_amount, NULL AS effective_deposit_amount,
1296 tx.eth_block_num, tx.type, tx.batch_num
1297 FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
1298 ORDER BY position;`,
1299 toForgeL1TxsNum,
1300 )
1301 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
1302}
1303
1304// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
1305
1306// GetLastTxsPosition for a given to_forge_l1_txs_num
1307func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
1308 row := hdb.db.QueryRow(
1309 "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
1310 toForgeL1TxsNum,
1311 )
1312 var lastL1TxsPosition int
1313 return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
1314}
1315
1316// GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
1317func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
1318 *common.WDelayerVariables, error) {
1319 var rollup common.RollupVariables
1320 var auction common.AuctionVariables
1321 var wDelayer common.WDelayerVariables
1322 if err := meddler.QueryRow(hdb.db, &rollup,
1323 "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
1324 return nil, nil, nil, tracerr.Wrap(err)
1325 }
1326 if err := meddler.QueryRow(hdb.db, &auction,
1327 "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
1328 return nil, nil, nil, tracerr.Wrap(err)
1329 }
1330 if err := meddler.QueryRow(hdb.db, &wDelayer,
1331 "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
1332 return nil, nil, nil, tracerr.Wrap(err)
1333 }
1334 return &rollup, &auction, &wDelayer, nil
1335}
1336
1337func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
1338 return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
1339}
1340
1341func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
1342 return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
1343}
1344
1345func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
1346 return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
1347}
1348
1349func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
1350 if len(bucketUpdates) == 0 {
1351 return nil
1352 }
1353 return tracerr.Wrap(db.BulkInsert(
1354 d,
1355 `INSERT INTO bucket_update (
1356 eth_block_num,
1357 num_bucket,
1358 block_stamp,
1359 withdrawals
1360 ) VALUES %s;`,
1361 bucketUpdates[:],
1362 ))
1363}
1364
1365// GetAllBucketUpdates retrieves all the bucket updates
1366func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
1367 var bucketUpdates []*common.BucketUpdate
1368 err := meddler.QueryAll(
1369 hdb.db, &bucketUpdates,
1370 `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
1371 FROM bucket_update ORDER BY item_id;`,
1372 )
1373 return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
1374}
1375
1376func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
1377 if len(tokenExchanges) == 0 {
1378 return nil
1379 }
1380 return tracerr.Wrap(db.BulkInsert(
1381 d,
1382 `INSERT INTO token_exchange (
1383 eth_block_num,
1384 eth_addr,
1385 value_usd
1386 ) VALUES %s;`,
1387 tokenExchanges[:],
1388 ))
1389}
1390
1391// GetAllTokenExchanges retrieves all the token exchanges
1392func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
1393 var tokenExchanges []*common.TokenExchange
1394 err := meddler.QueryAll(
1395 hdb.db, &tokenExchanges,
1396 "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
1397 )
1398 return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
1399}
1400
1401func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
1402 escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
1403 if len(escapeHatchWithdrawals) == 0 {
1404 return nil
1405 }
1406 return tracerr.Wrap(db.BulkInsert(
1407 d,
1408 `INSERT INTO escape_hatch_withdrawal (
1409 eth_block_num,
1410 who_addr,
1411 to_addr,
1412 token_addr,
1413 amount
1414 ) VALUES %s;`,
1415 escapeHatchWithdrawals[:],
1416 ))
1417}
1418
1419// GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
1420func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
1421 var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
1422 err := meddler.QueryAll(
1423 hdb.db, &escapeHatchWithdrawals,
1424 "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
1425 )
1426 return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
1427 tracerr.Wrap(err)
1428}
1429
1430// SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
1431// contract variables. This initial state is stored linked to block 0, which
1432// always exist in the DB and is used to store initialization data that always
1433// exist in the smart contracts.
1434func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
1435 auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
1436 txn, err := hdb.db.Beginx()
1437 if err != nil {
1438 return tracerr.Wrap(err)
1439 }
1440 defer func() {
1441 if err != nil {
1442 db.Rollback(txn)
1443 }
1444 }()
1445 // Force EthBlockNum to be 0 because it's the block used to link data
1446 // that belongs to the creation of the smart contracts
1447 rollup.EthBlockNum = 0
1448 auction.EthBlockNum = 0
1449 wDelayer.EthBlockNum = 0
1450 auction.DefaultSlotSetBidSlotNum = 0
1451 if err := hdb.setRollupVars(txn, rollup); err != nil {
1452 return tracerr.Wrap(err)
1453 }
1454 if err := hdb.setAuctionVars(txn, auction); err != nil {
1455 return tracerr.Wrap(err)
1456 }
1457 if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
1458 return tracerr.Wrap(err)
1459 }
1460
1461 return tracerr.Wrap(txn.Commit())
1462}
1463
1464// setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
1465// of the given l1UserTxs (with an UPDATE)
1466func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
1467 if len(txs) == 0 {
1468 return nil
1469 }
1470 // Effective amounts are stored as success flags in the DB, with true value by default
1471 // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
1472 // updated to become false
1473 type txUpdate struct {
1474 ID common.TxID `db:"id"`
1475 AmountSuccess bool `db:"amount_success"`
1476 DepositAmountSuccess bool `db:"deposit_amount_success"`
1477 }
1478 txUpdates := []txUpdate{}
1479 equal := func(a *big.Int, b *big.Int) bool {
1480 return a.Cmp(b) == 0
1481 }
1482 for i := range txs {
1483 amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
1484 depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
1485 if !amountSuccess || !depositAmountSuccess {
1486 txUpdates = append(txUpdates, txUpdate{
1487 ID: txs[i].TxID,
1488 AmountSuccess: amountSuccess,
1489 DepositAmountSuccess: depositAmountSuccess,
1490 })
1491 }
1492 }
1493 const query string = `
1494 UPDATE tx SET
1495 amount_success = tx_update.amount_success,
1496 deposit_amount_success = tx_update.deposit_amount_success
1497 FROM (VALUES
1498 (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
1499 (:id, :amount_success, :deposit_amount_success)
1500 ) as tx_update (id, amount_success, deposit_amount_success)
1501 WHERE tx.id = tx_update.id;
1502 `
1503 if len(txUpdates) > 0 {
1504 if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
1505 return tracerr.Wrap(err)
1506 }
1507 }
1508 return nil
1509}
1510
1511// AddBlockSCData stores all the information of a block retrieved by the
1512// Synchronizer. Blocks should be inserted in order, leaving no gaps because
1513// the pagination system of the API/DB depends on this. Within blocks, all
1514// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
1515func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
1516 txn, err := hdb.db.Beginx()
1517 if err != nil {
1518 return tracerr.Wrap(err)
1519 }
1520 defer func() {
1521 if err != nil {
1522 db.Rollback(txn)
1523 }
1524 }()
1525
1526 // Add block
1527 if err := hdb.addBlock(txn, &blockData.Block); err != nil {
1528 return tracerr.Wrap(err)
1529 }
1530
1531 // Add Coordinators
1532 if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
1533 return tracerr.Wrap(err)
1534 }
1535
1536 // Add Bids
1537 if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
1538 return tracerr.Wrap(err)
1539 }
1540
1541 // Add Tokens
1542 if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
1543 return tracerr.Wrap(err)
1544 }
1545
1546 // Prepare user L1 txs to be added.
1547 // They must be added before the batch that will forge them (which can be in the same block)
1548 // and after the account that will be sent to (also can be in the same block).
1549 // Note: insert order is not relevant since item_id will be updated by a DB trigger when
1550 // the batch that forges those txs is inserted
1551 userL1s := make(map[common.BatchNum][]common.L1Tx)
1552 for i := range blockData.Rollup.L1UserTxs {
1553 batchThatForgesIsInTheBlock := false
1554 for _, batch := range blockData.Rollup.Batches {
1555 if batch.Batch.ForgeL1TxsNum != nil &&
1556 *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
1557 // Tx is forged in this block. It's guaranteed that:
1558 // * the first batch of the block won't forge user L1 txs that have been added in this block
1559 // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
1560 batchThatForgesIsInTheBlock = true
1561 addAtBatchNum := batch.Batch.BatchNum - 1
1562 userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
1563 break
1564 }
1565 }
1566 if !batchThatForgesIsInTheBlock {
1567 // User artificial batchNum 0 to add txs that are not forge in this block
1568 // after all the accounts of the block have been added
1569 userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
1570 }
1571 }
1572
1573 // Add Batches
1574 for i := range blockData.Rollup.Batches {
1575 batch := &blockData.Rollup.Batches[i]
1576
1577 // Add Batch: this will trigger an update on the DB
1578 // that will set the batch num of forged L1 txs in this batch
1579 if err = hdb.addBatch(txn, &batch.Batch); err != nil {
1580 return tracerr.Wrap(err)
1581 }
1582
1583 // Set the EffectiveAmount and EffectiveDepositAmount of all the
1584 // L1UserTxs that have been forged in this batch
1585 if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
1586 return tracerr.Wrap(err)
1587 }
1588
1589 // Add accounts
1590 if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
1591 return tracerr.Wrap(err)
1592 }
1593
1594 // Add forged l1 coordinator Txs
1595 if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
1596 return tracerr.Wrap(err)
1597 }
1598
1599 // Add l2 Txs
1600 if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
1601 return tracerr.Wrap(err)
1602 }
1603
1604 // Add user L1 txs that will be forged in next batch
1605 if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
1606 if err := hdb.addL1Txs(txn, userlL1s); err != nil {
1607 return tracerr.Wrap(err)
1608 }
1609 }
1610
1611 // Add exit tree
1612 if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
1613 return tracerr.Wrap(err)
1614 }
1615 }
1616 // Add user L1 txs that won't be forged in this block
1617 if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
1618 if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
1619 return tracerr.Wrap(err)
1620 }
1621 }
1622
1623 // Set SC Vars if there was an update
1624 if blockData.Rollup.Vars != nil {
1625 if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
1626 return tracerr.Wrap(err)
1627 }
1628 }
1629 if blockData.Auction.Vars != nil {
1630 if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
1631 return tracerr.Wrap(err)
1632 }
1633 }
1634 if blockData.WDelayer.Vars != nil {
1635 if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
1636 return tracerr.Wrap(err)
1637 }
1638 }
1639
1640 // Update withdrawals in exit tree table
1641 if err := hdb.updateExitTree(txn, blockData.Block.Num,
1642 blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
1643 return tracerr.Wrap(err)
1644 }
1645
1646 // Add Escape Hatch Withdrawals
1647 if err := hdb.addEscapeHatchWithdrawals(txn,
1648 blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
1649 return tracerr.Wrap(err)
1650 }
1651
1652 // Add Buckets withdrawals updates
1653 if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
1654 return tracerr.Wrap(err)
1655 }
1656
1657 // Add Token exchange updates
1658 if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
1659 return tracerr.Wrap(err)
1660 }
1661
1662 return tracerr.Wrap(txn.Commit())
1663}
1664
1665// GetCoordinatorAPI returns a coordinator by its bidderAddr
1666func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
1667 coordinator := &CoordinatorAPI{}
1668 err := meddler.QueryRow(
1669 hdb.db, coordinator,
1670 "SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
1671 bidderAddr,
1672 )
1673 return coordinator, tracerr.Wrap(err)
1674}
1675
1676// GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
1677func (hdb *HistoryDB) GetCoordinatorsAPI(
1678 bidderAddr, forgerAddr *ethCommon.Address,
1679 fromItem, limit *uint, order string,
1680) ([]CoordinatorAPI, uint64, error) {
1681 var query string
1682 var args []interface{}
1683 queryStr := `SELECT coordinator.*, COUNT(*) OVER() AS total_items
1684 FROM coordinator INNER JOIN (
1685 SELECT MAX(item_id) AS item_id FROM coordinator
1686 GROUP BY bidder_addr
1687 ) c ON coordinator.item_id = c.item_id `
1688 // Apply filters
1689 nextIsAnd := false
1690 if bidderAddr != nil {
1691 queryStr += "WHERE bidder_addr = ? "
1692 nextIsAnd = true
1693 args = append(args, bidderAddr)
1694 }
1695 if forgerAddr != nil {
1696 if nextIsAnd {
1697 queryStr += "AND "
1698 } else {
1699 queryStr += "WHERE "
1700 }
1701 queryStr += "forger_addr = ? "
1702 nextIsAnd = true
1703 args = append(args, forgerAddr)
1704 }
1705 if fromItem != nil {
1706 if nextIsAnd {
1707 queryStr += "AND "
1708 } else {
1709 queryStr += "WHERE "
1710 }
1711 if order == OrderAsc {
1712 queryStr += "coordinator.item_id >= ? "
1713 } else {
1714 queryStr += "coordinator.item_id <= ? "
1715 }
1716 args = append(args, fromItem)
1717 }
1718 // pagination
1719 queryStr += "ORDER BY coordinator.item_id "
1720 if order == OrderAsc {
1721 queryStr += " ASC "
1722 } else {
1723 queryStr += " DESC "
1724 }
1725 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1726 query = hdb.db.Rebind(queryStr)
1727
1728 coordinators := []*CoordinatorAPI{}
1729 if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
1730 return nil, 0, tracerr.Wrap(err)
1731 }
1732 if len(coordinators) == 0 {
1733 return []CoordinatorAPI{}, 0, nil
1734 }
1735 return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
1736 coordinators[0].TotalItems - uint64(len(coordinators)), nil
1737}
1738
1739// AddAuctionVars insert auction vars into the DB
1740func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
1741 return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
1742}
1743
1744// GetAuctionVars returns auction variables
1745func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
1746 auctionVars := &common.AuctionVariables{}
1747 err := meddler.QueryRow(
1748 hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
1749 )
1750 return auctionVars, tracerr.Wrap(err)
1751}
1752
1753// GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
1754// from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
1755func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
1756 auctionVars := []*MinBidInfo{}
1757 query := `
1758 SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
1759 WHERE default_slot_set_bid_slot_num < $1
1760 ORDER BY default_slot_set_bid_slot_num DESC
1761 LIMIT $2;
1762 `
1763 err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
1764 if err != nil {
1765 return nil, tracerr.Wrap(err)
1766 }
1767 return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
1768}
1769
1770// GetAccountAPI returns an account by its index
1771func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
1772 account := &AccountAPI{}
1773 err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
1774 token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
1775 token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
1776 token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
1777 FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
1778
1779 if err != nil {
1780 return nil, tracerr.Wrap(err)
1781 }
1782
1783 return account, nil
1784}
1785
1786// GetAccountsAPI returns a list of accounts from the DB and pagination info
1787func (hdb *HistoryDB) GetAccountsAPI(
1788 tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
1789 bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
1790) ([]AccountAPI, uint64, error) {
1791 if ethAddr != nil && bjj != nil {
1792 return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
1793 }
1794 var query string
1795 var args []interface{}
1796 queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
1797 account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
1798 token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
1799 COUNT(*) OVER() AS total_items
1800 FROM account INNER JOIN token ON account.token_id = token.token_id `
1801 // Apply filters
1802 nextIsAnd := false
1803 // ethAddr filter
1804 if ethAddr != nil {
1805 queryStr += "WHERE account.eth_addr = ? "
1806 nextIsAnd = true
1807 args = append(args, ethAddr)
1808 } else if bjj != nil { // bjj filter
1809 queryStr += "WHERE account.bjj = ? "
1810 nextIsAnd = true
1811 args = append(args, bjj)
1812 }
1813 // tokenID filter
1814 if len(tokenIDs) > 0 {
1815 if nextIsAnd {
1816 queryStr += "AND "
1817 } else {
1818 queryStr += "WHERE "
1819 }
1820 queryStr += "account.token_id IN (?) "
1821 args = append(args, tokenIDs)
1822 nextIsAnd = true
1823 }
1824 if fromItem != nil {
1825 if nextIsAnd {
1826 queryStr += "AND "
1827 } else {
1828 queryStr += "WHERE "
1829 }
1830 if order == OrderAsc {
1831 queryStr += "account.item_id >= ? "
1832 } else {
1833 queryStr += "account.item_id <= ? "
1834 }
1835 args = append(args, fromItem)
1836 }
1837 // pagination
1838 queryStr += "ORDER BY account.item_id "
1839 if order == OrderAsc {
1840 queryStr += " ASC "
1841 } else {
1842 queryStr += " DESC "
1843 }
1844 queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1845 query, argsQ, err := sqlx.In(queryStr, args...)
1846 if err != nil {
1847 return nil, 0, tracerr.Wrap(err)
1848 }
1849 query = hdb.db.Rebind(query)
1850
1851 accounts := []*AccountAPI{}
1852 if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
1853 return nil, 0, tracerr.Wrap(err)
1854 }
1855 if len(accounts) == 0 {
1856 return []AccountAPI{}, 0, nil
1857 }
1858
1859 return db.SlicePtrsToSlice(accounts).([]AccountAPI),
1860 accounts[0].TotalItems - uint64(len(accounts)), nil
1861}
1862
1863// GetMetrics returns metrics
1864func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
1865 metricsTotals := &MetricsTotals{}
1866 metrics := &Metrics{}
1867 err := meddler.QueryRow(
1868 hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
1869 COALESCE (MIN(tx.batch_num), 0) as batch_num, COALESCE (MIN(block.timestamp),
1870 NOW()) AS min_timestamp, COALESCE (MAX(block.timestamp), NOW()) AS max_timestamp
1871 FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
1872 WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
1873 if err != nil {
1874 return nil, tracerr.Wrap(err)
1875 }
1876
1877 seconds := metricsTotals.MaxTimestamp.Sub(metricsTotals.MinTimestamp).Seconds()
1878 // Avoid dividing by 0
1879 if seconds == 0 {
1880 seconds++
1881 }
1882
1883 metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions) / seconds
1884
1885 if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
1886 metrics.TransactionsPerBatch = float64(metricsTotals.TotalTransactions) /
1887 float64(lastBatchNum-metricsTotals.FirstBatchNum+1)
1888 } else {
1889 metrics.TransactionsPerBatch = float64(0)
1890 }
1891
1892 err = meddler.QueryRow(
1893 hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
1894 COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
1895 WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
1896 if err != nil {
1897 return nil, tracerr.Wrap(err)
1898 }
1899 if metricsTotals.TotalBatches > 0 {
1900 metrics.BatchFrequency = seconds / float64(metricsTotals.TotalBatches)
1901 } else {
1902 metrics.BatchFrequency = 0
1903 }
1904 if metricsTotals.TotalTransactions > 0 {
1905 metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
1906 } else {
1907 metrics.AvgTransactionFee = 0
1908 }
1909 err = meddler.QueryRow(
1910 hdb.db, metrics,
1911 `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
1912 if err != nil {
1913 return nil, tracerr.Wrap(err)
1914 }
1915
1916 return metrics, nil
1917}
1918
1919// GetAvgTxFee returns average transaction fee of the last 1h
1920func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
1921 metricsTotals := &MetricsTotals{}
1922 err := meddler.QueryRow(
1923 hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
1924 COALESCE (MIN(tx.batch_num), 0) as batch_num
1925 FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
1926 WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
1927 if err != nil {
1928 return 0, tracerr.Wrap(err)
1929 }
1930 err = meddler.QueryRow(
1931 hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
1932 COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
1933 WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
1934 if err != nil {
1935 return 0, tracerr.Wrap(err)
1936 }
1937
1938 var avgTransactionFee float64
1939 if metricsTotals.TotalTransactions > 0 {
1940 avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
1941 } else {
1942 avgTransactionFee = 0
1943 }
1944
1945 return avgTransactionFee, nil
1946}