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