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.

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