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.

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