arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
   1package historydb
   2
   3import (
   4	"database/sql"
   5	"errors"
   6	"fmt"
   7	"math"
   8	"math/big"
   9
  10	ethCommon "github.com/ethereum/go-ethereum/common"
  11	"github.com/hermeznetwork/hermez-node/common"
  12	"github.com/hermeznetwork/hermez-node/db"
  13	"github.com/hermeznetwork/hermez-node/log"
  14	"github.com/iden3/go-iden3-crypto/babyjub"
  15	"github.com/jmoiron/sqlx"
  16
  17	//nolint:errcheck // driver for postgres DB
  18	_ "github.com/lib/pq"
  19	"github.com/russross/meddler"
  20)
  21
  22const (
  23	// OrderAsc indicates ascending order when using pagination
  24	OrderAsc = "ASC"
  25	// OrderDesc indicates descending order when using pagination
  26	OrderDesc = "DESC"
  27)
  28
  29// TODO(Edu): Document here how HistoryDB is kept consistent
  30
  31// HistoryDB persist the historic of the rollup
  32type HistoryDB struct {
  33	db *sqlx.DB
  34}
  35
  36// NewHistoryDB initialize the DB
  37func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  38	return &HistoryDB{db: db}
  39}
  40
  41// AddBlock insert a block into the DB
  42func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  43func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  44	return meddler.Insert(d, "block", block)
  45}
  46
  47// AddBlocks inserts blocks into the DB
  48func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  49	return hdb.addBlocks(hdb.db, blocks)
  50}
  51
  52func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  53	return db.BulkInsert(
  54		d,
  55		`INSERT INTO block (
  56			eth_block_num,
  57			timestamp,
  58			hash
  59		) VALUES %s;`,
  60		blocks[:],
  61	)
  62}
  63
  64// GetBlock retrieve a block from the DB, given a block number
  65func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  66	block := &common.Block{}
  67	err := meddler.QueryRow(
  68		hdb.db, block,
  69		"SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  70	)
  71	return block, err
  72}
  73
  74// GetAllBlocks retrieve all blocks from the DB
  75func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  76	var blocks []*common.Block
  77	err := meddler.QueryAll(
  78		hdb.db, &blocks,
  79		"SELECT * FROM block;",
  80	)
  81	return db.SlicePtrsToSlice(blocks).([]common.Block), err
  82}
  83
  84// GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  85func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  86	var blocks []*common.Block
  87	err := meddler.QueryAll(
  88		hdb.db, &blocks,
  89		"SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  90		from, to,
  91	)
  92	return db.SlicePtrsToSlice(blocks).([]common.Block), err
  93}
  94
  95// GetLastBlock retrieve the block with the highest block number from the DB
  96func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  97	block := &common.Block{}
  98	err := meddler.QueryRow(
  99		hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
 100	)
 101	return block, err
 102}
 103
 104// AddBatch insert a Batch into the DB
 105func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
 106func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
 107	// Calculate total collected fees in USD
 108	// Get IDs of collected tokens for fees
 109	tokenIDs := []common.TokenID{}
 110	for id := range batch.CollectedFees {
 111		tokenIDs = append(tokenIDs, id)
 112	}
 113	// Get USD value of the tokens
 114	type tokenPrice struct {
 115		ID       common.TokenID `meddler:"token_id"`
 116		USD      *float64       `meddler:"usd"`
 117		Decimals int            `meddler:"decimals"`
 118	}
 119	var tokenPrices []*tokenPrice
 120	if len(tokenIDs) > 0 {
 121		query, args, err := sqlx.In(
 122			"SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
 123			tokenIDs,
 124		)
 125		if err != nil {
 126			return err
 127		}
 128		query = hdb.db.Rebind(query)
 129		if err := meddler.QueryAll(
 130			hdb.db, &tokenPrices, query, args...,
 131		); err != nil {
 132			return err
 133		}
 134	}
 135	// Calculate total collected
 136	var total float64
 137	for _, tokenPrice := range tokenPrices {
 138		if tokenPrice.USD == nil {
 139			continue
 140		}
 141		f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
 142		amount, _ := f.Float64()
 143		total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
 144	}
 145	batch.TotalFeesUSD = &total
 146	// Insert to DB
 147	return meddler.Insert(d, "batch", batch)
 148}
 149
 150// AddBatches insert Bids into the DB
 151func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
 152	return hdb.addBatches(hdb.db, batches)
 153}
 154func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
 155	for i := 0; i < len(batches); i++ {
 156		if err := hdb.addBatch(d, &batches[i]); err != nil {
 157			return err
 158		}
 159	}
 160	return nil
 161}
 162
 163// GetBatchAPI return the batch with the given batchNum
 164func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
 165	batch := &BatchAPI{}
 166	return batch, meddler.QueryRow(
 167		hdb.db, batch,
 168		`SELECT batch.*, block.timestamp, block.hash
 169	 	FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
 170	 	WHERE batch_num = $1;`, batchNum,
 171	)
 172}
 173
 174// GetBatchesAPI return the batches applying the given filters
 175func (hdb *HistoryDB) GetBatchesAPI(
 176	minBatchNum, maxBatchNum, slotNum *uint,
 177	forgerAddr *ethCommon.Address,
 178	fromItem, limit *uint, order string,
 179) ([]BatchAPI, *db.Pagination, error) {
 180	var query string
 181	var args []interface{}
 182	queryStr := `SELECT batch.*, block.timestamp, block.hash,
 183	count(*) OVER() AS total_items, MIN(batch.item_id) OVER() AS first_item,
 184	MAX(batch.item_id) OVER() AS last_item 
 185	FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
 186	// Apply filters
 187	nextIsAnd := false
 188	// minBatchNum filter
 189	if minBatchNum != nil {
 190		if nextIsAnd {
 191			queryStr += "AND "
 192		} else {
 193			queryStr += "WHERE "
 194		}
 195		queryStr += "batch.batch_num > ? "
 196		args = append(args, minBatchNum)
 197		nextIsAnd = true
 198	}
 199	// maxBatchNum filter
 200	if maxBatchNum != nil {
 201		if nextIsAnd {
 202			queryStr += "AND "
 203		} else {
 204			queryStr += "WHERE "
 205		}
 206		queryStr += "batch.batch_num < ? "
 207		args = append(args, maxBatchNum)
 208		nextIsAnd = true
 209	}
 210	// slotNum filter
 211	if slotNum != nil {
 212		if nextIsAnd {
 213			queryStr += "AND "
 214		} else {
 215			queryStr += "WHERE "
 216		}
 217		queryStr += "batch.slot_num = ? "
 218		args = append(args, slotNum)
 219		nextIsAnd = true
 220	}
 221	// forgerAddr filter
 222	if forgerAddr != nil {
 223		if nextIsAnd {
 224			queryStr += "AND "
 225		} else {
 226			queryStr += "WHERE "
 227		}
 228		queryStr += "batch.forger_addr = ? "
 229		args = append(args, forgerAddr)
 230		nextIsAnd = true
 231	}
 232	// pagination
 233	if fromItem != nil {
 234		if nextIsAnd {
 235			queryStr += "AND "
 236		} else {
 237			queryStr += "WHERE "
 238		}
 239		if order == OrderAsc {
 240			queryStr += "batch.item_id >= ? "
 241		} else {
 242			queryStr += "batch.item_id <= ? "
 243		}
 244		args = append(args, fromItem)
 245	}
 246	queryStr += "ORDER BY batch.item_id "
 247	if order == OrderAsc {
 248		queryStr += " ASC "
 249	} else {
 250		queryStr += " DESC "
 251	}
 252	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 253	query = hdb.db.Rebind(queryStr)
 254	log.Debug(query)
 255	batchPtrs := []*BatchAPI{}
 256	if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
 257		return nil, nil, err
 258	}
 259	batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
 260	if len(batches) == 0 {
 261		return nil, nil, sql.ErrNoRows
 262	}
 263	return batches, &db.Pagination{
 264		TotalItems: batches[0].TotalItems,
 265		FirstItem:  batches[0].FirstItem,
 266		LastItem:   batches[0].LastItem,
 267	}, nil
 268}
 269
 270// GetAllBatches retrieve all batches from the DB
 271func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
 272	var batches []*common.Batch
 273	err := meddler.QueryAll(
 274		hdb.db, &batches,
 275		`SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
 276		 batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
 277		 batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`,
 278	)
 279	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 280}
 281
 282// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
 283func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
 284	var batches []*common.Batch
 285	err := meddler.QueryAll(
 286		hdb.db, &batches,
 287		"SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
 288		from, to,
 289	)
 290	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 291}
 292
 293// GetLastBatchNum returns the BatchNum of the latest forged batch
 294func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
 295	row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
 296	var batchNum common.BatchNum
 297	return batchNum, row.Scan(&batchNum)
 298}
 299
 300// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
 301// batches.  If there's no batch in the DB (nil, nil) is returned.
 302func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
 303	row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
 304	lastL1TxsNum := new(int64)
 305	return lastL1TxsNum, row.Scan(&lastL1TxsNum)
 306}
 307
 308// Reorg deletes all the information that was added into the DB after the
 309// lastValidBlock.  If lastValidBlock is negative, all block information is
 310// deleted.
 311func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
 312	var err error
 313	if lastValidBlock < 0 {
 314		_, err = hdb.db.Exec("DELETE FROM block;")
 315	} else {
 316		_, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
 317	}
 318	return err
 319}
 320
 321// SyncPoD stores all the data that can be changed / added on a block in the PoD SC
 322func (hdb *HistoryDB) SyncPoD(
 323	blockNum uint64,
 324	bids []common.Bid,
 325	coordinators []common.Coordinator,
 326	vars *common.AuctionVars,
 327) error {
 328	return nil
 329}
 330
 331// AddBids insert Bids into the DB
 332func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
 333func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
 334	// TODO: check the coordinator info
 335	return db.BulkInsert(
 336		d,
 337		"INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
 338		bids[:],
 339	)
 340}
 341
 342// GetBids return the bids
 343func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
 344	var bids []*common.Bid
 345	err := meddler.QueryAll(
 346		hdb.db, &bids,
 347		"SELECT * FROM bid;",
 348	)
 349	return db.SlicePtrsToSlice(bids).([]common.Bid), err
 350}
 351
 352// AddCoordinators insert Coordinators into the DB
 353func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
 354	return hdb.addCoordinators(hdb.db, coordinators)
 355}
 356func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
 357	return db.BulkInsert(
 358		d,
 359		"INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
 360		coordinators[:],
 361	)
 362}
 363
 364// AddExitTree insert Exit tree into the DB
 365func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
 366	return hdb.addExitTree(hdb.db, exitTree)
 367}
 368func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
 369	return db.BulkInsert(
 370		d,
 371		"INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
 372			"instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
 373		exitTree[:],
 374	)
 375}
 376
 377// AddToken insert a token into the DB
 378func (hdb *HistoryDB) AddToken(token *common.Token) error {
 379	return meddler.Insert(hdb.db, "token", token)
 380}
 381
 382// AddTokens insert tokens into the DB
 383func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
 384func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
 385	return db.BulkInsert(
 386		d,
 387		`INSERT INTO token (
 388			token_id,
 389			eth_block_num,
 390			eth_addr,
 391			name,
 392			symbol,
 393			decimals
 394		) VALUES %s;`,
 395		tokens[:],
 396	)
 397}
 398
 399// UpdateTokenValue updates the USD value of a token
 400func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
 401	_, err := hdb.db.Exec(
 402		"UPDATE token SET usd = $1 WHERE symbol = $2;",
 403		value, tokenSymbol,
 404	)
 405	return err
 406}
 407
 408// GetToken returns a token from the DB given a TokenID
 409func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
 410	token := &TokenWithUSD{}
 411	err := meddler.QueryRow(
 412		hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
 413	)
 414	return token, err
 415}
 416
 417// GetAllTokens returns all tokens from the DB
 418func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
 419	var tokens []*TokenWithUSD
 420	err := meddler.QueryAll(
 421		hdb.db, &tokens,
 422		"SELECT * FROM token ORDER BY token_id;",
 423	)
 424	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
 425}
 426
 427// GetTokens returns a list of tokens from the DB
 428func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
 429	var query string
 430	var args []interface{}
 431	queryStr := `SELECT * , COUNT(*) OVER() AS total_items, MIN(token.item_id) OVER() AS first_item, MAX(token.item_id) OVER() AS last_item FROM token `
 432	// Apply filters
 433	nextIsAnd := false
 434	if len(ids) > 0 {
 435		queryStr += "WHERE token_id IN (?) "
 436		nextIsAnd = true
 437		args = append(args, ids)
 438	}
 439	if len(symbols) > 0 {
 440		if nextIsAnd {
 441			queryStr += "AND "
 442		} else {
 443			queryStr += "WHERE "
 444		}
 445		queryStr += "symbol IN (?) "
 446		args = append(args, symbols)
 447		nextIsAnd = true
 448	}
 449	if name != "" {
 450		if nextIsAnd {
 451			queryStr += "AND "
 452		} else {
 453			queryStr += "WHERE "
 454		}
 455		queryStr += "name ~ ? "
 456		args = append(args, name)
 457		nextIsAnd = true
 458	}
 459	if fromItem != nil {
 460		if nextIsAnd {
 461			queryStr += "AND "
 462		} else {
 463			queryStr += "WHERE "
 464		}
 465		if order == OrderAsc {
 466			queryStr += "item_id >= ? "
 467		} else {
 468			queryStr += "item_id <= ? "
 469		}
 470		args = append(args, fromItem)
 471	}
 472	// pagination
 473	queryStr += "ORDER BY item_id "
 474	if order == OrderAsc {
 475		queryStr += "ASC "
 476	} else {
 477		queryStr += "DESC "
 478	}
 479	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 480	query, argsQ, err := sqlx.In(queryStr, args...)
 481	if err != nil {
 482		return nil, nil, err
 483	}
 484	query = hdb.db.Rebind(query)
 485	tokens := []*TokenWithUSD{}
 486	if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
 487		return nil, nil, err
 488	}
 489	if len(tokens) == 0 {
 490		return nil, nil, sql.ErrNoRows
 491	}
 492	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
 493		TotalItems: tokens[0].TotalItems,
 494		FirstItem:  tokens[0].FirstItem,
 495		LastItem:   tokens[0].LastItem,
 496	}, nil
 497}
 498
 499// GetTokenSymbols returns all the token symbols from the DB
 500func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
 501	var tokenSymbols []string
 502	rows, err := hdb.db.Query("SELECT symbol FROM token;")
 503	if err != nil {
 504		return nil, err
 505	}
 506	sym := new(string)
 507	for rows.Next() {
 508		err = rows.Scan(sym)
 509		if err != nil {
 510			return nil, err
 511		}
 512		tokenSymbols = append(tokenSymbols, *sym)
 513	}
 514	return tokenSymbols, nil
 515}
 516
 517// AddAccounts insert accounts into the DB
 518func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
 519	return hdb.addAccounts(hdb.db, accounts)
 520}
 521func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
 522	return db.BulkInsert(
 523		d,
 524		`INSERT INTO account (
 525			idx,
 526			token_id,
 527			batch_num,
 528			bjj,
 529			eth_addr
 530		) VALUES %s;`,
 531		accounts[:],
 532	)
 533}
 534
 535// GetAccounts returns a list of accounts from the DB
 536func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
 537	var accs []*common.Account
 538	err := meddler.QueryAll(
 539		hdb.db, &accs,
 540		"SELECT * FROM account ORDER BY idx;",
 541	)
 542	return db.SlicePtrsToSlice(accs).([]common.Account), err
 543}
 544
 545// AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 546// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 547// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 548func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
 549
 550// addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 551// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 552// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 553func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
 554	txs := []txWrite{}
 555	for i := 0; i < len(l1txs); i++ {
 556		af := new(big.Float).SetInt(l1txs[i].Amount)
 557		amountFloat, _ := af.Float64()
 558		laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
 559		loadAmountFloat, _ := laf.Float64()
 560		txs = append(txs, txWrite{
 561			// Generic
 562			IsL1:        true,
 563			TxID:        l1txs[i].TxID,
 564			Type:        l1txs[i].Type,
 565			Position:    l1txs[i].Position,
 566			FromIdx:     &l1txs[i].FromIdx,
 567			ToIdx:       l1txs[i].ToIdx,
 568			Amount:      l1txs[i].Amount,
 569			AmountFloat: amountFloat,
 570			TokenID:     l1txs[i].TokenID,
 571			BatchNum:    l1txs[i].BatchNum,
 572			EthBlockNum: l1txs[i].EthBlockNum,
 573			// L1
 574			ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
 575			UserOrigin:      &l1txs[i].UserOrigin,
 576			FromEthAddr:     &l1txs[i].FromEthAddr,
 577			FromBJJ:         l1txs[i].FromBJJ,
 578			LoadAmount:      l1txs[i].LoadAmount,
 579			LoadAmountFloat: &loadAmountFloat,
 580		})
 581	}
 582	return hdb.addTxs(d, txs)
 583}
 584
 585// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 586func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
 587
 588// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 589func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
 590	txs := []txWrite{}
 591	for i := 0; i < len(l2txs); i++ {
 592		f := new(big.Float).SetInt(l2txs[i].Amount)
 593		amountFloat, _ := f.Float64()
 594		txs = append(txs, txWrite{
 595			// Generic
 596			IsL1:        false,
 597			TxID:        l2txs[i].TxID,
 598			Type:        l2txs[i].Type,
 599			Position:    l2txs[i].Position,
 600			FromIdx:     &l2txs[i].FromIdx,
 601			ToIdx:       l2txs[i].ToIdx,
 602			Amount:      l2txs[i].Amount,
 603			AmountFloat: amountFloat,
 604			BatchNum:    &l2txs[i].BatchNum,
 605			EthBlockNum: l2txs[i].EthBlockNum,
 606			// L2
 607			Fee:   &l2txs[i].Fee,
 608			Nonce: &l2txs[i].Nonce,
 609		})
 610	}
 611	return hdb.addTxs(d, txs)
 612}
 613
 614func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
 615	return db.BulkInsert(
 616		d,
 617		`INSERT INTO tx (
 618			is_l1,
 619			id,
 620			type,
 621			position,
 622			from_idx,
 623			to_idx,
 624			amount,
 625			amount_f,
 626			token_id,
 627			batch_num,
 628			eth_block_num,
 629			to_forge_l1_txs_num,
 630			user_origin,
 631			from_eth_addr,
 632			from_bjj,
 633			load_amount,
 634			load_amount_f,
 635			fee,
 636			nonce
 637		) VALUES %s;`,
 638		txs[:],
 639	)
 640}
 641
 642// // GetTxs returns a list of txs from the DB
 643// func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
 644// 	var txs []*common.Tx
 645// 	err := meddler.QueryAll(
 646// 		hdb.db, &txs,
 647// 		`SELECT * FROM tx
 648// 		ORDER BY (batch_num, position) ASC`,
 649// 	)
 650// 	return db.SlicePtrsToSlice(txs).([]common.Tx), err
 651// }
 652
 653// GetHistoryTx returns a tx from the DB given a TxID
 654func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
 655	tx := &TxAPI{}
 656	err := meddler.QueryRow(
 657		hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 658		hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
 659		hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
 660		tx.amount, tx.token_id, tx.amount_usd, 
 661		tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 662		tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 663		token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
 664		token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 665		token.usd_update, block.timestamp
 666		FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 667		INNER JOIN block ON tx.eth_block_num = block.eth_block_num 
 668		WHERE tx.id = $1;`, txID,
 669	)
 670	return tx, err
 671}
 672
 673// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
 674// and pagination info
 675func (hdb *HistoryDB) GetHistoryTxs(
 676	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 677	tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
 678	fromItem, limit *uint, order string,
 679) ([]TxAPI, *db.Pagination, error) {
 680	if ethAddr != nil && bjj != nil {
 681		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 682	}
 683	var query string
 684	var args []interface{}
 685	queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 686	hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
 687	hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
 688	tx.amount, tx.token_id, tx.amount_usd, 
 689	tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 690	tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 691	token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
 692	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 693	token.usd_update, block.timestamp, count(*) OVER() AS total_items, 
 694	MIN(tx.item_id)  OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item 
 695	FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 696	INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
 697	// Apply filters
 698	nextIsAnd := false
 699	// ethAddr filter
 700	if ethAddr != nil {
 701		queryStr = `WITH acc AS 
 702		(select idx from account where eth_addr = ?) ` + queryStr
 703		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 704		nextIsAnd = true
 705		args = append(args, ethAddr)
 706	} else if bjj != nil { // bjj filter
 707		queryStr = `WITH acc AS 
 708		(select idx from account where bjj = ?) ` + queryStr
 709		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 710		nextIsAnd = true
 711		args = append(args, bjj)
 712	}
 713	// tokenID filter
 714	if tokenID != nil {
 715		if nextIsAnd {
 716			queryStr += "AND "
 717		} else {
 718			queryStr += "WHERE "
 719		}
 720		queryStr += "tx.token_id = ? "
 721		args = append(args, tokenID)
 722		nextIsAnd = true
 723	}
 724	// idx filter
 725	if idx != nil {
 726		if nextIsAnd {
 727			queryStr += "AND "
 728		} else {
 729			queryStr += "WHERE "
 730		}
 731		queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
 732		args = append(args, idx, idx)
 733		nextIsAnd = true
 734	}
 735	// batchNum filter
 736	if batchNum != nil {
 737		if nextIsAnd {
 738			queryStr += "AND "
 739		} else {
 740			queryStr += "WHERE "
 741		}
 742		queryStr += "tx.batch_num = ? "
 743		args = append(args, batchNum)
 744		nextIsAnd = true
 745	}
 746	// txType filter
 747	if txType != nil {
 748		if nextIsAnd {
 749			queryStr += "AND "
 750		} else {
 751			queryStr += "WHERE "
 752		}
 753		queryStr += "tx.type = ? "
 754		args = append(args, txType)
 755		nextIsAnd = true
 756	}
 757	if fromItem != nil {
 758		if nextIsAnd {
 759			queryStr += "AND "
 760		} else {
 761			queryStr += "WHERE "
 762		}
 763		if order == OrderAsc {
 764			queryStr += "tx.item_id >= ? "
 765		} else {
 766			queryStr += "tx.item_id <= ? "
 767		}
 768		args = append(args, fromItem)
 769		nextIsAnd = true
 770	}
 771	if nextIsAnd {
 772		queryStr += "AND "
 773	} else {
 774		queryStr += "WHERE "
 775	}
 776	queryStr += "tx.batch_num IS NOT NULL "
 777
 778	// pagination
 779	queryStr += "ORDER BY tx.item_id "
 780	if order == OrderAsc {
 781		queryStr += " ASC "
 782	} else {
 783		queryStr += " DESC "
 784	}
 785	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 786	query = hdb.db.Rebind(queryStr)
 787	log.Debug(query)
 788	txsPtrs := []*TxAPI{}
 789	if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
 790		return nil, nil, err
 791	}
 792	txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
 793	if len(txs) == 0 {
 794		return nil, nil, sql.ErrNoRows
 795	}
 796	return txs, &db.Pagination{
 797		TotalItems: txs[0].TotalItems,
 798		FirstItem:  txs[0].FirstItem,
 799		LastItem:   txs[0].LastItem,
 800	}, nil
 801}
 802
 803// GetAllExits returns all exit from the DB
 804func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
 805	var exits []*common.ExitInfo
 806	err := meddler.QueryAll(
 807		hdb.db, &exits,
 808		`SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
 809		exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
 810		exit_tree.delayed_withdrawn FROM exit_tree;`,
 811	)
 812	return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
 813}
 814
 815// GetExit returns a exit from the DB
 816func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
 817	exit := &HistoryExit{}
 818	err := meddler.QueryRow(
 819		hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 820		token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
 821		FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 822		INNER JOIN token ON account.token_id = token.token_id 
 823		WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
 824	)
 825	return exit, err
 826}
 827
 828// GetExits returns a list of exits from the DB and pagination info
 829func (hdb *HistoryDB) GetExits(
 830	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 831	tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
 832	fromItem, limit *uint, order string,
 833) ([]HistoryExit, *db.Pagination, error) {
 834	if ethAddr != nil && bjj != nil {
 835		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 836	}
 837	var query string
 838	var args []interface{}
 839	queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 840	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 841	token.usd_update, COUNT(*) OVER() AS total_items, MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
 842	FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 843	INNER JOIN token ON account.token_id = token.token_id `
 844	// Apply filters
 845	nextIsAnd := false
 846	// ethAddr filter
 847	if ethAddr != nil {
 848		queryStr += "WHERE account.eth_addr = ? "
 849		nextIsAnd = true
 850		args = append(args, ethAddr)
 851	} else if bjj != nil { // bjj filter
 852		queryStr += "WHERE account.bjj = ? "
 853		nextIsAnd = true
 854		args = append(args, bjj)
 855	}
 856	// tokenID filter
 857	if tokenID != nil {
 858		if nextIsAnd {
 859			queryStr += "AND "
 860		} else {
 861			queryStr += "WHERE "
 862		}
 863		queryStr += "account.token_id = ? "
 864		args = append(args, tokenID)
 865		nextIsAnd = true
 866	}
 867	// idx filter
 868	if idx != nil {
 869		if nextIsAnd {
 870			queryStr += "AND "
 871		} else {
 872			queryStr += "WHERE "
 873		}
 874		queryStr += "exit_tree.account_idx = ? "
 875		args = append(args, idx)
 876		nextIsAnd = true
 877	}
 878	// batchNum filter
 879	if batchNum != nil {
 880		if nextIsAnd {
 881			queryStr += "AND "
 882		} else {
 883			queryStr += "WHERE "
 884		}
 885		queryStr += "exit_tree.batch_num = ? "
 886		args = append(args, batchNum)
 887		nextIsAnd = true
 888	}
 889	if fromItem != nil {
 890		if nextIsAnd {
 891			queryStr += "AND "
 892		} else {
 893			queryStr += "WHERE "
 894		}
 895		if order == OrderAsc {
 896			queryStr += "exit_tree.item_id >= ? "
 897		} else {
 898			queryStr += "exit_tree.item_id <= ? "
 899		}
 900		args = append(args, fromItem)
 901		// nextIsAnd = true
 902	}
 903	// pagination
 904	queryStr += "ORDER BY exit_tree.item_id "
 905	if order == OrderAsc {
 906		queryStr += " ASC "
 907	} else {
 908		queryStr += " DESC "
 909	}
 910	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 911	query = hdb.db.Rebind(queryStr)
 912	// log.Debug(query)
 913	exits := []*HistoryExit{}
 914	if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
 915		return nil, nil, err
 916	}
 917	if len(exits) == 0 {
 918		return nil, nil, sql.ErrNoRows
 919	}
 920	return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
 921		TotalItems: exits[0].TotalItems,
 922		FirstItem:  exits[0].FirstItem,
 923		LastItem:   exits[0].LastItem,
 924	}, nil
 925}
 926
 927// // GetTx returns a tx from the DB
 928// func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
 929// 	tx := new(common.Tx)
 930// 	return tx, meddler.QueryRow(
 931// 		hdb.db, tx,
 932// 		"SELECT * FROM tx WHERE id = $1;",
 933// 		txID,
 934// 	)
 935// }
 936
 937// GetAllL1UserTxs returns all L1UserTxs from the DB
 938func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
 939	var txs []*common.L1Tx
 940	err := meddler.QueryAll(
 941		hdb.db, &txs,
 942		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 943		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
 944		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
 945		FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
 946	)
 947	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
 948}
 949
 950// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
 951func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
 952	var txs []*common.L1Tx
 953	err := meddler.QueryAll(
 954		hdb.db, &txs,
 955		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 956		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
 957		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
 958		FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
 959	)
 960	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
 961}
 962
 963// GetAllL2Txs returns all L2Txs from the DB
 964func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
 965	var txs []*common.L2Tx
 966	err := meddler.QueryAll(
 967		hdb.db, &txs,
 968		`SELECT tx.id, tx.batch_num, tx.position,
 969		tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
 970		tx.type, tx.eth_block_num
 971		FROM tx WHERE is_l1 = FALSE;`,
 972	)
 973	return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
 974}
 975
 976// GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
 977func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
 978	var txs []*common.L1Tx
 979	err := meddler.QueryAll(
 980		hdb.db, &txs,
 981		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
 982		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
 983		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
 984		FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
 985		toForgeL1TxsNum,
 986	)
 987	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
 988}
 989
 990// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
 991
 992// GetLastTxsPosition for a given to_forge_l1_txs_num
 993func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
 994	row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
 995	var lastL1TxsPosition int
 996	return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
 997}
 998
 999// AddBlockSCData stores all the information of a block retrieved by the
