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