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