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.

1627 lines
48 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 += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  847. nextIsAnd = true
  848. args = append(args, ethAddr, ethAddr)
  849. } else if bjj != nil { // bjj filter
  850. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  851. nextIsAnd = true
  852. args = append(args, bjj, bjj)
  853. }
  854. // tokenID filter
  855. if tokenID != nil {
  856. if nextIsAnd {
  857. queryStr += "AND "
  858. } else {
  859. queryStr += "WHERE "
  860. }
  861. queryStr += "tx.token_id = ? "
  862. args = append(args, tokenID)
  863. nextIsAnd = true
  864. }
  865. // idx filter
  866. if idx != nil {
  867. if nextIsAnd {
  868. queryStr += "AND "
  869. } else {
  870. queryStr += "WHERE "
  871. }
  872. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  873. args = append(args, idx, idx)
  874. nextIsAnd = true
  875. }
  876. // batchNum filter
  877. if batchNum != nil {
  878. if nextIsAnd {
  879. queryStr += "AND "
  880. } else {
  881. queryStr += "WHERE "
  882. }
  883. queryStr += "tx.batch_num = ? "
  884. args = append(args, batchNum)
  885. nextIsAnd = true
  886. }
  887. // txType filter
  888. if txType != nil {
  889. if nextIsAnd {
  890. queryStr += "AND "
  891. } else {
  892. queryStr += "WHERE "
  893. }
  894. queryStr += "tx.type = ? "
  895. args = append(args, txType)
  896. nextIsAnd = true
  897. }
  898. if fromItem != nil {
  899. if nextIsAnd {
  900. queryStr += "AND "
  901. } else {
  902. queryStr += "WHERE "
  903. }
  904. if order == OrderAsc {
  905. queryStr += "tx.item_id >= ? "
  906. } else {
  907. queryStr += "tx.item_id <= ? "
  908. }
  909. args = append(args, fromItem)
  910. nextIsAnd = true
  911. }
  912. if nextIsAnd {
  913. queryStr += "AND "
  914. } else {
  915. queryStr += "WHERE "
  916. }
  917. queryStr += "tx.batch_num IS NOT NULL "
  918. // pagination
  919. queryStr += "ORDER BY tx.item_id "
  920. if order == OrderAsc {
  921. queryStr += " ASC "
  922. } else {
  923. queryStr += " DESC "
  924. }
  925. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  926. query = hdb.db.Rebind(queryStr)
  927. // log.Debug(query)
  928. txsPtrs := []*TxAPI{}
  929. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  930. return nil, 0, err
  931. }
  932. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  933. if len(txs) == 0 {
  934. return nil, 0, sql.ErrNoRows
  935. }
  936. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  937. }
  938. // GetAllExits returns all exit from the DB
  939. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  940. var exits []*common.ExitInfo
  941. err := meddler.QueryAll(
  942. hdb.db, &exits,
  943. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  944. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  945. exit_tree.delayed_withdrawn FROM exit_tree;`,
  946. )
  947. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
  948. }
  949. // GetExitAPI returns a exit from the DB
  950. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  951. exit := &ExitAPI{}
  952. err := meddler.QueryRow(
  953. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  954. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  955. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  956. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  957. token.token_id, token.item_id AS token_item_id,
  958. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  959. token.decimals, token.usd, token.usd_update
  960. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  961. INNER JOIN token ON account.token_id = token.token_id
  962. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  963. )
  964. return exit, err
  965. }
  966. // GetExitsAPI returns a list of exits from the DB and pagination info
  967. func (hdb *HistoryDB) GetExitsAPI(
  968. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
  969. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  970. fromItem, limit *uint, order string,
  971. ) ([]ExitAPI, uint64, error) {
  972. if ethAddr != nil && bjj != nil {
  973. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  974. }
  975. var query string
  976. var args []interface{}
  977. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  978. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  979. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  980. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  981. token.token_id, token.item_id AS token_item_id,
  982. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  983. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  984. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  985. INNER JOIN token ON account.token_id = token.token_id `
  986. // Apply filters
  987. nextIsAnd := false
  988. // ethAddr filter
  989. if ethAddr != nil {
  990. queryStr += "WHERE account.eth_addr = ? "
  991. nextIsAnd = true
  992. args = append(args, ethAddr)
  993. } else if bjj != nil { // bjj filter
  994. queryStr += "WHERE account.bjj = ? "
  995. nextIsAnd = true
  996. args = append(args, bjj)
  997. }
  998. // tokenID filter
  999. if tokenID != nil {
  1000. if nextIsAnd {
  1001. queryStr += "AND "
  1002. } else {
  1003. queryStr += "WHERE "
  1004. }
  1005. queryStr += "account.token_id = ? "
  1006. args = append(args, tokenID)
  1007. nextIsAnd = true
  1008. }
  1009. // idx filter
  1010. if idx != nil {
  1011. if nextIsAnd {
  1012. queryStr += "AND "
  1013. } else {
  1014. queryStr += "WHERE "
  1015. }
  1016. queryStr += "exit_tree.account_idx = ? "
  1017. args = append(args, idx)
  1018. nextIsAnd = true
  1019. }
  1020. // batchNum filter
  1021. if batchNum != nil {
  1022. if nextIsAnd {
  1023. queryStr += "AND "
  1024. } else {
  1025. queryStr += "WHERE "
  1026. }
  1027. queryStr += "exit_tree.batch_num = ? "
  1028. args = append(args, batchNum)
  1029. nextIsAnd = true
  1030. }
  1031. // onlyPendingWithdraws
  1032. if onlyPendingWithdraws != nil {
  1033. if *onlyPendingWithdraws {
  1034. if nextIsAnd {
  1035. queryStr += "AND "
  1036. } else {
  1037. queryStr += "WHERE "
  1038. }
  1039. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1040. nextIsAnd = true
  1041. }
  1042. }
  1043. if fromItem != nil {
  1044. if nextIsAnd {
  1045. queryStr += "AND "
  1046. } else {
  1047. queryStr += "WHERE "
  1048. }
  1049. if order == OrderAsc {
  1050. queryStr += "exit_tree.item_id >= ? "
  1051. } else {
  1052. queryStr += "exit_tree.item_id <= ? "
  1053. }
  1054. args = append(args, fromItem)
  1055. // nextIsAnd = true
  1056. }
  1057. // pagination
  1058. queryStr += "ORDER BY exit_tree.item_id "
  1059. if order == OrderAsc {
  1060. queryStr += " ASC "
  1061. } else {
  1062. queryStr += " DESC "
  1063. }
  1064. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1065. query = hdb.db.Rebind(queryStr)
  1066. // log.Debug(query)
  1067. exits := []*ExitAPI{}
  1068. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1069. return nil, 0, err
  1070. }
  1071. if len(exits) == 0 {
  1072. return nil, 0, sql.ErrNoRows
  1073. }
  1074. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1075. }
  1076. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1077. func (hdb *HistoryDB) GetAllL1UserTxs() ([]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 = TRUE;`,
  1085. )
  1086. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1087. }
  1088. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1089. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1090. var txs []*common.L1Tx
  1091. err := meddler.QueryAll(
  1092. hdb.db, &txs,
  1093. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1094. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1095. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1096. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
  1097. )
  1098. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1099. }
  1100. // GetAllL2Txs returns all L2Txs from the DB
  1101. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1102. var txs []*common.L2Tx
  1103. err := meddler.QueryAll(
  1104. hdb.db, &txs,
  1105. `SELECT tx.id, tx.batch_num, tx.position,
  1106. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1107. tx.type, tx.eth_block_num
  1108. FROM tx WHERE is_l1 = FALSE;`,
  1109. )
  1110. return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
  1111. }
  1112. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1113. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1114. var txs []*common.L1Tx
  1115. err := meddler.QueryAll(
  1116. hdb.db, &txs,
  1117. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1118. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  1119. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  1120. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  1121. toForgeL1TxsNum,
  1122. )
  1123. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  1124. }
  1125. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1126. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1127. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1128. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  1129. var lastL1TxsPosition int
  1130. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  1131. }
  1132. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1133. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1134. *common.WDelayerVariables, error) {
  1135. var rollup common.RollupVariables
  1136. var auction common.AuctionVariables
  1137. var wDelayer common.WDelayerVariables
  1138. if err := meddler.QueryRow(hdb.db, &rollup,
  1139. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1140. return nil, nil, nil, err
  1141. }
  1142. if err := meddler.QueryRow(hdb.db, &auction,
  1143. "SELECT * FROM auction_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, &wDelayer,
  1147. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1148. return nil, nil, nil, err
  1149. }
  1150. return &rollup, &auction, &wDelayer, nil
  1151. }
  1152. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1153. return meddler.Insert(d, "rollup_vars", rollup)
  1154. }
  1155. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1156. return meddler.Insert(d, "auction_vars", auction)
  1157. }
  1158. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1159. return meddler.Insert(d, "wdelayer_vars", wDelayer)
  1160. }
  1161. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1162. // contract variables. This initial state is stored linked to block 0, which
  1163. // always exist in the DB and is used to store initialization data that always
  1164. // exist in the smart contracts.
  1165. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1166. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1167. txn, err := hdb.db.Beginx()
  1168. if err != nil {
  1169. return err
  1170. }
  1171. defer func() {
  1172. if err != nil {
  1173. db.Rollback(txn)
  1174. }
  1175. }()
  1176. // Force EthBlockNum to be 0 because it's the block used to link data
  1177. // that belongs to the creation of the smart contracts
  1178. rollup.EthBlockNum = 0
  1179. auction.EthBlockNum = 0
  1180. wDelayer.EthBlockNum = 0
  1181. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1182. return err
  1183. }
  1184. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1185. return err
  1186. }
  1187. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1188. return err
  1189. }
  1190. return txn.Commit()
  1191. }
  1192. // AddBlockSCData stores all the information of a block retrieved by the
  1193. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1194. // the pagination system of the API/DB depends on this. Within blocks, all
  1195. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1196. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1197. txn, err := hdb.db.Beginx()
  1198. if err != nil {
  1199. return err
  1200. }
  1201. defer func() {
  1202. if err != nil {
  1203. db.Rollback(txn)
  1204. }
  1205. }()
  1206. // Add block
  1207. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1208. return err
  1209. }
  1210. // Add Coordinators
  1211. if len(blockData.Auction.Coordinators) > 0 {
  1212. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1213. return err
  1214. }
  1215. }
  1216. // Add Bids
  1217. if len(blockData.Auction.Bids) > 0 {
  1218. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1219. return err
  1220. }
  1221. }
  1222. // Add Tokens
  1223. if len(blockData.Rollup.AddedTokens) > 0 {
  1224. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1225. return err
  1226. }
  1227. }
  1228. // Prepare user L1 txs to be added.
  1229. // They must be added before the batch that will forge them (which can be in the same block)
  1230. // and after the account that will be sent to (also can be in the same block).
  1231. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1232. // the batch that forges those txs is inserted
  1233. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1234. for i := range blockData.Rollup.L1UserTxs {
  1235. batchThatForgesIsInTheBlock := false
  1236. for _, batch := range blockData.Rollup.Batches {
  1237. if batch.Batch.ForgeL1TxsNum != nil &&
  1238. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1239. // Tx is forged in this block. It's guaranteed that:
  1240. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1241. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1242. batchThatForgesIsInTheBlock = true
  1243. addAtBatchNum := batch.Batch.BatchNum - 1
  1244. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1245. break
  1246. }
  1247. }
  1248. if !batchThatForgesIsInTheBlock {
  1249. // User artificial batchNum 0 to add txs that are not forge in this block
  1250. // after all the accounts of the block have been added
  1251. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1252. }
  1253. }
  1254. // Add Batches
  1255. for i := range blockData.Rollup.Batches {
  1256. batch := &blockData.Rollup.Batches[i]
  1257. // Add Batch: this will trigger an update on the DB
  1258. // that will set the batch num of forged L1 txs in this batch
  1259. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1260. return err
  1261. }
  1262. // Add accounts
  1263. if len(batch.CreatedAccounts) > 0 {
  1264. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1265. return err
  1266. }
  1267. }
  1268. // Add forged l1 coordinator Txs
  1269. if len(batch.L1CoordinatorTxs) > 0 {
  1270. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1271. return err
  1272. }
  1273. }
  1274. // Add l2 Txs
  1275. if len(batch.L2Txs) > 0 {
  1276. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1277. return err
  1278. }
  1279. }
  1280. // Add user L1 txs that will be forged in next batch
  1281. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1282. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1283. return err
  1284. }
  1285. }
  1286. // Add exit tree
  1287. if len(batch.ExitTree) > 0 {
  1288. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1289. return err
  1290. }
  1291. }
  1292. }
  1293. // Add user L1 txs that won't be forged in this block
  1294. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1295. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1296. return err
  1297. }
  1298. }
  1299. if blockData.Rollup.Vars != nil {
  1300. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1301. return err
  1302. }
  1303. }
  1304. if blockData.Auction.Vars != nil {
  1305. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1306. return err
  1307. }
  1308. }
  1309. if blockData.WDelayer.Vars != nil {
  1310. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1311. return err
  1312. }
  1313. }
  1314. if err := hdb.updateExitTree(txn, blockData.Block.EthBlockNum,
  1315. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1316. return err
  1317. }
  1318. return txn.Commit()
  1319. }
  1320. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1321. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1322. coordinator := &CoordinatorAPI{}
  1323. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1324. return coordinator, err
  1325. }
  1326. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1327. func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, uint64, error) {
  1328. var query string
  1329. var args []interface{}
  1330. queryStr := `SELECT coordinator.*,
  1331. COUNT(*) OVER() AS total_items
  1332. FROM coordinator `
  1333. // Apply filters
  1334. if fromItem != nil {
  1335. queryStr += "WHERE "
  1336. if order == OrderAsc {
  1337. queryStr += "coordinator.item_id >= ? "
  1338. } else {
  1339. queryStr += "coordinator.item_id <= ? "
  1340. }
  1341. args = append(args, fromItem)
  1342. }
  1343. // pagination
  1344. queryStr += "ORDER BY coordinator.item_id "
  1345. if order == OrderAsc {
  1346. queryStr += " ASC "
  1347. } else {
  1348. queryStr += " DESC "
  1349. }
  1350. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1351. query = hdb.db.Rebind(queryStr)
  1352. coordinators := []*CoordinatorAPI{}
  1353. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1354. return nil, 0, err
  1355. }
  1356. if len(coordinators) == 0 {
  1357. return nil, 0, sql.ErrNoRows
  1358. }
  1359. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1360. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1361. }
  1362. // AddAuctionVars insert auction vars into the DB
  1363. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1364. return meddler.Insert(hdb.db, "auction_vars", auctionVars)
  1365. }
  1366. // GetAuctionVars returns auction variables
  1367. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1368. auctionVars := &common.AuctionVariables{}
  1369. err := meddler.QueryRow(
  1370. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1371. )
  1372. return auctionVars, err
  1373. }
  1374. // GetAccountAPI returns an account by its index
  1375. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1376. account := &AccountAPI{}
  1377. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1378. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1379. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1380. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1381. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1382. if err != nil {
  1383. return nil, err
  1384. }
  1385. return account, nil
  1386. }
  1387. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1388. func (hdb *HistoryDB) GetAccountsAPI(
  1389. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1390. bjj *babyjub.PublicKey, fromItem, limit *uint, order string,
  1391. ) ([]AccountAPI, uint64, error) {
  1392. if ethAddr != nil && bjj != nil {
  1393. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  1394. }
  1395. var query string
  1396. var args []interface{}
  1397. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1398. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1399. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1400. COUNT(*) OVER() AS total_items
  1401. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1402. // Apply filters
  1403. nextIsAnd := false
  1404. // ethAddr filter
  1405. if ethAddr != nil {
  1406. queryStr += "WHERE account.eth_addr = ? "
  1407. nextIsAnd = true
  1408. args = append(args, ethAddr)
  1409. } else if bjj != nil { // bjj filter
  1410. queryStr += "WHERE account.bjj = ? "
  1411. nextIsAnd = true
  1412. args = append(args, bjj)
  1413. }
  1414. // tokenID filter
  1415. if len(tokenIDs) > 0 {
  1416. if nextIsAnd {
  1417. queryStr += "AND "
  1418. } else {
  1419. queryStr += "WHERE "
  1420. }
  1421. queryStr += "account.token_id IN (?) "
  1422. args = append(args, tokenIDs)
  1423. nextIsAnd = true
  1424. }
  1425. if fromItem != nil {
  1426. if nextIsAnd {
  1427. queryStr += "AND "
  1428. } else {
  1429. queryStr += "WHERE "
  1430. }
  1431. if order == OrderAsc {
  1432. queryStr += "account.item_id >= ? "
  1433. } else {
  1434. queryStr += "account.item_id <= ? "
  1435. }
  1436. args = append(args, fromItem)
  1437. }
  1438. // pagination
  1439. queryStr += "ORDER BY account.item_id "
  1440. if order == OrderAsc {
  1441. queryStr += " ASC "
  1442. } else {
  1443. queryStr += " DESC "
  1444. }
  1445. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1446. query, argsQ, err := sqlx.In(queryStr, args...)
  1447. if err != nil {
  1448. return nil, 0, err
  1449. }
  1450. query = hdb.db.Rebind(query)
  1451. accounts := []*AccountAPI{}
  1452. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1453. return nil, 0, err
  1454. }
  1455. if len(accounts) == 0 {
  1456. return nil, 0, sql.ErrNoRows
  1457. }
  1458. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1459. accounts[0].TotalItems - uint64(len(accounts)), nil
  1460. }
  1461. // GetMetrics returns metrics
  1462. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1463. metricsTotals := &MetricsTotals{}
  1464. metrics := &Metrics{}
  1465. err := meddler.QueryRow(
  1466. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1467. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1468. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1469. if err != nil {
  1470. return nil, err
  1471. }
  1472. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1473. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1474. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1475. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1476. } else {
  1477. metrics.TransactionsPerBatch = float64(0)
  1478. }
  1479. err = meddler.QueryRow(
  1480. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1481. SUM(total_fees_usd) AS total_fees FROM batch
  1482. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1483. if err != nil {
  1484. return nil, err
  1485. }
  1486. if metricsTotals.TotalBatches > 0 {
  1487. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1488. } else {
  1489. metrics.BatchFrequency = 0
  1490. }
  1491. if metricsTotals.TotalTransactions > 0 {
  1492. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1493. } else {
  1494. metrics.AvgTransactionFee = 0
  1495. }
  1496. err = meddler.QueryRow(
  1497. hdb.db, metrics,
  1498. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1499. if err != nil {
  1500. return nil, err
  1501. }
  1502. return metrics, nil
  1503. }
  1504. // GetAvgTxFee returns average transaction fee of the last 1h
  1505. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1506. metricsTotals := &MetricsTotals{}
  1507. err := meddler.QueryRow(
  1508. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num
  1509. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1510. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1511. if err != nil {
  1512. return 0, err
  1513. }
  1514. err = meddler.QueryRow(
  1515. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1516. SUM(total_fees_usd) AS total_fees FROM batch
  1517. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1518. if err != nil {
  1519. return 0, err
  1520. }
  1521. var avgTransactionFee float64
  1522. if metricsTotals.TotalTransactions > 0 {
  1523. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1524. } else {
  1525. avgTransactionFee = 0
  1526. }
  1527. return avgTransactionFee, nil
  1528. }