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.

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