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.

1646 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 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
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. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  284. // batches. If there's no batch in the DB (nil, nil) is returned.
  285. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  286. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  287. lastL1TxsNum := new(int64)
  288. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  289. }
  290. // Reorg deletes all the information that was added into the DB after the
  291. // lastValidBlock. If lastValidBlock is negative, all block information is
  292. // deleted.
  293. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  294. var err error
  295. if lastValidBlock < 0 {
  296. _, err = hdb.db.Exec("DELETE FROM block;")
  297. } else {
  298. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  299. }
  300. return err
  301. }
  302. // AddBids insert Bids into the DB
  303. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  304. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  305. // TODO: check the coordinator info
  306. return db.BulkInsert(
  307. d,
  308. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  309. bids[:],
  310. )
  311. }
  312. // GetAllBids retrieve all bids from the DB
  313. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  314. var bids []*common.Bid
  315. err := meddler.QueryAll(
  316. hdb.db, &bids,
  317. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid;`,
  318. )
  319. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  320. }
  321. // GetBestBidAPI returns the best bid in specific slot by slotNum
  322. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  323. bid := &BidAPI{}
  324. err := meddler.QueryRow(
  325. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  326. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  327. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  328. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  329. )
  330. return *bid, err
  331. }
  332. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  333. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  334. bidCoord := &common.BidCoordinator{}
  335. err := meddler.QueryRow(
  336. hdb.db, bidCoord,
  337. `SELECT (
  338. SELECT default_slot_set_bid_slot_num
  339. FROM auction_vars
  340. WHERE default_slot_set_bid_slot_num <= $1
  341. ORDER BY eth_block_num DESC LIMIT 1
  342. ),
  343. bid.slot_num, bid.bid_value, bid.bidder_addr,
  344. coordinator.forger_addr, coordinator.url
  345. FROM bid
  346. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  347. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  348. slotNum)
  349. return bidCoord, err
  350. }
  351. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  352. func (hdb *HistoryDB) GetBestBidsAPI(
  353. minSlotNum, maxSlotNum *int64,
  354. bidderAddr *ethCommon.Address,
  355. limit *uint, order string,
  356. ) ([]BidAPI, uint64, error) {
  357. var query string
  358. var args []interface{}
  359. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  360. COUNT(*) OVER() AS total_items FROM (
  361. SELECT slot_num, MAX(item_id) as maxitem
  362. FROM bid GROUP BY slot_num
  363. )
  364. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  365. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  366. INNER JOIN coordinator ON b.bidder_addr = coordinator.bidder_addr
  367. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  368. args = append(args, minSlotNum)
  369. args = append(args, maxSlotNum)
  370. // Apply filters
  371. if bidderAddr != nil {
  372. queryStr += " AND b.bidder_addr = ? "
  373. args = append(args, bidderAddr)
  374. }
  375. queryStr += " ORDER BY b.slot_num "
  376. if order == OrderAsc {
  377. queryStr += "ASC "
  378. } else {
  379. queryStr += "DESC "
  380. }
  381. if limit != nil {
  382. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  383. }
  384. query = hdb.db.Rebind(queryStr)
  385. bidPtrs := []*BidAPI{}
  386. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  387. return nil, 0, err
  388. }
  389. // log.Debug(query)
  390. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  391. if len(bids) == 0 {
  392. return nil, 0, sql.ErrNoRows
  393. }
  394. return bids, bids[0].TotalItems - uint64(len(bids)), nil
  395. }
  396. // GetBidsAPI return the bids applying the given filters
  397. func (hdb *HistoryDB) GetBidsAPI(
  398. slotNum *int64, forgerAddr *ethCommon.Address,
  399. fromItem, limit *uint, order string,
  400. ) ([]BidAPI, uint64, error) {
  401. var query string
  402. var args []interface{}
  403. queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  404. COUNT(*) OVER() AS total_items
  405. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  406. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
  407. // Apply filters
  408. nextIsAnd := false
  409. // slotNum filter
  410. if slotNum != nil {
  411. if nextIsAnd {
  412. queryStr += "AND "
  413. } else {
  414. queryStr += "WHERE "
  415. }
  416. queryStr += "bid.slot_num = ? "
  417. args = append(args, slotNum)
  418. nextIsAnd = true
  419. }
  420. // slotNum filter
  421. if forgerAddr != nil {
  422. if nextIsAnd {
  423. queryStr += "AND "
  424. } else {
  425. queryStr += "WHERE "
  426. }
  427. queryStr += "bid.bidder_addr = ? "
  428. args = append(args, forgerAddr)
  429. nextIsAnd = true
  430. }
  431. if fromItem != nil {
  432. if nextIsAnd {
  433. queryStr += "AND "
  434. } else {
  435. queryStr += "WHERE "
  436. }
  437. if order == OrderAsc {
  438. queryStr += "bid.item_id >= ? "
  439. } else {
  440. queryStr += "bid.item_id <= ? "
  441. }
  442. args = append(args, fromItem)
  443. }
  444. // pagination
  445. queryStr += "ORDER BY bid.item_id "
  446. if order == OrderAsc {
  447. queryStr += "ASC "
  448. } else {
  449. queryStr += "DESC "
  450. }
  451. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  452. query, argsQ, err := sqlx.In(queryStr, args...)
  453. if err != nil {
  454. return nil, 0, err
  455. }
  456. query = hdb.db.Rebind(query)
  457. bids := []*BidAPI{}
  458. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  459. return nil, 0, err
  460. }
  461. if len(bids) == 0 {
  462. return nil, 0, sql.ErrNoRows
  463. }
  464. return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
  465. }
  466. // AddCoordinators insert Coordinators into the DB
  467. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  468. return hdb.addCoordinators(hdb.db, coordinators)
  469. }
  470. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  471. return db.BulkInsert(
  472. d,
  473. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  474. coordinators[:],
  475. )
  476. }
  477. // AddExitTree insert Exit tree into the DB
  478. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  479. return hdb.addExitTree(hdb.db, exitTree)
  480. }
  481. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  482. return db.BulkInsert(
  483. d,
  484. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  485. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  486. exitTree[:],
  487. )
  488. }
  489. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  490. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  491. type withdrawal struct {
  492. BatchNum int64 `db:"batch_num"`
  493. AccountIdx int64 `db:"account_idx"`
  494. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  495. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  496. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  497. Owner *ethCommon.Address `db:"owner"`
  498. Token *ethCommon.Address `db:"token"`
  499. }
  500. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  501. for i := range rollupWithdrawals {
  502. info := &rollupWithdrawals[i]
  503. withdrawals[i] = withdrawal{
  504. BatchNum: int64(info.NumExitRoot),
  505. AccountIdx: int64(info.Idx),
  506. }
  507. if info.InstantWithdraw {
  508. withdrawals[i].InstantWithdrawn = &blockNum
  509. } else {
  510. withdrawals[i].DelayedWithdrawRequest = &blockNum
  511. withdrawals[i].Owner = &info.Owner
  512. withdrawals[i].Token = &info.Token
  513. }
  514. }
  515. for i := range wDelayerWithdrawals {
  516. info := &wDelayerWithdrawals[i]
  517. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  518. DelayedWithdrawn: &blockNum,
  519. Owner: &info.Owner,
  520. Token: &info.Token,
  521. }
  522. }
  523. // In VALUES we set an initial row of NULLs to set the types of each
  524. // variable passed as argument
  525. query := `
  526. UPDATE exit_tree e SET
  527. instant_withdrawn = d.instant_withdrawn,
  528. delayed_withdraw_request = CASE
  529. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  530. ELSE d.delayed_withdraw_request
  531. END,
  532. delayed_withdrawn = d.delayed_withdrawn,
  533. owner = d.owner,
  534. token = d.token
  535. FROM (VALUES
  536. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  537. (:batch_num,
  538. :account_idx,
  539. :instant_withdrawn,
  540. :delayed_withdraw_request,
  541. :delayed_withdrawn,
  542. :owner,
  543. :token)
  544. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  545. WHERE
  546. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  547. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token)
  548. `
  549. if len(withdrawals) > 0 {
  550. if _, err := sqlx.NamedQuery(d, query, withdrawals); err != nil {
  551. return err
  552. }
  553. }
  554. return nil
  555. }
  556. // AddToken insert a token into the DB
  557. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  558. return meddler.Insert(hdb.db, "token", token)
  559. }
  560. // AddTokens insert tokens into the DB
  561. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  562. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  563. return db.BulkInsert(
  564. d,
  565. `INSERT INTO token (
  566. token_id,
  567. eth_block_num,
  568. eth_addr,
  569. name,
  570. symbol,
  571. decimals
  572. ) VALUES %s;`,
  573. tokens[:],
  574. )
  575. }
  576. // UpdateTokenValue updates the USD value of a token
  577. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  578. _, err := hdb.db.Exec(
  579. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  580. value, tokenSymbol,
  581. )
  582. return err
  583. }
  584. // GetToken returns a token from the DB given a TokenID
  585. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  586. token := &TokenWithUSD{}
  587. err := meddler.QueryRow(
  588. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  589. )
  590. return token, err
  591. }
  592. // GetAllTokens returns all tokens from the DB
  593. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  594. var tokens []*TokenWithUSD
  595. err := meddler.QueryAll(
  596. hdb.db, &tokens,
  597. "SELECT * FROM token ORDER BY token_id;",
  598. )
  599. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
  600. }
  601. // GetTokens returns a list of tokens from the DB
  602. func (hdb *HistoryDB) GetTokens(
  603. ids []common.TokenID, symbols []string, name string, fromItem,
  604. limit *uint, order string,
  605. ) ([]TokenWithUSD, uint64, error) {
  606. var query string
  607. var args []interface{}
  608. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  609. // Apply filters
  610. nextIsAnd := false
  611. if len(ids) > 0 {
  612. queryStr += "WHERE token_id IN (?) "
  613. nextIsAnd = true
  614. args = append(args, ids)
  615. }
  616. if len(symbols) > 0 {
  617. if nextIsAnd {
  618. queryStr += "AND "
  619. } else {
  620. queryStr += "WHERE "
  621. }
  622. queryStr += "symbol IN (?) "
  623. args = append(args, symbols)
  624. nextIsAnd = true
  625. }
  626. if name != "" {
  627. if nextIsAnd {
  628. queryStr += "AND "
  629. } else {
  630. queryStr += "WHERE "
  631. }
  632. queryStr += "name ~ ? "
  633. args = append(args, name)
  634. nextIsAnd = true
  635. }
  636. if fromItem != nil {
  637. if nextIsAnd {
  638. queryStr += "AND "
  639. } else {
  640. queryStr += "WHERE "
  641. }
  642. if order == OrderAsc {
  643. queryStr += "item_id >= ? "
  644. } else {
  645. queryStr += "item_id <= ? "
  646. }
  647. args = append(args, fromItem)
  648. }
  649. // pagination
  650. queryStr += "ORDER BY item_id "
  651. if order == OrderAsc {
  652. queryStr += "ASC "
  653. } else {
  654. queryStr += "DESC "
  655. }
  656. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  657. query, argsQ, err := sqlx.In(queryStr, args...)
  658. if err != nil {
  659. return nil, 0, err
  660. }
  661. query = hdb.db.Rebind(query)
  662. tokens := []*TokenWithUSD{}
  663. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  664. return nil, 0, err
  665. }
  666. if len(tokens) == 0 {
  667. return nil, 0, sql.ErrNoRows
  668. }
  669. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  670. }
  671. // GetTokenSymbols returns all the token symbols from the DB
  672. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  673. var tokenSymbols []string
  674. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  675. if err != nil {
  676. return nil, err
  677. }
  678. sym := new(string)
  679. for rows.Next() {
  680. err = rows.Scan(sym)
  681. if err != nil {
  682. return nil, err
  683. }
  684. tokenSymbols = append(tokenSymbols, *sym)
  685. }
  686. return tokenSymbols, nil
  687. }
  688. // AddAccounts insert accounts into the DB
  689. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  690. return hdb.addAccounts(hdb.db, accounts)
  691. }
  692. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  693. return db.BulkInsert(
  694. d,
  695. `INSERT INTO account (
  696. idx,
  697. token_id,
  698. batch_num,
  699. bjj,
  700. eth_addr
  701. ) VALUES %s;`,
  702. accounts[:],
  703. )
  704. }
  705. // GetAllAccounts returns a list of accounts from the DB
  706. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  707. var accs []*common.Account
  708. err := meddler.QueryAll(
  709. hdb.db, &accs,
  710. "SELECT * FROM account ORDER BY idx;",
  711. )
  712. return db.SlicePtrsToSlice(accs).([]common.Account), err
  713. }
  714. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  715. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  716. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  717. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  718. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  719. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  720. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  721. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  722. txs := []txWrite{}
  723. for i := 0; i < len(l1txs); i++ {
  724. af := new(big.Float).SetInt(l1txs[i].Amount)
  725. amountFloat, _ := af.Float64()
  726. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  727. loadAmountFloat, _ := laf.Float64()
  728. txs = append(txs, txWrite{
  729. // Generic
  730. IsL1: true,
  731. TxID: l1txs[i].TxID,
  732. Type: l1txs[i].Type,
  733. Position: l1txs[i].Position,
  734. FromIdx: &l1txs[i].FromIdx,
  735. ToIdx: l1txs[i].ToIdx,
  736. Amount: l1txs[i].Amount,
  737. AmountFloat: amountFloat,
  738. TokenID: l1txs[i].TokenID,
  739. BatchNum: l1txs[i].BatchNum,
  740. EthBlockNum: l1txs[i].EthBlockNum,
  741. // L1
  742. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  743. UserOrigin: &l1txs[i].UserOrigin,
  744. FromEthAddr: &l1txs[i].FromEthAddr,
  745. FromBJJ: l1txs[i].FromBJJ,
  746. LoadAmount: l1txs[i].LoadAmount,
  747. LoadAmountFloat: &loadAmountFloat,
  748. })
  749. }
  750. return hdb.addTxs(d, txs)
  751. }
  752. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  753. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  754. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  755. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  756. txs := []txWrite{}
  757. for i := 0; i < len(l2txs); i++ {
  758. f := new(big.Float).SetInt(l2txs[i].Amount)
  759. amountFloat, _ := f.Float64()
  760. txs = append(txs, txWrite{
  761. // Generic
  762. IsL1: false,
  763. TxID: l2txs[i].TxID,
  764. Type: l2txs[i].Type,
  765. Position: l2txs[i].Position,
  766. FromIdx: &l2txs[i].FromIdx,
  767. ToIdx: l2txs[i].ToIdx,
  768. Amount: l2txs[i].Amount,
  769. AmountFloat: amountFloat,
  770. BatchNum: &l2txs[i].BatchNum,
  771. EthBlockNum: l2txs[i].EthBlockNum,
  772. // L2
  773. Fee: &l2txs[i].Fee,
  774. Nonce: &l2txs[i].Nonce,
  775. })
  776. }
  777. return hdb.addTxs(d, txs)
  778. }
  779. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  780. return db.BulkInsert(
  781. d,
  782. `INSERT INTO tx (
  783. is_l1,
  784. id,
  785. type,
  786. position,
  787. from_idx,
  788. to_idx,
  789. amount,
  790. amount_f,
  791. token_id,
  792. batch_num,
  793. eth_block_num,
  794. to_forge_l1_txs_num,
  795. user_origin,
  796. from_eth_addr,
  797. from_bjj,
  798. load_amount,
  799. load_amount_f,
  800. fee,
  801. nonce
  802. ) VALUES %s;`,
  803. txs[:],
  804. )
  805. }
  806. // // GetTxs returns a list of txs from the DB
  807. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  808. // var txs []*common.Tx
  809. // err := meddler.QueryAll(
  810. // hdb.db, &txs,
  811. // `SELECT * FROM tx
  812. // ORDER BY (batch_num, position) ASC`,
  813. // )
  814. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  815. // }
  816. // GetHistoryTx returns a tx from the DB given a TxID
  817. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  818. tx := &TxAPI{}
  819. err := meddler.QueryRow(
  820. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  821. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  822. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  823. tx.amount, tx.token_id, tx.amount_usd,
  824. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  825. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  826. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  827. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  828. token.usd_update, block.timestamp
  829. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  830. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  831. WHERE tx.id = $1;`, txID,
  832. )
  833. return tx, err
  834. }
  835. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  836. // and pagination info
  837. func (hdb *HistoryDB) GetHistoryTxs(
  838. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  839. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  840. fromItem, limit *uint, order string,
  841. ) ([]TxAPI, uint64, error) {
  842. if ethAddr != nil && bjj != nil {
  843. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  844. }
  845. var query string
  846. var args []interface{}
  847. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  848. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  849. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  850. tx.amount, tx.token_id, tx.amount_usd,
  851. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  852. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  853. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  854. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  855. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  856. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  857. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  858. // Apply filters
  859. nextIsAnd := false
  860. // ethAddr filter
  861. if ethAddr != nil {
  862. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  863. nextIsAnd = true
  864. args = append(args, ethAddr, ethAddr)
  865. } else if bjj != nil { // bjj filter
  866. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  867. nextIsAnd = true
  868. args = append(args, bjj, bjj)
  869. }
  870. // tokenID filter
  871. if tokenID != nil {
  872. if nextIsAnd {
  873. queryStr += "AND "
  874. } else {
  875. queryStr += "WHERE "
  876. }
  877. queryStr += "tx.token_id = ? "
  878. args = append(args, tokenID)
  879. nextIsAnd = true
  880. }
  881. // idx filter
  882. if idx != nil {
  883. if nextIsAnd {
  884. queryStr += "AND "
  885. } else {
  886. queryStr += "WHERE "
  887. }
  888. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  889. args = append(args, idx, idx)
  890. nextIsAnd = true
  891. }
  892. // batchNum filter
  893. if batchNum != nil {
  894. if nextIsAnd {
  895. queryStr += "AND "
  896. } else {
  897. queryStr += "WHERE "
  898. }
  899. queryStr += "tx.batch_num = ? "
  900. args = append(args, batchNum)
  901. nextIsAnd = true
  902. }
  903. // txType filter
  904. if txType != nil {
  905. if nextIsAnd {
  906. queryStr += "AND "
  907. } else {
  908. queryStr += "WHERE "
  909. }
  910. queryStr += "tx.type = ? "
  911. args = append(args, txType)
  912. nextIsAnd = true
  913. }
  914. if fromItem != nil {
  915. if nextIsAnd {
  916. queryStr += "AND "
  917. } else {
  918. queryStr += "WHERE "
  919. }
  920. if order == OrderAsc {
  921. queryStr += "tx.item_id >= ? "
  922. } else {
  923. queryStr += "tx.item_id <= ? "
  924. }
  925. args = append(args, fromItem)
  926. nextIsAnd = true
  927. }
  928. if nextIsAnd {
  929. queryStr += "AND "
  930. } else {
  931. queryStr += "WHERE "
  932. }
  933. queryStr += "tx.batch_num IS NOT NULL "
  934. // pagination
  935. queryStr += "ORDER BY tx.item_id "
  936. if order == OrderAsc {
  937. queryStr += " ASC "
  938. } else {
  939. queryStr += " DESC "
  940. }
  941. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  942. query = hdb.db.Rebind(queryStr)
  943. // log.Debug(query)
  944. txsPtrs := []*TxAPI{}
  945. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  946. return nil, 0, err
  947. }
  948. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  949. if len(txs) == 0 {
  950. return nil, 0, sql.ErrNoRows
  951. }
  952. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  953. }
  954. // GetAllExits returns all exit from the DB
  955. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  956. var exits []*common.ExitInfo
  957. err := meddler.QueryAll(
  958. hdb.db, &exits,
  959. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  960. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  961. exit_tree.delayed_withdrawn FROM exit_tree;`,
  962. )
  963. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  964. }
  965. // GetExitAPI returns a exit from the DB
  966. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  967. exit := &ExitAPI{}
  968. err := meddler.QueryRow(
  969. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  970. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  971. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  972. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  973. token.token_id, token.item_id AS token_item_id,
  974. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  975. token.decimals, token.usd, token.usd_update
  976. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  977. INNER JOIN token ON account.token_id = token.token_id
  978. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  979. )
  980. return exit, err
  981. }
  982. // GetExitsAPI returns a list of exits from the DB and pagination info
  983. func (hdb *HistoryDB) GetExitsAPI(
  984. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  985. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  986. fromItem, limit *uint, order string,
  987. ) ([]ExitAPI, uint64, error) {
  988. if ethAddr != nil && bjj != nil {
  989. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  990. }
  991. var query string
  992. var args []interface{}
  993. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  994. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  995. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  996. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  997. token.token_id, token.item_id AS token_item_id,
  998. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  999. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1000. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1001. INNER JOIN token ON account.token_id = token.token_id `
  1002. // Apply filters
  1003. nextIsAnd := false
  1004. // ethAddr filter
  1005. if ethAddr != nil {
  1006. queryStr += "WHERE account.eth_addr = ? "
  1007. nextIsAnd = true
  1008. args = append(args, ethAddr)
  1009. } else if bjj != nil { // bjj filter
  1010. queryStr += "WHERE account.bjj = ? "
  1011. nextIsAnd = true
  1012. args = append(args, bjj)
  1013. }
  1014. // tokenID filter
  1015. if tokenID != nil {
  1016. if nextIsAnd {
  1017. queryStr += "AND "
  1018. } else {
  1019. queryStr += "WHERE "
  1020. }
  1021. queryStr += "account.token_id = ? "
  1022. args = append(args, tokenID)
  1023. nextIsAnd = true
  1024. }
  1025. // idx filter
  1026. if idx != nil {
  1027. if nextIsAnd {
  1028. queryStr += "AND "
  1029. } else {
  1030. queryStr += "WHERE "
  1031. }
  1032. queryStr += "exit_tree.account_idx = ? "
  1033. args = append(args, idx)
  1034. nextIsAnd = true
  1035. }
  1036. // batchNum filter
  1037. if batchNum != nil {
  1038. if nextIsAnd {
  1039. queryStr += "AND "
  1040. } else {
  1041. queryStr += "WHERE "
  1042. }
  1043. queryStr += "exit_tree.batch_num = ? "
  1044. args = append(args, batchNum)
  1045. nextIsAnd = true
  1046. }
  1047. // onlyPendingWithdraws
  1048. if onlyPendingWithdraws != nil {
  1049. if *onlyPendingWithdraws {
  1050. if nextIsAnd {
  1051. queryStr += "AND "
  1052. } else {
  1053. queryStr += "WHERE "
  1054. }
  1055. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1056. nextIsAnd = true
  1057. }
  1058. }
  1059. if fromItem != nil {
  1060. if nextIsAnd {
  1061. queryStr += "AND "
  1062. } else {
  1063. queryStr += "WHERE "
  1064. }
  1065. if order == OrderAsc {
  1066. queryStr += "exit_tree.item_id >= ? "
  1067. } else {
  1068. queryStr += "exit_tree.item_id <= ? "
  1069. }
  1070. args = append(args, fromItem)
  1071. // nextIsAnd = true
  1072. }
  1073. // pagination
  1074. queryStr += "ORDER BY exit_tree.item_id "
  1075. if order == OrderAsc {
  1076. queryStr += " ASC "
  1077. } else {
  1078. queryStr += " DESC "
  1079. }
  1080. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1081. query = hdb.db.Rebind(queryStr)
  1082. // log.Debug(query)
  1083. exits := []*ExitAPI{}
  1084. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1085. return nil, 0, err
  1086. }
  1087. if len(exits) == 0 {
  1088. return nil, 0, sql.ErrNoRows
  1089. }
  1090. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1091. }
  1092. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1093. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1094. var txs []*common.L1Tx
  1095. err := meddler.QueryAll(
  1096. hdb.db, &txs,
  1097. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1098. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1099. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1100. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  1101. )
  1102. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1103. }
  1104. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1105. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]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, tx.amount,
  1111. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1112. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1113. )
  1114. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1115. }
  1116. // GetAllL2Txs returns all L2Txs from the DB
  1117. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1118. var txs []*common.L2Tx
  1119. err := meddler.QueryAll(
  1120. hdb.db, &txs,
  1121. `SELECT tx.id, tx.batch_num, tx.position,
  1122. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1123. tx.type, tx.eth_block_num
  1124. FROM tx WHERE is_l1 = FALSE;`,
  1125. )
  1126. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1127. }
  1128. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1129. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1130. var txs []*common.L1Tx
  1131. err := meddler.QueryAll(
  1132. hdb.db, &txs,
  1133. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1134. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1135. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1136. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1137. toForgeL1TxsNum,
  1138. )
  1139. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1140. }
  1141. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1142. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1143. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1144. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1145. var lastL1TxsPosition int
  1146. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1147. }
  1148. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1149. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1150. *common.WDelayerVariables, error) {
  1151. var rollup common.RollupVariables
  1152. var auction common.AuctionVariables
  1153. var wDelayer common.WDelayerVariables
  1154. if err := meddler.QueryRow(hdb.db, &rollup,
  1155. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1156. return nil, nil, nil, err
  1157. }
  1158. if err := meddler.QueryRow(hdb.db, &auction,
  1159. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1160. return nil, nil, nil, err
  1161. }
  1162. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1163. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1164. return nil, nil, nil, err
  1165. }
  1166. return &rollup, &auction, &wDelayer, nil
  1167. }
  1168. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1169. return meddler.Insert(d, "rollup_vars", rollup)
  1170. }
  1171. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1172. return meddler.Insert(d, "auction_vars", auction)
  1173. }
  1174. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1175. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1176. }
  1177. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1178. // contract variables. This initial state is stored linked to block 0, which
  1179. // always exist in the DB and is used to store initialization data that always
  1180. // exist in the smart contracts.
  1181. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1182. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1183. txn, err := hdb.db.Beginx()
  1184. if err != nil {
  1185. return err
  1186. }
  1187. defer func() {
  1188. if err != nil {
  1189. db.Rollback(txn)
  1190. }
  1191. }()
  1192. // Force EthBlockNum to be 0 because it's the block used to link data
  1193. // that belongs to the creation of the smart contracts
  1194. rollup.EthBlockNum = 0
  1195. auction.EthBlockNum = 0
  1196. wDelayer.EthBlockNum = 0
  1197. auction.DefaultSlotSetBidSlotNum = 0
  1198. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1199. return err
  1200. }
  1201. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1202. return err
  1203. }
  1204. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1205. return err
  1206. }
  1207. return txn.Commit()
  1208. }
  1209. // AddBlockSCData stores all the information of a block retrieved by the
  1210. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1211. // the pagination system of the API/DB depends on this. Within blocks, all
  1212. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1213. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1214. txn, err := hdb.db.Beginx()
  1215. if err != nil {
  1216. return err
  1217. }
  1218. defer func() {
  1219. if err != nil {
  1220. db.Rollback(txn)
  1221. }
  1222. }()
  1223. // Add block
  1224. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1225. return err
  1226. }
  1227. // Add Coordinators
  1228. if len(blockData.Auction.Coordinators) > 0 {
  1229. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1230. return err
  1231. }
  1232. }
  1233. // Add Bids
  1234. if len(blockData.Auction.Bids) > 0 {
  1235. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1236. return err
  1237. }
  1238. }
  1239. // Add Tokens
  1240. if len(blockData.Rollup.AddedTokens) > 0 {
  1241. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1242. return err
  1243. }
  1244. }
  1245. // Prepare user L1 txs to be added.
  1246. // They must be added before the batch that will forge them (which can be in the same block)
  1247. // and after the account that will be sent to (also can be in the same block).
  1248. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1249. // the batch that forges those txs is inserted
  1250. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1251. for i := range blockData.Rollup.L1UserTxs {
  1252. batchThatForgesIsInTheBlock := false
  1253. for _, batch := range blockData.Rollup.Batches {
  1254. if batch.Batch.ForgeL1TxsNum != nil &&
  1255. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1256. // Tx is forged in this block. It's guaranteed that:
  1257. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1258. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1259. batchThatForgesIsInTheBlock = true
  1260. addAtBatchNum := batch.Batch.BatchNum - 1
  1261. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1262. break
  1263. }
  1264. }
  1265. if !batchThatForgesIsInTheBlock {
  1266. // User artificial batchNum 0 to add txs that are not forge in this block
  1267. // after all the accounts of the block have been added
  1268. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1269. }
  1270. }
  1271. // Add Batches
  1272. for i := range blockData.Rollup.Batches {
  1273. batch := &blockData.Rollup.Batches[i]
  1274. // Add Batch: this will trigger an update on the DB
  1275. // that will set the batch num of forged L1 txs in this batch
  1276. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1277. return err
  1278. }
  1279. // Add accounts
  1280. if len(batch.CreatedAccounts) > 0 {
  1281. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1282. return err
  1283. }
  1284. }
  1285. // Add forged l1 coordinator Txs
  1286. if len(batch.L1CoordinatorTxs) > 0 {
  1287. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1288. return err
  1289. }
  1290. }
  1291. // Add l2 Txs
  1292. if len(batch.L2Txs) > 0 {
  1293. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1294. return err
  1295. }
  1296. }
  1297. // Add user L1 txs that will be forged in next batch
  1298. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1299. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1300. return err
  1301. }
  1302. }
  1303. // Add exit tree
  1304. if len(batch.ExitTree) > 0 {
  1305. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1306. return err
  1307. }
  1308. }
  1309. }
  1310. // Add user L1 txs that won't be forged in this block
  1311. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1312. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1313. return err
  1314. }
  1315. }
  1316. if blockData.Rollup.Vars != nil {
  1317. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1318. return err
  1319. }
  1320. }
  1321. if blockData.Auction.Vars != nil {
  1322. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1323. return err
  1324. }
  1325. }
  1326. if blockData.WDelayer.Vars != nil {
  1327. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1328. return err
  1329. }
  1330. }
  1331. if err := hdb.updateExitTree(txn, blockData.Block.EthBlockNum,
  1332. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1333. return err
  1334. }
  1335. return txn.Commit()
  1336. }
  1337. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1338. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1339. coordinator := &CoordinatorAPI{}
  1340. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1341. return coordinator, err
  1342. }
  1343. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1344. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, uint64, error) {
  1345. var query string
  1346. var args []interface{}
  1347. queryStr := `SELECT coordinator.*,
  1348. COUNT(*) OVER() AS total_items
  1349. FROM coordinator `
  1350. // Apply filters
  1351. if fromItem != nil {
  1352. queryStr += "WHERE "
  1353. if order == OrderAsc {
  1354. queryStr += "coordinator.item_id >= ? "
  1355. } else {
  1356. queryStr += "coordinator.item_id <= ? "
  1357. }
  1358. args = append(args, fromItem)
  1359. }
  1360. // pagination
  1361. queryStr += "ORDER BY coordinator.item_id "
  1362. if order == OrderAsc {
  1363. queryStr += " ASC "
  1364. } else {
  1365. queryStr += " DESC "
  1366. }
  1367. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1368. query = hdb.db.Rebind(queryStr)
  1369. coordinators := []*CoordinatorAPI{}
  1370. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1371. return nil, 0, err
  1372. }
  1373. if len(coordinators) == 0 {
  1374. return nil, 0, sql.ErrNoRows
  1375. }
  1376. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1377. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1378. }
  1379. // AddAuctionVars insert auction vars into the DB
  1380. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1381. return meddler.Insert(hdb.db, "auction_vars", auctionVars)
  1382. }
  1383. // GetAuctionVars returns auction variables
  1384. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1385. auctionVars := &common.AuctionVariables{}
  1386. err := meddler.QueryRow(
  1387. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1388. )
  1389. return auctionVars, err
  1390. }
  1391. // GetAccountAPI returns an account by its index
  1392. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1393. account := &AccountAPI{}
  1394. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1395. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1396. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1397. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1398. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1399. if err != nil {
  1400. return nil, err
  1401. }
  1402. return account, nil
  1403. }
  1404. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1405. func (hdb *HistoryDB) GetAccountsAPI(
  1406. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1407. bjj *babyjub.PublicKey, fromItem, limit *uint, order string,
  1408. ) ([]AccountAPI, uint64, error) {
  1409. if ethAddr != nil && bjj != nil {
  1410. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  1411. }
  1412. var query string
  1413. var args []interface{}
  1414. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1415. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1416. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1417. COUNT(*) OVER() AS total_items
  1418. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1419. // Apply filters
  1420. nextIsAnd := false
  1421. // ethAddr filter
  1422. if ethAddr != nil {
  1423. queryStr += "WHERE account.eth_addr = ? "
  1424. nextIsAnd = true
  1425. args = append(args, ethAddr)
  1426. } else if bjj != nil { // bjj filter
  1427. queryStr += "WHERE account.bjj = ? "
  1428. nextIsAnd = true
  1429. args = append(args, bjj)
  1430. }
  1431. // tokenID filter
  1432. if len(tokenIDs) > 0 {
  1433. if nextIsAnd {
  1434. queryStr += "AND "
  1435. } else {
  1436. queryStr += "WHERE "
  1437. }
  1438. queryStr += "account.token_id IN (?) "
  1439. args = append(args, tokenIDs)
  1440. nextIsAnd = true
  1441. }
  1442. if fromItem != nil {
  1443. if nextIsAnd {
  1444. queryStr += "AND "
  1445. } else {
  1446. queryStr += "WHERE "
  1447. }
  1448. if order == OrderAsc {
  1449. queryStr += "account.item_id >= ? "
  1450. } else {
  1451. queryStr += "account.item_id <= ? "
  1452. }
  1453. args = append(args, fromItem)
  1454. }
  1455. // pagination
  1456. queryStr += "ORDER BY account.item_id "
  1457. if order == OrderAsc {
  1458. queryStr += " ASC "
  1459. } else {
  1460. queryStr += " DESC "
  1461. }
  1462. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1463. query, argsQ, err := sqlx.In(queryStr, args...)
  1464. if err != nil {
  1465. return nil, 0, err
  1466. }
  1467. query = hdb.db.Rebind(query)
  1468. accounts := []*AccountAPI{}
  1469. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1470. return nil, 0, err
  1471. }
  1472. if len(accounts) == 0 {
  1473. return nil, 0, sql.ErrNoRows
  1474. }
  1475. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1476. accounts[0].TotalItems - uint64(len(accounts)), nil
  1477. }
  1478. // GetMetrics returns metrics
  1479. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1480. metricsTotals := &MetricsTotals{}
  1481. metrics := &Metrics{}
  1482. err := meddler.QueryRow(
  1483. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1484. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1485. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1486. if err != nil {
  1487. return nil, err
  1488. }
  1489. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1490. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1491. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1492. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1493. } else {
  1494. metrics.TransactionsPerBatch = float64(0)
  1495. }
  1496. err = meddler.QueryRow(
  1497. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1498. SUM(total_fees_usd) AS total_fees FROM batch
  1499. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1500. if err != nil {
  1501. return nil, err
  1502. }
  1503. if metricsTotals.TotalBatches > 0 {
  1504. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1505. } else {
  1506. metrics.BatchFrequency = 0
  1507. }
  1508. if metricsTotals.TotalTransactions > 0 {
  1509. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1510. } else {
  1511. metrics.AvgTransactionFee = 0
  1512. }
  1513. err = meddler.QueryRow(
  1514. hdb.db, metrics,
  1515. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1516. if err != nil {
  1517. return nil, err
  1518. }
  1519. return metrics, nil
  1520. }
  1521. // GetAvgTxFee returns average transaction fee of the last 1h
  1522. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1523. metricsTotals := &MetricsTotals{}
  1524. err := meddler.QueryRow(
  1525. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1526. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1527. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1528. if err != nil {
  1529. return 0, err
  1530. }
  1531. err = meddler.QueryRow(
  1532. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1533. SUM(total_fees_usd) AS total_fees FROM batch
  1534. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1535. if err != nil {
  1536. return 0, err
  1537. }
  1538. var avgTransactionFee float64
  1539. if metricsTotals.TotalTransactions > 0 {
  1540. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1541. } else {
  1542. avgTransactionFee = 0
  1543. }
  1544. return avgTransactionFee, nil
  1545. }