arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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(tokenAddr ethCommon.Address, value float64) error {
 460	_, err := hdb.dbWrite.Exec(
 461		"UPDATE token SET usd = $1 WHERE eth_addr = $2;",
 462		value, tokenAddr,
 463	)
 464	return tracerr.Wrap(err)
 465}
 466
 467// GetToken returns a token from the DB given a TokenID
 468func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
 469	token := &TokenWithUSD{}
 470	err := meddler.QueryRow(
 471		hdb.dbRead, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
 472	)
 473	return token, tracerr.Wrap(err)
 474}
 475
 476// GetAllTokens returns all tokens from the DB
 477func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
 478	var tokens []*TokenWithUSD
 479	err := meddler.QueryAll(
 480		hdb.dbRead, &tokens,
 481		"SELECT * FROM token ORDER BY token_id;",
 482	)
 483	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
 484}
 485
 486// GetTokenSymbolsAndAddrs returns all the token symbols and addresses from the DB
 487func (hdb *HistoryDB) GetTokenSymbolsAndAddrs() ([]TokenSymbolAndAddr, error) {
 488	var tokens []*TokenSymbolAndAddr
 489	err := meddler.QueryAll(
 490		hdb.dbRead, &tokens,
 491		"SELECT symbol, eth_addr FROM token;",
 492	)
 493	return db.SlicePtrsToSlice(tokens).([]TokenSymbolAndAddr), tracerr.Wrap(err)
 494}
 495
 496// AddAccounts insert accounts into the DB
 497func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
 498	return tracerr.Wrap(hdb.addAccounts(hdb.dbWrite, accounts))
 499}
 500func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
 501	if len(accounts) == 0 {
 502		return nil
 503	}
 504	return tracerr.Wrap(db.BulkInsert(
 505		d,
 506		`INSERT INTO account (
 507			idx,
 508			token_id,
 509			batch_num,
 510			bjj,
 511			eth_addr
 512		) VALUES %s;`,
 513		accounts,
 514	))
 515}
 516
 517// GetAllAccounts returns a list of accounts from the DB
 518func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
 519	var accs []*common.Account
 520	err := meddler.QueryAll(
 521		hdb.dbRead, &accs,
 522		"SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
 523	)
 524	return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
 525}
 526
 527// AddAccountUpdates inserts accUpdates into the DB
 528func (hdb *HistoryDB) AddAccountUpdates(accUpdates []common.AccountUpdate) error {
 529	return tracerr.Wrap(hdb.addAccountUpdates(hdb.dbWrite, accUpdates))
 530}
 531func (hdb *HistoryDB) addAccountUpdates(d meddler.DB, accUpdates []common.AccountUpdate) error {
 532	if len(accUpdates) == 0 {
 533		return nil
 534	}
 535	return tracerr.Wrap(db.BulkInsert(
 536		d,
 537		`INSERT INTO account_update (
 538			eth_block_num,
 539			batch_num,
 540			idx,
 541			nonce,
 542			balance
 543		) VALUES %s;`,
 544		accUpdates,
 545	))
 546}
 547
 548// GetAllAccountUpdates returns all the AccountUpdate from the DB
 549func (hdb *HistoryDB) GetAllAccountUpdates() ([]common.AccountUpdate, error) {
 550	var accUpdates []*common.AccountUpdate
 551	err := meddler.QueryAll(
 552		hdb.dbRead, &accUpdates,
 553		"SELECT eth_block_num, batch_num, idx, nonce, balance FROM account_update ORDER BY idx;",
 554	)
 555	return db.SlicePtrsToSlice(accUpdates).([]common.AccountUpdate), tracerr.Wrap(err)
 556}
 557
 558// AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
 559// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 560// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 561// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
 562func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
 563	return tracerr.Wrap(hdb.addL1Txs(hdb.dbWrite, l1txs))
 564}
 565
 566// addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
 567// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 568// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 569// EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
 570func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
 571	if len(l1txs) == 0 {
 572		return nil
 573	}
 574	txs := []txWrite{}
 575	for i := 0; i < len(l1txs); i++ {
 576		af := new(big.Float).SetInt(l1txs[i].Amount)
 577		amountFloat, _ := af.Float64()
 578		laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
 579		depositAmountFloat, _ := laf.Float64()
 580		var effectiveFromIdx *common.Idx
 581		if l1txs[i].UserOrigin {
 582			if l1txs[i].Type != common.TxTypeCreateAccountDeposit &&
 583				l1txs[i].Type != common.TxTypeCreateAccountDepositTransfer {
 584				effectiveFromIdx = &l1txs[i].FromIdx
 585			}
 586		} else {
 587			effectiveFromIdx = &l1txs[i].EffectiveFromIdx
 588		}
 589		txs = append(txs, txWrite{
 590			// Generic
 591			IsL1:             true,
 592			TxID:             l1txs[i].TxID,
 593			Type:             l1txs[i].Type,
 594			Position:         l1txs[i].Position,
 595			FromIdx:          &l1txs[i].FromIdx,
 596			EffectiveFromIdx: effectiveFromIdx,
 597			ToIdx:            l1txs[i].ToIdx,
 598			Amount:           l1txs[i].Amount,
 599			AmountFloat:      amountFloat,
 600			TokenID:          l1txs[i].TokenID,
 601			BatchNum:         l1txs[i].BatchNum,
 602			EthBlockNum:      l1txs[i].EthBlockNum,
 603			// L1
 604			ToForgeL1TxsNum:    l1txs[i].ToForgeL1TxsNum,
 605			UserOrigin:         &l1txs[i].UserOrigin,
 606			FromEthAddr:        &l1txs[i].FromEthAddr,
 607			FromBJJ:            &l1txs[i].FromBJJ,
 608			DepositAmount:      l1txs[i].DepositAmount,
 609			DepositAmountFloat: &depositAmountFloat,
 610		})
 611	}
 612	return tracerr.Wrap(hdb.addTxs(d, txs))
 613}
 614
 615// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 616func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
 617	return tracerr.Wrap(hdb.addL2Txs(hdb.dbWrite, l2txs))
 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(d meddler.DB, l2txs []common.L2Tx) error {
 622	txs := []txWrite{}
 623	for i := 0; i < len(l2txs); i++ {
 624		f := new(big.Float).SetInt(l2txs[i].Amount)
 625		amountFloat, _ := f.Float64()
 626		txs = append(txs, txWrite{
 627			// Generic
 628			IsL1:             false,
 629			TxID:             l2txs[i].TxID,
 630			Type:             l2txs[i].Type,
 631			Position:         l2txs[i].Position,
 632			FromIdx:          &l2txs[i].FromIdx,
 633			EffectiveFromIdx: &l2txs[i].FromIdx,
 634			ToIdx:            l2txs[i].ToIdx,
 635			TokenID:          l2txs[i].TokenID,
 636			Amount:           l2txs[i].Amount,
 637			AmountFloat:      amountFloat,
 638			BatchNum:         &l2txs[i].BatchNum,
 639			EthBlockNum:      l2txs[i].EthBlockNum,
 640			// L2
 641			Fee:   &l2txs[i].Fee,
 642			Nonce: &l2txs[i].Nonce,
 643		})
 644	}
 645	return tracerr.Wrap(hdb.addTxs(d, txs))
 646}
 647
 648func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
 649	if len(txs) == 0 {
 650		return nil
 651	}
 652	return tracerr.Wrap(db.BulkInsert(
 653		d,
 654		`INSERT INTO tx (
 655			is_l1,
 656			id,
 657			type,
 658			position,
 659			from_idx,
 660			effective_from_idx,
 661			to_idx,
 662			amount,
 663			amount_f,
 664			token_id,
 665			batch_num,
 666			eth_block_num,
 667			to_forge_l1_txs_num,
 668			user_origin,
 669			from_eth_addr,
 670			from_bjj,
 671			deposit_amount,
 672			deposit_amount_f,
 673			fee,
 674			nonce
 675		) VALUES %s;`,
 676		txs,
 677	))
 678}
 679
 680// GetAllExits returns all exit from the DB
 681func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
 682	var exits []*common.ExitInfo
 683	err := meddler.QueryAll(
 684		hdb.dbRead, &exits,
 685		`SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
 686		exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
 687		exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
 688	)
 689	return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
 690}
 691
 692// GetAllL1UserTxs returns all L1UserTxs from the DB
 693func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
 694	var txs []*common.L1Tx
 695	err := meddler.QueryAll(
 696		hdb.dbRead, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
 697		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 698		tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
 699		tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
 700		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,
 701		tx.eth_block_num, tx.type, tx.batch_num
 702		FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
 703	)
 704	return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
 705}
 706
 707// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
 708func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
 709	var txs []*common.L1Tx
 710	// Since the query specifies that only coordinator txs are returned, it's safe to assume
 711	// that returned txs will always have effective amounts
 712	err := meddler.QueryAll(
 713		hdb.dbRead, &txs,
 714		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 715		tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
 716		tx.amount, tx.amount AS effective_amount,
 717		tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
 718		tx.eth_block_num, tx.type, tx.batch_num
 719		FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
 720	)
 721	return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
 722}
 723
 724// GetAllL2Txs returns all L2Txs from the DB
 725func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
 726	var txs []*common.L2Tx
 727	err := meddler.QueryAll(
 728		hdb.dbRead, &txs,
 729		`SELECT tx.id, tx.batch_num, tx.position,
 730		tx.from_idx, tx.to_idx, tx.amount, tx.token_id,
 731		tx.fee, tx.nonce, tx.type, tx.eth_block_num
 732		FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
 733	)
 734	return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
 735}
 736
 737// GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
 738func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
 739	var txs []*common.L1Tx
 740	err := meddler.QueryAll(
 741		hdb.dbRead, &txs, // only L1 user txs can have batch_num set to null
 742		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 743		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
 744		tx.amount, NULL AS effective_amount,
 745		tx.deposit_amount, NULL AS effective_deposit_amount,
 746		tx.eth_block_num, tx.type, tx.batch_num
 747		FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
 748		ORDER BY position;`,
 749		toForgeL1TxsNum,
 750	)
 751	return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
 752}
 753
 754// GetUnforgedL1UserTxsCount returns the count of unforged L1Txs (either in
 755// open or frozen queues that are not yet forged)
 756func (hdb *HistoryDB) GetUnforgedL1UserTxsCount() (int, error) {
 757	row := hdb.dbRead.QueryRow(
 758		`SELECT COUNT(*) FROM tx WHERE batch_num IS NULL;`,
 759	)
 760	var count int
 761	return count, tracerr.Wrap(row.Scan(&count))
 762}
 763
 764// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
 765
 766// GetLastTxsPosition for a given to_forge_l1_txs_num
 767func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
 768	row := hdb.dbRead.QueryRow(
 769		"SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
 770		toForgeL1TxsNum,
 771	)
 772	var lastL1TxsPosition int
 773	return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
 774}
 775
 776// GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
 777func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
 778	*common.WDelayerVariables, error) {
 779	var rollup common.RollupVariables
 780	var auction common.AuctionVariables
 781	var wDelayer common.WDelayerVariables
 782	if err := meddler.QueryRow(hdb.dbRead, &rollup,
 783		"SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 784		return nil, nil, nil, tracerr.Wrap(err)
 785	}
 786	if err := meddler.QueryRow(hdb.dbRead, &auction,
 787		"SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 788		return nil, nil, nil, tracerr.Wrap(err)
 789	}
 790	if err := meddler.QueryRow(hdb.dbRead, &wDelayer,
 791		"SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 792		return nil, nil, nil, tracerr.Wrap(err)
 793	}
 794	return &rollup, &auction, &wDelayer, nil
 795}
 796
 797func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
 798	return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
 799}
 800
 801func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
 802	return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
 803}
 804
 805func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
 806	return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
 807}
 808
 809func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
 810	if len(bucketUpdates) == 0 {
 811		return nil
 812	}
 813	return tracerr.Wrap(db.BulkInsert(
 814		d,
 815		`INSERT INTO bucket_update (
 816		 	eth_block_num,
 817		 	num_bucket,
 818		 	block_stamp,
 819		 	withdrawals
 820		) VALUES %s;`,
 821		bucketUpdates,
 822	))
 823}
 824
 825// AddBucketUpdatesTest allows call to unexported method
 826// only for internal testing purposes
 827func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
 828	return hdb.addBucketUpdates(d, bucketUpdates)
 829}
 830
 831// GetAllBucketUpdates retrieves all the bucket updates
 832func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
 833	var bucketUpdates []*common.BucketUpdate
 834	err := meddler.QueryAll(
 835		hdb.dbRead, &bucketUpdates,
 836		`SELECT eth_block_num, num_bucket, block_stamp, withdrawals  
 837		FROM bucket_update ORDER BY item_id;`,
 838	)
 839	return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
 840}
 841
 842func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
 843	if len(tokenExchanges) == 0 {
 844		return nil
 845	}
 846	return tracerr.Wrap(db.BulkInsert(
 847		d,
 848		`INSERT INTO token_exchange (
 849			eth_block_num,
 850    			eth_addr,
 851    			value_usd
 852		) VALUES %s;`,
 853		tokenExchanges,
 854	))
 855}
 856
 857// GetAllTokenExchanges retrieves all the token exchanges
 858func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
 859	var tokenExchanges []*common.TokenExchange
 860	err := meddler.QueryAll(
 861		hdb.dbRead, &tokenExchanges,
 862		"SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
 863	)
 864	return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
 865}
 866
 867func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
 868	escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
 869	if len(escapeHatchWithdrawals) == 0 {
 870		return nil
 871	}
 872	return tracerr.Wrap(db.BulkInsert(
 873		d,
 874		`INSERT INTO escape_hatch_withdrawal (
 875			eth_block_num,
 876			who_addr,
 877			to_addr,
 878			token_addr,
 879			amount
 880		) VALUES %s;`,
 881		escapeHatchWithdrawals,
 882	))
 883}
 884
 885// GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
 886func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
 887	var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
 888	err := meddler.QueryAll(
 889		hdb.dbRead, &escapeHatchWithdrawals,
 890		"SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
 891	)
 892	return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
 893		tracerr.Wrap(err)
 894}
 895
 896// SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
 897// contract variables.  This initial state is stored linked to block 0, which
 898// always exist in the DB and is used to store initialization data that always
 899// exist in the smart contracts.
 900func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
 901	auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
 902	txn, err := hdb.dbWrite.Beginx()
 903	if err != nil {
 904		return tracerr.Wrap(err)
 905	}
 906	defer func() {
 907		if err != nil {
 908			db.Rollback(txn)
 909		}
 910	}()
 911	// Force EthBlockNum to be 0 because it's the block used to link data
 912	// that belongs to the creation of the smart contracts
 913	rollup.EthBlockNum = 0
 914	auction.EthBlockNum = 0
 915	wDelayer.EthBlockNum = 0
 916	auction.DefaultSlotSetBidSlotNum = 0
 917	if err := hdb.setRollupVars(txn, rollup); err != nil {
 918		return tracerr.Wrap(err)
 919	}
 920	if err := hdb.setAuctionVars(txn, auction); err != nil {
 921		return tracerr.Wrap(err)
 922	}
 923	if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
 924		return tracerr.Wrap(err)
 925	}
 926
 927	return tracerr.Wrap(txn.Commit())
 928}
 929
 930// setExtraInfoForgedL1UserTxs sets the EffectiveAmount, EffectiveDepositAmount
 931// and EffectiveFromIdx of the given l1UserTxs (with an UPDATE)
 932func (hdb *HistoryDB) setExtraInfoForgedL1UserTxs(d sqlx.Ext, txs []common.L1Tx) error {
 933	if len(txs) == 0 {
 934		return nil
 935	}
 936	// Effective amounts are stored as success flags in the DB, with true value by default
 937	// to reduce the amount of updates. Therefore, only amounts that became uneffective should be
 938	// updated to become false.  At the same time, all the txs that contain
 939	// accounts (FromIdx == 0) are updated to set the EffectiveFromIdx.
 940	type txUpdate struct {
 941		ID                   common.TxID `db:"id"`
 942		AmountSuccess        bool        `db:"amount_success"`
 943		DepositAmountSuccess bool        `db:"deposit_amount_success"`
 944		EffectiveFromIdx     common.Idx  `db:"effective_from_idx"`
 945	}
 946	txUpdates := []txUpdate{}
 947	equal := func(a *big.Int, b *big.Int) bool {
 948		return a.Cmp(b) == 0
 949	}
 950	for i := range txs {
 951		amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
 952		depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
 953		if !amountSuccess || !depositAmountSuccess || txs[i].FromIdx == 0 {
 954			txUpdates = append(txUpdates, txUpdate{
 955				ID:                   txs[i].TxID,
 956				AmountSuccess:        amountSuccess,
 957				DepositAmountSuccess: depositAmountSuccess,
 958				EffectiveFromIdx:     txs[i].EffectiveFromIdx,
 959			})
 960		}
 961	}
 962	const query string = `
 963		UPDATE tx SET
 964			amount_success = tx_update.amount_success,
 965			deposit_amount_success = tx_update.deposit_amount_success,
 966			effective_from_idx = tx_update.effective_from_idx
 967		FROM (VALUES
 968			(NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL, NULL::::BIGINT),
 969			(:id, :amount_success, :deposit_amount_success, :effective_from_idx)
 970		) as tx_update (id, amount_success, deposit_amount_success, effective_from_idx)
 971		WHERE tx.id = tx_update.id;
 972	`
 973	if len(txUpdates) > 0 {
 974		if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
 975			return tracerr.Wrap(err)
 976		}
 977	}
 978	return nil
 979}
 980
 981// AddBlockSCData stores all the information of a block retrieved by the
 982// Synchronizer.  Blocks should be inserted in order, leaving no gaps because
 983// the pagination system of the API/DB depends on this.  Within blocks, all
 984// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
 985func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
 986	txn, err := hdb.dbWrite.Beginx()
 987	if err != nil {
 988		return tracerr.Wrap(err)
 989	}
 990	defer func() {
 991		if err != nil {
 992			db.Rollback(txn)
 993		}
 994	}()
 995
 996	// Add block
 997	if err := hdb.addBlock(txn, &blockData.Block); err != nil {
 998		return tracerr.Wrap(err)
 999	}
1000
1001	// Add Coordinators
1002	if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
1003		return tracerr.Wrap(err)
1004	}
1005
1006	// Add Bids
1007	if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
1008		return tracerr.Wrap(err)
1009	}
1010
1011	// Add Tokens
1012	if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
1013		return tracerr.Wrap(err)
1014	}
1015
1016	// Prepare user L1 txs to be added.
1017	// They must be added before the batch that will forge them (which can be in the same block)
1018	// and after the account that will be sent to (also can be in the same block).
1019	// Note: insert order is not relevant since item_id will be updated by a DB trigger when
1020	// the batch that forges those txs is inserted
1021	userL1s := make(map[common.BatchNum][]common.L1Tx)
1022	for i := range blockData.Rollup.L1UserTxs {
1023		batchThatForgesIsInTheBlock := false
1024		for _, batch := range blockData.Rollup.Batches {
1025			if batch.Batch.ForgeL1TxsNum != nil &&
1026				*batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
1027				// Tx is forged in this block. It's guaranteed that:
1028				// * the first batch of the block won't forge user L1 txs that have been added in this block
1029				// * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
1030				batchThatForgesIsInTheBlock = true
1031				addAtBatchNum := batch.Batch.BatchNum - 1
1032				userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
1033				break
1034			}
1035		}
1036		if !batchThatForgesIsInTheBlock {
1037			// User artificial batchNum 0 to add txs that are not forge in this block
1038			// after all the accounts of the block have been added
1039			userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
1040		}
1041	}
1042
1043	// Add Batches
1044	for i := range blockData.Rollup.Batches {
1045		batch := &blockData.Rollup.Batches[i]
1046
1047		// Add Batch: this will trigger an update on the DB
1048		// that will set the batch num of forged L1 txs in this batch
1049		if err = hdb.addBatch(txn, &batch.Batch); err != nil {
1050			return tracerr.Wrap(err)
1051		}
1052
1053		// Add accounts
1054		if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
1055			return tracerr.Wrap(err)
1056		}
1057
1058		// Add accountBalances if it exists
1059		if err := hdb.addAccountUpdates(txn, batch.UpdatedAccounts); err != nil {
1060			return tracerr.Wrap(err)
1061		}
1062
1063		// Set the EffectiveAmount and EffectiveDepositAmount of all the
1064		// L1UserTxs that have been forged in this batch
1065		if err = hdb.setExtraInfoForgedL1UserTxs(txn, batch.L1UserTxs); err != nil {
1066			return tracerr.Wrap(err)
1067		}
1068
1069		// Add forged l1 coordinator Txs
1070		if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
1071			return tracerr.Wrap(err)
1072		}
1073
1074		// Add l2 Txs
1075		if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
1076			return tracerr.Wrap(err)
1077		}
1078
1079		// Add user L1 txs that will be forged in next batch
1080		if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
1081			if err := hdb.addL1Txs(txn, userlL1s); err != nil {
1082				return tracerr.Wrap(err)
1083			}
1084		}
1085
1086		// Add exit tree
1087		if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
1088			return tracerr.Wrap(err)
1089		}
1090	}
1091	// Add user L1 txs that won't be forged in this block
1092	if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
1093		if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
1094			return tracerr.Wrap(err)
1095		}
1096	}
1097
1098	// Set SC Vars if there was an update
1099	if blockData.Rollup.Vars != nil {
1100		if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
1101			return tracerr.Wrap(err)
1102		}
1103	}
1104	if blockData.Auction.Vars != nil {
1105		if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
1106			return tracerr.Wrap(err)
1107		}
1108	}
1109	if blockData.WDelayer.Vars != nil {
1110		if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
1111			return tracerr.Wrap(err)
1112		}
1113	}
1114
1115	// Update withdrawals in exit tree table
1116	if err := hdb.updateExitTree(txn, blockData.Block.Num,
1117		blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
1118		return tracerr.Wrap(err)
1119	}
1120
1121	// Add Escape Hatch Withdrawals
1122	if err := hdb.addEscapeHatchWithdrawals(txn,
1123		blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
1124		return tracerr.Wrap(err)
1125	}
1126
1127	// Add Buckets withdrawals updates
1128	if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
1129		return tracerr.Wrap(err)
1130	}
1131
1132	// Add Token exchange updates
1133	if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
1134		return tracerr.Wrap(err)
1135	}
1136
1137	return tracerr.Wrap(txn.Commit())
1138}
1139
1140// GetCoordinatorAPI returns a coordinator by its bidderAddr
1141func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
1142	coordinator := &CoordinatorAPI{}
1143	err := meddler.QueryRow(
1144		hdb.dbRead, coordinator,
1145		"SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
1146		bidderAddr,
1147	)
1148	return coordinator, tracerr.Wrap(err)
1149}
1150
1151// AddAuctionVars insert auction vars into the DB
1152func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
1153	return tracerr.Wrap(meddler.Insert(hdb.dbWrite, "auction_vars", auctionVars))
1154}
1155
1156// GetTokensTest used to get tokens in a testing context
1157func (hdb *HistoryDB) GetTokensTest() ([]TokenWithUSD, error) {
1158	tokens := []*TokenWithUSD{}
1159	if err := meddler.QueryAll(
1160		hdb.dbRead, &tokens,
1161		"SELECT * FROM token ORDER BY token_id ASC",
1162	); err != nil {
1163		return nil, tracerr.Wrap(err)
1164	}
1165	if len(tokens) == 0 {
1166		return []TokenWithUSD{}, nil
1167	}
1168	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), nil
1169}