You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1662 lines
50 KiB

Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package historydb
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "math/big"
  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/iden3/go-iden3-crypto/babyjub"
  12. "github.com/jmoiron/sqlx"
  13. //nolint:errcheck // driver for postgres DB
  14. _ "github.com/lib/pq"
  15. "github.com/russross/meddler"
  16. )
  17. const (
  18. // OrderAsc indicates ascending order when using pagination
  19. OrderAsc = "ASC"
  20. // OrderDesc indicates descending order when using pagination
  21. OrderDesc = "DESC"
  22. )
  23. // TODO(Edu): Document here how HistoryDB is kept consistent
  24. // HistoryDB persist the historic of the rollup
  25. type HistoryDB struct {
  26. db *sqlx.DB
  27. }
  28. // NewHistoryDB initialize the DB
  29. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  30. return &HistoryDB{db: db}
  31. }
  32. // DB returns a pointer to the L2DB.db. This method should be used only for
  33. // internal testing purposes.
  34. func (hdb *HistoryDB) DB() *sqlx.DB {
  35. return hdb.db
  36. }
  37. // AddBlock insert a block into the DB
  38. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  39. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  40. return meddler.Insert(d, "block", block)
  41. }
  42. // AddBlocks inserts blocks into the DB
  43. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  44. return hdb.addBlocks(hdb.db, blocks)
  45. }
  46. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  47. return db.BulkInsert(
  48. d,
  49. `INSERT INTO block (
  50. eth_block_num,
  51. timestamp,
  52. hash
  53. ) VALUES %s;`,
  54. blocks[:],
  55. )
  56. }
  57. // GetBlock retrieve a block from the DB, given a block number
  58. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  59. block := &common.Block{}
  60. err := meddler.QueryRow(
  61. hdb.db, block,
  62. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  63. )
  64. return block, err
  65. }
  66. // GetAllBlocks retrieve all blocks from the DB
  67. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  68. var blocks []*common.Block
  69. err := meddler.QueryAll(
  70. hdb.db, &blocks,
  71. "SELECT * FROM block;",
  72. )
  73. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  74. }
  75. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  76. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  77. var blocks []*common.Block
  78. err := meddler.QueryAll(
  79. hdb.db, &blocks,
  80. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  81. from, to,
  82. )
  83. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  84. }
  85. // GetLastBlock retrieve the block with the highest block number from the DB
  86. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  87. block := &common.Block{}
  88. err := meddler.QueryRow(
  89. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  90. )
  91. return block, err
  92. }
  93. // AddBatch insert a Batch into the DB
  94. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  95. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  96. // Calculate total collected fees in USD
  97. // Get IDs of collected tokens for fees
  98. tokenIDs := []common.TokenID{}
  99. for id := range batch.CollectedFees {
  100. tokenIDs = append(tokenIDs, id)
  101. }
  102. // Get USD value of the tokens
  103. type tokenPrice struct {
  104. ID common.TokenID `meddler:"token_id"`
  105. USD *float64 `meddler:"usd"`
  106. Decimals int `meddler:"decimals"`
  107. }
  108. var tokenPrices []*tokenPrice
  109. if len(tokenIDs) > 0 {
  110. query, args, err := sqlx.In(
  111. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
  112. tokenIDs,
  113. )
  114. if err != nil {
  115. return err
  116. }
  117. query = hdb.db.Rebind(query)
  118. if err := meddler.QueryAll(
  119. hdb.db, &tokenPrices, query, args...,
  120. ); err != nil {
  121. return err
  122. }
  123. }
  124. // Calculate total collected
  125. var total float64
  126. for _, tokenPrice := range tokenPrices {
  127. if tokenPrice.USD == nil {
  128. continue
  129. }
  130. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  131. amount, _ := f.Float64()
  132. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  133. }
  134. batch.TotalFeesUSD = &total
  135. // Insert to DB
  136. return meddler.Insert(d, "batch", batch)
  137. }
  138. // AddBatches insert Bids into the DB
  139. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  140. return hdb.addBatches(hdb.db, batches)
  141. }
  142. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  143. for i := 0; i < len(batches); i++ {
  144. if err := hdb.addBatch(d, &batches[i]); err != nil {
  145. return err
  146. }
  147. }
  148. return nil
  149. }
  150. // GetBatchAPI return the batch with the given batchNum
  151. func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
  152. batch := &BatchAPI{}
  153. return batch, meddler.QueryRow(
  154. hdb.db, batch,
  155. `SELECT batch.*, block.timestamp, block.hash
  156. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
  157. WHERE batch_num = $1;`, batchNum,
  158. )
  159. }
  160. // GetBatchesAPI return the batches applying the given filters
  161. func (hdb *HistoryDB) GetBatchesAPI(
  162. minBatchNum, maxBatchNum, slotNum *uint,
  163. forgerAddr *ethCommon.Address,
  164. fromItem, limit *uint, order string,
  165. ) ([]BatchAPI, uint64, error) {
  166. var query string
  167. var args []interface{}
  168. queryStr := `SELECT batch.*, block.timestamp, block.hash,
  169. count(*) OVER() AS total_items
  170. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
  171. // Apply filters
  172. nextIsAnd := false
  173. // minBatchNum filter
  174. if minBatchNum != nil {
  175. if nextIsAnd {
  176. queryStr += "AND "
  177. } else {
  178. queryStr += "WHERE "
  179. }
  180. queryStr += "batch.batch_num > ? "
  181. args = append(args, minBatchNum)
  182. nextIsAnd = true
  183. }
  184. // maxBatchNum filter
  185. if maxBatchNum != nil {
  186. if nextIsAnd {
  187. queryStr += "AND "
  188. } else {
  189. queryStr += "WHERE "
  190. }
  191. queryStr += "batch.batch_num < ? "
  192. args = append(args, maxBatchNum)
  193. nextIsAnd = true
  194. }
  195. // slotNum filter
  196. if slotNum != nil {
  197. if nextIsAnd {
  198. queryStr += "AND "
  199. } else {
  200. queryStr += "WHERE "
  201. }
  202. queryStr += "batch.slot_num = ? "
  203. args = append(args, slotNum)
  204. nextIsAnd = true
  205. }
  206. // forgerAddr filter
  207. if forgerAddr != nil {
  208. if nextIsAnd {
  209. queryStr += "AND "
  210. } else {
  211. queryStr += "WHERE "
  212. }
  213. queryStr += "batch.forger_addr = ? "
  214. args = append(args, forgerAddr)
  215. nextIsAnd = true
  216. }
  217. // pagination
  218. if fromItem != nil {
  219. if nextIsAnd {
  220. queryStr += "AND "
  221. } else {
  222. queryStr += "WHERE "
  223. }
  224. if order == OrderAsc {
  225. queryStr += "batch.item_id >= ? "
  226. } else {
  227. queryStr += "batch.item_id <= ? "
  228. }
  229. args = append(args, fromItem)
  230. }
  231. queryStr += "ORDER BY batch.item_id "
  232. if order == OrderAsc {
  233. queryStr += " ASC "
  234. } else {
  235. queryStr += " DESC "
  236. }
  237. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  238. query = hdb.db.Rebind(queryStr)
  239. // log.Debug(query)
  240. batchPtrs := []*BatchAPI{}
  241. if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
  242. return nil, 0, err
  243. }
  244. batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
  245. if len(batches) == 0 {
  246. return nil, 0, sql.ErrNoRows
  247. }
  248. return batches, batches[0].TotalItems - uint64(len(batches)), nil
  249. }
  250. // GetAllBatches retrieve all batches from the DB
  251. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  252. var batches []*common.Batch
  253. err := meddler.QueryAll(
  254. hdb.db, &batches,
  255. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  256. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  257. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`,
  258. )
  259. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  260. }
  261. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  262. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  263. var batches []*common.Batch
  264. err := meddler.QueryAll(
  265. hdb.db, &batches,
  266. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
  267. from, to,
  268. )
  269. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  270. }
  271. // GetBatchesLen retrieve number of batches from the DB, given a slotNum
  272. func (hdb *HistoryDB) GetBatchesLen(slotNum int64) (int, error) {
  273. row := hdb.db.QueryRow("SELECT COUNT(*) FROM batch WHERE slot_num = $1;", slotNum)
  274. var batchesLen int
  275. return batchesLen, row.Scan(&batchesLen)
  276. }
  277. // GetLastBatchNum returns the BatchNum of the latest forged batch
  278. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  279. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  280. var batchNum common.BatchNum
  281. return batchNum, row.Scan(&batchNum)
  282. }
  283. // GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
  284. func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
  285. row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
  286. WHERE forge_l1_txs_num IS NOT NULL
  287. ORDER BY batch_num DESC LIMIT 1;`)
  288. var blockNum int64
  289. return blockNum, row.Scan(&blockNum)
  290. }
  291. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  292. // batches. If there's no batch in the DB (nil, nil) is returned.
  293. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  294. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  295. lastL1TxsNum := new(int64)
  296. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  297. }
  298. // Reorg deletes all the information that was added into the DB after the
  299. // lastValidBlock. If lastValidBlock is negative, all block information is
  300. // deleted.
  301. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  302. var err error
  303. if lastValidBlock < 0 {
  304. _, err = hdb.db.Exec("DELETE FROM block;")
  305. } else {
  306. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  307. }
  308. return err
  309. }
  310. // AddBids insert Bids into the DB
  311. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  312. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  313. // TODO: check the coordinator info
  314. return db.BulkInsert(
  315. d,
  316. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  317. bids[:],
  318. )
  319. }
  320. // GetAllBids retrieve all bids from the DB
  321. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  322. var bids []*common.Bid
  323. err := meddler.QueryAll(
  324. hdb.db, &bids,
  325. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid;`,
  326. )
  327. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  328. }
  329. // GetBestBidAPI returns the best bid in specific slot by slotNum
  330. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  331. bid := &BidAPI{}
  332. err := meddler.QueryRow(
  333. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  334. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  335. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  336. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  337. )
  338. return *bid, err
  339. }
  340. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  341. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  342. bidCoord := &common.BidCoordinator{}
  343. err := meddler.QueryRow(
  344. hdb.db, bidCoord,
  345. `SELECT (
  346. SELECT default_slot_set_bid_slot_num
  347. FROM auction_vars
  348. WHERE default_slot_set_bid_slot_num <= $1
  349. ORDER BY eth_block_num DESC LIMIT 1
  350. ),
  351. bid.slot_num, bid.bid_value, bid.bidder_addr,
  352. coordinator.forger_addr, coordinator.url
  353. FROM bid
  354. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  355. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  356. slotNum)
  357. return bidCoord, err
  358. }
  359. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  360. func (hdb *HistoryDB) GetBestBidsAPI(
  361. minSlotNum, maxSlotNum *int64,
  362. bidderAddr *ethCommon.Address,
  363. limit *uint, order string,
  364. ) ([]BidAPI, uint64, error) {
  365. var query string
  366. var args []interface{}
  367. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  368. COUNT(*) OVER() AS total_items FROM (
  369. SELECT slot_num, MAX(item_id) as maxitem
  370. FROM bid GROUP BY slot_num
  371. )
  372. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  373. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  374. INNER JOIN coordinator ON b.bidder_addr = coordinator.bidder_addr
  375. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  376. args = append(args, minSlotNum)
  377. args = append(args, maxSlotNum)
  378. // Apply filters
  379. if bidderAddr != nil {
  380. queryStr += " AND b.bidder_addr = ? "
  381. args = append(args, bidderAddr)
  382. }
  383. queryStr += " ORDER BY b.slot_num "
  384. if order == OrderAsc {
  385. queryStr += "ASC "
  386. } else {
  387. queryStr += "DESC "
  388. }
  389. if limit != nil {
  390. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  391. }
  392. query = hdb.db.Rebind(queryStr)
  393. bidPtrs := []*BidAPI{}
  394. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  395. return nil, 0, err
  396. }
  397. // log.Debug(query)
  398. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  399. if len(bids) == 0 {
  400. return nil, 0, sql.ErrNoRows
  401. }
  402. return bids, bids[0].TotalItems - uint64(len(bids)), nil
  403. }
  404. // GetBidsAPI return the bids applying the given filters
  405. func (hdb *HistoryDB) GetBidsAPI(
  406. slotNum *int64, forgerAddr *ethCommon.Address,
  407. fromItem, limit *uint, order string,
  408. ) ([]BidAPI, uint64, error) {
  409. var query string
  410. var args []interface{}
  411. queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  412. COUNT(*) OVER() AS total_items
  413. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  414. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
  415. // Apply filters
  416. nextIsAnd := false
  417. // slotNum filter
  418. if slotNum != nil {
  419. if nextIsAnd {
  420. queryStr += "AND "
  421. } else {
  422. queryStr += "WHERE "
  423. }
  424. queryStr += "bid.slot_num = ? "
  425. args = append(args, slotNum)
  426. nextIsAnd = true
  427. }
  428. // slotNum filter
  429. if forgerAddr != nil {
  430. if nextIsAnd {
  431. queryStr += "AND "
  432. } else {
  433. queryStr += "WHERE "
  434. }
  435. queryStr += "bid.bidder_addr = ? "
  436. args = append(args, forgerAddr)
  437. nextIsAnd = true
  438. }
  439. if fromItem != nil {
  440. if nextIsAnd {
  441. queryStr += "AND "
  442. } else {
  443. queryStr += "WHERE "
  444. }
  445. if order == OrderAsc {
  446. queryStr += "bid.item_id >= ? "
  447. } else {
  448. queryStr += "bid.item_id <= ? "
  449. }
  450. args = append(args, fromItem)
  451. }
  452. // pagination
  453. queryStr += "ORDER BY bid.item_id "
  454. if order == OrderAsc {
  455. queryStr += "ASC "
  456. } else {
  457. queryStr += "DESC "
  458. }
  459. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  460. query, argsQ, err := sqlx.In(queryStr, args...)
  461. if err != nil {
  462. return nil, 0, err
  463. }
  464. query = hdb.db.Rebind(query)
  465. bids := []*BidAPI{}
  466. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  467. return nil, 0, err
  468. }
  469. if len(bids) == 0 {
  470. return nil, 0, sql.ErrNoRows
  471. }
  472. return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
  473. }
  474. // AddCoordinators insert Coordinators into the DB
  475. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  476. return hdb.addCoordinators(hdb.db, coordinators)
  477. }
  478. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  479. return db.BulkInsert(
  480. d,
  481. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  482. coordinators[:],
  483. )
  484. }
  485. // AddExitTree insert Exit tree into the DB
  486. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  487. return hdb.addExitTree(hdb.db, exitTree)
  488. }
  489. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  490. return db.BulkInsert(
  491. d,
  492. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  493. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  494. exitTree[:],
  495. )
  496. }
  497. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  498. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  499. type withdrawal struct {
  500. BatchNum int64 `db:"batch_num"`
  501. AccountIdx int64 `db:"account_idx"`
  502. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  503. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  504. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  505. Owner *ethCommon.Address `db:"owner"`
  506. Token *ethCommon.Address `db:"token"`
  507. }
  508. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  509. for i := range rollupWithdrawals {
  510. info := &rollupWithdrawals[i]
  511. withdrawals[i] = withdrawal{
  512. BatchNum: int64(info.NumExitRoot),
  513. AccountIdx: int64(info.Idx),
  514. }
  515. if info.InstantWithdraw {
  516. withdrawals[i].InstantWithdrawn = &blockNum
  517. } else {
  518. withdrawals[i].DelayedWithdrawRequest = &blockNum
  519. withdrawals[i].Owner = &info.Owner
  520. withdrawals[i].Token = &info.Token
  521. }
  522. }
  523. for i := range wDelayerWithdrawals {
  524. info := &wDelayerWithdrawals[i]
  525. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  526. DelayedWithdrawn: &blockNum,
  527. Owner: &info.Owner,
  528. Token: &info.Token,
  529. }
  530. }
  531. // In VALUES we set an initial row of NULLs to set the types of each
  532. // variable passed as argument
  533. query := `
  534. UPDATE exit_tree e SET
  535. instant_withdrawn = d.instant_withdrawn,
  536. delayed_withdraw_request = CASE
  537. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  538. ELSE d.delayed_withdraw_request
  539. END,
  540. delayed_withdrawn = d.delayed_withdrawn,
  541. owner = d.owner,
  542. token = d.token
  543. FROM (VALUES
  544. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  545. (:batch_num,
  546. :account_idx,
  547. :instant_withdrawn,
  548. :delayed_withdraw_request,
  549. :delayed_withdrawn,
  550. :owner,
  551. :token)
  552. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  553. WHERE
  554. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  555. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token)
  556. `
  557. if len(withdrawals) > 0 {
  558. if _, err := sqlx.NamedQuery(d, query, withdrawals); err != nil {
  559. return err
  560. }
  561. }
  562. return nil
  563. }
  564. // AddToken insert a token into the DB
  565. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  566. return meddler.Insert(hdb.db, "token", token)
  567. }
  568. // AddTokens insert tokens into the DB
  569. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  570. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  571. return db.BulkInsert(
  572. d,
  573. `INSERT INTO token (
  574. token_id,
  575. eth_block_num,
  576. eth_addr,
  577. name,
  578. symbol,
  579. decimals
  580. ) VALUES %s;`,
  581. tokens[:],
  582. )
  583. }
  584. // UpdateTokenValue updates the USD value of a token
  585. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  586. _, err := hdb.db.Exec(
  587. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  588. value, tokenSymbol,
  589. )
  590. return err
  591. }
  592. // GetToken returns a token from the DB given a TokenID
  593. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  594. token := &TokenWithUSD{}
  595. err := meddler.QueryRow(
  596. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  597. )
  598. return token, err
  599. }
  600. // GetAllTokens returns all tokens from the DB
  601. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  602. var tokens []*TokenWithUSD
  603. err := meddler.QueryAll(
  604. hdb.db, &tokens,
  605. "SELECT * FROM token ORDER BY token_id;",
  606. )
  607. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
  608. }
  609. // GetTokens returns a list of tokens from the DB
  610. func (hdb *HistoryDB) GetTokens(
  611. ids []common.TokenID, symbols []string, name string, fromItem,
  612. limit *uint, order string,
  613. ) ([]TokenWithUSD, uint64, error) {
  614. var query string
  615. var args []interface{}
  616. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  617. // Apply filters
  618. nextIsAnd := false
  619. if len(ids) > 0 {
  620. queryStr += "WHERE token_id IN (?) "
  621. nextIsAnd = true
  622. args = append(args, ids)
  623. }
  624. if len(symbols) > 0 {
  625. if nextIsAnd {
  626. queryStr += "AND "
  627. } else {
  628. queryStr += "WHERE "
  629. }
  630. queryStr += "symbol IN (?) "
  631. args = append(args, symbols)
  632. nextIsAnd = true
  633. }
  634. if name != "" {
  635. if nextIsAnd {
  636. queryStr += "AND "
  637. } else {
  638. queryStr += "WHERE "
  639. }
  640. queryStr += "name ~ ? "
  641. args = append(args, name)
  642. nextIsAnd = true
  643. }
  644. if fromItem != nil {
  645. if nextIsAnd {
  646. queryStr += "AND "
  647. } else {
  648. queryStr += "WHERE "
  649. }
  650. if order == OrderAsc {
  651. queryStr += "item_id >= ? "
  652. } else {
  653. queryStr += "item_id <= ? "
  654. }
  655. args = append(args, fromItem)
  656. }
  657. // pagination
  658. queryStr += "ORDER BY item_id "
  659. if order == OrderAsc {
  660. queryStr += "ASC "
  661. } else {
  662. queryStr += "DESC "
  663. }
  664. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  665. query, argsQ, err := sqlx.In(queryStr, args...)
  666. if err != nil {
  667. return nil, 0, err
  668. }
  669. query = hdb.db.Rebind(query)
  670. tokens := []*TokenWithUSD{}
  671. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  672. return nil, 0, err
  673. }
  674. if len(tokens) == 0 {
  675. return nil, 0, sql.ErrNoRows
  676. }
  677. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  678. }
  679. // GetTokenSymbols returns all the token symbols from the DB
  680. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  681. var tokenSymbols []string
  682. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  683. if err != nil {
  684. return nil, err
  685. }
  686. sym := new(string)
  687. for rows.Next() {
  688. err = rows.Scan(sym)
  689. if err != nil {
  690. return nil, err
  691. }
  692. tokenSymbols = append(tokenSymbols, *sym)
  693. }
  694. return tokenSymbols, nil
  695. }
  696. // AddAccounts insert accounts into the DB
  697. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  698. return hdb.addAccounts(hdb.db, accounts)
  699. }
  700. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  701. return db.BulkInsert(
  702. d,
  703. `INSERT INTO account (
  704. idx,
  705. token_id,
  706. batch_num,
  707. bjj,
  708. eth_addr
  709. ) VALUES %s;`,
  710. accounts[:],
  711. )
  712. }
  713. // GetAllAccounts returns a list of accounts from the DB
  714. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  715. var accs []*common.Account
  716. err := meddler.QueryAll(
  717. hdb.db, &accs,
  718. "SELECT * FROM account ORDER BY idx;",
  719. )
  720. return db.SlicePtrsToSlice(accs).([]common.Account), err
  721. }
  722. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  723. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  724. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  725. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  726. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  727. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  728. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  729. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  730. txs := []txWrite{}
  731. for i := 0; i < len(l1txs); i++ {
  732. af := new(big.Float).SetInt(l1txs[i].Amount)
  733. amountFloat, _ := af.Float64()
  734. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  735. loadAmountFloat, _ := laf.Float64()
  736. txs = append(txs, txWrite{
  737. // Generic
  738. IsL1: true,
  739. TxID: l1txs[i].TxID,
  740. Type: l1txs[i].Type,
  741. Position: l1txs[i].Position,
  742. FromIdx: &l1txs[i].FromIdx,
  743. ToIdx: l1txs[i].ToIdx,
  744. Amount: l1txs[i].Amount,
  745. EffectiveAmount: l1txs[i].EffectiveAmount,
  746. AmountFloat: amountFloat,
  747. TokenID: l1txs[i].TokenID,
  748. BatchNum: l1txs[i].BatchNum,
  749. EthBlockNum: l1txs[i].EthBlockNum,
  750. // L1
  751. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  752. UserOrigin: &l1txs[i].UserOrigin,
  753. FromEthAddr: &l1txs[i].FromEthAddr,
  754. FromBJJ: l1txs[i].FromBJJ,
  755. LoadAmount: l1txs[i].LoadAmount,
  756. EffectiveLoadAmount: l1txs[i].EffectiveLoadAmount,
  757. LoadAmountFloat: &loadAmountFloat,
  758. })
  759. }
  760. return hdb.addTxs(d, txs)
  761. }
  762. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  763. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  764. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  765. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  766. txs := []txWrite{}
  767. for i := 0; i < len(l2txs); i++ {
  768. f := new(big.Float).SetInt(l2txs[i].Amount)
  769. amountFloat, _ := f.Float64()
  770. txs = append(txs, txWrite{
  771. // Generic
  772. IsL1: false,
  773. TxID: l2txs[i].TxID,
  774. Type: l2txs[i].Type,
  775. Position: l2txs[i].Position,
  776. FromIdx: &l2txs[i].FromIdx,
  777. ToIdx: l2txs[i].ToIdx,
  778. Amount: l2txs[i].Amount,
  779. AmountFloat: amountFloat,
  780. BatchNum: &l2txs[i].BatchNum,
  781. EthBlockNum: l2txs[i].EthBlockNum,
  782. // L2
  783. Fee: &l2txs[i].Fee,
  784. Nonce: &l2txs[i].Nonce,
  785. })
  786. }
  787. return hdb.addTxs(d, txs)
  788. }
  789. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  790. return db.BulkInsert(
  791. d,
  792. `INSERT INTO tx (
  793. is_l1,
  794. id,
  795. type,
  796. position,
  797. from_idx,
  798. to_idx,
  799. amount,
  800. effective_amount,
  801. amount_f,
  802. token_id,
  803. batch_num,
  804. eth_block_num,
  805. to_forge_l1_txs_num,
  806. user_origin,
  807. from_eth_addr,
  808. from_bjj,
  809. load_amount,
  810. effective_load_amount,
  811. load_amount_f,
  812. fee,
  813. nonce
  814. ) VALUES %s;`,
  815. txs[:],
  816. )
  817. }
  818. // // GetTxs returns a list of txs from the DB
  819. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  820. // var txs []*common.Tx
  821. // err := meddler.QueryAll(
  822. // hdb.db, &txs,
  823. // `SELECT * FROM tx
  824. // ORDER BY (batch_num, position) ASC`,
  825. // )
  826. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  827. // }
  828. // GetHistoryTx returns a tx from the DB given a TxID
  829. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  830. tx := &TxAPI{}
  831. err := meddler.QueryRow(
  832. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  833. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  834. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  835. tx.amount, tx.token_id, tx.amount_usd,
  836. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  837. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  838. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  839. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  840. token.usd_update, block.timestamp
  841. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  842. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  843. WHERE tx.id = $1;`, txID,
  844. )
  845. return tx, err
  846. }
  847. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  848. // and pagination info
  849. func (hdb *HistoryDB) GetHistoryTxs(
  850. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  851. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  852. fromItem, limit *uint, order string,
  853. ) ([]TxAPI, uint64, error) {
  854. if ethAddr != nil && bjj != nil {
  855. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  856. }
  857. var query string
  858. var args []interface{}
  859. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  860. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  861. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  862. tx.amount, tx.token_id, tx.amount_usd,
  863. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  864. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  865. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  866. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  867. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  868. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  869. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  870. // Apply filters
  871. nextIsAnd := false
  872. // ethAddr filter
  873. if ethAddr != nil {
  874. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  875. nextIsAnd = true
  876. args = append(args, ethAddr, ethAddr)
  877. } else if bjj != nil { // bjj filter
  878. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  879. nextIsAnd = true
  880. args = append(args, bjj, bjj)
  881. }
  882. // tokenID filter
  883. if tokenID != nil {
  884. if nextIsAnd {
  885. queryStr += "AND "
  886. } else {
  887. queryStr += "WHERE "
  888. }
  889. queryStr += "tx.token_id = ? "
  890. args = append(args, tokenID)
  891. nextIsAnd = true
  892. }
  893. // idx filter
  894. if idx != nil {
  895. if nextIsAnd {
  896. queryStr += "AND "
  897. } else {
  898. queryStr += "WHERE "
  899. }
  900. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  901. args = append(args, idx, idx)
  902. nextIsAnd = true
  903. }
  904. // batchNum filter
  905. if batchNum != nil {
  906. if nextIsAnd {
  907. queryStr += "AND "
  908. } else {
  909. queryStr += "WHERE "
  910. }
  911. queryStr += "tx.batch_num = ? "
  912. args = append(args, batchNum)
  913. nextIsAnd = true
  914. }
  915. // txType filter
  916. if txType != nil {
  917. if nextIsAnd {
  918. queryStr += "AND "
  919. } else {
  920. queryStr += "WHERE "
  921. }
  922. queryStr += "tx.type = ? "
  923. args = append(args, txType)
  924. nextIsAnd = true
  925. }
  926. if fromItem != nil {
  927. if nextIsAnd {
  928. queryStr += "AND "
  929. } else {
  930. queryStr += "WHERE "
  931. }
  932. if order == OrderAsc {
  933. queryStr += "tx.item_id >= ? "
  934. } else {
  935. queryStr += "tx.item_id <= ? "
  936. }
  937. args = append(args, fromItem)
  938. nextIsAnd = true
  939. }
  940. if nextIsAnd {
  941. queryStr += "AND "
  942. } else {
  943. queryStr += "WHERE "
  944. }
  945. queryStr += "tx.batch_num IS NOT NULL "
  946. // pagination
  947. queryStr += "ORDER BY tx.item_id "
  948. if order == OrderAsc {
  949. queryStr += " ASC "
  950. } else {
  951. queryStr += " DESC "
  952. }
  953. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  954. query = hdb.db.Rebind(queryStr)
  955. // log.Debug(query)
  956. txsPtrs := []*TxAPI{}
  957. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  958. return nil, 0, err
  959. }
  960. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  961. if len(txs) == 0 {
  962. return nil, 0, sql.ErrNoRows
  963. }
  964. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  965. }
  966. // GetAllExits returns all exit from the DB
  967. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  968. var exits []*common.ExitInfo
  969. err := meddler.QueryAll(
  970. hdb.db, &exits,
  971. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  972. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  973. exit_tree.delayed_withdrawn FROM exit_tree;`,
  974. )
  975. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  976. }
  977. // GetExitAPI returns a exit from the DB
  978. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  979. exit := &ExitAPI{}
  980. err := meddler.QueryRow(
  981. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  982. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  983. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  984. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  985. token.token_id, token.item_id AS token_item_id,
  986. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  987. token.decimals, token.usd, token.usd_update
  988. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  989. INNER JOIN token ON account.token_id = token.token_id
  990. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  991. )
  992. return exit, err
  993. }
  994. // GetExitsAPI returns a list of exits from the DB and pagination info
  995. func (hdb *HistoryDB) GetExitsAPI(
  996. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  997. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  998. fromItem, limit *uint, order string,
  999. ) ([]ExitAPI, uint64, error) {
  1000. if ethAddr != nil && bjj != nil {
  1001. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  1002. }
  1003. var query string
  1004. var args []interface{}
  1005. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1006. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1007. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1008. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1009. token.token_id, token.item_id AS token_item_id,
  1010. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  1011. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1012. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1013. INNER JOIN token ON account.token_id = token.token_id `
  1014. // Apply filters
  1015. nextIsAnd := false
  1016. // ethAddr filter
  1017. if ethAddr != nil {
  1018. queryStr += "WHERE account.eth_addr = ? "
  1019. nextIsAnd = true
  1020. args = append(args, ethAddr)
  1021. } else if bjj != nil { // bjj filter
  1022. queryStr += "WHERE account.bjj = ? "
  1023. nextIsAnd = true
  1024. args = append(args, bjj)
  1025. }
  1026. // tokenID filter
  1027. if tokenID != nil {
  1028. if nextIsAnd {
  1029. queryStr += "AND "
  1030. } else {
  1031. queryStr += "WHERE "
  1032. }
  1033. queryStr += "account.token_id = ? "
  1034. args = append(args, tokenID)
  1035. nextIsAnd = true
  1036. }
  1037. // idx filter
  1038. if idx != nil {
  1039. if nextIsAnd {
  1040. queryStr += "AND "
  1041. } else {
  1042. queryStr += "WHERE "
  1043. }
  1044. queryStr += "exit_tree.account_idx = ? "
  1045. args = append(args, idx)
  1046. nextIsAnd = true
  1047. }
  1048. // batchNum filter
  1049. if batchNum != nil {
  1050. if nextIsAnd {
  1051. queryStr += "AND "
  1052. } else {
  1053. queryStr += "WHERE "
  1054. }
  1055. queryStr += "exit_tree.batch_num = ? "
  1056. args = append(args, batchNum)
  1057. nextIsAnd = true
  1058. }
  1059. // onlyPendingWithdraws
  1060. if onlyPendingWithdraws != nil {
  1061. if *onlyPendingWithdraws {
  1062. if nextIsAnd {
  1063. queryStr += "AND "
  1064. } else {
  1065. queryStr += "WHERE "
  1066. }
  1067. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1068. nextIsAnd = true
  1069. }
  1070. }
  1071. if fromItem != nil {
  1072. if nextIsAnd {
  1073. queryStr += "AND "
  1074. } else {
  1075. queryStr += "WHERE "
  1076. }
  1077. if order == OrderAsc {
  1078. queryStr += "exit_tree.item_id >= ? "
  1079. } else {
  1080. queryStr += "exit_tree.item_id <= ? "
  1081. }
  1082. args = append(args, fromItem)
  1083. // nextIsAnd = true
  1084. }
  1085. // pagination
  1086. queryStr += "ORDER BY exit_tree.item_id "
  1087. if order == OrderAsc {
  1088. queryStr += " ASC "
  1089. } else {
  1090. queryStr += " DESC "
  1091. }
  1092. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1093. query = hdb.db.Rebind(queryStr)
  1094. // log.Debug(query)
  1095. exits := []*ExitAPI{}
  1096. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1097. return nil, 0, err
  1098. }
  1099. if len(exits) == 0 {
  1100. return nil, 0, sql.ErrNoRows
  1101. }
  1102. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1103. }
  1104. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1105. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1106. var txs []*common.L1Tx
  1107. err := meddler.QueryAll(
  1108. hdb.db, &txs,
  1109. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1110. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1111. tx.amount, tx.effective_amount, tx.load_amount, tx.effective_load_amount,
  1112. tx.eth_block_num, tx.type, tx.batch_num
  1113. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  1114. )
  1115. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1116. }
  1117. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1118. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1119. var txs []*common.L1Tx
  1120. err := meddler.QueryAll(
  1121. hdb.db, &txs,
  1122. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1123. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1124. tx.amount, tx.effective_amount, tx.load_amount, tx.effective_load_amount,
  1125. tx.eth_block_num, tx.type, tx.batch_num
  1126. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1127. )
  1128. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1129. }
  1130. // GetAllL2Txs returns all L2Txs from the DB
  1131. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1132. var txs []*common.L2Tx
  1133. err := meddler.QueryAll(
  1134. hdb.db, &txs,
  1135. `SELECT tx.id, tx.batch_num, tx.position,
  1136. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1137. tx.type, tx.eth_block_num
  1138. FROM tx WHERE is_l1 = FALSE;`,
  1139. )
  1140. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1141. }
  1142. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1143. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1144. var txs []*common.L1Tx
  1145. err := meddler.QueryAll(
  1146. hdb.db, &txs,
  1147. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1148. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1149. tx.amount, tx.effective_amount, tx.load_amount, tx.effective_load_amount,
  1150. tx.eth_block_num, tx.type, tx.batch_num
  1151. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1152. toForgeL1TxsNum,
  1153. )
  1154. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1155. }
  1156. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1157. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1158. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1159. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1160. var lastL1TxsPosition int
  1161. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1162. }
  1163. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1164. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1165. *common.WDelayerVariables, error) {
  1166. var rollup common.RollupVariables
  1167. var auction common.AuctionVariables
  1168. var wDelayer common.WDelayerVariables
  1169. if err := meddler.QueryRow(hdb.db, &rollup,
  1170. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1171. return nil, nil, nil, err
  1172. }
  1173. if err := meddler.QueryRow(hdb.db, &auction,
  1174. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1175. return nil, nil, nil, err
  1176. }
  1177. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1178. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1179. return nil, nil, nil, err
  1180. }
  1181. return &rollup, &auction, &wDelayer, nil
  1182. }
  1183. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1184. return meddler.Insert(d, "rollup_vars", rollup)
  1185. }
  1186. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1187. return meddler.Insert(d, "auction_vars", auction)
  1188. }
  1189. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1190. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1191. }
  1192. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1193. // contract variables. This initial state is stored linked to block 0, which
  1194. // always exist in the DB and is used to store initialization data that always
  1195. // exist in the smart contracts.
  1196. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1197. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1198. txn, err := hdb.db.Beginx()
  1199. if err != nil {
  1200. return err
  1201. }
  1202. defer func() {
  1203. if err != nil {
  1204. db.Rollback(txn)
  1205. }
  1206. }()
  1207. // Force EthBlockNum to be 0 because it's the block used to link data
  1208. // that belongs to the creation of the smart contracts
  1209. rollup.EthBlockNum = 0
  1210. auction.EthBlockNum = 0
  1211. wDelayer.EthBlockNum = 0
  1212. auction.DefaultSlotSetBidSlotNum = 0
  1213. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1214. return err
  1215. }
  1216. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1217. return err
  1218. }
  1219. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1220. return err
  1221. }
  1222. return txn.Commit()
  1223. }
  1224. // AddBlockSCData stores all the information of a block retrieved by the
  1225. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1226. // the pagination system of the API/DB depends on this. Within blocks, all
  1227. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1228. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1229. txn, err := hdb.db.Beginx()
  1230. if err != nil {
  1231. return err
  1232. }
  1233. defer func() {
  1234. if err != nil {
  1235. db.Rollback(txn)
  1236. }
  1237. }()
  1238. // Add block
  1239. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1240. return err
  1241. }
  1242. // Add Coordinators
  1243. if len(blockData.Auction.Coordinators) > 0 {
  1244. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1245. return err
  1246. }
  1247. }
  1248. // Add Bids
  1249. if len(blockData.Auction.Bids) > 0 {
  1250. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1251. return err
  1252. }
  1253. }
  1254. // Add Tokens
  1255. if len(blockData.Rollup.AddedTokens) > 0 {
  1256. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1257. return err
  1258. }
  1259. }
  1260. // Prepare user L1 txs to be added.
  1261. // They must be added before the batch that will forge them (which can be in the same block)
  1262. // and after the account that will be sent to (also can be in the same block).
  1263. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1264. // the batch that forges those txs is inserted
  1265. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1266. for i := range blockData.Rollup.L1UserTxs {
  1267. batchThatForgesIsInTheBlock := false
  1268. for _, batch := range blockData.Rollup.Batches {
  1269. if batch.Batch.ForgeL1TxsNum != nil &&
  1270. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1271. // Tx is forged in this block. It's guaranteed that:
  1272. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1273. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1274. batchThatForgesIsInTheBlock = true
  1275. addAtBatchNum := batch.Batch.BatchNum - 1
  1276. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1277. break
  1278. }
  1279. }
  1280. if !batchThatForgesIsInTheBlock {
  1281. // User artificial batchNum 0 to add txs that are not forge in this block
  1282. // after all the accounts of the block have been added
  1283. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1284. }
  1285. }
  1286. // Add Batches
  1287. for i := range blockData.Rollup.Batches {
  1288. batch := &blockData.Rollup.Batches[i]
  1289. // Add Batch: this will trigger an update on the DB
  1290. // that will set the batch num of forged L1 txs in this batch
  1291. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1292. return err
  1293. }
  1294. // Add accounts
  1295. if len(batch.CreatedAccounts) > 0 {
  1296. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1297. return err
  1298. }
  1299. }
  1300. // Add forged l1 coordinator Txs
  1301. if len(batch.L1CoordinatorTxs) > 0 {
  1302. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1303. return err
  1304. }
  1305. }
  1306. // Add l2 Txs
  1307. if len(batch.L2Txs) > 0 {
  1308. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1309. return err
  1310. }
  1311. }
  1312. // Add user L1 txs that will be forged in next batch
  1313. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1314. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1315. return err
  1316. }
  1317. }
  1318. // Add exit tree
  1319. if len(batch.ExitTree) > 0 {
  1320. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1321. return err
  1322. }
  1323. }
  1324. }
  1325. // Add user L1 txs that won't be forged in this block
  1326. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1327. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1328. return err
  1329. }
  1330. }
  1331. if blockData.Rollup.Vars != nil {
  1332. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1333. return err
  1334. }
  1335. }
  1336. if blockData.Auction.Vars != nil {
  1337. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1338. return err
  1339. }
  1340. }
  1341. if blockData.WDelayer.Vars != nil {
  1342. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1343. return err
  1344. }
  1345. }
  1346. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1347. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1348. return err
  1349. }
  1350. return txn.Commit()
  1351. }
  1352. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1353. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1354. coordinator := &CoordinatorAPI{}
  1355. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1356. return coordinator, err
  1357. }
  1358. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1359. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, uint64, error) {
  1360. var query string
  1361. var args []interface{}
  1362. queryStr := `SELECT coordinator.*,
  1363. COUNT(*) OVER() AS total_items
  1364. FROM coordinator `
  1365. // Apply filters
  1366. if fromItem != nil {
  1367. queryStr += "WHERE "
  1368. if order == OrderAsc {
  1369. queryStr += "coordinator.item_id >= ? "
  1370. } else {
  1371. queryStr += "coordinator.item_id <= ? "
  1372. }
  1373. args = append(args, fromItem)
  1374. }
  1375. // pagination
  1376. queryStr += "ORDER BY coordinator.item_id "
  1377. if order == OrderAsc {
  1378. queryStr += " ASC "
  1379. } else {
  1380. queryStr += " DESC "
  1381. }
  1382. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1383. query = hdb.db.Rebind(queryStr)
  1384. coordinators := []*CoordinatorAPI{}
  1385. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1386. return nil, 0, err
  1387. }
  1388. if len(coordinators) == 0 {
  1389. return nil, 0, sql.ErrNoRows
  1390. }
  1391. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1392. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1393. }
  1394. // AddAuctionVars insert auction vars into the DB
  1395. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1396. return meddler.Insert(hdb.db, "auction_vars", auctionVars)
  1397. }
  1398. // GetAuctionVars returns auction variables
  1399. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1400. auctionVars := &common.AuctionVariables{}
  1401. err := meddler.QueryRow(
  1402. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1403. )
  1404. return auctionVars, err
  1405. }
  1406. // GetAccountAPI returns an account by its index
  1407. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1408. account := &AccountAPI{}
  1409. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1410. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1411. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1412. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1413. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1414. if err != nil {
  1415. return nil, err
  1416. }
  1417. return account, nil
  1418. }
  1419. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1420. func (hdb *HistoryDB) GetAccountsAPI(
  1421. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1422. bjj *babyjub.PublicKey, fromItem, limit *uint, order string,
  1423. ) ([]AccountAPI, uint64, error) {
  1424. if ethAddr != nil && bjj != nil {
  1425. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  1426. }
  1427. var query string
  1428. var args []interface{}
  1429. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1430. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1431. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1432. COUNT(*) OVER() AS total_items
  1433. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1434. // Apply filters
  1435. nextIsAnd := false
  1436. // ethAddr filter
  1437. if ethAddr != nil {
  1438. queryStr += "WHERE account.eth_addr = ? "
  1439. nextIsAnd = true
  1440. args = append(args, ethAddr)
  1441. } else if bjj != nil { // bjj filter
  1442. queryStr += "WHERE account.bjj = ? "
  1443. nextIsAnd = true
  1444. args = append(args, bjj)
  1445. }
  1446. // tokenID filter
  1447. if len(tokenIDs) > 0 {
  1448. if nextIsAnd {
  1449. queryStr += "AND "
  1450. } else {
  1451. queryStr += "WHERE "
  1452. }
  1453. queryStr += "account.token_id IN (?) "
  1454. args = append(args, tokenIDs)
  1455. nextIsAnd = true
  1456. }
  1457. if fromItem != nil {
  1458. if nextIsAnd {
  1459. queryStr += "AND "
  1460. } else {
  1461. queryStr += "WHERE "
  1462. }
  1463. if order == OrderAsc {
  1464. queryStr += "account.item_id >= ? "
  1465. } else {
  1466. queryStr += "account.item_id <= ? "
  1467. }
  1468. args = append(args, fromItem)
  1469. }
  1470. // pagination
  1471. queryStr += "ORDER BY account.item_id "
  1472. if order == OrderAsc {
  1473. queryStr += " ASC "
  1474. } else {
  1475. queryStr += " DESC "
  1476. }
  1477. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1478. query, argsQ, err := sqlx.In(queryStr, args...)
  1479. if err != nil {
  1480. return nil, 0, err
  1481. }
  1482. query = hdb.db.Rebind(query)
  1483. accounts := []*AccountAPI{}
  1484. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1485. return nil, 0, err
  1486. }
  1487. if len(accounts) == 0 {
  1488. return nil, 0, sql.ErrNoRows
  1489. }
  1490. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1491. accounts[0].TotalItems - uint64(len(accounts)), nil
  1492. }
  1493. // GetMetrics returns metrics
  1494. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1495. metricsTotals := &MetricsTotals{}
  1496. metrics := &Metrics{}
  1497. err := meddler.QueryRow(
  1498. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1499. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1500. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1501. if err != nil {
  1502. return nil, err
  1503. }
  1504. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1505. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1506. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1507. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1508. } else {
  1509. metrics.TransactionsPerBatch = float64(0)
  1510. }
  1511. err = meddler.QueryRow(
  1512. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1513. SUM(total_fees_usd) AS total_fees FROM batch
  1514. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1515. if err != nil {
  1516. return nil, err
  1517. }
  1518. if metricsTotals.TotalBatches > 0 {
  1519. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1520. } else {
  1521. metrics.BatchFrequency = 0
  1522. }
  1523. if metricsTotals.TotalTransactions > 0 {
  1524. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1525. } else {
  1526. metrics.AvgTransactionFee = 0
  1527. }
  1528. err = meddler.QueryRow(
  1529. hdb.db, metrics,
  1530. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1531. if err != nil {
  1532. return nil, err
  1533. }
  1534. return metrics, nil
  1535. }
  1536. // GetAvgTxFee returns average transaction fee of the last 1h
  1537. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1538. metricsTotals := &MetricsTotals{}
  1539. err := meddler.QueryRow(
  1540. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1541. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1542. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1543. if err != nil {
  1544. return 0, err
  1545. }
  1546. err = meddler.QueryRow(
  1547. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1548. SUM(total_fees_usd) AS total_fees FROM batch
  1549. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1550. if err != nil {
  1551. return 0, err
  1552. }
  1553. var avgTransactionFee float64
  1554. if metricsTotals.TotalTransactions > 0 {
  1555. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1556. } else {
  1557. avgTransactionFee = 0
  1558. }
  1559. return avgTransactionFee, nil
  1560. }