hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
1package historydb
2
3import (
4 "math"
5 "math/big"
6 "strings"
7
8 ethCommon "github.com/ethereum/go-ethereum/common"
9 "github.com/hermeznetwork/hermez-node/common"
10 "github.com/hermeznetwork/hermez-node/db"
11 "github.com/hermeznetwork/tracerr"
12 "github.com/jmoiron/sqlx"
13
14 //nolint:errcheck // driver for postgres DB
15 _ "github.com/lib/pq"
16 "github.com/russross/meddler"
17)
18
19const (
20 // OrderAsc indicates ascending order when using pagination
21 OrderAsc = "ASC"
22 // OrderDesc indicates descending order when using pagination
23 OrderDesc = "DESC"
24)
25
26// TODO(Edu): Document here how HistoryDB is kept consistent
27
28// HistoryDB persist the historic of the rollup
29type HistoryDB struct {
30 db *sqlx.DB
31 apiConnCon *db.APIConnectionController
32}
33
34// NewHistoryDB initialize the DB
35func NewHistoryDB(db *sqlx.DB, apiConnCon *db.APIConnectionController) *HistoryDB {
36 return &HistoryDB{db: db, apiConnCon: apiConnCon}
37}
38
39// DB returns a pointer to the L2DB.db. This method should be used only for
40// internal testing purposes.
41func (hdb *HistoryDB) DB() *sqlx.DB {
42 return hdb.db
43}
44
45// AddBlock insert a block into the DB
46func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
47func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
48 return tracerr.Wrap(meddler.Insert(d, "block", block))
49}
50
51// AddBlocks inserts blocks into the DB
52func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
53 return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
54}
55
56func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
57 return tracerr.Wrap(db.BulkInsert(
58 d,
59 `INSERT INTO block (
60 eth_block_num,
61 timestamp,
62 hash
63 ) VALUES %s;`,
64 blocks,
65 ))
66}
67
68// GetBlock retrieve a block from the DB, given a block number
69func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
70 block := &common.Block{}
71 err := meddler.QueryRow(
72 hdb.db, block,
73 "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
74 )
75 return block, tracerr.Wrap(err)
76}
77
78// GetAllBlocks retrieve all blocks from the DB
79func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
80 var blocks []*common.Block
81 err := meddler.QueryAll(
82 hdb.db, &blocks,
83 "SELECT * FROM block ORDER BY eth_block_num;",
84 )
85 return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
86}
87
88// getBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
89func (hdb *HistoryDB) getBlocks(from, to int64) ([]common.Block, error) {
90 var blocks []*common.Block
91 err := meddler.QueryAll(
92 hdb.db, &blocks,
93 "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
94 from, to,
95 )
96 return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
97}
98
99// GetLastBlock retrieve the block with the highest block number from the DB
100func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
101 block := &common.Block{}
102 err := meddler.QueryRow(
103 hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
104 )
105 return block, tracerr.Wrap(err)
106}
107
108// AddBatch insert a Batch into the DB
109func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
110func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
111 // Calculate total collected fees in USD
112 // Get IDs of collected tokens for fees
113 tokenIDs := []common.TokenID{}
114 for id := range batch.CollectedFees {
115 tokenIDs = append(tokenIDs, id)
116 }
117 // Get USD value of the tokens
118 type tokenPrice struct {
119 ID common.TokenID `meddler:"token_id"`
120 USD *float64 `meddler:"usd"`
121 Decimals int `meddler:"decimals"`
122 }
123 var tokenPrices []*tokenPrice
124 if len(tokenIDs) > 0 {
125 query, args, err := sqlx.In(
126 "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
127 tokenIDs,
128 )
129 if err != nil {
130 return tracerr.Wrap(err)
131 }
132 query = hdb.db.Rebind(query)
133 if err := meddler.QueryAll(
134 hdb.db, &tokenPrices, query, args...,
135 ); err != nil {
136 return tracerr.Wrap(err)
137 }
138 }
139 // Calculate total collected
140 var total float64
141 for _, tokenPrice := range tokenPrices {
142 if tokenPrice.USD == nil {
143 continue
144 }
145 f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
146 amount, _ := f.Float64()
147 total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
148 }
149 batch.TotalFeesUSD = &total
150 // Insert to DB
151 return tracerr.Wrap(meddler.Insert(d, "batch", batch))
152}
153
154// AddBatches insert Bids into the DB
155func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
156 return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
157}
158func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
159 for i := 0; i < len(batches); i++ {
160 if err := hdb.addBatch(d, &batches[i]); err != nil {
161 return tracerr.Wrap(err)
162 }
163 }
164 return nil
165}
166
167// GetBatch returns the batch with the given batchNum
168func (hdb *HistoryDB) GetBatch(batchNum common.BatchNum) (*common.Batch, error) {
169 var batch common.Batch
170 err := meddler.QueryRow(
171 hdb.db, &batch, `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr,
172 batch.fees_collected, batch.fee_idxs_coordinator, batch.state_root,
173 batch.num_accounts, batch.last_idx, batch.exit_root, batch.forge_l1_txs_num,
174 batch.slot_num, batch.total_fees_usd FROM batch WHERE batch_num = $1;`,
175 batchNum,
176 )
177 return &batch, err
178}
179
180// GetAllBatches retrieve all batches from the DB
181func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
182 var batches []*common.Batch
183 err := meddler.QueryAll(
184 hdb.db, &batches,
185 `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
186 batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
187 batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
188 ORDER BY item_id;`,
189 )
190 return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
191}
192
193// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
194func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
195 var batches []*common.Batch
196 err := meddler.QueryAll(
197 hdb.db, &batches,
198 `SELECT batch_num, eth_block_num, forger_addr, fees_collected, fee_idxs_coordinator,
199 state_root, num_accounts, last_idx, exit_root, forge_l1_txs_num, slot_num, total_fees_usd
200 FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;`,
201 from, to,
202 )
203 return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
204}
205
206// GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
207// batch within a slot
208func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
209 row := hdb.db.QueryRow(
210 `SELECT eth_block_num FROM batch
211 WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
212 )
213 var blockNum int64
214 return blockNum, tracerr.Wrap(row.Scan(&blockNum))
215}
216
217// GetLastBatchNum returns the BatchNum of the latest forged batch
218func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
219 row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
220 var batchNum common.BatchNum
221 return batchNum, tracerr.Wrap(row.Scan(&batchNum))
222}
223
224// GetLastBatch returns the last forged batch
225func (hdb *HistoryDB) GetLastBatch() (*common.Batch, error) {
226 var batch common.Batch
227 err := meddler.QueryRow(
228 hdb.db, &batch, `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr,
229 batch.fees_collected, batch.fee_idxs_coordinator, batch.state_root,
230 batch.num_accounts, batch.last_idx, batch.exit_root, batch.forge_l1_txs_num,
231 batch.slot_num, batch.total_fees_usd FROM batch ORDER BY batch_num DESC LIMIT 1;`,
232 )
233 return &batch, err
234}
235
236// GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
237func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
238 row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
239 WHERE forge_l1_txs_num IS NOT NULL
240 ORDER BY batch_num DESC LIMIT 1;`)
241 var blockNum int64
242 return blockNum, tracerr.Wrap(row.Scan(&blockNum))
243}
244
245// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
246// batches. If there's no batch in the DB (nil, nil) is returned.
247func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
248 row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
249 lastL1TxsNum := new(int64)
250 return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
251}
252
253// Reorg deletes all the information that was added into the DB after the
254// lastValidBlock. If lastValidBlock is negative, all block information is
255// deleted.
256func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
257 var err error
258 if lastValidBlock < 0 {
259 _, err = hdb.db.Exec("DELETE FROM block;")
260 } else {
261 _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
262 }
263 return tracerr.Wrap(err)
264}
265
266// AddBids insert Bids into the DB
267func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
268func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
269 if len(bids) == 0 {
270 return nil
271 }
272 // TODO: check the coordinator info
273 return tracerr.Wrap(db.BulkInsert(
274 d,
275 "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
276 bids,
277 ))
278}
279
280// GetAllBids retrieve all bids from the DB
281func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
282 var bids []*common.Bid
283 err := meddler.QueryAll(
284 hdb.db, &bids,
285 `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
286 ORDER BY item_id;`,
287 )
288 return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
289}
290
291// GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
292func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
293 bidCoord := &common.BidCoordinator{}
294 err := meddler.QueryRow(
295 hdb.db, bidCoord,
296 `SELECT (
297 SELECT default_slot_set_bid
298 FROM auction_vars
299 WHERE default_slot_set_bid_slot_num <= $1
300 ORDER BY eth_block_num DESC LIMIT 1
301 ),
302 bid.slot_num, bid.bid_value, bid.bidder_addr,
303 coordinator.forger_addr, coordinator.url
304 FROM bid
305 INNER JOIN (
306 SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
307 GROUP BY bidder_addr
308 ) c ON bid.bidder_addr = c.bidder_addr
309 INNER JOIN coordinator ON c.item_id = coordinator.item_id
310 WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
311 slotNum)
312
313 return bidCoord, tracerr.Wrap(err)
314}
315
316// AddCoordinators insert Coordinators into the DB
317func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
318 return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
319}
320func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
321 if len(coordinators) == 0 {
322 return nil
323 }
324 return tracerr.Wrap(db.BulkInsert(
325 d,
326 "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
327 coordinators,
328 ))
329}
330
331// AddExitTree insert Exit tree into the DB
332func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
333 return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
334}
335func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
336 if len(exitTree) == 0 {
337 return nil
338 }
339 return tracerr.Wrap(db.BulkInsert(
340 d,
341 "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
342 "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
343 exitTree,
344 ))
345}
346
347func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
348 rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
349 if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
350 return nil
351 }
352 type withdrawal struct {
353 BatchNum int64 `db:"batch_num"`
354 AccountIdx int64 `db:"account_idx"`
355 InstantWithdrawn *int64 `db:"instant_withdrawn"`
356 DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
357 DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
358 Owner *ethCommon.Address `db:"owner"`
359 Token *ethCommon.Address `db:"token"`
360 }
361 withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
362 for i := range rollupWithdrawals {
363 info := &rollupWithdrawals[i]
364 withdrawals[i] = withdrawal{
365 BatchNum: int64(info.NumExitRoot),
366 AccountIdx: int64(info.Idx),
367 }
368 if info.InstantWithdraw {
369 withdrawals[i].InstantWithdrawn = &blockNum
370 } else {
371 withdrawals[i].DelayedWithdrawRequest = &blockNum
372 withdrawals[i].Owner = &info.Owner
373 withdrawals[i].Token = &info.Token
374 }
375 }
376 for i := range wDelayerWithdrawals {
377 info := &wDelayerWithdrawals[i]
378 withdrawals[len(rollupWithdrawals)+i] = withdrawal{
379 DelayedWithdrawn: &blockNum,
380 Owner: &info.Owner,
381 Token: &info.Token,
382 }
383 }
384 // In VALUES we set an initial row of NULLs to set the types of each
385 // variable passed as argument
386 const query string = `
387 UPDATE exit_tree e SET
388 instant_withdrawn = d.instant_withdrawn,
389 delayed_withdraw_request = CASE
390 WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
391 ELSE d.delayed_withdraw_request
392 END,
393 delayed_withdrawn = d.delayed_withdrawn,
394 owner = d.owner,
395 token = d.token
396 FROM (VALUES
397 (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
398 (:batch_num,
399 :account_idx,
400 :instant_withdrawn,
401 :delayed_withdraw_request,
402 :delayed_withdrawn,
403 :owner,
404 :token)
405 ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
406 WHERE
407 (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
408 (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
409 `
410 if len(withdrawals) > 0 {
411 if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
412 return tracerr.Wrap(err)
413 }
414 }
415
416 return nil
417}
418
419// AddToken insert a token into the DB
420func (hdb *HistoryDB) AddToken(token *common.Token) error {
421 return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
422}
423
424// AddTokens insert tokens into the DB
425func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
426func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
427 if len(tokens) == 0 {
428 return nil
429 }
430 // Sanitize name and symbol
431 for i, token := range tokens {
432 token.Name = strings.ToValidUTF8(token.Name, " ")
433 token.Symbol = strings.ToValidUTF8(token.Symbol, " ")
434 tokens[i] = token
435 }
436 return tracerr.Wrap(db.BulkInsert(
437 d,
438 `INSERT INTO token (
439 token_id,
440 eth_block_num,
441 eth_addr,
442 name,
443 symbol,
444 decimals
445 ) VALUES %s;`,
446 tokens,
447 ))
448}
449
450// UpdateTokenValue updates the USD value of a token. Value is the price in
451// USD of a normalized token (1 token = 10^decimals units)
452func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
453 // Sanitize symbol
454 tokenSymbol = strings.ToValidUTF8(tokenSymbol, " ")
455
456 _, err := hdb.db.Exec(
457 "UPDATE token SET usd = $1 WHERE symbol = $2;",
458 value, tokenSymbol,
459 )
460 return tracerr.Wrap(err)
461}
462
463// GetToken returns a token from the DB given a TokenID
464func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
465 token := &TokenWithUSD{}
466 err := meddler.QueryRow(
467 hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
468 )
469 return token, tracerr.Wrap(err)
470}
471
472// GetAllTokens returns all tokens from the DB
473func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
474 var tokens []*TokenWithUSD
475 err := meddler.QueryAll(
476 hdb.db, &tokens,
477 "SELECT * FROM token ORDER BY token_id;",
478 )
479 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
480}
481
482// GetTokenSymbols returns all the token symbols from the DB
483func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
484 var tokenSymbols []string
485 rows, err := hdb.db.Query("SELECT symbol FROM token;")
486 if err != nil {
487 return nil, tracerr.Wrap(err)
488 }
489 defer db.RowsClose(rows)
490 sym := new(string)
491 for rows.Next() {
492 err = rows.Scan(sym)
493 if err != nil {
494 return nil, tracerr.Wrap(err)
495 }
496 tokenSymbols = append(tokenSymbols, *sym)
497 }
498 return tokenSymbols, nil
499}
500
501// AddAccounts insert accounts into the DB
502func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
503 return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
504}
505func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
506 if len(accounts) == 0 {
507 return nil
508 }
509 return tracerr.Wrap(db.BulkInsert(
510 d,
511 `INSERT INTO account (
512 idx,
513 token_id,
514 batch_num,
515 bjj,
516 eth_addr
517 ) VALUES %s;`,
518 accounts,
519 ))
520}
521
522// GetAllAccounts returns a list of accounts from the DB
523func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
524 var accs []*common.Account
525 err := meddler.QueryAll(
526 hdb.db, &accs,
527 "SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
528 )
529 return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
530}
531
532// AddAccountUpdates inserts accUpdates into the DB
533func (hdb *HistoryDB) AddAccountUpdates(accUpdates []common.AccountUpdate) error {
534 return tracerr.Wrap(hdb.addAccountUpdates(hdb.db, accUpdates))
535}
536func (hdb *HistoryDB) addAccountUpdates(d meddler.DB, accUpdates []common.AccountUpdate) error {
537 if len(accUpdates) == 0 {
538 return nil
539 }
540 return tracerr.Wrap(db.BulkInsert(
541 d,
542 `INSERT INTO account_update (
543 eth_block_num,
544 batch_num,
545 idx,
546 nonce,
547 balance
548 ) VALUES %s;`,
549 accUpdates,
550 ))
551}
552
553// GetAllAccountUpdates returns all the AccountUpdate from the DB
554func (hdb *HistoryDB) GetAllAccountUpdates() ([]common.AccountUpdate, error) {
555 var accUpdates []*common.AccountUpdate
556 err := meddler.QueryAll(
557 hdb.db, &accUpdates,
558 "SELECT eth_block_num, batch_num, idx, nonce, balance FROM account_update ORDER BY idx;",
559 )
560 return db.SlicePtrsToSlice(accUpdates).([]common.AccountUpdate), tracerr.Wrap(err)
561}
562
563// AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
564// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
565// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
566// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
567func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
568 return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
569}
570
571// addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
572// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
573// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
574// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
575func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
576 if len(l1txs) == 0 {
577 return nil
578 }
579 txs := []txWrite{}
580 for i := 0; i < len(l1txs); i++ {
581 af := new(big.Float).SetInt(l1txs[i].Amount)
582 amountFloat, _ := af.Float64()
583 laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
584 depositAmountFloat, _ := laf.Float64()
585 var effectiveFromIdx *common.Idx
586 if l1txs[i].UserOrigin {
587 if l1txs[i].Type != common.TxTypeCreateAccountDeposit &&
588 l1txs[i].Type != common.TxTypeCreateAccountDepositTransfer {
589 effectiveFromIdx = &l1txs[i].FromIdx
590 }
591 } else {
592 effectiveFromIdx = &l1txs[i].EffectiveFromIdx
593 }
594 txs = append(txs, txWrite{
595 // Generic
596 IsL1: true,
597 TxID: l1txs[i].TxID,
598 Type: l1txs[i].Type,
599 Position: l1txs[i].Position,
600 FromIdx: &l1txs[i].FromIdx,
601 EffectiveFromIdx: effectiveFromIdx,
602 ToIdx: l1txs[i].ToIdx,
603 Amount: l1txs[i].Amount,
604 AmountFloat: amountFloat,
605 TokenID: l1txs[i].TokenID,
606 BatchNum: l1txs[i].BatchNum,
607 EthBlockNum: l1txs[i].EthBlockNum,
608 // L1
609 ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
610 UserOrigin: &l1txs[i].UserOrigin,
611 FromEthAddr: &l1txs[i].FromEthAddr,
612 FromBJJ: &l1txs[i].FromBJJ,
613 DepositAmount: l1txs[i].DepositAmount,
614 DepositAmountFloat: &depositAmountFloat,
615 })
616 }
617 return tracerr.Wrap(hdb.addTxs(d, txs))
618}
619
620// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
621func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
622 return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
623}
624
625// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
626func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
627 txs := []txWrite{}
628 for i := 0; i < len(l2txs); i++ {
629 f := new(big.Float).SetInt(l2txs[i].Amount)
630 amountFloat, _ := f.Float64()
631 txs = append(txs, txWrite{
632 // Generic
633 IsL1: false,
634 TxID: l2txs[i].TxID,
635 Type: l2txs[i].Type,
636 Position: l2txs[i].Position,
637 FromIdx: &l2txs[i].FromIdx,
638 EffectiveFromIdx: &l2txs[i].FromIdx,
639 ToIdx: l2txs[i].ToIdx,
640 TokenID: l2txs[i].TokenID,
641 Amount: l2txs[i].Amount,
642 AmountFloat: amountFloat,
643 BatchNum: &l2txs[i].BatchNum,
644 EthBlockNum: l2txs[i].EthBlockNum,
645 // L2
646 Fee: &l2txs[i].Fee,
647 Nonce: &l2txs[i].Nonce,
648 })
649 }
650 return tracerr.Wrap(hdb.addTxs(d, txs))
651}
652
653func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
654 if len(txs) == 0 {
655 return nil
656 }
657 return tracerr.Wrap(db.BulkInsert(
658 d,
659 `INSERT INTO tx (
660 is_l1,
661 id,
662 type,
663 position,
664 from_idx,
665 effective_from_idx,
666 to_idx,
667 amount,
668 amount_f,
669 token_id,
670 batch_num,
671 eth_block_num,
672 to_forge_l1_txs_num,
673 user_origin,
674 from_eth_addr,
675 from_bjj,
676 deposit_amount,
677 deposit_amount_f,
678 fee,
679 nonce
680 ) VALUES %s;`,
681 txs,
682 ))
683}
684
685// GetAllExits returns all exit from the DB
686func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
687 var exits []*common.ExitInfo
688 err := meddler.QueryAll(
689 hdb.db, &exits,
690 `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
691 exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
692 exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
693 )
694 return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
695}
696
697// GetAllL1UserTxs returns all L1UserTxs from the DB
698func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
699 var txs []*common.L1Tx
700 err := meddler.QueryAll(
701 hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
702 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
703 tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
704 tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
705 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,
706 tx.eth_block_num, tx.type, tx.batch_num
707 FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
708 )
709 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
710}
711
712// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
713func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
714 var txs []*common.L1Tx
715 // Since the query specifies that only coordinator txs are returned, it's safe to assume
716 // that returned txs will always have effective amounts
717 err := meddler.QueryAll(
718 hdb.db, &txs,
719 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
720 tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
721 tx.amount, tx.amount AS effective_amount,
722 tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
723 tx.eth_block_num, tx.type, tx.batch_num
724 FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
725 )
726 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
727}
728
729// GetAllL2Txs returns all L2Txs from the DB
730func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
731 var txs []*common.L2Tx
732 err := meddler.QueryAll(
733 hdb.db, &txs,
734 `SELECT tx.id, tx.batch_num, tx.position,
735 tx.from_idx, tx.to_idx, tx.amount, tx.token_id,
736 tx.fee, tx.nonce, tx.type, tx.eth_block_num
737 FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
738 )
739 return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
740}
741
742// GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
743func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
744 var txs []*common.L1Tx
745 err := meddler.QueryAll(
746 hdb.db, &txs, // only L1 user txs can have batch_num set to null
747 `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
748 tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
749 tx.amount, NULL AS effective_amount,
750 tx.deposit_amount, NULL AS effective_deposit_amount,
751 tx.eth_block_num, tx.type, tx.batch_num
752 FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
753 ORDER BY position;`,
754 toForgeL1TxsNum,
755 )
756 return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
757}
758
759// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
760
761// GetLastTxsPosition for a given to_forge_l1_txs_num
762func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
763 row := hdb.db.QueryRow(
764 "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
765 toForgeL1TxsNum,
766 )
767 var lastL1TxsPosition int
768 return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
769}
770
771// GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
772func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
773 *common.WDelayerVariables, error) {
774 var rollup common.RollupVariables
775 var auction common.AuctionVariables
776 var wDelayer common.WDelayerVariables
777 if err := meddler.QueryRow(hdb.db, &rollup,
778 "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
779 return nil, nil, nil, tracerr.Wrap(err)
780 }
781 if err := meddler.QueryRow(hdb.db, &auction,
782 "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
783 return nil, nil, nil, tracerr.Wrap(err)
784 }
785 if err := meddler.QueryRow(hdb.db, &wDelayer,
786 "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
787 return nil, nil, nil, tracerr.Wrap(err)
788 }
789 return &rollup, &auction, &wDelayer, nil
790}
791
792func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
793 return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
794}
795
796func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
797 return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
798}
799
800func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
801 return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
802}
803
804func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
805 if len(bucketUpdates) == 0 {
806 return nil
807 }
808 return tracerr.Wrap(db.BulkInsert(
809 d,
810 `INSERT INTO bucket_update (
811 eth_block_num,
812 num_bucket,
813 block_stamp,
814 withdrawals
815 ) VALUES %s;`,
816 bucketUpdates,
817 ))
818}
819
820// AddBucketUpdatesTest allows call to unexported method
821// only for internal testing purposes
822func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
823 return hdb.addBucketUpdates(d, bucketUpdates)
824}
825
826// GetAllBucketUpdates retrieves all the bucket updates
827func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
828 var bucketUpdates []*common.BucketUpdate
829 err := meddler.QueryAll(
830 hdb.db, &bucketUpdates,
831 `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
832 FROM bucket_update ORDER BY item_id;`,
833 )
834 return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
835}
836
837func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
838 if len(tokenExchanges) == 0 {
839 return nil
840 }
841 return tracerr.Wrap(db.BulkInsert(
842 d,
843 `INSERT INTO token_exchange (
844 eth_block_num,
845 eth_addr,
846 value_usd
847 ) VALUES %s;`,
848 tokenExchanges,
849 ))
850}
851
852// GetAllTokenExchanges retrieves all the token exchanges
853func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
854 var tokenExchanges []*common.TokenExchange
855 err := meddler.QueryAll(
856 hdb.db, &tokenExchanges,
857 "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
858 )
859 return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
860}
861
862func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
863 escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
864 if len(escapeHatchWithdrawals) == 0 {
865 return nil
866 }
867 return tracerr.Wrap(db.BulkInsert(
868 d,
869 `INSERT INTO escape_hatch_withdrawal (
870 eth_block_num,
871 who_addr,
872 to_addr,
873 token_addr,
874 amount
875 ) VALUES %s;`,
876 escapeHatchWithdrawals,
877 ))
878}
879
880// GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
881func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
882 var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
883 err := meddler.QueryAll(
884 hdb.db, &escapeHatchWithdrawals,
885 "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
886 )
887 return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
888 tracerr.Wrap(err)
889}
890
891// SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
892// contract variables. This initial state is stored linked to block 0, which
893// always exist in the DB and is used to store initialization data that always
894// exist in the smart contracts.
895func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
896 auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
897 txn, err := hdb.db.Beginx()
898 if err != nil {
899 return tracerr.Wrap(err)
900 }
901 defer func() {
902 if err != nil {
903 db.Rollback(txn)
904 }
905 }()
906 // Force EthBlockNum to be 0 because it's the block used to link data
907 // that belongs to the creation of the smart contracts
908 rollup.EthBlockNum = 0
909 auction.EthBlockNum = 0
910 wDelayer.EthBlockNum = 0
911 auction.DefaultSlotSetBidSlotNum = 0
912 if err := hdb.setRollupVars(txn, rollup); err != nil {
913 return tracerr.Wrap(err)
914 }
915 if err := hdb.setAuctionVars(txn, auction); err != nil {
916 return tracerr.Wrap(err)
917 }
918 if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
919 return tracerr.Wrap(err)
920 }
921
922 return tracerr.Wrap(txn.Commit())
923}
924
925// setExtraInfoForgedL1UserTxs sets the EffectiveAmount, EffectiveDepositAmount
926// and EffectiveFromIdx of the given l1UserTxs (with an UPDATE)
927func (hdb *HistoryDB) setExtraInfoForgedL1UserTxs(d sqlx.Ext, txs []common.L1Tx) error {
928 if len(txs) == 0 {
929 return nil
930 }
931 // Effective amounts are stored as success flags in the DB, with true value by default
932 // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
933 // updated to become false. At the same time, all the txs that contain
934 // accounts (FromIdx == 0) are updated to set the EffectiveFromIdx.
935 type txUpdate struct {
936 ID common.TxID `db:"id"`
937 AmountSuccess bool `db:"amount_success"`
938 DepositAmountSuccess bool `db:"deposit_amount_success"`
939 EffectiveFromIdx common.Idx `db:"effective_from_idx"`
940 }
941 txUpdates := []txUpdate{}
942 equal := func(a *big.Int, b *big.Int) bool {
943 return a.Cmp(b) == 0
944 }
945 for i := range txs {
946 amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
947 depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
948 if !amountSuccess || !depositAmountSuccess || txs[i].FromIdx == 0 {
949 txUpdates = append(txUpdates, txUpdate{
950 ID: txs[i].TxID,
951 AmountSuccess: amountSuccess,
952 DepositAmountSuccess: depositAmountSuccess,
953 EffectiveFromIdx: txs[i].EffectiveFromIdx,
954 })
955 }
956 }
957 const query string = `
958 UPDATE tx SET
959 amount_success = tx_update.amount_success,
960 deposit_amount_success = tx_update.deposit_amount_success,
961 effective_from_idx = tx_update.effective_from_idx
962 FROM (VALUES
963 (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL, NULL::::BIGINT),
964 (:id, :amount_success, :deposit_amount_success, :effective_from_idx)
965 ) as tx_update (id, amount_success, deposit_amount_success, effective_from_idx)
966 WHERE tx.id = tx_update.id;
967 `
968 if len(txUpdates) > 0 {
969 if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
970 return tracerr.Wrap(err)
971 }
972 }
973 return nil
974}
975
976// AddBlockSCData stores all the information of a block retrieved by the
977// Synchronizer. Blocks should be inserted in order, leaving no gaps because
978// the pagination system of the API/DB depends on this. Within blocks, all
979// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
980func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
981 txn, err := hdb.db.Beginx()
982 if err != nil {
983 return tracerr.Wrap(err)
984 }
985 defer func() {
986 if err != nil {
987 db.Rollback(txn)
988 }
989 }()
990
991 // Add block
992 if err := hdb.addBlock(txn, &blockData.Block); err != nil {
993 return tracerr.Wrap(err)
994 }
995
996 // Add Coordinators
997 if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
998 return tracerr.Wrap(err)
999 }
1000
1001 // Add Bids
1002 if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
1003 return tracerr.Wrap(err)
1004 }
1005
1006 // Add Tokens
1007 if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
1008 return tracerr.Wrap(err)
1009 }
1010
1011 // Prepare user L1 txs to be added.
1012 // They must be added before the batch that will forge them (which can be in the same block)
1013 // and after the account that will be sent to (also can be in the same block).
1014 // Note: insert order is not relevant since item_id will be updated by a DB trigger when
1015 // the batch that forges those txs is inserted
1016 userL1s := make(map[common.BatchNum][]common.L1Tx)
1017 for i := range blockData.Rollup.L1UserTxs {
1018 batchThatForgesIsInTheBlock := false
1019 for _, batch := range blockData.Rollup.Batches {
1020 if batch.Batch.ForgeL1TxsNum != nil &&
1021 *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
1022 // Tx is forged in this block. It's guaranteed that:
1023 // * the first batch of the block won't forge user L1 txs that have been added in this block
1024 // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
1025 batchThatForgesIsInTheBlock = true
1026 addAtBatchNum := batch.Batch.BatchNum - 1
1027 userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
1028 break
1029 }
1030 }
1031 if !batchThatForgesIsInTheBlock {
1032 // User artificial batchNum 0 to add txs that are not forge in this block
1033 // after all the accounts of the block have been added
1034 userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
1035 }
1036 }
1037
1038 // Add Batches
1039 for i := range blockData.Rollup.Batches {
1040 batch := &blockData.Rollup.Batches[i]
1041
1042 // Add Batch: this will trigger an update on the DB
1043 // that will set the batch num of forged L1 txs in this batch
1044 if err = hdb.addBatch(txn, &batch.Batch); err != nil {
1045 return tracerr.Wrap(err)
1046 }
1047
1048 // Add accounts
1049 if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
1050 return tracerr.Wrap(err)
1051 }
1052
1053 // Add accountBalances if it exists
1054 if err := hdb.addAccountUpdates(txn, batch.UpdatedAccounts); err != nil {
1055 return tracerr.Wrap(err)
1056 }
1057
1058 // Set the EffectiveAmount and EffectiveDepositAmount of all the
1059 // L1UserTxs that have been forged in this batch
1060 if err = hdb.setExtraInfoForgedL1UserTxs(txn, batch.L1UserTxs); err != nil {
1061 return tracerr.Wrap(err)
1062 }
1063
1064 // Add forged l1 coordinator Txs
1065 if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
1066 return tracerr.Wrap(err)
1067 }
1068
1069 // Add l2 Txs
1070 if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
1071 return tracerr.Wrap(err)
1072 }
1073
1074 // Add user L1 txs that will be forged in next batch
1075 if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
1076 if err := hdb.addL1Txs(txn, userlL1s); err != nil {
1077 return tracerr.Wrap(err)
1078 }
1079 }
1080
1081 // Add exit tree
1082 if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
1083 return tracerr.Wrap(err)
1084 }
1085 }
1086 // Add user L1 txs that won't be forged in this block
1087 if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
1088 if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
1089 return tracerr.Wrap(err)
1090 }
1091 }
1092
1093 // Set SC Vars if there was an update
1094 if blockData.Rollup.Vars != nil {
1095 if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
1096 return tracerr.Wrap(err)
1097 }
1098 }
1099 if blockData.Auction.Vars != nil {
1100 if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
1101 return tracerr.Wrap(err)
1102 }
1103 }
1104 if blockData.WDelayer.Vars != nil {
1105 if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
1106 return tracerr.Wrap(err)
1107 }
1108 }
1109
1110 // Update withdrawals in exit tree table
1111 if err := hdb.updateExitTree(txn, blockData.Block.Num,
1112 blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
1113 return tracerr.Wrap(err)
1114 }
1115
1116 // Add Escape Hatch Withdrawals
1117 if err := hdb.addEscapeHatchWithdrawals(txn,
1118 blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
1119 return tracerr.Wrap(err)
1120 }
1121
1122 // Add Buckets withdrawals updates
1123 if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
1124 return tracerr.Wrap(err)
1125 }
1126
1127 // Add Token exchange updates
1128 if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
1129 return tracerr.Wrap(err)
1130 }
1131
1132 return tracerr.Wrap(txn.Commit())
1133}
1134
1135// GetCoordinatorAPI returns a coordinator by its bidderAddr
1136func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
1137 coordinator := &CoordinatorAPI{}
1138 err := meddler.QueryRow(
1139 hdb.db, coordinator,
1140 "SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
1141 bidderAddr,
1142 )
1143 return coordinator, tracerr.Wrap(err)
1144}
1145
1146// AddAuctionVars insert auction vars into the DB
1147func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
1148 return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
1149}
1150
1151// GetTokensTest used to get tokens in a testing context
1152func (hdb *HistoryDB) GetTokensTest() ([]TokenWithUSD, error) {
1153 tokens := []*TokenWithUSD{}
1154 if err := meddler.QueryAll(
1155 hdb.db, &tokens,
1156 "SELECT * FROM TOKEN",
1157 ); err != nil {
1158 return nil, tracerr.Wrap(err)
1159 }
1160 if len(tokens) == 0 {
1161 return []TokenWithUSD{}, nil
1162 }
1163 return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), nil
1164}