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.

1549 lines
46 KiB

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