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,
 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 0 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 0 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// GetUnforgedL1UserFutureTxs gets L1 User Txs to be forged after the L1Batch
 755// with toForgeL1TxsNum (in one of the future batches, not in the next one).
 756func (hdb *HistoryDB) GetUnforgedL1UserFutureTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
 757	var txs []*common.L1Tx
 758	err := meddler.QueryAll(
 759		hdb.dbRead, &txs, // only L1 user txs can have batch_num set to null
 760		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 761		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
 762		tx.amount, NULL AS effective_amount,
 763		tx.deposit_amount, NULL AS effective_deposit_amount,
 764		tx.eth_block_num, tx.type, tx.batch_num
 765		FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num > $1
 766		ORDER BY position;`,
 767		toForgeL1TxsNum,
 768	)
 769	return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
 770}
 771
 772// GetUnforgedL1UserTxsCount returns the count of unforged L1Txs (either in
 773// open or frozen queues that are not yet forged)
 774func (hdb *HistoryDB) GetUnforgedL1UserTxsCount() (int, error) {
 775	row := hdb.dbRead.QueryRow(
 776		`SELECT COUNT(*) FROM tx WHERE batch_num IS NULL;`,
 777	)
 778	var count int
 779	return count, tracerr.Wrap(row.Scan(&count))
 780}
 781
 782// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
 783
 784// GetLastTxsPosition for a given to_forge_l1_txs_num
 785func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
 786	row := hdb.dbRead.QueryRow(
 787		"SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
 788		toForgeL1TxsNum,
 789	)
 790	var lastL1TxsPosition int
 791	return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
 792}
 793
 794// GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
 795func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
 796	*common.WDelayerVariables, error) {
 797	var rollup common.RollupVariables
 798	var auction common.AuctionVariables
 799	var wDelayer common.WDelayerVariables
 800	if err := meddler.QueryRow(hdb.dbRead, &rollup,
 801		"SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 802		return nil, nil, nil, tracerr.Wrap(err)
 803	}
 804	if err := meddler.QueryRow(hdb.dbRead, &auction,
 805		"SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 806		return nil, nil, nil, tracerr.Wrap(err)
 807	}
 808	if err := meddler.QueryRow(hdb.dbRead, &wDelayer,
 809		"SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
 810		return nil, nil, nil, tracerr.Wrap(err)
 811	}
 812	return &rollup, &auction, &wDelayer, nil
 813}
 814
 815func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
 816	return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
 817}
 818
 819func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
 820	return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
 821}
 822
 823func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
 824	return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
 825}
 826
 827func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
 828	if len(bucketUpdates) == 0 {
 829		return nil
 830	}
 831	return tracerr.Wrap(db.BulkInsert(
 832		d,
 833		`INSERT INTO bucket_update (
 834		 	eth_block_num,
 835		 	num_bucket,
 836		 	block_stamp,
 837		 	withdrawals
 838		) VALUES %s;`,
 839		bucketUpdates,
 840	))
 841}
 842
 843// AddBucketUpdatesTest allows call to unexported method
 844// only for internal testing purposes
 845func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
 846	return hdb.addBucketUpdates(d, bucketUpdates)
 847}
 848
 849// GetAllBucketUpdates retrieves all the bucket updates
 850func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
 851	var bucketUpdates []*common.BucketUpdate
 852	err := meddler.QueryAll(
 853		hdb.dbRead, &bucketUpdates,
 854		`SELECT eth_block_num, num_bucket, block_stamp, withdrawals  
 855		FROM bucket_update ORDER BY item_id;`,
 856	)
 857	return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
 858}
 859
 860func (hdb *HistoryDB) getMinBidInfo(d meddler.DB,
 861	currentSlot, lastClosedSlot int64) ([]MinBidInfo, error) {
 862	minBidInfo := []*MinBidInfo{}
 863	query := `
 864		SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
 865		WHERE default_slot_set_bid_slot_num < $1
 866		ORDER BY default_slot_set_bid_slot_num DESC
 867		LIMIT $2;`
 868	err := meddler.QueryAll(d, &minBidInfo, query, lastClosedSlot, int(lastClosedSlot-currentSlot)+1)
 869	return db.SlicePtrsToSlice(minBidInfo).([]MinBidInfo), tracerr.Wrap(err)
 870}
 871
 872func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
 873	if len(tokenExchanges) == 0 {
 874		return nil
 875	}
 876	return tracerr.Wrap(db.BulkInsert(
 877		d,
 878		`INSERT INTO token_exchange (
 879			eth_block_num,
 880    			eth_addr,
 881    			value_usd
 882		) VALUES %s;`,
 883		tokenExchanges,
 884	))
 885}
 886
 887// GetAllTokenExchanges retrieves all the token exchanges
 888func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
 889	var tokenExchanges []*common.TokenExchange
 890	err := meddler.QueryAll(
 891		hdb.dbRead, &tokenExchanges,
 892		"SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
 893	)
 894	return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
 895}
 896
 897func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
 898	escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
 899	if len(escapeHatchWithdrawals) == 0 {
 900		return nil
 901	}
 902	return tracerr.Wrap(db.BulkInsert(
 903		d,
 904		`INSERT INTO escape_hatch_withdrawal (
 905			eth_block_num,
 906			who_addr,
 907			to_addr,
 908			token_addr,
 909			amount
 910		) VALUES %s;`,
 911		escapeHatchWithdrawals,
 912	))
 913}
 914
 915// GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
 916func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
 917	var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
 918	err := meddler.QueryAll(
 919		hdb.dbRead, &escapeHatchWithdrawals,
 920		"SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
 921	)
 922	return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
 923		tracerr.Wrap(err)
 924}
 925
 926// SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
 927// contract variables.  This initial state is stored linked to block 0, which
 928// always exist in the DB and is used to store initialization data that always
 929// exist in the smart contracts.
 930func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
 931	auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
 932	txn, err := hdb.dbWrite.Beginx()
 933	if err != nil {
 934		return tracerr.Wrap(err)
 935	}
 936	defer func() {
 937		if err != nil {
 938			db.Rollback(txn)
 939		}
 940	}()
 941	// Force EthBlockNum to be 0 because it's the block used to link data
 942	// that belongs to the creation of the smart contracts
 943	rollup.EthBlockNum = 0
 944	auction.EthBlockNum = 0
 945	wDelayer.EthBlockNum = 0
 946	auction.DefaultSlotSetBidSlotNum = 0
 947	if err := hdb.setRollupVars(txn, rollup); err != nil {
 948		return tracerr.Wrap(err)
 949	}
 950	if err := hdb.setAuctionVars(txn, auction); err != nil {
 951		return tracerr.Wrap(err)
 952	}
 953	if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
 954		return tracerr.Wrap(err)
 955	}
 956
 957	return tracerr.Wrap(txn.Commit())
 958}
 959
 960// setExtraInfoForgedL1UserTxs sets the EffectiveAmount, EffectiveDepositAmount
 961// and EffectiveFromIdx of the given l1UserTxs (with an UPDATE)
 962func (hdb *HistoryDB) setExtraInfoForgedL1UserTxs(d sqlx.Ext, txs []common.L1Tx) error {
 963	if len(txs) == 0 {
 964		return nil
 965	}
 966	// Effective amounts are stored as success flags in the DB, with true value by default
 967	// to reduce the amount of updates. Therefore, only amounts that became uneffective should be
 968	// updated to become false.  At the same time, all the txs that contain
 969	// accounts (FromIdx == 0) are updated to set the EffectiveFromIdx.
 970	type txUpdate struct {
 971		ID                   common.TxID `db:"id"`
 972		AmountSuccess        bool        `db:"amount_success"`
 973		DepositAmountSuccess bool        `db:"deposit_amount_success"`
 974		EffectiveFromIdx     common.Idx  `db:"effective_from_idx"`
 975	}
 976	txUpdates := []txUpdate{}
 977	equal := func(a *big.Int, b *big.Int) bool {
 978		return a.Cmp(b) == 0
 979	}
 980	for i := range txs {
 981		amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
 982		depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
 983		if !amountSuccess || !depositAmountSuccess || txs[i].FromIdx == 0 {
 984			txUpdates = append(txUpdates, txUpdate{
 985				ID:                   txs[i].TxID,
 986				AmountSuccess:        amountSuccess,
 987				DepositAmountSuccess: depositAmountSuccess,
 988				EffectiveFromIdx:     txs[i].EffectiveFromIdx,
 989			})
 990		}
 991	}
 992	const query string = `
 993		UPDATE tx SET
 994			amount_success = tx_update.amount_success,
 995			deposit_amount_success = tx_update.deposit_amount_success,
 996			effective_from_idx = tx_update.effective_from_idx
 997		FROM (VALUES
 998			(NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL, NULL::::BIGINT),
 999			(:id, :amount_success, :deposit_amount_success, :effective_from_idx)
1000		) as tx_update (id, amount_success, deposit_amount_success, effective_from_idx)
1001		WHERE tx.id = tx_update.id;
1002	`
1003	if len(txUpdates) > 0 {
1004		if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
1005			return tracerr.Wrap(err)
1006		}
1007	}
1008	return nil
1009}
1010
1011// AddBlockSCData stores all the information of a block retrieved by the
1012// Synchronizer.  Blocks should be inserted in order, leaving no gaps because
1013// the pagination system of the API/DB depends on this.  Within blocks, all
1014// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
1015func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
1016	txn, err := hdb.dbWrite.Beginx()
1017	if err != nil {
1018		return tracerr.Wrap(err)
1019	}
1020	defer func() {
1021		if err != nil {
1022			db.Rollback(txn)
1023		}
1024	}()
1025
1026	// Add block
1027	if err := hdb.addBlock(txn, &blockData.Block); err != nil {
1028		return tracerr.Wrap(err)
1029	}
1030
1031	// Add Coordinators
1032	if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
1033		return tracerr.Wrap(err)
1034	}
1035
1036	// Add Bids
1037	if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
1038		return tracerr.Wrap(err)
1039	}
1040
1041	// Add Tokens
1042	if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
1043		return tracerr.Wrap(err)
1044	}
1045
1046	// Prepare user L1 txs to be added.
1047	// They must be added before the batch that will forge them (which can be in the same block)
1048	// and after the account that will be sent to (also can be in the same block).
1049	// Note: insert order is not relevant since item_id will be updated by a DB trigger when
1050	// the batch that forges those txs is inserted
1051	userL1s := make(map[common.BatchNum][]common.L1Tx)
1052	for i := range blockData.Rollup.L1UserTxs {
1053		batchThatForgesIsInTheBlock := false
1054		for _, batch := range blockData.Rollup.Batches {
1055			if batch.Batch.ForgeL1TxsNum != nil &&
1056				*batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
1057				// Tx is forged in this block. It's guaranteed that:
1058				// * the first batch of the block won't forge user L1 txs that have been added in this block
1059				// * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
1060				batchThatForgesIsInTheBlock = true
1061				addAtBatchNum := batch.Batch.BatchNum - 1
1062				userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
1063				break
1064			}
1065		}
1066		if !batchThatForgesIsInTheBlock {
1067			// User artificial batchNum 0 to add txs that are not forge in this block
1068			// after all the accounts of the block have been added
1069			userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
1070		}
1071	}
1072
1073	// Add Batches
1074	for i := range blockData.Rollup.Batches {
1075		batch := &blockData.Rollup.Batches[i]
1076
1077		// Add Batch: this will trigger an update on the DB
1078		// that will set the batch num of forged L1 txs in this batch
1079		if err = hdb.addBatch(txn, &batch.Batch); err != nil {
1080			return tracerr.Wrap(err)
1081		}
1082
1083		// Add accounts
1084		if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
1085			return tracerr.Wrap(err)
1086		}
1087
1088		// Add accountBalances if it exists
1089		if err := hdb.addAccountUpdates(txn, batch.UpdatedAccounts); err != nil {
1090			return tracerr.Wrap(err)
1091		}
1092
1093		// Set the EffectiveAmount and EffectiveDepositAmount of all the
1094		// L1UserTxs that have been forged in this batch
1095		if err = hdb.setExtraInfoForgedL1UserTxs(txn, batch.L1UserTxs); err != nil {
1096			return tracerr.Wrap(err)
1097		}
1098
1099		// Add forged l1 coordinator Txs
1100		if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
1101			return tracerr.Wrap(err)
1102		}
1103
1104		// Add l2 Txs
1105		if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
1106			return tracerr.Wrap(err)
1107		}
1108
1109		// Add user L1 txs that will be forged in next batch
1110		if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
1111			if err := hdb.addL1Txs(txn, userlL1s); err != nil {
1112				return tracerr.Wrap(err)
1113			}
1114		}
1115
1116		// Add exit tree
1117		if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
1118			return tracerr.Wrap(err)
1119		}
1120	}
1121	// Add user L1 txs that won't be forged in this block
1122	if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
1123		if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
1124			return tracerr.Wrap(err)
1125		}
1126	}
1127
1128	// Set SC Vars if there was an update
1129	if blockData.Rollup.Vars != nil {
1130		if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
1131			return tracerr.Wrap(err)
1132		}
1133	}
1134	if blockData.Auction.Vars != nil {
1135		if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
1136			return tracerr.Wrap(err)
1137		}
1138	}
1139	if blockData.WDelayer.Vars != nil {
1140		if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
1141			return tracerr.Wrap(err)
1142		}
1143	}
1144
1145	// Update withdrawals in exit tree table
1146	if err := hdb.updateExitTree(txn, blockData.Block.Num,
1147		blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
1148		return tracerr.Wrap(err)
1149	}
1150
1151	// Add Escape Hatch Withdrawals
1152	if err := hdb.addEscapeHatchWithdrawals(txn,
1153		blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
1154		return tracerr.Wrap(err)
1155	}
1156
1157	// Add Buckets withdrawals updates
1158	if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
1159		return tracerr.Wrap(err)
1160	}
1161
1162	// Add Token exchange updates
1163	if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
1164		return tracerr.Wrap(err)
1165	}
1166
1167	return tracerr.Wrap(txn.Commit())
1168}
1169
1170// AddAuctionVars insert auction vars into the DB
1171func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
1172	return tracerr.Wrap(meddler.Insert(hdb.dbWrite, "auction_vars", auctionVars))
1173}
1174
1175// GetTokensTest used to get tokens in a testing context
1176func (hdb *HistoryDB) GetTokensTest() ([]TokenWithUSD, error) {
1177	tokens := []*TokenWithUSD{}
1178	if err := meddler.QueryAll(
1179		hdb.dbRead, &tokens,
1180		"SELECT * FROM token ORDER BY token_id ASC",
1181	); err != nil {
1182		return nil, tracerr.Wrap(err)
1183	}
1184	if len(tokens) == 0 {
1185		return []TokenWithUSD{}, nil
1186	}
1187	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), nil
1188}
1189
1190const (
1191	// CreateAccountExtraFeePercentage is the multiplication factor over
1192	// the average fee for CreateAccount that is applied to obtain the
1193	// recommended fee for CreateAccount
1194	CreateAccountExtraFeePercentage float64 = 2.5
1195	// CreateAccountInternalExtraFeePercentage is the multiplication factor
1196	// over the average fee for CreateAccountInternal that is applied to
1197	// obtain the recommended fee for CreateAccountInternal
1198	CreateAccountInternalExtraFeePercentage float64 = 2.0
1199)
1200
1201// GetRecommendedFee returns the RecommendedFee information
1202func (hdb *HistoryDB) GetRecommendedFee(minFeeUSD, maxFeeUSD float64) (*common.RecommendedFee, error) {
1203	var recommendedFee common.RecommendedFee
1204	// Get total txs and the batch of the first selected tx of the last hour
1205	type totalTxsSinceBatchNum struct {
1206		TotalTxs      int             `meddler:"total_txs"`
1207		FirstBatchNum common.BatchNum `meddler:"batch_num"`
1208	}
1209	ttsbn := &totalTxsSinceBatchNum{}
1210	if err := meddler.QueryRow(
1211		hdb.dbRead, ttsbn, `SELECT COUNT(tx.*) as total_txs, 
1212			COALESCE (MIN(tx.batch_num), 0) as batch_num 
1213			FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
1214			WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`,
1215	); err != nil {
1216		return nil, tracerr.Wrap(err)
1217	}
1218	// Get the amount of batches and acumulated fees for the last hour
1219	type totalBatchesAndFee struct {
1220		TotalBatches int     `meddler:"total_batches"`
1221		TotalFees    float64 `meddler:"total_fees"`
1222	}
1223	tbf := &totalBatchesAndFee{}
1224	if err := meddler.QueryRow(
1225		hdb.dbRead, tbf, `SELECT COUNT(*) AS total_batches, 
1226			COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch 
1227			WHERE batch_num > $1;`, ttsbn.FirstBatchNum,
1228	); err != nil {
1229		return nil, tracerr.Wrap(err)
1230	}
1231	// Update NodeInfo struct
1232	var avgTransactionFee float64
1233	if ttsbn.TotalTxs > 0 {
1234		avgTransactionFee = tbf.TotalFees / float64(ttsbn.TotalTxs)
1235	} else {
1236		avgTransactionFee = 0
1237	}
1238	recommendedFee.ExistingAccount = math.Min(maxFeeUSD,
1239		math.Max(avgTransactionFee, minFeeUSD))
1240	recommendedFee.CreatesAccount = math.Min(maxFeeUSD,
1241		math.Max(CreateAccountExtraFeePercentage*avgTransactionFee, minFeeUSD))
1242	recommendedFee.CreatesAccountInternal = math.Min(maxFeeUSD,
1243		math.Max(CreateAccountInternalExtraFeePercentage*avgTransactionFee, minFeeUSD))
1244	return &recommendedFee, nil
1245}