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.

1153 lines
33 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. // GetBids return the bids
  317. func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
  318. var bids []*common.Bid
  319. err := meddler.QueryAll(
  320. hdb.db, &bids,
  321. "SELECT * FROM bid;",
  322. )
  323. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  324. }
  325. // AddCoordinators insert Coordinators into the DB
  326. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  327. return hdb.addCoordinators(hdb.db, coordinators)
  328. }
  329. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  330. return db.BulkInsert(
  331. d,
  332. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  333. coordinators[:],
  334. )
  335. }
  336. // AddExitTree insert Exit tree into the DB
  337. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  338. return hdb.addExitTree(hdb.db, exitTree)
  339. }
  340. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  341. return db.BulkInsert(
  342. d,
  343. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  344. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  345. exitTree[:],
  346. )
  347. }
  348. // AddToken insert a token into the DB
  349. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  350. return meddler.Insert(hdb.db, "token", token)
  351. }
  352. // AddTokens insert tokens into the DB
  353. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  354. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  355. return db.BulkInsert(
  356. d,
  357. `INSERT INTO token (
  358. token_id,
  359. eth_block_num,
  360. eth_addr,
  361. name,
  362. symbol,
  363. decimals
  364. ) VALUES %s;`,
  365. tokens[:],
  366. )
  367. }
  368. // UpdateTokenValue updates the USD value of a token
  369. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  370. _, err := hdb.db.Exec(
  371. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  372. value, tokenSymbol,
  373. )
  374. return err
  375. }
  376. // GetToken returns a token from the DB given a TokenID
  377. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  378. token := &TokenWithUSD{}
  379. err := meddler.QueryRow(
  380. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  381. )
  382. return token, err
  383. }
  384. // GetAllTokens returns all tokens from the DB
  385. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  386. var tokens []*TokenWithUSD
  387. err := meddler.QueryAll(
  388. hdb.db, &tokens,
  389. "SELECT * FROM token ORDER BY token_id;",
  390. )
  391. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
  392. }
  393. // GetTokens returns a list of tokens from the DB
  394. func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
  395. var query string
  396. var args []interface{}
  397. 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 `
  398. // Apply filters
  399. nextIsAnd := false
  400. if len(ids) > 0 {
  401. queryStr += "WHERE token_id IN (?) "
  402. nextIsAnd = true
  403. args = append(args, ids)
  404. }
  405. if len(symbols) > 0 {
  406. if nextIsAnd {
  407. queryStr += "AND "
  408. } else {
  409. queryStr += "WHERE "
  410. }
  411. queryStr += "symbol IN (?) "
  412. args = append(args, symbols)
  413. nextIsAnd = true
  414. }
  415. if name != "" {
  416. if nextIsAnd {
  417. queryStr += "AND "
  418. } else {
  419. queryStr += "WHERE "
  420. }
  421. queryStr += "name ~ ? "
  422. args = append(args, name)
  423. nextIsAnd = true
  424. }
  425. if fromItem != nil {
  426. if nextIsAnd {
  427. queryStr += "AND "
  428. } else {
  429. queryStr += "WHERE "
  430. }
  431. if order == OrderAsc {
  432. queryStr += "item_id >= ? "
  433. } else {
  434. queryStr += "item_id <= ? "
  435. }
  436. args = append(args, fromItem)
  437. }
  438. // pagination
  439. queryStr += "ORDER BY item_id "
  440. if order == OrderAsc {
  441. queryStr += "ASC "
  442. } else {
  443. queryStr += "DESC "
  444. }
  445. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  446. query, argsQ, err := sqlx.In(queryStr, args...)
  447. if err != nil {
  448. return nil, nil, err
  449. }
  450. query = hdb.db.Rebind(query)
  451. tokens := []*TokenWithUSD{}
  452. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  453. return nil, nil, err
  454. }
  455. if len(tokens) == 0 {
  456. return nil, nil, sql.ErrNoRows
  457. }
  458. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
  459. TotalItems: tokens[0].TotalItems,
  460. FirstItem: tokens[0].FirstItem,
  461. LastItem: tokens[0].LastItem,
  462. }, nil
  463. }
  464. // GetTokenSymbols returns all the token symbols from the DB
  465. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  466. var tokenSymbols []string
  467. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  468. if err != nil {
  469. return nil, err
  470. }
  471. sym := new(string)
  472. for rows.Next() {
  473. err = rows.Scan(sym)
  474. if err != nil {
  475. return nil, err
  476. }
  477. tokenSymbols = append(tokenSymbols, *sym)
  478. }
  479. return tokenSymbols, nil
  480. }
  481. // AddAccounts insert accounts into the DB
  482. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  483. return hdb.addAccounts(hdb.db, accounts)
  484. }
  485. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  486. return db.BulkInsert(
  487. d,
  488. `INSERT INTO account (
  489. idx,
  490. token_id,
  491. batch_num,
  492. bjj,
  493. eth_addr
  494. ) VALUES %s;`,
  495. accounts[:],
  496. )
  497. }
  498. // GetAccounts returns a list of accounts from the DB
  499. func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
  500. var accs []*common.Account
  501. err := meddler.QueryAll(
  502. hdb.db, &accs,
  503. "SELECT * FROM account ORDER BY idx;",
  504. )
  505. return db.SlicePtrsToSlice(accs).([]common.Account), err
  506. }
  507. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  508. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  509. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  510. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  511. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  512. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  513. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  514. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  515. txs := []txWrite{}
  516. for i := 0; i < len(l1txs); i++ {
  517. af := new(big.Float).SetInt(l1txs[i].Amount)
  518. amountFloat, _ := af.Float64()
  519. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  520. loadAmountFloat, _ := laf.Float64()
  521. txs = append(txs, txWrite{
  522. // Generic
  523. IsL1: true,
  524. TxID: l1txs[i].TxID,
  525. Type: l1txs[i].Type,
  526. Position: l1txs[i].Position,
  527. FromIdx: &l1txs[i].FromIdx,
  528. ToIdx: l1txs[i].ToIdx,
  529. Amount: l1txs[i].Amount,
  530. AmountFloat: amountFloat,
  531. TokenID: l1txs[i].TokenID,
  532. BatchNum: l1txs[i].BatchNum,
  533. EthBlockNum: l1txs[i].EthBlockNum,
  534. // L1
  535. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  536. UserOrigin: &l1txs[i].UserOrigin,
  537. FromEthAddr: &l1txs[i].FromEthAddr,
  538. FromBJJ: l1txs[i].FromBJJ,
  539. LoadAmount: l1txs[i].LoadAmount,
  540. LoadAmountFloat: &loadAmountFloat,
  541. })
  542. }
  543. return hdb.addTxs(d, txs)
  544. }
  545. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  546. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  547. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  548. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  549. txs := []txWrite{}
  550. for i := 0; i < len(l2txs); i++ {
  551. f := new(big.Float).SetInt(l2txs[i].Amount)
  552. amountFloat, _ := f.Float64()
  553. txs = append(txs, txWrite{
  554. // Generic
  555. IsL1: false,
  556. TxID: l2txs[i].TxID,
  557. Type: l2txs[i].Type,
  558. Position: l2txs[i].Position,
  559. FromIdx: &l2txs[i].FromIdx,
  560. ToIdx: l2txs[i].ToIdx,
  561. Amount: l2txs[i].Amount,
  562. AmountFloat: amountFloat,
  563. BatchNum: &l2txs[i].BatchNum,
  564. EthBlockNum: l2txs[i].EthBlockNum,
  565. // L2
  566. Fee: &l2txs[i].Fee,
  567. Nonce: &l2txs[i].Nonce,
  568. })
  569. }
  570. return hdb.addTxs(d, txs)
  571. }
  572. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  573. return db.BulkInsert(
  574. d,
  575. `INSERT INTO tx (
  576. is_l1,
  577. id,
  578. type,
  579. position,
  580. from_idx,
  581. to_idx,
  582. amount,
  583. amount_f,
  584. token_id,
  585. batch_num,
  586. eth_block_num,
  587. to_forge_l1_txs_num,
  588. user_origin,
  589. from_eth_addr,
  590. from_bjj,
  591. load_amount,
  592. load_amount_f,
  593. fee,
  594. nonce
  595. ) VALUES %s;`,
  596. txs[:],
  597. )
  598. }
  599. // // GetTxs returns a list of txs from the DB
  600. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  601. // var txs []*common.Tx
  602. // err := meddler.QueryAll(
  603. // hdb.db, &txs,
  604. // `SELECT * FROM tx
  605. // ORDER BY (batch_num, position) ASC`,
  606. // )
  607. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  608. // }
  609. // GetHistoryTx returns a tx from the DB given a TxID
  610. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  611. tx := &TxAPI{}
  612. err := meddler.QueryRow(
  613. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  614. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  615. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  616. tx.amount, tx.token_id, tx.amount_usd,
  617. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  618. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  619. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  620. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  621. token.usd_update, block.timestamp
  622. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  623. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  624. WHERE tx.id = $1;`, txID,
  625. )
  626. return tx, err
  627. }
  628. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  629. // and pagination info
  630. func (hdb *HistoryDB) GetHistoryTxs(
  631. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  632. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  633. fromItem, limit *uint, order string,
  634. ) ([]TxAPI, *db.Pagination, error) {
  635. if ethAddr != nil && bjj != nil {
  636. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  637. }
  638. var query string
  639. var args []interface{}
  640. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  641. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  642. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  643. tx.amount, tx.token_id, tx.amount_usd,
  644. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  645. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  646. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  647. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  648. token.usd_update, block.timestamp, count(*) OVER() AS total_items,
  649. MIN(tx.item_id) OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item
  650. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  651. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  652. // Apply filters
  653. nextIsAnd := false
  654. // ethAddr filter
  655. if ethAddr != nil {
  656. queryStr = `WITH acc AS
  657. (select idx from account where eth_addr = ?) ` + queryStr
  658. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  659. nextIsAnd = true
  660. args = append(args, ethAddr)
  661. } else if bjj != nil { // bjj filter
  662. queryStr = `WITH acc AS
  663. (select idx from account where bjj = ?) ` + queryStr
  664. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  665. nextIsAnd = true
  666. args = append(args, bjj)
  667. }
  668. // tokenID filter
  669. if tokenID != nil {
  670. if nextIsAnd {
  671. queryStr += "AND "
  672. } else {
  673. queryStr += "WHERE "
  674. }
  675. queryStr += "tx.token_id = ? "
  676. args = append(args, tokenID)
  677. nextIsAnd = true
  678. }
  679. // idx filter
  680. if idx != nil {
  681. if nextIsAnd {
  682. queryStr += "AND "
  683. } else {
  684. queryStr += "WHERE "
  685. }
  686. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  687. args = append(args, idx, idx)
  688. nextIsAnd = true
  689. }
  690. // batchNum filter
  691. if batchNum != nil {
  692. if nextIsAnd {
  693. queryStr += "AND "
  694. } else {
  695. queryStr += "WHERE "
  696. }
  697. queryStr += "tx.batch_num = ? "
  698. args = append(args, batchNum)
  699. nextIsAnd = true
  700. }
  701. // txType filter
  702. if txType != nil {
  703. if nextIsAnd {
  704. queryStr += "AND "
  705. } else {
  706. queryStr += "WHERE "
  707. }
  708. queryStr += "tx.type = ? "
  709. args = append(args, txType)
  710. nextIsAnd = true
  711. }
  712. if fromItem != nil {
  713. if nextIsAnd {
  714. queryStr += "AND "
  715. } else {
  716. queryStr += "WHERE "
  717. }
  718. if order == OrderAsc {
  719. queryStr += "tx.item_id >= ? "
  720. } else {
  721. queryStr += "tx.item_id <= ? "
  722. }
  723. args = append(args, fromItem)
  724. nextIsAnd = true
  725. }
  726. if nextIsAnd {
  727. queryStr += "AND "
  728. } else {
  729. queryStr += "WHERE "
  730. }
  731. queryStr += "tx.batch_num IS NOT NULL "
  732. // pagination
  733. queryStr += "ORDER BY tx.item_id "
  734. if order == OrderAsc {
  735. queryStr += " ASC "
  736. } else {
  737. queryStr += " DESC "
  738. }
  739. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  740. query = hdb.db.Rebind(queryStr)
  741. log.Debug(query)
  742. txsPtrs := []*TxAPI{}
  743. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  744. return nil, nil, err
  745. }
  746. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  747. if len(txs) == 0 {
  748. return nil, nil, sql.ErrNoRows
  749. }
  750. return txs, &db.Pagination{
  751. TotalItems: txs[0].TotalItems,
  752. FirstItem: txs[0].FirstItem,
  753. LastItem: txs[0].LastItem,
  754. }, nil
  755. }
  756. // GetAllExits returns all exit from the DB
  757. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  758. var exits []*common.ExitInfo
  759. err := meddler.QueryAll(
  760. hdb.db, &exits,
  761. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  762. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  763. exit_tree.delayed_withdrawn FROM exit_tree;`,
  764. )
  765. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  766. }
  767. // GetExit returns a exit from the DB
  768. func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
  769. exit := &HistoryExit{}
  770. err := meddler.QueryRow(
  771. hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  772. token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  773. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  774. INNER JOIN token ON account.token_id = token.token_id
  775. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  776. )
  777. return exit, err
  778. }
  779. // GetExits returns a list of exits from the DB and pagination info
  780. func (hdb *HistoryDB) GetExits(
  781. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  782. tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
  783. fromItem, limit *uint, order string,
  784. ) ([]HistoryExit, *db.Pagination, error) {
  785. if ethAddr != nil && bjj != nil {
  786. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  787. }
  788. var query string
  789. var args []interface{}
  790. queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  791. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  792. 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
  793. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  794. INNER JOIN token ON account.token_id = token.token_id `
  795. // Apply filters
  796. nextIsAnd := false
  797. // ethAddr filter
  798. if ethAddr != nil {
  799. queryStr += "WHERE account.eth_addr = ? "
  800. nextIsAnd = true
  801. args = append(args, ethAddr)
  802. } else if bjj != nil { // bjj filter
  803. queryStr += "WHERE account.bjj = ? "
  804. nextIsAnd = true
  805. args = append(args, bjj)
  806. }
  807. // tokenID filter
  808. if tokenID != nil {
  809. if nextIsAnd {
  810. queryStr += "AND "
  811. } else {
  812. queryStr += "WHERE "
  813. }
  814. queryStr += "account.token_id = ? "
  815. args = append(args, tokenID)
  816. nextIsAnd = true
  817. }
  818. // idx filter
  819. if idx != nil {
  820. if nextIsAnd {
  821. queryStr += "AND "
  822. } else {
  823. queryStr += "WHERE "
  824. }
  825. queryStr += "exit_tree.account_idx = ? "
  826. args = append(args, idx)
  827. nextIsAnd = true
  828. }
  829. // batchNum filter
  830. if batchNum != nil {
  831. if nextIsAnd {
  832. queryStr += "AND "
  833. } else {
  834. queryStr += "WHERE "
  835. }
  836. queryStr += "exit_tree.batch_num = ? "
  837. args = append(args, batchNum)
  838. nextIsAnd = true
  839. }
  840. if fromItem != nil {
  841. if nextIsAnd {
  842. queryStr += "AND "
  843. } else {
  844. queryStr += "WHERE "
  845. }
  846. if order == OrderAsc {
  847. queryStr += "exit_tree.item_id >= ? "
  848. } else {
  849. queryStr += "exit_tree.item_id <= ? "
  850. }
  851. args = append(args, fromItem)
  852. // nextIsAnd = true
  853. }
  854. // pagination
  855. queryStr += "ORDER BY exit_tree.item_id "
  856. if order == OrderAsc {
  857. queryStr += " ASC "
  858. } else {
  859. queryStr += " DESC "
  860. }
  861. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  862. query = hdb.db.Rebind(queryStr)
  863. // log.Debug(query)
  864. exits := []*HistoryExit{}
  865. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  866. return nil, nil, err
  867. }
  868. if len(exits) == 0 {
  869. return nil, nil, sql.ErrNoRows
  870. }
  871. return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
  872. TotalItems: exits[0].TotalItems,
  873. FirstItem: exits[0].FirstItem,
  874. LastItem: exits[0].LastItem,
  875. }, nil
  876. }
  877. // // GetTx returns a tx from the DB
  878. // func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  879. // tx := new(common.Tx)
  880. // return tx, meddler.QueryRow(
  881. // hdb.db, tx,
  882. // "SELECT * FROM tx WHERE id = $1;",
  883. // txID,
  884. // )
  885. // }
  886. // GetAllL1UserTxs returns all L1UserTxs from the DB
  887. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  888. var txs []*common.L1Tx
  889. err := meddler.QueryAll(
  890. hdb.db, &txs,
  891. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  892. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  893. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  894. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  895. )
  896. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  897. }
  898. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  899. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  900. var txs []*common.L1Tx
  901. err := meddler.QueryAll(
  902. hdb.db, &txs,
  903. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  904. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  905. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  906. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  907. )
  908. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  909. }
  910. // GetAllL2Txs returns all L2Txs from the DB
  911. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  912. var txs []*common.L2Tx
  913. err := meddler.QueryAll(
  914. hdb.db, &txs,
  915. `SELECT tx.id, tx.batch_num, tx.position,
  916. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  917. tx.type, tx.eth_block_num
  918. FROM tx WHERE is_l1 = FALSE;`,
  919. )
  920. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  921. }
  922. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  923. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  924. var txs []*common.L1Tx
  925. err := meddler.QueryAll(
  926. hdb.db, &txs,
  927. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  928. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  929. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  930. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  931. toForgeL1TxsNum,
  932. )
  933. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  934. }
  935. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  936. // GetLastTxsPosition for a given to_forge_l1_txs_num
  937. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  938. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  939. var lastL1TxsPosition int
  940. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  941. }
  942. // AddBlockSCData stores all the information of a block retrieved by the
  943. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  944. // the pagination system of the API/DB depends on this. Within blocks, all
  945. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  946. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  947. txn, err := hdb.db.Begin()
  948. if err != nil {
  949. return err
  950. }
  951. defer func() {
  952. if err != nil {
  953. errRollback := txn.Rollback()
  954. if errRollback != nil {
  955. log.Errorw("Rollback", "err", errRollback)
  956. }
  957. }
  958. }()
  959. // Add block
  960. err = hdb.addBlock(txn, &blockData.Block)
  961. if err != nil {
  962. return err
  963. }
  964. // Add Coordinators
  965. if len(blockData.Coordinators) > 0 {
  966. err = hdb.addCoordinators(txn, blockData.Coordinators)
  967. if err != nil {
  968. return err
  969. }
  970. }
  971. // Add Bids
  972. if len(blockData.Bids) > 0 {
  973. err = hdb.addBids(txn, blockData.Bids)
  974. if err != nil {
  975. return err
  976. }
  977. }
  978. // Add Tokens
  979. if len(blockData.AddedTokens) > 0 {
  980. err = hdb.addTokens(txn, blockData.AddedTokens)
  981. if err != nil {
  982. return err
  983. }
  984. }
  985. // Add l1 Txs
  986. if len(blockData.L1UserTxs) > 0 {
  987. err = hdb.addL1Txs(txn, blockData.L1UserTxs)
  988. if err != nil {
  989. return err
  990. }
  991. }
  992. // Add Batches
  993. for i := range blockData.Batches {
  994. batch := &blockData.Batches[i]
  995. // Add Batch: this will trigger an update on the DB
  996. // that will set the batch num of forged L1 txs in this batch
  997. err = hdb.addBatch(txn, &batch.Batch)
  998. if err != nil {
  999. return err
  1000. }
  1001. // Add unforged l1 Txs
  1002. if batch.L1Batch {
  1003. if len(batch.L1CoordinatorTxs) > 0 {
  1004. err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
  1005. if err != nil {
  1006. return err
  1007. }
  1008. }
  1009. }
  1010. // Add l2 Txs
  1011. if len(batch.L2Txs) > 0 {
  1012. err = hdb.addL2Txs(txn, batch.L2Txs)
  1013. if err != nil {
  1014. return err
  1015. }
  1016. }
  1017. // Add accounts
  1018. if len(batch.CreatedAccounts) > 0 {
  1019. err = hdb.addAccounts(txn, batch.CreatedAccounts)
  1020. if err != nil {
  1021. return err
  1022. }
  1023. }
  1024. // Add exit tree
  1025. if len(batch.ExitTree) > 0 {
  1026. err = hdb.addExitTree(txn, batch.ExitTree)
  1027. if err != nil {
  1028. return err
  1029. }
  1030. }
  1031. // TODO: INSERT CONTRACTS VARS
  1032. }
  1033. return txn.Commit()
  1034. }
  1035. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1036. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1037. coordinator := &CoordinatorAPI{}
  1038. err := meddler.QueryRow(
  1039. hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
  1040. )
  1041. return coordinator, err
  1042. }
  1043. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1044. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, *db.Pagination, error) {
  1045. var query string
  1046. var args []interface{}
  1047. queryStr := `SELECT coordinator.*,
  1048. COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
  1049. FROM coordinator `
  1050. // Apply filters
  1051. if fromItem != nil {
  1052. queryStr += "WHERE "
  1053. if order == OrderAsc {
  1054. queryStr += "coordinator.item_id >= ? "
  1055. } else {
  1056. queryStr += "coordinator.item_id <= ? "
  1057. }
  1058. args = append(args, fromItem)
  1059. }
  1060. // pagination
  1061. queryStr += "ORDER BY coordinator.item_id "
  1062. if order == OrderAsc {
  1063. queryStr += " ASC "
  1064. } else {
  1065. queryStr += " DESC "
  1066. }
  1067. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1068. query = hdb.db.Rebind(queryStr)
  1069. coordinators := []*CoordinatorAPI{}
  1070. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1071. return nil, nil, err
  1072. }
  1073. if len(coordinators) == 0 {
  1074. return nil, nil, sql.ErrNoRows
  1075. }
  1076. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI), &db.Pagination{
  1077. TotalItems: coordinators[0].TotalItems,
  1078. FirstItem: coordinators[0].FirstItem,
  1079. LastItem: coordinators[0].LastItem,
  1080. }, nil
  1081. }