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.

1655 lines
49 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.
3 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.
3 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.
3 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.
3 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.
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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. AmountFloat: amountFloat,
  746. TokenID: l1txs[i].TokenID,
  747. BatchNum: l1txs[i].BatchNum,
  748. EthBlockNum: l1txs[i].EthBlockNum,
  749. // L1
  750. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  751. UserOrigin: &l1txs[i].UserOrigin,
  752. FromEthAddr: &l1txs[i].FromEthAddr,
  753. FromBJJ: l1txs[i].FromBJJ,
  754. LoadAmount: l1txs[i].LoadAmount,
  755. LoadAmountFloat: &loadAmountFloat,
  756. })
  757. }
  758. return hdb.addTxs(d, txs)
  759. }
  760. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  761. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  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(d meddler.DB, l2txs []common.L2Tx) error {
  764. txs := []txWrite{}
  765. for i := 0; i < len(l2txs); i++ {
  766. f := new(big.Float).SetInt(l2txs[i].Amount)
  767. amountFloat, _ := f.Float64()
  768. txs = append(txs, txWrite{
  769. // Generic
  770. IsL1: false,
  771. TxID: l2txs[i].TxID,
  772. Type: l2txs[i].Type,
  773. Position: l2txs[i].Position,
  774. FromIdx: &l2txs[i].FromIdx,
  775. ToIdx: l2txs[i].ToIdx,
  776. Amount: l2txs[i].Amount,
  777. AmountFloat: amountFloat,
  778. BatchNum: &l2txs[i].BatchNum,
  779. EthBlockNum: l2txs[i].EthBlockNum,
  780. // L2
  781. Fee: &l2txs[i].Fee,
  782. Nonce: &l2txs[i].Nonce,
  783. })
  784. }
  785. return hdb.addTxs(d, txs)
  786. }
  787. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  788. return db.BulkInsert(
  789. d,
  790. `INSERT INTO tx (
  791. is_l1,
  792. id,
  793. type,
  794. position,
  795. from_idx,
  796. to_idx,
  797. amount,
  798. amount_f,
  799. token_id,
  800. batch_num,
  801. eth_block_num,
  802. to_forge_l1_txs_num,
  803. user_origin,
  804. from_eth_addr,
  805. from_bjj,
  806. load_amount,
  807. load_amount_f,
  808. fee,
  809. nonce
  810. ) VALUES %s;`,
  811. txs[:],
  812. )
  813. }
  814. // // GetTxs returns a list of txs from the DB
  815. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  816. // var txs []*common.Tx
  817. // err := meddler.QueryAll(
  818. // hdb.db, &txs,
  819. // `SELECT * FROM tx
  820. // ORDER BY (batch_num, position) ASC`,
  821. // )
  822. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  823. // }
  824. // GetHistoryTx returns a tx from the DB given a TxID
  825. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  826. tx := &TxAPI{}
  827. err := meddler.QueryRow(
  828. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  829. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  830. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  831. tx.amount, tx.token_id, tx.amount_usd,
  832. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  833. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  834. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  835. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  836. token.usd_update, block.timestamp
  837. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  838. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  839. WHERE tx.id = $1;`, txID,
  840. )
  841. return tx, err
  842. }
  843. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  844. // and pagination info
  845. func (hdb *HistoryDB) GetHistoryTxs(
  846. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  847. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  848. fromItem, limit *uint, order string,
  849. ) ([]TxAPI, uint64, error) {
  850. if ethAddr != nil && bjj != nil {
  851. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  852. }
  853. var query string
  854. var args []interface{}
  855. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  856. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  857. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  858. tx.amount, tx.token_id, tx.amount_usd,
  859. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  860. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  861. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  862. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  863. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  864. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  865. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  866. // Apply filters
  867. nextIsAnd := false
  868. // ethAddr filter
  869. if ethAddr != nil {
  870. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  871. nextIsAnd = true
  872. args = append(args, ethAddr, ethAddr)
  873. } else if bjj != nil { // bjj filter
  874. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  875. nextIsAnd = true
  876. args = append(args, bjj, bjj)
  877. }
  878. // tokenID filter
  879. if tokenID != nil {
  880. if nextIsAnd {
  881. queryStr += "AND "
  882. } else {
  883. queryStr += "WHERE "
  884. }
  885. queryStr += "tx.token_id = ? "
  886. args = append(args, tokenID)
  887. nextIsAnd = true
  888. }
  889. // idx filter
  890. if idx != nil {
  891. if nextIsAnd {
  892. queryStr += "AND "
  893. } else {
  894. queryStr += "WHERE "
  895. }
  896. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  897. args = append(args, idx, idx)
  898. nextIsAnd = true
  899. }
  900. // batchNum filter
  901. if batchNum != nil {
  902. if nextIsAnd {
  903. queryStr += "AND "
  904. } else {
  905. queryStr += "WHERE "
  906. }
  907. queryStr += "tx.batch_num = ? "
  908. args = append(args, batchNum)
  909. nextIsAnd = true
  910. }
  911. // txType filter
  912. if txType != nil {
  913. if nextIsAnd {
  914. queryStr += "AND "
  915. } else {
  916. queryStr += "WHERE "
  917. }
  918. queryStr += "tx.type = ? "
  919. args = append(args, txType)
  920. nextIsAnd = true
  921. }
  922. if fromItem != nil {
  923. if nextIsAnd {
  924. queryStr += "AND "
  925. } else {
  926. queryStr += "WHERE "
  927. }
  928. if order == OrderAsc {
  929. queryStr += "tx.item_id >= ? "
  930. } else {
  931. queryStr += "tx.item_id <= ? "
  932. }
  933. args = append(args, fromItem)
  934. nextIsAnd = true
  935. }
  936. if nextIsAnd {
  937. queryStr += "AND "
  938. } else {
  939. queryStr += "WHERE "
  940. }
  941. queryStr += "tx.batch_num IS NOT NULL "
  942. // pagination
  943. queryStr += "ORDER BY tx.item_id "
  944. if order == OrderAsc {
  945. queryStr += " ASC "
  946. } else {
  947. queryStr += " DESC "
  948. }
  949. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  950. query = hdb.db.Rebind(queryStr)
  951. // log.Debug(query)
  952. txsPtrs := []*TxAPI{}
  953. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  954. return nil, 0, err
  955. }
  956. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  957. if len(txs) == 0 {
  958. return nil, 0, sql.ErrNoRows
  959. }
  960. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  961. }
  962. // GetAllExits returns all exit from the DB
  963. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  964. var exits []*common.ExitInfo
  965. err := meddler.QueryAll(
  966. hdb.db, &exits,
  967. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  968. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  969. exit_tree.delayed_withdrawn FROM exit_tree;`,
  970. )
  971. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  972. }
  973. // GetExitAPI returns a exit from the DB
  974. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  975. exit := &ExitAPI{}
  976. err := meddler.QueryRow(
  977. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  978. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  979. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  980. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  981. token.token_id, token.item_id AS token_item_id,
  982. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  983. token.decimals, token.usd, token.usd_update
  984. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  985. INNER JOIN token ON account.token_id = token.token_id
  986. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  987. )
  988. return exit, err
  989. }
  990. // GetExitsAPI returns a list of exits from the DB and pagination info
  991. func (hdb *HistoryDB) GetExitsAPI(
  992. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  993. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  994. fromItem, limit *uint, order string,
  995. ) ([]ExitAPI, uint64, error) {
  996. if ethAddr != nil && bjj != nil {
  997. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  998. }
  999. var query string
  1000. var args []interface{}
  1001. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1002. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1003. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1004. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1005. token.token_id, token.item_id AS token_item_id,
  1006. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  1007. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1008. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1009. INNER JOIN token ON account.token_id = token.token_id `
  1010. // Apply filters
  1011. nextIsAnd := false
  1012. // ethAddr filter
  1013. if ethAddr != nil {
  1014. queryStr += "WHERE account.eth_addr = ? "
  1015. nextIsAnd = true
  1016. args = append(args, ethAddr)
  1017. } else if bjj != nil { // bjj filter
  1018. queryStr += "WHERE account.bjj = ? "
  1019. nextIsAnd = true
  1020. args = append(args, bjj)
  1021. }
  1022. // tokenID filter
  1023. if tokenID != nil {
  1024. if nextIsAnd {
  1025. queryStr += "AND "
  1026. } else {
  1027. queryStr += "WHERE "
  1028. }
  1029. queryStr += "account.token_id = ? "
  1030. args = append(args, tokenID)
  1031. nextIsAnd = true
  1032. }
  1033. // idx filter
  1034. if idx != nil {
  1035. if nextIsAnd {
  1036. queryStr += "AND "
  1037. } else {
  1038. queryStr += "WHERE "
  1039. }
  1040. queryStr += "exit_tree.account_idx = ? "
  1041. args = append(args, idx)
  1042. nextIsAnd = true
  1043. }
  1044. // batchNum filter
  1045. if batchNum != nil {
  1046. if nextIsAnd {
  1047. queryStr += "AND "
  1048. } else {
  1049. queryStr += "WHERE "
  1050. }
  1051. queryStr += "exit_tree.batch_num = ? "
  1052. args = append(args, batchNum)
  1053. nextIsAnd = true
  1054. }
  1055. // onlyPendingWithdraws
  1056. if onlyPendingWithdraws != nil {
  1057. if *onlyPendingWithdraws {
  1058. if nextIsAnd {
  1059. queryStr += "AND "
  1060. } else {
  1061. queryStr += "WHERE "
  1062. }
  1063. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1064. nextIsAnd = true
  1065. }
  1066. }
  1067. if fromItem != nil {
  1068. if nextIsAnd {
  1069. queryStr += "AND "
  1070. } else {
  1071. queryStr += "WHERE "
  1072. }
  1073. if order == OrderAsc {
  1074. queryStr += "exit_tree.item_id >= ? "
  1075. } else {
  1076. queryStr += "exit_tree.item_id <= ? "
  1077. }
  1078. args = append(args, fromItem)
  1079. // nextIsAnd = true
  1080. }
  1081. // pagination
  1082. queryStr += "ORDER BY exit_tree.item_id "
  1083. if order == OrderAsc {
  1084. queryStr += " ASC "
  1085. } else {
  1086. queryStr += " DESC "
  1087. }
  1088. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1089. query = hdb.db.Rebind(queryStr)
  1090. // log.Debug(query)
  1091. exits := []*ExitAPI{}
  1092. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1093. return nil, 0, err
  1094. }
  1095. if len(exits) == 0 {
  1096. return nil, 0, sql.ErrNoRows
  1097. }
  1098. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1099. }
  1100. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1101. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1102. var txs []*common.L1Tx
  1103. err := meddler.QueryAll(
  1104. hdb.db, &txs,
  1105. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1106. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1107. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1108. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  1109. )
  1110. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1111. }
  1112. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1113. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1114. var txs []*common.L1Tx
  1115. err := meddler.QueryAll(
  1116. hdb.db, &txs,
  1117. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1118. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1119. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1120. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1121. )
  1122. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1123. }
  1124. // GetAllL2Txs returns all L2Txs from the DB
  1125. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1126. var txs []*common.L2Tx
  1127. err := meddler.QueryAll(
  1128. hdb.db, &txs,
  1129. `SELECT tx.id, tx.batch_num, tx.position,
  1130. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1131. tx.type, tx.eth_block_num
  1132. FROM tx WHERE is_l1 = FALSE;`,
  1133. )
  1134. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1135. }
  1136. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1137. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1138. var txs []*common.L1Tx
  1139. err := meddler.QueryAll(
  1140. hdb.db, &txs,
  1141. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1142. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1143. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1144. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1145. toForgeL1TxsNum,
  1146. )
  1147. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1148. }
  1149. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1150. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1151. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1152. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1153. var lastL1TxsPosition int
  1154. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1155. }
  1156. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1157. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1158. *common.WDelayerVariables, error) {
  1159. var rollup common.RollupVariables
  1160. var auction common.AuctionVariables
  1161. var wDelayer common.WDelayerVariables
  1162. if err := meddler.QueryRow(hdb.db, &rollup,
  1163. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1164. return nil, nil, nil, err
  1165. }
  1166. if err := meddler.QueryRow(hdb.db, &auction,
  1167. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1168. return nil, nil, nil, err
  1169. }
  1170. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1171. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1172. return nil, nil, nil, err
  1173. }
  1174. return &rollup, &auction, &wDelayer, nil
  1175. }
  1176. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1177. return meddler.Insert(d, "rollup_vars", rollup)
  1178. }
  1179. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1180. return meddler.Insert(d, "auction_vars", auction)
  1181. }
  1182. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1183. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1184. }
  1185. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1186. // contract variables. This initial state is stored linked to block 0, which
  1187. // always exist in the DB and is used to store initialization data that always
  1188. // exist in the smart contracts.
  1189. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1190. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1191. txn, err := hdb.db.Beginx()
  1192. if err != nil {
  1193. return err
  1194. }
  1195. defer func() {
  1196. if err != nil {
  1197. db.Rollback(txn)
  1198. }
  1199. }()
  1200. // Force EthBlockNum to be 0 because it's the block used to link data
  1201. // that belongs to the creation of the smart contracts
  1202. rollup.EthBlockNum = 0
  1203. auction.EthBlockNum = 0
  1204. wDelayer.EthBlockNum = 0
  1205. auction.DefaultSlotSetBidSlotNum = 0
  1206. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1207. return err
  1208. }
  1209. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1210. return err
  1211. }
  1212. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1213. return err
  1214. }
  1215. return txn.Commit()
  1216. }
  1217. // AddBlockSCData stores all the information of a block retrieved by the
  1218. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1219. // the pagination system of the API/DB depends on this. Within blocks, all
  1220. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1221. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1222. txn, err := hdb.db.Beginx()
  1223. if err != nil {
  1224. return err
  1225. }
  1226. defer func() {
  1227. if err != nil {
  1228. db.Rollback(txn)
  1229. }
  1230. }()
  1231. // Add block
  1232. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1233. return err
  1234. }
  1235. // Add Coordinators
  1236. if len(blockData.Auction.Coordinators) > 0 {
  1237. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1238. return err
  1239. }
  1240. }
  1241. // Add Bids
  1242. if len(blockData.Auction.Bids) > 0 {
  1243. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1244. return err
  1245. }
  1246. }
  1247. // Add Tokens
  1248. if len(blockData.Rollup.AddedTokens) > 0 {
  1249. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1250. return err
  1251. }
  1252. }
  1253. // Prepare user L1 txs to be added.
  1254. // They must be added before the batch that will forge them (which can be in the same block)
  1255. // and after the account that will be sent to (also can be in the same block).
  1256. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1257. // the batch that forges those txs is inserted
  1258. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1259. for i := range blockData.Rollup.L1UserTxs {
  1260. batchThatForgesIsInTheBlock := false
  1261. for _, batch := range blockData.Rollup.Batches {
  1262. if batch.Batch.ForgeL1TxsNum != nil &&
  1263. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1264. // Tx is forged in this block. It's guaranteed that:
  1265. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1266. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1267. batchThatForgesIsInTheBlock = true
  1268. addAtBatchNum := batch.Batch.BatchNum - 1
  1269. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1270. break
  1271. }
  1272. }
  1273. if !batchThatForgesIsInTheBlock {
  1274. // User artificial batchNum 0 to add txs that are not forge in this block
  1275. // after all the accounts of the block have been added
  1276. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1277. }
  1278. }
  1279. // Add Batches
  1280. for i := range blockData.Rollup.Batches {
  1281. batch := &blockData.Rollup.Batches[i]
  1282. // Add Batch: this will trigger an update on the DB
  1283. // that will set the batch num of forged L1 txs in this batch
  1284. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1285. return err
  1286. }
  1287. // Add accounts
  1288. if len(batch.CreatedAccounts) > 0 {
  1289. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1290. return err
  1291. }
  1292. }
  1293. // Add forged l1 coordinator Txs
  1294. if len(batch.L1CoordinatorTxs) > 0 {
  1295. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1296. return err
  1297. }
  1298. }
  1299. // Add l2 Txs
  1300. if len(batch.L2Txs) > 0 {
  1301. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1302. return err
  1303. }
  1304. }
  1305. // Add user L1 txs that will be forged in next batch
  1306. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1307. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1308. return err
  1309. }
  1310. }
  1311. // Add exit tree
  1312. if len(batch.ExitTree) > 0 {
  1313. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1314. return err
  1315. }
  1316. }
  1317. }
  1318. // Add user L1 txs that won't be forged in this block
  1319. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1320. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1321. return err
  1322. }
  1323. }
  1324. if blockData.Rollup.Vars != nil {
  1325. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1326. return err
  1327. }
  1328. }
  1329. if blockData.Auction.Vars != nil {
  1330. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1331. return err
  1332. }
  1333. }
  1334. if blockData.WDelayer.Vars != nil {
  1335. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1336. return err
  1337. }
  1338. }
  1339. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1340. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1341. return err
  1342. }
  1343. return txn.Commit()
  1344. }
  1345. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1346. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1347. coordinator := &CoordinatorAPI{}
  1348. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1349. return coordinator, err
  1350. }
  1351. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1352. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, uint64, error) {
  1353. var query string
  1354. var args []interface{}
  1355. queryStr := `SELECT coordinator.*,
  1356. COUNT(*) OVER() AS total_items
  1357. FROM coordinator `
  1358. // Apply filters
  1359. if fromItem != nil {
  1360. queryStr += "WHERE "
  1361. if order == OrderAsc {
  1362. queryStr += "coordinator.item_id >= ? "
  1363. } else {
  1364. queryStr += "coordinator.item_id <= ? "
  1365. }
  1366. args = append(args, fromItem)
  1367. }
  1368. // pagination
  1369. queryStr += "ORDER BY coordinator.item_id "
  1370. if order == OrderAsc {
  1371. queryStr += " ASC "
  1372. } else {
  1373. queryStr += " DESC "
  1374. }
  1375. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1376. query = hdb.db.Rebind(queryStr)
  1377. coordinators := []*CoordinatorAPI{}
  1378. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1379. return nil, 0, err
  1380. }
  1381. if len(coordinators) == 0 {
  1382. return nil, 0, sql.ErrNoRows
  1383. }
  1384. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1385. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1386. }
  1387. // AddAuctionVars insert auction vars into the DB
  1388. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1389. return meddler.Insert(hdb.db, "auction_vars", auctionVars)
  1390. }
  1391. // GetAuctionVars returns auction variables
  1392. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1393. auctionVars := &common.AuctionVariables{}
  1394. err := meddler.QueryRow(
  1395. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1396. )
  1397. return auctionVars, err
  1398. }
  1399. // GetAccountAPI returns an account by its index
  1400. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1401. account := &AccountAPI{}
  1402. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1403. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1404. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1405. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1406. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1407. if err != nil {
  1408. return nil, err
  1409. }
  1410. return account, nil
  1411. }
  1412. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1413. func (hdb *HistoryDB) GetAccountsAPI(
  1414. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1415. bjj *babyjub.PublicKey, fromItem, limit *uint, order string,
  1416. ) ([]AccountAPI, uint64, error) {
  1417. if ethAddr != nil && bjj != nil {
  1418. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  1419. }
  1420. var query string
  1421. var args []interface{}
  1422. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1423. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1424. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1425. COUNT(*) OVER() AS total_items
  1426. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1427. // Apply filters
  1428. nextIsAnd := false
  1429. // ethAddr filter
  1430. if ethAddr != nil {
  1431. queryStr += "WHERE account.eth_addr = ? "
  1432. nextIsAnd = true
  1433. args = append(args, ethAddr)
  1434. } else if bjj != nil { // bjj filter
  1435. queryStr += "WHERE account.bjj = ? "
  1436. nextIsAnd = true
  1437. args = append(args, bjj)
  1438. }
  1439. // tokenID filter
  1440. if len(tokenIDs) > 0 {
  1441. if nextIsAnd {
  1442. queryStr += "AND "
  1443. } else {
  1444. queryStr += "WHERE "
  1445. }
  1446. queryStr += "account.token_id IN (?) "
  1447. args = append(args, tokenIDs)
  1448. nextIsAnd = true
  1449. }
  1450. if fromItem != nil {
  1451. if nextIsAnd {
  1452. queryStr += "AND "
  1453. } else {
  1454. queryStr += "WHERE "
  1455. }
  1456. if order == OrderAsc {
  1457. queryStr += "account.item_id >= ? "
  1458. } else {
  1459. queryStr += "account.item_id <= ? "
  1460. }
  1461. args = append(args, fromItem)
  1462. }
  1463. // pagination
  1464. queryStr += "ORDER BY account.item_id "
  1465. if order == OrderAsc {
  1466. queryStr += " ASC "
  1467. } else {
  1468. queryStr += " DESC "
  1469. }
  1470. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1471. query, argsQ, err := sqlx.In(queryStr, args...)
  1472. if err != nil {
  1473. return nil, 0, err
  1474. }
  1475. query = hdb.db.Rebind(query)
  1476. accounts := []*AccountAPI{}
  1477. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1478. return nil, 0, err
  1479. }
  1480. if len(accounts) == 0 {
  1481. return nil, 0, sql.ErrNoRows
  1482. }
  1483. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1484. accounts[0].TotalItems - uint64(len(accounts)), nil
  1485. }
  1486. // GetMetrics returns metrics
  1487. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1488. metricsTotals := &MetricsTotals{}
  1489. metrics := &Metrics{}
  1490. err := meddler.QueryRow(
  1491. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1492. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1493. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1494. if err != nil {
  1495. return nil, err
  1496. }
  1497. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1498. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1499. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1500. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1501. } else {
  1502. metrics.TransactionsPerBatch = float64(0)
  1503. }
  1504. err = meddler.QueryRow(
  1505. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1506. SUM(total_fees_usd) AS total_fees FROM batch
  1507. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1508. if err != nil {
  1509. return nil, err
  1510. }
  1511. if metricsTotals.TotalBatches > 0 {
  1512. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1513. } else {
  1514. metrics.BatchFrequency = 0
  1515. }
  1516. if metricsTotals.TotalTransactions > 0 {
  1517. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1518. } else {
  1519. metrics.AvgTransactionFee = 0
  1520. }
  1521. err = meddler.QueryRow(
  1522. hdb.db, metrics,
  1523. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1524. if err != nil {
  1525. return nil, err
  1526. }
  1527. return metrics, nil
  1528. }
  1529. // GetAvgTxFee returns average transaction fee of the last 1h
  1530. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1531. metricsTotals := &MetricsTotals{}
  1532. err := meddler.QueryRow(
  1533. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1534. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1535. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1536. if err != nil {
  1537. return 0, err
  1538. }
  1539. err = meddler.QueryRow(
  1540. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1541. SUM(total_fees_usd) AS total_fees FROM batch
  1542. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1543. if err != nil {
  1544. return 0, err
  1545. }
  1546. var avgTransactionFee float64
  1547. if metricsTotals.TotalTransactions > 0 {
  1548. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1549. } else {
  1550. avgTransactionFee = 0
  1551. }
  1552. return avgTransactionFee, nil
  1553. }