1000// Synchronizer.  Blocks should be inserted in order, leaving no gaps because
1001// the pagination system of the API/DB depends on this.  Within blocks, all
1002// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
1003func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
1004	txn, err := hdb.db.Begin()
1005	if err != nil {
1006		return err
1007	}
1008	defer func() {
1009		if err != nil {
1010			errRollback := txn.Rollback()
1011			if errRollback != nil {
1012				log.Errorw("Rollback", "err", errRollback)
1013			}
1014		}
1015	}()
1016
1017	// Add block
1018	err = hdb.addBlock(txn, &blockData.Block)
1019	if err != nil {
1020		return err
1021	}
1022
1023	// Add Coordinators
1024	if len(blockData.Coordinators) > 0 {
1025		err = hdb.addCoordinators(txn, blockData.Coordinators)
1026		if err != nil {
1027			return err
1028		}
1029	}
1030
1031	// Add Bids
1032	if len(blockData.Bids) > 0 {
1033		err = hdb.addBids(txn, blockData.Bids)
1034		if err != nil {
1035			return err
1036		}
1037	}
1038
1039	// Add Tokens
1040	if len(blockData.AddedTokens) > 0 {
1041		err = hdb.addTokens(txn, blockData.AddedTokens)
1042		if err != nil {
1043			return err
1044		}
1045	}
1046
1047	// Add l1 Txs
1048	if len(blockData.L1UserTxs) > 0 {
1049		err = hdb.addL1Txs(txn, blockData.L1UserTxs)
1050		if err != nil {
1051			return err
1052		}
1053	}
1054
1055	// Add Batches
1056	for i := range blockData.Batches {
1057		batch := &blockData.Batches[i]
1058		// Add Batch: this will trigger an update on the DB
1059		// that will set the batch num of forged L1 txs in this batch
1060		err = hdb.addBatch(txn, &batch.Batch)
1061		if err != nil {
1062			return err
1063		}
1064
1065		// Add unforged l1 Txs
1066		if batch.L1Batch {
1067			if len(batch.L1CoordinatorTxs) > 0 {
1068				err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
1069				if err != nil {
1070					return err
1071				}
1072			}
1073		}
1074
1075		// Add l2 Txs
1076		if len(batch.L2Txs) > 0 {
1077			err = hdb.addL2Txs(txn, batch.L2Txs)
1078			if err != nil {
1079				return err
1080			}
1081		}
1082
1083		// Add accounts
1084		if len(batch.CreatedAccounts) > 0 {
1085			err = hdb.addAccounts(txn, batch.CreatedAccounts)
1086			if err != nil {
1087				return err
1088			}
1089		}
1090
1091		// Add exit tree
1092		if len(batch.ExitTree) > 0 {
1093			err = hdb.addExitTree(txn, batch.ExitTree)
1094			if err != nil {
1095				return err
1096			}
1097		}
1098
1099		// TODO: INSERT CONTRACTS VARS
1100	}
1101
1102	return txn.Commit()
1103}
1104
1105// GetCoordinatorAPI returns a coordinator by its bidderAddr
1106func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
1107	coordinator := &CoordinatorAPI{}
1108	err := meddler.QueryRow(
1109		hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
1110	)
1111	return coordinator, err
1112}
1113
1114// GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
1115func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, *db.Pagination, error) {
1116	var query string
1117	var args []interface{}
1118	queryStr := `SELECT coordinator.*, 
1119	COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
1120	FROM coordinator `
1121	// Apply filters
1122	if fromItem != nil {
1123		queryStr += "WHERE "
1124		if order == OrderAsc {
1125			queryStr += "coordinator.item_id >= ? "
1126		} else {
1127			queryStr += "coordinator.item_id <= ? "
1128		}
1129		args = append(args, fromItem)
1130	}
1131	// pagination
1132	queryStr += "ORDER BY coordinator.item_id "
1133	if order == OrderAsc {
1134		queryStr += " ASC "
1135	} else {
1136		queryStr += " DESC "
1137	}
1138	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1139	query = hdb.db.Rebind(queryStr)
1140
1141	coordinators := []*CoordinatorAPI{}
1142	if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
1143		return nil, nil, err
1144	}
1145	if len(coordinators) == 0 {
1146		return nil, nil, sql.ErrNoRows
1147	}
1148	return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI), &db.Pagination{
1149		TotalItems: coordinators[0].TotalItems,
1150		FirstItem:  coordinators[0].FirstItem,
1151		LastItem:   coordinators[0].LastItem,
1152	}, nil
1153}