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.

1600 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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, 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. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  474. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  475. type withdrawal struct {
  476. BatchNum int64 `db:"batch_num"`
  477. AccountIdx int64 `db:"account_idx"`
  478. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  479. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  480. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  481. Owner *ethCommon.Address `db:"owner"`
  482. Token *ethCommon.Address `db:"token"`
  483. }
  484. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  485. for i := range rollupWithdrawals {
  486. info := &rollupWithdrawals[i]
  487. withdrawals[i] = withdrawal{
  488. BatchNum: int64(info.NumExitRoot),
  489. AccountIdx: int64(info.Idx),
  490. }
  491. if info.InstantWithdraw {
  492. withdrawals[i].InstantWithdrawn = &blockNum
  493. } else {
  494. withdrawals[i].DelayedWithdrawRequest = &blockNum
  495. withdrawals[i].Owner = &info.Owner
  496. withdrawals[i].Token = &info.Token
  497. }
  498. }
  499. for i := range wDelayerWithdrawals {
  500. info := &wDelayerWithdrawals[i]
  501. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  502. DelayedWithdrawn: &blockNum,
  503. Owner: &info.Owner,
  504. Token: &info.Token,
  505. }
  506. }
  507. // In VALUES we set an initial row of NULLs to set the types of each
  508. // variable passed as argument
  509. query := `
  510. UPDATE exit_tree e SET
  511. instant_withdrawn = d.instant_withdrawn,
  512. delayed_withdraw_request = CASE
  513. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  514. ELSE d.delayed_withdraw_request
  515. END,
  516. delayed_withdrawn = d.delayed_withdrawn,
  517. owner = d.owner,
  518. token = d.token
  519. FROM (VALUES
  520. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  521. (:batch_num,
  522. :account_idx,
  523. :instant_withdrawn,
  524. :delayed_withdraw_request,
  525. :delayed_withdrawn,
  526. :owner,
  527. :token)
  528. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  529. WHERE
  530. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  531. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token)
  532. `
  533. if len(withdrawals) > 0 {
  534. if _, err := sqlx.NamedQuery(d, query, withdrawals); err != nil {
  535. return err
  536. }
  537. }
  538. return nil
  539. }
  540. // AddToken insert a token into the DB
  541. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  542. return meddler.Insert(hdb.db, "token", token)
  543. }
  544. // AddTokens insert tokens into the DB
  545. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  546. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  547. return db.BulkInsert(
  548. d,
  549. `INSERT INTO token (
  550. token_id,
  551. eth_block_num,
  552. eth_addr,
  553. name,
  554. symbol,
  555. decimals
  556. ) VALUES %s;`,
  557. tokens[:],
  558. )
  559. }
  560. // UpdateTokenValue updates the USD value of a token
  561. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  562. _, err := hdb.db.Exec(
  563. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  564. value, tokenSymbol,
  565. )
  566. return err
  567. }
  568. // GetToken returns a token from the DB given a TokenID
  569. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  570. token := &TokenWithUSD{}
  571. err := meddler.QueryRow(
  572. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  573. )
  574. return token, err
  575. }
  576. // GetAllTokens returns all tokens from the DB
  577. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  578. var tokens []*TokenWithUSD
  579. err := meddler.QueryAll(
  580. hdb.db, &tokens,
  581. "SELECT * FROM token ORDER BY token_id;",
  582. )
  583. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
  584. }
  585. // GetTokens returns a list of tokens from the DB
  586. func (hdb *HistoryDB) GetTokens(
  587. ids []common.TokenID, symbols []string, name string, fromItem,
  588. limit *uint, order string,
  589. ) ([]TokenWithUSD, uint64, error) {
  590. var query string
  591. var args []interface{}
  592. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  593. // Apply filters
  594. nextIsAnd := false
  595. if len(ids) > 0 {
  596. queryStr += "WHERE token_id IN (?) "
  597. nextIsAnd = true
  598. args = append(args, ids)
  599. }
  600. if len(symbols) > 0 {
  601. if nextIsAnd {
  602. queryStr += "AND "
  603. } else {
  604. queryStr += "WHERE "
  605. }
  606. queryStr += "symbol IN (?) "
  607. args = append(args, symbols)
  608. nextIsAnd = true
  609. }
  610. if name != "" {
  611. if nextIsAnd {
  612. queryStr += "AND "
  613. } else {
  614. queryStr += "WHERE "
  615. }
  616. queryStr += "name ~ ? "
  617. args = append(args, name)
  618. nextIsAnd = true
  619. }
  620. if fromItem != nil {
  621. if nextIsAnd {
  622. queryStr += "AND "
  623. } else {
  624. queryStr += "WHERE "
  625. }
  626. if order == OrderAsc {
  627. queryStr += "item_id >= ? "
  628. } else {
  629. queryStr += "item_id <= ? "
  630. }
  631. args = append(args, fromItem)
  632. }
  633. // pagination
  634. queryStr += "ORDER BY item_id "
  635. if order == OrderAsc {
  636. queryStr += "ASC "
  637. } else {
  638. queryStr += "DESC "
  639. }
  640. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  641. query, argsQ, err := sqlx.In(queryStr, args...)
  642. if err != nil {
  643. return nil, 0, err
  644. }
  645. query = hdb.db.Rebind(query)
  646. tokens := []*TokenWithUSD{}
  647. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  648. return nil, 0, err
  649. }
  650. if len(tokens) == 0 {
  651. return nil, 0, sql.ErrNoRows
  652. }
  653. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  654. }
  655. // GetTokenSymbols returns all the token symbols from the DB
  656. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  657. var tokenSymbols []string
  658. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  659. if err != nil {
  660. return nil, err
  661. }
  662. sym := new(string)
  663. for rows.Next() {
  664. err = rows.Scan(sym)
  665. if err != nil {
  666. return nil, err
  667. }
  668. tokenSymbols = append(tokenSymbols, *sym)
  669. }
  670. return tokenSymbols, nil
  671. }
  672. // AddAccounts insert accounts into the DB
  673. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  674. return hdb.addAccounts(hdb.db, accounts)
  675. }
  676. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  677. return db.BulkInsert(
  678. d,
  679. `INSERT INTO account (
  680. idx,
  681. token_id,
  682. batch_num,
  683. bjj,
  684. eth_addr
  685. ) VALUES %s;`,
  686. accounts[:],
  687. )
  688. }
  689. // GetAllAccounts returns a list of accounts from the DB
  690. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  691. var accs []*common.Account
  692. err := meddler.QueryAll(
  693. hdb.db, &accs,
  694. "SELECT * FROM account ORDER BY idx;",
  695. )
  696. return db.SlicePtrsToSlice(accs).([]common.Account), err
  697. }
  698. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  699. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  700. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  701. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  702. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  703. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  704. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  705. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  706. txs := []txWrite{}
  707. for i := 0; i < len(l1txs); i++ {
  708. af := new(big.Float).SetInt(l1txs[i].Amount)
  709. amountFloat, _ := af.Float64()
  710. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  711. loadAmountFloat, _ := laf.Float64()
  712. txs = append(txs, txWrite{
  713. // Generic
  714. IsL1: true,
  715. TxID: l1txs[i].TxID,
  716. Type: l1txs[i].Type,
  717. Position: l1txs[i].Position,
  718. FromIdx: &l1txs[i].FromIdx,
  719. ToIdx: l1txs[i].ToIdx,
  720. Amount: l1txs[i].Amount,
  721. AmountFloat: amountFloat,
  722. TokenID: l1txs[i].TokenID,
  723. BatchNum: l1txs[i].BatchNum,
  724. EthBlockNum: l1txs[i].EthBlockNum,
  725. // L1
  726. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  727. UserOrigin: &l1txs[i].UserOrigin,
  728. FromEthAddr: &l1txs[i].FromEthAddr,
  729. FromBJJ: l1txs[i].FromBJJ,
  730. LoadAmount: l1txs[i].LoadAmount,
  731. LoadAmountFloat: &loadAmountFloat,
  732. })
  733. }
  734. return hdb.addTxs(d, txs)
  735. }
  736. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  737. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  738. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  739. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  740. txs := []txWrite{}
  741. for i := 0; i < len(l2txs); i++ {
  742. f := new(big.Float).SetInt(l2txs[i].Amount)
  743. amountFloat, _ := f.Float64()
  744. txs = append(txs, txWrite{
  745. // Generic
  746. IsL1: false,
  747. TxID: l2txs[i].TxID,
  748. Type: l2txs[i].Type,
  749. Position: l2txs[i].Position,
  750. FromIdx: &l2txs[i].FromIdx,
  751. ToIdx: l2txs[i].ToIdx,
  752. Amount: l2txs[i].Amount,
  753. AmountFloat: amountFloat,
  754. BatchNum: &l2txs[i].BatchNum,
  755. EthBlockNum: l2txs[i].EthBlockNum,
  756. // L2
  757. Fee: &l2txs[i].Fee,
  758. Nonce: &l2txs[i].Nonce,
  759. })
  760. }
  761. return hdb.addTxs(d, txs)
  762. }
  763. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  764. return db.BulkInsert(
  765. d,
  766. `INSERT INTO tx (
  767. is_l1,
  768. id,
  769. type,
  770. position,
  771. from_idx,
  772. to_idx,
  773. amount,
  774. amount_f,
  775. token_id,
  776. batch_num,
  777. eth_block_num,
  778. to_forge_l1_txs_num,
  779. user_origin,
  780. from_eth_addr,
  781. from_bjj,
  782. load_amount,
  783. load_amount_f,
  784. fee,
  785. nonce
  786. ) VALUES %s;`,
  787. txs[:],
  788. )
  789. }
  790. // // GetTxs returns a list of txs from the DB
  791. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  792. // var txs []*common.Tx
  793. // err := meddler.QueryAll(
  794. // hdb.db, &txs,
  795. // `SELECT * FROM tx
  796. // ORDER BY (batch_num, position) ASC`,
  797. // )
  798. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  799. // }
  800. // GetHistoryTx returns a tx from the DB given a TxID
  801. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  802. tx := &TxAPI{}
  803. err := meddler.QueryRow(
  804. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  805. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  806. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  807. tx.amount, tx.token_id, tx.amount_usd,
  808. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  809. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  810. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  811. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  812. token.usd_update, block.timestamp
  813. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  814. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  815. WHERE tx.id = $1;`, txID,
  816. )
  817. return tx, err
  818. }
  819. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  820. // and pagination info
  821. func (hdb *HistoryDB) GetHistoryTxs(
  822. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  823. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  824. fromItem, limit *uint, order string,
  825. ) ([]TxAPI, uint64, error) {
  826. if ethAddr != nil && bjj != nil {
  827. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  828. }
  829. var query string
  830. var args []interface{}
  831. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  832. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  833. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  834. tx.amount, tx.token_id, tx.amount_usd,
  835. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  836. tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  837. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  838. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  839. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  840. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  841. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  842. // Apply filters
  843. nextIsAnd := false
  844. // ethAddr filter
  845. if ethAddr != nil {
  846. queryStr = `WITH acc AS
  847. (select idx from account where eth_addr = ?) ` + queryStr
  848. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  849. nextIsAnd = true
  850. args = append(args, ethAddr)
  851. } else if bjj != nil { // bjj filter
  852. queryStr = `WITH acc AS
  853. (select idx from account where bjj = ?) ` + queryStr
  854. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  855. nextIsAnd = true
  856. args = append(args, bjj)
  857. }
  858. // tokenID filter
  859. if tokenID != nil {
  860. if nextIsAnd {
  861. queryStr += "AND "
  862. } else {
  863. queryStr += "WHERE "
  864. }
  865. queryStr += "tx.token_id = ? "
  866. args = append(args, tokenID)
  867. nextIsAnd = true
  868. }
  869. // idx filter
  870. if idx != nil {
  871. if nextIsAnd {
  872. queryStr += "AND "
  873. } else {
  874. queryStr += "WHERE "
  875. }
  876. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  877. args = append(args, idx, idx)
  878. nextIsAnd = true
  879. }
  880. // batchNum filter
  881. if batchNum != nil {
  882. if nextIsAnd {
  883. queryStr += "AND "
  884. } else {
  885. queryStr += "WHERE "
  886. }
  887. queryStr += "tx.batch_num = ? "
  888. args = append(args, batchNum)
  889. nextIsAnd = true
  890. }
  891. // txType filter
  892. if txType != nil {
  893. if nextIsAnd {
  894. queryStr += "AND "
  895. } else {
  896. queryStr += "WHERE "
  897. }
  898. queryStr += "tx.type = ? "
  899. args = append(args, txType)
  900. nextIsAnd = true
  901. }
  902. if fromItem != nil {
  903. if nextIsAnd {
  904. queryStr += "AND "
  905. } else {
  906. queryStr += "WHERE "
  907. }
  908. if order == OrderAsc {
  909. queryStr += "tx.item_id >= ? "
  910. } else {
  911. queryStr += "tx.item_id <= ? "
  912. }
  913. args = append(args, fromItem)
  914. nextIsAnd = true
  915. }
  916. if nextIsAnd {
  917. queryStr += "AND "
  918. } else {
  919. queryStr += "WHERE "
  920. }
  921. queryStr += "tx.batch_num IS NOT NULL "
  922. // pagination
  923. queryStr += "ORDER BY tx.item_id "
  924. if order == OrderAsc {
  925. queryStr += " ASC "
  926. } else {
  927. queryStr += " DESC "
  928. }
  929. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  930. query = hdb.db.Rebind(queryStr)
  931. // log.Debug(query)
  932. txsPtrs := []*TxAPI{}
  933. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  934. return nil, 0, err
  935. }
  936. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  937. if len(txs) == 0 {
  938. return nil, 0, sql.ErrNoRows
  939. }
  940. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  941. }
  942. // GetAllExits returns all exit from the DB
  943. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  944. var exits []*common.ExitInfo
  945. err := meddler.QueryAll(
  946. hdb.db, &exits,
  947. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  948. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  949. exit_tree.delayed_withdrawn FROM exit_tree;`,
  950. )
  951. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  952. }
  953. // GetExitAPI returns a exit from the DB
  954. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  955. exit := &ExitAPI{}
  956. err := meddler.QueryRow(
  957. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  958. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  959. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  960. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  961. token.token_id, token.item_id AS token_item_id,
  962. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  963. token.decimals, token.usd, token.usd_update
  964. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  965. INNER JOIN token ON account.token_id = token.token_id
  966. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  967. )
  968. return exit, err
  969. }
  970. // GetExitsAPI returns a list of exits from the DB and pagination info
  971. func (hdb *HistoryDB) GetExitsAPI(
  972. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  973. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  974. fromItem, limit *uint, order string,
  975. ) ([]ExitAPI, uint64, error) {
  976. if ethAddr != nil && bjj != nil {
  977. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  978. }
  979. var query string
  980. var args []interface{}
  981. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  982. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  983. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  984. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  985. token.token_id, token.item_id AS token_item_id,
  986. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  987. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  988. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  989. INNER JOIN token ON account.token_id = token.token_id `
  990. // Apply filters
  991. nextIsAnd := false
  992. // ethAddr filter
  993. if ethAddr != nil {
  994. queryStr += "WHERE account.eth_addr = ? "
  995. nextIsAnd = true
  996. args = append(args, ethAddr)
  997. } else if bjj != nil { // bjj filter
  998. queryStr += "WHERE account.bjj = ? "
  999. nextIsAnd = true
  1000. args = append(args, bjj)
  1001. }
  1002. // tokenID filter
  1003. if tokenID != nil {
  1004. if nextIsAnd {
  1005. queryStr += "AND "
  1006. } else {
  1007. queryStr += "WHERE "
  1008. }
  1009. queryStr += "account.token_id = ? "
  1010. args = append(args, tokenID)
  1011. nextIsAnd = true
  1012. }
  1013. // idx filter
  1014. if idx != nil {
  1015. if nextIsAnd {
  1016. queryStr += "AND "
  1017. } else {
  1018. queryStr += "WHERE "
  1019. }
  1020. queryStr += "exit_tree.account_idx = ? "
  1021. args = append(args, idx)
  1022. nextIsAnd = true
  1023. }
  1024. // batchNum filter
  1025. if batchNum != nil {
  1026. if nextIsAnd {
  1027. queryStr += "AND "
  1028. } else {
  1029. queryStr += "WHERE "
  1030. }
  1031. queryStr += "exit_tree.batch_num = ? "
  1032. args = append(args, batchNum)
  1033. nextIsAnd = true
  1034. }
  1035. // onlyPendingWithdraws
  1036. if onlyPendingWithdraws != nil {
  1037. if *onlyPendingWithdraws {
  1038. if nextIsAnd {
  1039. queryStr += "AND "
  1040. } else {
  1041. queryStr += "WHERE "
  1042. }
  1043. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1044. nextIsAnd = true
  1045. }
  1046. }
  1047. if fromItem != nil {
  1048. if nextIsAnd {
  1049. queryStr += "AND "
  1050. } else {
  1051. queryStr += "WHERE "
  1052. }
  1053. if order == OrderAsc {
  1054. queryStr += "exit_tree.item_id >= ? "
  1055. } else {
  1056. queryStr += "exit_tree.item_id <= ? "
  1057. }
  1058. args = append(args, fromItem)
  1059. // nextIsAnd = true
  1060. }
  1061. // pagination
  1062. queryStr += "ORDER BY exit_tree.item_id "
  1063. if order == OrderAsc {
  1064. queryStr += " ASC "
  1065. } else {
  1066. queryStr += " DESC "
  1067. }
  1068. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1069. query = hdb.db.Rebind(queryStr)
  1070. // log.Debug(query)
  1071. exits := []*ExitAPI{}
  1072. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1073. return nil, 0, err
  1074. }
  1075. if len(exits) == 0 {
  1076. return nil, 0, sql.ErrNoRows
  1077. }
  1078. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1079. }
  1080. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1081. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1082. var txs []*common.L1Tx
  1083. err := meddler.QueryAll(
  1084. hdb.db, &txs,
  1085. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1086. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1087. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1088. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
  1089. )
  1090. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1091. }
  1092. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1093. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1094. var txs []*common.L1Tx
  1095. err := meddler.QueryAll(
  1096. hdb.db, &txs,
  1097. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1098. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1099. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1100. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1101. )
  1102. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1103. }
  1104. // GetAllL2Txs returns all L2Txs from the DB
  1105. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1106. var txs []*common.L2Tx
  1107. err := meddler.QueryAll(
  1108. hdb.db, &txs,
  1109. `SELECT tx.id, tx.batch_num, tx.position,
  1110. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1111. tx.type, tx.eth_block_num
  1112. FROM tx WHERE is_l1 = FALSE;`,
  1113. )
  1114. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1115. }
  1116. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1117. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1118. var txs []*common.L1Tx
  1119. err := meddler.QueryAll(
  1120. hdb.db, &txs,
  1121. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1122. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1123. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1124. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1125. toForgeL1TxsNum,
  1126. )
  1127. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1128. }
  1129. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1130. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1131. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1132. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1133. var lastL1TxsPosition int
  1134. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1135. }
  1136. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1137. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1138. *common.WDelayerVariables, error) {
  1139. var rollup common.RollupVariables
  1140. var auction common.AuctionVariables
  1141. var wDelayer common.WDelayerVariables
  1142. if err := meddler.QueryRow(hdb.db, &rollup,
  1143. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1144. return nil, nil, nil, err
  1145. }
  1146. if err := meddler.QueryRow(hdb.db, &auction,
  1147. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1148. return nil, nil, nil, err
  1149. }
  1150. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1151. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1152. return nil, nil, nil, err
  1153. }
  1154. return &rollup, &auction, &wDelayer, nil
  1155. }
  1156. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1157. return meddler.Insert(d, "rollup_vars", rollup)
  1158. }
  1159. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1160. return meddler.Insert(d, "auction_vars", auction)
  1161. }
  1162. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1163. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1164. }
  1165. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1166. // contract variables. This initial state is stored linked to block 0, which
  1167. // always exist in the DB and is used to store initialization data that always
  1168. // exist in the smart contracts.
  1169. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1170. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1171. txn, err := hdb.db.Beginx()
  1172. if err != nil {
  1173. return err
  1174. }
  1175. defer func() {
  1176. if err != nil {
  1177. db.Rollback(txn)
  1178. }
  1179. }()
  1180. // Force EthBlockNum to be 0 because it's the block used to link data
  1181. // that belongs to the creation of the smart contracts
  1182. rollup.EthBlockNum = 0
  1183. auction.EthBlockNum = 0
  1184. wDelayer.EthBlockNum = 0
  1185. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1186. return err
  1187. }
  1188. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1189. return err
  1190. }
  1191. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1192. return err
  1193. }
  1194. return txn.Commit()
  1195. }
  1196. // AddBlockSCData stores all the information of a block retrieved by the
  1197. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1198. // the pagination system of the API/DB depends on this. Within blocks, all
  1199. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1200. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1201. txn, err := hdb.db.Beginx()
  1202. if err != nil {
  1203. return err
  1204. }
  1205. defer func() {
  1206. if err != nil {
  1207. db.Rollback(txn)
  1208. }
  1209. }()
  1210. // Add block
  1211. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1212. return err
  1213. }
  1214. // Add Coordinators
  1215. if len(blockData.Auction.Coordinators) > 0 {
  1216. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1217. return err
  1218. }
  1219. }
  1220. // Add Bids
  1221. if len(blockData.Auction.Bids) > 0 {
  1222. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1223. return err
  1224. }
  1225. }
  1226. // Add Tokens
  1227. if len(blockData.Rollup.AddedTokens) > 0 {
  1228. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1229. return err
  1230. }
  1231. }
  1232. // Add l1 Txs
  1233. if len(blockData.Rollup.L1UserTxs) > 0 {
  1234. if err := hdb.addL1Txs(txn, blockData.Rollup.L1UserTxs); err != nil {
  1235. return err
  1236. }
  1237. }
  1238. // Add Batches
  1239. for i := range blockData.Rollup.Batches {
  1240. batch := &blockData.Rollup.Batches[i]
  1241. // Add Batch: this will trigger an update on the DB
  1242. // that will set the batch num of forged L1 txs in this batch
  1243. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1244. return err
  1245. }
  1246. // Add unforged l1 Txs
  1247. if batch.L1Batch {
  1248. if len(batch.L1CoordinatorTxs) > 0 {
  1249. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1250. return err
  1251. }
  1252. }
  1253. }
  1254. // Add l2 Txs
  1255. if len(batch.L2Txs) > 0 {
  1256. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1257. return err
  1258. }
  1259. }
  1260. // Add accounts
  1261. if len(batch.CreatedAccounts) > 0 {
  1262. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1263. return err
  1264. }
  1265. }
  1266. // Add exit tree
  1267. if len(batch.ExitTree) > 0 {
  1268. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1269. return err
  1270. }
  1271. }
  1272. }
  1273. if blockData.Rollup.Vars != nil {
  1274. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1275. return err
  1276. }
  1277. }
  1278. if blockData.Auction.Vars != nil {
  1279. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1280. return err
  1281. }
  1282. }
  1283. if blockData.WDelayer.Vars != nil {
  1284. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1285. return err
  1286. }
  1287. }
  1288. if err := hdb.updateExitTree(txn, blockData.Block.EthBlockNum,
  1289. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1290. return err
  1291. }
  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. }