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