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.

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