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.

1520 lines
45 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
3 years ago
3 years ago
  1. package historydb
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "math/big"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/db"
  11. "github.com/iden3/go-iden3-crypto/babyjub"
  12. "github.com/jmoiron/sqlx"
  13. //nolint:errcheck // driver for postgres DB
  14. _ "github.com/lib/pq"
  15. "github.com/russross/meddler"
  16. )
  17. const (
  18. // OrderAsc indicates ascending order when using pagination
  19. OrderAsc = "ASC"
  20. // OrderDesc indicates descending order when using pagination
  21. OrderDesc = "DESC"
  22. )
  23. // TODO(Edu): Document here how HistoryDB is kept consistent
  24. // HistoryDB persist the historic of the rollup
  25. type HistoryDB struct {
  26. db *sqlx.DB
  27. }
  28. // NewHistoryDB initialize the DB
  29. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  30. return &HistoryDB{db: db}
  31. }
  32. // DB returns a pointer to the L2DB.db. This method should be used only for
  33. // internal testing purposes.
  34. func (hdb *HistoryDB) DB() *sqlx.DB {
  35. return hdb.db
  36. }
  37. // AddBlock insert a block into the DB
  38. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  39. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  40. return meddler.Insert(d, "block", block)
  41. }
  42. // AddBlocks inserts blocks into the DB
  43. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  44. return hdb.addBlocks(hdb.db, blocks)
  45. }
  46. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  47. return db.BulkInsert(
  48. d,
  49. `INSERT INTO block (
  50. eth_block_num,
  51. timestamp,
  52. hash
  53. ) VALUES %s;`,
  54. blocks[:],
  55. )
  56. }
  57. // GetBlock retrieve a block from the DB, given a block number
  58. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  59. block := &common.Block{}
  60. err := meddler.QueryRow(
  61. hdb.db, block,
  62. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  63. )
  64. return block, err
  65. }
  66. // GetAllBlocks retrieve all blocks from the DB
  67. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  68. var blocks []*common.Block
  69. err := meddler.QueryAll(
  70. hdb.db, &blocks,
  71. "SELECT * FROM block;",
  72. )
  73. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  74. }
  75. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  76. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  77. var blocks []*common.Block
  78. err := meddler.QueryAll(
  79. hdb.db, &blocks,
  80. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  81. from, to,
  82. )
  83. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  84. }
  85. // GetLastBlock retrieve the block with the highest block number from the DB
  86. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  87. block := &common.Block{}
  88. err := meddler.QueryRow(
  89. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  90. )
  91. return block, err
  92. }
  93. // AddBatch insert a Batch into the DB
  94. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  95. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  96. // Calculate total collected fees in USD
  97. // Get IDs of collected tokens for fees
  98. tokenIDs := []common.TokenID{}
  99. for id := range batch.CollectedFees {
  100. tokenIDs = append(tokenIDs, id)
  101. }
  102. // Get USD value of the tokens
  103. type tokenPrice struct {
  104. ID common.TokenID `meddler:"token_id"`
  105. USD *float64 `meddler:"usd"`
  106. Decimals int `meddler:"decimals"`
  107. }
  108. var tokenPrices []*tokenPrice
  109. if len(tokenIDs) > 0 {
  110. query, args, err := sqlx.In(
  111. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
  112. tokenIDs,
  113. )
  114. if err != nil {
  115. return err
  116. }
  117. query = hdb.db.Rebind(query)
  118. if err := meddler.QueryAll(
  119. hdb.db, &tokenPrices, query, args...,
  120. ); err != nil {
  121. return err
  122. }
  123. }
  124. // Calculate total collected
  125. var total float64
  126. for _, tokenPrice := range tokenPrices {
  127. if tokenPrice.USD == nil {
  128. continue
  129. }
  130. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  131. amount, _ := f.Float64()
  132. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  133. }
  134. batch.TotalFeesUSD = &total
  135. // Insert to DB
  136. return meddler.Insert(d, "batch", batch)
  137. }
  138. // AddBatches insert Bids into the DB
  139. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  140. return hdb.addBatches(hdb.db, batches)
  141. }
  142. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  143. for i := 0; i < len(batches); i++ {
  144. if err := hdb.addBatch(d, &batches[i]); err != nil {
  145. return err
  146. }
  147. }
  148. return nil
  149. }
  150. // GetBatchAPI return the batch with the given batchNum
  151. func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
  152. batch := &BatchAPI{}
  153. return batch, meddler.QueryRow(
  154. hdb.db, batch,
  155. `SELECT batch.*, block.timestamp, block.hash
  156. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
  157. WHERE batch_num = $1;`, batchNum,
  158. )
  159. }
  160. // GetBatchesAPI return the batches applying the given filters
  161. func (hdb *HistoryDB) GetBatchesAPI(
  162. minBatchNum, maxBatchNum, slotNum *uint,
  163. forgerAddr *ethCommon.Address,
  164. fromItem, limit *uint, order string,
  165. ) ([]BatchAPI, *db.Pagination, error) {
  166. var query string
  167. var args []interface{}
  168. queryStr := `SELECT batch.*, block.timestamp, block.hash,
  169. count(*) OVER() AS total_items, MIN(batch.item_id) OVER() AS first_item,
  170. MAX(batch.item_id) OVER() AS last_item
  171. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
  172. // Apply filters
  173. nextIsAnd := false
  174. // minBatchNum filter
  175. if minBatchNum != nil {
  176. if nextIsAnd {
  177. queryStr += "AND "
  178. } else {
  179. queryStr += "WHERE "
  180. }
  181. queryStr += "batch.batch_num > ? "
  182. args = append(args, minBatchNum)
  183. nextIsAnd = true
  184. }
  185. // maxBatchNum filter
  186. if maxBatchNum != nil {
  187. if nextIsAnd {
  188. queryStr += "AND "
  189. } else {
  190. queryStr += "WHERE "
  191. }
  192. queryStr += "batch.batch_num < ? "
  193. args = append(args, maxBatchNum)
  194. nextIsAnd = true
  195. }
  196. // slotNum filter
  197. if slotNum != nil {
  198. if nextIsAnd {
  199. queryStr += "AND "
  200. } else {
  201. queryStr += "WHERE "
  202. }
  203. queryStr += "batch.slot_num = ? "
  204. args = append(args, slotNum)
  205. nextIsAnd = true
  206. }
  207. // forgerAddr filter
  208. if forgerAddr != nil {
  209. if nextIsAnd {
  210. queryStr += "AND "
  211. } else {
  212. queryStr += "WHERE "
  213. }
  214. queryStr += "batch.forger_addr = ? "
  215. args = append(args, forgerAddr)
  216. nextIsAnd = true
  217. }
  218. // pagination
  219. if fromItem != nil {
  220. if nextIsAnd {
  221. queryStr += "AND "
  222. } else {
  223. queryStr += "WHERE "
  224. }
  225. if order == OrderAsc {
  226. queryStr += "batch.item_id >= ? "
  227. } else {
  228. queryStr += "batch.item_id <= ? "
  229. }
  230. args = append(args, fromItem)
  231. }
  232. queryStr += "ORDER BY batch.item_id "
  233. if order == OrderAsc {
  234. queryStr += " ASC "
  235. } else {
  236. queryStr += " DESC "
  237. }
  238. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  239. query = hdb.db.Rebind(queryStr)
  240. // log.Debug(query)
  241. batchPtrs := []*BatchAPI{}
  242. if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
  243. return nil, nil, err
  244. }
  245. batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
  246. if len(batches) == 0 {
  247. return nil, nil, sql.ErrNoRows
  248. }
  249. return batches, &db.Pagination{
  250. TotalItems: batches[0].TotalItems,
  251. FirstItem: batches[0].FirstItem,
  252. LastItem: batches[0].LastItem,
  253. }, nil
  254. }
  255. // GetAllBatches retrieve all batches from the DB
  256. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  257. var batches []*common.Batch
  258. err := meddler.QueryAll(
  259. hdb.db, &batches,
  260. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  261. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  262. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`,
  263. )
  264. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  265. }
  266. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  267. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  268. var batches []*common.Batch
  269. err := meddler.QueryAll(
  270. hdb.db, &batches,
  271. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
  272. from, to,
  273. )
  274. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  275. }
  276. // GetLastBatchNum returns the BatchNum of the latest forged batch
  277. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  278. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  279. var batchNum common.BatchNum
  280. return batchNum, row.Scan(&batchNum)
  281. }
  282. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  283. // batches. If there's no batch in the DB (nil, nil) is returned.
  284. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  285. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  286. lastL1TxsNum := new(int64)
  287. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  288. }
  289. // Reorg deletes all the information that was added into the DB after the
  290. // lastValidBlock. If lastValidBlock is negative, all block information is
  291. // deleted.
  292. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  293. var err error
  294. if lastValidBlock < 0 {
  295. _, err = hdb.db.Exec("DELETE FROM block;")
  296. } else {
  297. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  298. }
  299. return err
  300. }
  301. // SyncPoD stores all the data that can be changed / added on a block in the PoD SC
  302. func (hdb *HistoryDB) SyncPoD(
  303. blockNum uint64,
  304. bids []common.Bid,
  305. coordinators []common.Coordinator,
  306. vars *common.AuctionVariables,
  307. ) error {
  308. return nil
  309. }
  310. // AddBids insert Bids into the DB
  311. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  312. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  313. // TODO: check the coordinator info
  314. return db.BulkInsert(
  315. d,
  316. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  317. bids[:],
  318. )
  319. }
  320. // GetAllBids retrieve all bids from the DB
  321. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  322. var bids []*common.Bid
  323. err := meddler.QueryAll(
  324. hdb.db, &bids,
  325. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid;`,
  326. )
  327. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  328. }
  329. // GetBestBidAPI returns the best bid in specific slot by slotNum
  330. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  331. bid := &BidAPI{}
  332. err := meddler.QueryRow(
  333. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  334. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  335. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  336. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  337. )
  338. return *bid, err
  339. }
  340. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  341. func (hdb *HistoryDB) GetBestBidsAPI(minSlotNum, maxSlotNum *int64, bidderAddr *ethCommon.Address, limit *uint, order string) ([]BidAPI, *db.Pagination, error) {
  342. var query string
  343. var args []interface{}
  344. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  345. COUNT(*) OVER() AS total_items, MIN(b.slot_num) OVER() AS first_item,
  346. MAX(b.slot_num) OVER() AS last_item FROM (
  347. SELECT slot_num, MAX(item_id) as maxitem
  348. FROM bid GROUP BY slot_num
  349. )
  350. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  351. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  352. INNER JOIN coordinator ON b.bidder_addr = coordinator.bidder_addr
  353. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  354. args = append(args, minSlotNum)
  355. args = append(args, maxSlotNum)
  356. // Apply filters
  357. if bidderAddr != nil {
  358. queryStr += " AND b.bidder_addr = ? "
  359. args = append(args, bidderAddr)
  360. }
  361. queryStr += " ORDER BY b.slot_num "
  362. if order == OrderAsc {
  363. queryStr += "ASC "
  364. } else {
  365. queryStr += "DESC "
  366. }
  367. if limit != nil {
  368. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  369. }
  370. query = hdb.db.Rebind(queryStr)
  371. bidPtrs := []*BidAPI{}
  372. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  373. return nil, nil, err
  374. }
  375. // log.Debug(query)
  376. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  377. if len(bids) == 0 {
  378. return nil, nil, sql.ErrNoRows
  379. }
  380. return bids, &db.Pagination{
  381. TotalItems: bids[0].TotalItems,
  382. FirstItem: bids[0].FirstItem,
  383. LastItem: bids[0].LastItem,
  384. }, nil
  385. }
  386. // GetBidsAPI return the bids applying the given filters
  387. func (hdb *HistoryDB) GetBidsAPI(slotNum *int64, forgerAddr *ethCommon.Address, fromItem, limit *uint, order string) ([]BidAPI, *db.Pagination, error) {
  388. var query string
  389. var args []interface{}
  390. queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  391. COUNT(*) OVER() AS total_items, MIN(bid.item_id) OVER() AS first_item,
  392. MAX(bid.item_id) OVER() AS last_item FROM bid
  393. INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  394. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
  395. // Apply filters
  396. nextIsAnd := false
  397. // slotNum filter
  398. if slotNum != nil {
  399. if nextIsAnd {
  400. queryStr += "AND "
  401. } else {
  402. queryStr += "WHERE "
  403. }
  404. queryStr += "bid.slot_num = ? "
  405. args = append(args, slotNum)
  406. nextIsAnd = true
  407. }
  408. // slotNum filter
  409. if forgerAddr != nil {
  410. if nextIsAnd {
  411. queryStr += "AND "
  412. } else {
  413. queryStr += "WHERE "
  414. }
  415. queryStr += "bid.bidder_addr = ? "
  416. args = append(args, forgerAddr)
  417. nextIsAnd = true
  418. }
  419. if fromItem != nil {
  420. if nextIsAnd {
  421. queryStr += "AND "
  422. } else {
  423. queryStr += "WHERE "
  424. }
  425. if order == OrderAsc {
  426. queryStr += "bid.item_id >= ? "
  427. } else {
  428. queryStr += "bid.item_id <= ? "
  429. }
  430. args = append(args, fromItem)
  431. }
  432. // pagination
  433. queryStr += "ORDER BY bid.item_id "
  434. if order == OrderAsc {
  435. queryStr += "ASC "
  436. } else {
  437. queryStr += "DESC "
  438. }
  439. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  440. query, argsQ, err := sqlx.In(queryStr, args...)
  441. if err != nil {
  442. return nil, nil, err
  443. }
  444. query = hdb.db.Rebind(query)
  445. bids := []*BidAPI{}
  446. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  447. return nil, nil, err
  448. }
  449. if len(bids) == 0 {
  450. return nil, nil, sql.ErrNoRows
  451. }
  452. return db.SlicePtrsToSlice(bids).([]BidAPI), &db.Pagination{
  453. TotalItems: bids[0].TotalItems,
  454. FirstItem: bids[0].FirstItem,
  455. LastItem: bids[0].LastItem,
  456. }, nil
  457. }
  458. // AddCoordinators insert Coordinators into the DB
  459. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  460. return hdb.addCoordinators(hdb.db, coordinators)
  461. }
  462. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  463. return db.BulkInsert(
  464. d,
  465. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  466. coordinators[:],
  467. )
  468. }
  469. // AddExitTree insert Exit tree into the DB
  470. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  471. return hdb.addExitTree(hdb.db, exitTree)
  472. }
  473. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  474. return db.BulkInsert(
  475. d,
  476. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  477. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  478. exitTree[:],
  479. )
  480. }
  481. // AddToken insert a token into the DB
  482. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  483. return meddler.Insert(hdb.db, "token", token)
  484. }
  485. // AddTokens insert tokens into the DB
  486. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  487. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  488. return db.BulkInsert(
  489. d,
  490. `INSERT INTO token (
  491. token_id,
  492. eth_block_num,
  493. eth_addr,
  494. name,
  495. symbol,
  496. decimals
  497. ) VALUES %s;`,
  498. tokens[:],
  499. )
  500. }
  501. // UpdateTokenValue updates the USD value of a token
  502. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  503. _, err := hdb.db.Exec(
  504. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  505. value, tokenSymbol,
  506. )
  507. return err
  508. }
  509. // GetToken returns a token from the DB given a TokenID
  510. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  511. token := &TokenWithUSD{}
  512. err := meddler.QueryRow(
  513. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  514. )
  515. return token, err
  516. }
  517. // GetAllTokens returns all tokens from the DB
  518. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  519. var tokens []*TokenWithUSD
  520. err := meddler.QueryAll(
  521. hdb.db, &tokens,
  522. "SELECT * FROM token ORDER BY token_id;",
  523. )
  524. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
  525. }
  526. // GetTokens returns a list of tokens from the DB
  527. func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
  528. var query string
  529. var args []interface{}
  530. 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 `
  531. // Apply filters
  532. nextIsAnd := false
  533. if len(ids) > 0 {
  534. queryStr += "WHERE token_id IN (?) "
  535. nextIsAnd = true
  536. args = append(args, ids)
  537. }
  538. if len(symbols) > 0 {
  539. if nextIsAnd {
  540. queryStr += "AND "
  541. } else {
  542. queryStr += "WHERE "
  543. }
  544. queryStr += "symbol IN (?) "
  545. args = append(args, symbols)
  546. nextIsAnd = true
  547. }
  548. if name != "" {
  549. if nextIsAnd {
  550. queryStr += "AND "
  551. } else {
  552. queryStr += "WHERE "
  553. }
  554. queryStr += "name ~ ? "
  555. args = append(args, name)
  556. nextIsAnd = true
  557. }
  558. if fromItem != nil {
  559. if nextIsAnd {
  560. queryStr += "AND "
  561. } else {
  562. queryStr += "WHERE "
  563. }
  564. if order == OrderAsc {
  565. queryStr += "item_id >= ? "
  566. } else {
  567. queryStr += "item_id <= ? "
  568. }
  569. args = append(args, fromItem)
  570. }
  571. // pagination
  572. queryStr += "ORDER BY item_id "
  573. if order == OrderAsc {
  574. queryStr += "ASC "
  575. } else {
  576. queryStr += "DESC "
  577. }
  578. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  579. query, argsQ, err := sqlx.In(queryStr, args...)
  580. if err != nil {
  581. return nil, nil, err
  582. }
  583. query = hdb.db.Rebind(query)
  584. tokens := []*TokenWithUSD{}
  585. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  586. return nil, nil, err
  587. }
  588. if len(tokens) == 0 {
  589. return nil, nil, sql.ErrNoRows
  590. }
  591. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
  592. TotalItems: tokens[0].TotalItems,
  593. FirstItem: tokens[0].FirstItem,
  594. LastItem: tokens[0].LastItem,
  595. }, nil
  596. }
  597. // GetTokenSymbols returns all the token symbols from the DB
  598. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  599. var tokenSymbols []string
  600. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  601. if err != nil {
  602. return nil, err
  603. }
  604. sym := new(string)
  605. for rows.Next() {
  606. err = rows.Scan(sym)
  607. if err != nil {
  608. return nil, err
  609. }
  610. tokenSymbols = append(tokenSymbols, *sym)
  611. }
  612. return tokenSymbols, nil
  613. }
  614. // AddAccounts insert accounts into the DB
  615. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  616. return hdb.addAccounts(hdb.db, accounts)
  617. }
  618. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  619. return db.BulkInsert(
  620. d,
  621. `INSERT INTO account (
  622. idx,
  623. token_id,
  624. batch_num,
  625. bjj,
  626. eth_addr
  627. ) VALUES %s;`,
  628. accounts[:],
  629. )
  630. }
  631. // GetAccounts returns a list of accounts from the DB
  632. func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
  633. var accs []*common.Account
  634. err := meddler.QueryAll(
  635. hdb.db, &accs,
  636. "SELECT * FROM account ORDER BY idx;",
  637. )
  638. return db.SlicePtrsToSlice(accs).([]common.Account), err
  639. }
  640. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  641. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  642. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  643. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  644. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  645. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  646. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  647. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  648. txs := []txWrite{}
  649. for i := 0; i < len(l1txs); i++ {
  650. af := new(big.Float).SetInt(l1txs[i].Amount)
  651. amountFloat, _ := af.Float64()
  652. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  653. loadAmountFloat, _ := laf.Float64()
  654. txs = append(txs, txWrite{
  655. // Generic
  656. IsL1: true,
  657. TxID: l1txs[i].TxID,
  658. Type: l1txs[i].Type,
  659. Position: l1txs[i].Position,
  660. FromIdx: &l1txs[i].FromIdx,
  661. ToIdx: l1txs[i].ToIdx,
  662. Amount: l1txs[i].Amount,
  663. AmountFloat: amountFloat,
  664. TokenID: l1txs[i].TokenID,
  665. BatchNum: l1txs[i].BatchNum,
  666. EthBlockNum: l1txs[i].EthBlockNum,
  667. // L1
  668. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  669. UserOrigin: &l1txs[i].UserOrigin,
  670. FromEthAddr: &l1txs[i].FromEthAddr,
  671. FromBJJ: l1txs[i].FromBJJ,
  672. LoadAmount: l1txs[i].LoadAmount,
  673. LoadAmountFloat: &loadAmountFloat,
  674. })
  675. }
  676. return hdb.addTxs(d, txs)
  677. }
  678. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  679. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  680. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  681. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  682. txs := []txWrite{}
  683. for i := 0; i < len(l2txs); i++ {
  684. f := new(big.Float).SetInt(l2txs[i].Amount)
  685. amountFloat, _ := f.Float64()
  686. txs = append(txs, txWrite{
  687. // Generic
  688. IsL1: false,
  689. TxID: l2txs[i].TxID,
  690. Type: l2txs[i].Type,
  691. Position: l2txs[i].Position,
  692. FromIdx: &l2txs[i].FromIdx,
  693. ToIdx: l2txs[i].ToIdx,
  694. Amount: l2txs[i].Amount,
  695. AmountFloat: amountFloat,
  696. BatchNum: &l2txs[i].BatchNum,
  697. EthBlockNum: l2txs[i].EthBlockNum,
  698. // L2
  699. Fee: &l2txs[i].Fee,
  700. Nonce: &l2txs[i].Nonce,
  701. })
  702. }
  703. return hdb.addTxs(d, txs)
  704. }
  705. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  706. return db.BulkInsert(
  707. d,
  708. `INSERT INTO tx (
  709. is_l1,
  710. id,
  711. type,
  712. position,
  713. from_idx,
  714. to_idx,
  715. amount,
  716. amount_f,
  717. token_id,
  718. batch_num,
  719. eth_block_num,
  720. to_forge_l1_txs_num,
  721. user_origin,
  722. from_eth_addr,
  723. from_bjj,
  724. load_amount,
  725. load_amount_f,
  726. fee,
  727. nonce
  728. ) VALUES %s;`,
  729. txs[:],
  730. )
  731. }
  732. // // GetTxs returns a list of txs from the DB
  733. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  734. // var txs []*common.Tx
  735. // err := meddler.QueryAll(
  736. // hdb.db, &txs,
  737. // `SELECT * FROM tx
  738. // ORDER BY (batch_num, position) ASC`,
  739. // )
  740. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  741. // }
  742. // GetHistoryTx returns a tx from the DB given a TxID
  743. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  744. tx := &TxAPI{}
  745. err := meddler.QueryRow(
  746. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  747. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  748. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  749. tx.amount, tx.token_id, tx.amount_usd,
  750. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  751. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  752. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  753. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  754. token.usd_update, block.timestamp
  755. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  756. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  757. WHERE tx.id = $1;`, txID,
  758. )
  759. return tx, err
  760. }
  761. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  762. // and pagination info
  763. func (hdb *HistoryDB) GetHistoryTxs(
  764. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  765. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  766. fromItem, limit *uint, order string,
  767. ) ([]TxAPI, *db.Pagination, error) {
  768. if ethAddr != nil && bjj != nil {
  769. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  770. }
  771. var query string
  772. var args []interface{}
  773. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  774. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  775. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  776. tx.amount, tx.token_id, tx.amount_usd,
  777. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  778. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  779. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  780. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  781. token.usd_update, block.timestamp, count(*) OVER() AS total_items,
  782. MIN(tx.item_id) OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item
  783. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  784. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  785. // Apply filters
  786. nextIsAnd := false
  787. // ethAddr filter
  788. if ethAddr != nil {
  789. queryStr = `WITH acc AS
  790. (select idx from account where eth_addr = ?) ` + queryStr
  791. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  792. nextIsAnd = true
  793. args = append(args, ethAddr)
  794. } else if bjj != nil { // bjj filter
  795. queryStr = `WITH acc AS
  796. (select idx from account where bjj = ?) ` + queryStr
  797. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  798. nextIsAnd = true
  799. args = append(args, bjj)
  800. }
  801. // tokenID filter
  802. if tokenID != nil {
  803. if nextIsAnd {
  804. queryStr += "AND "
  805. } else {
  806. queryStr += "WHERE "
  807. }
  808. queryStr += "tx.token_id = ? "
  809. args = append(args, tokenID)
  810. nextIsAnd = true
  811. }
  812. // idx filter
  813. if idx != nil {
  814. if nextIsAnd {
  815. queryStr += "AND "
  816. } else {
  817. queryStr += "WHERE "
  818. }
  819. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  820. args = append(args, idx, idx)
  821. nextIsAnd = true
  822. }
  823. // batchNum filter
  824. if batchNum != nil {
  825. if nextIsAnd {
  826. queryStr += "AND "
  827. } else {
  828. queryStr += "WHERE "
  829. }
  830. queryStr += "tx.batch_num = ? "
  831. args = append(args, batchNum)
  832. nextIsAnd = true
  833. }
  834. // txType filter
  835. if txType != nil {
  836. if nextIsAnd {
  837. queryStr += "AND "
  838. } else {
  839. queryStr += "WHERE "
  840. }
  841. queryStr += "tx.type = ? "
  842. args = append(args, txType)
  843. nextIsAnd = true
  844. }
  845. if fromItem != nil {
  846. if nextIsAnd {
  847. queryStr += "AND "
  848. } else {
  849. queryStr += "WHERE "
  850. }
  851. if order == OrderAsc {
  852. queryStr += "tx.item_id >= ? "
  853. } else {
  854. queryStr += "tx.item_id <= ? "
  855. }
  856. args = append(args, fromItem)
  857. nextIsAnd = true
  858. }
  859. if nextIsAnd {
  860. queryStr += "AND "
  861. } else {
  862. queryStr += "WHERE "
  863. }
  864. queryStr += "tx.batch_num IS NOT NULL "
  865. // pagination
  866. queryStr += "ORDER BY tx.item_id "
  867. if order == OrderAsc {
  868. queryStr += " ASC "
  869. } else {
  870. queryStr += " DESC "
  871. }
  872. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  873. query = hdb.db.Rebind(queryStr)
  874. // log.Debug(query)
  875. txsPtrs := []*TxAPI{}
  876. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  877. return nil, nil, err
  878. }
  879. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  880. if len(txs) == 0 {
  881. return nil, nil, sql.ErrNoRows
  882. }
  883. return txs, &db.Pagination{
  884. TotalItems: txs[0].TotalItems,
  885. FirstItem: txs[0].FirstItem,
  886. LastItem: txs[0].LastItem,
  887. }, nil
  888. }
  889. // GetAllExits returns all exit from the DB
  890. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  891. var exits []*common.ExitInfo
  892. err := meddler.QueryAll(
  893. hdb.db, &exits,
  894. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  895. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  896. exit_tree.delayed_withdrawn FROM exit_tree;`,
  897. )
  898. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  899. }
  900. // GetExitAPI returns a exit from the DB
  901. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  902. exit := &ExitAPI{}
  903. err := meddler.QueryRow(
  904. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  905. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  906. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  907. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  908. token.token_id, token.item_id AS token_item_id,
  909. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  910. token.decimals, token.usd, token.usd_update
  911. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  912. INNER JOIN token ON account.token_id = token.token_id
  913. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  914. )
  915. return exit, err
  916. }
  917. // GetExitsAPI returns a list of exits from the DB and pagination info
  918. func (hdb *HistoryDB) GetExitsAPI(
  919. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  920. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  921. fromItem, limit *uint, order string,
  922. ) ([]ExitAPI, *db.Pagination, error) {
  923. if ethAddr != nil && bjj != nil {
  924. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  925. }
  926. var query string
  927. var args []interface{}
  928. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  929. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  930. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  931. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  932. token.token_id, token.item_id AS token_item_id,
  933. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  934. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items,
  935. MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
  936. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  937. INNER JOIN token ON account.token_id = token.token_id `
  938. // Apply filters
  939. nextIsAnd := false
  940. // ethAddr filter
  941. if ethAddr != nil {
  942. queryStr += "WHERE account.eth_addr = ? "
  943. nextIsAnd = true
  944. args = append(args, ethAddr)
  945. } else if bjj != nil { // bjj filter
  946. queryStr += "WHERE account.bjj = ? "
  947. nextIsAnd = true
  948. args = append(args, bjj)
  949. }
  950. // tokenID filter
  951. if tokenID != nil {
  952. if nextIsAnd {
  953. queryStr += "AND "
  954. } else {
  955. queryStr += "WHERE "
  956. }
  957. queryStr += "account.token_id = ? "
  958. args = append(args, tokenID)
  959. nextIsAnd = true
  960. }
  961. // idx filter
  962. if idx != nil {
  963. if nextIsAnd {
  964. queryStr += "AND "
  965. } else {
  966. queryStr += "WHERE "
  967. }
  968. queryStr += "exit_tree.account_idx = ? "
  969. args = append(args, idx)
  970. nextIsAnd = true
  971. }
  972. // batchNum filter
  973. if batchNum != nil {
  974. if nextIsAnd {
  975. queryStr += "AND "
  976. } else {
  977. queryStr += "WHERE "
  978. }
  979. queryStr += "exit_tree.batch_num = ? "
  980. args = append(args, batchNum)
  981. nextIsAnd = true
  982. }
  983. // onlyPendingWithdraws
  984. if onlyPendingWithdraws != nil {
  985. if *onlyPendingWithdraws {
  986. if nextIsAnd {
  987. queryStr += "AND "
  988. } else {
  989. queryStr += "WHERE "
  990. }
  991. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  992. nextIsAnd = true
  993. }
  994. }
  995. if fromItem != nil {
  996. if nextIsAnd {
  997. queryStr += "AND "
  998. } else {
  999. queryStr += "WHERE "
  1000. }
  1001. if order == OrderAsc {
  1002. queryStr += "exit_tree.item_id >= ? "
  1003. } else {
  1004. queryStr += "exit_tree.item_id <= ? "
  1005. }
  1006. args = append(args, fromItem)
  1007. // nextIsAnd = true
  1008. }
  1009. // pagination
  1010. queryStr += "ORDER BY exit_tree.item_id "
  1011. if order == OrderAsc {
  1012. queryStr += " ASC "
  1013. } else {
  1014. queryStr += " DESC "
  1015. }
  1016. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1017. query = hdb.db.Rebind(queryStr)
  1018. // log.Debug(query)
  1019. exits := []*ExitAPI{}
  1020. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1021. return nil, nil, err
  1022. }
  1023. if len(exits) == 0 {
  1024. return nil, nil, sql.ErrNoRows
  1025. }
  1026. return db.SlicePtrsToSlice(exits).([]ExitAPI), &db.Pagination{
  1027. TotalItems: exits[0].TotalItems,
  1028. FirstItem: exits[0].FirstItem,
  1029. LastItem: exits[0].LastItem,
  1030. }, nil
  1031. }
  1032. // // GetTx returns a tx from the DB
  1033. // func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  1034. // tx := new(common.Tx)
  1035. // return tx, meddler.QueryRow(
  1036. // hdb.db, tx,
  1037. // "SELECT * FROM tx WHERE id = $1;",
  1038. // txID,
  1039. // )
  1040. // }
  1041. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1042. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1043. var txs []*common.L1Tx
  1044. err := meddler.QueryAll(
  1045. hdb.db, &txs,
  1046. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1047. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1048. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1049. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  1050. )
  1051. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1052. }
  1053. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1054. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1055. var txs []*common.L1Tx
  1056. err := meddler.QueryAll(
  1057. hdb.db, &txs,
  1058. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1059. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1060. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1061. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1062. )
  1063. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1064. }
  1065. // GetAllL2Txs returns all L2Txs from the DB
  1066. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1067. var txs []*common.L2Tx
  1068. err := meddler.QueryAll(
  1069. hdb.db, &txs,
  1070. `SELECT tx.id, tx.batch_num, tx.position,
  1071. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1072. tx.type, tx.eth_block_num
  1073. FROM tx WHERE is_l1 = FALSE;`,
  1074. )
  1075. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1076. }
  1077. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1078. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1079. var txs []*common.L1Tx
  1080. err := meddler.QueryAll(
  1081. hdb.db, &txs,
  1082. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1083. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1084. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1085. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1086. toForgeL1TxsNum,
  1087. )
  1088. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1089. }
  1090. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1091. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1092. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1093. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1094. var lastL1TxsPosition int
  1095. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1096. }
  1097. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1098. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1099. *common.WDelayerVariables, error) {
  1100. var rollup common.RollupVariables
  1101. var auction common.AuctionVariables
  1102. var wDelayer common.WDelayerVariables
  1103. if err := meddler.QueryRow(hdb.db, &rollup,
  1104. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1105. return nil, nil, nil, err
  1106. }
  1107. if err := meddler.QueryRow(hdb.db, &auction,
  1108. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1109. return nil, nil, nil, err
  1110. }
  1111. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1112. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1113. return nil, nil, nil, err
  1114. }
  1115. return &rollup, &auction, &wDelayer, nil
  1116. }
  1117. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1118. return meddler.Insert(d, "rollup_vars", rollup)
  1119. }
  1120. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1121. return meddler.Insert(d, "auction_vars", auction)
  1122. }
  1123. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1124. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1125. }
  1126. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1127. // contract variables. This initial state is stored linked to block 0, which
  1128. // always exist in the DB and is used to store initialization data that always
  1129. // exist in the smart contracts.
  1130. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1131. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1132. txn, err := hdb.db.Begin()
  1133. if err != nil {
  1134. return err
  1135. }
  1136. defer func() {
  1137. if err != nil {
  1138. db.Rollback(txn)
  1139. }
  1140. }()
  1141. // Force EthBlockNum to be 0 because it's the block used to link data
  1142. // that belongs to the creation of the smart contracts
  1143. rollup.EthBlockNum = 0
  1144. auction.EthBlockNum = 0
  1145. wDelayer.EthBlockNum = 0
  1146. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1147. return err
  1148. }
  1149. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1150. return err
  1151. }
  1152. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1153. return err
  1154. }
  1155. return txn.Commit()
  1156. }
  1157. // AddBlockSCData stores all the information of a block retrieved by the
  1158. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1159. // the pagination system of the API/DB depends on this. Within blocks, all
  1160. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1161. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1162. txn, err := hdb.db.Begin()
  1163. if err != nil {
  1164. return err
  1165. }
  1166. defer func() {
  1167. if err != nil {
  1168. db.Rollback(txn)
  1169. }
  1170. }()
  1171. // Add block
  1172. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1173. return err
  1174. }
  1175. // Add Coordinators
  1176. if len(blockData.Auction.Coordinators) > 0 {
  1177. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1178. return err
  1179. }
  1180. }
  1181. // Add Bids
  1182. if len(blockData.Auction.Bids) > 0 {
  1183. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1184. return err
  1185. }
  1186. }
  1187. // Add Tokens
  1188. if len(blockData.Rollup.AddedTokens) > 0 {
  1189. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1190. return err
  1191. }
  1192. }
  1193. // Add l1 Txs
  1194. if len(blockData.Rollup.L1UserTxs) > 0 {
  1195. if err := hdb.addL1Txs(txn, blockData.Rollup.L1UserTxs); err != nil {
  1196. return err
  1197. }
  1198. }
  1199. // Add Batches
  1200. for i := range blockData.Rollup.Batches {
  1201. batch := &blockData.Rollup.Batches[i]
  1202. // Add Batch: this will trigger an update on the DB
  1203. // that will set the batch num of forged L1 txs in this batch
  1204. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1205. return err
  1206. }
  1207. // Add unforged l1 Txs
  1208. if batch.L1Batch {
  1209. if len(batch.L1CoordinatorTxs) > 0 {
  1210. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1211. return err
  1212. }
  1213. }
  1214. }
  1215. // Add l2 Txs
  1216. if len(batch.L2Txs) > 0 {
  1217. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1218. return err
  1219. }
  1220. }
  1221. // Add accounts
  1222. if len(batch.CreatedAccounts) > 0 {
  1223. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1224. return err
  1225. }
  1226. }
  1227. // Add exit tree
  1228. if len(batch.ExitTree) > 0 {
  1229. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1230. return err
  1231. }
  1232. }
  1233. }
  1234. if blockData.Rollup.Vars != nil {
  1235. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1236. return err
  1237. }
  1238. }
  1239. if blockData.Auction.Vars != nil {
  1240. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1241. return err
  1242. }
  1243. }
  1244. if blockData.WDelayer.Vars != nil {
  1245. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1246. return err
  1247. }
  1248. }
  1249. // TODO: Process withdrawals
  1250. return txn.Commit()
  1251. }
  1252. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1253. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1254. coordinator := &CoordinatorAPI{}
  1255. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1256. return coordinator, err
  1257. }
  1258. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1259. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, *db.Pagination, error) {
  1260. var query string
  1261. var args []interface{}
  1262. queryStr := `SELECT coordinator.*,
  1263. COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
  1264. FROM coordinator `
  1265. // Apply filters
  1266. if fromItem != nil {
  1267. queryStr += "WHERE "
  1268. if order == OrderAsc {
  1269. queryStr += "coordinator.item_id >= ? "
  1270. } else {
  1271. queryStr += "coordinator.item_id <= ? "
  1272. }
  1273. args = append(args, fromItem)
  1274. }
  1275. // pagination
  1276. queryStr += "ORDER BY coordinator.item_id "
  1277. if order == OrderAsc {
  1278. queryStr += " ASC "
  1279. } else {
  1280. queryStr += " DESC "
  1281. }
  1282. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1283. query = hdb.db.Rebind(queryStr)
  1284. coordinators := []*CoordinatorAPI{}
  1285. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1286. return nil, nil, err
  1287. }
  1288. if len(coordinators) == 0 {
  1289. return nil, nil, sql.ErrNoRows
  1290. }
  1291. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI), &db.Pagination{
  1292. TotalItems: coordinators[0].TotalItems,
  1293. FirstItem: coordinators[0].FirstItem,
  1294. LastItem: coordinators[0].LastItem,
  1295. }, nil
  1296. }
  1297. // AddAuctionVars insert auction vars into the DB
  1298. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1299. return meddler.Insert(hdb.db, "auction_vars", auctionVars)
  1300. }
  1301. // GetAuctionVars returns auction variables
  1302. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1303. auctionVars := &common.AuctionVariables{}
  1304. err := meddler.QueryRow(
  1305. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1306. )
  1307. return auctionVars, err
  1308. }
  1309. // GetAccountAPI returns an account by its index
  1310. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1311. account := &AccountAPI{}
  1312. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1313. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1314. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1315. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1316. if err != nil {
  1317. return nil, err
  1318. }
  1319. return account, nil
  1320. }
  1321. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1322. func (hdb *HistoryDB) GetAccountsAPI(tokenIDs []common.TokenID, ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, fromItem, limit *uint, order string) ([]AccountAPI, *db.Pagination, error) {
  1323. if ethAddr != nil && bjj != nil {
  1324. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  1325. }
  1326. var query string
  1327. var args []interface{}
  1328. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1329. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1330. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1331. COUNT(*) OVER() AS total_items, MIN(account.item_id) OVER() AS first_item, MAX(account.item_id) OVER() AS last_item
  1332. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1333. // Apply filters
  1334. nextIsAnd := false
  1335. // ethAddr filter
  1336. if ethAddr != nil {
  1337. queryStr += "WHERE account.eth_addr = ? "
  1338. nextIsAnd = true
  1339. args = append(args, ethAddr)
  1340. } else if bjj != nil { // bjj filter
  1341. queryStr += "WHERE account.bjj = ? "
  1342. nextIsAnd = true
  1343. args = append(args, bjj)
  1344. }
  1345. // tokenID filter
  1346. if len(tokenIDs) > 0 {
  1347. if nextIsAnd {
  1348. queryStr += "AND "
  1349. } else {
  1350. queryStr += "WHERE "
  1351. }
  1352. queryStr += "account.token_id IN (?) "
  1353. args = append(args, tokenIDs)
  1354. nextIsAnd = true
  1355. }
  1356. if fromItem != nil {
  1357. if nextIsAnd {
  1358. queryStr += "AND "
  1359. } else {
  1360. queryStr += "WHERE "
  1361. }
  1362. if order == OrderAsc {
  1363. queryStr += "account.item_id >= ? "
  1364. } else {
  1365. queryStr += "account.item_id <= ? "
  1366. }
  1367. args = append(args, fromItem)
  1368. }
  1369. // pagination
  1370. queryStr += "ORDER BY account.item_id "
  1371. if order == OrderAsc {
  1372. queryStr += " ASC "
  1373. } else {
  1374. queryStr += " DESC "
  1375. }
  1376. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1377. query, argsQ, err := sqlx.In(queryStr, args...)
  1378. if err != nil {
  1379. return nil, nil, err
  1380. }
  1381. query = hdb.db.Rebind(query)
  1382. accounts := []*AccountAPI{}
  1383. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1384. return nil, nil, err
  1385. }
  1386. if len(accounts) == 0 {
  1387. return nil, nil, sql.ErrNoRows
  1388. }
  1389. return db.SlicePtrsToSlice(accounts).([]AccountAPI), &db.Pagination{
  1390. TotalItems: accounts[0].TotalItems,
  1391. FirstItem: accounts[0].FirstItem,
  1392. LastItem: accounts[0].LastItem,
  1393. }, nil
  1394. }
  1395. // GetMetrics returns metrics
  1396. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1397. metricsTotals := &MetricsTotals{}
  1398. metrics := &Metrics{}
  1399. err := meddler.QueryRow(
  1400. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1401. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1402. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1403. if err != nil {
  1404. return nil, err
  1405. }
  1406. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1407. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) / int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1408. err = meddler.QueryRow(
  1409. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1410. SUM(total_fees_usd) AS total_fees FROM batch
  1411. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1412. if err != nil {
  1413. return nil, err
  1414. }
  1415. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1416. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1417. err = meddler.QueryRow(
  1418. hdb.db, metrics,
  1419. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1420. if err != nil {
  1421. return nil, err
  1422. }
  1423. return metrics, nil
  1424. }